Prompt specification
Build or customize the Three.js 3D scene "Toy Factory Buffer Placement" 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: Toy Factory Buffer Placement
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/toy-factory-buffer-placement-x3183
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts production bottlenecks and queues. Build a compact assembly line with intermediate storage bins. Compare buffer locations while keeping operation durations fixed and display starvation, waiting, and finished-unit counts. Voxel style.
Working Three.js Starter (toy-factory-buffer-placement-x3183):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Buffer Placement Lab</title>
<style>
:root {
--bg: #080d13;
--panel: #101720;
--panel-2: #151e28;
--line: #263342;
--text: #edf4fb;
--muted: #8d9aaa;
--cyan: #55d6d0;
--blue: #65a9ff;
--green: #62dd8b;
--amber: #ffbf4b;
--red: #ff6b66;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
width: 100%;
height: 100dvh;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 40%, rgba(38, 67, 91, 0.18), transparent 55%),
#090e15;
}
#canvasHost {
position: absolute;
inset: 0;
}
#canvasHost canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
outline: none;
}
#canvasHost canvas:active {
cursor: grabbing;
}
.stage-heading {
position: absolute;
top: 24px;
left: 26px;
z-index: 3;
pointer-events: none;
}
.stage-heading .eyebrow {
color: var(--cyan);
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.stage-heading h2 {
margin: 7px 0 0;
font-size: clamp(22px, 3vw, 34px);
letter-spacing: -0.04em;
}
.stage-heading p {
margin: 7px 0 0;
color: var(--muted);
font-size: 13px;
}
.legend {
position: absolute;
top: 24px;
right: 22px;
z-index: 3;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
max-width: 380px;
pointer-events: none;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 7px;
background: rgba(11, 17, 24, 0.74);
backdrop-filter: blur(8px);
color: #b9c6d4;
font-size: 11px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: currentColor;
box-shadow: 0 0 9px currentColor;
}
.dot.green { color: var(--green); }
.dot.amber { color: var(--amber); }
.dot.red { color: var(--red); }
.dot.cyan { color: var(--cyan); }
.view-hint {
position: absolute;
left: 24px;
bottom: 22px;
z-index: 3;
padding: 8px 11px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
background: rgba(8, 13, 19, 0.72);
color: var(--muted);
font-size: 11px;
pointer-events: none;
}
#resetView {
position: absolute;
right: 22px;
bottom: 22px;
z-index: 4;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(18, 27, 37, 0.9);
color: var(--text);
cursor: pointer;
}
#resetView:hover {
border-color: var(--cyan);
}
aside {
position: relative;
z-index: 5;
min-height: 0;
overflow: auto;
padding: 24px 20px 28px;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(26, 38, 51, 0.4), transparent 190px),
var(--panel);
scrollbar-color: #344558 transparent;
}
aside header {
margin-bottom: 20px;
}
aside .eyebrow {
color: var(--cyan);
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
aside h1 {
margin: 7px 0 8px;
font-size: 25px;
line-height: 1.08;
letter-spacing: -0.045em;
}
aside header p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin: 21px 0 10px;
color: #a8b5c3;
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-label span:last-child {
color: #647487;
font-weight: 500;
letter-spacing: 0.03em;
text-transform: none;
}
.scenario-card {
position: relative;
margin-bottom: 12px;
padding: 15px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 12px;
background: linear-gradient(145deg, rgba(255, 255, 255, 0.035), transparent);
transition: border-color 160ms ease, transform 160ms ease;
}
.scenario-card::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 3px;
height: 100%;
background: var(--accent);
}
.scenario-card.leader {
border-color: color-mix(in srgb, var(--accent) 65%, #263342);
transform: translateX(-2px);
}
.card-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
}
.card-title h3 {
margin: 4px 0 0;
font-size: 15px;
letter-spacing: -0.02em;
}
.scenario-tag {
flex: none;
padding: 5px 7px;
border: 1px solid color-mix(in srgb, var(--accent) 45%, transparent);
border-radius: 5px;
color: var(--accent);
background: color-mix(in srgb, var(--accent) 9%, transparent);
font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
}
.card-description {
min-height: 34px;
margin: 9px 0 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 7px;
}
.metric {
min-width: 0;
padding: 10px 8px 9px;
border: 1px solid rgba(255, 255, 255, 0.065);
border-radius: 8px;
background: rgba(3, 7, 11, 0.28);
}
.metric span {
display: block;
overflow: hidden;
color: var(--muted);
font-size: 9px;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric strong {
display: block;
margin-top: 4px;
color: var(--text);
font: 750 19px/1.1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: -0.05em;
}
.metric small {
color: #647487;
font-size: 9px;
}
.card-footer {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 10px;
color: #8391a1;
font-size: 10px;
}
.card-footer b {
color: #c8d4df;
font-weight: 650;
}
.utilization {
height: 3px;
margin-top: 10px;
overflow: hidden;
border-radius: 3px;
background: #202b37;
}
.utilization > div {
width: 0;
height: 100%;
background: var(--accent);
transition: width 180ms linear;
}
.comparison {
padding: 12px 13px;
border: 1px solid rgba(85, 214, 208, 0.2);
border-radius: 9px;
background: rgba(85, 214, 208, 0.055);
color: #c2d7d9;
font-size: 11px;
line-height: 1.5;
}
.comparison strong {
color: var(--cyan);
}
.controls {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
}
.control-button {
min-height: 40px;
padding: 0 14px;
border: 1px solid var(--line);
border-radius: 8px;
background: #19232e;
color: var(--text);
font-weight: 700;
cursor: pointer;
}
.control-button:hover {
border-color: #53677a;
}
.control-button.primary {
border-color: rgba(85, 214, 208, 0.45);
background: rgba(85, 214, 208, 0.11);
color: #8ce9e4;
}
.speed-group {
display: flex;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 8px;
}
.speed-group button {
min-width: 40px;
border: 0;
border-right: 1px solid var(--line);
background: #131b24;
color: var(--muted);
cursor: pointer;
}
.speed-group button:last-child {
border-right: 0;
}
.speed-group button.active {
background: #263748;
color: var(--cyan);
font-weight: 800;
}
.duration-list {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 7px;
}
.duration-item {
display: flex;
justify-content: space-between;
gap: 8px;
padding: 9px 10px;
border: 1px solid rgba(255, 255, 255, 0.065);
border-radius: 7px;
background: rgba(3, 7, 11, 0.22);
color: #a9b6c4;
font-size: 10px;
}
.duration-item b {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.duration-item.bottleneck {
border-color: rgba(255, 107, 102, 0.25);
}
.duration-item.bottleneck b {
color: var(--red);
}
.fixed-note {
margin: 9px 0 0;
color: #718092;
font-size: 10px;
line-height: 1.5;
}
.clock-row {
display: flex;
justify-content: space-between;
margin-top: 18px;
padding-top: 14px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
}
#clock {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
@media (max-width: 900px) {
html,
body {
overflow: auto;
}
#app {
grid-template-columns: 1fr;
grid-template-rows: 58dvh 42dvh;
height: auto;
min-height: 100dvh;
}
aside {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.legend {
display: none;
}
}
@media (max-width: 520px) {
#app {
grid-template-rows: 52dvh auto;
}
.stage-heading {
top: 16px;
left: 16px;
}
.stage-heading p {
display: none;
}
.view-hint {
left: 14px;
bottom: 14px;
}
#resetView {
right: 14px;
bottom: 14px;
}
aside {
padding: 20px 14px 28px;
}
}
</style>
</head>
<body>
<div id="app">
<main id="stage">
<div id="canvasHost"></div>
<div class="stage-heading">
<div class="eyebrow">Flow systems / live comparison</div>
<h2>Where should the buffer live?</h2>
<p>Identical machines. Identical cycle times. One movable storage bin.</p>
</div>
<div class="legend">
<span><i class="dot green"></i>Processing</span>
<span><i class="dot amber"></i>Starved</span>
<span><i class="dot red"></i>Blocked</span>
<span><i class="dot cyan"></i>Queued units</span>
</div>
<div class="view-hint">Drag to orbit · Scroll or pinch to zoom</div>
<button id="resetView" type="button">Reset view</button>
</main>
<aside>
<header>
<div class="eyebrow">Three.js / voxel production study</div>
<h1>Buffer Placement Lab</h1>
<p>
Two synchronized assembly lines compare a four-unit bin before or
after the slow operation. All operation durations remain fixed.
</p>
</header>
<div class="section-label">
<span>Live scenarios</span>
<span>elapsed time</span>
</div>
<section class="scenario-card" id="beforeCard" style="--accent: var(--cyan)">
<div class="card-title">
<div>
<div class="eyebrow" style="color: var(--muted)">Scenario A</div>
<h3>Buffer before bottleneck</h3>
</div>
<div class="scenario-tag">BEFORE</div>
</div>
<p class="card-description">
The bin sits between Form and Bottleneck, changing where upstream
backpressure accumulates.
</p>
<div class="metrics">
<div class="metric" title="Cumulative idle-input episodes across all stations">
<span>Starvation</span>
<strong id="beforeStarved">0</strong>
<small>events</small>
</div>
<div class="metric">
<span>Waiting</span>
<strong id="beforeWaiting">0</strong>
<small>units</small>
</div>
<div class="metric">
<span>Finished</span>
<strong id="beforeFinished">0</strong>
<small>units</small>
</div>
</div>
<div class="card-footer">
<span>Buffer <b id="beforeBuffer">0 / 4</b></span>
<span>Bottleneck blocked <b id="beforeBlocked">0.0s</b></span>
</div>
<div class="utilization"><div id="beforeUtil"></div></div>
</section>
<section class="scenario-card" id="afterCard" style="--accent: var(--blue)">
<div class="card-title">
<div>
<div class="eyebrow" style="color: var(--muted)">Scenario B</div>
<h3>Buffer after bottleneck</h3>
</div>
<div class="scenario-tag">AFTER</div>
</div>
<p class="card-description">
The bin sits between Bottleneck and Pack, protecting the slow station
from downstream blocking.
</p>
<div class="metrics">
<div class="metric" title="Cumulative idle-input episodes across all stations">
<span>Starvation</span>
<strong id="afterStarved">0</strong>
<small>events</small>
</div>
<div class="metric">
<span>Waiting</span>
<strong id="afterWaiting">0</strong>
<small>units</small>
</div>
<div class="metric">
<span>Finished</span>
<strong id="afterFinished">0</strong>
<small>units</small>
</div>
</div>
<div class="card-footer">
<span>Buffer <b id="afterBuffer">0 / 4</b></span>
<span>Bottleneck blocked <b id="afterBlocked">0.0s</b></span>
</div>
<div class="utilization"><div id="afterUtil"></div></div>
</section>
<div class="comparison" id="comparison" aria-live="polite">
<strong>Comparison:</strong> Let the line run to compare throughput,
starvation, and queue placement.
</div>
<div class="section-label">
<span>Simulation controls</span>
<span id="runState">running</span>
</div>
<div class="controls">
<button class="control-button primary" id="playPause" type="button">
Pause
</button>
<button class="control-button" id="reset" type="button">Reset</button>
<div class="speed-group" aria-label="Simulation speed">
<button class="active" data-speed="1" type="button">1×</button>
<button data-speed="2" type="button">2×</button>
<button data-speed="4" type="button">4×</button>
</div>
</div>
<div class="section-label">
<span>Fixed operation times</span>
<span>same in both runs</span>
</div>
<div class="duration-list">
<div class="duration-item"><span>Load</span><b>1.0s</b></div>
<div class="duration-item"><span>Form</span><b>1.4s</b></div>
<div class="duration-item bottleneck"><span>Bottleneck</span><b>3.2s</b></div>
<div class="duration-item"><span>Pack</span><b>1.2s</b></div>
<div class="duration-item"><span>Source</span><b>1.15s</b></div>
<div class="duration-item"><span>Bin capacity</span><b>4 units</b></div>
</div>
<p class="fixed-note">
Starvation counts idle-input episodes. Waiting includes queued units,
blocked outputs, and units still waiting at the source.
</p>
<div class="clock-row">
<span>Simulation clock</span>
<span id="clock">00:00.0</span>
</div>
</aside>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Shared constants and scenarios
// -------------------------------------------------------------------------
const COLORS = {
background: 0x090e15,
floor: 0x101923,
platform: 0x15212c,
belt: 0x1d2935,
beltEdge: 0x344554,
machine: 0x617488,
machineDark: 0x273542,
cyan: 0x55d6d0,
blue: 0x65a9ff,
green: 0x62dd8b,
amber: 0xffbf4b,
red: 0xff6b66,
purple: 0xa78bfa,
unit: 0xe9f4ff
};
const FIXED_DT = 1 / 60;
const ARRIVAL_INTERVAL = 1.15;
const BUFFER_CAPACITY = 4;
const STATION_QUEUE_CAPACITY = 3;
const configurations = [
{
id: "before",
label: "A / BUFFER BEFORE",
accent: 0x55d6d0,
z: -2.45,
nodes: [
{ id: "load", type: "station", label: "LOAD", duration: 1.0, x: -7.2 },
{ id: "form", type: "station", label: "FORM", duration: 1.4, x: -3.9 },
{ id: "buffer", type: "buffer", label: "BUFFER", x: -1.25 },
{ id: "bottleneck", type: "station", label: "BOTTLENECK", duration: 3.2, x: 1.55 },
{ id: "pack", type: "station", label: "PACK", duration: 1.2, x: 5.85 }
],
edges: [
["load", "form"],
["form", "buffer"],
["buffer", "bottleneck"],
["bottleneck", "pack"]
]
},
{
id: "after",
label: "B / BUFFER AFTER",
accent: 0x65a9ff,
z: 2.35,
nodes: [
{ id: "load", type: "station", label: "LOAD", duration: 1.0, x: -7.2 },
{ id: "form", type: "station", label: "FORM", duration: 1.4, x: -3.9 },
{ id: "bottleneck", type: "station", label: "BOTTLENECK", duration: 3.2, x: -0.65 },
{ id: "buffer", type: "buffer", label: "BUFFER", x: 2.65 },
{ id: "pack", type: "station", label: "PACK", duration: 1.2, x: 6.15 }
],
edges: [
["load", "form"],
["form", "bottleneck"],
["bottleneck", "buffer"],
["buffer", "pack"]
]
}
];
// -------------------------------------------------------------------------
// Simulation
// -------------------------------------------------------------------------
function createSimulation(config) {
const nodes = {};
for (const definition of config.nodes) {
if (definition.type === "buffer") {
nodes[definition.id] = {
...definition,
queue: [],
capacity: BUFFER_CAPACITY
};
} else {
nodes[definition.id] = {
...definition,
queue: [],
capacity: STATION_QUEUE_CAPACITY,
busy: false,
remaining: 0,
ready: false,
starved: false,
starvationEvents: 0,
busySeconds: 0
};
}
}
return {
config,
nodes,
edges: config.edges.map(([from, to]) => ({ from, to })),
time: 0,
nextArrival: 0.15,
sourceBacklog: 0,
finished: 0,
bottleneckBlockedSeconds: 0
};
}
function resetSimulation(simulation) {
simulation.time = 0;
simulation.nextArrival = 0.15;
simulation.sourceBacklog = 0;
simulation.finished = 0;
simulation.bottleneckBlockedSeconds = 0;
for (const node of Object.values(simulation.nodes)) {
node.queue.length = 0;
if (node.type === "station") {
node.busy = false;
node.remaining = 0;
node.ready = false;
node.starved = false;
node.starvationEvents = 0;
node.busySeconds = 0;
}
}
}
function stepSimulation(simulation, dt) {
simulation.time += dt;
// Deterministic source cadence keeps both scenarios directly comparable.
while (simulation.time + 1e-9 >= simulation.nextArrival) {
simulation.sourceBacklog++;
simulation.nextArrival += ARRIVAL_INTERVAL;
}
const load = simulation.nodes.load;
if (simulation.sourceBacklog > 0 && load.queue.length < load.capacity) {
load.queue.push({});
simulation.sourceBacklog--;
}
// Advance each station by its fixed operation duration.
for (const node of Object.values(simulation.nodes)) {
if (node.type !== "station") continue;
if (node.busy) {
node.remaining -= dt;
node.busySeconds += dt;
if (node.remaining <= 0) {
node.remaining = 0;
node.busy = false;
node.ready = true;
node.starved = false;
if (node.id === "pack") {
simulation.finished++;
}
}
} else if (node.queue.length > 0) {
node.queue.shift();
node.busy = true;
node.remaining = node.duration;
node.starved = false;
} else {
// Count an episode only once per continuous idle-empty interval.
if (!node.starved) {
node.starvationEvents++;
node.starved = true;
}
}
}
// Move completed outputs and buffered units downstream.
for (const edge of simulation.edges) {
const from = simulation.nodes[edge.from];
const to = simulation.nodes[edge.to];
if (from.type === "station") {
if (from.ready && to.queue.length < to.capacity) {
to.queue.push({});
from.ready = false;
}
} else if (from.queue.length > 0 && to.queue.length < to.capacity) {
to.queue.push(from.queue.shift());
}
}
const bottleneck = simulation.nodes.bottleneck;
if (bottleneck.ready) {
simulation.bottleneckBlockedSeconds += dt;
}
}
function getMetrics(simulation) {
let starvation = 0;
let waiting = simulation.sourceBacklog;
for (const node of Object.values(simulation.nodes)) {
waiting += node.queue.length;
if (node.type === "station") {
starvation += node.starvationEvents;
if (node.ready) waiting++;
}
}
const bottleneck = simulation.nodes.bottleneck;
const utilization = simulation.time > 0
? Math.min(100, bottleneck.busySeconds / simulation.time * 100)
: 0;
return {
starvation,
waiting,
finished: simulation.finished,
bufferFill: simulation.nodes.buffer.queue.length,
blocked: simulation.bottleneckBlockedSeconds,
utilization
};
}
const simulations = configurations.map(createSimulation);
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const host = document.getElementById("canvasHost");
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.background);
scene.fog = new THREE.Fog(COLORS.background, 25, 44);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D comparison of two voxel assembly lines"
);
host.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const orbit = {
theta: 0.19,
phi: 1.02,
radius: 21,
target: new THREE.Vector3(-0.75, 0.75, 0)
};
const hemisphere = new THREE.HemisphereLight(0xb8d8ff, 0x18202b, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.4);
keyLight.position.set(-4, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 11;
keyLight.shadow.camera.bottom = -11;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4fb8d7, 1.3);
rimLight.position.set(8, 6, -10);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: COLORS.floor,
roughness: 0.94,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.08;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(40, 40, 0x385064, 0x20303e);
grid.position.y = -0.065;
grid.material.transparent = true;
grid.material.opacity = 0.23;
scene.add(grid);
// -------------------------------------------------------------------------
// Voxel construction helpers
// -------------------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.78,
metalness: options.metalness ?? 0.04,
flatShading: true,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
}
function addBox(
parent,
width,
height,
depth,
x,
y,
z,
color,
options = {}
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
standardMaterial(color, options)
);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function makeTextSprite(text, accent = "#55d6d0", width = 2.25) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 160;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(8, 14, 21, 0.92)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = accent;
context.lineWidth = 8;
context.strokeRect(4, 4, canvas.width - 8, canvas.height - 8);
context.fillStyle = accent;
context.fillRect(28, 28, 9, 104);
context.fillStyle = "#edf4fb";
context.font = "700 47px ui-monospace, SFMono-Regular, Menlo, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2 + 8, canvas.height / 2);
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,
depthTest: false
})
);
sprite.scale.set(width, width * 160 / 768, 1);
sprite.renderOrder = 20;
return sprite;
}
function createConveyor(x1, x2, z, accent) {
const group = new THREE.Group();
const length = Math.abs(x2 - x1);
const center = (x1 + x2) / 2;
addBox(group, length, 0.17, 0.82, center, 0.42, z, COLORS.belt);
addBox(group, length, 0.09, 0.08, center, 0.55, z - 0.39, COLORS.beltEdge);
addBox(group, length, 0.09, 0.08, center, 0.55, z + 0.39, COLORS.beltEdge);
const rollerCount = Math.max(2, Math.floor(length / 0.48));
for (let i = 0; i < rollerCount; i++) {
const x = x1 + ((i + 0.5) / rollerCount) * (x2 - x1);
addBox(group, 0.075, 0.045, 0.76, x, 0.55, z, 0x445563, {
castShadow: false
});
}
const dashCount = Math.max(1, Math.floor(length / 1.1));
for (let i = 0; i < dashCount; i++) {
const x = x1 + ((i + 0.5) / dashCount) * (x2 - x1);
addBox(group, 0.14, 0.035, 0.12, x, 0.61, z, accent, {
emissive: accent,
emissiveIntensity: 0.12,
castShadow: false
});
}
scene.add(group);
return group;
}
function createStationVisual(node, z, accent) {
const group = new THREE.Group();
group.position.set(node.x, 0, z);
const isBottleneck = node.id === "bottleneck";
const bodyColor = isBottleneck
? 0x743d43
: node.id === "load"
? 0x4d426c
: 0x415466;
addBox(group, 1.38, 0.28, 1.34, 0, 0.61, 0, COLORS.machineDark);
addBox(group, 1.08, 0.8, 1.02, 0, 1.13, 0, bodyColor);
addBox(group, 1.32, 0.18, 1.15, 0, 1.63, 0, isBottleneck ? COLORS.red : COLORS.machine);
addBox(group, 0.18, 0.68, 0.18, -0.38, 1.91, -0.34, COLORS.machineDark);
addBox(group, 0.18, 0.68, 0.18, 0.38, 1.91, -0.34, COLORS.machineDark);
addBox(group, 1.0, 0.18, 0.28, 0, 2.25, -0.34, isBottleneck ? 0xa14d4b : 0x72869a);
// Colored status tower.
addBox(group, 0.16, 0.48, 0.16, 0.43, 2.08, 0.42, COLORS.machineDark);
const light = addBox(group, 0.19, 0.19, 0.19, 0.43, 2.42, 0.42, COLORS.amber, {
emissive: COLORS.amber,
emissiveIntensity: 0.65
});
// Fixed-duration progress bar.
const progress = addBox(group, 0.96, 0.08, 0.12, 0, 1.99, 0.54, accent, {
emissive: accent,
emissiveIntensity: 0.24,
castShadow: false
});
progress.scale.x = 0.02;
const queueMeshes = [];
for (let i = 0; i < STATION_QUEUE_CAPACITY; i++) {
const cube = addBox(
group,
0.23,
0.23,
0.23,
-0.95 - i * 0.29,
0.78,
0,
COLORS.unit,
{ roughness: 0.45 }
);
cube.visible = false;
queueMeshes.push(cube);
}
// A visible output cube represents a completed unit blocked downstream.
const output = addBox(group, 0.25, 0.25, 0.25, 0.78, 0.78, 0, 0xffd166, {
emissive: 0x6f4a00,
emissiveIntensity: 0.25
});
output.visible = false;
const label = makeTextSprite(
`${node.label} ${node.duration.toFixed(1)}s`,
isBottleneck ? "#ff6b66" : "#a8bbcc",
isBottleneck ? 2.65 : 2.15
);
label.position.set(0, isBottleneck ? 2.85 : 2.62, 0);
group.add(label);
scene.add(group);
return { group, light, progress, queueMeshes, output };
}
function createBufferVisual(node, z, accent) {
const group = new THREE.Group();
group.position.set(node.x, 0, z);
addBox(group, 1.45, 0.14, 1.12, 0, 0.7, 0, 0x66552c);
addBox(group, 1.45, 0.45, 0.10, 0, 0.94, -0.53, 0xd8a92f);
addBox(group, 1.45, 0.45, 0.10, 0, 0.94, 0.53, 0xd8a92f);
addBox(group, 0.10, 0.45, 0.96, -0.68, 0.94, 0, 0xb98a25);
addBox(group, 0.10, 0.45, 0.96, 0.68, 0.94, 0, 0xb98a25);
// Voxel floor outline.
addBox(group, 1.72, 0.04, 0.06, 0, 0.28, -0.73, accent, {
emissive: accent,
emissiveIntensity: 0.18,
castShadow: false
});
addBox(group, 1.72, 0.04, 0.06, 0, 0.28, 0.73, accent, {
emissive: accent,
emissiveIntensity: 0.18,
castShadow: false
});
const slots = [];
const slotPositions = [
[-0.32, -0.25],
[0.32, -0.25],
[-0.32, 0.25],
[0.32, 0.25]
];
for (const [x, localZ] of slotPositions) {
const slot = addBox(
group,
0.27,
0.27,
0.27,
x,
0.96,
localZ,
COLORS.unit,
{ roughness: 0.42 }
);
slot.visible = false;
slots.push(slot);
}
const label = makeTextSprite("BUFFER / 4", "#ffd166", 2.05);
label.position.set(0, 1.88, 0);
group.add(label);
scene.add(group);
return { group, slots };
}
function createSourceVisual(z, accent) {
const group = new THREE.Group();
group.position.set(-8.65, 0, z);
addBox(group, 1.1, 0.23, 1.08, 0, 0.58, 0, COLORS.machineDark);
addBox(group, 0.72, 0.58, 0.72, 0, 0.98, 0, 0x3d594f);
addBox(group, 0.82, 0.14, 0.82, 0, 1.34, 0, 0x668579);
const backlog = [];
for (let i = 0; i < 8; i++) {
const x = -0.42 + (i % 3) * 0.31;
const y = 0.74 + Math.floor(i / 3) * 0.29;
const cube = addBox(
group,
0.25,
0.25,
0.25,
x,
y,
0.76,
i % 2 === 0 ? COLORS.unit : 0xaee6d2,
{ roughness: 0.45 }
);
cube.visible = false;
backlog.push(cube);
}
const label = makeTextSprite("PARTS / 1.15s", "#92d8b0", 1.95);
label.position.set(0, 1.92, 0);
group.add(label);
scene.add(group);
return { group, backlog };
}
function createLineVisual(config) {
const group = new THREE.Group();
addBox(
group,
18.3,
0.14,
3.08,
-0.7,
0.02,
config.z,
COLORS.platform,
{ castShadow: false }
);
const stationVisuals = {};
const bufferVisual = {};
for (const node of config.nodes) {
if (node.type === "station") {
stationVisuals[node.id] = createStationVisual(node, config.z, config.accent);
} else {
bufferVisual[node.id] = createBufferVisual(node, config.z, config.accent);
}
}
createConveyor(-8.1, config.nodes[0].x - 0.66, config.z, config.accent);
for (const [fromId, toId] of config.edges) {
const from = config.nodes.find(node => node.id === fromId);
const to = config.nodes.find(node => node.id === toId);
createConveyor(from.x, to.x, config.z, config.accent);
}
const source = createSourceVisual(config.z, config.accent);
const lineLabel = makeTextSprite(
config.label,
config.id === "before" ? "#55d6d0" : "#65a9ff",
3.35
);
lineLabel.position.set(-7.1, 3.12, config.z - 0.08);
group.add(lineLabel);
scene.add(group);
return { stationVisuals, bufferVisual, source };
}
const lineVisuals = configurations.map(createLineVisual);
// -------------------------------------------------------------------------
// Dynamic visual state
// -------------------------------------------------------------------------
function updateLineVisual(visual, simulation) {
for (const [nodeId, stationVisual] of Object.entries(visual.stationVisuals)) {
const node = simulation.nodes[nodeId];
let statusColor = COLORS.blue;
if (node.busy) {
statusColor = COLORS.green;
} else if (node.ready) {
statusColor = COLORS.red;
} else if (node.starved) {
statusColor = COLORS.amber;
}
stationVisual.light.material.color.setHex(statusColor);
stationVisual.light.material.emissive.setHex(statusColor);
stationVisual.light.material.emissiveIntensity = node.busy ? 0.9 : 0.45;
const progress = node.busy
? Math.max(0.02, 1 - node.remaining / node.duration)
: node.ready
? 1
: 0.02;
stationVisual.progress.scale.x = progress;
for (let i = 0; i < stationVisual.queueMeshes.length; i++) {
stationVisual.queueMeshes[i].visible = i < node.queue.length;
}
stationVisual.output.visible = node.ready;
}
const buffer = simulation.nodes.buffer;
for (let i = 0; i < visual.bufferVisual.buffer.slots.length; i++) {
visual.bufferVisual.buffer.slots[i].visible = i < buffer.queue.length;
}
for (let i = 0; i < visual.source.backlog.length; i++) {
visual.source.backlog[i].visible = i < simulation.sourceBacklog;
}
}
// -------------------------------------------------------------------------
// Camera controls implemented directly without addons
// -------------------------------------------------------------------------
const pointers = new Map();
let pinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
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;
const previous = pointers.get(event.pointerId);
const deltaX = event.clientX - previous.x;
const deltaY = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
orbit.theta -= deltaX * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi + deltaY * 0.005,
0.42,
1.42
);
} else 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 && distance > 0) {
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * (pinchDistance / distance),
11,
31
);
}
pinchDistance = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
pinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("lostpointercapture", releasePointer);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
11,
31
);
}, { passive: false });
function resetView() {
orbit.theta = 0.19;
orbit.phi = 1.02;
orbit.radius = 21;
orbit.target.set(-0.75, 0.75, 0);
}
document.getElementById("resetView").addEventListener("click", resetView);
function updateCamera() {
const aspectCompensation = camera.aspect < 1
? Math.min(1.75, 1 / camera.aspect)
: 1;
const radius = orbit.radius * aspectCompensation;
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + radius * Math.cos(orbit.phi),
orbit.target.z + radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function resize() {
const width = Math.max(1, host.clientWidth);
const height = Math.max(1, host.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(host);
resize();
// -------------------------------------------------------------------------
// UI controls and live metrics
// -------------------------------------------------------------------------
let running = true;
let speed = 1;
let accumulator = 0;
const playPause = document.getElementById("playPause");
const resetButton = document.getElementById("reset");
const runState = document.getElementById("runState");
const speedButtons = [...document.querySelectorAll("[data-speed]")];
function updateRunState() {
playPause.textContent = running ? "Pause" : "Resume";
runState.textContent = running ? "running" : "paused";
runState.style.color = running ? "var(--green)" : "var(--amber)";
}
playPause.addEventListener("click", () => {
running = !running;
accumulator = 0;
updateRunState();
});
resetButton.addEventListener("click", () => {
simulations.forEach(resetSimulation);
accumulator = 0;
updateUI();
});
for (const button of speedButtons) {
button.addEventListener("click", () => {
speed = Number(button.dataset.speed);
speedButtons.forEach(item => {
item.classList.toggle("active", item === button);
});
accumulator = 0;
});
}
function formatClock(seconds) {
const minutes = Math.floor(seconds / 60);
const remaining = seconds - minutes * 60;
return `${String(minutes).padStart(2, "0")}:${remaining.toFixed(1).padStart(4, "0")}`;
}
function updateScenarioUI(prefix, metrics) {
document.getElementById(`${prefix}Starved`).textContent =
metrics.starvation.toLocaleString();
document.getElementById(`${prefix}Waiting`).textContent =
metrics.waiting.toLocaleString();
document.getElementById(`${prefix}Finished`).textContent =
metrics.finished.toLocaleString();
document.getElementById(`${prefix}Buffer`).textContent =
`${metrics.bufferFill} / ${BUFFER_CAPACITY}`;
document.getElementById(`${prefix}Blocked`).textContent =
`${metrics.blocked.toFixed(1)}s`;
document.getElementById(`${prefix}Util`).style.width =
`${metrics.utilization.toFixed(1)}%`;
}
function updateUI() {
const before = getMetrics(simulations[0]);
const after = getMetrics(simulations[1]);
updateScenarioUI("before", before);
updateScenarioUI("after", after);
const finishedDifference = after.finished - before.finished;
const waitingDifference = after.waiting - before.waiting;
document.getElementById("beforeCard").classList.toggle(
"leader",
finishedDifference > 0
);
document.getElementById("afterCard").classList.toggle(
"leader",
finishedDifference < 0
);
const comparison = document.getElementById("comparison");
if (finishedDifference === 0) {
comparison.innerHTML =
`<strong>Comparison:</strong> Both runs have finished the same number of units. ` +
`Currently, the after-bottleneck layout holds ` +
`${Math.abs(waitingDifference)} ${Math.abs(waitingDifference) === 1 ? "unit" : "units"} ` +
`${waitingDifference < 0 ? "less" : "more"} in the system.`;
} else {
const leader = finishedDifference > 0 ? "after" : "before";
const leaderName = leader === "after"
? "After-bottleneck"
: "Before-bottleneck";
const waitingPhrase = waitingDifference === 0
? "The waiting totals are equal."
: `The after-bottleneck run currently holds ` +
`${Math.abs(waitingDifference)} ` +
`${Math.abs(waitingDifference) === 1 ? "unit" : "units"} ` +
`${waitingDifference < 0 ? "less" : "more"}.`;
comparison.innerHTML =
`<strong>Comparison:</strong> ${leaderName} is ahead by ` +
`${Math.abs(finishedDifference)} finished ` +
`${Math.abs(finishedDifference) === 1 ? "unit" : "units"}. ` +
waitingPhrase;
}
document.getElementById("clock").textContent =
formatClock(simulations[0].time);
}
updateRunState();
updateUI();
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let previousTime = performance.now();
let previousUIUpdate = 0;
function animate(now) {
requestAnimationFrame(animate);
const frameDelta = Math.min((now - previousTime) / 1000, 0.1);
previousTime = now;
if (running) {
accumulator += frameDelta * speed;
let steps = 0;
while (accumulator >= FIXED_DT && steps < 40) {
for (const simulation of simulations) {
stepSimulation(simulation, FIXED_DT);
}
accumulator -= FIXED_DT;
steps++;
}
}
for (let i = 0; i < simulations.length; i++) {
updateLineVisual(lineVisuals[i], simulations[i]);
}
if (now - previousUIUpdate > 100) {
updateUI();
previousUIUpdate = now;
}
updateCamera();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```