Prompt specification
Build or customize the Three.js 3D scene "Village service detour around a karst sinkhole" 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: Village service detour around a karst sinkhole
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/village-service-detour-around-a-karst-sinkhole-x1155
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a voxel village with a sinkhole severing its service road and hypothetical cave voids in cutaway. Reroute a delivery cart around marked exclusion zones under explicitly geometric rules. Voxel style.
Working Three.js Starter (village-service-detour-around-a-karst-sinkhole-x1155):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sinkline Hamlet — Voxel Reroute</title>
<style>
:root {
--bg: #101820;
--panel: rgba(17, 26, 34, 0.88);
--panel-line: rgba(190, 224, 235, 0.16);
--text: #eef8fa;
--muted: #9bb1b9;
--cyan: #55e6f2;
--cyan-soft: rgba(85, 230, 242, 0.16);
--red: #ff5c62;
--amber: #ffbd59;
--green: #73e5a2;
}
* {
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;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#overlay {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 3;
}
.panel {
position: absolute;
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--panel-line);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.brand {
top: 20px;
left: 20px;
width: min(410px, calc(100vw - 40px));
padding: 18px 20px 17px;
border-radius: 14px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 9px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 38px);
line-height: 1;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 350px;
margin: 10px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.status {
top: 20px;
right: 20px;
width: 286px;
padding: 15px 16px;
border-radius: 14px;
}
.status-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding-bottom: 11px;
border-bottom: 1px solid var(--panel-line);
}
.status-label {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.badge {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--green);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.badge::before {
content: "";
width: 7px;
height: 7px;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.badge.invalid {
color: var(--red);
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 11px 14px;
margin-top: 13px;
}
.stat span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat strong {
display: block;
margin-top: 3px;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.rules {
top: 178px;
right: 20px;
width: 286px;
padding: 15px 16px 14px;
border-radius: 14px;
}
.rules-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
color: var(--text);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.rules-title::after {
content: "1 m GRID";
padding: 4px 6px;
border: 1px solid var(--panel-line);
color: var(--muted);
font-size: 8px;
letter-spacing: 0.1em;
}
.rule {
position: relative;
display: grid;
grid-template-columns: 22px 1fr;
gap: 9px;
margin: 10px 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.rule b {
color: var(--text);
}
.rule-number {
display: grid;
width: 21px;
height: 21px;
place-items: center;
border: 1px solid rgba(85, 230, 242, 0.35);
color: var(--cyan);
background: var(--cyan-soft);
font-size: 9px;
font-weight: 900;
}
.formula {
margin-top: 12px;
padding: 10px;
border: 1px solid rgba(85, 230, 242, 0.14);
background: rgba(85, 230, 242, 0.055);
color: #bfeff3;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.55;
}
.legend {
left: 20px;
bottom: 20px;
width: 270px;
padding: 13px 15px;
border-radius: 13px;
}
.legend-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px 12px;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.25;
}
.swatch {
flex: 0 0 auto;
width: 13px;
height: 13px;
border: 2px solid currentColor;
}
.swatch.cyan {
color: var(--cyan);
background: rgba(85, 230, 242, 0.22);
}
.swatch.red {
color: var(--red);
background: repeating-linear-gradient(
45deg,
rgba(255, 92, 98, 0.5) 0 3px,
transparent 3px 6px
);
}
.swatch.cave {
color: #7ce9f2;
background: rgba(124, 233, 242, 0.22);
}
.swatch.dashed {
color: var(--amber);
border-style: dashed;
}
.controls {
left: 50%;
bottom: 20px;
width: min(570px, calc(100vw - 630px));
min-width: 440px;
transform: translateX(-50%);
padding: 13px 15px;
border-radius: 14px;
}
.control-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 13px;
}
button {
min-width: 104px;
padding: 10px 13px;
border: 1px solid rgba(85, 230, 242, 0.4);
border-radius: 8px;
background: rgba(85, 230, 242, 0.12);
color: var(--cyan);
font: inherit;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
transition: background 150ms, transform 150ms;
}
button:hover {
background: rgba(85, 230, 242, 0.22);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
.slider-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.slider-label output {
color: var(--text);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 5px;
outline: none;
background: linear-gradient(
90deg,
var(--cyan) 0%,
var(--cyan) 31%,
rgba(255, 255, 255, 0.12) 31%,
rgba(255, 255, 255, 0.12) 100%
);
appearance: none;
-webkit-appearance: none;
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
border: 2px solid #dffbff;
border-radius: 3px;
background: var(--cyan);
box-shadow: 0 0 10px rgba(85, 230, 242, 0.7);
cursor: ew-resize;
appearance: none;
-webkit-appearance: none;
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #dffbff;
border-radius: 3px;
background: var(--cyan);
box-shadow: 0 0 10px rgba(85, 230, 242, 0.7);
cursor: ew-resize;
}
.hint {
margin-top: 9px;
color: #748c95;
font-size: 9px;
text-align: center;
letter-spacing: 0.035em;
}
.world-label {
position: absolute;
left: 0;
top: 0;
padding: 6px 8px;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 5px;
background: rgba(13, 21, 28, 0.82);
color: #eaf8fa;
box-shadow: 0 5px 18px rgba(0, 0, 0, 0.22);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
white-space: nowrap;
transform: translate(-50%, -50%);
}
.world-label.danger {
border-color: rgba(255, 92, 98, 0.55);
color: #ff969a;
}
.world-label.cave {
border-color: rgba(85, 230, 242, 0.55);
color: #8df0f7;
}
.world-label.route {
border-color: rgba(85, 230, 242, 0.42);
color: var(--cyan);
}
@media (max-width: 1050px) {
.brand {
width: 330px;
}
.status,
.rules {
width: 250px;
}
.controls {
left: 20px;
bottom: 20px;
width: calc(100vw - 310px);
min-width: 360px;
transform: none;
}
.legend {
display: none;
}
}
@media (max-width: 720px) {
.brand {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 15px;
}
.subtitle {
display: none;
}
.status {
top: 108px;
right: 10px;
width: 210px;
padding: 11px;
}
.status .stats {
gap: 8px;
}
.stat strong {
font-size: 13px;
}
.rules {
top: 108px;
left: 10px;
right: auto;
width: calc(100vw - 240px);
max-height: 42vh;
overflow: auto;
padding: 11px;
}
.rule {
grid-template-columns: 19px 1fr;
gap: 6px;
font-size: 10px;
}
.rule-number {
width: 18px;
height: 18px;
}
.formula {
display: none;
}
.controls {
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
min-width: 0;
}
.hint {
display: none;
}
.world-label {
font-size: 7px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel village and delivery reroute"></canvas>
<div id="overlay">
<header class="panel brand">
<div class="eyebrow">Geologic logistics / scenario 04</div>
<h1>Sinkline Hamlet</h1>
<p class="subtitle">
A voxel delivery route crosses a collapsed service road. A second route is
computed around geometric exclusion envelopes and a hypothetical cave void.
</p>
</header>
<section class="panel status">
<div class="status-head">
<span class="status-label">Route evaluation</span>
<span id="routeBadge" class="badge">Valid</span>
</div>
<div class="stats">
<div class="stat">
<span>Distance</span>
<strong id="routeLength">—</strong>
</div>
<div class="stat">
<span>Grid cells</span>
<strong id="routeCells">—</strong>
</div>
<div class="stat">
<span>Decision</span>
<strong id="routeDecision">—</strong>
</div>
<div class="stat">
<span>Direct conflicts</span>
<strong id="routeConflicts">—</strong>
</div>
</div>
</section>
<aside class="panel rules">
<div class="rules-title">Explicit geometric rules</div>
<div class="rule">
<span class="rule-number">1</span>
<div>
The service network is rasterized into <b>1 m cells</b>. Moves are
<b>cardinal only</b>; diagonal corner cutting is forbidden.
</div>
</div>
<div class="rule">
<span class="rule-number">2</span>
<div>
The cart has a <b>0.55 m half-width envelope</b>. The selected safety
buffer is added to every exclusion rectangle.
</div>
</div>
<div class="rule">
<span class="rule-number">3</span>
<div>
A cell is blocked when its center intersects an axis-aligned
<b>square-dilated exclusion rectangle</b>.
</div>
</div>
<div class="rule">
<span class="rule-number">4</span>
<div>
A* returns the minimum-length valid path through the remaining
service-road cells.
</div>
</div>
<div class="formula" id="formulaText">
blocked ⇔ center ∈ rect ⊕ [−r−b, r+b]²<br>
r = 0.55 m b = selected buffer
</div>
</aside>
<section class="panel legend">
<div class="legend-grid">
<div class="legend-item">
<span class="swatch cyan"></span>
Computed delivery route
</div>
<div class="legend-item">
<span class="swatch red"></span>
Exclusion projection
</div>
<div class="legend-item">
<span class="swatch cave"></span>
Hypothetical cave void
</div>
<div class="legend-item">
<span class="swatch dashed"></span>
Required clearance edge
</div>
</div>
</section>
<section class="panel controls">
<div class="control-row">
<button id="playToggle" type="button">Pause cart</button>
<div>
<label class="slider-label" for="clearance">
<span>Exclusion safety buffer</span>
<output id="clearanceValue">0.75 m</output>
</label>
<input
id="clearance"
type="range"
min="0.25"
max="2"
step="0.25"
value="0.75"
>
</div>
<div class="stat" style="min-width: 82px">
<span>Total envelope</span>
<strong id="totalEnvelope">1.30 m</strong>
</div>
</div>
<div class="hint">
Drag to orbit · Shift-drag to pan · Scroll to zoom · Cyan cart follows the
minimum-length safe route
</div>
</section>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene, renderer, and direct orthographic camera controls.
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101820);
scene.fog = new THREE.Fog(0x101820, 45, 80);
const camera = new THREE.OrthographicCamera(-20, 20, 15, -15, 0.1, 120);
const controls = {
theta: 0.69,
phi: 0.89,
zoom: 1,
target: new THREE.Vector3(0, -0.55, 0),
dragging: false,
panMode: false,
lastX: 0,
lastY: 0
};
function fitView() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const fittedHeight = Math.max(24, 35 / aspect);
const viewHeight = fittedHeight * controls.zoom;
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
function updateCamera() {
const radius = 48;
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x + radius * sinPhi * Math.sin(controls.theta),
controls.target.y + radius * Math.cos(controls.phi),
controls.target.z + radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
camera.updateMatrixWorld();
}
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
controls.dragging = true;
controls.panMode = event.shiftKey || event.button === 2;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!controls.dragging) return;
const dx = event.clientX - controls.lastX;
const dy = event.clientY - controls.lastY;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
if (controls.panMode) {
const fit = Math.max(24, 35 / (window.innerWidth / window.innerHeight));
const worldPerPixel =
(fit * controls.zoom) / Math.max(1, window.innerHeight);
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 0);
right.y = 0;
right.normalize();
const forward = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 2);
forward.y = 0;
forward.normalize();
controls.target.addScaledVector(right, -dx * worldPerPixel);
controls.target.addScaledVector(forward, dy * worldPerPixel);
} else {
controls.theta -= dx * 0.006;
controls.phi = THREE.MathUtils.clamp(
controls.phi - dy * 0.005,
0.3,
1.35
);
}
updateCamera();
});
function endDrag(event) {
controls.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();
controls.zoom = THREE.MathUtils.clamp(
controls.zoom * Math.exp(event.deltaY * 0.001),
0.52,
1.75
);
fitView();
},
{ passive: false }
);
window.addEventListener("resize", fitView);
fitView();
updateCamera();
// -------------------------------------------------------------------------
// Lighting.
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xb9e8ff, 0x4b382b, 2.0));
const sun = new THREE.DirectionalLight(0xfff1cf, 3.0);
sun.position.set(-12, 25, 16);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -22;
sun.shadow.camera.right = 22;
sun.shadow.camera.top = 22;
sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x69cfff, 0.75);
fill.position.set(18, 10, -18);
scene.add(fill);
// -------------------------------------------------------------------------
// Materials.
// -------------------------------------------------------------------------
const materials = {
grass: new THREE.MeshStandardMaterial({ color: 0x678f57, roughness: 1 }),
grass2: new THREE.MeshStandardMaterial({ color: 0x739c60, roughness: 1 }),
road: new THREE.MeshStandardMaterial({ color: 0x4d5b62, roughness: 0.96 }),
soil: new THREE.MeshStandardMaterial({ color: 0x795740, roughness: 1 }),
soilDark: new THREE.MeshStandardMaterial({ color: 0x5d4335, roughness: 1 }),
rock: new THREE.MeshStandardMaterial({ color: 0x766c61, roughness: 1 }),
base: new THREE.MeshStandardMaterial({ color: 0x26313a, roughness: 0.9 }),
trim: new THREE.MeshStandardMaterial({ color: 0x26333b, roughness: 0.8 }),
yellow: new THREE.MeshStandardMaterial({
color: 0xf2c45c,
emissive: 0x8a5d14,
emissiveIntensity: 0.35,
roughness: 0.8
}),
window: new THREE.MeshStandardMaterial({
color: 0xffdc87,
emissive: 0xffad42,
emissiveIntensity: 0.9,
roughness: 0.55
}),
red: new THREE.MeshStandardMaterial({ color: 0xe9575d, roughness: 0.8 }),
cream: new THREE.MeshStandardMaterial({ color: 0xe8dfc4, roughness: 0.9 }),
bark: new THREE.MeshStandardMaterial({ color: 0x72503a, roughness: 1 }),
leafA: new THREE.MeshStandardMaterial({ color: 0x3f7751, roughness: 1 }),
leafB: new THREE.MeshStandardMaterial({ color: 0x57935f, roughness: 1 }),
cyan: new THREE.MeshStandardMaterial({
color: 0x69eef7,
emissive: 0x1ea7b5,
emissiveIntensity: 0.85,
roughness: 0.45
}),
cartBody: new THREE.MeshStandardMaterial({
color: 0x44cbd6,
emissive: 0x116a74,
emissiveIntensity: 0.35,
roughness: 0.5
}),
cartCargo: new THREE.MeshStandardMaterial({ color: 0xc99555, roughness: 0.9 }),
wheel: new THREE.MeshStandardMaterial({ color: 0x202a30, roughness: 0.95 }),
wheelHub: new THREE.MeshStandardMaterial({ color: 0x91a4ac, roughness: 0.6 }),
caveFill: new THREE.MeshBasicMaterial({
color: 0x57dfea,
transparent: true,
opacity: 0.2,
depthWrite: false,
depthTest: false
}),
caveEdge: new THREE.LineBasicMaterial({
color: 0x8af3fa,
transparent: true,
opacity: 0.92,
depthTest: false
}),
caveCap: new THREE.MeshBasicMaterial({
color: 0x83dce3,
transparent: true,
opacity: 0.12,
depthWrite: false
})
};
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Road graph, hazard rectangles, and geometric collision rules.
// -------------------------------------------------------------------------
const GRID = {
nx: 27,
nz: 19,
cell: 1
};
const CART_HALF_WIDTH = 0.55;
const hazards = {
sinkhole: {
minX: 2.5,
maxX: 5.5,
minZ: -0.5,
maxZ: 2.5
},
cave: {
minX: 3.5,
maxX: 8.5,
minZ: 3.5,
maxZ: 8.5
}
};
const roadCells = new Set();
const roadRows = [];
const roadColumns = [];
function cellKey(i, j) {
return `${i},${j}`;
}
function cellCenter(i, j) {
return {
x: i - (GRID.nx - 1) / 2,
z: j - (GRID.nz - 1) / 2
};
}
function addRoadRow(j, i0 = 0, i1 = GRID.nx - 1) {
roadRows.push({ j, i0, i1 });
for (let i = i0; i <= i1; i++) roadCells.add(cellKey(i, j));
}
function addRoadColumn(i, j0, j1) {
roadColumns.push({ i, j0, j1 });
for (let j = j0; j <= j1; j++) roadCells.add(cellKey(i, j));
}
addRoadRow(10); // Severed east-west service road
addRoadRow(5, 4, 22); // Northern service loop
addRoadRow(15, 4, 22); // Southern service loop
addRoadColumn(4, 5, 15); // West connectors
addRoadColumn(22, 5, 15); // East connectors
const startCell = { i: 1, j: 10 };
const goalCell = { i: 25, j: 10 };
let safetyBuffer = 0.75;
function expandedRect(rect, amount) {
return {
minX: rect.minX - amount,
maxX: rect.maxX + amount,
minZ: rect.minZ - amount,
maxZ: rect.maxZ + amount
};
}
function pointInsideExpandedRect(x, z, rect, amount) {
return (
x >= rect.minX - amount &&
x <= rect.maxX + amount &&
z >= rect.minZ - amount &&
z <= rect.maxZ + amount
);
}
function cellBlocked(i, j) {
const p = cellCenter(i, j);
const envelope = CART_HALF_WIDTH + safetyBuffer;
return (
pointInsideExpandedRect(
p.x,
p.z,
hazards.sinkhole,
envelope
) ||
pointInsideExpandedRect(p.x, p.z, hazards.cave, envelope)
);
}
function findRoute() {
const blocked = new Set();
for (const key of roadCells) {
const [i, j] = key.split(",").map(Number);
if (cellBlocked(i, j)) blocked.add(key);
}
const startKey = cellKey(startCell.i, startCell.j);
const goalKey = cellKey(goalCell.i, goalCell.j);
if (blocked.has(startKey) || blocked.has(goalKey)) return null;
const heuristic = (i, j) =>
Math.abs(i - goalCell.i) + Math.abs(j - goalCell.j);
const open = [
{
i: startCell.i,
j: startCell.j,
g: 0,
f: heuristic(startCell.i, startCell.j)
}
];
const cameFrom = new Map();
const gScore = new Map([[startKey, 0]]);
const closed = new Set();
while (open.length) {
open.sort((a, b) => a.f - b.f);
const current = open.shift();
const currentKey = cellKey(current.i, current.j);
if (currentKey === goalKey) {
const path = [];
let key = goalKey;
while (key) {
const [i, j] = key.split(",").map(Number);
path.push({ i, j });
key = cameFrom.get(key);
}
path.reverse();
return { path, blocked };
}
if (closed.has(currentKey)) continue;
closed.add(currentKey);
const neighbors = [
[current.i + 1, current.j],
[current.i - 1, current.j],
[current.i, current.j + 1],
[current.i, current.j - 1]
];
for (const [ni, nj] of neighbors) {
if (
ni < 0 ||
ni >= GRID.nx ||
nj < 0 ||
nj >= GRID.nz
) {
continue;
}
const nextKey = cellKey(ni, nj);
if (!roadCells.has(nextKey) || blocked.has(nextKey)) continue;
const tentative = current.g + 1;
if (tentative < (gScore.get(nextKey) ?? Infinity)) {
cameFrom.set(nextKey, currentKey);
gScore.set(nextKey, tentative);
open.push({
i: ni,
j: nj,
g: tentative,
f: tentative + heuristic(ni, nj)
});
}
}
}
return null;
}
// -------------------------------------------------------------------------
// Voxel terrain and road surface.
// -------------------------------------------------------------------------
const terrain = new THREE.Group();
scene.add(terrain);
const sinkCells = new Set();
for (let i = 16; i <= 18; i++) {
for (let j = 9; j <= 11; j++) sinkCells.add(cellKey(i, j));
}
const caveCells = new Set();
for (let i = 17; i <= 21; i++) {
for (let j = 13; j <= 17; j++) caveCells.add(cellKey(i, j));
}
const frontCutCells = new Set();
for (let i = 22; i <= 26; i++) {
for (let j = 16; j <= 18; j++) frontCutCells.add(cellKey(i, j));
}
function deterministicNoise(i, j) {
const value = Math.sin(i * 12.9898 + j * 78.233) * 43758.5453;
return value - Math.floor(value);
}
const topTransforms = [];
const topColors = [];
const bodyTransforms = [];
const bodyColors = [];
const caveCapTransforms = [];
const grassA = new THREE.Color(0x638e55);
const grassB = new THREE.Color(0x719a5b);
const roadColor = new THREE.Color(0x4d5a61);
const soilColor = new THREE.Color(0x76543e);
const soilColorB = new THREE.Color(0x684b39);
for (let i = 0; i < GRID.nx; i++) {
for (let j = 0; j < GRID.nz; j++) {
const key = cellKey(i, j);
const p = cellCenter(i, j);
if (sinkCells.has(key) || frontCutCells.has(key)) continue;
if (caveCells.has(key)) {
caveCapTransforms.push(p);
continue;
}
topTransforms.push(p);
if (roadCells.has(key)) {
topColors.push(roadColor);
} else {
topColors.push(
deterministicNoise(i, j) > 0.48 ? grassA : grassB
);
}
if (!caveCells.has(key)) {
bodyTransforms.push(p);
bodyColors.push(
deterministicNoise(i + 7, j - 3) > 0.52
? soilColor
: soilColorB
);
}
}
}
function createInstancedBoxes(
transforms,
colors,
geometry,
material
) {
const mesh = new THREE.InstancedMesh(
geometry,
material,
transforms.length
);
const matrix = new THREE.Matrix4();
transforms.forEach((p, index) => {
matrix.makeTranslation(p.x, p.y, p.z);
mesh.setMatrixAt(index, matrix);
mesh.setColorAt(index, colors[index]);
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
const topGeometry = new THREE.BoxGeometry(0.98, 0.16, 0.98);
const bodyGeometry = new THREE.BoxGeometry(0.98, 2.35, 0.98);
const topMesh = createInstancedBoxes(
topTransforms,
topColors,
topGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
})
);
topMesh.position.y = 0.08;
terrain.add(topMesh);
const bodyMesh = createInstancedBoxes(
bodyTransforms,
bodyColors,
bodyGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
})
);
bodyMesh.position.y = -1.175;
terrain.add(bodyMesh);
const caveCapMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.98, 0.055, 0.98),
materials.caveCap,
caveCapTransforms.length
);
const capMatrix = new THREE.Matrix4();
caveCapTransforms.forEach((p, index) => {
capMatrix.makeTranslation(p.x, 0.14, p.z);
caveCapMesh.setMatrixAt(index, capMatrix);
});
caveCapMesh.instanceMatrix.needsUpdate = true;
caveCapMesh.renderOrder = 2;
terrain.add(caveCapMesh);
addBox(
terrain,
[27.7, 0.55, 19.7],
[0, -2.48, 0],
materials.base
);
// Road center marks.
for (const row of roadRows) {
for (let i = row.i0; i <= row.i1; i += 2) {
const key = cellKey(i, row.j);
if (sinkCells.has(key) || caveCells.has(key)) continue;
const p = cellCenter(i, row.j);
addBox(
terrain,
[0.42, 0.035, 0.075],
[p.x, 0.19, p.z],
materials.yellow,
false
);
}
}
// -------------------------------------------------------------------------
// Sinkhole pit, barriers, and exclusion hatching.
// -------------------------------------------------------------------------
function makeHatchTexture() {
const c = document.createElement("canvas");
c.width = 64;
c.height = 64;
const ctx = c.getContext("2d");
ctx.clearRect(0, 0, 64, 64);
ctx.fillStyle = "rgba(255, 78, 87, 0.18)";
ctx.fillRect(0, 0, 64, 64);
ctx.strokeStyle = "rgba(255, 102, 108, 0.88)";
ctx.lineWidth = 8;
for (let x = -64; x < 128; x += 22) {
ctx.beginPath();
ctx.moveTo(x, 64);
ctx.lineTo(x + 64, 0);
ctx.stroke();
}
const texture = new THREE.CanvasTexture(c);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(3, 3);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const hatchTexture = makeHatchTexture();
const hatchMaterial = new THREE.MeshBasicMaterial({
map: hatchTexture,
transparent: true,
side: THREE.DoubleSide,
depthWrite: false
});
const sinkHole = new THREE.Group();
scene.add(sinkHole);
addBox(
sinkHole,
[3.1, 0.24, 3.1],
[4, -1.86, 1],
materials.soilDark
);
const rubblePositions = [
[3.25, -1.48, 0.25],
[4.65, -1.48, 0.6],
[3.8, -1.43, 1.85],
[5.05, -1.38, 1.45],
[2.95, -1.5, 1.25]
];
rubblePositions.forEach((position, index) => {
const rock = addBox(
sinkHole,
index % 2 ? [0.48, 0.45, 0.5] : [0.6, 0.32, 0.42],
position,
index % 2 ? materials.rock : materials.soilDark
);
rock.rotation.y = index * 0.47;
});
const sinkProjection = new THREE.Mesh(
new THREE.PlaneGeometry(3, 3),
hatchMaterial
);
sinkProjection.rotation.x = -Math.PI / 2;
sinkProjection.position.set(4, 0.225, 1);
sinkProjection.renderOrder = 4;
scene.add(sinkProjection);
function makeBarrier(x) {
const group = new THREE.Group();
group.position.set(x, 0.16, 1);
addBox(group, [0.16, 1.2, 0.16], [0, 0.6, -0.68], materials.trim);
addBox(group, [0.16, 1.2, 0.16], [0, 0.6, 0.68], materials.trim);
addBox(group, [0.18, 0.2, 1.55], [0, 0.88, 0], materials.red);
for (let z = -0.55; z <= 0.55; z += 0.28) {
addBox(
group,
[0.205, 0.205, 0.13],
[0, 0.88, z],
materials.cream
);
}
scene.add(group);
}
makeBarrier(1.15);
makeBarrier(6.85);
// -------------------------------------------------------------------------
// Cave cutaway: stepped translucent chamber volumes and geology details.
// -------------------------------------------------------------------------
const caveGroup = new THREE.Group();
scene.add(caveGroup);
const caveBoxes = [
{ size: [3.2, 1.65, 1.9], position: [5.25, -1.35, 5.15] },
{ size: [2.25, 1.45, 2.5], position: [6.95, -1.4, 6.4] },
{ size: [1.25, 1.25, 1.35], position: [7.85, -1.45, 7.4] }
];
caveBoxes.forEach(({ size, position }) => {
const fill = new THREE.Mesh(
new THREE.BoxGeometry(...size),
materials.caveFill
);
fill.position.set(...position);
fill.renderOrder = 7;
caveGroup.add(fill);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(...size)
),
materials.caveEdge
);
edges.position.copy(fill.position);
edges.renderOrder = 8;
caveGroup.add(edges);
});
const caveStalactites = [
[4.45, -0.28, 4.8, 0.18, 0.72],
[5.4, -0.2, 5.35, 0.15, 0.55],
[6.35, -0.35, 6.1, 0.22, 0.9],
[7.25, -0.25, 6.75, 0.16, 0.65],
[7.75, -0.38, 7.55, 0.2, 0.82]
];
caveStalactites.forEach(([x, y, z, w, h]) => {
addBox(
caveGroup,
[w, h, w],
[x, y, z],
new THREE.MeshStandardMaterial({
color: 0x4b7c83,
roughness: 0.9,
emissive: 0x163e44,
emissiveIntensity: 0.35
})
);
});
const caveProjection = new THREE.Mesh(
new THREE.PlaneGeometry(5, 5),
hatchMaterial
);
caveProjection.rotation.x = -Math.PI / 2;
caveProjection.position.set(6, 0.23, 6);
caveProjection.renderOrder = 5;
scene.add(caveProjection);
// Corner section posts emphasize that the cave is a subsurface projection.
const caveCorners = [
[3.5, 3.5],
[8.5, 3.5],
[3.5, 8.5],
[8.5, 8.5]
];
caveCorners.forEach(([x, z]) => {
addBox(
caveGroup,
[0.06, 2.35, 0.06],
[x, -1.05, z],
materials.cyan,
false
);
});
// -------------------------------------------------------------------------
// Exclusion outlines.
// -------------------------------------------------------------------------
function makeRectLine(rect, y, color, dashSize = 0.28) {
const points = [
new THREE.Vector3(rect.minX, y, rect.minZ),
new THREE.Vector3(rect.maxX, y, rect.minZ),
new THREE.Vector3(rect.maxX, y, rect.maxZ),
new THREE.Vector3(rect.minX, y, rect.maxZ),
new THREE.Vector3(rect.minX, y, rect.minZ)
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineDashedMaterial({
color,
dashSize,
gapSize: 0.18,
transparent: true,
opacity: 0.95,
depthTest: false
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
line.renderOrder = 9;
scene.add(line);
return line;
}
function updateRectLine(line, rect, y) {
const points = [
new THREE.Vector3(rect.minX, y, rect.minZ),
new THREE.Vector3(rect.maxX, y, rect.minZ),
new THREE.Vector3(rect.maxX, y, rect.maxZ),
new THREE.Vector3(rect.minX, y, rect.maxZ),
new THREE.Vector3(rect.minX, y, rect.minZ)
];
line.geometry.setFromPoints(points);
line.computeLineDistances();
}
const sinkClearanceLine = makeRectLine(
expandedRect(hazards.sinkhole, CART_HALF_WIDTH + safetyBuffer),
0.31,
0xffbd59
);
const caveClearanceLine = makeRectLine(
expandedRect(hazards.cave, CART_HALF_WIDTH + safetyBuffer),
0.32,
0xffbd59
);
// -------------------------------------------------------------------------
// Voxel village.
// -------------------------------------------------------------------------
const village = new THREE.Group();
scene.add(village);
function buildHouse({ x, z, w, d, h, wall, roof }) {
const group = new THREE.Group();
group.position.set(x, 0.16, z);
village.add(group);
const wallMaterial = new THREE.MeshStandardMaterial({
color: wall,
roughness: 0.95
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: roof,
roughness: 0.9
});
addBox(
group,
[w + 0.18, 0.2, d + 0.18],
[0, 0.1, 0],
materials.trim
);
addBox(group, [w, h, d], [0, h / 2 + 0.2, 0], wallMaterial);
// Stepped, block-built roof.
for (let layer = 0; layer < 4; layer++) {
const layerWidth = w + 0.42 - layer * 0.28;
const layerDepth = d + 0.42 - layer * 0.25;
addBox(
group,
[Math.max(0.45, layerWidth), 0.25, Math.max(0.45, layerDepth)],
[0, h + 0.42 + layer * 0.22, 0],
roofMaterial
);
}
addBox(
group,
[0.48, 0.78, 0.16],
[0, 0.61, d / 2 + 0.035],
materials.trim
);
const windowY = h * 0.63;
const windowX = w * 0.28;
for (const wx of [-windowX, windowX]) {
addBox(
group,
[0.42, 0.42, 0.08],
[wx, windowY, d / 2 + 0.055],
materials.window,
false
);
}
addBox(
group,
[0.08, 0.42, 0.42],
[w / 2 + 0.055, windowY, 0.25],
materials.window,
false
);
addBox(
group,
[0.34, 0.62, 0.34],
[w * 0.25, h + 1.25, -d * 0.18],
materials.trim
);
}
const houses = [
{ x: -10, z: -7, w: 3.0, d: 2.0, h: 2.4, wall: 0xd9c29e, roof: 0x9d5145 },
{ x: -5.2, z: -7, w: 2.6, d: 2.0, h: 2.2, wall: 0xc9d6c5, roof: 0x4f7480 },
{ x: -0.4, z: -7, w: 3.2, d: 2.3, h: 2.7, wall: 0xe0b66f, roof: 0x875044 },
{ x: 4.9, z: -7, w: 2.5, d: 2.0, h: 2.3, wall: 0xbad0cf, roof: 0x4d6f7a },
{ x: 10, z: -6.8, w: 2.5, d: 2.0, h: 2.2, wall: 0xd9c8aa, roof: 0x8e5650 },
{ x: -5.1, z: 3.7, w: 2.6, d: 1.8, h: 2.2, wall: 0xc8d5bb, roof: 0x5f7680 },
{ x: -1.0, z: 3.8, w: 2.4, d: 1.8, h: 2.1, wall: 0xe0c48f, roof: 0x985449 }
];
houses.forEach(buildHouse);
function buildTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0.16, z);
village.add(group);
addBox(
group,
[0.22 * scale, 1.05 * scale, 0.22 * scale],
[0, 0.53 * scale, 0],
materials.bark
);
addBox(
group,
[0.8 * scale, 0.8 * scale, 0.8 * scale],
[0, 1.22 * scale, 0],
materials.leafA
);
addBox(
group,
[0.58 * scale, 0.58 * scale, 0.58 * scale],
[0.28 * scale, 1.68 * scale, 0.08 * scale],
materials.leafB
);
addBox(
group,
[0.5 * scale, 0.5 * scale, 0.5 * scale],
[-0.23 * scale, 1.56 * scale, -0.15 * scale],
materials.leafA
);
}
[
[-12, -5, 1],
[-7.1, -0.9, 0.95],
[-2.8, -1.0, 1.05],
[1.9, -1.2, 0.9],
[12.0, -4.8, 1],
[-12, 3.4, 0.9],
[-7.0, 8.2, 1],
[-1.0, 8.3, 0.9],
[12.1, 3.5, 0.85]
].forEach(([x, z, s]) => buildTree(x, z, s));
function buildLamp(x, z) {
const group = new THREE.Group();
group.position.set(x, 0.16, z);
addBox(group, [0.11, 1.45, 0.11], [0, 0.72, 0], materials.trim);
addBox(group, [0.4, 0.13, 0.4], [0, 1.48, 0], materials.window, false);
scene.add(group);
}
[
[-9.7, 1.7],
[-9.7, -3.4],
[9.7, 1.7],
[9.7, -3.4],
[0, -3.4],
[0, 5.4]
].forEach(([x, z]) => buildLamp(x, z));
// Start and destination depots.
function buildDepot(x, z, accent) {
const group = new THREE.Group();
group.position.set(x, 0.16, z);
village.add(group);
const accentMaterial = new THREE.MeshStandardMaterial({
color: accent,
emissive: accent,
emissiveIntensity: 0.18,
roughness: 0.8
});
addBox(group, [2.4, 0.18, 1.6], [0, 0.09, 0], materials.trim);
addBox(group, [2.1, 1.65, 1.25], [0, 1.0, 0], materials.trim);
addBox(group, [2.35, 0.2, 1.5], [0, 1.93, 0], accentMaterial);
for (let n = 0; n < 3; n++) {
addBox(
group,
[0.5, 0.5, 0.5],
[-0.55 + n * 0.55, 2.28, 0],
materials.cartCargo
);
}
}
buildDepot(-12, -1.2, 0x4fb9c5);
buildDepot(12, -1.2, 0xffbd59);
// -------------------------------------------------------------------------
// Route rendering.
// -------------------------------------------------------------------------
const routeGroup = new THREE.Group();
scene.add(routeGroup);
let routePoints = [];
let routeLength = 0;
let routeSegments = [];
let cartProgress = 0;
const routeMaterial = new THREE.MeshBasicMaterial({
color: 0x55e6f2,
transparent: true,
opacity: 0.96,
depthTest: false
});
const routeHaloMaterial = new THREE.MeshBasicMaterial({
color: 0x55e6f2,
transparent: true,
opacity: 0.16,
depthTest: false
});
function clearRoute() {
while (routeGroup.children.length) {
const child = routeGroup.children.pop();
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material && object.material !== routeMaterial) {
// Route materials are shared and intentionally retained.
}
});
}
}
function makeRouteSegment(a, b, material, width, height, y) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const midpoint = new THREE.Vector3().addVectors(a, b).multiplyScalar(0.5);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, length),
material
);
mesh.position.set(midpoint.x, y, midpoint.z);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 0, 1),
direction.normalize()
);
mesh.renderOrder = 11;
routeGroup.add(mesh);
}
function renderRoute(path) {
clearRoute();
routePoints = [];
routeSegments = [];
routeLength = 0;
if (!path) return;
for (const cell of path) {
const p = cellCenter(cell.i, cell.j);
routePoints.push(new THREE.Vector3(p.x, 0.39, p.z));
}
for (let index = 0; index < routePoints.length - 1; index++) {
const a = routePoints[index];
const b = routePoints[index + 1];
const length = a.distanceTo(b);
routeSegments.push({ a, b, length, start: routeLength });
routeLength += length;
makeRouteSegment(a, b, routeHaloMaterial, 0.3, 0.04, 0.385);
makeRouteSegment(a, b, routeMaterial, 0.105, 0.065, 0.425);
}
routePoints.forEach((point, index) => {
if (
index === 0 ||
index === routePoints.length - 1 ||
index % 3 !== 0
) {
return;
}
const dot = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.11, 0.18),
routeMaterial
);
dot.position.copy(point);
dot.position.y = 0.45;
dot.renderOrder = 12;
routeGroup.add(dot);
});
}
// Invalid straight-line intent.
const directGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(
cellCenter(startCell.i, startCell.j).x,
0.35,
cellCenter(startCell.i, startCell.j).z
),
new THREE.Vector3(
cellCenter(goalCell.i, goalCell.j).x,
0.35,
cellCenter(goalCell.i, goalCell.j).z
)
]);
const directLine = new THREE.Line(
directGeometry,
new THREE.LineDashedMaterial({
color: 0xff5c62,
dashSize: 0.36,
gapSize: 0.24,
transparent: true,
opacity: 0.88,
depthTest: false
})
);
directLine.computeLineDistances();
directLine.renderOrder = 10;
scene.add(directLine);
// Red X above the sinkhole.
const sinkX = new THREE.Group();
sinkX.position.set(4, 0.52, 1);
const xBar1 = addBox(sinkX, [1.55, 0.08, 0.14], [0, 0, 0], materials.red, false);
const xBar2 = addBox(sinkX, [1.55, 0.08, 0.14], [0, 0, 0], materials.red, false);
xBar1.rotation.y = Math.PI / 4;
xBar2.rotation.y = -Math.PI / 4;
scene.add(sinkX);
// -------------------------------------------------------------------------
// Voxel delivery cart.
// -------------------------------------------------------------------------
const cart = new THREE.Group();
scene.add(cart);
addBox(cart, [0.78, 0.2, 1.18], [0, 0.31, 0], materials.cartBody);
addBox(cart, [0.66, 0.1, 0.76], [0, 0.45, -0.15], materials.trim);
addBox(cart, [0.54, 0.5, 0.54], [0, 0.72, -0.18], materials.cartCargo);
addBox(cart, [0.4, 0.26, 0.4], [0, 1.08, -0.18], materials.cream);
addBox(cart, [0.62, 0.42, 0.16], [0, 0.66, 0.46], materials.cartBody);
const wheels = [];
for (const x of [-0.48, 0.48]) {
for (const z of [-0.38, 0.38]) {
const wheel = addBox(
cart,
[0.24, 0.24, 0.24],
[x, 0.08, z],
materials.wheel
);
addBox(
wheel,
[0.26, 0.08, 0.08],
[0, 0, 0],
materials.wheelHub,
false
);
wheels.push(wheel);
}
}
let cartPlaying = true;
document.querySelector("#playToggle").addEventListener("click", () => {
cartPlaying = !cartPlaying;
document.querySelector("#playToggle").textContent =
cartPlaying ? "Pause cart" : "Play cart";
});
function sampleRoute(distance) {
if (!routeSegments.length) return null;
const d = THREE.MathUtils.clamp(distance, 0, routeLength);
for (const segment of routeSegments) {
const end = segment.start + segment.length;
if (d <= end) {
const local = (d - segment.start) / segment.length;
const position = new THREE.Vector3().lerpVectors(
segment.a,
segment.b,
local
);
const direction = new THREE.Vector3().subVectors(
segment.b,
segment.a
);
return { position, direction };
}
}
const last = routeSegments[routeSegments.length - 1];
return {
position: last.b.clone(),
direction: last.b.clone().sub(last.a).normalize()
};
}
function updateCart() {
if (!routeSegments.length) {
cart.visible = false;
return;
}
cart.visible = true;
const sample = sampleRoute(cartProgress);
if (!sample) return;
cart.position.set(sample.position.x, 0.17, sample.position.z);
const yaw = Math.atan2(sample.direction.x, sample.direction.z);
cart.rotation.y = yaw;
wheels.forEach((wheel) => {
wheel.rotation.x = -cartProgress * 4.2;
});
}
// -------------------------------------------------------------------------
// World labels projected directly from Three.js coordinates.
// -------------------------------------------------------------------------
const worldLabels = [];
function addWorldLabel(text, className, position) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
document.querySelector("#overlay").appendChild(element);
worldLabels.push({
element,
position: new THREE.Vector3(...position)
});
}
addWorldLabel("Sinkhole", "danger", [4, 1.15, 1]);
addWorldLabel("Cave void / section", "cave", [6, -0.3, 6.2]);
addWorldLabel("Depot A", "route", [-12, 2.8, -1.2]);
addWorldLabel("Depot B", "route", [12, 2.8, -1.2]);
addWorldLabel("Rerouted path", "route", [0, 0.9, -4]);
function updateLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const label of worldLabels) {
const projected = label.position.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.15 &&
projected.x < 1.15 &&
projected.y > -1.15 &&
projected.y < 1.15;
label.element.style.display = visible ? "block" : "none";
label.element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
label.element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
}
}
// -------------------------------------------------------------------------
// Route evaluation and UI updates.
// -------------------------------------------------------------------------
const routeBadge = document.querySelector("#routeBadge");
const routeLengthEl = document.querySelector("#routeLength");
const routeCellsEl = document.querySelector("#routeCells");
const routeDecisionEl = document.querySelector("#routeDecision");
const routeConflictsEl = document.querySelector("#routeConflicts");
const clearanceInput = document.querySelector("#clearance");
const clearanceValue = document.querySelector("#clearanceValue");
const totalEnvelope = document.querySelector("#totalEnvelope");
const formulaText = document.querySelector("#formulaText");
function updateRoute() {
safetyBuffer = Number(clearanceInput.value);
const envelope = CART_HALF_WIDTH + safetyBuffer;
clearanceValue.textContent = `${safetyBuffer.toFixed(2)} m`;
totalEnvelope.textContent = `${envelope.toFixed(2)} m`;
formulaText.innerHTML =
`blocked ⇔ center ∈ rect ⊕ [−r−b, r+b]²<br>` +
`r = 0.55 m b = ${safetyBuffer.toFixed(2)} m`;
const sliderPercent =
((safetyBuffer - Number(clearanceInput.min)) /
(Number(clearanceInput.max) -
Number(clearanceInput.min))) *
100;
clearanceInput.style.background = `linear-gradient(
90deg,
var(--cyan) 0%,
var(--cyan) ${sliderPercent}%,
rgba(255,255,255,.12) ${sliderPercent}%,
rgba(255,255,255,.12) 100%
)`;
updateRectLine(
sinkClearanceLine,
expandedRect(hazards.sinkhole, envelope),
0.31
);
updateRectLine(
caveClearanceLine,
expandedRect(hazards.cave, envelope),
0.32
);
const result = findRoute();
if (!result) {
renderRoute(null);
routeBadge.textContent = "Blocked";
routeBadge.classList.add("invalid");
routeLengthEl.textContent = "—";
routeCellsEl.textContent = "—";
routeDecisionEl.textContent = "No path";
routeConflictsEl.textContent = "—";
return;
}
renderRoute(result.path);
cartProgress = 0;
routeBadge.textContent = "Valid";
routeBadge.classList.remove("invalid");
routeLengthEl.textContent = `${routeLength.toFixed(1)} m`;
routeCellsEl.textContent = result.path.length;
const usesNorth = result.path.some((cell) => cell.j < 7);
routeDecisionEl.textContent = usesNorth ? "North loop" : "South loop";
let conflicts = 0;
for (let i = startCell.i; i <= goalCell.i; i++) {
if (cellBlocked(i, startCell.j)) conflicts++;
}
routeConflictsEl.textContent = `${conflicts} cells`;
}
clearanceInput.addEventListener("input", updateRoute);
updateRoute();
// -------------------------------------------------------------------------
// Animation loop.
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (cartPlaying && routeLength > 0) {
cartProgress = (cartProgress + delta * 1.65) % routeLength;
}
updateCart();
updateLabels();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```