Prompt specification
Build or customize the Three.js 3D scene "Road Closure Route Replanning" 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: Road Closure Route Replanning
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/road-closure-route-replanning-x3596
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts weighted routes and travel costs. Create a delivery strategy puzzle where one route closes after planning. Recompute reachable paths and compare revised costs without teleporting couriers across blocked links. Voxel style.
Working Three.js Starter (road-closure-route-replanning-x3596):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BlockShift — The 17:00 Switch</title>
<style>
:root {
--bg: #08101d;
--panel: #0d1626;
--panel-2: #121f32;
--line: #25344a;
--text: #edf4ff;
--muted: #8fa1b8;
--cyan: #43e0c8;
--amber: #ffb454;
--violet: #b990ff;
--red: #ff5f6d;
--green: #8ee66b;
}
* {
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;
}
button {
color: inherit;
}
#app {
display: grid;
grid-template-columns: 350px 1fr;
width: 100%;
height: 100%;
}
.panel {
position: relative;
z-index: 10;
display: flex;
flex-direction: column;
min-height: 0;
padding: 24px 22px 18px;
overflow-y: auto;
background:
linear-gradient(180deg, rgba(16, 29, 48, 0.98), rgba(8, 16, 29, 0.99)),
repeating-linear-gradient(
90deg,
transparent 0,
transparent 39px,
rgba(255, 255, 255, 0.02) 40px
);
border-right: 1px solid var(--line);
box-shadow: 18px 0 50px rgba(0, 0, 0, 0.25);
}
.brand {
display: flex;
align-items: center;
gap: 11px;
margin-bottom: 22px;
}
.brand-mark {
position: relative;
width: 34px;
height: 34px;
transform: rotate(-8deg);
}
.brand-mark i {
position: absolute;
display: block;
width: 14px;
height: 14px;
background: var(--cyan);
box-shadow: 0 0 18px rgba(67, 224, 200, 0.3);
}
.brand-mark i:nth-child(1) {
left: 1px;
top: 1px;
}
.brand-mark i:nth-child(2) {
right: 1px;
top: 1px;
background: var(--amber);
}
.brand-mark i:nth-child(3) {
left: 1px;
bottom: 1px;
background: var(--violet);
}
.brand-mark i:nth-child(4) {
right: 1px;
bottom: 1px;
background: #d9e7f6;
}
.eyebrow {
margin: 0 0 4px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.brand-name {
font-size: 15px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(28px, 3vw, 38px);
line-height: 0.98;
letter-spacing: -0.045em;
}
.intro {
margin: 14px 0 19px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.objective {
position: relative;
margin-bottom: 20px;
padding: 15px 15px 14px;
overflow: hidden;
background: linear-gradient(135deg, rgba(67, 224, 200, 0.09), rgba(18, 31, 50, 0.8));
border: 1px solid #294258;
border-left: 3px solid var(--cyan);
border-radius: 10px;
}
.objective::after {
content: "";
position: absolute;
right: -22px;
bottom: -30px;
width: 86px;
height: 86px;
border: 12px solid rgba(67, 224, 200, 0.05);
transform: rotate(12deg);
}
.objective small {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.objective strong {
display: block;
margin: 6px 0 4px;
font-size: 14px;
}
.objective p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 0 10px;
color: #bdcadd;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.section-label span {
color: #61738b;
font-size: 9px;
}
.strategy {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 22px;
}
.strategy button {
padding: 10px 8px;
cursor: pointer;
background: #111e31;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--muted);
font-size: 11px;
font-weight: 750;
transition: 160ms ease;
}
.strategy button:hover {
color: var(--text);
border-color: #486078;
transform: translateY(-1px);
}
.strategy button.active {
color: var(--cyan);
background: rgba(67, 224, 200, 0.08);
border-color: rgba(67, 224, 200, 0.55);
box-shadow: inset 0 0 0 1px rgba(67, 224, 200, 0.08);
}
.orders {
display: grid;
gap: 9px;
margin-bottom: 20px;
}
.order-card {
position: relative;
padding: 13px 13px 12px 16px;
overflow: hidden;
background: rgba(16, 28, 46, 0.8);
border: 1px solid #223147;
border-radius: 10px;
}
.order-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--order-color);
}
.order-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.courier-id {
display: flex;
align-items: center;
gap: 8px;
}
.courier-dot {
width: 9px;
height: 9px;
background: var(--order-color);
box-shadow: 0 0 10px color-mix(in srgb, var(--order-color), transparent 35%);
}
.courier-name {
font-size: 12px;
font-weight: 850;
letter-spacing: 0.05em;
}
.order-status {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.order-card.rerouted .order-status {
color: var(--amber);
}
.order-card.delivered .order-status {
color: var(--green);
}
.order-route {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
margin-top: 9px;
color: #c6d2e2;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
}
.route-node {
padding: 3px 5px;
background: #0a1424;
border: 1px solid #29394f;
border-radius: 4px;
}
.route-arrow {
color: #586b83;
}
.order-meta {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 10px;
color: var(--muted);
font-size: 10px;
}
.order-meta strong {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
}
.actions {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: auto;
padding-top: 4px;
}
.primary,
.secondary,
.speed-button {
border-radius: 8px;
cursor: pointer;
transition: 160ms ease;
}
.primary {
padding: 13px 15px;
background: var(--cyan);
border: 1px solid var(--cyan);
color: #06131a;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
box-shadow: 0 8px 24px rgba(67, 224, 200, 0.12);
}
.primary:hover {
transform: translateY(-1px);
box-shadow: 0 10px 28px rgba(67, 224, 200, 0.22);
}
.primary.pause {
background: var(--amber);
border-color: var(--amber);
}
.secondary {
min-width: 48px;
padding: 10px 12px;
background: #142136;
border: 1px solid #2b3c54;
color: #c5d1e0;
font-size: 11px;
font-weight: 800;
}
.secondary:hover {
background: #1b2b43;
}
.panel-foot {
margin-top: 14px;
color: #65788f;
font-size: 10px;
line-height: 1.5;
}
.panel-foot kbd {
padding: 1px 5px;
background: #17253a;
border: 1px solid #2c3d55;
border-radius: 4px;
color: #aebed0;
font-family: inherit;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, rgba(45, 75, 104, 0.16), transparent 55%),
#08101d;
}
#scene {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
touch-action: none;
}
#scene:active {
cursor: grabbing;
}
.hud {
position: absolute;
z-index: 3;
pointer-events: none;
}
.scene-top {
top: 20px;
left: 22px;
right: 22px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 15px;
}
.location {
display: flex;
align-items: center;
gap: 9px;
padding: 9px 12px;
background: rgba(8, 17, 30, 0.78);
border: 1px solid rgba(76, 99, 127, 0.48);
border-radius: 8px;
backdrop-filter: blur(12px);
color: #b7c8db;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.live-dot {
width: 7px;
height: 7px;
background: var(--cyan);
box-shadow: 0 0 11px var(--cyan);
border-radius: 50%;
}
.speed-button {
pointer-events: auto;
padding: 9px 12px;
background: rgba(8, 17, 30, 0.78);
border: 1px solid rgba(76, 99, 127, 0.48);
color: #b7c8db;
font-size: 10px;
font-weight: 850;
backdrop-filter: blur(12px);
}
.cost-board {
top: 74px;
right: 22px;
width: 246px;
padding: 16px;
background: rgba(9, 18, 32, 0.84);
border: 1px solid rgba(70, 91, 118, 0.5);
border-radius: 12px;
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(14px);
}
.cost-board h2 {
margin: 0 0 14px;
color: #a6b8cd;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
padding: 11px;
background: rgba(22, 36, 56, 0.7);
border: 1px solid #293b52;
border-radius: 8px;
}
.metric span {
display: block;
margin-bottom: 5px;
color: #7f94ad;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 22px;
}
.metric.delta strong {
color: var(--amber);
}
.budget-line {
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid #26364b;
}
.budget-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: #8da1b9;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.budget-track {
height: 6px;
overflow: hidden;
background: #1c2a3d;
border-radius: 99px;
}
.budget-fill {
width: 74%;
height: 100%;
background: linear-gradient(90deg, var(--cyan), var(--amber));
border-radius: inherit;
transition: width 300ms ease;
}
.timeline {
left: 22px;
bottom: 22px;
width: 280px;
padding: 14px 16px;
background: rgba(8, 17, 30, 0.82);
border: 1px solid rgba(70, 91, 118, 0.45);
border-radius: 11px;
backdrop-filter: blur(14px);
}
.timeline-item {
position: relative;
display: grid;
grid-template-columns: 14px 1fr auto;
gap: 9px;
align-items: center;
min-height: 27px;
color: #70849d;
font-size: 10px;
}
.timeline-item::before {
content: "";
position: relative;
z-index: 1;
width: 8px;
height: 8px;
margin-left: 2px;
background: #33445a;
border: 2px solid #101c2d;
box-sizing: content-box;
border-radius: 50%;
}
.timeline-item.done {
color: #b9c8d9;
}
.timeline-item.done::before {
background: var(--cyan);
box-shadow: 0 0 9px rgba(67, 224, 200, 0.45);
}
.timeline-item.active {
color: var(--amber);
}
.timeline-item.active::before {
background: var(--amber);
box-shadow: 0 0 10px rgba(255, 180, 84, 0.55);
}
.timeline-item small {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.legend {
right: 22px;
bottom: 22px;
display: flex;
gap: 13px;
padding: 10px 13px;
background: rgba(8, 17, 30, 0.76);
border: 1px solid rgba(70, 91, 118, 0.4);
border-radius: 8px;
color: #8498af;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
backdrop-filter: blur(12px);
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-swatch {
width: 15px;
height: 4px;
background: var(--swatch);
box-shadow: 0 0 7px color-mix(in srgb, var(--swatch), transparent 40%);
}
.camera-hint {
right: 23px;
bottom: 67px;
color: rgba(160, 178, 199, 0.62);
font-size: 9px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
#toast {
position: absolute;
z-index: 8;
top: 78px;
left: 50%;
width: min(420px, calc(100% - 40px));
padding: 15px 18px;
opacity: 0;
pointer-events: none;
background: rgba(12, 22, 37, 0.94);
border: 1px solid rgba(255, 95, 109, 0.55);
border-left: 4px solid var(--red);
border-radius: 9px;
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.35);
transform: translate(-50%, -14px);
transition: 260ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.reroute {
border-color: rgba(255, 180, 84, 0.55);
border-left-color: var(--amber);
}
#toast strong {
display: block;
margin-bottom: 4px;
font-size: 11px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#toast span {
color: #a8b8ca;
font-size: 11px;
line-height: 1.45;
}
@media (max-width: 900px) {
#app {
grid-template-columns: 310px 1fr;
}
.panel {
padding: 20px 17px 16px;
}
.cost-board {
right: 14px;
width: 218px;
}
.scene-top {
left: 14px;
right: 14px;
}
.timeline {
left: 14px;
bottom: 14px;
}
.legend,
.camera-hint {
right: 14px;
}
}
@media (max-width: 680px) {
html,
body {
overflow: auto;
}
#app {
display: flex;
flex-direction: column;
height: auto;
min-height: 100%;
}
#viewport {
order: 0;
height: 62vh;
min-height: 480px;
}
.panel {
order: 1;
overflow: visible;
border-right: 0;
border-top: 1px solid var(--line);
}
.cost-board {
top: 65px;
width: 190px;
padding: 12px;
}
.metric strong {
font-size: 18px;
}
.timeline {
width: 245px;
}
.legend,
.camera-hint {
display: none;
}
}
</style>
</head>
<body>
<div id="app">
<aside class="panel">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i>
</div>
<div>
<p class="eyebrow">Tactical logistics lab</p>
<div class="brand-name">BlockShift</div>
</div>
</div>
<p class="eyebrow">Case 07 / Network contingency</p>
<h1>The 17:00<br />Switch</h1>
<p class="intro">
Three couriers. One committed plan. A street closure after dispatch.
Reprice the remaining work without skipping a single blocked block.
</p>
<section class="objective">
<small>Delivery objective</small>
<strong>Deliver all three drops for ≤ 42 credits</strong>
<p>
If the route fails, couriers continue from their current position and
follow a newly calculated open path.
</p>
</section>
<div class="section-label">
Planning policy
<span>Pre-dispatch</span>
</div>
<div class="strategy" role="group" aria-label="Planning policy">
<button class="active" data-policy="cost">Lowest cost</button>
<button data-policy="links">Fewest links</button>
</div>
<div class="section-label">
Fleet manifest
<span id="fleet-count">3 active couriers</span>
</div>
<div class="orders" id="orders"></div>
<div class="actions">
<button class="primary" id="dispatch">Commit & dispatch</button>
<button class="secondary" id="reset" title="Reset scenario">↺</button>
</div>
<div class="panel-foot">
<kbd>Space</kbd> dispatch / pause <kbd>R</kbd> reset<br />
Drag to orbit the voxel city. Scroll to zoom.
</div>
</aside>
<main id="viewport">
<canvas id="scene" aria-label="Interactive voxel delivery network"></canvas>
<div class="hud scene-top">
<div class="location">
<span class="live-dot" id="status-dot"></span>
<span id="status-text">Planning · routes priced</span>
</div>
<button class="speed-button" id="speed">1× speed</button>
</div>
<section class="hud cost-board" aria-label="Cost comparison">
<h2>Fleet cost board</h2>
<div class="metric-grid">
<div class="metric">
<span>Committed</span>
<strong id="planned-cost">31</strong>
</div>
<div class="metric">
<span>Revised</span>
<strong id="revised-cost">—</strong>
</div>
<div class="metric delta">
<span>Delta</span>
<strong id="delta-cost">—</strong>
</div>
<div class="metric">
<span>Delivered</span>
<strong id="delivered-count">0/3</strong>
</div>
</div>
<div class="budget-line">
<div class="budget-label">
<span>42-credit budget</span>
<span id="budget-value">31 planned</span>
</div>
<div class="budget-track">
<div class="budget-fill" id="budget-fill"></div>
</div>
</div>
</section>
<section class="hud timeline" aria-label="Scenario timeline">
<div class="timeline-item done" id="timeline-plan">
<span>Plan committed</span><small>READY</small>
</div>
<div class="timeline-item" id="timeline-close">
<span>Link failure</span><small>WAIT</small>
</div>
<div class="timeline-item" id="timeline-recalc">
<span>Recalculate</span><small>WAIT</small>
</div>
<div class="timeline-item" id="timeline-deliver">
<span>Complete drops</span><small>0/3</small>
</div>
</section>
<div class="hud legend">
<div class="legend-item">
<span class="legend-swatch" style="--swatch:#43e0c8"></span> Vela
</div>
<div class="legend-item">
<span class="legend-swatch" style="--swatch:#ffb454"></span> Rook
</div>
<div class="legend-item">
<span class="legend-swatch" style="--swatch:#b990ff"></span> Pip
</div>
</div>
<div class="hud camera-hint">Drag · orbit Scroll · zoom</div>
<div id="toast" role="status" aria-live="polite">
<strong id="toast-title"></strong>
<span id="toast-text"></span>
</div>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const viewport = $("#viewport");
const canvas = $("#scene");
// -------------------------------------------------------------------------
// Renderer, camera, and custom orbit controls. No external controls module.
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
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.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08101d);
scene.fog = new THREE.Fog(0x08101d, 27, 48);
const camera = new THREE.PerspectiveCamera(36, 1, 0.1, 100);
const orbit = {
target: new THREE.Vector3(0.5, 0, 0),
yaw: -0.64,
pitch: 0.76,
radius: 25.5,
dragging: false,
pointerX: 0,
pointerY: 0
};
function updateCamera() {
const horizontal = Math.cos(orbit.pitch) * orbit.radius;
camera.position.set(
orbit.target.x + Math.sin(orbit.yaw) * horizontal,
orbit.target.y + Math.sin(orbit.pitch) * orbit.radius,
orbit.target.z + Math.cos(orbit.yaw) * horizontal
);
camera.lookAt(orbit.target);
}
canvas.addEventListener("pointerdown", (event) => {
orbit.dragging = true;
orbit.pointerX = event.clientX;
orbit.pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!orbit.dragging) return;
const dx = event.clientX - orbit.pointerX;
const dy = event.clientY - orbit.pointerY;
orbit.pointerX = event.clientX;
orbit.pointerY = event.clientY;
orbit.yaw -= dx * 0.006;
orbit.pitch = THREE.MathUtils.clamp(orbit.pitch + dy * 0.004, 0.38, 1.25);
updateCamera();
});
function endDrag(event) {
orbit.dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.012,
15,
37
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Network model. All edge weights represent travel cost in credits.
// -------------------------------------------------------------------------
const nodes = {
A: { x: -8, z: 0, name: "West depot" },
B: { x: -5, z: -5, name: "Foundry" },
C: { x: -3, z: 4, name: "North market" },
D: { x: 1, z: 0, name: "Central hub" },
E: { x: 6, z: 1, name: "East yard" },
F: { x: 3, z: -5, name: "South works" },
G: { x: 7, z: 6, name: "Sky gardens" },
H: { x: 11, z: 4, name: "Final drop" }
};
const edges = [
{ a: "A", b: "B", w: 4 },
{ a: "A", b: "C", w: 5 },
{ a: "B", b: "D", w: 4 },
{ a: "C", b: "D", w: 2 },
{ a: "D", b: "E", w: 3 },
{ a: "D", b: "F", w: 6 },
{ a: "E", b: "F", w: 4 },
{ a: "E", b: "G", w: 5 },
{ a: "E", b: "H", w: 5 },
{ a: "F", b: "G", w: 6 },
{ a: "G", b: "H", w: 2 }
];
const adjacency = Object.fromEntries(
Object.keys(nodes).map((id) => [id, []])
);
for (const edge of edges) {
adjacency[edge.a].push({ to: edge.b, w: edge.w, edge });
adjacency[edge.b].push({ to: edge.a, w: edge.w, edge });
}
// Preserve this neighbor order so equal-hop routes have a deterministic tie.
adjacency.A = [
{ to: "C", w: 5, edge: edges[1] },
{ to: "B", w: 4, edge: edges[0] }
];
const orders = [
{
id: "C1",
name: "Vela",
order: "V-17",
from: "A",
to: "H",
color: 0x43e0c8,
css: "#43e0c8"
},
{
id: "C2",
name: "Rook",
order: "R-04",
from: "B",
to: "G",
color: 0xffb454,
css: "#ffb454"
},
{
id: "C3",
name: "Pip",
order: "P-09",
from: "F",
to: "E",
color: 0xb990ff,
css: "#b990ff"
}
];
const edgeKey = (a, b) => [a, b].sort().join("-");
const CLOSED_EDGE = edgeKey("D", "E");
const CLOSURE_TIME = 0.78;
const SECONDS_PER_CREDIT = 0.21;
// Dijkstra with either cost-first or link-first comparison.
function findPath(start, end, policy = "cost", blocked = new Set()) {
const distance = {};
const hops = {};
const previous = {};
const unvisited = new Set(Object.keys(nodes));
for (const id of unvisited) {
distance[id] = Infinity;
hops[id] = Infinity;
}
distance[start] = 0;
hops[start] = 0;
while (unvisited.size) {
let current = null;
for (const id of unvisited) {
if (current === null) {
current = id;
continue;
}
const better =
policy === "links"
? hops[id] < hops[current] ||
(hops[id] === hops[current] &&
distance[id] < distance[current])
: distance[id] < distance[current] ||
(distance[id] === distance[current] &&
hops[id] < hops[current]);
if (better) current = id;
}
if (!Number.isFinite(distance[current])) break;
unvisited.delete(current);
if (current === end) break;
for (const connection of adjacency[current]) {
if (unvisited.has(connection.to) === false) continue;
if (blocked.has(edgeKey(current, connection.to))) continue;
const nextDistance = distance[current] + connection.w;
const nextHops = hops[current] + 1;
const better =
policy === "links"
? nextHops < hops[connection.to] ||
(nextHops === hops[connection.to] &&
nextDistance < distance[connection.to])
: nextDistance < distance[connection.to] ||
(nextDistance === distance[connection.to] &&
nextHops < hops[connection.to]);
if (better) {
distance[connection.to] = nextDistance;
hops[connection.to] = nextHops;
previous[connection.to] = current;
}
}
}
if (!Number.isFinite(distance[end])) return { path: [], cost: Infinity };
const path = [end];
while (path[0] !== start) {
const prior = previous[path[0]];
if (!prior) return { path: [], cost: Infinity };
path.unshift(prior);
}
return { path, cost: distance[end] };
}
function pathCost(path) {
let total = 0;
for (let i = 0; i < path.length - 1; i++) {
const edge = edges.find(
(candidate) =>
edgeKey(candidate.a, candidate.b) ===
edgeKey(path[i], path[i + 1])
);
total += edge.w;
}
return total;
}
// -------------------------------------------------------------------------
// Voxel environment.
// -------------------------------------------------------------------------
const hemi = new THREE.HemisphereLight(0xa9d8ff, 0x1a2030, 2.1);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffefd4, 3.1);
sun.position.set(-11, 19, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -19;
sun.shadow.camera.right = 19;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.00025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x4aa8ff, 1.2);
rimLight.position.set(13, 9, -13);
scene.add(rimLight);
const base = new THREE.Mesh(
new THREE.BoxGeometry(27, 0.8, 22),
new THREE.MeshStandardMaterial({
color: 0x101b2c,
roughness: 0.9,
metalness: 0.05
})
);
base.position.set(0, -0.55, 0);
base.receiveShadow = true;
scene.add(base);
const grid = new THREE.GridHelper(26, 26, 0x26354b, 0x172438);
grid.position.y = -0.135;
grid.material.transparent = true;
grid.material.opacity = 0.5;
scene.add(grid);
function makeLabel(text, subtext = "", accent = "#dcecff", compact = false) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = compact ? 128 : 256;
labelCanvas.height = compact ? 64 : 128;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
const w = labelCanvas.width;
const h = labelCanvas.height;
const radius = compact ? 8 : 13;
ctx.beginPath();
ctx.moveTo(radius, 4);
ctx.lineTo(w - radius, 4);
ctx.quadraticCurveTo(w - 4, 4, w - 4, 4 + radius);
ctx.lineTo(w - 4, h - 4 - radius);
ctx.quadraticCurveTo(w - 4, h - 4, w - radius, h - 4);
ctx.lineTo(radius, h - 4);
ctx.quadraticCurveTo(4, h - 4, 4, h - 4 - radius);
ctx.lineTo(4, 4 + radius);
ctx.quadraticCurveTo(4, 4, radius, 4);
ctx.closePath();
ctx.fillStyle = "rgba(7, 15, 28, 0.92)";
ctx.fill();
ctx.strokeStyle = "rgba(104, 135, 169, 0.68)";
ctx.lineWidth = compact ? 2 : 3;
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = accent;
ctx.font = `800 ${compact ? 30 : 52}px ui-monospace, monospace`;
ctx.fillText(text, w / 2, subtext ? h * 0.38 : h / 2);
if (subtext) {
ctx.fillStyle = "#8fa7bf";
ctx.font = `700 ${compact ? 12 : 18}px system-ui, sans-serif`;
ctx.fillText(subtext.toUpperCase(), w / 2, h * 0.73);
}
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
const edgeVisuals = new Map();
for (const edge of edges) {
const a = nodes[edge.a];
const b = nodes[edge.b];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const angle = Math.atan2(dz, dx);
const group = new THREE.Group();
group.position.set((a.x + b.x) / 2, -0.065, (a.z + b.z) / 2);
group.rotation.y = -angle;
const roadMaterial = new THREE.MeshStandardMaterial({
color: 0x283446,
roughness: 0.92,
metalness: 0.02
});
const road = new THREE.Mesh(
new THREE.BoxGeometry(length + 0.35, 0.14, 1.08),
roadMaterial
);
road.receiveShadow = true;
group.add(road);
const curbMaterial = new THREE.MeshStandardMaterial({
color: 0x405069,
roughness: 0.95
});
for (const side of [-1, 1]) {
const curb = new THREE.Mesh(
new THREE.BoxGeometry(length + 0.32, 0.13, 0.14),
curbMaterial
);
curb.position.set(0, 0.015, side * 0.6);
curb.receiveShadow = true;
group.add(curb);
}
const dashMaterial = new THREE.MeshBasicMaterial({ color: 0x718198 });
const dashCount = Math.max(1, Math.floor(length / 1.25));
for (let i = 0; i < dashCount; i++) {
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.36, 0.025, 0.065),
dashMaterial
);
dash.position.set(
-length / 2 + ((i + 0.5) * length) / dashCount,
0.095,
0
);
group.add(dash);
}
scene.add(group);
const costLabel = makeLabel(
String(edge.w),
"",
edgeKey(edge.a, edge.b) === CLOSED_EDGE ? "#ff7b86" : "#dce9f7",
true
);
costLabel.position.set((a.x + b.x) / 2, 0.68, (a.z + b.z) / 2);
costLabel.scale.set(0.7, 0.35, 1);
scene.add(costLabel);
edgeVisuals.set(edgeKey(edge.a, edge.b), {
edge,
group,
road,
roadMaterial,
costLabel
});
}
// Small destination brackets around the three drop nodes.
for (const target of ["H", "G", "E"]) {
const node = nodes[target];
const marker = new THREE.Group();
marker.position.set(node.x, 0.15, node.z);
const material = new THREE.MeshBasicMaterial({ color: 0xffd479 });
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const corner = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.12, 0.12),
material
);
corner.position.set(sx * 0.73, 0, sz * 0.73);
marker.add(corner);
const cornerZ = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.12, 0.42),
material
);
cornerZ.position.set(sx * 0.73, 0, sz * 0.73);
marker.add(cornerZ);
}
}
scene.add(marker);
}
// Voxel buildings.
const buildingSpecs = [
[-10.5, 6, 2.3, 2.0, 3.2, 0x33445d],
[-6.8, 8.0, 2.5, 2.0, 4.4, 0x3d5069],
[-2.8, 8.2, 2.0, 2.0, 2.7, 0x2b3d55],
[1.2, 8.4, 2.5, 2.0, 3.7, 0x354760],
[5.0, 9.0, 2.0, 2.0, 2.4, 0x40566e],
[9.7, 8.1, 2.4, 2.0, 4.1, 0x33465f],
[-11.0, 3.2, 2.4, 2.0, 2.5, 0x41546b],
[-11.0, -3.0, 2.3, 2.5, 3.8, 0x30435c],
[-10.0, -7.1, 2.6, 2.0, 2.4, 0x3e5066],
[-6.0, -8.3, 2.3, 2.0, 3.6, 0x2b3c54],
[-2.0, -8.3, 2.2, 2.0, 4.2, 0x3a4e66],
[2.0, -8.1, 2.8, 2.0, 3.2, 0x31445e],
[6.2, -7.2, 2.4, 2.0, 4.0, 0x40546a],
[10.0, -6.0, 2.5, 2.0, 2.8, 0x2d4058],
[10.1, 0.0, 2.0, 3.0, 3.5, 0x3b4e67],
[4.0, 4.4, 1.6, 1.8, 2.5, 0x43576e],
[1.0, 5.2, 1.8, 1.6, 3.3, 0x30435c],
[-4.3, -1.3, 2.0, 2.0, 3.0, 0x3b4d63],
[-0.3, -2.2, 2.0, 1.8, 2.8, 0x2c4059],
[4.2, -2.5, 1.9, 1.9, 3.0, 0x40546a]
];
function addBuilding(spec) {
const [x, z, width, depth, height, color] = spec;
const building = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({
color,
roughness: 0.84,
metalness: 0.03
})
);
building.position.set(x, height / 2 - 0.14, z);
building.castShadow = true;
building.receiveShadow = true;
scene.add(building);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(width + 0.16, 0.18, depth + 0.16),
new THREE.MeshStandardMaterial({
color: 0x536a82,
roughness: 0.9
})
);
roof.position.set(x, height - 0.05, z);
roof.castShadow = true;
scene.add(roof);
const utility = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.26, 0.34, depth * 0.3),
new THREE.MeshStandardMaterial({
color: 0x25364a,
roughness: 0.8
})
);
utility.position.set(x + width * 0.18, height + 0.2, z);
utility.castShadow = true;
scene.add(utility);
const windowMaterial = new THREE.MeshBasicMaterial({
color: 0x70a8bd,
transparent: true,
opacity: 0.55
});
for (let row = 0; row < Math.max(1, Math.floor(height / 1.2)); row++) {
for (let column = -1; column <= 1; column += 2) {
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.13, 0.17, 0.03),
windowMaterial
);
windowMesh.position.set(
x + column * width * 0.23,
0.45 + row * 0.92,
z + depth / 2 + 0.018
);
scene.add(windowMesh);
}
}
}
buildingSpecs.forEach(addBuilding);
// A few blocky trees.
const treeMaterial = new THREE.MeshStandardMaterial({
color: 0x2c665d,
roughness: 1
});
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x59483e,
roughness: 1
});
for (const [x, z] of [
[-12, 7], [-12, -6], [-7.5, -8.5], [0, -8.5],
[8.5, -7.5], [11.8, 7], [4.5, 8.7], [-4.8, 7.3]
]) {
const trunk = new THREE.Mesh(
new THREE.BoxGeometry(0.22, 0.7, 0.22),
trunkMaterial
);
trunk.position.set(x, 0.2, z);
trunk.castShadow = true;
scene.add(trunk);
const crown = new THREE.Mesh(
new THREE.BoxGeometry(0.8, 0.9, 0.8),
treeMaterial
);
crown.position.set(x, 0.95, z);
crown.castShadow = true;
scene.add(crown);
}
// Network hubs.
for (const [id, node] of Object.entries(nodes)) {
const hub = new THREE.Group();
hub.position.set(node.x, 0, node.z);
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(1.25, 0.28, 1.25),
new THREE.MeshStandardMaterial({
color: 0x44556c,
roughness: 0.72,
metalness: 0.12
})
);
pedestal.position.y = 0.05;
pedestal.castShadow = true;
pedestal.receiveShadow = true;
hub.add(pedestal);
const top = new THREE.Mesh(
new THREE.BoxGeometry(0.82, 0.12, 0.82),
new THREE.MeshStandardMaterial({
color: 0xa9bfd2,
emissive: 0x29465a,
emissiveIntensity: 0.55,
roughness: 0.5
})
);
top.position.y = 0.24;
top.castShadow = true;
hub.add(top);
scene.add(hub);
const label = makeLabel(id, node.name, "#edf7ff");
label.position.set(node.x, 1.25, node.z);
label.scale.set(1.15, 0.575, 1);
scene.add(label);
}
// Closure barricade for D–E.
const closureVisual = new THREE.Group();
{
const d = nodes.D;
const e = nodes.E;
closureVisual.position.set((d.x + e.x) / 2, 0, (d.z + e.z) / 2);
closureVisual.rotation.y = -Math.atan2(e.z - d.z, e.x - d.x);
const dark = new THREE.MeshStandardMaterial({ color: 0x1a2432 });
const red = new THREE.MeshStandardMaterial({
color: 0xff4f5f,
emissive: 0x7a1520,
emissiveIntensity: 0.65
});
const white = new THREE.MeshStandardMaterial({ color: 0xe8f2ff });
for (const side of [-1, 1]) {
const support = new THREE.Mesh(
new THREE.BoxGeometry(0.22, 1.0, 0.22),
dark
);
support.position.set(side * 0.8, 0.5, 0);
support.castShadow = true;
closureVisual.add(support);
}
for (let i = 0; i < 6; i++) {
const stripe = new THREE.Mesh(
new THREE.BoxGeometry(0.3, 0.23, 0.24),
i % 2 ? white : red
);
stripe.position.set(-0.75 + i * 0.3, 0.72, 0);
stripe.rotation.z = -0.25;
closureVisual.add(stripe);
}
const closedLabel = makeLabel("CLOSED", "D → E", "#ff7b86");
closedLabel.position.set(0, 1.65, 0);
closedLabel.scale.set(1.35, 0.675, 1);
closureVisual.add(closedLabel);
closureVisual.visible = false;
scene.add(closureVisual);
}
// -------------------------------------------------------------------------
// Courier models and route overlays.
// -------------------------------------------------------------------------
function createCourier(order, index) {
const group = new THREE.Group();
const start = nodes[order.from];
const bodyMaterial = new THREE.MeshStandardMaterial({
color: order.color,
emissive: order.color,
emissiveIntensity: 0.12,
roughness: 0.55,
metalness: 0.12
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x172131,
roughness: 0.8
});
const lightMaterial = new THREE.MeshStandardMaterial({
color: 0xdcecf8,
roughness: 0.55
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.7, 0.6, 0.78),
bodyMaterial
);
body.position.y = 0.65;
body.castShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(0.76, 0.16, 0.82),
lightMaterial
);
roof.position.y = 1.02;
roof.castShadow = true;
group.add(roof);
const head = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.4, 0.42),
bodyMaterial
);
head.position.set(0, 1.29, 0);
head.castShadow = true;
group.add(head);
const cargo = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.35, 0.42),
new THREE.MeshStandardMaterial({
color: 0xc79355,
roughness: 0.85
})
);
cargo.position.set(0, 1.12, -0.54);
cargo.castShadow = true;
group.add(cargo);
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const wheel = new THREE.Mesh(
new THREE.BoxGeometry(0.2, 0.24, 0.2),
darkMaterial
);
wheel.position.set(sx * 0.39, 0.27, sz * 0.25);
wheel.castShadow = true;
group.add(wheel);
}
}
const label = makeLabel(order.id, order.name, order.css);
label.position.set(0, 2.05, 0);
label.scale.set(0.8, 0.4, 1);
group.add(label);
group.position.set(start.x, 0.18, start.z);
scene.add(group);
return { group, body };
}
const courierVisuals = orders.map(createCourier);
function clearGroup(group) {
for (const child of [...group.children]) {
group.remove(child);
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) object.material.dispose();
});
}
}
function addRouteStrip(group, a, b, color, opacity, height) {
const nodeA = nodes[a];
const nodeB = nodes[b];
const dx = nodeB.x - nodeA.x;
const dz = nodeB.z - nodeA.z;
const length = Math.hypot(dx, dz);
const underlay = new THREE.Mesh(
new THREE.BoxGeometry(length - 0.2, 0.025, 0.34),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: opacity * 0.23,
depthWrite: false
})
);
underlay.position.set(
(nodeA.x + nodeB.x) / 2,
height,
(nodeA.z + nodeB.z) / 2
);
underlay.rotation.y = -Math.atan2(dz, dx);
group.add(underlay);
const core = new THREE.Mesh(
new THREE.BoxGeometry(length - 0.22, 0.055, 0.12),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false
})
);
core.position.copy(underlay.position);
core.position.y += 0.04;
core.rotation.y = underlay.rotation.y;
group.add(core);
}
function drawRoute(group, path, order, opacity, live = false) {
clearGroup(group);
for (let i = 0; i < path.length - 1; i++) {
addRouteStrip(
group,
path[i],
path[i + 1],
order.color,
opacity,
live ? 0.19 + i * 0.006 : 0.12 + i * 0.006
);
}
}
const plannedRouteGroups = orders.map(() => {
const group = new THREE.Group();
scene.add(group);
return group;
});
const liveRouteGroups = orders.map(() => {
const group = new THREE.Group();
group.visible = false;
scene.add(group);
return group;
});
// -------------------------------------------------------------------------
// Simulation state.
// -------------------------------------------------------------------------
let policy = "cost";
let phase = "planning";
let paused = false;
let closed = false;
let simTime = 0;
let speed = 1;
let planned = [];
let states = [];
let reroutedCount = 0;
let toastTimer = null;
function computePlan() {
planned = orders.map((order) =>
findPath(order.from, order.to, policy, new Set())
);
orders.forEach((order, index) => {
drawRoute(
plannedRouteGroups[index],
planned[index].path,
order,
phase === "planning" ? 0.62 : 0.2
);
});
updateUI();
}
function makeStates() {
states = orders.map((order, index) => ({
order,
path: planned[index].path.slice(),
segmentIndex: 0,
currentNode: order.from,
active: null,
progress: 0,
spent: 0,
status: "moving",
rerouted: false,
rerouteNode: null,
forecast: planned[index].cost
}));
states.forEach((state, index) => {
const visual = courierVisuals[index];
visual.group.position.set(
nodes[state.order.from].x,
0.18,
nodes[state.order.from].z
);
visual.group.rotation.y = 0;
beginSegment(state, index);
});
}
function beginSegment(state, index) {
if (state.segmentIndex >= state.path.length - 1) {
state.status = "delivered";
state.active = null;
return;
}
const from = state.path[state.segmentIndex];
const to = state.path[state.segmentIndex + 1];
const key = edgeKey(from, to);
if (closed && blockedEdges.has(key)) {
const revised = findPath(
state.currentNode,
state.order.to,
"cost",
blockedEdges
);
state.path = revised.path;
state.segmentIndex = 0;
state.rerouted = true;
state.rerouteNode = state.currentNode;
reroutedCount++;
drawRoute(
liveRouteGroups[index],
state.path,
state.order,
0.95,
true
);
showToast(
"Reroute confirmed",
`${state.order.name} is taking a new open path from ${state.currentNode}.`,
"reroute"
);
return beginSegment(state, index);
}
const edge = edges.find(
(candidate) => edgeKey(candidate.a, candidate.b) === key
);
state.active = {
from,
to,
key,
w: edge.w
};
state.progress = 0;
}
const blockedEdges = new Set();
function closeRoute() {
if (closed) return;
closed = true;
blockedEdges.add(CLOSED_EDGE);
const visual = edgeVisuals.get(CLOSED_EDGE);
visual.roadMaterial.color.setHex(0x6c2d39);
visual.roadMaterial.emissive.setHex(0x3c0b12);
visual.roadMaterial.emissiveIntensity = 0.45;
visual.costLabel.material.color.setHex(0xff8790);
closureVisual.visible = true;
showToast(
"Route closed: D → E",
"Both affected couriers will recalculate when they reach their next open hub.",
"closure"
);
}
function updateSimulation(dt) {
if (phase !== "live" || paused) return;
simTime += dt;
if (!closed && simTime >= CLOSURE_TIME) {
closeRoute();
}
states.forEach((state, index) => {
if (state.status === "delivered") return;
if (!state.active) {
beginSegment(state, index);
return;
}
const edge = state.active;
const duration = edge.w * SECONDS_PER_CREDIT / speed;
state.progress += dt / duration;
if (state.progress >= 1) {
state.spent += edge.w;
state.currentNode = edge.to;
state.active = null;
state.progress = 0;
if (state.currentNode === state.order.to) {
state.status = "delivered";
} else {
state.segmentIndex++;
beginSegment(state, index);
}
}
});
}
function updateCourierVisuals(time) {
states.forEach((state, index) => {
const visual = courierVisuals[index];
if (!state.active) return;
const a = nodes[state.active.from];
const b = nodes[state.active.to];
const t = Math.min(1, state.progress);
const x = THREE.MathUtils.lerp(a.x, b.x, t);
const z = THREE.MathUtils.lerp(a.z, b.z, t);
const bob = Math.sin(time * 11 + index) * 0.025;
visual.group.position.set(x, 0.18 + bob, z);
visual.group.rotation.y = Math.atan2(b.x - a.x, b.z - a.z);
});
}
function revisedForecast() {
if (!closed) return null;
return states.reduce((sum, state) => {
if (state.status === "delivered") return sum + state.spent;
if (state.active) {
const remaining = findPath(
state.active.to,
state.order.to,
"cost",
blockedEdges
);
return (
sum +
state.spent +
state.active.w * (1 - state.progress) +
remaining.cost
);
}
return sum + state.spent + state.forecast;
}, 0);
}
// -------------------------------------------------------------------------
// UI updates.
// -------------------------------------------------------------------------
function routeMarkup(path) {
return path
.map(
(node, index) =>
`${index ? '<span class="route-arrow">→</span>' : ""}` +
`<span class="route-node">${node}</span>`
)
.join("");
}
function updateOrders() {
const delivered = states.filter((state) => state.status === "delivered").length;
$("#orders").innerHTML = orders
.map((order, index) => {
const plan = planned[index];
const state = states[index];
const isLive = phase !== "planning";
let status = "Ready";
let shownPath = plan.path;
let cost = plan.cost;
let css = "";
if (isLive) {
if (state.status === "delivered") {
status = "Delivered";
css = "delivered";
cost = state.spent;
shownPath = state.path;
} else if (state.rerouted) {
status = "Rerouted";
css = "rerouted";
shownPath = state.path;
cost = state.forecast;
} else {
status = closed ? "Recalculating" : "En route";
shownPath = state.path;
cost = closed ? state.forecast : plan.cost;
}
}
return `
<article class="order-card ${css}" style="--order-color:${order.css}">
<div class="order-top">
<div class="courier-id">
<span class="courier-dot"></span>
<span class="courier-name">${order.id} · ${order.name}</span>
</div>
<span class="order-status">${status}</span>
</div>
<div class="order-route">${routeMarkup(shownPath)}</div>
<div class="order-meta">
<span>${order.order} · ${order.from} → ${order.to}</span>
<strong>${Number.isFinite(cost) ? cost : "—"} cr</strong>
</div>
</article>
`;
})
.join("");
$("#delivered-count").textContent = `${delivered}/3`;
$("#fleet-count").textContent = `${3 - delivered} active couriers`;
}
function updateUI() {
const plannedTotal = planned.reduce((sum, item) => sum + item.cost, 0);
const forecast = revisedForecast();
const delivered = states.filter((state) => state.status === "delivered").length;
$("#planned-cost").textContent = plannedTotal;
$("#revised-cost").textContent = forecast === null ? "—" : Math.round(forecast * 10) / 10;
$("#delta-cost").textContent =
forecast === null
? "—"
: `${forecast >= plannedTotal ? "+" : ""}${Math.round((forecast - plannedTotal) * 10) / 10}`;
const displayCost = forecast === null ? plannedTotal : forecast;
const percentage = Math.min(100, (displayCost / 42) * 100);
$("#budget-fill").style.width = `${percentage}%`;
$("#budget-value").textContent =
forecast === null ? `${plannedTotal} planned` : `${Math.round(forecast)} revised`;
if (phase === "planning") {
$("#status-text").textContent = "Planning · routes priced";
$("#status-dot").style.background = "#43e0c8";
$("#status-dot").style.boxShadow = "0 0 11px #43e0c8";
} else if (phase === "live") {
$("#status-text").textContent = closed
? "Live · open-network recalculation"
: "Live · committed routes moving";
$("#status-dot").style.background = closed ? "#ffb454" : "#43e0c8";
$("#status-dot").style.boxShadow = `0 0 11px ${closed ? "#ffb454" : "#43e0c8"}`;
} else {
$("#status-text").textContent = "Complete · revised fleet cost";
$("#status-dot").style.background = "#8ee66b";
$("#status-dot").style.boxShadow = "0 0 11px #8ee66b";
}
const planItem = $("#timeline-plan");
const closeItem = $("#timeline-close");
const recalcItem = $("#timeline-recalc");
const deliverItem = $("#timeline-deliver");
planItem.className = "timeline-item done";
planItem.querySelector("small").textContent = "LOCKED";
closeItem.className = `timeline-item ${closed ? "done" : phase === "live" ? "active" : ""}`;
closeItem.querySelector("small").textContent = closed ? "D–E" : "WAIT";
const expectedReroutes = planned.filter((plan) =>
plan.path.some(
(node, index) =>
index < plan.path.length - 1 &&
edgeKey(node, plan.path[index + 1]) === CLOSED_EDGE
)
).length;
recalcItem.className = `timeline-item ${
reroutedCount >= expectedReroutes && closed ? "done" : closed ? "active" : ""
}`;
recalcItem.querySelector("small").textContent = closed
? `${reroutedCount}/${expectedReroutes}`
: "WAIT";
deliverItem.className = `timeline-item ${delivered === 3 ? "done" : ""}`;
deliverItem.querySelector("small").textContent = `${delivered}/3`;
updateOrders();
}
function showToast(title, text, kind = "closure") {
const toast = $("#toast");
$("#toast-title").textContent = title;
$("#toast-text").textContent = text;
toast.classList.toggle("reroute", kind === "reroute");
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("show");
}, 4100);
}
function dispatch() {
if (phase === "planning") {
phase = "live";
paused = false;
simTime = 0;
closed = false;
blockedEdges.clear();
reroutedCount = 0;
const visual = edgeVisuals.get(CLOSED_EDGE);
visual.roadMaterial.color.setHex(0x283446);
visual.roadMaterial.emissive.setHex(0x000000);
visual.roadMaterial.emissiveIntensity = 0;
visual.costLabel.material.color.setHex(0xffffff);
closureVisual.visible = false;
orders.forEach((order, index) => {
drawRoute(plannedRouteGroups[index], planned[index].path, order, 0.2);
drawRoute(liveRouteGroups[index], planned[index].path, order, 0.95, true);
liveRouteGroups[index].visible = true;
});
makeStates();
$("#dispatch").textContent = "Pause";
$("#dispatch").classList.add("pause");
document.querySelectorAll("[data-policy]").forEach((button) => {
button.disabled = true;
button.style.opacity = "0.55";
button.style.cursor = "not-allowed";
});
showToast(
"Plan committed",
"Couriers are moving. The network may still change after departure.",
"reroute"
);
updateUI();
} else if (phase === "live") {
paused = !paused;
$("#dispatch").textContent = paused ? "Resume" : "Pause";
updateUI();
} else {
resetScenario();
}
}
function resetScenario() {
phase = "planning";
paused = false;
closed = false;
simTime = 0;
reroutedCount = 0;
blockedEdges.clear();
const visual = edgeVisuals.get(CLOSED_EDGE);
visual.roadMaterial.color.setHex(0x283446);
visual.roadMaterial.emissive.setHex(0x000000);
visual.roadMaterial.emissiveIntensity = 0;
visual.costLabel.material.color.setHex(0xffffff);
closureVisual.visible = false;
liveRouteGroups.forEach((group) => {
group.visible = false;
clearGroup(group);
});
states = [];
$("#dispatch").textContent = "Commit & dispatch";
$("#dispatch").classList.remove("pause");
document.querySelectorAll("[data-policy]").forEach((button) => {
button.disabled = false;
button.style.opacity = "1";
button.style.cursor = "pointer";
});
computePlan();
orders.forEach((order, index) => {
const courier = courierVisuals[index];
courier.group.position.set(nodes[order.from].x, 0.18, nodes[order.from].z);
courier.group.rotation.y = 0;
});
}
$("#dispatch").addEventListener("click", dispatch);
$("#reset").addEventListener("click", resetScenario);
document.querySelectorAll("[data-policy]").forEach((button) => {
button.addEventListener("click", () => {
if (phase !== "planning") return;
policy = button.dataset.policy;
document.querySelectorAll("[data-policy]").forEach((candidate) => {
candidate.classList.toggle("active", candidate === button);
});
computePlan();
});
});
$("#speed").addEventListener("click", () => {
speed = speed === 1 ? 2 : 1;
$("#speed").textContent = `${speed}× speed`;
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
dispatch();
}
if (event.key.toLowerCase() === "r") {
resetScenario();
}
});
// -------------------------------------------------------------------------
// Resize and render loop.
// -------------------------------------------------------------------------
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(viewport);
resize();
updateCamera();
const clock = new THREE.Clock();
let uiAccumulator = 0;
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
updateSimulation(dt);
updateCourierVisuals(simTime);
uiAccumulator += dt;
if (uiAccumulator > 0.1) {
updateUI();
uiAccumulator = 0;
}
if (closed) {
const pulse = 1 + Math.sin(simTime * 8) * 0.06;
closureVisual.scale.y = pulse;
}
renderer.render(scene, camera);
}
computePlan();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```