Prompt specification
Build or customize the Three.js 3D scene "Inventor's Sandbox Rule Garden" 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: Inventor's Sandbox Rule Garden
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/inventor-s-sandbox-rule-garden-x3599
Scene Description Prompt:
Please use Three.js from cdnjs for a voxel scene based on this idea: inventor's sandbox rule garden. Build an original garden containing switches, weights, gates, and conveyors governed by a small shared rule set. Let players combine familiar parts in new arrangements. Return one self-contained HTML file.
Working Three.js Starter (inventor-s-sandbox-rule-garden-x3599):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Inventor's Rule Garden</title>
<style>
:root {
--ink: #26352d;
--muted: #68766b;
--panel: rgba(250, 249, 235, 0.91);
--line: rgba(48, 70, 52, 0.15);
--green: #4f7958;
--lime: #cce96c;
--amber: #e9a743;
--blue: #5dbbc3;
--shadow: 0 12px 36px rgba(37, 58, 39, 0.14);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
background:
radial-gradient(circle at 28% 18%, #fff8d9 0, #e7efcf 36%, transparent 62%),
linear-gradient(145deg, #d8e8d2, #b9d3c4);
}
button { font: inherit; }
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
outline: none;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid rgba(255,255,255,.72);
box-shadow: var(--shadow);
backdrop-filter: blur(16px) saturate(1.1);
-webkit-backdrop-filter: blur(16px) saturate(1.1);
}
.brand {
top: 22px;
left: 22px;
width: 315px;
padding: 18px 20px 16px;
border-radius: 19px;
}
.eyebrow {
display: flex;
align-items: center;
justify-content: space-between;
color: #71806f;
font-size: 10px;
font-weight: 800;
letter-spacing: .18em;
text-transform: uppercase;
}
.edition {
padding: 4px 7px;
border: 1px solid var(--line);
border-radius: 6px;
letter-spacing: .12em;
}
h1 {
margin: 9px 0 5px;
font-family: Georgia, "Times New Roman", serif;
font-size: 28px;
line-height: .98;
letter-spacing: -.035em;
font-weight: 700;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.palette {
top: 186px;
left: 22px;
width: 174px;
padding: 12px;
border-radius: 17px;
}
.section-title {
margin: 1px 4px 9px;
color: #7a8779;
font-size: 9px;
font-weight: 900;
letter-spacing: .17em;
text-transform: uppercase;
}
.part-list {
display: grid;
gap: 7px;
}
.part {
position: relative;
display: grid;
grid-template-columns: 34px 1fr auto;
align-items: center;
gap: 9px;
width: 100%;
min-height: 47px;
padding: 7px 9px 7px 7px;
border: 1px solid transparent;
border-radius: 11px;
color: var(--ink);
background: rgba(255,255,255,.42);
text-align: left;
cursor: pointer;
transition: transform .15s ease, background .15s ease, border-color .15s ease;
}
.part:hover {
transform: translateX(2px);
background: rgba(255,255,255,.8);
}
.part.active {
border-color: rgba(79,121,88,.45);
background: #e5edc9;
box-shadow: inset 3px 0 0 var(--green);
}
.part-icon {
display: grid;
place-items: center;
width: 33px;
height: 33px;
border-radius: 8px;
color: #324b38;
background: #e8e2c8;
font-size: 21px;
font-weight: 800;
box-shadow: inset 0 -2px 0 rgba(0,0,0,.08);
}
.part[data-part="switch"] .part-icon { background: #f0d7a5; }
.part[data-part="weight"] .part-icon { background: #d5d7cd; }
.part[data-part="gate"] .part-icon { background: #e7c3a4; }
.part[data-part="conveyor"] .part-icon { background: #cbd9c5; }
.part[data-part="erase"] .part-icon { background: #ead0ca; color: #874f46; }
.part-name {
display: block;
font-size: 12px;
font-weight: 800;
}
.part-note {
display: block;
margin-top: 1px;
color: #788477;
font-size: 9px;
}
.key {
color: #889187;
font: 700 9px ui-monospace, monospace;
}
.rules {
top: 22px;
right: 22px;
width: 300px;
padding: 18px;
border-radius: 19px;
}
.rules h2 {
margin: 0 0 11px;
font-family: Georgia, serif;
font-size: 18px;
letter-spacing: -.02em;
}
.rule-list {
margin: 0;
padding: 0;
list-style: none;
counter-reset: rule;
}
.rule-list li {
position: relative;
min-height: 38px;
padding: 0 0 10px 31px;
counter-increment: rule;
color: #59675b;
font-size: 11px;
line-height: 1.42;
}
.rule-list li::before {
content: counter(rule);
position: absolute;
top: 0;
left: 0;
display: grid;
place-items: center;
width: 20px;
height: 20px;
border-radius: 6px;
color: #46614c;
background: #e3e9cc;
font-size: 9px;
font-weight: 900;
}
.rule-list b { color: #35473a; }
.divider {
height: 1px;
margin: 8px 0 13px;
background: var(--line);
}
.objectives-title {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.objectives-title span:first-child {
color: #788477;
font-size: 9px;
font-weight: 900;
letter-spacing: .16em;
text-transform: uppercase;
}
#completeBadge {
padding: 3px 7px;
border-radius: 20px;
color: #71806d;
background: #e4e8da;
font-size: 8px;
font-weight: 900;
letter-spacing: .08em;
}
.objective {
display: grid;
grid-template-columns: 10px 1fr auto;
gap: 8px;
align-items: center;
min-height: 28px;
font-size: 10px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #b8c0b3;
box-shadow: 0 0 0 3px rgba(160,171,155,.13);
}
.dot.amber { background: var(--amber); }
.dot.blue { background: var(--blue); }
.dot.brass { background: #a77548; }
.objective-state {
color: #899286;
font-size: 8px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
.objective.done .objective-state { color: #4d7954; }
.toolbar {
left: 50%;
bottom: 20px;
display: flex;
gap: 6px;
padding: 7px;
border-radius: 15px;
transform: translateX(-50%);
}
.tool {
min-height: 37px;
padding: 0 13px;
border: 0;
border-radius: 10px;
color: #445247;
background: rgba(255,255,255,.62);
font-size: 10px;
font-weight: 800;
cursor: pointer;
transition: background .15s ease, transform .15s ease;
}
.tool:hover { background: #fff; transform: translateY(-1px); }
.tool.primary { color: #f6f7e9; background: #4f7657; }
.tool.primary:hover { background: #42684b; }
.tool.danger:hover { color: #934e45; background: #f4dfda; }
.selection {
left: 22px;
bottom: 20px;
min-width: 174px;
padding: 11px 13px;
border-radius: 13px;
font-size: 10px;
line-height: 1.45;
}
.selection strong {
display: block;
margin-bottom: 2px;
color: #3e5544;
font-size: 11px;
}
.selection span { color: #7a867a; }
#toast {
position: fixed;
z-index: 30;
left: 50%;
top: 26px;
max-width: min(480px, calc(100vw - 40px));
padding: 11px 16px;
border-radius: 12px;
color: #f7f7ec;
background: rgba(46,66,51,.93);
box-shadow: 0 12px 35px rgba(29,45,33,.23);
font-size: 11px;
line-height: 1.4;
text-align: center;
pointer-events: none;
opacity: 0;
transform: translate(-50%, -12px);
transition: opacity .25s ease, transform .25s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.help {
position: fixed;
z-index: 9;
right: 338px;
bottom: 22px;
color: rgba(49,72,54,.7);
font-size: 9px;
line-height: 1.55;
text-align: right;
pointer-events: none;
}
@media (max-width: 900px) {
.rules { width: 255px; }
.help { display: none; }
.brand { width: 280px; }
}
@media (max-width: 680px) {
.brand {
top: 10px;
left: 10px;
width: calc(100% - 20px);
padding: 13px 15px;
}
h1 { font-size: 23px; }
.subtitle { display: none; }
.palette {
top: 104px;
left: 10px;
width: calc(100% - 20px);
padding: 8px;
}
.section-title { display: none; }
.part-list { grid-template-columns: repeat(6, 1fr); gap: 4px; }
.part {
display: grid;
grid-template-columns: 1fr;
justify-items: center;
min-width: 0;
min-height: 47px;
padding: 5px 2px;
gap: 2px;
}
.part:hover { transform: none; }
.part-name { font-size: 8px; }
.part-note, .key { display: none; }
.rules {
top: 170px;
right: 10px;
width: 215px;
padding: 13px;
}
.rule-list { display: none; }
.rules h2 { font-size: 15px; }
.divider { margin: 4px 0 10px; }
.selection { display: none; }
.toolbar {
bottom: 10px;
width: calc(100% - 20px);
overflow-x: auto;
justify-content: flex-start;
}
.tool { flex: 0 0 auto; padding: 0 10px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel rule garden"></canvas>
<section class="panel brand">
<div class="eyebrow">
<span>Inventor's field notes</span>
<span class="edition">SANDBOX / 01</span>
</div>
<h1>The Rule Garden</h1>
<p class="subtitle">Arrange humble machines. Wake the garden. Let one simple rule carry everything.</p>
</section>
<section class="panel palette">
<div class="section-title">Garden parts</div>
<div class="part-list" id="partList">
<button class="part" data-part="vine">
<span class="part-icon">╬</span>
<span><span class="part-name">Signal vine</span><span class="part-note">Carries a rule</span></span>
<span class="key">1</span>
</button>
<button class="part" data-part="switch">
<span class="part-icon">↕</span>
<span><span class="part-name">Toggle switch</span><span class="part-note">ON / OFF source</span></span>
<span class="key">2</span>
</button>
<button class="part" data-part="weight">
<span class="part-icon">▥</span>
<span><span class="part-name">Counterweight</span><span class="part-note">Activates at 2</span></span>
<span class="key">3</span>
</button>
<button class="part" data-part="gate">
<span class="part-icon">∩</span>
<span><span class="part-name">Brass gate</span><span class="part-note">Opens when powered</span></span>
<span class="key">4</span>
</button>
<button class="part" data-part="conveyor">
<span class="part-icon">▸</span>
<span><span class="part-name">Voxel conveyor</span><span class="part-note">Click to rotate</span></span>
<span class="key">5</span>
</button>
<button class="part" data-part="erase">
<span class="part-icon">⌫</span>
<span><span class="part-name">Lift part</span><span class="part-note">Remove from soil</span></span>
<span class="key">E</span>
</button>
</div>
</section>
<section class="panel rules">
<h2>A very small rulebook</h2>
<ol class="rule-list">
<li><b>Touching makes one network.</b> Orthogonally adjacent parts share the same ON or OFF state.</li>
<li><b>Sources make ON.</b> A switch is ON when toggled; a counterweight is ON at weight 2.</li>
<li><b>One source powers its network.</b> Vines carry it, gates open, and conveyors move.</li>
<li><b>Seeds follow the belts.</b> A powered conveyor advances its seed one square. An open gate passes it onward.</li>
</ol>
<div class="divider"></div>
<div class="objectives-title">
<span>Garden checklist</span>
<span id="completeBadge">INCOMPLETE</span>
</div>
<div class="objective" id="amberObjective">
<span class="dot amber"></span><span>Wake the amber planter</span><span class="objective-state">Dormant</span>
</div>
<div class="objective" id="blueObjective">
<span class="dot blue"></span><span>Wake the blue planter</span><span class="objective-state">Dormant</span>
</div>
<div class="objective" id="gateObjective">
<span class="dot brass"></span><span>Hold the brass gate open</span><span class="objective-state">Closed</span>
</div>
</section>
<div class="panel selection" id="selection">
<strong id="selectionTitle">Voxel conveyor</strong>
<span id="selectionHint">Click soil to place. Click a placed conveyor to rotate it.</span>
</div>
<div class="help">
Drag to orbit · wheel to zoom · right-drag to pan<br>
1–5 select · E erase · Space pause · R reset pods
</div>
<nav class="panel toolbar">
<button class="tool primary" id="runButton">Pause garden</button>
<button class="tool" id="resetButton">Reset pods</button>
<button class="tool" id="undoButton">Undo</button>
<button class="tool" id="exampleButton">Example</button>
<button class="tool danger" id="clearButton">Clear</button>
</nav>
<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 $ = (selector) => document.querySelector(selector);
const $$ = (selector) => [...document.querySelectorAll(selector)];
const canvas = $("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setClearColor(0x000000, 0);
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-10, 10, 7, -7, 0.1, 100);
const GRID = { cols: 13, rows: 9, size: 1 };
const GOALS = [
{ x: 11, z: 2, color: "amber", hex: 0xe9a743 },
{ x: 11, z: 6, color: "blue", hex: 0x5dbbc3 }
];
const SPAWNS = [
{ x: 1, z: 2, color: "amber", hex: 0xf0b24f },
{ x: 1, z: 6, color: "blue", hex: 0x63c7d0 }
];
const DIRECTIONS = [
{ x: 1, z: 0 },
{ x: 0, z: 1 },
{ x: -1, z: 0 },
{ x: 0, z: -1 }
];
const parts = new Map();
const goalVisuals = [];
const pods = [];
const history = [];
const fireflies = [];
let selectedPart = "conveyor";
let running = true;
let simulationAccumulator = 0;
let won = false;
let toastTimer;
let networkCount = 0;
let activeNetworks = 0;
const keyFor = (x, z) => `${x},${z}`;
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
function gridToWorld(x, z) {
return {
x: (x - (GRID.cols - 1) / 2) * GRID.size,
z: (z - (GRID.rows - 1) / 2) * GRID.size
};
}
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.82,
metalness: options.metalness ?? 0,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1,
depthWrite: options.depthWrite ?? true
});
}
const M = {
ground: material(0xadc9ad, { roughness: 1 }),
board: material(0x6f5946),
boardEdge: material(0x8a6a4e),
soilA: material(0x78805a),
soilB: material(0x707852),
soilDark: material(0x5d654d),
green: material(0x53795a),
greenLight: material(0x7ea16b),
greenDark: material(0x365b44),
leaf: material(0x8eb36f),
wood: material(0x8b6444),
woodDark: material(0x654936),
stone: material(0x9b9d90),
stoneDark: material(0x71756d),
brass: material(0xb88243, { metalness: 0.34, roughness: 0.5 }),
brassDark: material(0x75512f, { metalness: 0.25 }),
belt: material(0x3f4a43),
beltEdge: material(0x647166),
red: material(0xc85f4d),
cream: material(0xeee6c7),
signalOn: material(0xd9f66c, { emissive: 0x92d936, emissiveIntensity: 1.35 }),
signalOff: material(0x728b58, { emissive: 0x17250d, emissiveIntensity: 0.08 }),
amber: material(0xf0b24f, { emissive: 0xd97917, emissiveIntensity: 0.45 }),
blue: material(0x63c7d0, { emissive: 0x218f9b, emissiveIntensity: 0.42 }),
beamAmber: new THREE.MeshBasicMaterial({
color: 0xf1c768, transparent: true, opacity: 0.13, depthWrite: false
}),
beamBlue: new THREE.MeshBasicMaterial({
color: 0x7bdce4, transparent: true, opacity: 0.13, depthWrite: false
}),
firefly: material(0xfff19a, { emissive: 0xffdb61, emissiveIntensity: 1.6 })
};
function box(parent, sx, sy, sz, x, y, z, mat) {
const mesh = new THREE.Mesh(unitBox, mat);
mesh.scale.set(sx, sy, sz);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addLights() {
scene.add(new THREE.HemisphereLight(0xfff8df, 0x667d68, 2.25));
const sun = new THREE.DirectionalLight(0xfff1c6, 3.2);
sun.position.set(-9, 15, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8dce0, 0.75);
fill.position.set(10, 7, -8);
scene.add(fill);
}
function buildGarden() {
const ground = box(scene, 60, 0.3, 60, 0, -0.9, 0, M.ground);
ground.castShadow = false;
box(
scene,
GRID.cols * GRID.size + 0.48,
0.7,
GRID.rows * GRID.size + 0.48,
0,
-0.43,
0,
M.board
);
box(
scene,
GRID.cols * GRID.size + 0.65,
0.18,
GRID.rows * GRID.size + 0.65,
0,
-0.18,
0,
M.boardEdge
);
for (let z = 0; z < GRID.rows; z++) {
for (let x = 0; x < GRID.cols; x++) {
const reserved = GOALS.some(g => g.x === x && g.z === z);
const mat = reserved ? M.soilDark : ((x + z) % 2 ? M.soilA : M.soilB);
box(scene, 0.94, 0.12, 0.94, ...Object.values(gridToWorld(x, z)).slice(0, 1), -0.025, 0, mat);
}
}
// Correct the soil tile positions using a dedicated loop to keep coordinates clear.
scene.children
.filter(o => o.isMesh && o.scale.x === 0.94 && o.scale.z === 0.94)
.forEach(mesh => mesh.position.y = -0.025);
// A low voxel fence around the garden bed.
const xExtent = GRID.cols * GRID.size / 2 + 0.34;
const zExtent = GRID.rows * GRID.size / 2 + 0.34;
for (let x = -6; x <= 6; x++) {
box(scene, 0.12, 0.52, 0.12, x, 0.08, -zExtent, M.wood);
box(scene, 0.12, 0.52, 0.12, x, 0.08, zExtent, M.wood);
}
for (let z = -4; z <= 4; z++) {
box(scene, 0.12, 0.52, 0.12, -xExtent, 0.08, z, M.wood);
box(scene, 0.12, 0.52, 0.12, xExtent, 0.08, z, M.wood);
}
box(scene, xExtent * 2, 0.1, 0.1, 0, 0.2, -zExtent, M.woodDark);
box(scene, xExtent * 2, 0.1, 0.1, 0, 0.2, zExtent, M.woodDark);
box(scene, 0.1, 0.1, zExtent * 2, -xExtent, 0.2, 0, M.woodDark);
box(scene, 0.1, 0.1, zExtent * 2, xExtent, 0.2, 0, M.woodDark);
buildDecor();
buildGoals();
buildPods();
}
function buildDecor() {
const treeSpots = [
[-8.1, -5.5], [-8.7, -1.8], [-8.2, 2.1], [-8.8, 5.7],
[8.3, -5.6], [8.9, -2.1], [8.2, 1.8], [8.8, 5.4],
[-4.7, -6.1], [1.8, -6.2], [5.3, -6.0]
];
treeSpots.forEach(([x, z], i) => {
const tree = new THREE.Group();
tree.position.set(x, -0.7, z);
const scale = 0.82 + (i % 3) * 0.12;
tree.scale.setScalar(scale);
scene.add(tree);
box(tree, 0.38, 1.7, 0.38, 0, 0.85, 0, M.woodDark);
box(tree, 1.35, 1.0, 1.25, 0, 1.75, 0, i % 2 ? M.green : M.greenDark);
box(tree, 0.95, 0.75, 0.95, 0.45, 2.25, 0.05, M.greenLight);
box(tree, 0.75, 0.65, 0.8, -0.48, 2.08, -0.08, M.green);
});
// Small block flowers.
const flowerColors = [material(0xe9b94d), material(0xd97c6e), material(0xe6e2c0)];
for (let i = 0; i < 22; i++) {
const side = i % 2 ? 1 : -1;
const x = side * (7.05 + (i * 0.37) % 1.2);
const z = -5.6 + ((i * 1.71) % 11.1);
const flower = new THREE.Group();
flower.position.set(x, -0.7, z);
scene.add(flower);
box(flower, 0.08, 0.55, 0.08, 0, 0.27, 0, M.greenDark);
box(flower, 0.28, 0.2, 0.28, 0, 0.62, 0, flowerColors[i % 3]);
}
// Little workbench.
const bench = new THREE.Group();
bench.position.set(-7.7, -0.7, -3.45);
bench.rotation.y = 0.2;
scene.add(bench);
box(bench, 1.8, 0.16, 0.75, 0, 0.72, 0, M.wood);
box(bench, 0.15, 0.7, 0.55, -0.62, 0.35, 0, M.woodDark);
box(bench, 0.15, 0.7, 0.55, 0.62, 0.35, 0, M.woodDark);
box(bench, 0.48, 0.35, 0.38, -0.25, 0.98, 0, M.brassDark);
box(bench, 0.18, 0.22, 0.22, 0.42, 0.91, 0.08, M.signalOff);
// Fireflies.
for (let i = 0; i < 18; i++) {
const mesh = new THREE.Mesh(unitBox, M.firefly);
const s = 0.045 + (i % 3) * 0.018;
mesh.scale.setScalar(s);
mesh.position.set(
-6.5 + (i * 1.73) % 13,
0.65 + (i % 4) * 0.28,
-4.2 + (i * 2.13) % 8.4
);
scene.add(mesh);
fireflies.push({ mesh, phase: i * 0.83, radius: 0.16 + (i % 5) * 0.04 });
}
}
function buildGoals() {
GOALS.forEach((goal, index) => {
const group = new THREE.Group();
const p = gridToWorld(goal.x, goal.z);
group.position.set(p.x, 0.04, p.z);
scene.add(group);
box(group, 0.78, 0.28, 0.78, 0, 0.14, 0, M.boardEdge);
box(group, 0.66, 0.38, 0.66, 0, 0.4, 0, M.wood);
box(group, 0.73, 0.1, 0.73, 0, 0.62, 0, M.brassDark);
const stem = box(group, 0.09, 0.72, 0.09, 0, 0.96, 0, M.greenDark);
const petalGroup = new THREE.Group();
petalGroup.position.y = 1.34;
group.add(petalGroup);
const petalMat = goal.color === "amber" ? M.amber : M.blue;
for (let i = 0; i < 5; i++) {
const angle = (i / 5) * Math.PI * 2;
const petal = box(
petalGroup,
0.29,
0.13,
0.18,
Math.cos(angle) * 0.22,
0,
Math.sin(angle) * 0.22,
petalMat
);
petal.rotation.y = -angle;
}
box(petalGroup, 0.25, 0.18, 0.25, 0, 0.06, 0, M.brass);
const beam = box(
group,
0.48,
2.2,
0.48,
0,
1.25,
0,
goal.color === "amber" ? M.beamAmber : M.beamBlue
);
beam.castShadow = false;
beam.receiveShadow = false;
const orb = box(
group,
0.15,
0.15,
0.15,
0,
1.35,
0,
goal.color === "amber" ? M.amber : M.blue
);
goalVisuals.push({
goal,
group,
petalGroup,
stem,
beam,
orb,
powered: false,
delivered: false,
index
});
});
}
function buildPods() {
SPAWNS.forEach((spawn, index) => {
const group = new THREE.Group();
const p = gridToWorld(spawn.x, spawn.z);
group.position.set(p.x, 0.43, p.z);
scene.add(group);
const mat = spawn.color === "amber" ? M.amber : M.blue;
box(group, 0.3, 0.3, 0.3, 0, 0, 0, mat);
box(group, 0.08, 0.22, 0.08, 0, 0.23, 0, M.greenDark);
box(group, 0.25, 0.07, 0.13, 0.12, 0.08, 0, M.greenLight);
box(group, 0.25, 0.07, 0.13, -0.09, 0.08, 0.08, M.greenLight);
pods.push({
group,
mat,
x: spawn.x,
z: spawn.z,
color: spawn.color,
dir: 0,
delivered: false,
index
});
});
}
function createPart(type, x, z, state = 0, dir = 0) {
const root = new THREE.Group();
const world = gridToWorld(x, z);
root.position.set(world.x, 0.05, world.z);
scene.add(root);
const part = {
type, x, z, state, dir, root, powered: false,
glow: null, signalMeshes: [], lever: null, blocks: [],
gatePivot: null, treads: []
};
if (type === "vine") {
box(root, 0.78, 0.08, 0.78, 0, 0.04, 0, M.soilDark);
const positions = [
[0, 0.13, 0, 0.26, 0.08, 0.16],
[-0.25, 0.13, 0, 0.18, 0.08, 0.16],
[0.25, 0.13, 0, 0.18, 0.08, 0.16],
[0, 0.13, -0.25, 0.16, 0.08, 0.18],
[0, 0.13, 0.25, 0.16, 0.08, 0.18]
];
positions.forEach(v => {
const m = box(root, v[3], v[4], v[5], v[0], v[1], v[2], M.signalOff);
part.signalMeshes.push(m);
});
part.glow = box(root, 0.12, 0.12, 0.12, 0, 0.4, 0, M.signalOn);
part.glow.visible = false;
}
if (type === "switch") {
box(root, 0.78, 0.12, 0.64, 0, 0.07, 0, M.brassDark);
box(root, 0.16, 0.42, 0.16, -0.19, 0.29, 0, M.brass);
box(root, 0.16, 0.42, 0.16, 0.19, 0.29, 0, M.brass);
const pivot = new THREE.Group();
pivot.position.set(0, 0.49, 0);
root.add(pivot);
box(pivot, 0.42, 0.1, 0.1, 0.16, 0.02, 0, M.stoneDark);
box(pivot, 0.18, 0.18, 0.18, 0.38, 0.02, 0, M.red);
part.lever = pivot;
part.indicator = box(root, 0.11, 0.11, 0.11, 0, 0.55, 0.24, M.signalOff);
part.glow = box(root, 0.1, 0.1, 0.1, 0, 0.66, 0, M.signalOn);
part.glow.visible = false;
}
if (type === "weight") {
box(root, 0.78, 0.1, 0.7, 0, 0.06, 0, M.stoneDark);
box(root, 0.62, 0.12, 0.58, 0, 0.17, 0, M.stone);
const b1 = box(root, 0.43, 0.24, 0.43, 0, 0.35, 0, M.stoneDark);
const b2 = box(root, 0.36, 0.24, 0.36, 0, 0.59, 0, M.stone);
part.blocks = [b1, b2];
part.glow = box(root, 0.11, 0.11, 0.11, 0.3, 0.35, 0.25, M.signalOn);
part.glow.visible = false;
}
if (type === "gate") {
box(root, 0.88, 0.1, 0.72, 0, 0.06, 0, M.stoneDark);
box(root, 0.16, 0.78, 0.18, -0.36, 0.42, 0, M.brass);
box(root, 0.16, 0.78, 0.18, 0.36, 0.42, 0, M.brass);
box(root, 0.86, 0.12, 0.18, 0, 0.8, 0, M.brassDark);
const pivot = new THREE.Group();
pivot.position.set(-0.34, 0.43, 0);
root.add(pivot);
box(pivot, 0.68, 0.18, 0.12, 0.34, 0, 0, M.brass);
box(pivot, 0.1, 0.2, 0.14, 0.16, 0, 0, M.brassDark);
box(pivot, 0.1, 0.2, 0.14, 0.51, 0, 0, M.brassDark);
part.gatePivot = pivot;
part.glow = box(root, 0.13, 0.13, 0.13, 0, 0.94, 0, M.signalOn);
part.glow.visible = false;
}
if (type === "conveyor") {
box(root, 0.92, 0.12, 0.92, 0, 0.07, 0, M.beltEdge);
box(root, 0.8, 0.08, 0.76, 0, 0.15, 0, M.belt);
const directionGroup = new THREE.Group();
root.add(directionGroup);
part.directionGroup = directionGroup;
for (let i = 0; i < 5; i++) {
const tread = box(directionGroup, 0.09, 0.035, 0.7, -0.32 + i * 0.16, 0.21, 0, M.stoneDark);
part.treads.push(tread);
}
box(directionGroup, 0.28, 0.045, 0.075, 0.16, 0.24, 0, M.cream);
const headA = box(directionGroup, 0.19, 0.045, 0.07, 0.32, 0.24, 0.085, M.cream);
const headB = box(directionGroup, 0.19, 0.045, 0.07, 0.32, 0.24, -0.085, M.cream);
headA.rotation.y = -0.62;
headB.rotation.y = 0.62;
part.glow = box(root, 0.12, 0.12, 0.12, 0, 0.42, 0, M.signalOn);
part.glow.visible = false;
updateDirection(part);
}
parts.set(keyFor(x, z), part);
updatePartVisual(part);
return part;
}
function updateDirection(part) {
if (!part.directionGroup) return;
const d = DIRECTIONS[part.dir];
part.directionGroup.rotation.y = Math.atan2(-d.z, d.x);
}
function removePart(x, z) {
const key = keyFor(x, z);
const part = parts.get(key);
if (!part) return;
part.root.removeFromParent();
parts.delete(key);
}
function setSignalMaterial(part, mat) {
part.signalMeshes.forEach(mesh => mesh.material = mat);
if (part.indicator) part.indicator.material = mat;
}
function updatePartVisual(part) {
if (part.type === "vine") {
setSignalMaterial(part, part.powered ? M.signalOn : M.signalOff);
}
if (part.type === "switch") {
if (part.indicator) part.indicator.material = part.state ? M.signalOn : M.signalOff;
}
if (part.type === "weight") {
part.blocks[0].visible = part.state >= 1;
part.blocks[1].visible = part.state >= 2;
}
if (part.glow) part.glow.visible = part.powered;
}
function recomputePower() {
const visited = new Set();
networkCount = 0;
activeNetworks = 0;
for (const [key, part] of parts) {
if (visited.has(key)) continue;
networkCount++;
const stack = [part];
const component = [];
visited.add(key);
while (stack.length) {
const current = stack.pop();
component.push(current);
for (const [nx, nz] of neighbors(current.x, current.z)) {
const nk = keyFor(nx, nz);
const neighbor = parts.get(nk);
if (neighbor && !visited.has(nk)) {
visited.add(nk);
stack.push(neighbor);
}
}
}
const active = component.some(p =>
(p.type === "switch" && p.state === 1) ||
(p.type === "weight" && p.state >= 2)
);
if (active) activeNetworks++;
component.forEach(p => {
p.powered = active;
updatePartVisual(p);
});
}
goalVisuals.forEach(gv => {
gv.powered = neighbors(gv.goal.x, gv.goal.z).some(([x, z]) => {
const p = parts.get(keyFor(x, z));
return p && p.powered;
});
});
updateHUD();
}
function neighbors(x, z) {
return [
[x + 1, z], [x - 1, z], [x, z + 1], [x, z - 1]
];
}
function updateHUD() {
const amberGoal = goalVisuals.find(g => g.goal.color === "amber");
const blueGoal = goalVisuals.find(g => g.goal.color === "blue");
const anyGate = [...parts.values()].some(p => p.type === "gate" && p.powered);
const complete = amberGoal.delivered && blueGoal.delivered && anyGate;
setObjective($("#amberObjective"), amberGoal.delivered, amberGoal.powered ? "Awake" : "Dormant");
setObjective($("#blueObjective"), blueGoal.delivered, blueGoal.powered ? "Awake" : "Dormant");
setObjective($("#gateObjective"), anyGate, anyGate ? "Open" : "Closed");
$("#completeBadge").textContent = complete ? "GARDEN BLOOMING" : "INCOMPLETE";
$("#completeBadge").style.background = complete ? "#dcecaa" : "#e4e8da";
$("#completeBadge").style.color = complete ? "#4d744b" : "#71806d";
if (complete && !won) {
won = true;
toast("The Rule Garden is blooming. Try making your own arrangement now.");
celebrate();
}
}
function setObjective(element, done, state) {
element.classList.toggle("done", done);
element.querySelector(".objective-state").textContent = done ? "Seeded" : state;
}
function canEnter(x, z, pod) {
const goal = GOALS.find(g => g.x === x && g.z === z && g.color === pod.color);
if (goal) return true;
const part = parts.get(keyFor(x, z));
if (!part) return true;
if (part.type === "conveyor" && part.powered) return true;
if (part.type === "gate" && part.powered) return true;
return false;
}
function movePod(pod, nx, nz) {
pod.x = nx;
pod.z = nz;
const world = gridToWorld(nx, nz);
pod.group.position.x = world.x;
pod.group.position.z = world.z;
const goal = GOALS.find(g => g.x === nx && g.z === nz && g.color === pod.color);
if (goal) {
pod.delivered = true;
pod.group.position.y = 0.8;
pod.group.scale.setScalar(0.78);
const gv = goalVisuals.find(g => g.goal.color === pod.color);
gv.delivered = true;
toast(`${pod.color === "amber" ? "Amber" : "Blue"} seed planted. One rule, one small beginning.`);
}
}
function updatePods() {
recomputePower();
pods.forEach(pod => {
if (pod.delivered) return;
const currentPart = parts.get(keyFor(pod.x, pod.z));
if (currentPart?.type === "conveyor" && currentPart.powered) {
const d = DIRECTIONS[currentPart.dir];
pod.dir = currentPart.dir;
const nx = pod.x + d.x;
const nz = pod.z + d.z;
if (nx >= 0 && nx < GRID.cols && nz >= 0 && nz < GRID.rows && canEnter(nx, nz, pod)) {
movePod(pod, nx, nz);
}
} else if (currentPart?.type === "gate" && currentPart.powered) {
const d = DIRECTIONS[pod.dir];
const nx = pod.x + d.x;
const nz = pod.z + d.z;
if (nx >= 0 && nx < GRID.cols && nz >= 0 && nz < GRID.rows && canEnter(nx, nz, pod)) {
movePod(pod, nx, nz);
}
}
});
updateHUD();
}
function resetPods() {
pods.forEach((pod, i) => {
const spawn = SPAWNS[i];
pod.x = spawn.x;
pod.z = spawn.z;
pod.dir = 0;
pod.delivered = false;
const world = gridToWorld(spawn.x, spawn.z);
pod.group.position.set(world.x, 0.43, world.z);
pod.group.scale.setScalar(1);
});
goalVisuals.forEach(gv => gv.delivered = false);
won = false;
updateHUD();
}
function serializeParts() {
return [...parts.values()].map(p => ({
type: p.type, x: p.x, z: p.z, state: p.state, dir: p.dir
}));
}
function pushHistory() {
history.push(serializeParts());
if (history.length > 60) history.shift();
}
function restoreSnapshot(snapshot) {
[...parts.values()].forEach(p => p.root.removeFromParent());
parts.clear();
snapshot.forEach(data => createPart(data.type, data.x, data.z, data.state, data.dir));
recomputePower();
}
function undo() {
if (!history.length) {
toast("Nothing to undo yet.");
return;
}
restoreSnapshot(history.pop());
resetPods();
toast("Undid the last garden change.");
}
function placePart(type, x, z) {
if (GOALS.some(g => g.x === x && g.z === z)) {
toast("The two planters are reserved for seeds.");
return;
}
if (parts.has(keyFor(x, z))) return;
pushHistory();
const state = type === "switch" ? 0 : type === "weight" ? 0 : 0;
createPart(type, x, z, state, 0);
recomputePower();
}
function interactPart(part) {
pushHistory();
if (part.type === "switch") {
part.state = part.state ? 0 : 1;
toast(part.state ? "Switch ON — its network is awake." : "Switch OFF.");
} else if (part.type === "weight") {
part.state = (part.state + 1) % 3;
toast(
part.state === 2 ? "Counterweight at 2 — the network activates." :
part.state === 1 ? "Counterweight at 1 — not heavy enough." :
"Counterweight reset."
);
} else if (part.type === "conveyor") {
part.dir = (part.dir + 1) % DIRECTIONS.length;
updateDirection(part);
const names = ["east", "south", "west", "north"];
toast(`Conveyor now points ${names[part.dir]}.`);
} else if (part.type === "gate") {
toast("The brass gate opens automatically when its network is ON.");
} else if (part.type === "vine") {
toast("Signal vines simply carry the network's rule.");
}
recomputePower();
}
function clearGarden() {
if (!parts.size) return;
pushHistory();
[...parts.values()].forEach(p => p.root.removeFromParent());
parts.clear();
resetPods();
recomputePower();
toast("Garden cleared. The soil is waiting.");
}
function loadPreset(name) {
pushHistory();
[...parts.values()].forEach(p => p.root.removeFromParent());
parts.clear();
if (name === "example") {
createPart("switch", 1, 1, 1, 0);
for (let x = 1; x <= 10; x++) createPart("conveyor", x, 2, 0, 0);
createPart("weight", 1, 7, 2, 0);
for (let x = 1; x <= 3; x++) createPart("conveyor", x, 6, 0, 0);
createPart("gate", 4, 6);
for (let x = 5; x <= 10; x++) createPart("conveyor", x, 6, 0, 0);
createPart("vine", 2, 1);
createPart("vine", 2, 7);
toast("Example loaded. Watch both networks carry their seeds.");
} else {
createPart("switch", 1, 1, 1, 0);
for (let x = 1; x <= 5; x++) createPart("conveyor", x, 2, 0, 0);
createPart("vine", 1, 3);
createPart("weight", 1, 7, 1, 0);
for (let x = 1; x <= 3; x++) createPart("conveyor", x, 6, 0, 0);
createPart("gate", 4, 6);
for (let x = 5; x <= 8; x++) createPart("conveyor", x, 6, 0, 0);
toast("Starter garden restored. Raise the stone weight to 2, then extend the belts east.");
}
resetPods();
recomputePower();
}
// ---------- Camera and picking ----------
const orbit = {
azimuth: Math.PI * 0.25,
polar: 0.83,
zoom: 1,
target: new THREE.Vector3(0, 0.2, 0)
};
function updateCamera() {
const aspect = innerWidth / innerHeight;
const halfHeight = Math.max(6.7, 8.8 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
const distance = 24;
const sinPolar = Math.sin(orbit.polar);
camera.position.set(
orbit.target.x + Math.sin(orbit.azimuth) * sinPolar * distance,
orbit.target.y + Math.cos(orbit.polar) * distance,
orbit.target.z + Math.cos(orbit.azimuth) * sinPolar * distance
);
camera.zoom = orbit.zoom;
camera.updateProjectionMatrix();
camera.lookAt(orbit.target);
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);
const hover = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({
color: 0xe9f39b,
transparent: true,
opacity: 0.23,
depthWrite: false
})
);
hover.scale.set(0.91, 0.025, 0.91);
hover.position.y = 0.075;
hover.visible = false;
scene.add(hover);
function pickCell(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointerNDC.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const point = new THREE.Vector3();
if (!raycaster.ray.intersectPlane(groundPlane, point)) return null;
const x = Math.round(point.x + (GRID.cols - 1) / 2);
const z = Math.round(point.z + (GRID.rows - 1) / 2);
if (x < 0 || x >= GRID.cols || z < 0 || z >= GRID.rows) return null;
return { x, z };
}
function updateHover(clientX, clientY) {
const cell = pickCell(clientX, clientY);
if (!cell) {
hover.visible = false;
return;
}
const world = gridToWorld(cell.x, cell.z);
hover.position.x = world.x;
hover.position.z = world.z;
hover.visible = true;
hover.material.color.setHex(parts.has(keyFor(cell.x, cell.z)) ? 0xf2b56a : 0xe9f39b);
}
function handleCanvasClick(clientX, clientY) {
const cell = pickCell(clientX, clientY);
if (!cell) return;
const existing = parts.get(keyFor(cell.x, cell.z));
if (selectedPart === "erase") {
if (existing) {
pushHistory();
removePart(cell.x, cell.z);
recomputePower();
toast("Part lifted from the soil.");
}
return;
}
if (existing) {
interactPart(existing);
} else {
placePart(selectedPart, cell.x, cell.z);
}
}
const pointerState = new Map();
let drag = null;
let pinchDistance = 0;
canvas.addEventListener("contextmenu", e => e.preventDefault());
canvas.addEventListener("pointerdown", e => {
canvas.setPointerCapture(e.pointerId);
pointerState.set(e.pointerId, {
x: e.clientX, y: e.clientY,
startX: e.clientX, startY: e.clientY,
button: e.button, moved: false
});
if (pointerState.size === 1) {
drag = {
mode: e.button === 2 || e.button === 1 ? "pan" : "orbit",
x: e.clientX, y: e.clientY,
moved: false
};
} else if (pointerState.size === 2) {
const points = [...pointerState.values()];
pinchDistance = Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y);
}
});
canvas.addEventListener("pointermove", e => {
const state = pointerState.get(e.pointerId);
if (!state) {
updateHover(e.clientX, e.clientY);
return;
}
const dx = e.clientX - state.x;
const dy = e.clientY - state.y;
state.x = e.clientX;
state.y = e.clientY;
if (Math.hypot(e.clientX - state.startX, e.clientY - state.startY) > 4) {
state.moved = true;
}
if (pointerState.size === 2) {
const points = [...pointerState.values()];
const distance = Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y);
if (pinchDistance > 0 && distance > 0) {
orbit.zoom = clamp(orbit.zoom * distance / pinchDistance, 0.65, 1.8);
updateCamera();
}
pinchDistance = distance;
return;
}
if (!drag || !state.moved) return;
drag.moved = true;
if (drag.mode === "orbit") {
orbit.azimuth -= dx * 0.006;
orbit.polar = clamp(orbit.polar - dy * 0.005, 0.42, 1.22);
} else {
const scale = 0.012 / orbit.zoom;
const right = new THREE.Vector3(Math.cos(orbit.azimuth), 0, -Math.sin(orbit.azimuth));
const forward = new THREE.Vector3(-Math.sin(orbit.azimuth), 0, -Math.cos(orbit.azimuth));
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(forward, -dy * scale);
}
updateCamera();
});
canvas.addEventListener("pointerup", e => {
const state = pointerState.get(e.pointerId);
pointerState.delete(e.pointerId);
if (state && !state.moved && state.button === 0 && pointerState.size === 0) {
handleCanvasClick(e.clientX, e.clientY);
}
if (pointerState.size === 0) drag = null;
if (pointerState.size < 2) pinchDistance = 0;
});
canvas.addEventListener("pointercancel", e => {
pointerState.delete(e.pointerId);
drag = null;
});
canvas.addEventListener("pointerleave", () => {
if (!pointerState.size) hover.visible = false;
});
canvas.addEventListener("wheel", e => {
e.preventDefault();
orbit.zoom = clamp(orbit.zoom * Math.exp(-e.deltaY * 0.001), 0.65, 1.8);
updateCamera();
}, { passive: false });
// ---------- UI ----------
const selectionCopy = {
vine: ["Signal vine", "Click soil to place. Vines carry their network's ON/OFF rule."],
switch: ["Toggle switch", "Click a placed switch to turn its network ON or OFF."],
weight: ["Counterweight", "Click a placed weight to cycle 0, 1, and 2. Weight 2 activates."],
gate: ["Brass gate", "Click a placed gate for a reminder. It opens automatically when powered."],
conveyor: ["Voxel conveyor", "Click soil to place. Click a placed conveyor to rotate it."],
erase: ["Lift part", "Click a placed part to remove it. Right-click also erases."]
};
function selectPart(type) {
selectedPart = type;
$$(".part").forEach(button => button.classList.toggle("active", button.dataset.part === type));
$("#selectionTitle").textContent = selectionCopy[type][0];
$("#selectionHint").textContent = selectionCopy[type][1];
}
$$(".part").forEach(button => {
button.addEventListener("click", () => selectPart(button.dataset.part));
});
$("#runButton").addEventListener("click", () => {
running = !running;
$("#runButton").textContent = running ? "Pause garden" : "Run garden";
});
$("#resetButton").addEventListener("click", () => {
resetPods();
toast("Seeds returned to their starting beds.");
});
$("#undoButton").addEventListener("click", undo);
$("#clearButton").addEventListener("click", clearGarden);
$("#exampleButton").addEventListener("click", () => loadPreset("example"));
addEventListener("keydown", e => {
if (e.ctrlKey || e.metaKey) {
if (e.key.toLowerCase() === "z") {
e.preventDefault();
undo();
}
return;
}
const key = e.key.toLowerCase();
const shortcuts = {
"1": "vine",
"2": "switch",
"3": "weight",
"4": "gate",
"5": "conveyor",
"e": "erase"
};
if (shortcuts[key]) selectPart(shortcuts[key]);
if (key === " ") {
e.preventDefault();
$("#runButton").click();
}
if (key === "r") resetPods();
});
function toast(message) {
const element = $("#toast");
element.textContent = message;
element.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => element.classList.remove("show"), 3600);
}
function celebrate() {
const colors = [M.amber, M.blue, M.signalOn, M.cream];
for (let i = 0; i < 28; i++) {
const mesh = new THREE.Mesh(unitBox, colors[i % colors.length]);
const size = 0.06 + (i % 4) * 0.025;
mesh.scale.setScalar(size);
mesh.castShadow = true;
mesh.position.set(
-2 + (i % 7) * 0.7,
1.8 + (i % 4) * 0.22,
-1.5 + Math.floor(i / 7) * 0.6
);
scene.add(mesh);
mesh.userData.velocity = new THREE.Vector3(
(Math.random() - 0.5) * 2.2,
1.6 + Math.random() * 1.8,
(Math.random() - 0.5) * 2.2
);
mesh.userData.life = 2.5;
celebrateBits.push(mesh);
}
}
const celebrateBits = [];
function updateCelebration(delta) {
for (let i = celebrateBits.length - 1; i >= 0; i--) {
const bit = celebrateBits[i];
bit.userData.life -= delta;
bit.userData.velocity.y -= 2.4 * delta;
bit.position.addScaledVector(bit.userData.velocity, delta);
bit.rotation.x += delta * 4;
bit.rotation.z += delta * 3;
if (bit.userData.life <= 0) {
bit.removeFromParent();
celebrateBits.splice(i, 1);
}
}
}
addEventListener("resize", () => {
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
updateCamera();
});
// ---------- Animation ----------
addLights();
buildGarden();
loadPreset("starter");
selectPart("conveyor");
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
if (running) {
simulationAccumulator += delta;
if (simulationAccumulator >= 0.58) {
simulationAccumulator -= 0.58;
updatePods();
}
}
parts.forEach(part => {
if (part.lever) {
const target = part.state ? -0.67 : 0.67;
part.lever.rotation.z = lerp(part.lever.rotation.z, target, 1 - Math.pow(0.001, delta));
}
if (part.gatePivot) {
const target = part.powered ? -1.34 : 0;
part.gatePivot.rotation.z = lerp(part.gatePivot.rotation.z, target, 1 - Math.pow(0.0005, delta));
}
if (part.type === "conveyor" && part.powered) {
part.treads.forEach((tread, i) => {
const phase = (elapsed * 0.72 + i / part.treads.length) % 1;
tread.position.x = -0.34 + phase * 0.68;
});
if (part.glow) {
part.glow.scale.setScalar(0.11 + Math.sin(elapsed * 4 + part.x) * 0.018);
}
}
});
goalVisuals.forEach((gv, index) => {
const awake = gv.powered || gv.delivered;
const pulse = awake ? 1 + Math.sin(elapsed * 2.4 + index) * 0.045 : 0.82;
gv.petalGroup.scale.setScalar(pulse);
gv.petalGroup.rotation.y = elapsed * (awake ? 0.12 : 0.025);
gv.beam.visible = awake;
gv.beam.material.opacity = gv.delivered ? 0.22 : awake ? 0.1 + Math.sin(elapsed * 2) * 0.025 : 0;
gv.orb.rotation.y += delta * 0.8;
});
pods.forEach((pod, index) => {
pod.group.rotation.y += delta * (pod.delivered ? 0.5 : 1.15);
if (!pod.delivered) {
pod.group.position.y = 0.43 + Math.sin(elapsed * 3 + index) * 0.035;
}
});
fireflies.forEach((f, i) => {
f.mesh.position.x += Math.sin(elapsed * 0.55 + f.phase) * 0.0018;
f.mesh.position.y += Math.cos(elapsed * 0.7 + f.phase) * 0.0013;
f.mesh.position.z += Math.sin(elapsed * 0.45 + f.phase * 1.3) * 0.0016;
const s = 0.04 + (i % 3) * 0.012 + Math.sin(elapsed * 3 + f.phase) * 0.008;
f.mesh.scale.setScalar(Math.max(0.025, s));
});
updateCelebration(delta);
renderer.render(scene, camera);
}
setTimeout(() => {
toast("Try this: click the stone weight until it reaches 2, then extend the belts east.");
}, 1000);
animate();
</script>
</body>
</html>
```