Prompt specification
Build or customize the Three.js 3D scene "Route a delivery through a busy covered passage" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Route a delivery through a busy covered passage
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/route-a-delivery-through-a-busy-covered-passage-x2900
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring Khan el-Khalili's market passages in Cairo. Let users choose a fictional delivery window and path. Highlight narrow turning points and maintain access to shop entrances while keeping permanent architecture fixed. Voxel style.
Working Three.js Starter (route-a-delivery-through-a-busy-covered-passage-x2900):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Khan Passage Dispatcher</title>
<style>
:root {
--ink: #16242d;
--muted: #65747b;
--paper: rgba(250, 245, 232, 0.94);
--paper-solid: #faf5e8;
--line: rgba(22, 36, 45, 0.13);
--teal: #087f78;
--teal-bright: #16a39a;
--amber: #d9822b;
--blue: #3978b8;
--green: #2d8a57;
--shadow: 0 18px 48px rgba(32, 30, 22, 0.19);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d9c6a5;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.brand {
position: fixed;
z-index: 5;
top: 24px;
left: 26px;
display: flex;
align-items: center;
gap: 12px;
pointer-events: none;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(2, 7px);
grid-template-rows: repeat(2, 7px);
gap: 3px;
transform: rotate(45deg);
}
.brand-mark span {
display: block;
background: var(--ink);
}
.brand-copy strong {
display: block;
font-size: 13px;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.brand-copy small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.04em;
}
.planner {
position: fixed;
z-index: 10;
top: 82px;
left: 26px;
width: 340px;
max-height: calc(100vh - 108px);
overflow: auto;
padding: 22px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 20px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(20px);
scrollbar-width: thin;
}
.eyebrow {
margin-bottom: 7px;
color: var(--teal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 38px;
font-weight: 500;
line-height: 0.95;
letter-spacing: -0.04em;
}
.intro {
margin: 13px 0 21px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.field {
margin-top: 17px;
}
.field-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
color: #435159;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.field-label small {
color: #899399;
font-size: 9px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: none;
}
.window-switch {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
padding: 4px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(22, 36, 45, 0.045);
}
.window-switch button {
min-height: 53px;
padding: 7px 4px;
border: 0;
border-radius: 9px;
background: transparent;
color: #65747b;
cursor: pointer;
font-size: 10px;
font-weight: 750;
transition: 160ms ease;
}
.window-switch button span {
display: block;
margin-bottom: 4px;
font-size: 15px;
}
.window-switch button.active {
background: var(--ink);
color: #fffaf0;
box-shadow: 0 5px 14px rgba(22, 36, 45, 0.18);
}
select {
width: 100%;
min-height: 42px;
padding: 0 38px 0 12px;
border: 1px solid var(--line);
border-radius: 10px;
outline: none;
background: rgba(255, 255, 255, 0.56);
color: var(--ink);
cursor: pointer;
font-size: 12px;
}
select:focus {
border-color: rgba(8, 127, 120, 0.6);
box-shadow: 0 0 0 3px rgba(8, 127, 120, 0.09);
}
.field-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.primary-button {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
min-height: 48px;
margin-top: 18px;
padding: 0 16px;
border: 0;
border-radius: 11px;
background: var(--teal);
color: white;
box-shadow: 0 10px 22px rgba(8, 127, 120, 0.23);
cursor: pointer;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.03em;
transition: 160ms ease;
}
.primary-button:hover {
background: #066d67;
transform: translateY(-1px);
}
.primary-button:active {
transform: translateY(0);
}
.primary-button .arrow {
font-size: 18px;
font-weight: 400;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
margin-top: 17px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.34);
}
.metric {
padding: 11px 8px 10px;
text-align: center;
}
.metric + .metric {
border-left: 1px solid var(--line);
}
.metric strong {
display: block;
font-family: Georgia, "Times New Roman", serif;
font-size: 19px;
font-weight: 500;
}
.metric small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.progress {
height: 4px;
margin-top: 13px;
overflow: hidden;
border-radius: 4px;
background: rgba(22, 36, 45, 0.09);
}
.progress > div {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--teal-bright);
transition: width 80ms linear;
}
.route-note {
min-height: 34px;
margin: 9px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.divider {
height: 1px;
margin: 19px 0 15px;
background: var(--line);
}
.toggle-list {
display: grid;
gap: 10px;
}
.toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
cursor: pointer;
font-size: 11px;
font-weight: 700;
}
.toggle-label {
display: flex;
align-items: center;
gap: 9px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 2px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.swatch.amber {
background: var(--amber);
}
.swatch.green {
background: var(--green);
}
.swatch.person {
background: #816a91;
}
.toggle input {
position: relative;
width: 34px;
height: 19px;
flex: 0 0 auto;
margin: 0;
appearance: none;
border-radius: 20px;
background: #c9c8bf;
cursor: pointer;
transition: 150ms ease;
}
.toggle input::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 13px;
height: 13px;
border-radius: 50%;
background: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18);
transition: 150ms ease;
}
.toggle input:checked {
background: var(--teal);
}
.toggle input:checked::after {
transform: translateX(15px);
}
.fixed-note {
display: flex;
gap: 10px;
margin-top: 17px;
padding: 11px;
border: 1px solid rgba(45, 138, 87, 0.16);
border-radius: 10px;
background: rgba(45, 138, 87, 0.07);
color: #466352;
font-size: 9px;
line-height: 1.45;
}
.lock {
display: grid;
place-items: center;
width: 23px;
height: 23px;
flex: 0 0 auto;
border-radius: 6px;
background: rgba(45, 138, 87, 0.13);
font-size: 12px;
}
.fixed-note strong {
display: block;
margin-bottom: 2px;
color: #27583c;
font-size: 9px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.scene-caption {
position: fixed;
z-index: 4;
right: 25px;
top: 25px;
max-width: 275px;
padding: 13px 15px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 13px;
background: rgba(250, 245, 232, 0.82);
box-shadow: 0 12px 35px rgba(32, 30, 22, 0.12);
backdrop-filter: blur(13px);
pointer-events: none;
}
.scene-caption strong {
display: block;
margin-bottom: 4px;
font-family: Georgia, "Times New Roman", serif;
font-size: 17px;
font-weight: 500;
}
.scene-caption span {
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.camera-controls {
position: fixed;
z-index: 8;
right: 25px;
bottom: 25px;
display: flex;
gap: 6px;
padding: 6px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 12px;
background: rgba(250, 245, 232, 0.88);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.camera-controls button {
display: grid;
place-items: center;
width: 35px;
height: 35px;
border: 0;
border-radius: 8px;
background: transparent;
cursor: pointer;
font-size: 16px;
}
.camera-controls button:hover {
background: rgba(22, 36, 45, 0.08);
}
.camera-help {
position: fixed;
z-index: 4;
right: 25px;
bottom: 79px;
padding: 7px 10px;
border-radius: 8px;
background: rgba(22, 36, 45, 0.72);
color: rgba(255, 255, 255, 0.9);
font-size: 9px;
pointer-events: none;
}
.toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 28px;
max-width: min(420px, calc(100vw - 30px));
padding: 11px 16px;
border-radius: 10px;
background: var(--ink);
color: white;
box-shadow: var(--shadow);
font-size: 11px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition: 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 760px) {
.brand {
top: 15px;
left: 16px;
}
.brand-copy small {
display: none;
}
.planner {
top: 62px;
left: 12px;
width: min(330px, calc(100vw - 24px));
max-height: 53vh;
padding: 17px;
border-radius: 16px;
}
h1 {
font-size: 31px;
}
.intro {
margin-bottom: 15px;
}
.scene-caption {
top: 62px;
right: 12px;
display: none;
}
.camera-controls {
right: 12px;
bottom: 12px;
}
.camera-help {
display: none;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive voxel market scene"></div>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<span></span><span></span><span></span><span></span>
</div>
<div class="brand-copy">
<strong>Passage Dispatcher</strong>
<small>Khan el-Khalili inspired · fictional Cairo operations</small>
</div>
</div>
<aside class="planner" aria-label="Delivery planner">
<div class="eyebrow">Fictional delivery window</div>
<h1>Market route<br />workshop</h1>
<p class="intro">
Choose a window and passage strategy. Routes are illustrative rather than
a survey or real-world navigation service.
</p>
<section>
<div class="field-label">
<span>Delivery window</span>
<small>local time</small>
</div>
<div class="window-switch" id="windowSwitch">
<button type="button" data-window="dawn" class="active">
<span>☀</span>08:00–10:00
</button>
<button type="button" data-window="peak">
<span>◒</span>12:00–14:00
</button>
<button type="button" data-window="evening">
<span>☾</span>18:00–20:00
</button>
</div>
<div class="field">
<div class="field-label"><span>Pickup</span></div>
<select id="pickup">
<option value="coffee">Nabil Coffee — west arcade</option>
<option value="textile">Cairo Linen — east arcade</option>
<option value="brass">Old Brass Workshop</option>
<option value="rose">Rosewater Attar</option>
</select>
</div>
<div class="field">
<div class="field-label"><span>Drop-off</span></div>
<select id="dropoff">
<option value="rose">Rosewater Attar</option>
<option value="brass">Old Brass Workshop</option>
<option value="textile">Cairo Linen — east arcade</option>
<option value="coffee">Nabil Coffee — west arcade</option>
</select>
</div>
<div class="field">
<div class="field-label">
<span>Passage strategy</span>
<small>architecture fixed</small>
</div>
<select id="routeStrategy">
<option value="express">Lantern Express — central arcade</option>
<option value="balanced">Balanced Passage — window-aware</option>
<option value="loop">Vendor’s Loop — outer lanes</option>
</select>
</div>
<button class="primary-button" id="plotButton" type="button">
Plot / replay delivery <span class="arrow">↗</span>
</button>
<div class="metrics">
<div class="metric">
<strong id="distanceMetric">—</strong>
<small>route</small>
</div>
<div class="metric">
<strong id="turnMetric">—</strong>
<small>pinch points</small>
</div>
<div class="metric">
<strong id="accessMetric">4/4</strong>
<small>entrances</small>
</div>
</div>
<div class="progress"><div id="progressFill"></div></div>
<p class="route-note" id="routeNote">Select a route to begin.</p>
</section>
<div class="divider"></div>
<div class="field-label"><span>Scene overlays</span></div>
<div class="toggle-list">
<label class="toggle">
<span class="toggle-label">
<i class="swatch amber"></i>
Narrow turning points
</span>
<input id="showTurns" type="checkbox" checked />
</label>
<label class="toggle">
<span class="toggle-label">
<i class="swatch green"></i>
Shop entrance access
</span>
<input id="showAccess" type="checkbox" checked />
</label>
<label class="toggle">
<span class="toggle-label">
<i class="swatch person"></i>
Window activity
</span>
<input id="showPeople" type="checkbox" checked />
</label>
</div>
<div class="fixed-note">
<div class="lock">▣</div>
<div>
<strong>Permanent fabric locked</strong>
Arches, shopfronts, and lane widths remain fixed. Only the delivery
overlay and courier are simulated.
</div>
</div>
</aside>
<div class="scene-caption">
<strong>Bayt al-Suhaymi quarter</strong>
<span>
A fictional voxel interpretation inspired by Cairo’s dense market
passages. Shop names and delivery times are invented.
</span>
</div>
<div class="camera-help">Drag to orbit · wheel to zoom · shift/right-drag to pan</div>
<div class="camera-controls" aria-label="Camera controls">
<button id="zoomIn" type="button" aria-label="Zoom in">+</button>
<button id="zoomOut" type="button" aria-label="Zoom out">−</button>
<button id="resetCamera" type="button" aria-label="Reset camera">⌂</button>
</div>
<div class="toast" id="toast" role="status"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Core scene
// ---------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const scene = new THREE.Scene();
const state = {
window: "dawn",
strategy: "express",
pickup: "coffee",
dropoff: "rose",
routeIds: [],
routePoints: [],
routeLength: 0,
segmentLengths: [],
progress: 0,
duration: 14,
turns: [],
accessCount: 4,
narrowTurnCount: 0
};
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Voxel market passage with an interactive delivery route"
);
sceneHost.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-20, 20, 15, -15, 0.1, 160);
const cameraState = {
target: new THREE.Vector3(0, 0.6, -0.8),
radius: 36,
theta: 0.74,
phi: 0.91,
zoom: 1.02
};
const hemi = new THREE.HemisphereLight(0xffedce, 0x806a4b, 1.65);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffe5b5, 2.7);
sun.position.set(-13, 24, 12);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -24;
sun.shadow.camera.right = 24;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x90b9c8, 0.55);
fill.position.set(15, 10, -12);
scene.add(fill);
const architecture = new THREE.Group();
architecture.name = "Permanent market architecture";
const routeGroup = new THREE.Group();
const turnGroup = new THREE.Group();
const accessGroup = new THREE.Group();
const peopleGroup = new THREE.Group();
const propsGroup = new THREE.Group();
scene.add(architecture, routeGroup, turnGroup, accessGroup, peopleGroup, propsGroup);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function material(color, roughness = 0.86, metalness = 0) {
const key = `${color}-${roughness}-${metalness}`;
if (!materialCache.has(key)) {
materialCache.set(
key,
new THREE.MeshStandardMaterial({ color, roughness, metalness })
);
}
return materialCache.get(key);
}
function addBox(parent, width, height, depth, x, y, z, mat, cast = true) {
const mesh = new THREE.Mesh(unitBox, mat);
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function beamBetween(parent, a, b, width, mat) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = end.clone().sub(start);
const midpoint = start.clone().add(end).multiplyScalar(0.5);
const mesh = addBox(
parent,
width,
direction.length(),
width,
midpoint.x,
midpoint.y,
midpoint.z,
mat
);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
return mesh;
}
function roundedRect(ctx, x, y, w, h, radius) {
const r = Math.min(radius, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function labelSprite(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 144;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 6, 6, 628, 132, 22);
ctx.fillStyle = options.background || "rgba(250,245,232,0.94)";
ctx.fill();
ctx.strokeStyle = options.border || "rgba(22,36,45,0.16)";
ctx.lineWidth = 4;
ctx.stroke();
ctx.fillStyle = options.color || "#16242d";
ctx.font = `700 ${options.fontSize || 34}px system-ui, sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 320, 75);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(options.width || 3.5, options.height || 0.78, 1);
sprite.renderOrder = 20;
return sprite;
}
// ---------------------------------------------------------------------
// Voxel market construction
// ---------------------------------------------------------------------
const sandstone = material(0xb98252);
const sandstoneLight = material(0xd09a65);
const sandstoneDark = material(0x996744);
const trim = material(0xe0b982);
const plaster = material(0xd9bf91);
const darkWood = material(0x50382c);
const dark = material(0x252f31);
const wood = material(0x76513a);
const cream = material(0xf1ddb5);
const teal = material(0x277b78);
const rust = material(0xb75b3e);
const blue = material(0x456b87);
const groundBase = addBox(
architecture,
24.8,
0.7,
30.8,
0,
-0.52,
-1.5,
material(0x947654),
false
);
groundBase.receiveShadow = true;
const tileGeometry = new THREE.BoxGeometry(0.94, 0.1, 0.94);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96
});
const tileCount = 25 * 30;
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
tiles.receiveShadow = true;
const tileMatrix = new THREE.Matrix4();
const tilePosition = new THREE.Vector3();
const tileQuaternion = new THREE.Quaternion();
const tileScale = new THREE.Vector3(1, 1, 1);
const tileColors = [0xbaa27d, 0xc6af8a, 0xb49a75, 0xcdb894, 0xa99170];
let tileIndex = 0;
for (let z = -15; z < 15; z++) {
for (let x = -12; x < 13; x++) {
tilePosition.set(x + (z % 2) * 0.08, -0.08, z);
tileMatrix.compose(tilePosition, tileQuaternion, tileScale);
tiles.setMatrixAt(tileIndex, tileMatrix);
tiles.setColorAt(
tileIndex,
new THREE.Color(tileColors[(x * 13 + z * 7 + 40) % tileColors.length])
);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
architecture.add(tiles);
function makeWallSegment(side, z1, z2, height = 6.6) {
const length = z2 - z1;
const centerZ = (z1 + z2) / 2;
addBox(
architecture,
0.68,
height,
length,
side * 3.08,
height / 2,
centerZ,
sandstone
);
addBox(
architecture,
3.15,
height + 1.05,
Math.max(0.6, length - 0.12),
side * 4.66,
(height + 1.05) / 2,
centerZ,
sandstoneLight
);
for (const y of [0.75, 2.85, height - 0.35]) {
addBox(
architecture,
0.78,
0.23,
length,
side * 3.08,
y,
centerZ,
trim
);
}
const blockCount = Math.max(1, Math.floor(length / 1.15));
for (let i = 0; i < blockCount; i++) {
const z = z1 + 0.35 + (i / blockCount) * (length - 0.7);
addBox(
architecture,
0.82,
0.55,
0.64,
side * 3.08,
height + 0.18,
z,
i % 2 ? sandstoneDark : sandstoneLight
);
}
const windowCount = Math.max(1, Math.floor(length / 3.2));
for (let i = 0; i < windowCount; i++) {
const z = z1 + 1.15 + (i / Math.max(1, windowCount - 1)) * (length - 2.3);
if (Math.abs(z - centerZ) > 0.7) {
addBox(
architecture,
0.13,
0.9,
0.72,
side * 2.72,
3.9,
z,
darkWood
);
addBox(
architecture,
0.16,
0.08,
0.82,
side * 2.66,
3.9,
z,
trim
);
}
}
}
const leftSegments = [
[-12.5, -6.4],
[-3.6, -1.4],
[1.4, 4.8],
[7.2, 12.5]
];
const rightSegments = [
[-12.5, -8.9],
[-6.1, -1.4],
[1.4, 4.8],
[7.2, 12.5]
];
leftSegments.forEach(([a, b], i) =>
makeWallSegment(-1, a, b, 6.2 + (i % 2) * 0.8)
);
rightSegments.forEach(([a, b], i) =>
makeWallSegment(1, a, b, 6.5 + (i % 2) * 0.9)
);
function makeOuterSide(side) {
for (const [a, b] of [
[-12.5, -1.45],
[1.45, 12.5]
]) {
const length = b - a;
addBox(
architecture,
0.7,
5.4,
length,
side * 9.55,
2.7,
(a + b) / 2,
sandstoneDark
);
addBox(
architecture,
0.82,
0.25,
length,
side * 9.55,
5.25,
(a + b) / 2,
trim
);
}
}
makeOuterSide(-1);
makeOuterSide(1);
addBox(
architecture,
22.8,
4.7,
0.7,
0,
2.35,
-12.7,
sandstoneDark
);
addBox(
architecture,
23.2,
0.28,
0.9,
0,
4.85,
-12.7,
trim
);
function makeArch(side, centerZ, label, accent, isShop = true) {
const x = side * 3.04;
for (const offset of [-1.48, 1.48]) {
addBox(
architecture,
0.82,
2.8,
0.38,
x,
1.4,
centerZ + offset,
trim
);
addBox(
architecture,
0.95,
0.26,
0.55,
x,
0.28,
centerZ + offset,
sandstoneDark
);
}
addBox(
architecture,
0.9,
0.55,
3.55,
x,
3.08,
centerZ,
trim
);
for (let step = 0; step < 3; step++) {
for (const direction of [-1, 1]) {
addBox(
architecture,
0.9,
0.35,
0.55,
x,
3.54 + step * 0.34,
centerZ + direction * (1.05 - step * 0.32),
step % 2 ? trim : sandstoneLight
);
}
}
if (!isShop) {
const passageLabel = labelSprite(label, {
width: 2.6,
height: 0.55,
fontSize: 27,
background: "rgba(250,245,232,0.88)"
});
passageLabel.position.set(side * 2.82, 4.32, centerZ);
architecture.add(passageLabel);
return;
}
addBox(
architecture,
0.15,
2.65,
2.65,
side * 3.48,
1.32,
centerZ,
dark
);
addBox(
architecture,
0.15,
3.3,
2.6,
side * 5.65,
1.65,
centerZ,
sandstoneDark
);
addBox(
architecture,
1.15,
0.65,
2.4,
side * 4.25,
0.35,
centerZ,
wood
);
const rugColors = [rust, teal, blue];
for (let i = 0; i < 6; i++) {
addBox(
architecture,
1.55,
0.035,
0.27,
side * 4.25,
0.035,
centerZ - 0.95 + i * 0.38,
rugColors[i % rugColors.length],
false
);
}
const stripeCount = 7;
for (let i = 0; i < stripeCount; i++) {
const z = centerZ - 1.55 + (i / (stripeCount - 1)) * 3.1;
addBox(
architecture,
1.45,
0.12,
0.43,
side * 2.28,
2.72,
z,
i % 2 ? cream : accent
);
}
for (const z of [centerZ - 1.35, centerZ + 1.35]) {
addBox(
architecture,
0.11,
2.6,
0.11,
side * 1.62,
1.3,
z,
wood
);
}
const sign = labelSprite(label, {
width: 3.25,
height: 0.68,
fontSize: 28,
border: "rgba(22,36,45,0.23)"
});
sign.position.set(side * 2.56, 4.38, centerZ);
architecture.add(sign);
addBox(
propsGroup,
0.55,
0.45,
0.55,
side * 1.8,
0.22,
centerZ + 1.72,
wood
);
}
makeArch(-1, 0, "WEST PASSAGE", sandstoneLight, false);
makeArch(1, 0, "EAST PASSAGE", sandstoneLight, false);
makeArch(-1, 6, "NABIL COFFEE", rust);
makeArch(1, 6, "CAIRO LINEN", teal);
makeArch(-1, -5, "OLD BRASS", blue);
makeArch(1, -7.5, "ROSEWATER ATTAR", rust);
// Southern market gate.
for (const x of [-3.1, 3.1]) {
addBox(architecture, 1.1, 5.5, 1.2, x, 2.75, 12.35, trim);
addBox(architecture, 1.45, 0.45, 1.5, x, 5.55, 12.35, sandstoneDark);
}
addBox(architecture, 7.3, 0.9, 1.4, 0, 5.05, 12.35, sandstoneLight);
addBox(architecture, 6.4, 0.25, 1.6, 0, 5.65, 12.35, trim);
// Distant stepped minaret and dome-like voxel silhouette.
addBox(architecture, 3.1, 1.1, 2.7, 0, 0.55, -14.7, sandstoneDark);
addBox(architecture, 1.5, 10.5, 1.4, 0, 5.9, -14.7, sandstoneLight);
addBox(architecture, 2.2, 0.55, 2.0, 0, 10.7, -14.7, trim);
addBox(architecture, 1.2, 1.8, 1.1, 0, 11.85, -14.7, sandstoneLight);
addBox(architecture, 0.7, 2.3, 0.7, 0, 13.4, -14.7, trim);
for (let i = 0; i < 5; i++) {
const width = 4.2 - i * 0.65;
addBox(
architecture,
width,
0.65,
width,
6.4,
0.35 + i * 0.63,
-14.3,
i % 2 ? sandstone : sandstoneLight
);
}
addBox(architecture, 0.45, 1.2, 0.45, 6.4, 3.8, -14.3, trim);
// ---------------------------------------------------------------------
// Lanterns and props
// ---------------------------------------------------------------------
const lanternMaterial = new THREE.MeshStandardMaterial({
color: 0xf6b94f,
emissive: 0xff9d27,
emissiveIntensity: 0.25,
roughness: 0.55
});
const lanternLights = [];
for (const z of [8.8, 3.2, -2.2, -8.8]) {
const points = [];
for (let i = 0; i <= 8; i++) {
const x = -2.8 + (i / 8) * 5.6;
const y = 5.35 - Math.sin((i / 8) * Math.PI) * 0.85;
points.push([x, y, z]);
}
for (let i = 0; i < points.length - 1; i++) {
beamBetween(architecture, points[i], points[i + 1], 0.035, darkWood);
}
for (let i = 1; i < points.length - 1; i++) {
const [x, y] = points[i];
addBox(architecture, 0.27, 0.38, 0.27, x, y - 0.32, z, lanternMaterial, false);
addBox(architecture, 0.32, 0.08, 0.32, x, y - 0.12, z, darkWood, false);
addBox(architecture, 0.32, 0.08, 0.32, x, y - 0.53, z, darkWood, false);
}
}
for (const [x, z] of [
[-2.65, 8.9],
[2.65, -2.2],
[-7.45, 0],
[7.45, -10.5]
]) {
addBox(architecture, 0.12, 3.6, 0.12, x, 1.8, z, darkWood);
addBox(architecture, 0.45, 0.62, 0.45, x, 3.55, z, lanternMaterial, false);
const light = new THREE.PointLight(0xffa53d, 4, 8, 2);
light.position.set(x, 3.35, z);
scene.add(light);
lanternLights.push(light);
}
function makeStall(x, z, accent) {
addBox(propsGroup, 1.65, 0.22, 1.3, x, 1.15, z, wood);
addBox(propsGroup, 0.18, 1.15, 0.18, x - 0.65, 0.55, z - 0.45, darkWood);
addBox(propsGroup, 0.18, 1.15, 0.18, x + 0.65, 0.55, z - 0.45, darkWood);
addBox(propsGroup, 0.18, 1.15, 0.18, x - 0.65, 0.55, z + 0.45, darkWood);
addBox(propsGroup, 0.18, 1.15, 0.18, x + 0.65, 0.55, z + 0.45, darkWood);
for (let i = 0; i < 5; i++) {
addBox(
propsGroup,
1.8,
0.13,
0.34,
x,
2.25,
z - 0.52 + i * 0.26,
i % 2 ? cream : accent
);
}
for (let i = 0; i < 5; i++) {
const potMat = i % 2 ? material(0xb9653f) : material(0x477c77);
addBox(
propsGroup,
0.23,
0.28,
0.23,
x - 0.48 + i * 0.24,
1.4,
z,
potMat
);
}
}
makeStall(-8.65, -4.7, teal);
makeStall(8.65, -4.1, rust);
makeStall(-8.65, 7.6, blue);
for (const [x, z] of [
[-1.8, 10],
[1.75, 9.4],
[-8.4, -8.3],
[8.2, 5.9],
[-1.8, -9.4]
]) {
addBox(propsGroup, 0.75, 0.55, 0.75, x, 0.28, z, wood);
addBox(propsGroup, 0.68, 0.12, 0.68, x, 0.62, z, trim);
}
// ---------------------------------------------------------------------
// Voxel people
// ---------------------------------------------------------------------
const people = [];
function makePerson(x, z, color, order, scale = 1) {
const group = new THREE.Group();
const bodyMat = material(color);
const skinMat = material(0xa96f4f);
const body = addBox(group, 0.42, 0.64, 0.3, 0, 0.83, 0, bodyMat);
const head = addBox(group, 0.29, 0.29, 0.29, 0, 1.32, 0, skinMat);
const leftLeg = addBox(group, 0.14, 0.47, 0.17, -0.12, 0.34, 0, dark);
const rightLeg = addBox(group, 0.14, 0.47, 0.17, 0.12, 0.34, 0, dark);
group.position.set(x, 0, z);
group.scale.setScalar(scale);
group.userData = {
order,
leftLeg,
rightLeg,
body,
head,
homeX: x,
homeZ: z,
phase: order * 1.73
};
peopleGroup.add(group);
people.push(group);
}
const peoplePositions = [
[-1.3, 9.2],
[1.25, 8.4],
[-1.45, 3.1],
[1.3, -2.7],
[0.95, -9.6],
[-7.7, 0.7],
[7.6, -0.7],
[-7.8, -6.7],
[7.7, -7.5],
[-1.2, -3.9],
[1.35, -6.5],
[-8.4, 9.2],
[8.4, 9.1],
[-4.9, 0.1],
[5.0, -0.2]
];
const shirtColors = [
0x557b8e,
0x93647d,
0x7b8761,
0xa65f43,
0x4e7772,
0xc18a4d
];
peoplePositions.forEach(([x, z], index) => {
makePerson(
x,
z,
shirtColors[index % shirtColors.length],
index,
0.86 + (index % 3) * 0.08
);
});
// ---------------------------------------------------------------------
// Navigation graph
// ---------------------------------------------------------------------
const graphNodes = {
coffee: [-2.15, 6],
textile: [2.15, 6],
brass: [-2.15, -5],
rose: [2.15, -7.5],
S: [0, 10.5],
J: [0, 0],
K: [0, -5],
L: [0, -7.5],
N: [0, -10.5],
W: [-7.7, 0],
E: [7.7, 0],
NW: [-7.7, -10.5],
NE: [7.7, -10.5]
};
const graphEdges = [
["coffee", "J", "central"],
["textile", "J", "central"],
["brass", "K", "central"],
["rose", "L", "central"],
["S", "J", "central"],
["J", "K", "central"],
["K", "L", "central"],
["J", "W", "outer"],
["J", "E", "outer"],
["W", "NW", "outer"],
["NW", "N", "outer"],
["E", "NE", "outer"],
["NE", "N", "outer"],
["N", "L", "outer"]
];
const nodeClearance = {
S: 3.5,
J: 2.35,
K: 2.8,
L: 2.6,
N: 2.1,
W: 2.75,
E: 2.7,
NW: 2.85,
NE: 2.8
};
function distanceBetween(a, b) {
const pa = graphNodes[a];
const pb = graphNodes[b];
return Math.hypot(pb[0] - pa[0], pb[1] - pa[1]);
}
function edgeMultipliers() {
if (state.strategy === "express") {
return { central: 1.0, outer: 1.8 };
}
if (state.strategy === "loop") {
return { central: 2.4, outer: 0.72 };
}
if (state.window === "peak") {
return { central: 2.35, outer: 0.9 };
}
return { central: 1.0, outer: 1.15 };
}
function findRoute(start, goal) {
const adjacency = Object.fromEntries(
Object.keys(graphNodes).map((id) => [id, []])
);
const multiplier = edgeMultipliers();
graphEdges.forEach(([a, b, kind]) => {
const cost = distanceBetween(a, b) * multiplier[kind];
adjacency[a].push({ node: b, cost });
adjacency[b].push({ node: a, cost });
});
const unvisited = new Set(Object.keys(graphNodes));
const distance = Object.fromEntries(
Object.keys(graphNodes).map((id) => [id, Infinity])
);
const previous = {};
distance[start] = 0;
while (unvisited.size) {
let current = null;
let best = Infinity;
for (const id of unvisited) {
if (distance[id] < best) {
best = distance[id];
current = id;
}
}
if (current === null) break;
if (current === goal) break;
unvisited.delete(current);
for (const edge of adjacency[current]) {
if (!unvisited.has(edge.node)) continue;
const candidate = distance[current] + edge.cost;
if (candidate < distance[edge.node]) {
distance[edge.node] = candidate;
previous[edge.node] = current;
}
}
}
if (!Number.isFinite(distance[goal])) {
return { ids: [start, goal], length: distanceBetween(start, goal) };
}
const ids = [goal];
while (ids[0] !== start) {
ids.unshift(previous[ids[0]]);
}
let length = 0;
for (let i = 1; i < ids.length; i++) {
length += distanceBetween(ids[i - 1], ids[i]);
}
return { ids, length };
}
// ---------------------------------------------------------------------
// Route and overlay rendering
// ---------------------------------------------------------------------
const routeDotGeometry = new THREE.BoxGeometry(0.16, 0.075, 0.16);
const routeDotMaterial = new THREE.MeshBasicMaterial({ color: 0x079d91 });
const routeLineMaterial = new THREE.LineBasicMaterial({
color: 0x05877f,
transparent: true,
opacity: 0.8
});
function clearGroup(group, disposeSpriteTextures = false) {
while (group.children.length) {
const child = group.children[0];
group.remove(child);
if (child.isLine && child.geometry) child.geometry.dispose();
if (disposeSpriteTextures && child.isSprite) {
if (child.material.map) child.material.map.dispose();
child.material.dispose();
}
}
}
function addRouteDots(points) {
let dotIndex = 0;
for (let i = 1; i < points.length; i++) {
const a = points[i - 1];
const b = points[i];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const count = Math.max(1, Math.floor(length / 0.36));
for (let j = 0; j < count; j++) {
const t = j / count;
const dot = new THREE.Mesh(routeDotGeometry, routeDotMaterial);
dot.position.set(
THREE.MathUtils.lerp(a.x, b.x, t),
0.09,
THREE.MathUtils.lerp(a.z, b.z, t)
);
routeGroup.add(dot);
dotIndex++;
}
}
return dotIndex;
}
function makeRoutePin(x, z, color) {
const group = new THREE.Group();
const pinMat = new THREE.MeshBasicMaterial({ color });
addBox(group, 0.16, 1.15, 0.16, 0, 0.58, 0, pinMat, false);
addBox(group, 0.48, 0.3, 0.48, 0, 1.25, 0, pinMat, false);
addBox(group, 0.26, 0.12, 0.26, 0, 1.48, 0, pinMat, false);
group.position.set(x, 0, z);
return group;
}
function detectTurns(ids) {
const turns = [];
for (let i = 1; i < ids.length - 1; i++) {
const previous = graphNodes[ids[i - 1]];
const current = graphNodes[ids[i]];
const next = graphNodes[ids[i + 1]];
const incoming = new THREE.Vector2(
current[0] - previous[0],
current[1] - previous[1]
).normalize();
const outgoing = new THREE.Vector2(
next[0] - current[0],
next[1] - current[1]
).normalize();
const angle = Math.acos(
THREE.MathUtils.clamp(incoming.dot(outgoing), -1, 1)
);
if (angle > THREE.MathUtils.degToRad(22)) {
turns.push({
id: ids[i],
x: current[0],
z: current[1],
angle,
clearance: nodeClearance[ids[i]] || 3
});
}
}
return turns;
}
function makeTurnMarker(turn) {
const group = new THREE.Group();
const color = turn.clearance <= 2.25 ? 0xd86628 : 0xe0a12d;
const markerMat = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.92
});
const size = 1.65;
const thickness = 0.12;
addBox(group, size, 0.08, thickness, 0, 0.11, -size / 2, markerMat, false);
addBox(group, size, 0.08, thickness, 0, 0.11, size / 2, markerMat, false);
addBox(group, thickness, 0.08, size, -size / 2, 0.11, 0, markerMat, false);
addBox(group, thickness, 0.08, size, size / 2, 0.11, 0, markerMat, false);
for (const x of [-size / 2, size / 2]) {
for (const z of [-size / 2, size / 2]) {
addBox(group, 0.14, 0.58, 0.14, x, 0.39, z, markerMat, false);
}
}
const label = labelSprite(
`${turn.clearance.toFixed(1)} m PINCH`,
{
width: 2.25,
height: 0.51,
fontSize: 28,
color: "#6b3215",
background: "rgba(255,237,193,0.95)",
border: "rgba(216,102,40,0.45)"
}
);
label.position.set(0, 1.18, 0);
group.add(label);
group.position.set(turn.x, 0, turn.z);
group.userData.baseScale = 1;
return group;
}
const shops = {
coffee: { x: -2.15, z: 6, label: "Nabil Coffee" },
textile: { x: 2.15, z: 6, label: "Cairo Linen" },
brass: { x: -2.15, z: -5, label: "Old Brass" },
rose: { x: 2.15, z: -7.5, label: "Rosewater Attar" }
};
const accessMarkers = {};
Object.entries(shops).forEach(([id, shop]) => {
const group = new THREE.Group();
const markerMat = new THREE.MeshBasicMaterial({
color: 0x2d9b62,
transparent: true,
opacity: 0.9
});
const size = 1.22;
addBox(group, size, 0.045, 0.09, 0, 0.08, -size / 2, markerMat, false);
addBox(group, size, 0.045, 0.09, 0, 0.08, size / 2, markerMat, false);
addBox(group, 0.09, 0.045, size, -size / 2, 0.08, 0, markerMat, false);
addBox(group, 0.09, 0.045, size, size / 2, 0.08, 0, markerMat, false);
const label = labelSprite("ACCESS", {
width: 1.75,
height: 0.4,
fontSize: 25,
color: "#235f3d",
background: "rgba(235,249,233,0.94)",
border: "rgba(45,138,87,0.28)"
});
label.position.set(0, 0.53, 0);
group.add(label);
group.position.set(shop.x, 0, shop.z);
group.userData.material = markerMat;
accessGroup.add(group);
accessMarkers[id] = group;
});
function pointSegmentDistance(point, a, b) {
const abx = b.x - a.x;
const abz = b.z - a.z;
const apx = point.x - a.x;
const apz = point.z - a.z;
const denominator = abx * abx + abz * abz;
const t = denominator
? THREE.MathUtils.clamp((apx * abx + apz * abz) / denominator, 0, 1)
: 0;
const closestX = a.x + abx * t;
const closestZ = a.z + abz * t;
return Math.hypot(point.x - closestX, point.z - closestZ);
}
function routeDistanceTo(point) {
let minimum = Infinity;
for (let i = 1; i < state.routePoints.length; i++) {
minimum = Math.min(
minimum,
pointSegmentDistance(point, state.routePoints[i - 1], state.routePoints[i])
);
}
return minimum;
}
function updateEntranceAccess() {
state.accessCount = 0;
Object.entries(shops).forEach(([id, shop]) => {
const marker = accessMarkers[id];
const distance = routeDistanceTo({ x: shop.x, z: shop.z });
const isEndpoint = id === state.pickup || id === state.dropoff;
const clear = isEndpoint || distance > 0.72;
marker.userData.material.color.setHex(
clear ? (isEndpoint ? 0x168e91 : 0x2d9b62) : 0xc44b35
);
if (clear) state.accessCount++;
});
document.getElementById("accessMetric").textContent =
`${state.accessCount}/4`;
}
function hidePeopleNearRoute() {
for (const person of people) {
const position = person.position;
const distance = state.routePoints.length
? routeDistanceTo({ x: position.x, z: position.z })
: 99;
person.userData.routeHidden = distance < 0.68;
}
}
// ---------------------------------------------------------------------
// Courier
// ---------------------------------------------------------------------
const courier = new THREE.Group();
const courierBodyMat = material(0x087f78);
const courierBagMat = material(0xd68b32);
addBox(courier, 0.48, 0.65, 0.34, 0, 0.87, 0, courierBodyMat);
addBox(courier, 0.31, 0.31, 0.31, 0, 1.4, 0, material(0xa96f4f));
addBox(courier, 0.34, 0.08, 0.34, 0, 1.59, 0, cream);
addBox(courier, 0.38, 0.42, 0.25, 0, 0.88, -0.29, courierBagMat);
const courierLeftLeg = addBox(
courier,
0.15,
0.5,
0.18,
-0.13,
0.35,
0,
dark
);
const courierRightLeg = addBox(
courier,
0.15,
0.5,
0.18,
0.13,
0.35,
0,
dark
);
scene.add(courier);
function updateCourier(delta, elapsed) {
if (state.routePoints.length < 2) return;
if (state.progress < 1) {
state.progress = Math.min(
1,
state.progress + delta / state.duration
);
document.getElementById("progressFill").style.width =
`${state.progress * 100}%`;
}
const targetDistance = state.progress * state.routeLength;
let accumulated = 0;
let segmentIndex = 0;
let localT = 0;
for (let i = 1; i < state.routePoints.length; i++) {
const segmentLength = state.segmentLengths[i - 1];
if (targetDistance <= accumulated + segmentLength || i === state.routePoints.length - 1) {
segmentIndex = i - 1;
localT = segmentLength
? THREE.MathUtils.clamp(
(targetDistance - accumulated) / segmentLength,
0,
1
)
: 0;
break;
}
accumulated += segmentLength;
}
const a = state.routePoints[segmentIndex];
const b = state.routePoints[segmentIndex + 1] || a;
const x = THREE.MathUtils.lerp(a.x, b.x, localT);
const z = THREE.MathUtils.lerp(a.z, b.z, localT);
courier.position.set(x, 0.02 + Math.sin(elapsed * 10) * 0.025, z);
const dx = b.x - a.x;
const dz = b.z - a.z;
if (Math.hypot(dx, dz) > 0.001) {
courier.rotation.y = Math.atan2(dx, dz);
}
const walking = state.progress < 1 ? 1 : 0;
courierLeftLeg.rotation.x = Math.sin(elapsed * 10) * 0.5 * walking;
courierRightLeg.rotation.x = -Math.sin(elapsed * 10) * 0.5 * walking;
}
// ---------------------------------------------------------------------
// Plotting and summary
// ---------------------------------------------------------------------
const distanceMetric = document.getElementById("distanceMetric");
const turnMetric = document.getElementById("turnMetric");
const accessMetric = document.getElementById("accessMetric");
const routeNote = document.getElementById("routeNote");
const progressFill = document.getElementById("progressFill");
const windowSettings = {
dawn: {
start: 8,
multiplier: 0.85,
label: "08:00–10:00"
},
peak: {
start: 12,
multiplier: 1.4,
label: "12:00–14:00"
},
evening: {
start: 18,
multiplier: 1.15,
label: "18:00–20:00"
}
};
function formatArrival(hour, minute) {
const suffix = hour >= 12 ? "PM" : "AM";
const displayHour = hour % 12 || 12;
return `${displayHour}:${String(minute).padStart(2, "0")} ${suffix}`;
}
function plotRoute(showMessage = false) {
state.pickup = document.getElementById("pickup").value;
state.dropoff = document.getElementById("dropoff").value;
state.strategy = document.getElementById("routeStrategy").value;
if (state.pickup === state.dropoff) {
showToast("Pickup and drop-off must be different shop entrances.");
return;
}
const result = findRoute(state.pickup, state.dropoff);
state.routeIds = result.ids;
state.routeLength = result.length;
state.routePoints = result.ids.map((id) => {
const [x, z] = graphNodes[id];
return { x, z };
});
state.segmentLengths = [];
for (let i = 1; i < state.routePoints.length; i++) {
state.segmentLengths.push(
Math.hypot(
state.routePoints[i].x - state.routePoints[i - 1].x,
state.routePoints[i].z - state.routePoints[i - 1].z
)
);
}
clearGroup(routeGroup);
clearGroup(turnGroup, true);
const linePoints = state.routePoints.map(
(point) => new THREE.Vector3(point.x, 0.13, point.z)
);
const lineGeometry = new THREE.BufferGeometry().setFromPoints(linePoints);
routeGroup.add(new THREE.Line(lineGeometry, routeLineMaterial));
addRouteDots(state.routePoints);
const pickup = shops[state.pickup];
const dropoff = shops[state.dropoff];
routeGroup.add(makeRoutePin(pickup.x, pickup.z, 0x168e91));
routeGroup.add(makeRoutePin(dropoff.x, dropoff.z, 0x3978b8));
state.turns = detectTurns(result.ids);
state.narrowTurnCount = state.turns.filter(
(turn) => turn.clearance < 3
).length;
state.turns
.filter((turn) => turn.clearance < 3)
.forEach((turn) => turnGroup.add(makeTurnMarker(turn)));
updateEntranceAccess();
hidePeopleNearRoute();
const distanceMeters = Math.round(state.routeLength * 1.15);
const settings = windowSettings[state.window];
const minutes = Math.max(
3,
Math.round((distanceMeters / 5.5) * settings.multiplier)
);
const arrivalTotal = settings.start * 60 + minutes;
const arrivalHour = Math.floor(arrivalTotal / 60) % 24;
const arrivalMinute = arrivalTotal % 60;
distanceMetric.textContent = `${distanceMeters} m`;
turnMetric.textContent = state.narrowTurnCount;
accessMetric.textContent = `${state.accessCount}/4`;
const routeDescriptions = {
express: "Fastest fictional run through the central arcade.",
balanced:
state.window === "peak"
? "Peak activity shifts this run onto the outer vendor lanes."
: "A quieter-window balance favoring the central arcade.",
loop: "A longer run using the wider outer lanes and vendor passages."
};
routeNote.textContent =
`${routeDescriptions[state.strategy]} ` +
`Arrival ${formatArrival(arrivalHour, arrivalMinute)} · ` +
`${settings.label} · all permanent arches remain fixed.`;
state.progress = 0;
state.duration = 12 + state.routeLength * 0.16;
progressFill.style.width = "0%";
if (showMessage) {
showToast("Fictional delivery plotted. Entrance access remains clear.");
}
}
let toastTimer;
function showToast(message) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2900);
}
// ---------------------------------------------------------------------
// Window lighting and activity
// ---------------------------------------------------------------------
function applyWindow(windowName, replot = true) {
state.window = windowName;
document.querySelectorAll("#windowSwitch button").forEach((button) => {
button.classList.toggle("active", button.dataset.window === windowName);
});
if (windowName === "dawn") {
scene.background = new THREE.Color(0xe3d1ae);
scene.fog = new THREE.Fog(0xe3d1ae, 42, 78);
hemi.color.setHex(0xffedce);
hemi.groundColor.setHex(0x806a4b);
hemi.intensity = 1.65;
sun.color.setHex(0xffe1ad);
sun.intensity = 2.7;
sun.position.set(-13, 24, 12);
fill.intensity = 0.55;
lanternMaterial.emissiveIntensity = 0.25;
lanternLights.forEach((light) => (light.intensity = 4));
setCrowdLimit(5);
} else if (windowName === "peak") {
scene.background = new THREE.Color(0xd8cfb8);
scene.fog = new THREE.Fog(0xd8cfb8, 43, 82);
hemi.color.setHex(0xfff4dc);
hemi.groundColor.setHex(0x8b795d);
hemi.intensity = 1.9;
sun.color.setHex(0xfff4d6);
sun.intensity = 3.1;
sun.position.set(6, 27, 5);
fill.intensity = 0.4;
lanternMaterial.emissiveIntensity = 0.12;
lanternLights.forEach((light) => (light.intensity = 1.5));
setCrowdLimit(13);
} else {
scene.background = new THREE.Color(0x25323a);
scene.fog = new THREE.Fog(0x25323a, 40, 75);
hemi.color.setHex(0x7e9ba7);
hemi.groundColor.setHex(0x342a28);
hemi.intensity = 0.82;
sun.color.setHex(0x9caec2);
sun.intensity = 0.65;
sun.position.set(-18, 15, 3);
fill.intensity = 0.25;
lanternMaterial.emissiveIntensity = 2.3;
lanternLights.forEach((light) => (light.intensity = 22));
setCrowdLimit(8);
}
if (replot) plotRoute(false);
}
function setCrowdLimit(limit) {
people.forEach((person, index) => {
person.userData.crowdLimitVisible = index < limit;
});
}
function updatePeople(delta, elapsed) {
const enabled = document.getElementById("showPeople").checked;
peopleGroup.visible = enabled;
for (const person of people) {
const visible =
enabled &&
person.userData.crowdLimitVisible &&
!person.userData.routeHidden;
person.visible = visible;
if (!visible) continue;
const phase = elapsed * 1.8 + person.userData.phase;
person.userData.leftLeg.rotation.x = Math.sin(phase) * 0.18;
person.userData.rightLeg.rotation.x = -Math.sin(phase) * 0.18;
person.position.y = Math.abs(Math.sin(phase)) * 0.025;
}
}
// ---------------------------------------------------------------------
// Direct camera controls
// ---------------------------------------------------------------------
function updateCamera() {
const aspect = window.innerWidth / window.innerHeight;
const viewHeight = aspect < 0.8 ? 39 : aspect < 1.2 ? 35 : 30;
const halfHeight = viewHeight / 2;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.target.set(0, 0.6, -0.8);
cameraState.radius = 36;
cameraState.theta = 0.74;
cameraState.phi = 0.91;
cameraState.zoom = 1.02;
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
let activePointer = null;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
activePointer = event.pointerId;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== activePointer) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
if (event.button === 2 || event.shiftKey) {
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 0)
.setY(0)
.normalize();
const forward = camera.getWorldDirection(new THREE.Vector3());
forward.y = 0;
forward.normalize();
const scale = 0.018 / cameraState.zoom;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.34,
1.35
);
}
updateCamera();
});
function endDrag(event) {
if (event.pointerId !== activePointer) return;
dragging = false;
activePointer = null;
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.62,
2.5
);
updateCamera();
},
{ passive: false }
);
document.getElementById("zoomIn").addEventListener("click", () => {
cameraState.zoom = THREE.MathUtils.clamp(cameraState.zoom * 1.16, 0.62, 2.5);
updateCamera();
});
document.getElementById("zoomOut").addEventListener("click", () => {
cameraState.zoom = THREE.MathUtils.clamp(cameraState.zoom / 1.16, 0.62, 2.5);
updateCamera();
});
document.getElementById("resetCamera").addEventListener("click", resetCamera);
window.addEventListener("resize", () => {
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
updateCamera();
});
// ---------------------------------------------------------------------
// UI bindings
// ---------------------------------------------------------------------
document.querySelectorAll("#windowSwitch button").forEach((button) => {
button.addEventListener("click", () => {
applyWindow(button.dataset.window, true);
});
});
document.getElementById("routeStrategy").addEventListener("change", () => {
plotRoute(false);
});
document.getElementById("pickup").addEventListener("change", () => {
plotRoute(false);
});
document.getElementById("dropoff").addEventListener("change", () => {
plotRoute(false);
});
document.getElementById("plotButton").addEventListener("click", () => {
plotRoute(true);
});
document.getElementById("showTurns").addEventListener("change", (event) => {
turnGroup.visible = event.target.checked;
});
document.getElementById("showAccess").addEventListener("change", (event) => {
accessGroup.visible = event.target.checked;
});
// ---------------------------------------------------------------------
// Initialization and render loop
// ---------------------------------------------------------------------
updateCamera();
applyWindow("dawn", false);
plotRoute(false);
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updateCourier(delta, elapsed);
updatePeople(delta, elapsed);
turnGroup.children.forEach((marker, index) => {
const pulse = 1 + Math.sin(elapsed * 3.4 + index) * 0.055;
marker.scale.setScalar(pulse);
});
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```