Prompt specification
Build or customize the Three.js 3D scene "Compare relay layouts with one blocked passage" 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: Compare relay layouts with one blocked passage
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/compare-relay-layouts-with-one-blocked-passage-x2360
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Let users rearrange a fictional bucket relay when a lane is blocked. Track water deliveries under simple timing rules and show how bottlenecks affect the response.
Working Three.js Starter (compare-relay-layouts-with-one-blocked-passage-x2360):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bucket Relay — Voxel Logistics Lab</title>
<style>
:root {
--ink: #173630;
--muted: #6b8179;
--paper: rgba(250, 252, 246, 0.94);
--line: rgba(23, 54, 48, 0.12);
--teal: #159d8a;
--teal-dark: #0c776b;
--amber: #ee9b39;
--amber-dark: #b96b13;
--red: #d95e4f;
--shadow: 0 18px 55px rgba(27, 60, 51, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 45% 20%, #f9fcf3 0, #e9f1e8 45%, #dce9df 100%);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
linear-gradient(90deg, rgba(255,255,255,.2), transparent 24%),
radial-gradient(ellipse at center, transparent 55%, rgba(50, 79, 69, .08));
}
.brand {
position: fixed;
top: 24px;
left: 26px;
z-index: 5;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: var(--teal-dark);
font-size: 11px;
font-weight: 800;
letter-spacing: .16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--teal);
box-shadow: 0 0 0 5px rgba(21, 157, 138, .12);
}
h1 {
margin: 0;
font-size: clamp(26px, 3vw, 42px);
line-height: .95;
letter-spacing: -.055em;
font-weight: 850;
}
.subtitle {
max-width: 420px;
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.clock {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 13px;
padding: 7px 10px;
border: 1px solid rgba(23, 54, 48, .1);
border-radius: 8px;
background: rgba(255,255,255,.55);
color: var(--muted);
font-size: 11px;
font-weight: 750;
letter-spacing: .08em;
}
.clock b {
color: var(--ink);
font-variant-numeric: tabular-nums;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
width: min(330px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
border: 1px solid rgba(255,255,255,.72);
border-radius: 18px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
scrollbar-width: thin;
}
.panel-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 14px;
}
.panel-head h2 {
margin: 0 0 3px;
font-size: 16px;
letter-spacing: -.025em;
}
.panel-head p {
margin: 0;
color: var(--muted);
font-size: 11px;
}
.status-pill {
flex: 0 0 auto;
padding: 6px 8px;
border-radius: 999px;
background: rgba(21, 157, 138, .1);
color: var(--teal-dark);
font-size: 10px;
font-weight: 800;
letter-spacing: .06em;
text-transform: uppercase;
white-space: nowrap;
}
.status-pill.warn {
background: rgba(238, 155, 57, .15);
color: var(--amber-dark);
}
.status-pill.danger {
background: rgba(217, 94, 79, .13);
color: #a53e34;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 16px;
}
.metric {
min-height: 76px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255,255,255,.72);
}
.metric strong {
display: block;
font-size: 25px;
line-height: 1;
letter-spacing: -.04em;
font-variant-numeric: tabular-nums;
}
.metric span {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: .07em;
text-transform: uppercase;
}
.metric.alert strong {
color: var(--amber-dark);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 17px 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 850;
letter-spacing: .12em;
text-transform: uppercase;
}
.section-title small {
color: #91a099;
font-size: 9px;
letter-spacing: .05em;
}
.route-row {
display: grid;
grid-template-columns: 12px 1fr auto;
align-items: center;
gap: 9px;
min-height: 47px;
padding: 8px 0;
border-bottom: 1px solid var(--line);
}
.route-row:last-child {
border-bottom: 0;
}
.route-dot {
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--route);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--route) 14%, transparent);
}
.route-copy {
min-width: 0;
}
.route-copy b {
display: block;
font-size: 12px;
}
.route-copy small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.route-row.blocked .route-copy small {
color: var(--amber-dark);
font-weight: 750;
}
.block-button {
min-width: 60px;
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 8px;
background: #fff;
cursor: pointer;
font-size: 10px;
font-weight: 800;
transition: .15s ease;
}
.block-button:hover {
border-color: var(--amber);
color: var(--amber-dark);
}
.block-button.active {
border-color: rgba(238, 155, 57, .4);
background: rgba(238, 155, 57, .14);
color: var(--amber-dark);
}
.control-grid {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
align-items: end;
}
.field label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
select {
width: 100%;
height: 36px;
padding: 0 30px 0 10px;
border: 1px solid var(--line);
border-radius: 9px;
outline: none;
background: #fff;
color: var(--ink);
font-size: 11px;
font-weight: 700;
cursor: pointer;
}
.speed-buttons {
display: flex;
gap: 4px;
padding: 3px;
border: 1px solid var(--line);
border-radius: 9px;
background: #fff;
}
.speed-buttons button {
width: 34px;
height: 28px;
padding: 0;
border: 0;
border-radius: 6px;
background: transparent;
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.speed-buttons button.active {
background: var(--ink);
color: #fff;
}
.chart-wrap {
position: relative;
height: 94px;
padding: 8px 8px 4px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255,255,255,.72);
overflow: hidden;
}
#chart {
width: 100%;
height: 100%;
display: block;
}
.chart-legend {
position: absolute;
top: 7px;
right: 9px;
display: flex;
gap: 9px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
text-transform: uppercase;
}
.chart-legend span::before {
content: "";
display: inline-block;
width: 6px;
height: 6px;
margin-right: 4px;
border-radius: 2px;
background: var(--teal);
vertical-align: 0;
}
.chart-legend span:last-child::before {
background: var(--amber);
}
.event-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.event {
display: grid;
grid-template-columns: 7px 1fr;
gap: 8px;
align-items: start;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.event::before {
content: "";
width: 6px;
height: 6px;
margin-top: 3px;
border-radius: 2px;
background: var(--teal);
}
.event.warn::before {
background: var(--amber);
}
.event.info::before {
background: #7f91a0;
}
.reset-button {
width: 100%;
margin-top: 15px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: transparent;
cursor: pointer;
font-size: 10px;
font-weight: 850;
letter-spacing: .07em;
text-transform: uppercase;
}
.reset-button:hover {
background: #fff;
}
#labels {
position: fixed;
inset: 0;
z-index: 3;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
padding: 5px 7px;
border: 1px solid rgba(255,255,255,.72);
border-radius: 6px;
background: rgba(250,252,246,.82);
box-shadow: 0 5px 14px rgba(38,68,59,.11);
color: var(--ink);
font-size: 9px;
font-weight: 850;
letter-spacing: .09em;
text-transform: uppercase;
white-space: nowrap;
transform: translate(-50%, -50%);
backdrop-filter: blur(5px);
}
.world-label.route-label {
padding-top: 4px;
padding-bottom: 4px;
border-color: color-mix(in srgb, var(--route) 38%, white);
color: color-mix(in srgb, var(--route) 72%, #173630);
}
.help {
position: fixed;
z-index: 6;
left: 50%;
bottom: 22px;
display: flex;
align-items: center;
gap: 9px;
max-width: min(560px, calc(100vw - 40px));
padding: 10px 14px;
border: 1px solid rgba(255,255,255,.72);
border-radius: 12px;
background: rgba(250,252,246,.88);
box-shadow: 0 12px 34px rgba(32,67,57,.13);
color: var(--muted);
font-size: 11px;
line-height: 1.35;
transform: translateX(-50%);
backdrop-filter: blur(12px);
}
.help-icon {
display: grid;
flex: 0 0 auto;
width: 24px;
height: 24px;
place-items: center;
border-radius: 7px;
background: var(--amber);
color: #fff;
font-weight: 900;
}
.help b {
color: var(--ink);
}
.toast {
position: fixed;
z-index: 20;
top: 24px;
left: 50%;
padding: 11px 15px;
border-radius: 10px;
background: var(--ink);
box-shadow: 0 12px 35px rgba(23,54,48,.22);
color: #fff;
font-size: 11px;
font-weight: 700;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -12px);
transition: .2s ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
.brand {
top: 17px;
left: 18px;
}
.subtitle,
.clock {
display: none;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
width: min(310px, calc(100vw - 24px));
max-height: 58vh;
padding: 14px;
}
.help {
left: 16px;
bottom: 16px;
max-width: calc(100vw - 350px);
transform: none;
}
}
@media (max-width: 650px) {
.brand h1 {
font-size: 27px;
}
.panel {
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 47vh;
}
.metrics {
grid-template-columns: repeat(4, 1fr);
}
.metric {
min-height: 66px;
padding: 9px;
}
.metric strong {
font-size: 19px;
}
.metric span {
font-size: 8px;
}
.help {
left: 10px;
bottom: auto;
top: 76px;
max-width: calc(100vw - 20px);
}
.chart-wrap,
.event-list {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional bucket relay simulation"></canvas>
<div class="vignette"></div>
<div id="labels"></div>
<header class="brand">
<div class="eyebrow">Voxel logistics lab</div>
<h1>Bucket Relay</h1>
<p class="subtitle">
A tiny emergency-water network. When a lane closes, move stranded buckets
and watch response time recover.
</p>
<div class="clock">SIM CLOCK <b id="clock">00:00</b></div>
</header>
<aside class="panel">
<div class="panel-head">
<div>
<h2>Relay control</h2>
<p>Production: one bucket every 2.2 seconds</p>
</div>
<div id="systemStatus" class="status-pill">Flowing</div>
</div>
<div class="metrics">
<div class="metric">
<strong id="delivered">0</strong>
<span>Delivered</span>
</div>
<div class="metric">
<strong id="response">—</strong>
<span>Avg response</span>
</div>
<div class="metric alert">
<strong id="queued">0</strong>
<span>Queued</span>
</div>
<div class="metric">
<strong id="flow">0</strong>
<span>Flow / min</span>
</div>
</div>
<div class="section-title">
<span>Lane status</span>
<small>Click to block / reopen</small>
</div>
<div id="routeRows"></div>
<div class="section-title">
<span>Dispatch rules</span>
<small>Timing is simulated</small>
</div>
<div class="control-grid">
<div class="field">
<label for="policy">New bucket routing</label>
<select id="policy">
<option value="cycle">Round-robin relay</option>
<option value="auto">Auto-clear blocked lanes</option>
</select>
</div>
<div>
<label class="field" style="margin-bottom: 6px">Speed</label>
<div class="speed-buttons">
<button id="pause" title="Pause simulation">Ⅱ</button>
<button data-speed="1" class="active">1×</button>
<button data-speed="2">2×</button>
</div>
</div>
</div>
<div class="section-title">
<span>Bottleneck pressure</span>
<small>Last 40 seconds</small>
</div>
<div class="chart-wrap">
<canvas id="chart"></canvas>
<div class="chart-legend">
<span>Deliveries</span>
<span>Waiting</span>
</div>
</div>
<div class="section-title">
<span>Relay log</span>
<small>Latest events</small>
</div>
<div id="eventList" class="event-list"></div>
<button id="reset" class="reset-button">Restart blockage drill</button>
</aside>
<div class="help">
<span class="help-icon">↗</span>
<span><b>Drag an amber stranded bucket</b> onto a glowing open-lane pad.
Drag empty space to orbit; scroll to zoom.</span>
</div>
<div id="toast" class="toast"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and state
// -------------------------------------------------------------------------
const PRODUCTION_INTERVAL = 2.2;
const SOURCE_DISPATCH_INTERVAL = 0.85;
const APPROACH_DURATION = 2.0;
const LANE_SPEED = 1.65;
const DRAG_HANDOFF_DURATION = 0.9;
const routeDefs = [
{
id: "lily",
name: "Lily lane",
z: -3.2,
color: 0x39b7a1,
css: "#159d8a",
tile: 0x8bd1c2
},
{
id: "reed",
name: "Reed lane",
z: 0,
color: 0x4d8ed8,
css: "#4d8ed8",
tile: 0x9dbfe2
},
{
id: "moss",
name: "Moss lane",
z: 3.2,
color: 0xd88b45,
css: "#d88b45",
tile: 0xe4ba89
}
];
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xe7efe7, 27, 47);
const camera = new THREE.OrthographicCamera(-12, 12, 8, -8, 0.1, 100);
const cameraTarget = new THREE.Vector3(-0.4, 0, 0);
const cameraState = {
yaw: 0.42,
pitch: 0.76,
zoom: 1
};
const hemisphere = new THREE.HemisphereLight(0xf8fff2, 0x668176, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4d5, 3.1);
sun.position.set(-7, 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 = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0003;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xaadfff, 0.8);
fill.position.set(10, 7, -10);
scene.add(fill);
const materialCache = new Map();
function standardMaterial(color) {
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0.02
})
);
}
return materialCache.get(color);
}
function addBox(
parent,
width,
height,
depth,
color,
x = 0,
y = 0,
z = 0,
castShadow = true
) {
const geometry = new THREE.BoxGeometry(width, height, depth);
const mesh = new THREE.Mesh(
geometry,
typeof color === "object" ? color : standardMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(
parent,
radiusTop,
radiusBottom,
height,
color,
x = 0,
y = 0,
z = 0,
segments = 8
) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments),
typeof color === "object" ? color : standardMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Route geometry
// -------------------------------------------------------------------------
function buildRouteData(route) {
const points = [
new THREE.Vector3(-5.4, 0.56, 0),
new THREE.Vector3(-2.8, 0.56, route.z),
new THREE.Vector3(-0.1, 0.56, route.z),
new THREE.Vector3(1.8, 0.56, route.z),
new THREE.Vector3(4.7, 0.56, 0),
new THREE.Vector3(8.3, 0.56, 0)
];
const lengths = [];
let total = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
lengths.push(length);
total += length;
}
let barrierDistance = 0;
for (let i = 0; i < 3; i++) barrierDistance += lengths[i];
return {
points,
lengths,
total,
barrierDistance,
barrierFraction: barrierDistance / total
};
}
const routeData = routeDefs.map(buildRouteData);
function routePoint(routeIndex, fraction, target = new THREE.Vector3()) {
const data = routeData[routeIndex];
let distance = THREE.MathUtils.clamp(fraction, 0, 1) * data.total;
for (let i = 0; i < data.lengths.length; i++) {
if (distance <= data.lengths[i] || i === data.lengths.length - 1) {
const t = THREE.MathUtils.clamp(distance / data.lengths[i], 0, 1);
target.lerpVectors(data.points[i], data.points[i + 1], t);
return target;
}
distance -= data.lengths[i];
}
return target.copy(data.points[data.points.length - 1]);
}
// -------------------------------------------------------------------------
// Voxel environment
// -------------------------------------------------------------------------
const world = new THREE.Group();
scene.add(world);
addBox(world, 23.5, 0.65, 12.6, 0xd7e4d4, -0.4, -0.48, 0);
addBox(world, 22.7, 0.14, 11.8, 0xe8efdf, -0.4, -0.11, 0);
function voxelPath(points, color, spacing = 0.43) {
const group = new THREE.Group();
world.add(group);
for (let segment = 0; segment < points.length - 1; segment++) {
const start = points[segment];
const end = points[segment + 1];
const count = Math.ceil(start.distanceTo(end) / spacing);
for (let i = 0; i < count; i++) {
const t = i / count;
const point = new THREE.Vector3().lerpVectors(start, end, t);
const tile = addBox(
group,
0.37,
0.11,
0.37,
color,
point.x,
0.02,
point.z,
false
);
tile.rotation.y = ((segment + i) % 3 - 1) * 0.035;
}
}
}
voxelPath(
[
new THREE.Vector3(-9.0, 0, 0),
new THREE.Vector3(-5.4, 0, 0)
],
0xb7c8bb
);
routeDefs.forEach((route, index) => {
voxelPath(routeData[index].points, route.tile);
});
// Small route guide markers around the fork.
routeDefs.forEach((route) => {
const marker = new THREE.Group();
marker.position.set(-5.05, 0.12, route.z * 0.24);
addBox(marker, 0.13, 0.23, 0.13, route.color, 0, 0, 0);
world.add(marker);
});
// Source well.
const well = new THREE.Group();
well.position.set(-9, 0, 0);
world.add(well);
addBox(well, 2.25, 0.16, 2.25, 0xb7c3ae, 0, 0.05, 0);
for (let i = 0; i < 8; i++) {
const angle = (i / 8) * Math.PI * 2;
addBox(
well,
0.54,
0.36,
0.54,
i % 2 ? 0x899888 : 0x9cab99,
Math.cos(angle) * 0.88,
0.25,
Math.sin(angle) * 0.88
);
}
addBox(well, 1.35, 0.08, 1.35, 0x43b8d0, 0, 0.24, 0);
addBox(well, 0.12, 1.45, 0.12, 0x76543d, -0.84, 0.83, 0);
addBox(well, 0.12, 1.45, 0.12, 0x76543d, 0.84, 0.83, 0);
addBox(well, 1.95, 0.18, 1.28, 0xd77f4f, 0, 1.58, 0);
// Source queue rack.
addBox(world, 0.16, 0.8, 2.8, 0x7b6950, -10.65, 0.42, 0);
addBox(world, 1.1, 0.12, 2.8, 0x9a815e, -10.18, 0.83, 0);
// Fork platform.
addCylinder(world, 1.1, 1.1, 0.18, 0xc8d3c3, -5.4, 0.08, 0, 12);
addCylinder(world, 0.42, 0.42, 0.25, 0x547d70, -5.4, 0.25, 0, 8);
// Relay huts.
routeDefs.forEach((route, index) => {
const side = index === 1 ? 0.9 : index === 0 ? 0.9 : -0.9;
const hut = new THREE.Group();
hut.position.set(-2.5, 0.04, route.z + side);
world.add(hut);
addBox(hut, 1.1, 0.15, 1.05, 0xb6c3af, 0, 0.02, 0);
addBox(hut, 0.85, 0.72, 0.76, 0xe2e4d0, 0, 0.43, 0);
addBox(hut, 1.08, 0.18, 0.98, route.color, 0, 0.88, 0);
addBox(hut, 0.38, 0.36, 0.06, 0x426f67, 0, 0.42, -0.4);
const sign = addBox(
hut,
0.48,
0.2,
0.08,
route.color,
0,
0.75,
-0.42
);
sign.rotation.x = -0.08;
});
// Merge plaza.
addCylinder(world, 1.18, 1.18, 0.18, 0xc7d2c1, 4.7, 0.08, 0, 12);
addCylinder(world, 0.3, 0.3, 0.38, 0x496f66, 4.7, 0.31, 0, 8);
// Homes.
const homeColors = [0xe99763, 0xe5c96d, 0x7bb6a2];
[-1.55, 0, 1.55].forEach((z, index) => {
const home = new THREE.Group();
home.position.set(9.1, 0, z);
world.add(home);
addBox(home, 1.45, 1.15, 1.35, 0xe9e2cb, 0, 0.62, 0);
addBox(home, 1.7, 0.24, 1.58, homeColors[index], 0, 1.3, 0);
addBox(home, 0.34, 0.57, 0.08, 0x527c78, 0, 0.38, -0.7);
addBox(home, 0.3, 0.3, 0.08, 0xa9d8db, -0.48, 0.73, -0.7);
addBox(home, 0.3, 0.3, 0.08, 0xa9d8db, 0.48, 0.73, -0.7);
addBox(home, 0.22, 0.65, 0.22, 0x896955, 0.4, 1.64, 0.15);
});
// Small crop plots.
[[-7.1, -4.6], [-4.8, -4.7], [6.6, -4.6], [-9.6, 4.3]].forEach(
([x, z], plotIndex) => {
const plot = new THREE.Group();
plot.position.set(x, 0, z);
world.add(plot);
addBox(plot, 1.75, 0.12, 1.3, 0x9eaa78, 0, 0.02, 0);
for (let row = -1; row <= 1; row++) {
for (let col = -1; col <= 1; col++) {
addBox(
plot,
0.18,
0.32 + (plotIndex % 2) * 0.1,
0.18,
plotIndex % 2 ? 0xe0b64f : 0x78aa61,
col * 0.5,
0.22,
row * 0.37
);
}
}
}
);
// Voxel trees.
function addTree(x, z, size = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(size);
world.add(tree);
addBox(tree, 0.34, 1.25, 0.34, 0x846447, 0, 0.65, 0);
addBox(tree, 1.15, 0.8, 1.15, 0x5d9b70, 0, 1.45, 0);
addBox(tree, 0.82, 0.66, 0.82, 0x72ad7e, 0.18, 1.98, -0.12);
}
[
[-10.7, -4.6, 1.0],
[-6.7, 4.8, 0.85],
[-1.8, 4.8, 1.05],
[3.5, -4.9, 0.9],
[10.6, -4.4, 1.05],
[10.6, 4.5, 0.9]
].forEach(([x, z, s]) => addTree(x, z, s));
// -------------------------------------------------------------------------
// Lane barriers and drag targets
// -------------------------------------------------------------------------
const barriers = [];
const targetPads = [];
const targetHits = [];
routeDefs.forEach((route, index) => {
const barrier = new THREE.Group();
const barrierPosition = routePoint(index, routeData[index].barrierFraction);
barrier.position.copy(barrierPosition);
barrier.position.y = 0;
addBox(barrier, 0.18, 0.92, 0.18, 0x5d665c, 0, 0.46, -0.7);
addBox(barrier, 0.18, 0.92, 0.18, 0x5d665c, 0, 0.46, 0.7);
addBox(barrier, 0.18, 0.3, 1.55, 0xf0a23f, 0, 0.7, 0);
for (let stripe = -2; stripe <= 2; stripe++) {
const stripeMesh = addBox(
barrier,
0.205,
0.18,
0.18,
0x5b5144,
0,
0.71,
stripe * 0.29
);
stripeMesh.rotation.x = -0.45;
}
barrier.traverse((child) => {
child.userData.routeIndex = index;
});
barrier.visible = false;
world.add(barrier);
barriers.push(barrier);
const padPosition = routePoint(index, 0.24);
const pad = new THREE.Group();
pad.position.set(padPosition.x, 0.13, padPosition.z);
world.add(pad);
const padMaterial = new THREE.MeshBasicMaterial({
color: route.color,
transparent: true,
opacity: 0.8,
depthWrite: false
});
addBox(pad, 1.0, 0.06, 0.12, padMaterial, 0, 0, -0.5, false);
addBox(pad, 1.0, 0.06, 0.12, padMaterial, 0, 0, 0.5, false);
addBox(pad, 0.12, 0.06, 1.0, padMaterial, -0.5, 0, 0, false);
addBox(pad, 0.12, 0.06, 1.0, padMaterial, 0.5, 0, 0, false);
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
const hit = addBox(pad, 1.25, 0.35, 1.25, hitMaterial, 0, 0.16, 0, false);
hit.userData.routeIndex = index;
targetPads.push({ group: pad, material: padMaterial });
targetHits.push(hit);
});
// -------------------------------------------------------------------------
// World labels
// -------------------------------------------------------------------------
const labels = [];
function addWorldLabel(text, position, routeIndex = null) {
const element = document.createElement("div");
element.className = routeIndex === null ? "world-label" : "world-label route-label";
element.textContent = text;
if (routeIndex !== null) {
element.style.setProperty("--route", routeDefs[routeIndex].css);
}
document.querySelector("#labels").appendChild(element);
labels.push({ element, position });
}
addWorldLabel("Deep well", new THREE.Vector3(-9, 2.25, 0));
addWorldLabel("Relay fork", new THREE.Vector3(-5.4, 1.25, 0));
addWorldLabel("Lily relay", new THREE.Vector3(-2.5, 1.55, -3.2), 0);
addWorldLabel("Reed relay", new THREE.Vector3(-2.5, 1.55, 0), 1);
addWorldLabel("Moss relay", new THREE.Vector3(-2.5, 1.55, 3.2), 2);
addWorldLabel("Merge", new THREE.Vector3(4.7, 1.25, 0));
addWorldLabel("Homes", new THREE.Vector3(9.1, 2.25, 0));
// -------------------------------------------------------------------------
// Simulation state
// -------------------------------------------------------------------------
let buckets = [];
let bucketGroups = [];
let sourceQueue = [];
let blocked = [false, false, false];
let nextBucketId = 1;
let routeCursor = 0;
let simulationTime = 0;
let productionTimer = 0;
let dispatchTimer = 0;
let deliveredCount = 0;
let responseTimes = [];
let deliveryTimes = [];
let history = [];
let historyTimer = 0;
let previousHistoryDeliveries = 0;
let policy = "cycle";
let simulationSpeed = 1;
let paused = false;
const events = [];
function logEvent(message, type = "info") {
events.unshift({ message, type });
if (events.length > 5) events.pop();
renderEvents();
}
function renderEvents() {
document.querySelector("#eventList").innerHTML = events
.map(
(event) =>
`<div class="event ${event.type}">${event.message}</div>`
)
.join("");
}
function createBucketVisual(bucket) {
const group = new THREE.Group();
group.userData.bucketId = bucket.id;
const bodyMaterial = new THREE.MeshStandardMaterial({
color: routeDefs[bucket.route].color,
roughness: 0.7,
emissive: 0x000000,
emissiveIntensity: 0
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x315b55,
roughness: 0.82
});
const woodMaterial = new THREE.MeshStandardMaterial({
color: 0x8b6847,
roughness: 0.9
});
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x55c4dd,
roughness: 0.24,
metalness: 0.05,
transparent: true,
opacity: 0.94
});
addBox(group, 0.54, 0.22, 0.54, bodyMaterial, 0, 0.37, 0);
addBox(group, 0.62, 0.26, 0.62, bodyMaterial, 0, 0.6, 0);
addBox(group, 0.7, 0.09, 0.7, bodyMaterial, 0, 0.76, 0);
addBox(group, 0.56, 0.045, 0.56, waterMaterial, 0, 0.815, 0);
addBox(group, 0.07, 0.58, 0.07, darkMaterial, -0.34, 0.95, 0);
addBox(group, 0.07, 0.58, 0.07, darkMaterial, 0.34, 0.95, 0);
addBox(group, 0.75, 0.07, 0.07, darkMaterial, 0, 1.23, 0);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0xffa536,
transparent: true,
opacity: 0.9,
depthWrite: false
});
const warningRing = new THREE.Group();
warningRing.position.y = -0.42;
addBox(warningRing, 0.95, 0.035, 0.1, ringMaterial, 0, 0, -0.45, false);
addBox(warningRing, 0.95, 0.035, 0.1, ringMaterial, 0, 0, 0.45, false);
addBox(warningRing, 0.1, 0.035, 0.95, ringMaterial, -0.45, 0, 0, false);
addBox(warningRing, 0.1, 0.035, 0.95, ringMaterial, 0.45, 0, 0, false);
warningRing.visible = false;
group.add(warningRing);
// Small canvas number tag.
const numberCanvas = document.createElement("canvas");
numberCanvas.width = 128;
numberCanvas.height = 64;
const context = numberCanvas.getContext("2d");
context.fillStyle = "rgba(250,252,246,0.94)";
context.fillRect(12, 8, 104, 48);
context.fillStyle = "#173630";
context.font = "bold 29px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(`#${bucket.id}`, 64, 33);
const numberTexture = new THREE.CanvasTexture(numberCanvas);
numberTexture.colorSpace = THREE.SRGBColorSpace;
const numberSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: numberTexture,
transparent: true,
depthWrite: false
})
);
numberSprite.position.set(0, 1.65, 0);
numberSprite.scale.set(0.75, 0.375, 1);
group.add(numberSprite);
bucket.group = group;
bucket.bodyMaterial = bodyMaterial;
bucket.waterMesh = group.children.find(
(child) => child.material === waterMaterial
);
bucket.warningRing = warningRing;
scene.add(group);
bucketGroups.push(group);
return group;
}
function chooseRoute() {
if (policy === "auto") {
const openRoutes = routeDefs
.map((_, index) => index)
.filter((index) => !blocked[index]);
if (openRoutes.length) {
return openRoutes.reduce((best, index) => {
const pressure = buckets.filter(
(bucket) => bucket.route === index
).length + buckets.filter(
(bucket) => bucket.route === index && bucket.waiting
).length * 2;
const bestPressure = buckets.filter(
(bucket) => bucket.route === best
).length + buckets.filter(
(bucket) => bucket.route === best && bucket.waiting
).length * 2;
return pressure < bestPressure ? index : best;
}, openRoutes[0]);
}
}
const selected = routeCursor % routeDefs.length;
routeCursor++;
return selected;
}
function createBucket(routeIndex = chooseRoute(), options = {}) {
const bucket = {
id: nextBucketId++,
route: routeIndex,
phase: options.phase ?? "source",
progress: options.progress ?? 0,
createdAt: simulationTime,
waiting: options.waiting ?? false,
waitStarted: options.waiting ? simulationTime : null,
handoff: null
};
buckets.push(bucket);
createBucketVisual(bucket);
if (bucket.phase === "source") sourceQueue.push(bucket.id);
return bucket;
}
function dispatchSourceBucket() {
if (!sourceQueue.length) return;
const id = sourceQueue.shift();
const bucket = buckets.find((item) => item.id === id);
if (!bucket) return;
bucket.phase = "approach";
bucket.progress = 0;
}
function removeBucketMesh(bucket) {
bucket.group.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
if (child.material.map) child.material.map.dispose();
child.material.dispose();
}
});
scene.remove(bucket.group);
const groupIndex = bucketGroups.indexOf(bucket.group);
if (groupIndex !== -1) bucketGroups.splice(groupIndex, 1);
}
function completeBucket(bucket) {
const responseTime = simulationTime - bucket.createdAt;
responseTimes.push(responseTime);
deliveryTimes.push(simulationTime);
deliveredCount++;
removeBucketMesh(bucket);
buckets = buckets.filter((item) => item.id !== bucket.id);
}
function setBucketWaiting(bucket, waiting) {
if (waiting === bucket.waiting) return;
bucket.waiting = waiting;
bucket.waitStarted = waiting ? simulationTime : null;
if (waiting) {
logEvent(
`#${bucket.id} stranded at the ${routeDefs[bucket.route].name} checkpoint.`,
"warn"
);
} else {
logEvent(
`${routeDefs[bucket.route].name} reopened; #${bucket.id} is moving.`,
"info"
);
}
}
function startHandoff(bucket, targetRoute) {
bucket.handoff = {
elapsed: 0,
targetRoute,
start: bucket.group.position.clone(),
end: routePoint(targetRoute, 0.025)
};
bucket.phase = "handoff";
bucket.waiting = false;
bucket.waitStarted = null;
logEvent(
`#${bucket.id} transferred from ${routeDefs[bucket.route].name} to ${routeDefs[targetRoute].name}.`
);
}
function updateSimulation(dt) {
simulationTime += dt;
productionTimer += dt;
dispatchTimer += dt;
historyTimer += dt;
while (productionTimer >= PRODUCTION_INTERVAL) {
productionTimer -= PRODUCTION_INTERVAL;
createBucket();
if (sourceQueue.length > 7) {
logEvent("The well queue is overflowing.", "warn");
}
}
while (dispatchTimer >= SOURCE_DISPATCH_INTERVAL) {
dispatchTimer -= SOURCE_DISPATCH_INTERVAL;
dispatchSourceBucket();
}
for (const bucket of [...buckets]) {
if (bucket.phase === "source") continue;
if (bucket.phase === "approach") {
bucket.progress += dt / APPROACH_DURATION;
if (bucket.progress >= 1) {
bucket.progress = 0;
bucket.phase = "lane";
}
continue;
}
if (bucket.phase === "handoff") {
bucket.handoff.elapsed += dt;
const t = Math.min(bucket.handoff.elapsed / DRAG_HANDOFF_DURATION, 1);
const eased = t * t * (3 - 2 * t);
bucket.group.position.lerpVectors(
bucket.handoff.start,
bucket.handoff.end,
eased
);
bucket.group.position.y += Math.sin(Math.PI * t) * 1.55;
bucket.group.rotation.y += dt * 5;
if (t >= 1) {
bucket.route = bucket.handoff.targetRoute;
bucket.phase = "lane";
bucket.progress = 0.005;
bucket.handoff = null;
bucket.bodyMaterial.color.setHex(routeDefs[bucket.route].color);
bucket.bodyMaterial.emissive.setHex(0x000000);
bucket.bodyMaterial.emissiveIntensity = 0;
}
continue;
}
if (bucket.phase === "lane") {
const barrierFraction = routeData[bucket.route].barrierFraction;
if (bucket.waiting) {
if (!blocked[bucket.route]) {
setBucketWaiting(bucket, false);
} else {
continue;
}
}
const oldProgress = bucket.progress;
bucket.progress += (dt * LANE_SPEED) / routeData[bucket.route].total;
if (
blocked[bucket.route] &&
oldProgress < barrierFraction &&
bucket.progress >= barrierFraction
) {
bucket.progress = barrierFraction - 0.014;
setBucketWaiting(bucket, true);
}
if (bucket.progress >= 1) completeBucket(bucket);
}
}
if (historyTimer >= 1) {
historyTimer -= 1;
history.push({
deliveries: deliveredCount - previousHistoryDeliveries,
waiting: buckets.filter((bucket) => bucket.waiting).length
});
previousHistoryDeliveries = deliveredCount;
if (history.length > 40) history.shift();
}
}
// -------------------------------------------------------------------------
// Visual transforms
// -------------------------------------------------------------------------
const sourceStart = new THREE.Vector3(-9, 0.56, 0);
const forkPoint = new THREE.Vector3(-5.4, 0.56, 0);
const temporaryPoint = new THREE.Vector3();
function updateBucketTransforms() {
sourceQueue.forEach((id, queueIndex) => {
const bucket = buckets.find((item) => item.id === id);
if (!bucket) return;
const row = Math.floor(queueIndex / 4);
const column = queueIndex % 4;
bucket.group.position.set(
-10.2 - row * 0.2,
1.0 + row * 0.6,
-1.05 + column * 0.7
);
});
for (const bucket of buckets) {
if (bucket.phase === "approach") {
const t = THREE.MathUtils.clamp(bucket.progress, 0, 1);
temporaryPoint.lerpVectors(sourceStart, forkPoint, t);
temporaryPoint.z += ((bucket.id % 3) - 1) * 0.11;
bucket.group.position.copy(temporaryPoint);
} else if (bucket.phase === "lane") {
routePoint(bucket.route, bucket.progress, temporaryPoint);
if (bucket.waiting) {
const offset = ((bucket.id % 3) - 1) * 0.12;
temporaryPoint.z += offset;
temporaryPoint.y -= 0.015;
}
bucket.group.position.copy(temporaryPoint);
}
bucket.warningRing.visible = bucket.waiting;
bucket.bodyMaterial.emissive.setHex(bucket.waiting ? 0x6b3510 : 0x000000);
bucket.bodyMaterial.emissiveIntensity = bucket.waiting ? 0.3 : 0;
if (bucket.waterMesh) {
bucket.waterMesh.position.y =
0.815 + Math.sin(simulationTime * 4 + bucket.id) * 0.014;
}
}
}
function updateTargetPads() {
targetPads.forEach((pad, index) => {
const blockedTarget = blocked[index];
const highlighted = dragState.targetRoute === index;
pad.material.opacity = blockedTarget ? 0.16 : highlighted ? 1 : 0.68;
pad.material.color.setHex(
highlighted ? 0xffb044 : routeDefs[index].color
);
const pulse = highlighted ? 1.08 + Math.sin(simulationTime * 8) * 0.08 : 1;
pad.group.scale.setScalar(pulse);
});
}
// -------------------------------------------------------------------------
// Controls panel
// -------------------------------------------------------------------------
const routeRows = document.querySelector("#routeRows");
routeRows.innerHTML = routeDefs
.map(
(route, index) => `
<div class="route-row" id="route-row-${index}" style="--route:${route.css}">
<span class="route-dot"></span>
<div class="route-copy">
<b>${route.name}</b>
<small id="route-detail-${index}">0 buckets · clear</small>
</div>
<button class="block-button" id="block-${index}" aria-label="Toggle ${route.name} blockage">
Block
</button>
</div>
`
)
.join("");
routeDefs.forEach((route, index) => {
document.querySelector(`#block-${index}`).addEventListener("click", () => {
toggleBlockage(index);
});
});
function toggleBlockage(index) {
blocked[index] = !blocked[index];
barriers[index].visible = blocked[index];
if (blocked[index]) {
const affected = buckets.filter(
(bucket) => bucket.route === index
).length;
logEvent(
`${routeDefs[index].name} blocked${affected ? `; ${affected} bucket${affected === 1 ? "" : "s"} affected` : ""}.`,
"warn"
);
showToast(
`${routeDefs[index].name} is blocked. Drag amber buckets to an open pad.`
);
} else {
logEvent(`${routeDefs[index].name} reopened.`, "info");
showToast(`${routeDefs[index].name} is open again.`);
}
updateUI();
}
document.querySelector("#policy").addEventListener("change", (event) => {
policy = event.target.value;
logEvent(
policy === "auto"
? "Auto-clear routing enabled for new buckets."
: "Round-robin routing enabled for new buckets.",
"info"
);
});
document.querySelectorAll("[data-speed]").forEach((button) => {
button.addEventListener("click", () => {
simulationSpeed = Number(button.dataset.speed);
document.querySelectorAll("[data-speed]").forEach((item) => {
item.classList.toggle("active", item === button);
});
});
});
document.querySelector("#pause").addEventListener("click", () => {
paused = !paused;
document.querySelector("#pause").classList.toggle("active", paused);
document.querySelector("#pause").textContent = paused ? "▶" : "Ⅱ";
});
document.querySelector("#reset").addEventListener("click", resetScenario);
let toastTimer;
function showToast(message) {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 3200);
}
function formatClock(seconds) {
const minutes = Math.floor(seconds / 60);
const remainder = Math.floor(seconds % 60);
return `${String(minutes).padStart(2, "0")}:${String(remainder).padStart(2, "0")}`;
}
function updateUI() {
const waiting = buckets.filter((bucket) => bucket.waiting).length;
const queued = waiting + sourceQueue.length;
const recentDeliveries = deliveryTimes.filter(
(time) => simulationTime - time <= 20
).length;
const averageResponse = responseTimes.length
? responseTimes.reduce((sum, time) => sum + time, 0) /
responseTimes.length
: null;
document.querySelector("#delivered").textContent = deliveredCount;
document.querySelector("#queued").textContent = queued;
document.querySelector("#flow").textContent = recentDeliveries * 3;
document.querySelector("#response").textContent = averageResponse === null
? "—"
: `${averageResponse.toFixed(1)}s`;
document.querySelector("#clock").textContent = formatClock(simulationTime);
const status = document.querySelector("#systemStatus");
const allBlocked = blocked.every(Boolean);
if (allBlocked) {
status.textContent = "Halted";
status.className = "status-pill danger";
} else if (waiting > 0) {
status.textContent = "Bottleneck";
status.className = "status-pill warn";
} else {
status.textContent = "Flowing";
status.className = "status-pill";
}
routeDefs.forEach((route, index) => {
const routeBuckets = buckets.filter(
(bucket) => bucket.route === index
).length;
const routeWaiting = buckets.filter(
(bucket) => bucket.route === index && bucket.waiting
).length;
const row = document.querySelector(`#route-row-${index}`);
const button = document.querySelector(`#block-${index}`);
row.classList.toggle("blocked", blocked[index]);
button.classList.toggle("active", blocked[index]);
button.textContent = blocked[index] ? "Reopen" : "Block";
document.querySelector(`#route-detail-${index}`).textContent = blocked[index]
? `${routeWaiting} waiting · ${routeBuckets} assigned`
: `${routeBuckets} buckets · clear`;
});
}
// -------------------------------------------------------------------------
// Dragging and custom camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.56);
const planeIntersection = new THREE.Vector3();
const dragState = {
bucket: null,
targetRoute: null,
moved: false
};
const orbitState = {
active: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false
};
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function findBucketAncestor(object) {
let current = object;
while (current) {
if (current.userData && current.userData.bucketId) return current;
current = current.parent;
}
return null;
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
updatePointer(event);
const bucketHits = raycaster.intersectObjects(bucketGroups, true);
if (bucketHits.length) {
const group = findBucketAncestor(bucketHits[0].object);
const bucket = buckets.find((item) => item.group === group);
if (bucket?.waiting) {
dragState.bucket = bucket;
dragState.targetRoute = null;
dragState.moved = false;
canvas.setPointerCapture(event.pointerId);
showToast("Choose a glowing open-lane pad.");
return;
}
}
orbitState.active = true;
orbitState.startX = event.clientX;
orbitState.startY = event.clientY;
orbitState.lastX = event.clientX;
orbitState.lastY = event.clientY;
orbitState.moved = false;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (dragState.bucket) {
dragState.moved = true;
updatePointer(event);
if (raycaster.ray.intersectPlane(dragPlane, planeIntersection)) {
dragState.bucket.group.position.copy(planeIntersection);
dragState.bucket.group.position.y += 0.12;
}
const padIntersections = raycaster.intersectObjects(targetHits, false);
dragState.targetRoute = null;
if (padIntersections.length) {
const routeIndex = padIntersections[0].object.userData.routeIndex;
if (!blocked[routeIndex]) dragState.targetRoute = routeIndex;
}
updateTargetPads();
return;
}
if (!orbitState.active) return;
const dx = event.clientX - orbitState.lastX;
const dy = event.clientY - orbitState.lastY;
orbitState.lastX = event.clientX;
orbitState.lastY = event.clientY;
if (
Math.abs(event.clientX - orbitState.startX) +
Math.abs(event.clientY - orbitState.startY) >
3
) {
orbitState.moved = true;
}
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.38,
1.23
);
});
canvas.addEventListener("pointerup", (event) => {
if (dragState.bucket) {
const bucket = dragState.bucket;
const targetRoute = dragState.targetRoute;
if (targetRoute !== null && targetRoute !== bucket.route) {
startHandoff(bucket, targetRoute);
} else {
updateBucketTransforms();
if (dragState.moved) showToast("Drop it on a glowing open-lane pad.");
}
dragState.bucket = null;
dragState.targetRoute = null;
updateTargetPads();
} else if (orbitState.active && !orbitState.moved) {
updatePointer(event);
const barrierHits = raycaster.intersectObjects(barriers, true);
if (barrierHits.length) {
const routeIndex = barrierHits[0].object.userData.routeIndex;
toggleBlockage(routeIndex);
}
}
orbitState.active = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointercancel", () => {
if (dragState.bucket) updateBucketTransforms();
dragState.bucket = null;
dragState.targetRoute = null;
orbitState.active = false;
updateTargetPads();
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.72,
1.7
);
},
{ passive: false }
);
function updateCamera() {
const radius = 25;
const horizontal = radius * Math.cos(cameraState.pitch);
const vertical = radius * Math.sin(cameraState.pitch);
camera.position.set(
cameraTarget.x + Math.sin(cameraState.yaw) * horizontal,
cameraTarget.y + vertical,
cameraTarget.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
const aspect = width / height;
const halfWidth = 12.7 / cameraState.zoom;
camera.left = -halfWidth;
camera.right = halfWidth;
camera.top = halfWidth / aspect;
camera.bottom = -halfWidth / aspect;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
// -------------------------------------------------------------------------
// Chart
// -------------------------------------------------------------------------
const chart = document.querySelector("#chart");
const chartContext = chart.getContext("2d");
function drawChart() {
const rect = chart.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const width = rect.width;
const height = rect.height;
chart.width = Math.round(width * dpr);
chart.height = Math.round(height * dpr);
chartContext.setTransform(dpr, 0, 0, dpr, 0, 0);
chartContext.clearRect(0, 0, width, height);
const padding = { left: 7, right: 7, top: 13, bottom: 8 };
const chartWidth = width - padding.left - padding.right;
const chartHeight = height - padding.top - padding.bottom;
chartContext.strokeStyle = "rgba(23,54,48,0.07)";
chartContext.lineWidth = 1;
for (let line = 0; line < 4; line++) {
const y = padding.top + (chartHeight / 3) * line;
chartContext.beginPath();
chartContext.moveTo(padding.left, y);
chartContext.lineTo(width - padding.right, y);
chartContext.stroke();
}
if (!history.length) return;
const maxWaiting = Math.max(
4,
...history.map((item) => item.waiting)
);
const maxDeliveries = Math.max(
2,
...history.map((item) => item.deliveries)
);
const count = history.length;
const xAt = (index) =>
padding.left +
(count === 1 ? chartWidth / 2 : (index / (count - 1)) * chartWidth);
history.forEach((item, index) => {
const barWidth = Math.max(2, chartWidth / Math.max(count, 1) - 2);
const barHeight =
(item.deliveries / maxDeliveries) * chartHeight * 0.7;
const x = xAt(index) - barWidth / 2;
const y = padding.top + chartHeight - barHeight;
chartContext.fillStyle = "rgba(21,157,138,0.64)";
chartContext.fillRect(x, y, barWidth, barHeight);
});
chartContext.beginPath();
history.forEach((item, index) => {
const x = xAt(index);
const y =
padding.top +
chartHeight -
(item.waiting / maxWaiting) * chartHeight;
if (index === 0) chartContext.moveTo(x, y);
else chartContext.lineTo(x, y);
});
chartContext.strokeStyle = "#ee9b39";
chartContext.lineWidth = 2;
chartContext.stroke();
const last = history[history.length - 1];
const lastY =
padding.top +
chartHeight -
(last.waiting / maxWaiting) * chartHeight;
chartContext.beginPath();
chartContext.arc(xAt(count - 1), lastY, 3, 0, Math.PI * 2);
chartContext.fillStyle = "#ee9b39";
chartContext.fill();
}
// -------------------------------------------------------------------------
// Reset / initial scenario
// -------------------------------------------------------------------------
function resetScenario() {
buckets.forEach(removeBucketMesh);
buckets = [];
bucketGroups = [];
sourceQueue = [];
blocked = [false, false, false];
barriers.forEach((barrier) => (barrier.visible = false));
nextBucketId = 1;
routeCursor = 1;
simulationTime = 0;
productionTimer = 1.1;
dispatchTimer = 0;
deliveredCount = 0;
responseTimes = [];
deliveryTimes = [];
history = [];
historyTimer = 0;
previousHistoryDeliveries = 0;
events.length = 0;
// The scenario begins with one blocked lane and one stranded bucket.
blocked[0] = true;
barriers[0].visible = true;
createBucket(0, {
phase: "lane",
progress: routeData[0].barrierFraction - 0.014,
waiting: true
});
createBucket(0, {
phase: "lane",
progress: 0.16
});
createBucket(1, {
phase: "lane",
progress: 0.29
});
createBucket(2, {
phase: "approach",
progress: 0.55
});
logEvent("Lily lane blocked for the emergency drill.", "warn");
logEvent("Bucket #1 is stranded and ready to transfer.", "warn");
updateBucketTransforms();
updateUI();
drawChart();
showToast("Drag amber bucket #1 onto an open-lane pad.");
}
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
let previousTime = performance.now();
let uiTimer = 0;
function animate(now) {
requestAnimationFrame(animate);
const realDelta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!paused) {
updateSimulation(realDelta * simulationSpeed);
}
updateBucketTransforms();
updateTargetPads();
updateCamera();
renderer.render(scene, camera);
labels.forEach((label) => {
projected.copy(label.position).project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
label.element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
label.element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
});
uiTimer += realDelta;
if (uiTimer >= 0.2) {
uiTimer = 0;
updateUI();
drawChart();
}
}
resetScenario();
requestAnimationFrame(animate);
</script>
</body>
</html>
```