Prompt specification
Build or customize the Three.js 3D scene "Station Concourse Crowd Diorama" 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: Station Concourse Crowd Diorama
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/station-concourse-crowd-diorama-x3715
Scene Description Prompt:
Create a standalone voxel scene in one HTML file using Three.js from cdnjs. Build a bounded fictional concourse with a small crowd, benches, and two exits. Use simple deterministic routing and collision avoidance without claiming calibrated pedestrian-safety analysis.
Working Three.js Starter (station-concourse-crowd-diorama-x3715):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Concourse — Deterministic Crowd Demo</title>
<style>
:root {
color-scheme: dark;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
--panel: rgba(12, 18, 30, 0.88);
--border: rgba(255, 255, 255, 0.12);
--muted: #9ca9bd;
--text: #eef4ff;
--exit-a: #51d6c8;
--exit-b: #ffb457;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #101827;
color: var(--text);
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
top: 18px;
left: 18px;
width: min(340px, calc(100vw - 36px));
padding: 16px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(14px);
user-select: none;
}
.eyebrow {
margin-bottom: 5px;
color: #8ea1be;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 21px;
line-height: 1.15;
letter-spacing: -0.02em;
}
.subtitle {
margin: 7px 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 13px;
}
.stat {
padding: 9px 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.stat strong {
display: block;
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.stat span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 0 0 13px;
color: #c8d2e2;
font-size: 11px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.dot {
width: 9px;
height: 9px;
border-radius: 2px;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.dot.a {
color: var(--exit-a);
}
.dot.b {
color: var(--exit-b);
}
.controls {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
button {
min-height: 34px;
padding: 7px 8px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 9px;
background: rgba(255, 255, 255, 0.07);
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.13);
border-color: rgba(255, 255, 255, 0.24);
}
button.active {
border-color: rgba(81, 214, 200, 0.55);
background: rgba(81, 214, 200, 0.14);
}
.speed-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 12px;
color: var(--muted);
font-size: 11px;
}
.speed-row input {
flex: 1;
accent-color: var(--exit-a);
}
#speedValue {
min-width: 34px;
color: var(--text);
text-align: right;
font-variant-numeric: tabular-nums;
}
.notice {
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.09);
color: #aab6c9;
font-size: 10px;
line-height: 1.45;
}
.notice strong {
color: #d7dfeb;
}
.help {
position: fixed;
right: 16px;
bottom: 14px;
padding: 8px 11px;
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(12, 18, 30, 0.72);
color: #aab6c9;
font-size: 10px;
backdrop-filter: blur(10px);
pointer-events: none;
}
@media (max-width: 620px) {
.panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px;
}
.subtitle {
margin-bottom: 9px;
}
.help {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel concourse scene"></canvas>
<section class="panel">
<div class="eyebrow">Fictional environment</div>
<h1>Voxel Concourse</h1>
<p class="subtitle">
A bounded, fictional concourse with deterministic route selection and
local collision avoidance.
</p>
<div class="stats">
<div class="stat">
<strong id="insideCount">14</strong>
<span>Inside</span>
</div>
<div class="stat">
<strong id="exitedCount">0</strong>
<span>Exited</span>
</div>
<div class="stat">
<strong id="clock">00:00</strong>
<span>Sim time</span>
</div>
</div>
<div class="legend">
<span><i class="dot a"></i>Exit A route</span>
<span><i class="dot b"></i>Exit B route</span>
<span><i class="dot"></i>Benches / walls</span>
</div>
<div class="controls">
<button id="pauseButton" type="button">Pause</button>
<button id="resetButton" type="button">Reset</button>
<button id="routesButton" type="button">Routes</button>
</div>
<label class="speed-row">
Speed
<input id="speedSlider" type="range" min="0.5" max="2" step="0.1" value="1">
<output id="speedValue">1.0×</output>
</label>
<div class="notice">
<strong>Illustrative model only.</strong>
Fixed-step heuristic routing and simplified separation are not calibrated
pedestrian-safety, evacuation-capacity, or code-compliance analysis.
</div>
</section>
<div class="help">
Drag to orbit · wheel to zoom · WASD to pan · double-click to reset camera
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101827);
scene.fog = new THREE.Fog(0x101827, 38, 76);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
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;
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
120
);
// Direct camera controls; no Three.js examples/addons are used.
const cameraState = {
target: new THREE.Vector3(0, 0.35, 0),
radius: 31,
theta: 0.67,
phi: 0.88
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
const horizontal = radius * Math.sin(phi);
camera.position.set(
target.x + horizontal * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + horizontal * Math.cos(theta)
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.target.set(0, 0.35, 0);
cameraState.radius = 31;
cameraState.theta = 0.67;
cameraState.phi = 0.88;
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.28,
1.38
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined &&
canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
15,
48
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement ||
event.target instanceof HTMLButtonElement) {
return;
}
const step = 0.18;
let handled = true;
switch (event.key.toLowerCase()) {
case "w": cameraState.target.z -= step; break;
case "s": cameraState.target.z += step; break;
case "a": cameraState.target.x -= step; break;
case "d": cameraState.target.x += step; break;
case "arrowleft": cameraState.theta -= 0.09; break;
case "arrowright": cameraState.theta += 0.09; break;
case "arrowup":
cameraState.phi = Math.max(0.28, cameraState.phi - 0.06);
break;
case "arrowdown":
cameraState.phi = Math.min(1.38, cameraState.phi + 0.06);
break;
case " ":
togglePause();
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
updateCamera();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
resetCamera();
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xc8ddff, 0x20283a, 1.8));
const sun = new THREE.DirectionalLight(0xfff3dc, 2.7);
sun.position.set(10, 18, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -24;
sun.shadow.camera.right = 24;
sun.shadow.camera.top = 20;
sun.shadow.camera.bottom = -20;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8bbcff, 0.7);
fill.position.set(-12, 8, -10);
scene.add(fill);
// -------------------------------------------------------------------------
// Reusable voxel geometry
// -------------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function material(color, roughness = 0.85, metalness = 0) {
return new THREE.MeshStandardMaterial({
color,
roughness,
metalness
});
}
function addBox(parent, size, position, mat, castShadow = true, receiveShadow = true) {
const mesh = new THREE.Mesh(unitBox, mat);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = receiveShadow;
parent.add(mesh);
return mesh;
}
const world = new THREE.Group();
scene.add(world);
const groundMaterial = material(0x0b111c);
addBox(
world,
[80, 0.5, 80],
[0, -0.72, 0],
groundMaterial,
false,
true
);
const baseMaterial = material(0x202b3d);
addBox(
world,
[28.8, 0.42, 18.8],
[0, -0.25, 0],
baseMaterial,
false,
true
);
// Deterministic hash used instead of Math.random.
function hash2D(x, z) {
let n = Math.imul(x + 97, 374761393) +
Math.imul(z + 131, 668265263);
n = Math.imul(n ^ (n >>> 13), 1274126177);
n ^= n >>> 16;
return (n >>> 0) / 4294967295;
}
const tileGeometry = new THREE.BoxGeometry(0.94, 0.08, 0.94);
const tileMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.92,
metalness: 0.02
});
const tileCount = 28 * 18;
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
const tileDummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let x = -13.5; x <= 13.5; x += 1) {
for (let z = -8.5; z <= 8.5; z += 1) {
const ix = Math.round(x);
const iz = Math.round(z);
tileDummy.position.set(x, 0.055, z);
tileDummy.updateMatrix();
tiles.setMatrixAt(tileIndex, tileDummy.matrix);
const variation = hash2D(ix, iz);
tileColor.setHSL(
0.59 + variation * 0.025,
0.18,
0.235 + variation * 0.055
);
tiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
tiles.receiveShadow = true;
world.add(tiles);
// Exit aprons outside the bounded interior.
const apronMaterial = material(0x1d2c3c);
addBox(world, [3.2, 0.12, 4.3], [-15.55, -0.04, 0], apronMaterial, false, true);
addBox(world, [3.2, 0.12, 4.3], [15.55, -0.04, 0], apronMaterial, false, true);
// -------------------------------------------------------------------------
// Walls, openings, and exit portals
// -------------------------------------------------------------------------
const wallMaterial = material(0x8996aa, 0.92);
const wallTrimMaterial = material(0x394a63, 0.78);
const portalMaterial = material(0x4c607a, 0.7, 0.12);
const exitAccentMaterial = material(0x51d6c8, 0.55, 0.12);
// North and south walls.
addBox(world, [28.8, 2.4, 0.5], [0, 1.2, 9.25], wallMaterial);
addBox(world, [28.8, 2.4, 0.5], [0, 1.2, -9.25], wallMaterial);
// West and east walls, each split around a four-unit exit opening.
for (const x of [-14.25, 14.25]) {
addBox(world, [0.5, 2.4, 7], [x, 1.2, -5.5], wallMaterial);
addBox(world, [0.5, 2.4, 7], [x, 1.2, 5.5], wallMaterial);
addBox(world, [0.65, 0.24, 7], [x, 0.16, -5.5], wallTrimMaterial);
addBox(world, [0.65, 0.24, 7], [x, 0.16, 5.5], wallTrimMaterial);
addBox(world, [0.65, 2.65, 0.28], [x, 1.32, -2.15], portalMaterial);
addBox(world, [0.65, 2.65, 0.28], [x, 1.32, 2.15], portalMaterial);
addBox(world, [0.65, 0.35, 4.58], [x, 2.48, 0], portalMaterial);
}
// Colored threshold strips.
addBox(world, [0.18, 0.11, 3.65], [-14.03, 0.13, 0], exitAccentMaterial);
addBox(world, [0.18, 0.11, 3.65], [14.03, 0.13, 0], material(0xffb457, 0.55, 0.12));
function makeExitSign(x, label, arrowDirection, rotationY) {
const signCanvas = document.createElement("canvas");
signCanvas.width = 512;
signCanvas.height = 160;
const context = signCanvas.getContext("2d");
context.fillStyle = "#10251f";
context.fillRect(0, 0, 512, 160);
context.strokeStyle = "#6fffee";
context.lineWidth = 12;
context.strokeRect(8, 8, 496, 144);
context.fillStyle = "#effffb";
context.font = "700 72px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(label, 270, 84);
context.beginPath();
const startX = arrowDirection < 0 ? 405 : 108;
const direction = arrowDirection < 0 ? -1 : 1;
context.moveTo(startX - direction * 28, 48);
context.lineTo(startX + direction * 22, 82);
context.lineTo(startX - direction * 28, 116);
context.lineTo(startX - direction * 6, 82);
context.closePath();
context.fillStyle = "#6fffee";
context.fill();
const texture = new THREE.CanvasTexture(signCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const signMaterial = new THREE.MeshBasicMaterial({
map: texture,
side: THREE.DoubleSide
});
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(3.5, 1.09),
signMaterial
);
sign.position.set(x, 2.25, 0);
sign.rotation.y = rotationY;
world.add(sign);
}
makeExitSign(-13.94, "EXIT A", -1, Math.PI / 2);
makeExitSign(13.94, "EXIT B", 1, -Math.PI / 2);
// -------------------------------------------------------------------------
// Benches and navigation obstacles
// -------------------------------------------------------------------------
const obstacles = [];
const woodMaterial = material(0xb77743, 0.8);
const benchDarkMaterial = material(0x6f452d, 0.85);
const metalMaterial = material(0x394451, 0.55, 0.45);
function addBench(cx, cz, axis) {
const group = new THREE.Group();
group.position.set(cx, 0, cz);
if (axis === "z") group.rotation.y = Math.PI / 2;
world.add(group);
addBox(group, [3.6, 0.3, 1.12], [0, 0.73, 0], woodMaterial);
addBox(group, [3.6, 0.72, 0.18], [0, 1.18, 0.47], benchDarkMaterial);
for (const x of [-1.35, 1.35]) {
for (const z of [-0.34, 0.34]) {
addBox(group, [0.18, 0.55, 0.18], [x, 0.31, z], metalMaterial);
}
}
const width = axis === "x" ? 3.9 : 1.35;
const depth = axis === "x" ? 1.35 : 3.9;
obstacles.push({
minX: cx - width / 2,
maxX: cx + width / 2,
minZ: cz - depth / 2,
maxZ: cz + depth / 2
});
}
addBench(-4, -3.5, "x");
addBench(4, 3.5, "x");
addBench(-5, 4, "z");
addBench(5, -4, "z");
// -------------------------------------------------------------------------
// Deterministic grid navigation
// -------------------------------------------------------------------------
const AGENT_RADIUS = 0.28;
const GRID = {
minX: -13,
maxX: 13,
minZ: -8,
maxZ: 8
};
function cellKey(x, z) {
return `${x},${z}`;
}
function isBlocked(x, z) {
const clearance = AGENT_RADIUS + 0.27;
for (const obstacle of obstacles) {
if (
x > obstacle.minX - clearance &&
x < obstacle.maxX + clearance &&
z > obstacle.minZ - clearance &&
z < obstacle.maxZ + clearance
) {
return true;
}
}
return false;
}
function nearestFreeCell(x, z) {
x = THREE.MathUtils.clamp(x, GRID.minX, GRID.maxX);
z = THREE.MathUtils.clamp(z, GRID.minZ, GRID.maxZ);
if (!isBlocked(x, z)) return { x, z };
for (let radius = 1; radius < 10; radius++) {
const candidates = [];
for (let dz = -radius; dz <= radius; dz++) {
for (let dx = -radius; dx <= radius; dx++) {
if (Math.abs(dx) !== radius && Math.abs(dz) !== radius) continue;
const nx = x + dx;
const nz = z + dz;
if (
nx < GRID.minX || nx > GRID.maxX ||
nz < GRID.minZ || nz > GRID.maxZ ||
isBlocked(nx, nz)
) {
continue;
}
candidates.push({ x: nx, z: nz, score: dx * dx + dz * dz });
}
}
candidates.sort((a, b) => a.score - b.score || a.z - b.z || a.x - b.x);
if (candidates.length) return { x: candidates[0].x, z: candidates[0].z };
}
return { x, z };
}
function heuristic(x, z, goal) {
return Math.abs(x - goal.x) + Math.abs(z - goal.z);
}
function findPath(startX, startZ, goalX, goalZ) {
const start = nearestFreeCell(startX, startZ);
const goal = nearestFreeCell(goalX, goalZ);
const startKey = cellKey(start.x, start.z);
const goalKey = cellKey(goal.x, goal.z);
const open = [{
x: start.x,
z: start.z,
g: 0,
h: heuristic(start.x, start.z, goal)
}];
const gScore = new Map([[startKey, 0]]);
const cameFrom = new Map();
const closed = new Set();
const directions = [
[1, 0], [-1, 0], [0, 1], [0, -1],
[1, 1], [1, -1], [-1, 1], [-1, -1]
];
while (open.length) {
open.sort((a, b) =>
a.g + a.h - (b.g + b.h) ||
a.h - b.h ||
a.z - b.z ||
a.x - b.x
);
const current = open.shift();
const currentKey = cellKey(current.x, current.z);
if (closed.has(currentKey)) continue;
closed.add(currentKey);
if (currentKey === goalKey) {
const path = [];
let node = { x: goal.x, z: goal.z };
while (node.x !== start.x || node.z !== start.z) {
path.push({ x: node.x, z: node.z });
node = cameFrom.get(cellKey(node.x, node.z));
if (!node) return [];
}
path.push({ x: start.x, z: start.z });
path.reverse();
return path;
}
for (const [dx, dz] of directions) {
const nx = current.x + dx;
const nz = current.z + dz;
if (
nx < GRID.minX || nx > GRID.maxX ||
nz < GRID.minZ || nz > GRID.maxZ ||
isBlocked(nx, nz)
) {
continue;
}
// Prevent diagonal corner cutting through benches.
if (dx !== 0 && dz !== 0) {
if (
isBlocked(current.x + dx, current.z) ||
isBlocked(current.x, current.z + dz)
) {
continue;
}
}
const nextKey = cellKey(nx, nz);
if (closed.has(nextKey)) continue;
const tentativeG = current.g + 1;
if (tentativeG < (gScore.get(nextKey) ?? Infinity)) {
gScore.set(nextKey, tentativeG);
cameFrom.set(nextKey, { x: current.x, z: current.z });
open.push({
x: nx,
z: nz,
g: tentativeG,
h: heuristic(nx, nz, goal)
});
}
}
}
return [];
}
// -------------------------------------------------------------------------
// Voxel people
// -------------------------------------------------------------------------
const routeGroup = new THREE.Group();
routeGroup.visible = false;
scene.add(routeGroup);
const routeMaterials = {
A: new THREE.LineBasicMaterial({
color: 0x51d6c8,
transparent: true,
opacity: 0.36
}),
B: new THREE.LineBasicMaterial({
color: 0xffb457,
transparent: true,
opacity: 0.36
})
};
const darkClothing = material(0x263247, 0.9);
const hairMaterial = material(0x2b2525, 0.95);
const skinMaterials = [
material(0xe4b087, 0.95),
material(0x9b6247, 0.95),
material(0xc98f68, 0.95),
material(0x744b38, 0.95)
];
const starts = [
[-11, -6], [-8, -6], [-11, 2], [-8, 6],
[-2, -6], [0, -6], [-2, 6], [0, 6],
[6, 6], [9, 6], [11, 2], [11, -6],
[-1, 0], [6, -1]
];
const agents = [];
function createAgent(id, start, exitCode) {
const group = new THREE.Group();
world.add(group);
const bodyMaterial = material(
exitCode === "A" ? 0x43bcae : 0xd88d3f,
0.82
);
const skin = skinMaterials[id % skinMaterials.length];
addBox(group, [0.48, 0.72, 0.34], [0, 0.92, 0], bodyMaterial);
addBox(group, [0.4, 0.4, 0.4], [0, 1.49, 0], skin);
addBox(group, [0.42, 0.13, 0.42], [0, 1.68, -0.015], hairMaterial);
addBox(group, [0.17, 0.54, 0.18], [-0.14, 0.31, 0], darkClothing);
addBox(group, [0.17, 0.54, 0.18], [0.14, 0.31, 0], darkClothing);
addBox(group, [0.14, 0.61, 0.16], [-0.34, 0.91, 0], bodyMaterial);
addBox(group, [0.14, 0.61, 0.16], [0.34, 0.91, 0], bodyMaterial);
if (id % 3 === 0) {
addBox(group, [0.34, 0.4, 0.18], [0, 1.02, -0.25], darkClothing);
}
const line = new THREE.Line(
new THREE.BufferGeometry(),
routeMaterials[exitCode]
);
line.frustumCulled = false;
routeGroup.add(line);
const agent = {
id,
start: new THREE.Vector2(start[0], start[1]),
pos: new THREE.Vector2(start[0], start[1]),
vel: new THREE.Vector2(),
exitCode,
speed: 1.12 + ((id * 7) % 5) * 0.07,
group,
line,
path: [],
active: true,
respawnAt: 0,
cycle: 0
};
agents.push(agent);
configureAgent(agent);
return agent;
}
function updateRouteLine(agent) {
const points = agent.path.map((point) =>
new THREE.Vector3(point.x, 0.125, point.y)
);
agent.line.geometry.dispose();
agent.line.geometry = new THREE.BufferGeometry().setFromPoints(points);
}
function configureAgent(agent) {
agent.pos.copy(agent.start);
agent.vel.set(0, 0);
agent.active = true;
agent.group.visible = true;
agent.group.position.set(agent.pos.x, 0, agent.pos.y);
agent.group.rotation.y = 0;
const goalX = agent.exitCode === "A" ? -13 : 13;
const cells = findPath(
Math.round(agent.start.x),
Math.round(agent.start.y),
goalX,
0
);
agent.path = cells.map((cell) => new THREE.Vector2(cell.x, cell.y));
agent.path.push(new THREE.Vector2(
agent.exitCode === "A" ? -15.3 : 15.3,
0
));
updateRouteLine(agent);
}
starts.forEach((start, id) => {
createAgent(id, start, id < 7 ? "A" : "B");
});
// -------------------------------------------------------------------------
// Local collision avoidance
// -------------------------------------------------------------------------
const desiredVelocity = new THREE.Vector2();
const separation = new THREE.Vector2();
const obstaclePush = new THREE.Vector2();
function addObstacleAvoidance(agent, output) {
output.set(0, 0);
const safeDistance = AGENT_RADIUS + 0.34;
for (const obstacle of obstacles) {
const closestX = THREE.MathUtils.clamp(
agent.pos.x,
obstacle.minX,
obstacle.maxX
);
const closestZ = THREE.MathUtils.clamp(
agent.pos.y,
obstacle.minZ,
obstacle.maxZ
);
const dx = agent.pos.x - closestX;
const dz = agent.pos.y - closestZ;
const distance = Math.hypot(dx, dz);
if (distance < safeDistance) {
if (distance > 0.0001) {
const strength = (safeDistance - distance) * 4.2;
output.x += dx / distance * strength;
output.y += dz / distance * strength;
} else {
// Rare fallback if the center enters an obstacle rectangle.
const sideDistances = [
agent.pos.x - obstacle.minX,
obstacle.maxX - agent.pos.x,
agent.pos.y - obstacle.minZ,
obstacle.maxZ - agent.pos.y
];
let minimumSide = 0;
for (let i = 1; i < sideDistances.length; i++) {
if (sideDistances[i] < sideDistances[minimumSide]) {
minimumSide = i;
}
}
if (minimumSide === 0) output.x -= 1;
if (minimumSide === 1) output.x += 1;
if (minimumSide === 2) output.y -= 1;
if (minimumSide === 3) output.y += 1;
}
}
}
}
function resolveObstacles(agent) {
const expanded = AGENT_RADIUS + 0.03;
for (const obstacle of obstacles) {
const minX = obstacle.minX - expanded;
const maxX = obstacle.maxX + expanded;
const minZ = obstacle.minZ - expanded;
const maxZ = obstacle.maxZ + expanded;
if (
agent.pos.x > minX && agent.pos.x < maxX &&
agent.pos.y > minZ && agent.pos.y < maxZ
) {
const distances = [
agent.pos.x - minX,
maxX - agent.pos.x,
agent.pos.y - minZ,
maxZ - agent.pos.y
];
let nearestSide = 0;
for (let i = 1; i < distances.length; i++) {
if (distances[i] < distances[nearestSide]) nearestSide = i;
}
if (nearestSide === 0) agent.pos.x = minX - 0.005;
if (nearestSide === 1) agent.pos.x = maxX + 0.005;
if (nearestSide === 2) agent.pos.y = minZ - 0.005;
if (nearestSide === 3) agent.pos.y = maxZ + 0.005;
}
}
}
function enforceBounds(agent) {
agent.pos.y = THREE.MathUtils.clamp(agent.pos.y, -8.48, 8.48);
if (agent.exitCode === "A") {
if (agent.pos.x < -13.55) {
agent.pos.y = THREE.MathUtils.clamp(agent.pos.y, -1.55, 1.55);
} else {
agent.pos.x = Math.min(agent.pos.x, 13.55);
}
} else {
if (agent.pos.x > 13.55) {
agent.pos.y = THREE.MathUtils.clamp(agent.pos.y, -1.55, 1.55);
} else {
agent.pos.x = Math.max(agent.pos.x, -13.55);
}
}
}
function canRespawn(agent) {
for (const other of agents) {
if (!other.active || other === agent) continue;
if (other.pos.distanceTo(agent.start) < 0.95) return false;
}
return true;
}
let simulationTime = 0;
let totalExited = 0;
function updateAgents(dt) {
simulationTime += dt;
// Steering and local separation.
for (const agent of agents) {
if (!agent.active) {
if (simulationTime >= agent.respawnAt && canRespawn(agent)) {
agent.cycle++;
configureAgent(agent);
}
continue;
}
while (
agent.path.length > 0 &&
agent.pos.distanceTo(agent.path[0]) < 0.2
) {
agent.path.shift();
}
desiredVelocity.set(0, 0);
if (agent.path.length) {
const target = agent.path[0];
const dx = target.x - agent.pos.x;
const dz = target.y - agent.pos.y;
const distance = Math.hypot(dx, dz);
if (distance > 0.0001) {
desiredVelocity.x = dx / distance * agent.speed;
desiredVelocity.y = dz / distance * agent.speed;
}
}
separation.set(0, 0);
for (const other of agents) {
if (!other.active || other === agent) continue;
const dx = agent.pos.x - other.pos.x;
const dz = agent.pos.y - other.pos.y;
const distance = Math.hypot(dx, dz);
if (distance < 1.25) {
if (distance > 0.0001) {
const strength = (1.25 - distance) * 2.65;
separation.x += dx / distance * strength;
separation.y += dz / distance * strength;
} else {
const direction = (agent.id + other.id) % 2 === 0 ? 1 : -1;
separation.x += direction * 0.04;
}
}
}
addObstacleAvoidance(agent, obstaclePush);
desiredVelocity.add(separation);
desiredVelocity.add(obstaclePush);
desiredVelocity.clampLength(0, agent.speed * 1.7);
const response = 1 - Math.exp(-6 * dt);
agent.vel.lerp(desiredVelocity, response);
agent.pos.addScaledVector(agent.vel, dt);
resolveObstacles(agent);
}
// Deterministic pairwise separation after integration.
for (let i = 0; i < agents.length; i++) {
const a = agents[i];
if (!a.active) continue;
for (let j = i + 1; j < agents.length; j++) {
const b = agents[j];
if (!b.active) continue;
let dx = a.pos.x - b.pos.x;
let dz = a.pos.y - b.pos.y;
let distance = Math.hypot(dx, dz);
const minimumDistance = AGENT_RADIUS * 2;
if (distance < minimumDistance) {
if (distance < 0.0001) {
dx = (i + j) % 2 === 0 ? 0.01 : -0.01;
dz = 0.01;
distance = Math.hypot(dx, dz);
}
const correction = (minimumDistance - distance) * 0.5;
const nx = dx / distance;
const nz = dz / distance;
a.pos.x += nx * correction;
a.pos.y += nz * correction;
b.pos.x -= nx * correction;
b.pos.y -= nz * correction;
}
}
}
// Apply transforms, exit detection, and deterministic respawn scheduling.
for (const agent of agents) {
if (!agent.active) continue;
resolveObstacles(agent);
enforceBounds(agent);
if (agent.vel.lengthSq() > 0.0025) {
agent.group.rotation.y = Math.atan2(agent.vel.x, agent.vel.y);
}
agent.group.position.set(
agent.pos.x,
Math.sin(simulationTime * 8 + agent.id) * 0.014,
agent.pos.y
);
const hasExited =
(agent.exitCode === "A" && agent.pos.x < -14.45) ||
(agent.exitCode === "B" && agent.pos.x > 14.45);
if (hasExited) {
agent.active = false;
agent.group.visible = false;
totalExited++;
agent.respawnAt = simulationTime + 3.2 + (agent.id % 4) * 0.55;
}
}
}
// -------------------------------------------------------------------------
// UI and simulation loop
// -------------------------------------------------------------------------
const pauseButton = document.querySelector("#pauseButton");
const resetButton = document.querySelector("#resetButton");
const routesButton = document.querySelector("#routesButton");
const speedSlider = document.querySelector("#speedSlider");
const speedValue = document.querySelector("#speedValue");
const insideCount = document.querySelector("#insideCount");
const exitedCount = document.querySelector("#exitedCount");
const clock = document.querySelector("#clock");
let paused = false;
let simulationSpeed = 1;
function togglePause() {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
pauseButton.classList.toggle("active", paused);
}
pauseButton.addEventListener("click", togglePause);
resetButton.addEventListener("click", () => {
simulationTime = 0;
totalExited = 0;
for (const agent of agents) {
agent.respawnAt = 0;
configureAgent(agent);
}
accumulator = 0;
updateHud();
});
routesButton.addEventListener("click", () => {
routeGroup.visible = !routeGroup.visible;
routesButton.classList.toggle("active", routeGroup.visible);
});
speedSlider.addEventListener("input", () => {
simulationSpeed = Number(speedSlider.value);
speedValue.value = `${simulationSpeed.toFixed(1)}×`;
});
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const remaining = Math.floor(seconds % 60);
return `${String(minutes).padStart(2, "0")}:${String(remaining).padStart(2, "0")}`;
}
function updateHud() {
const inside = agents.reduce((count, agent) => count + (agent.active ? 1 : 0), 0);
insideCount.textContent = String(inside);
exitedCount.textContent = String(totalExited);
clock.textContent = formatTime(simulationTime);
}
const FIXED_STEP = 1 / 60;
let accumulator = 0;
let lastFrame = performance.now();
let hudTimer = 0;
function animate(now) {
requestAnimationFrame(animate);
const frameDelta = Math.min((now - lastFrame) / 1000, 0.1);
lastFrame = now;
if (!paused) {
accumulator += frameDelta * simulationSpeed;
while (accumulator >= FIXED_STEP) {
updateAgents(FIXED_STEP);
accumulator -= FIXED_STEP;
}
} else {
accumulator = 0;
}
hudTimer += frameDelta;
if (hudTimer >= 0.1) {
updateHud();
hudTimer = 0;
}
renderer.render(scene, camera);
}
updateHud();
requestAnimationFrame(animate);
</script>
</body>
</html>
```