Prompt specification
Build or customize the Three.js 3D scene "Bedroom marble-run construction" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Bedroom marble-run construction
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/bedroom-marble-run-construction-x0355
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts marble runs. Compose a bounded toy track with towers, ramps, and collection cups; users assemble two routes that differ in length while sharing the same release height. Stylized solid forms.
Working Three.js Starter (bedroom-marble-run-construction-x0355):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Marble Assembly Workshop</title>
<style>
:root {
--ink: #25302e;
--muted: #718079;
--paper: #f5f0e6;
--panel: rgba(255, 252, 245, 0.9);
--line: rgba(57, 72, 68, 0.14);
--route-a: #e4604f;
--route-b: #208f85;
--accent: #e99b3f;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #e7e1d6;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button { font: inherit; }
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active { cursor: grabbing; }
#brand {
position: fixed;
z-index: 4;
top: 24px;
left: 26px;
pointer-events: none;
max-width: 360px;
}
.eyebrow {
display: block;
margin-bottom: 7px;
color: #64736d;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
}
#brand h1 {
margin: 0;
font-size: clamp(26px, 3vw, 42px);
line-height: 1;
letter-spacing: -0.045em;
font-weight: 850;
}
#brand p {
margin: 10px 0 0;
color: #66736e;
font-size: 13px;
}
#panel {
position: fixed;
z-index: 5;
top: 112px;
left: 24px;
width: 330px;
max-height: calc(100vh - 136px);
overflow: auto;
padding: 17px;
border: 1px solid rgba(255, 255, 255, 0.76);
border-radius: 22px;
background: var(--panel);
box-shadow:
0 20px 55px rgba(57, 62, 53, 0.13),
inset 0 0 0 1px rgba(57, 72, 68, 0.05);
backdrop-filter: blur(16px);
scrollbar-width: thin;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
}
.panel-head strong {
font-size: 10px;
letter-spacing: 0.16em;
}
.text-button {
padding: 0;
border: 0;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 11px;
font-weight: 700;
}
.text-button:hover { color: var(--ink); }
#palette {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.module {
min-width: 0;
padding: 11px 6px 9px;
border: 1px solid var(--line);
border-radius: 13px;
color: var(--ink);
background: rgba(255, 255, 255, 0.58);
cursor: grab;
transition: transform 150ms ease, border-color 150ms ease, background 150ms ease;
}
.module:hover {
transform: translateY(-2px);
border-color: rgba(37, 48, 46, 0.28);
background: #fffdf8;
}
.module.selected {
border-color: var(--accent);
background: #fff8e9;
box-shadow: 0 0 0 2px rgba(233, 155, 63, 0.13);
}
.module .glyph {
display: block;
height: 23px;
color: var(--accent);
font-size: 23px;
font-weight: 900;
line-height: 21px;
}
.module b {
display: block;
margin-top: 5px;
font-size: 10px;
letter-spacing: 0.015em;
}
.instruction {
margin: 10px 1px 12px;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
.route-card {
--route: var(--route-a);
margin-top: 10px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(255, 255, 255, 0.55);
transition: border-color 150ms ease, background 150ms ease;
}
.route-card.route-b { --route: var(--route-b); }
.route-card.dragover {
border-color: var(--route);
background: color-mix(in srgb, var(--route) 7%, white);
}
.route-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.route-name {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.swatch {
width: 10px;
height: 25px;
flex: 0 0 auto;
border-radius: 7px;
background: var(--route);
}
.route-name b {
display: block;
font-size: 12px;
}
.route-name small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9.5px;
}
.length {
color: var(--route);
font-size: 13px;
font-weight: 850;
white-space: nowrap;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
min-height: 31px;
margin-top: 10px;
}
.chip {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 6px 5px 6px 8px;
border: 1px solid color-mix(in srgb, var(--route) 24%, white);
border-radius: 9px;
color: color-mix(in srgb, var(--route) 78%, #26302e);
background: color-mix(in srgb, var(--route) 7%, white);
cursor: grab;
font-size: 9px;
font-weight: 750;
}
.chip::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--route);
}
.chip.drop-target {
outline: 2px solid var(--route);
outline-offset: 1px;
}
.chip button {
width: 17px;
height: 17px;
padding: 0;
border: 0;
border-radius: 50%;
color: #6a7772;
background: transparent;
cursor: pointer;
line-height: 15px;
}
.chip button:hover {
color: #222c2a;
background: rgba(0, 0, 0, 0.07);
}
.route-footer {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 9px;
}
.route-footer span {
color: var(--muted);
font-size: 9px;
}
.add-button {
width: 29px;
height: 29px;
padding: 0;
border: 0;
border-radius: 9px;
color: white;
background: var(--route);
cursor: pointer;
font-size: 19px;
line-height: 1;
}
.add-button:hover { filter: brightness(1.08); }
.shared-card {
display: flex;
align-items: center;
gap: 10px;
margin-top: 13px;
padding: 10px 12px;
border: 1px dashed rgba(37, 48, 46, 0.24);
border-radius: 13px;
background: rgba(239, 233, 219, 0.58);
}
.shared-icon {
display: grid;
place-items: center;
width: 30px;
height: 30px;
border-radius: 9px;
color: #8b663c;
background: #f2d29f;
font-weight: 900;
}
.shared-card span {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
}
.shared-card strong {
display: block;
margin-top: 2px;
font-size: 10.5px;
}
#transport {
position: fixed;
z-index: 5;
left: 50%;
bottom: 24px;
display: flex;
align-items: center;
gap: 9px;
padding: 8px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 17px;
background: rgba(255, 252, 245, 0.9);
box-shadow: 0 15px 40px rgba(45, 53, 47, 0.17);
backdrop-filter: blur(14px);
transform: translateX(-50%);
}
#transport button {
height: 42px;
padding: 0 17px;
border: 0;
border-radius: 12px;
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition: transform 150ms ease, filter 150ms ease;
}
#transport button:hover {
transform: translateY(-1px);
filter: brightness(1.04);
}
#releaseButton {
color: white;
background: #253b37;
box-shadow: 0 6px 13px rgba(37, 59, 55, 0.2);
}
#resetMarbles {
color: #52605b;
background: #eee8dc;
}
#timer {
min-width: 102px;
padding: 0 10px;
color: #69766f;
font-size: 9.5px;
font-weight: 750;
text-align: center;
}
#viewHint {
position: fixed;
z-index: 4;
right: 24px;
bottom: 27px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.55);
border-radius: 12px;
color: #65716c;
background: rgba(255, 252, 245, 0.68);
backdrop-filter: blur(10px);
font-size: 9.5px;
line-height: 1.5;
text-align: right;
pointer-events: none;
}
#viewHint b { color: #34443f; }
#toast {
position: fixed;
z-index: 10;
left: 50%;
top: 24px;
max-width: min(430px, calc(100vw - 32px));
padding: 11px 15px;
border-radius: 12px;
color: white;
background: rgba(34, 48, 44, 0.93);
box-shadow: 0 10px 30px rgba(32, 42, 39, 0.2);
font-size: 11px;
font-weight: 700;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -12px);
transition: opacity 180ms ease, transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 760px) {
#brand {
top: 16px;
left: 17px;
}
#brand h1 { font-size: 28px; }
#brand p { display: none; }
#panel {
top: auto;
left: 12px;
bottom: 86px;
width: calc(100vw - 24px);
max-height: 43vh;
padding: 13px;
border-radius: 18px;
}
#viewHint { display: none; }
#transport {
bottom: 13px;
width: calc(100vw - 24px);
justify-content: center;
}
#transport button { padding: 0 13px; }
#timer { display: none; }
}
</style>
</head>
<body>
<div id="stage"></div>
<header id="brand">
<span class="eyebrow">PLAY LAB / 02</span>
<h1>Marble Assembly</h1>
<p>Build two drops. Keep the start level.</p>
</header>
<aside id="panel">
<div class="panel-head">
<strong>TRACK MODULES</strong>
<button class="text-button" id="resetLayouts">Reset layouts</button>
</div>
<div id="palette">
<button class="module selected" data-module="runway" draggable="true">
<span class="glyph">━</span><b>Runway</b>
</button>
<button class="module" data-module="ramp" draggable="true">
<span class="glyph">◩</span><b>Ramp</b>
</button>
<button class="module" data-module="switchback" draggable="true">
<span class="glyph">⤴</span><b>Switchback</b>
</button>
</div>
<p class="instruction">
Drag modules onto a route, or select one and use the + button.
Reorder chips by dragging them.
</p>
<section class="route-card" id="routeCardA">
<div class="route-title">
<div class="route-name">
<span class="swatch"></span>
<div><b>Route A</b><small>SHORT LAYOUT</small></div>
</div>
<span class="length" id="lengthA">0.0 m</span>
</div>
<div class="chips" id="chipsA"></div>
<div class="route-footer">
<span id="countA">0 modules</span>
<button class="add-button" id="addA" title="Add selected module">+</button>
</div>
</section>
<section class="route-card route-b" id="routeCardB">
<div class="route-title">
<div class="route-name">
<span class="swatch"></span>
<div><b>Route B</b><small>LONG LAYOUT</small></div>
</div>
<span class="length" id="lengthB">0.0 m</span>
</div>
<div class="chips" id="chipsB"></div>
<div class="route-footer">
<span id="countB">0 modules</span>
<button class="add-button" id="addB" title="Add selected module">+</button>
</div>
</section>
<div class="shared-card">
<div class="shared-icon">↔</div>
<div>
<span>SHARED RELEASE</span>
<strong>Both routes begin at 5.65 units high</strong>
</div>
</div>
</aside>
<div id="transport">
<button id="releaseButton">Release pair</button>
<button id="resetMarbles">Reset marbles</button>
<span id="timer">Ready to run</span>
</div>
<div id="viewHint">
<b>Drag</b> to orbit · <b>Scroll</b> to zoom<br />
<b>Shift + drag</b> to pan · <b>Double-click</b> to reset view
</div>
<div id="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const MODULES = {
runway: { label: "Runway" },
ramp: { label: "Ramp" },
switchback: { label: "Switchback" }
};
const COLORS = {
A: 0xe4604f,
B: 0x208f85,
cream: 0xf2ebdd,
dark: 0x32423e,
board: 0xd8c7aa,
orange: 0xe8a047
};
const START_Y = 5.65;
const END_Y = 1.52;
const TOTAL_DROP = START_Y - END_Y;
const X_STEP = 1.5;
const Z_STEP = 1.25;
const TRACK_WIDTH = 0.76;
const state = {
selectedModule: "runway",
routes: {
A: {
key: "A",
side: -1,
modules: ["ramp", "switchback", "ramp", "runway"]
},
B: {
key: "B",
side: 1,
modules: ["ramp", "switchback", "ramp", "runway", "switchback", "ramp"]
}
}
};
const routeData = {};
const routeGroups = {};
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe7e1d6);
scene.fog = new THREE.Fog(0xe7e1d6, 28, 58);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
stage.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xffffff, 0xa79376, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff3dc, 3.4);
sun.position.set(8, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -16;
sun.shadow.camera.right = 16;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.00025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbad9d2, 0.9);
fill.position.set(-10, 7, -8);
scene.add(fill);
function standard(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0,
...options
});
}
function roundedShape(width, depth, radius) {
const x = -width / 2;
const y = -depth / 2;
const s = new THREE.Shape();
s.moveTo(x + radius, y);
s.lineTo(x + width - radius, y);
s.quadraticCurveTo(x + width, y, x + width, y + radius);
s.lineTo(x + width, y + depth - radius);
s.quadraticCurveTo(
x + width,
y + depth,
x + width - radius,
y + depth
);
s.lineTo(x + radius, y + depth);
s.quadraticCurveTo(x, y + depth, x, y + depth - radius);
s.lineTo(x, y + radius);
s.quadraticCurveTo(x, y, x + radius, y);
return s;
}
function createTextSprite(text, color = "#32423e", scale = 2.0) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 512, 128);
ctx.fillStyle = "rgba(255, 252, 245, 0.94)";
ctx.strokeStyle = "rgba(50, 66, 62, 0.13)";
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(18, 16);
ctx.lineTo(494, 16);
ctx.quadraticCurveTo(504, 16, 504, 28);
ctx.lineTo(504, 100);
ctx.quadraticCurveTo(504, 112, 492, 112);
ctx.lineTo(20, 112);
ctx.quadraticCurveTo(8, 112, 8, 100);
ctx.lineTo(8, 28);
ctx.quadraticCurveTo(8, 16, 18, 16);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = color;
ctx.font = "800 42px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(scale, scale * 0.25, 1);
return sprite;
}
function addBoard() {
const boardGroup = new THREE.Group();
const boardGeo = new THREE.ExtrudeGeometry(roundedShape(22, 15, 0.8), {
depth: 0.45,
bevelEnabled: true,
bevelThickness: 0.08,
bevelSize: 0.08,
bevelSegments: 3,
curveSegments: 8
});
boardGeo.rotateX(-Math.PI / 2);
const board = new THREE.Mesh(boardGeo, standard(COLORS.board));
board.position.y = -0.58;
board.receiveShadow = true;
board.castShadow = true;
boardGroup.add(board);
const lineVertices = [];
for (let x = -10; x <= 10; x += 2) {
lineVertices.push(x, 0.035, -7, x, 0.035, 7);
}
for (let z = -7; z <= 7; z += 2) {
lineVertices.push(-10.5, 0.035, z, 10.5, 0.035, z);
}
const gridGeo = new THREE.BufferGeometry();
gridGeo.setAttribute(
"position",
new THREE.Float32BufferAttribute(lineVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeo,
new THREE.LineBasicMaterial({
color: 0xb9a98e,
transparent: true,
opacity: 0.25
})
);
boardGroup.add(grid);
const borderMat = standard(0xf4eddf);
const borderY = 0.17;
const borderH = 0.24;
const side1 = new THREE.Mesh(
new THREE.BoxGeometry(21.4, borderH, 0.16),
borderMat
);
side1.position.set(0, borderY, -7.25);
boardGroup.add(side1);
const side2 = side1.clone();
side2.position.z = 7.25;
boardGroup.add(side2);
const side3 = new THREE.Mesh(
new THREE.BoxGeometry(0.16, borderH, 14.3),
borderMat
);
side3.position.set(-10.7, borderY, 0);
boardGroup.add(side3);
const side4 = side3.clone();
side4.position.x = 10.7;
boardGroup.add(side4);
const pegMat = standard(0xe3b267);
const pegGeo = new THREE.CylinderGeometry(0.12, 0.14, 0.42, 12);
const pegPositions = [
[-10.25, -6.85], [10.25, -6.85],
[-10.25, 6.85], [10.25, 6.85],
[-6.5, -6.85], [6.5, -6.85]
];
for (const [x, z] of pegPositions) {
const peg = new THREE.Mesh(pegGeo, pegMat);
peg.position.set(x, 0.21, z);
peg.castShadow = true;
boardGroup.add(peg);
}
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
standard(0xdcd6ca, { roughness: 1 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.67;
floor.receiveShadow = true;
boardGroup.add(floor);
scene.add(boardGroup);
}
function addReleaseTower() {
const group = new THREE.Group();
const cream = standard(COLORS.cream);
const orange = standard(COLORS.orange);
const legGeo = new THREE.BoxGeometry(0.34, 5.3, 0.34);
for (const x of [-0.56, 0.56]) {
const leg = new THREE.Mesh(legGeo, cream);
leg.position.set(x, 2.68, -4.45);
leg.castShadow = true;
group.add(leg);
}
const braceGeo = new THREE.BoxGeometry(1.42, 0.16, 0.18);
for (const y of [1.3, 3.4]) {
const brace = new THREE.Mesh(braceGeo, orange);
brace.position.set(0, y, -4.45);
brace.castShadow = true;
group.add(brace);
}
const platform = new THREE.Mesh(
new THREE.BoxGeometry(2.75, 0.24, 0.9),
cream
);
platform.position.set(0, START_Y - 0.16, -4.25);
platform.castShadow = true;
group.add(platform);
const canopy = new THREE.Mesh(
new THREE.BoxGeometry(3.0, 0.18, 1.08),
orange
);
canopy.position.set(0, 6.48, -4.25);
canopy.castShadow = true;
group.add(canopy);
for (const x of [-1.25, 1.25]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 0.8, 0.13),
cream
);
post.position.set(x, 6.03, -4.25);
group.add(post);
}
for (const [key, x] of [["A", -1], ["B", 1]]) {
const gate = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.42, 0.68),
standard(COLORS[key])
);
gate.position.set(x, START_Y + 0.12, -4.25);
gate.castShadow = true;
group.add(gate);
const branch = new THREE.Mesh(
new THREE.BoxGeometry(1.0, 0.12, TRACK_WIDTH),
standard(COLORS[key], { roughness: 0.48 })
);
branch.position.set(x * 0.5, START_Y - 0.06, -4.25);
branch.castShadow = true;
branch.receiveShadow = true;
group.add(branch);
for (const z of [-4.25 - 0.4, -4.25 + 0.4]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(1.0, 0.06, 0.055),
standard(COLORS[key], { roughness: 0.42 })
);
rail.position.set(x * 0.5, START_Y + 0.14, z);
group.add(rail);
}
}
const dropLabel = createTextSprite("DROP", "#8d6337", 1.35);
dropLabel.position.set(0, 6.88, -4.25);
group.add(dropLabel);
const heightGeo = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-4.5, START_Y, -4.85),
new THREE.Vector3(4.5, START_Y, -4.85)
]);
const heightLine = new THREE.Line(
heightGeo,
new THREE.LineDashedMaterial({
color: 0x9a7950,
dashSize: 0.22,
gapSize: 0.16,
transparent: true,
opacity: 0.65
})
);
heightLine.computeLineDistances();
group.add(heightLine);
const heightLabel = createTextSprite("SAME START HEIGHT", "#82613e", 2.3);
heightLabel.position.set(-2.8, START_Y + 0.38, -4.85);
group.add(heightLabel);
scene.add(group);
}
function disposeGroup(group) {
if (!group) return;
const geometries = new Set();
const materials = new Set();
const textures = new Set();
group.traverse((object) => {
if (object.geometry) geometries.add(object.geometry);
if (object.material) {
const list = Array.isArray(object.material)
? object.material
: [object.material];
list.forEach((material) => {
materials.add(material);
if (material.map) textures.add(material.map);
});
}
});
geometries.forEach((g) => g.dispose());
materials.forEach((m) => m.dispose());
textures.forEach((t) => t.dispose());
scene.remove(group);
}
function buildRouteData(route) {
let x = route.side * 1.0;
let z = -4.25;
let cumulativeWeight = 0;
const raw = [];
const boundaryIndices = [0];
function addPoint(nx, nz, weightIncrement) {
cumulativeWeight += weightIncrement;
raw.push({
x: nx,
z: nz,
weight: cumulativeWeight,
distance: 0
});
}
for (const type of route.modules) {
if (type === "runway") {
addPoint(x, z + Z_STEP, 0);
x = x;
z += Z_STEP;
} else if (type === "ramp") {
addPoint(x, z + Z_STEP, 1);
z += Z_STEP;
} else if (type === "switchback") {
const midZ = z + Z_STEP * 0.48;
addPoint(x, midZ, 0.18);
addPoint(x + route.side * X_STEP, midZ, 0);
addPoint(x + route.side * X_STEP, z + Z_STEP, 0.18);
x += route.side * X_STEP;
z += Z_STEP;
}
boundaryIndices.push(raw.length - 1);
}
const totalWeight = raw[raw.length - 1]?.weight || 0;
let totalDistance = 0;
for (let i = 1; i < raw.length; i++) {
totalDistance += Math.hypot(
raw[i].x - raw[i - 1].x,
raw[i].z - raw[i - 1].z
);
raw[i].distance = totalDistance;
}
const points = raw.map((point, index) => {
const ratio = totalWeight > 0.001
? point.weight / totalWeight
: totalDistance > 0
? point.distance / totalDistance
: 0;
return new THREE.Vector3(
point.x,
START_Y - TOTAL_DROP * ratio,
point.z
);
});
const curve = new THREE.CatmullRomCurve3(
points,
false,
"centripetal",
0.32
);
const boundaries = boundaryIndices.map((index) => ({
point: points[index],
tangent: points[Math.min(index + 1, points.length - 1)]
.clone()
.sub(points[Math.max(0, index - 1)])
}));
const end = points[points.length - 1];
const endTangent = curve.getTangentAt(1).setY(0).normalize();
const cupCenter = end.clone().add(endTangent.multiplyScalar(0.58));
return {
curve,
points,
boundaries,
length: curve.getLength(),
end,
cupCenter
};
}
function createRibbon(curve, width, material) {
const samples = 150;
const positions = [];
const indices = [];
for (let i = 0; i <= samples; i++) {
const t = i / samples;
const point = curve.getPointAt(t);
const tangent = curve.getTangentAt(t);
const side = new THREE.Vector3(-tangent.z, 0, tangent.x).normalize();
const left = point.clone().addScaledVector(side, width / 2);
const right = point.clone().addScaledVector(side, -width / 2);
positions.push(
left.x, left.y, left.z,
right.x, right.y, right.z,
left.x, left.y - 0.12, left.z,
right.x, right.y - 0.12, right.z
);
}
for (let i = 0; i < samples; i++) {
const a = i * 4;
const b = (i + 1) * 4;
indices.push(
a, b, a + 1,
a + 1, b, b + 1,
a + 2, a + 3, b + 2,
a + 3, b + 3, b + 2,
a, a + 2, b,
a + 2, b + 2, b,
a + 1, b + 1, a + 3,
a + 3, b + 1, b + 3
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function createRails(curve, color) {
const group = new THREE.Group();
const samples = 120;
const railMat = standard(color, {
roughness: 0.42,
metalness: 0.04
});
for (const direction of [1, -1]) {
const points = [];
for (let i = 0; i <= samples; i++) {
const t = i / samples;
const point = curve.getPointAt(t);
const tangent = curve.getTangentAt(t);
const side = new THREE.Vector3(-tangent.z, 0, tangent.x).normalize();
point.addScaledVector(side, direction * (TRACK_WIDTH / 2 + 0.035));
point.y += 0.16;
points.push(point);
}
const railCurve = new THREE.CatmullRomCurve3(
points,
false,
"centripetal",
0.3
);
const rail = new THREE.Mesh(
new THREE.TubeGeometry(railCurve, 120, 0.035, 6, false),
railMat
);
rail.castShadow = true;
group.add(rail);
}
return group;
}
function createSupport(point, tangent, color) {
const support = new THREE.Group();
const height = point.y - 0.21;
if (height > 0.25) {
const column = new THREE.Mesh(
new THREE.BoxGeometry(0.17, height, 0.17),
standard(COLORS.cream)
);
column.position.set(point.x, height / 2, point.z);
column.castShadow = true;
support.add(column);
const cap = new THREE.Mesh(
new THREE.BoxGeometry(0.62, 0.12, 0.28),
standard(color, { roughness: 0.6 })
);
cap.position.set(point.x, point.y - 0.16, point.z);
cap.rotation.y = Math.atan2(tangent.x, tangent.z);
cap.castShadow = true;
support.add(cap);
}
return support;
}
function createCup(route, data) {
const group = new THREE.Group();
const color = COLORS[route.key];
const rimY = data.end.y;
const cupHeight = 0.8;
const center = data.cupCenter;
const outer = new THREE.Mesh(
new THREE.CylinderGeometry(0.58, 0.42, cupHeight, 24, 1, true),
standard(color, {
roughness: 0.48,
side: THREE.DoubleSide
})
);
outer.position.set(center.x, rimY - cupHeight / 2, center.z);
outer.castShadow = true;
group.add(outer);
const interior = new THREE.Mesh(
new THREE.CylinderGeometry(0.51, 0.35, cupHeight - 0.08, 24, 1, true),
standard(0x42504c, {
roughness: 0.88,
side: THREE.BackSide
})
);
interior.position.set(center.x, rimY - cupHeight / 2, center.z);
group.add(interior);
const bottom = new THREE.Mesh(
new THREE.CylinderGeometry(0.42, 0.42, 0.07, 24),
standard(0x42504c)
);
bottom.position.set(center.x, rimY - cupHeight + 0.035, center.z);
group.add(bottom);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(0.58, 0.055, 8, 28),
standard(color, { roughness: 0.42 })
);
rim.rotation.x = Math.PI / 2;
rim.position.set(center.x, rimY, center.z);
rim.castShadow = true;
group.add(rim);
const pedestalHeight = Math.max(0.1, rimY - cupHeight - 0.02);
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(0.22, pedestalHeight, 0.22),
standard(COLORS.cream)
);
pedestal.position.set(
center.x,
pedestalHeight / 2,
center.z
);
pedestal.castShadow = true;
group.add(pedestal);
const base = new THREE.Mesh(
new THREE.BoxGeometry(0.78, 0.12, 0.78),
standard(0xe3d6c2)
);
base.position.set(center.x, 0.08, center.z);
base.castShadow = true;
group.add(base);
for (let i = 0; i < 3; i++) {
const angle = i * 2.1;
const marble = new THREE.Mesh(
new THREE.SphereGeometry(0.115, 14, 10),
standard(i % 2 ? 0xf3eee2 : color, { roughness: 0.28 })
);
marble.position.set(
center.x + Math.cos(angle) * 0.17,
rimY - cupHeight + 0.14,
center.z + Math.sin(angle) * 0.17
);
group.add(marble);
}
return group;
}
function buildRouteVisual(route, data) {
const group = new THREE.Group();
const color = COLORS[route.key];
const track = createRibbon(
data.curve,
TRACK_WIDTH,
standard(color, {
roughness: 0.5,
side: THREE.DoubleSide
})
);
group.add(track);
group.add(createRails(data.curve, color));
data.boundaries.forEach((boundary, index) => {
if (index > 0 && index < data.boundaries.length - 1) {
const tangent = boundary.tangent.clone().setY(0).normalize();
const seam = new THREE.Mesh(
new THREE.BoxGeometry(TRACK_WIDTH + 0.025, 0.035, 0.08),
standard(0xf4ecdc, { roughness: 0.6 })
);
seam.position.copy(boundary.point);
seam.position.y += 0.025;
seam.rotation.y = Math.atan2(tangent.x, tangent.z);
seam.castShadow = true;
group.add(seam);
}
if (index > 0 && index % 2 === 0) {
group.add(createSupport(boundary.point, boundary.tangent, color));
}
});
group.add(createCup(route, data));
const labelPosition = data.boundaries[Math.min(2, data.boundaries.length - 1)].point;
const label = createTextSprite(
`ROUTE ${route.key}`,
route.key === "A" ? "#b94f42" : "#167b73",
1.75
);
label.position.set(
labelPosition.x,
Math.min(labelPosition.y + 1.0, 6.35),
labelPosition.z
);
group.add(label);
return group;
}
function rebuildRoute(key) {
const route = state.routes[key];
if (routeData[key]?.length > 100) {
// Recomputed below; keeping this reference makes the intent explicit.
}
disposeGroup(routeGroups[key]);
const data = buildRouteData(route);
routeData[key] = data;
routeGroups[key] = buildRouteVisual(route, data);
scene.add(routeGroups[key]);
document.getElementById(`length${key}`).textContent =
`${(data.length * 0.5).toFixed(1)} m`;
document.getElementById(`count${key}`).textContent =
`${route.modules.length} module${route.modules.length === 1 ? "" : "s"}`;
}
function rebuildAll() {
rebuildRoute("A");
rebuildRoute("B");
renderRecipes();
resetMarbles();
updateTimer("Ready to run");
}
const marbles = {};
const marbleGroup = new THREE.Group();
scene.add(marbleGroup);
function createMarble(key) {
const material = standard(COLORS[key], {
roughness: 0.18,
metalness: 0.12
});
const marble = new THREE.Mesh(
new THREE.SphereGeometry(0.18, 22, 16),
material
);
marble.castShadow = true;
marble.receiveShadow = true;
marbleGroup.add(marble);
return marble;
}
function resetMarbles() {
launch.active = false;
for (const key of ["A", "B"]) {
if (!marbles[key]) marbles[key] = createMarble(key);
const start = routeData[key].curve.getPointAt(0);
marbles[key].visible = true;
marbles[key].scale.setScalar(1);
marbles[key].position.set(start.x, start.y + 0.23, start.z);
}
}
const launch = {
active: false,
start: 0,
durations: { A: 0, B: 0 }
};
function releasePair() {
if (!routeData.A || !routeData.B) return;
launch.active = true;
launch.start = performance.now();
launch.durations.A = routeData.A.length * 650;
launch.durations.B = routeData.B.length * 650;
for (const key of ["A", "B"]) {
marbles[key].visible = true;
marbles[key].scale.setScalar(1);
}
updateTimer("Rolling…");
}
function updateTimer(text) {
document.getElementById("timer").textContent = text;
}
function updateMarbles(now) {
if (!launch.active) {
["A", "B"].forEach((key, index) => {
const start = routeData[key]?.curve.getPointAt(0);
if (!start) return;
marbles[key].position.set(
start.x,
start.y + 0.23 + Math.sin(now * 0.002 + index) * 0.018,
start.z
);
});
return;
}
const elapsed = now - launch.start;
let allDone = true;
for (const [index, key] of ["A", "B"].entries()) {
const marble = marbles[key];
const data = routeData[key];
const duration = launch.durations[key];
const local = elapsed - index * 110;
if (local < 0) {
const start = data.curve.getPointAt(0);
marble.position.set(start.x, start.y + 0.23, start.z);
allDone = false;
continue;
}
const progress = THREE.MathUtils.clamp(local / duration, 0, 1);
if (progress < 0.87) {
const t = progress / 0.87;
const point = data.curve.getPointAt(t);
marble.position.set(point.x, point.y + 0.23, point.z);
marble.rotation.x += 0.035;
marble.rotation.z += 0.025;
marble.scale.setScalar(1);
} else {
const t = (progress - 0.87) / 0.13;
const end = data.end;
const cup = data.cupCenter;
marble.position.set(
THREE.MathUtils.lerp(end.x, cup.x, t),
end.y + 0.23 - t * 0.7,
THREE.MathUtils.lerp(end.z, cup.z, t)
);
marble.scale.setScalar(1 - t * 0.2);
}
if (progress < 1) allDone = false;
}
if (allDone) {
launch.active = false;
marbles.A.visible = false;
marbles.B.visible = false;
updateTimer("Pair collected");
}
}
function canAddModule(route, type) {
if (route.modules.length >= 9) return false;
let x = route.side;
let z = -4.25;
for (const moduleType of [...route.modules, type]) {
if (moduleType === "switchback") {
x += route.side * X_STEP;
z += Z_STEP;
} else {
z += Z_STEP;
}
}
return Math.abs(x) <= 9.65 && z <= 6.9;
}
function addModule(key, type = state.selectedModule) {
const route = state.routes[key];
if (!canAddModule(route, type)) {
showToast("That module would leave the toy board.");
return;
}
route.modules.push(type);
rebuildRoute(key);
renderRecipes();
resetMarbles();
showToast(`${MODULES[type].label} added to Route ${key}.`);
}
function removeModule(key, index) {
const route = state.routes[key];
if (route.modules.length <= 1) {
showToast("Keep at least one module in the route.");
return;
}
route.modules.splice(index, 1);
rebuildRoute(key);
renderRecipes();
resetMarbles();
}
function renderRecipes() {
for (const key of ["A", "B"]) {
const container = document.getElementById(`chips${key}`);
const route = state.routes[key];
container.innerHTML = route.modules.map((type, index) => `
<span
class="chip"
draggable="true"
data-route="${key}"
data-index="${index}"
title="Drag to reorder"
>
${MODULES[type].label}
<button aria-label="Remove ${MODULES[type].label}">×</button>
</span>
`).join("");
container.querySelectorAll(".chip").forEach((chip) => {
const index = Number(chip.dataset.index);
chip.addEventListener("dragstart", (event) => {
event.dataTransfer.setData("application/x-module", type);
event.dataTransfer.setData(
"application/x-source-route",
chip.dataset.route
);
event.dataTransfer.setData(
"application/x-source-index",
String(index)
);
event.dataTransfer.effectAllowed = "move";
});
chip.addEventListener("dragover", (event) => {
event.preventDefault();
event.stopPropagation();
chip.classList.add("drop-target");
});
chip.addEventListener("dragleave", () => {
chip.classList.remove("drop-target");
});
chip.addEventListener("drop", (event) => {
event.preventDefault();
event.stopPropagation();
chip.classList.remove("drop-target");
const moduleType = event.dataTransfer.getData("application/x-module");
const sourceRoute = event.dataTransfer.getData("application/x-source-route");
const sourceIndex = Number(
event.dataTransfer.getData("application/x-source-index")
);
if (!moduleType || sourceRoute !== key || sourceIndex === index) return;
const [moved] = state.routes[sourceRoute].modules.splice(sourceIndex, 1);
state.routes[sourceRoute].modules.splice(index, 0, moved);
rebuildRoute(sourceRoute);
renderRecipes();
});
chip.querySelector("button").addEventListener("click", (event) => {
event.stopPropagation();
removeModule(key, index);
});
});
}
}
let toastTimer;
function showToast(message) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2100);
}
document.querySelectorAll(".module").forEach((button) => {
button.addEventListener("click", () => {
state.selectedModule = button.dataset.module;
document.querySelectorAll(".module").forEach((item) => {
item.classList.toggle("selected", item === button);
});
showToast(`${MODULES[state.selectedModule].label} selected.`);
});
button.addEventListener("dragstart", (event) => {
event.dataTransfer.setData(
"application/x-module",
button.dataset.module
);
event.dataTransfer.effectAllowed = "copy";
});
});
for (const key of ["A", "B"]) {
const card = document.getElementById(`routeCard${key}`);
card.addEventListener("dragover", (event) => {
event.preventDefault();
card.classList.add("dragover");
});
card.addEventListener("dragleave", (event) => {
if (!card.contains(event.relatedTarget)) {
card.classList.remove("dragover");
}
});
card.addEventListener("drop", (event) => {
event.preventDefault();
card.classList.remove("dragover");
const type = event.dataTransfer.getData("application/x-module");
const sourceRoute = event.dataTransfer.getData("application/x-source-route");
const sourceIndex = Number(
event.dataTransfer.getData("application/x-source-index")
);
if (sourceRoute && Number.isInteger(sourceIndex)) {
const [moved] = state.routes[sourceRoute].modules.splice(sourceIndex, 1);
state.routes[sourceRoute] && moved;
state.routes[key].modules.push(moved);
rebuildRoute(sourceRoute);
rebuildRoute(key);
renderRecipes();
resetMarbles();
} else if (type) {
addModule(key, type);
}
});
document.getElementById(`add${key}`).addEventListener("click", () => {
addModule(key);
});
}
document.getElementById("resetLayouts").addEventListener("click", () => {
state.routes.A.modules = ["ramp", "switchback", "ramp", "runway"];
state.routes.B.modules = [
"ramp", "switchback", "ramp", "runway", "switchback", "ramp"
];
rebuildAll();
showToast("Original layouts restored.");
});
document.getElementById("releaseButton").addEventListener("click", releasePair);
document.getElementById("resetMarbles").addEventListener("click", () => {
resetMarbles();
updateTimer("Ready to run");
});
// Direct camera controls, implemented without Three.js examples/addons.
const cameraState = {
theta: 0.72,
phi: 0.88,
radius: 22,
target: new THREE.Vector3(0, 2.3, 0.6)
};
const defaultCamera = {
theta: 0.72,
phi: 0.88,
radius: 22,
target: new THREE.Vector3(0, 2.3, 0.6)
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.theta = defaultCamera.theta;
cameraState.phi = defaultCamera.phi;
cameraState.radius = defaultCamera.radius;
cameraState.target.copy(defaultCamera.target);
updateCamera();
}
const pointers = new Map();
let pinchDistance = 0;
let dragging = false;
let lastX = 0;
let lastY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
renderer.domElement.setPointerCapture(event.pointerId);
if (pointers.size === 1) {
dragging = true;
lastX = event.clientX;
lastY = event.clientY;
} else if (pointers.size === 2) {
const values = [...pointers.values()];
pinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (pinchDistance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * (pinchDistance / distance),
11,
32
);
updateCamera();
}
return;
}
if (!dragging) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
if (event.shiftKey) {
const right = new THREE.Vector3();
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
right.crossVectors(forward, camera.up).normalize();
cameraState.target.addScaledVector(right, -dx * 0.012);
cameraState.target.addScaledVector(forward, -dy * 0.012);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x, -8, 8
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z, -6, 7
);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.28,
1.38
);
}
updateCamera();
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) pinchDistance = 0;
if (pointers.size === 0) dragging = false;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
11,
32
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
releasePair();
}
if (event.key.toLowerCase() === "r") resetCamera();
});
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
}
addEventListener("resize", resize);
addBoard();
addReleaseTower();
rebuildAll();
updateCamera();
function animate(now) {
requestAnimationFrame(animate);
updateMarbles(now);
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```