Prompt specification
Build or customize the Three.js 3D scene "Island Supply Chain Interruption" 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: Island Supply Chain Interruption
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/island-supply-chain-interruption-x3171
Scene Description Prompt:
Build one HTML scene using Three.js from cdnjs where interrupting a voxel island supply route causes delayed shortages as finite inventories run out.
Working Three.js Starter (island-supply-chain-interruption-x3171):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tideland — Voxel Supply Resilience</title>
<style>
:root {
--ink: #092832;
--panel: rgba(7, 31, 40, 0.92);
--panel-soft: rgba(255, 255, 255, 0.07);
--text: #eefbf7;
--muted: #9eb9bc;
--mint: #69e2c3;
--amber: #ffb85c;
--red: #ff7167;
--line: rgba(210, 245, 239, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #9bcbd0;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background:
radial-gradient(
circle at 45% 42%,
transparent 35%,
rgba(9, 35, 44, 0.08) 100%
);
}
canvas {
display: block;
}
.brand {
position: fixed;
top: 22px;
left: 24px;
z-index: 5;
pointer-events: none;
}
.brand-mark {
display: flex;
align-items: center;
gap: 12px;
}
.brand-icon {
display: grid;
grid-template-columns: repeat(3, 5px);
grid-template-rows: repeat(3, 5px);
gap: 3px;
width: 32px;
height: 32px;
padding: 4px;
border: 1px solid rgba(9, 40, 48, 0.25);
background: rgba(238, 251, 247, 0.72);
box-shadow: 0 8px 22px rgba(9, 40, 48, 0.12);
backdrop-filter: blur(10px);
}
.brand-icon i {
display: block;
background: var(--ink);
}
.brand-icon i:nth-child(2),
.brand-icon i:nth-child(4),
.brand-icon i:nth-child(8) {
opacity: 0.45;
}
.brand h1 {
margin: 0;
color: var(--ink);
font-size: 18px;
line-height: 1;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.brand p {
margin: 8px 0 0 45px;
color: rgba(9, 40, 48, 0.72);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.world-status {
position: fixed;
top: 24px;
left: 50%;
z-index: 5;
display: flex;
gap: 8px;
transform: translateX(-50%);
pointer-events: none;
}
.status-chip {
display: flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 0 12px;
border: 1px solid rgba(9, 40, 48, 0.16);
border-radius: 999px;
background: rgba(238, 251, 247, 0.78);
box-shadow: 0 8px 24px rgba(9, 40, 48, 0.1);
color: var(--ink);
backdrop-filter: blur(12px);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 0 4px rgba(105, 226, 195, 0.18);
}
.status-dot.cut {
background: var(--red);
box-shadow: 0 0 0 4px rgba(255, 113, 103, 0.18);
}
.panel {
position: fixed;
top: 22px;
right: 22px;
z-index: 10;
width: 354px;
max-height: calc(100vh - 44px);
overflow: auto;
padding: 20px;
border: 1px solid rgba(221, 249, 243, 0.16);
border-radius: 22px;
background: var(--panel);
box-shadow:
0 24px 70px rgba(4, 28, 37, 0.27),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(20px) saturate(1.1);
scrollbar-width: thin;
scrollbar-color: rgba(105, 226, 195, 0.3) transparent;
}
.eyebrow {
margin: 0 0 7px;
color: var(--mint);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.panel h2 {
margin: 0;
font-size: 21px;
font-weight: 650;
letter-spacing: -0.025em;
}
.badge {
padding: 6px 8px;
border-radius: 7px;
background: rgba(105, 226, 195, 0.13);
color: var(--mint);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
}
.badge.cut {
background: rgba(255, 113, 103, 0.14);
color: var(--red);
}
.description {
min-height: 42px;
margin: 12px 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.route-button {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
min-height: 48px;
border: 1px solid rgba(255, 113, 103, 0.38);
border-radius: 13px;
background: linear-gradient(135deg, #ff786d, #e95355);
color: #fff;
cursor: pointer;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
box-shadow: 0 10px 24px rgba(217, 65, 65, 0.2);
transition:
transform 160ms ease,
box-shadow 160ms ease,
background 160ms ease;
}
.route-button:hover {
transform: translateY(-1px);
box-shadow: 0 14px 28px rgba(217, 65, 65, 0.26);
}
.route-button:active {
transform: translateY(0);
}
.route-button.cut {
border-color: rgba(105, 226, 195, 0.36);
background: linear-gradient(135deg, #70e6c6, #3dbb9f);
color: #062f32;
box-shadow: 0 10px 24px rgba(44, 183, 151, 0.18);
}
.button-glyph {
display: grid;
place-items: center;
width: 20px;
height: 20px;
border: 1px solid currentColor;
border-radius: 5px;
font-size: 9px;
line-height: 1;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 12px;
}
.metric {
min-height: 82px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: var(--panel-soft);
}
.metric.wide {
grid-column: 1 / -1;
min-height: 105px;
}
.metric-label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
font-weight: 700;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.metric-value {
display: inline-block;
color: var(--text);
font-size: 25px;
font-weight: 700;
line-height: 1;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.metric-sub {
margin-left: 5px;
color: var(--muted);
font-size: 10px;
}
.metric.critical .metric-value {
color: var(--red);
}
.metric.warning .metric-value {
color: var(--amber);
}
.stock-track {
height: 7px;
margin-top: 14px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.09);
}
.stock-fill {
width: 60%;
height: 100%;
border-radius: inherit;
background: var(--mint);
transition:
width 180ms linear,
background 180ms ease;
}
.chart-section {
margin-top: 13px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(0, 0, 0, 0.08);
}
.chart-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.chart-title {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
font-weight: 700;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.chart-legend {
display: flex;
align-items: center;
gap: 5px;
color: var(--muted);
font-size: 8px;
}
.chart-legend i {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--mint);
}
#stockChart {
width: 100%;
height: 98px;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 13px;
}
.control-card {
padding: 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--panel-soft);
}
.control-title {
display: block;
margin-bottom: 8px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.speed-buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 4px;
}
.speed-button,
.small-button {
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 7px;
background: rgba(255, 255, 255, 0.05);
color: var(--muted);
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
transition: 140ms ease;
}
.speed-button {
height: 27px;
}
.speed-button:hover,
.small-button:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.1);
}
.speed-button.active {
border-color: rgba(105, 226, 195, 0.35);
background: rgba(105, 226, 195, 0.15);
color: var(--mint);
}
.small-button {
width: 100%;
height: 34px;
}
.small-button.pause.active {
border-color: rgba(255, 184, 92, 0.35);
background: rgba(255, 184, 92, 0.12);
color: var(--amber);
}
.log-section {
margin-top: 13px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.event-log {
display: grid;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
}
.event-log li {
display: grid;
grid-template-columns: 43px 1fr;
gap: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.event-time {
color: rgba(238, 251, 247, 0.42);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.event-log li.success .event-message {
color: var(--mint);
}
.event-log li.warning .event-message {
color: var(--amber);
}
.event-log li.critical .event-message {
color: var(--red);
}
.scene-hint {
position: fixed;
bottom: 23px;
left: 24px;
z-index: 5;
display: flex;
align-items: center;
gap: 10px;
padding: 10px 13px;
border: 1px solid rgba(9, 40, 48, 0.14);
border-radius: 11px;
background: rgba(238, 251, 247, 0.73);
color: rgba(9, 40, 48, 0.75);
backdrop-filter: blur(10px);
pointer-events: none;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.hint-keys {
display: flex;
gap: 4px;
}
.hint-keys span {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border: 1px solid rgba(9, 40, 48, 0.18);
border-radius: 5px;
color: var(--ink);
background: rgba(255, 255, 255, 0.42);
font-size: 9px;
}
@media (max-width: 760px) {
.brand {
top: 13px;
left: 13px;
}
.brand h1 {
font-size: 14px;
}
.brand p {
display: none;
}
.world-status {
top: 62px;
left: 13px;
transform: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 51vh;
padding: 15px;
border-radius: 17px;
}
.description {
min-height: 0;
}
.metric-grid {
grid-template-columns: repeat(4, 1fr);
}
.metric {
min-height: 68px;
padding: 9px;
}
.metric.wide {
grid-column: span 2;
}
.metric-value {
font-size: 20px;
}
.chart-section,
.log-section {
display: none;
}
.scene-hint {
display: none;
}
}
</style>
</head>
<body>
<main id="scene" aria-label="Interactive voxel island supply simulation"></main>
<header class="brand">
<div class="brand-mark">
<div class="brand-icon" aria-hidden="true">
<i></i><i></i><i></i>
<i></i><i></i><i></i>
<i></i><i></i><i></i>
</div>
<h1>Tideland</h1>
</div>
<p>Island logistics / resilience sandbox</p>
</header>
<div class="world-status">
<div class="status-chip">
<span id="routeDot" class="status-dot"></span>
<span id="routeStatus">Route live</span>
</div>
<div class="status-chip">
Day <strong id="dayValue">000.0</strong>
</div>
</div>
<aside class="panel">
<p class="eyebrow">Scenario 07 / finite buffer</p>
<div class="panel-heading">
<h2>Supply route</h2>
<span id="routeBadge" class="badge">Live</span>
</div>
<p id="description" class="description">
Interrupt the causeway now. The island keeps consuming its finite
inventory, so shortages appear only after the buffer runs out.
</p>
<button id="routeToggle" class="route-button" type="button">
<span class="button-glyph">×</span>
<span id="toggleLabel">Interrupt route</span>
</button>
<div class="metric-grid">
<div id="stockCard" class="metric wide">
<span class="metric-label">Island inventory</span>
<span id="stockValue" class="metric-value">72</span>
<span class="metric-sub">/ 120 crates</span>
<div class="stock-track">
<div id="stockFill" class="stock-fill"></div>
</div>
</div>
<div id="backlogCard" class="metric">
<span class="metric-label">Current shortage</span>
<span id="backlogValue" class="metric-value">0</span>
<span class="metric-sub">crates</span>
</div>
<div class="metric">
<span class="metric-label">Next delivery</span>
<span id="arrivalValue" class="metric-value">2.6d</span>
</div>
<div class="metric">
<span class="metric-label">Source reserve</span>
<span id="sourceValue" class="metric-value">180</span>
<span class="metric-sub">crates</span>
</div>
<div class="metric">
<span class="metric-label">Unmet demand</span>
<span id="unmetValue" class="metric-value">0</span>
<span class="metric-sub">total</span>
</div>
</div>
<section class="chart-section" aria-label="Inventory history chart">
<div class="chart-head">
<span class="chart-title">Inventory buffer / time</span>
<span class="chart-legend"><i></i> stock</span>
</div>
<canvas id="stockChart"></canvas>
</section>
<div class="controls">
<div class="control-card">
<span class="control-title">Simulation speed</span>
<div class="speed-buttons">
<button class="speed-button" data-speed="0.5" type="button">½×</button>
<button class="speed-button active" data-speed="1" type="button">1×</button>
<button class="speed-button" data-speed="2" type="button">2×</button>
<button class="speed-button" data-speed="4" type="button">4×</button>
</div>
</div>
<div class="control-card">
<span class="control-title">Simulation</span>
<div style="display: grid; gap: 5px">
<button id="pauseButton" class="small-button pause" type="button">
Pause
</button>
<button id="resetButton" class="small-button" type="button">
Reset scenario
</button>
</div>
</div>
</div>
<section class="log-section">
<span class="control-title">Event log</span>
<ul id="eventLog" class="event-log"></ul>
</section>
</aside>
<div class="scene-hint">
<div class="hint-keys"><span>↔</span><span>↕</span></div>
Drag to orbit · Scroll to zoom
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneElement = document.getElementById("scene");
// -------------------------------------------------------------------------
// Renderer, camera and lighting
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
sceneElement.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x9bcbd0);
scene.fog = new THREE.Fog(0x9bcbd0, 47, 88);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
150
);
const hemisphere = new THREE.HemisphereLight(0xd8f5f0, 0x42636a, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1cf, 3.1);
sun.position.set(-18, 30, 15);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -38;
sun.shadow.camera.right = 38;
sun.shadow.camera.top = 30;
sun.shadow.camera.bottom = -30;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 75;
sun.shadow.bias = -0.00025;
scene.add(sun);
const fillLight = new THREE.DirectionalLight(0x8fe9df, 0.65);
fillLight.position.set(20, 12, -22);
scene.add(fillLight);
// -------------------------------------------------------------------------
// Shared voxel helpers
// -------------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function getMaterial(color, roughness = 0.86) {
const key = `${color}-${roughness}`;
if (!materialCache.has(key)) {
materialCache.set(
key,
new THREE.MeshStandardMaterial({
color,
roughness,
metalness: 0.02
})
);
}
return materialCache.get(key);
}
function addBox(
parent,
sx,
sy,
sz,
color,
x = 0,
y = 0,
z = 0,
options = {}
) {
const material =
color && color.isMaterial
? color
: new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.86,
metalness: options.metalness ?? 0.02,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
const mesh = new THREE.Mesh(unitBox, material);
mesh.position.set(x, y, z);
mesh.scale.set(sx, sy, sz);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function hash(x, z) {
const n = Math.sin(x * 127.1 + z * 311.7) * 43758.5453123;
return n - Math.floor(n);
}
function roundedRect(context, x, y, w, h, radius) {
const r = Math.min(radius, w / 2, h / 2);
context.beginPath();
context.moveTo(x + r, y);
context.lineTo(x + w - r, y);
context.quadraticCurveTo(x + w, y, x + w, y + r);
context.lineTo(x + w, y + h - r);
context.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
context.lineTo(x + r, y + h);
context.quadraticCurveTo(x, y + h, x, y + h - r);
context.lineTo(x, y + r);
context.quadraticCurveTo(x, y, x + r, y);
context.closePath();
}
function makeLabel(text, accent = "#69e2c3") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 512, 128);
roundedRect(context, 8, 18, 496, 92, 22);
context.fillStyle = "rgba(7, 31, 40, 0.88)";
context.fill();
context.lineWidth = 4;
context.strokeStyle = accent;
context.stroke();
context.fillStyle = accent;
context.font = "800 42px ui-monospace, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(5.6, 1.4, 1);
sprite.renderOrder = 20;
return sprite;
}
// -------------------------------------------------------------------------
// Animated water
// -------------------------------------------------------------------------
const waterGeometry = new THREE.PlaneGeometry(120, 120, 28, 28);
waterGeometry.rotateX(-Math.PI / 2);
const water = new THREE.Mesh(
waterGeometry,
new THREE.MeshStandardMaterial({
color: 0x4e9eaa,
roughness: 0.32,
metalness: 0.08
})
);
water.position.y = -0.06;
water.receiveShadow = true;
scene.add(water);
const waveMeshes = [];
for (let i = 0; i < 38; i++) {
const wave = addBox(
scene,
0.7 + hash(i, 4) * 1.5,
0.025,
0.07,
0xb7e6e6,
-30 + hash(i, 8) * 60,
0.025,
-27 + hash(i, 12) * 54,
{ castShadow: false }
);
wave.userData.speed = 0.12 + hash(i, 19) * 0.22;
waveMeshes.push(wave);
}
// -------------------------------------------------------------------------
// Voxel island and mainland
// -------------------------------------------------------------------------
function islandHeight(ix, iz) {
const rx = (ix - 7) / 8.1;
const rz = iz / 7.5;
const radius = Math.hypot(rx, rz);
if (radius > 1.04) return 0;
const noise = hash(Math.round(ix), Math.round(iz));
return 1 + Math.max(0, Math.floor((1 - radius) * 4.3 + noise * 1.7));
}
function mainlandHeight(ix, iz) {
const rx = (ix + 15) / 5.8;
const rz = iz / 5.2;
const radius = Math.hypot(rx, rz);
if (radius > 1.04) return 0;
const noise = hash(Math.round(ix) + 31, Math.round(iz) - 17);
return 2 + Math.max(0, Math.floor((1 - radius) * 2.2 + noise * 1.4));
}
function buildVoxelTerrain(cells, heightFunction, colorFunction) {
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
});
const mesh = new THREE.InstancedMesh(unitBox, material, cells.length);
const dummy = new THREE.Object3D();
cells.forEach((cell, index) => {
dummy.position.set(cell.x, -1 + cell.height / 2, cell.z);
dummy.scale.set(1, cell.height, 1);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
mesh.setColorAt(index, new THREE.Color(cell.color));
});
mesh.instanceMatrix.needsUpdate = true;
mesh.instanceColor.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
const islandCells = [];
for (let x = -1; x <= 15; x++) {
for (let z = -8; z <= 8; z++) {
const height = islandHeight(x, z);
if (!height) continue;
const radius = Math.hypot((x - 7) / 8.1, z / 7.5);
const variation = hash(x + 13, z - 9);
let color = 0x6ba873;
if (radius > 0.86) color = 0xd7c58b;
else if (height >= 5) color = 0x7d8e78;
else if (variation > 0.84) color = 0x7cb77b;
else if (variation < 0.13) color = 0x5c9869;
islandCells.push({ x, z, height, color });
}
}
buildVoxelTerrain(islandCells, islandHeight, null);
const mainlandCells = [];
for (let x = -21; x <= -9; x++) {
for (let z = -7; z <= 7; z++) {
const height = mainlandHeight(x, z);
if (!height) continue;
const variation = hash(x - 11, z + 21);
let color = 0x6f817f;
if (variation > 0.76) color = 0x81918a;
if (variation < 0.2) color = 0x637773;
mainlandCells.push({ x, z, height, color });
}
}
buildVoxelTerrain(mainlandCells, mainlandHeight, null);
// -------------------------------------------------------------------------
// Raised voxel supply route
// -------------------------------------------------------------------------
function addPathSegment(a, b, width, raised = true) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const pieces = Math.ceil(length / 0.75);
const angle = -Math.atan2(dz, dx);
for (let i = 0; i < pieces; i++) {
const t = (i + 0.5) / pieces;
const x = a.x + dx * t;
const z = a.z + dz * t;
const color = i % 2 === 0 ? 0x9c7952 : 0xb08a5e;
const piece = addBox(
scene,
length / pieces + 0.04,
0.32,
width,
color,
x,
raised ? 0.22 : 0.08,
z
);
piece.rotation.y = angle;
}
}
addPathSegment({ x: -10.5, z: 0 }, { x: 1, z: 0 }, 2.1, true);
addPathSegment({ x: 1, z: 0 }, { x: 3, z: -3 }, 1.65, false);
for (let x = -10; x <= 0.8; x += 1.35) {
addBox(scene, 0.2, 1.4, 0.2, 0x685242, x, -0.35, -0.78);
addBox(scene, 0.2, 1.4, 0.2, 0x685242, x, -0.35, 0.78);
}
const routeMarkerMaterial = new THREE.MeshStandardMaterial({
color: 0x69e2c3,
roughness: 0.45,
emissive: 0x2f9f83,
emissiveIntensity: 0.65
});
const routeMarkers = [];
for (let x = -10; x <= 0.8; x += 1.25) {
routeMarkers.push(
addBox(
scene,
0.25,
0.08,
0.18,
routeMarkerMaterial,
x,
0.45,
-0.78
)
);
}
// Checkpoint B barrier.
const gate = new THREE.Group();
scene.add(gate);
addBox(gate, 0.28, 1.9, 0.28, 0x46585b, -4.5, 0.62, -1.28);
addBox(gate, 0.28, 1.9, 0.28, 0x46585b, -4.5, 0.62, 1.28);
addBox(gate, 0.8, 0.18, 0.8, 0x33474a, -4.5, 0.03, 0);
const gatePivot = new THREE.Group();
gatePivot.position.set(-4.5, 1.23, -1.15);
gate.add(gatePivot);
for (let i = 0; i < 6; i++) {
addBox(
gatePivot,
0.24,
0.24,
0.39,
i % 2 === 0 ? 0xff7167 : 0xf4eee0,
0,
0,
0.195 + i * 0.39
);
}
const routeSignalMaterial = new THREE.MeshStandardMaterial({
color: 0x69e2c3,
emissive: 0x38b998,
emissiveIntensity: 1
});
const routeSignal = addBox(
gate,
0.36,
0.36,
0.36,
routeSignalMaterial,
-4.5,
1.78,
0
);
const gateLabel = makeLabel("CHECKPOINT B", "#ffb85c");
gateLabel.position.set(-4.5, 3.05, 0);
gateLabel.scale.set(4.4, 1.1, 1);
scene.add(gateLabel);
// -------------------------------------------------------------------------
// Buildings, trees and small details
// -------------------------------------------------------------------------
function makeBuilding({
x,
z,
w,
d,
h,
base,
body = 0xe8d7b2,
roof = 0xc5684d
}) {
const group = new THREE.Group();
group.position.set(x, base, z);
scene.add(group);
addBox(group, w + 0.5, 0.22, d + 0.5, 0x8e8d78, 0, 0.02, 0);
addBox(group, w, h, d, body, 0, h / 2, 0);
addBox(group, w + 0.45, 0.34, d + 0.45, roof, 0, h + 0.08, 0);
addBox(group, w * 0.72, 0.32, d * 0.72, roof, 0, h + 0.34, 0);
addBox(group, 0.62, 1.15, 0.09, 0x334b4b, 0, 0.58, d / 2 + 0.055);
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x8ed8d7,
emissive: 0x306e72,
emissiveIntensity: 0.35,
roughness: 0.3
});
addBox(
group,
0.55,
0.5,
0.09,
windowMaterial,
-w * 0.29,
h * 0.61,
d / 2 + 0.055
);
addBox(
group,
0.55,
0.5,
0.09,
windowMaterial,
w * 0.29,
h * 0.61,
d / 2 + 0.055
);
return group;
}
function makeTree(x, z, size = 1) {
const base = islandHeight(Math.round(x), Math.round(z)) - 1;
const group = new THREE.Group();
group.position.set(x, base, z);
scene.add(group);
addBox(group, 0.32 * size, 1.5 * size, 0.32 * size, 0x77543c, 0, 0.75 * size, 0);
addBox(group, 1.55 * size, 0.85 * size, 1.55 * size, 0x397c5a, 0, 1.65 * size, 0);
addBox(group, 1.05 * size, 0.75 * size, 1.05 * size, 0x4b9164, 0, 2.25 * size, 0);
addBox(group, 0.62 * size, 0.55 * size, 0.62 * size, 0x64a873, 0.15, 2.8 * size, 0);
}
const islandWarehouse = makeBuilding({
x: 4.4,
z: -4.6,
w: 4.2,
d: 3.1,
h: 2.6,
base: islandHeight(4, -5) - 1,
body: 0xd8c9a7,
roof: 0x397e75
});
const sourceWarehouse = makeBuilding({
x: -15,
z: -3.5,
w: 4.4,
d: 3.5,
h: 3,
base: mainlandHeight(-15, -4) - 1,
body: 0x9eaaa3,
roof: 0x405e60
});
const houseData = [
[8.7, -3.4, 2.2, 2.1, 1.8, 0xe8d5ad, 0xb95f49],
[10.8, 0.6, 2.5, 2.2, 1.9, 0xe9cfaa, 0x8c6c57],
[7.2, 4.1, 2.1, 2, 1.7, 0xddd5b7, 0x4e7b75],
[10.5, 4.1, 2.3, 2.1, 1.8, 0xe5c6a0, 0xbd674e],
[4.2, 3.5, 2.1, 2, 1.7, 0xe9dbba, 0x577b72]
];
houseData.forEach(([x, z, w, d, h, body, roof]) => {
makeBuilding({
x,
z,
w,
d,
h,
base: islandHeight(Math.round(x), Math.round(z)) - 1,
body,
roof
});
});
[
[1.2, -5.7, 1.05],
[5.2, -6.6, 0.85],
[12.8, -3.3, 0.9],
[12.3, 4.8, 1.05],
[8.4, 5.8, 0.82],
[1.8, 5.6, 0.94],
[6.2, 1.1, 0.72]
].forEach(([x, z, size]) => makeTree(x, z, size));
// Lighthouse.
const lighthouseBase = islandHeight(13, -1) - 1;
const lighthouse = new THREE.Group();
lighthouse.position.set(13, lighthouseBase, -1);
scene.add(lighthouse);
addBox(lighthouse, 1.35, 2.9, 1.35, 0xe7e3d2, 0, 1.45, 0);
addBox(lighthouse, 0.48, 0.8, 1.38, 0xcf6556, 0, 1.7, 0);
addBox(lighthouse, 1.65, 0.28, 1.65, 0x405d63, 0, 3.05, 0);
addBox(lighthouse, 0.78, 0.75, 0.78, 0xffe6a6, 0, 3.55, 0);
addBox(lighthouse, 1.1, 0.26, 1.1, 0x405d63, 0, 4.05, 0);
const sourceLabel = makeLabel("SOURCE RIDGE", "#ffb85c");
sourceLabel.position.set(-15, 6.2, -3.5);
sourceLabel.scale.set(5.5, 1.35, 1);
scene.add(sourceLabel);
const depotLabel = makeLabel("ISLAND DEPOT 07", "#69e2c3");
depotLabel.position.set(4.4, 5.5, -4.6);
depotLabel.scale.set(5.4, 1.35, 1);
scene.add(depotLabel);
const shortageLabel = makeLabel("SHORTAGE / BACKLOG", "#ff7167");
shortageLabel.position.set(8.3, 8.5, 0);
shortageLabel.scale.set(6.1, 1.5, 1);
shortageLabel.visible = false;
scene.add(shortageLabel);
// Tiny villagers.
function makePerson(x, z, color) {
const base = islandHeight(Math.round(x), Math.round(z)) - 1;
const group = new THREE.Group();
group.position.set(x, base, z);
scene.add(group);
addBox(group, 0.3, 0.48, 0.3, color, 0, 0.34, 0);
addBox(group, 0.25, 0.24, 0.25, 0xe4b48c, 0, 0.7, 0);
addBox(group, 0.1, 0.22, 0.1, 0x30484a, -0.08, 0.11, 0);
addBox(group, 0.1, 0.22, 0.1, 0x30484a, 0.08, 0.11, 0);
}
makePerson(7.7, -2.3, 0xe7a44e);
makePerson(9.7, 1.5, 0x3e9d91);
makePerson(8.2, 3.1, 0xcf6258);
makePerson(11.8, 2.4, 0x697fbe);
// -------------------------------------------------------------------------
// Finite island stock shown as physical crates
// -------------------------------------------------------------------------
const stockCrates = [];
for (let i = 0; i < 12; i++) {
const material = new THREE.MeshStandardMaterial({
color: 0x69cfae,
roughness: 0.8
});
const crate = addBox(
scene,
0.72,
0.62,
0.72,
material,
2.35 + (i % 4) * 0.85,
islandHeight(3, -1) - 0.66,
-1.55 + Math.floor(i / 4) * 0.88
);
crate.userData.index = i;
stockCrates.push(crate);
}
// Source-side reserve crates.
for (let i = 0; i < 12; i++) {
addBox(
scene,
0.68,
0.58,
0.68,
i % 3 === 0 ? 0xc88a52 : 0x9e7048,
-13 + (i % 4) * 0.78,
mainlandHeight(-12, -1) - 0.55,
-1.65 + Math.floor(i / 4) * 0.82
);
}
const warningBeacons = [];
[
[8.7, -3.4, 2.35],
[10.8, 0.6, 2.45],
[7.2, 4.1, 2.15]
].forEach(([x, z, height]) => {
const material = new THREE.MeshStandardMaterial({
color: 0xff7167,
emissive: 0xff392f,
emissiveIntensity: 1.5
});
const beacon = addBox(
scene,
0.24,
0.24,
0.24,
material,
x,
islandHeight(Math.round(x), Math.round(z)) - 1 + height,
z
);
warningBeacons.push(beacon);
});
// -------------------------------------------------------------------------
// Voxel supply truck
// -------------------------------------------------------------------------
const truck = new THREE.Group();
scene.add(truck);
addBox(truck, 1.8, 0.24, 0.84, 0x30484a, 0, 0.04, 0);
addBox(truck, 0.72, 0.76, 0.78, 0xe7b34e, 0.58, 0.49, 0);
addBox(truck, 0.09, 0.32, 0.58, 0x91d9d2, 0.965, 0.62, 0);
const cargoGroup = new THREE.Group();
truck.add(cargoGroup);
addBox(cargoGroup, 1.02, 0.72, 0.72, 0xd7754d, -0.37, 0.52, 0);
addBox(cargoGroup, 0.12, 0.74, 0.74, 0xf1b15f, -0.37, 0.52, 0);
[
[-0.55, -0.48],
[-0.55, 0.48],
[0.58, -0.48],
[0.58, 0.48]
].forEach(([x, z]) => {
addBox(truck, 0.34, 0.28, 0.18, 0x233437, x, -0.12, z);
});
const routePoints = [
{ x: -10.5, z: 0 },
{ x: -4.5, z: 0 },
{ x: 1, z: 0 },
{ x: 3, z: -3 }
];
const routeSegmentLengths = [];
for (let i = 0; i < routePoints.length - 1; i++) {
routeSegmentLengths.push(
Math.hypot(
routePoints[i + 1].x - routePoints[i].x,
routePoints[i + 1].z - routePoints[i].z
)
);
}
const routeLength = routeSegmentLengths.reduce((a, b) => a + b, 0);
const gateProgress = routeSegmentLengths[0] / routeLength;
function routePosition(progress) {
let distance = THREE.MathUtils.clamp(progress, 0, 1) * routeLength;
for (let i = 0; i < routeSegmentLengths.length; i++) {
const length = routeSegmentLengths[i];
if (distance <= length || i === routeSegmentLengths.length - 1) {
const a = routePoints[i];
const b = routePoints[i + 1];
const t = THREE.MathUtils.clamp(distance / length, 0, 1);
return {
x: THREE.MathUtils.lerp(a.x, b.x, t),
z: THREE.MathUtils.lerp(a.z, b.z, t),
angle: -Math.atan2(b.z - a.z, b.x - a.x),
segment: i
};
}
distance -= length;
}
return { x: 0, z: 0, angle: 0, segment: 0 };
}
// -------------------------------------------------------------------------
// Voxel clouds
// -------------------------------------------------------------------------
const clouds = [];
function makeCloud(x, y, z, scale) {
const group = new THREE.Group();
group.position.set(x, y, z);
scene.add(group);
addBox(group, 3.4 * scale, 0.85 * scale, 1.1 * scale, 0xe7f2ea, 0, 0, 0);
addBox(group, 1.5 * scale, 0.75 * scale, 1.2 * scale, 0xf4f6ed, -0.8 * scale, 0.5 * scale, 0);
addBox(group, 1.25 * scale, 0.65 * scale, 1 * scale, 0xffffff, 0.9 * scale, 0.4 * scale, 0);
group.userData.speed = 0.16 + hash(x, z) * 0.12;
clouds.push(group);
}
makeCloud(-13, 12.5, -13, 1.4);
makeCloud(7, 14.5, -17, 1.05);
makeCloud(20, 11.5, 7, 1.2);
// -------------------------------------------------------------------------
// Simulation state
// -------------------------------------------------------------------------
const DAYS_PER_SECOND = 0.5;
const OUTBOUND_DAYS = 2.8;
const RETURN_DAYS = 2;
const LOAD_SIZE = 36;
const DEMAND_RATE = 10;
function makeState() {
return {
day: 0,
stock: 72,
capacity: 120,
demandRate: DEMAND_RATE,
backlog: 0,
unmetTotal: 0,
source: 180,
deliveredTotal: 0,
routeOpen: true,
paused: false,
speed: 1,
truck: {
phase: "outbound",
progress: 0.08,
load: LOAD_SIZE,
timer: 0
},
history: [{ day: 0, stock: 72 }],
cutMarks: [],
logs: [
{
day: 0,
message: "Convoy departed Source Ridge with 36 crates.",
tone: "info"
}
],
logVersion: 0,
lastHistoryDay: 0
};
}
let simulation = makeState();
function addLog(message, tone = "info") {
simulation.logs.unshift({
day: simulation.day,
message,
tone
});
simulation.logs = simulation.logs.slice(0, 5);
simulation.logVersion++;
}
function consumeInventory(dt) {
const demand = simulation.demandRate * dt;
const hadStock = simulation.stock > 0;
if (simulation.stock >= demand) {
simulation.stock -= demand;
} else {
const lost = demand - simulation.stock;
simulation.stock = 0;
simulation.backlog += lost;
simulation.unmetTotal += lost;
}
if (hadStock && simulation.stock <= 0) {
addLog("Island inventory depleted; unmet demand is accumulating.", "critical");
}
}
function deliverShipment() {
const shipment = simulation.truck.load;
const oldBacklog = simulation.backlog;
const backlogCleared = Math.min(simulation.backlog, shipment);
simulation.backlog -= backlogCleared;
const restocked = shipment - backlogCleared;
simulation.stock = Math.min(simulation.capacity, simulation.stock + restocked);
simulation.deliveredTotal += shipment;
if (oldBacklog > 0) {
addLog(
`Delivery landed: ${Math.round(backlogCleared)} backlog cleared, ${Math.round(restocked)} restocked.`,
backlogCleared >= oldBacklog ? "success" : "warning"
);
} else {
addLog(`Delivery landed: ${Math.round(restocked)} crates added to stock.`, "success");
}
simulation.truck.phase = "docked";
simulation.truck.timer = 0.38;
simulation.truck.load = 0;
}
function updateTruck(dt) {
const vehicle = simulation.truck;
if (vehicle.phase === "outbound") {
if (!simulation.routeOpen && vehicle.progress <= gateProgress) {
vehicle.progress = Math.min(
gateProgress,
vehicle.progress + dt / OUTBOUND_DAYS
);
} else {
vehicle.progress += dt / OUTBOUND_DAYS;
}
if (vehicle.progress >= 1) deliverShipment();
} else if (vehicle.phase === "docked") {
vehicle.timer -= dt;
if (vehicle.timer <= 0) {
vehicle.phase = "returning";
vehicle.progress = 1;
}
} else if (vehicle.phase === "returning") {
if (!simulation.routeOpen && vehicle.progress >= gateProgress) {
vehicle.progress = Math.max(
gateProgress,
vehicle.progress - dt / RETURN_DAYS
);
} else {
vehicle.progress -= dt / RETURN_DAYS;
}
if (vehicle.progress <= 0) {
vehicle.phase = "loading";
vehicle.timer = 0.7;
}
} else if (vehicle.phase === "loading") {
vehicle.timer -= dt;
if (vehicle.timer <= 0) {
if (simulation.source > 0) {
const shipment = Math.min(LOAD_SIZE, simulation.source);
simulation.source -= shipment;
simulation.truck.load = shipment;
simulation.truck.phase = "outbound";
simulation.truck.progress = 0;
if (!simulation.routeOpen) {
addLog(`Convoy loaded ${shipment} crates and is waiting at Checkpoint B.`, "warning");
}
} else {
simulation.truck.phase = "empty";
}
}
}
}
function simulate(realDt) {
if (simulation.paused) return;
const dt = realDt * DAYS_PER_SECOND * simulation.speed;
simulation.day += dt;
consumeInventory(dt);
updateTruck(dt);
if (simulation.day - simulation.lastHistoryDay >= 0.25) {
simulation.history.push({
day: simulation.day,
stock: simulation.stock
});
simulation.history = simulation.history.slice(-500);
simulation.lastHistoryDay = simulation.day;
}
}
// -------------------------------------------------------------------------
// UI references and event handlers
// -------------------------------------------------------------------------
const routeToggle = document.getElementById("routeToggle");
const toggleLabel = document.getElementById("toggleLabel");
const routeBadge = document.getElementById("routeBadge");
const routeStatus = document.getElementById("routeStatus");
const routeDot = document.getElementById("routeDot");
const description = document.getElementById("description");
const dayValue = document.getElementById("dayValue");
const stockCard = document.getElementById("stockCard");
const stockValue = document.getElementById("stockValue");
const stockFill = document.getElementById("stockFill");
const backlogCard = document.getElementById("backlogCard");
const backlogValue = document.getElementById("backlogValue");
const arrivalValue = document.getElementById("arrivalValue");
const sourceValue = document.getElementById("sourceValue");
const unmetValue = document.getElementById("unmetValue");
const pauseButton = document.getElementById("pauseButton");
const resetButton = document.getElementById("resetButton");
const eventLog = document.getElementById("eventLog");
const stockChart = document.getElementById("stockChart");
routeToggle.addEventListener("click", () => {
simulation.routeOpen = !simulation.routeOpen;
if (!simulation.routeOpen) {
simulation.cutMarks.push(simulation.day);
addLog("Checkpoint B closed; in-transit cargo is frozen.", "critical");
} else {
addLog("Checkpoint B reopened; the convoy can resume transit.", "success");
}
updateUI();
});
document.querySelectorAll(".speed-button").forEach((button) => {
button.addEventListener("click", () => {
simulation.speed = Number(button.dataset.speed);
document.querySelectorAll(".speed-button").forEach((other) => {
other.classList.toggle("active", other === button);
});
});
});
pauseButton.addEventListener("click", () => {
simulation.paused = !simulation.paused;
pauseButton.textContent = simulation.paused ? "Resume" : "Pause";
pauseButton.classList.toggle("active", simulation.paused);
});
resetButton.addEventListener("click", () => {
simulation = makeState();
pauseButton.textContent = "Pause";
pauseButton.classList.remove("active");
document.querySelectorAll(".speed-button").forEach((button) => {
button.classList.toggle("active", button.dataset.speed === "1");
});
addLog("Scenario reset. Island inventory restored to 72 crates.", "info");
updateUI();
});
function formatDay(day) {
return day.toFixed(1).padStart(5, "0");
}
function deliveryETA() {
const vehicle = simulation.truck;
if (vehicle.phase === "outbound") {
if (!simulation.routeOpen && vehicle.progress <= gateProgress) {
return "Gate";
}
return `${((1 - vehicle.progress) * OUTBOUND_DAYS).toFixed(1)}d`;
}
if (vehicle.phase === "docked") return "Now";
if (vehicle.phase === "returning") return "Return";
if (vehicle.phase === "loading") return "Load";
return "Empty";
}
function updateLog() {
eventLog.innerHTML = simulation.logs
.map(
(entry) => `
<li class="${entry.tone}">
<span class="event-time">D${formatDay(entry.day)}</span>
<span class="event-message">${entry.message}</span>
</li>
`
)
.join("");
}
let lastLogVersion = -1;
function updateUI() {
const stockRatio = simulation.stock / simulation.capacity;
const shortage = simulation.backlog > 0.01;
dayValue.textContent = formatDay(simulation.day);
stockValue.textContent = Math.floor(simulation.stock);
stockFill.style.width = `${Math.max(0, stockRatio * 100)}%`;
if (stockRatio < 0.22) {
stockFill.style.background = "#ff7167";
stockCard.classList.add("critical");
} else if (stockRatio < 0.45) {
stockFill.style.background = "#ffb85c";
stockCard.classList.remove("critical");
} else {
stockFill.style.background = "#69e2c3";
stockCard.classList.remove("critical");
}
backlogValue.textContent = Math.floor(simulation.backlog);
backlogCard.classList.toggle("critical", shortage);
arrivalValue.textContent = deliveryETA();
sourceValue.textContent = Math.floor(simulation.source);
unmetValue.textContent = Math.floor(simulation.unmetTotal);
if (simulation.routeOpen) {
routeBadge.textContent = "Live";
routeBadge.classList.remove("cut");
routeStatus.textContent = "Route live";
routeDot.classList.remove("cut");
routeToggle.classList.remove("cut");
toggleLabel.textContent = "Interrupt route";
routeToggle.querySelector(".button-glyph").textContent = "×";
description.textContent = shortage
? "The route is live, but a shipment must still complete transit before the shortage is relieved."
: "Interrupt the causeway now. The island keeps consuming its finite inventory, so shortages appear only after the buffer runs out.";
} else {
routeBadge.textContent = "Cut";
routeBadge.classList.add("cut");
routeStatus.textContent = "Route interrupted";
routeDot.classList.add("cut");
routeToggle.classList.add("cut");
toggleLabel.textContent = "Reopen route";
routeToggle.querySelector(".button-glyph").textContent = "▶";
description.textContent = shortage
? "Shortage active. Reopening the route starts a transit delay before relief arrives."
: "Checkpoint B is down. Existing stock is still being consumed while the in-transit shipment waits.";
}
if (lastLogVersion !== simulation.logVersion) {
updateLog();
lastLogVersion = simulation.logVersion;
}
drawChart();
}
// -------------------------------------------------------------------------
// Inventory chart
// -------------------------------------------------------------------------
const chartContext = stockChart.getContext("2d");
function drawChart() {
const rect = stockChart.getBoundingClientRect();
const width = Math.max(1, rect.width);
const height = Math.max(1, rect.height);
const ratio = Math.min(window.devicePixelRatio || 1, 2);
stockChart.width = Math.floor(width * ratio);
stockChart.height = Math.floor(height * ratio);
chartContext.setTransform(ratio, 0, 0, ratio, 0, 0);
chartContext.clearRect(0, 0, width, height);
const padLeft = 7;
const padRight = 7;
const padTop = 10;
const padBottom = 15;
const plotWidth = width - padLeft - padRight;
const plotHeight = height - padTop - padBottom;
const maxDay = Math.max(12, simulation.day + 3);
const xFor = (day) => padLeft + (day / maxDay) * plotWidth;
const yFor = (stock) =>
padTop + plotHeight - (stock / simulation.capacity) * plotHeight;
chartContext.strokeStyle = "rgba(220, 245, 240, 0.09)";
chartContext.lineWidth = 1;
for (let i = 0; i <= 3; i++) {
const y = padTop + (plotHeight * i) / 3;
chartContext.beginPath();
chartContext.moveTo(padLeft, y);
chartContext.lineTo(width - padRight, y);
chartContext.stroke();
}
chartContext.setLineDash([3, 4]);
chartContext.strokeStyle = "rgba(255, 184, 92, 0.35)";
chartContext.beginPath();
chartContext.moveTo(padLeft, yFor(simulation.capacity));
chartContext.lineTo(width - padRight, yFor(simulation.capacity));
chartContext.stroke();
chartContext.setLineDash([]);
const history = simulation.history;
if (!history.length) return;
const gradient = chartContext.createLinearGradient(0, padTop, 0, height);
gradient.addColorStop(0, "rgba(105, 226, 195, 0.22)");
gradient.addColorStop(1, "rgba(105, 226, 195, 0)");
chartContext.beginPath();
chartContext.moveTo(xFor(history[0].day), yFor(history[0].stock));
history.forEach((point) => {
chartContext.lineTo(xFor(point.day), yFor(point.stock));
});
chartContext.lineTo(xFor(history[history.length - 1].day), yFor(0));
chartContext.lineTo(xFor(history[0].day), yFor(0));
chartContext.closePath();
chartContext.fillStyle = gradient;
chartContext.fill();
chartContext.beginPath();
history.forEach((point, index) => {
if (index === 0) {
chartContext.moveTo(xFor(point.day), yFor(point.stock));
} else {
chartContext.lineTo(xFor(point.day), yFor(point.stock));
}
});
chartContext.strokeStyle =
simulation.stock <= 0 ? "#ff7167" : "#69e2c3";
chartContext.lineWidth = 2;
chartContext.stroke();
simulation.cutMarks.forEach((day) => {
const x = xFor(day);
chartContext.strokeStyle = "rgba(255, 113, 103, 0.65)";
chartContext.lineWidth = 1;
chartContext.setLineDash([2, 3]);
chartContext.beginPath();
chartContext.moveTo(x, padTop);
chartContext.lineTo(x, height - padBottom);
chartContext.stroke();
chartContext.setLineDash([]);
chartContext.fillStyle = "#ff7167";
chartContext.font = "700 7px ui-monospace, monospace";
chartContext.fillText("CUT", x + 3, padTop + 7);
});
chartContext.fillStyle = "rgba(220, 245, 240, 0.46)";
chartContext.font = "7px ui-monospace, monospace";
chartContext.fillText("0d", padLeft, height - 3);
chartContext.textAlign = "right";
chartContext.fillText(`${maxDay.toFixed(0)}d`, width - padRight, height - 3);
chartContext.textAlign = "left";
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, wheel zoom, pinch zoom, keyboard
// -------------------------------------------------------------------------
const cameraControl = {
target: new THREE.Vector3(-1.5, 1.1, 0),
goal: {
radius: 44,
theta: 0.7,
phi: 0.88
},
current: {
radius: 44,
theta: 0.7,
phi: 0.88
}
};
const pointers = new Map();
let pinchDistance = 0;
function pointerDistance() {
const points = [...pointers.values()];
if (points.length < 2) return 0;
return Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
pinchDistance = pointerDistance();
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const current = { x: event.clientX, y: event.clientY };
pointers.set(event.pointerId, current);
if (pointers.size === 1) {
const dx = current.x - previous.x;
const dy = current.y - previous.y;
cameraControl.goal.theta -= dx * 0.006;
cameraControl.goal.phi = THREE.MathUtils.clamp(
cameraControl.goal.phi - dy * 0.005,
0.36,
1.34
);
} else if (pointers.size >= 2) {
const nextDistance = pointerDistance();
if (pinchDistance > 0 && nextDistance > 0) {
cameraControl.goal.radius = THREE.MathUtils.clamp(
cameraControl.goal.radius * (pinchDistance / nextDistance),
23,
67
);
}
pinchDistance = nextDistance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
pinchDistance = pointers.size >= 2 ? pointerDistance() : 0;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("pointerleave", releasePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControl.goal.radius = THREE.MathUtils.clamp(
cameraControl.goal.radius * Math.exp(event.deltaY * 0.001),
23,
67
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraControl.goal.radius = 44;
cameraControl.goal.theta = 0.7;
cameraControl.goal.phi = 0.88;
});
window.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") cameraControl.goal.theta -= 0.08;
if (event.key === "ArrowRight") cameraControl.goal.theta += 0.08;
if (event.key === "ArrowUp") {
cameraControl.goal.phi = Math.max(0.36, cameraControl.goal.phi - 0.06);
}
if (event.key === "ArrowDown") {
cameraControl.goal.phi = Math.min(1.34, cameraControl.goal.phi + 0.06);
}
});
function updateCamera() {
const easing = 0.09;
cameraControl.current.radius = THREE.MathUtils.lerp(
cameraControl.current.radius,
cameraControl.goal.radius,
easing
);
cameraControl.current.theta = THREE.MathUtils.lerp(
cameraControl.current.theta,
cameraControl.goal.theta,
easing
);
cameraControl.current.phi = THREE.MathUtils.lerp(
cameraControl.current.phi,
cameraControl.goal.phi,
easing
);
const { radius, theta, phi } = cameraControl.current;
camera.position.set(
cameraControl.target.x + radius * Math.sin(phi) * Math.sin(theta),
cameraControl.target.y + radius * Math.cos(phi),
cameraControl.target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(cameraControl.target);
}
// -------------------------------------------------------------------------
// Dynamic scene state
// -------------------------------------------------------------------------
function updateSceneState(dt, elapsed) {
const stockRatio = simulation.stock / simulation.capacity;
const visibleCrates = Math.ceil(simulation.stock / 10);
const shortage = simulation.backlog > 0.01;
stockCrates.forEach((crate, index) => {
crate.visible = index < visibleCrates;
const color =
stockRatio < 0.22
? 0xff7167
: stockRatio < 0.45
? 0xffb85c
: 0x69cfae;
crate.material.color.setHex(color);
});
warningBeacons.forEach((beacon, index) => {
beacon.visible = shortage;
beacon.material.emissiveIntensity =
1.1 + Math.sin(elapsed * 5 + index) * 0.65;
});
shortageLabel.visible = shortage;
const targetGateRotation = simulation.routeOpen ? 0 : -Math.PI / 2;
const targetGateHeight = simulation.routeOpen ? 1.23 : 0.58;
const gateEase = 1 - Math.exp(-dt * 8);
gatePivot.rotation.z = THREE.MathUtils.lerp(
gatePivot.rotation.z,
targetGateRotation,
gateEase
);
gatePivot.position.y = THREE.MathUtils.lerp(
gatePivot.position.y,
targetGateHeight,
gateEase
);
if (simulation.routeOpen) {
routeMarkerMaterial.color.setHex(0x69e2c3);
routeMarkerMaterial.emissive.setHex(0x2f9f83);
routeSignalMaterial.color.setHex(0x69e2c3);
routeSignalMaterial.emissive.setHex(0x38b998);
} else {
routeMarkerMaterial.color.setHex(0xff7167);
routeMarkerMaterial.emissive.setHex(0x9b302d);
routeSignalMaterial.color.setHex(0xff7167);
routeSignalMaterial.emissive.setHex(0xa9322e);
}
routeMarkerMaterial.emissiveIntensity =
0.45 + (simulation.routeOpen ? Math.sin(elapsed * 3) * 0.2 : 0.2);
const position = routePosition(simulation.truck.progress);
truck.position.set(position.x, 0.63, position.z);
const returning =
simulation.truck.phase === "returning" ||
simulation.truck.phase === "loading";
truck.rotation.y = position.angle + (returning ? Math.PI : 0);
cargoGroup.visible =
simulation.truck.phase === "outbound" && simulation.truck.load > 0;
waveMeshes.forEach((wave, index) => {
wave.position.x += wave.userData.speed * dt;
if (wave.position.x > 31) {
wave.position.x = -31;
wave.position.z = -27 + hash(index, simulation.day) * 54;
}
});
clouds.forEach((cloud) => {
cloud.position.x += cloud.userData.speed * dt;
if (cloud.position.x > 29) {
cloud.position.x = -29;
}
});
const positions = waterGeometry.attributes.position;
for (let i = 0; i < positions.count; i++) {
const x = positions.getX(i);
const z = positions.getZ(i);
positions.setY(
i,
Math.sin(x * 0.38 + elapsed * 0.75) * 0.025 +
Math.cos(z * 0.31 + elapsed * 0.55) * 0.018
);
}
positions.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Resize and main loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
drawChart();
});
const clock = new THREE.Clock();
let uiTimer = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
simulate(dt);
updateCamera();
updateSceneState(dt, elapsed);
uiTimer += dt;
if (uiTimer > 0.08) {
uiTimer = 0;
updateUI();
}
renderer.render(scene, camera);
}
updateUI();
updateCamera();
animate();
</script>
</body>
</html>
```