Prompt specification
Build or customize the Three.js 3D scene "Ice and Carpet Warehouse Route" 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: Ice and Carpet Warehouse Route
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/ice-and-carpet-warehouse-route-x3511
Scene Description Prompt:
I'd like to see this as a voxel Three.js scene: ice and carpet warehouse route. Build an original room combining low-friction and high-friction zones with barriers. Make tile boundaries legible and require planning a route that respects the declared motion model. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (ice-and-carpet-warehouse-route-x3511):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ice & Carpet — Voxel Warehouse Route</title>
<style>
:root {
--bg: #07131d;
--panel: rgba(9, 23, 34, 0.86);
--panel-border: rgba(173, 229, 239, 0.2);
--text: #eaf8fa;
--muted: #91aeb9;
--cyan: #79e7ef;
--ice: #91dfe8;
--carpet: #a84d62;
--amber: #ffd166;
--green: #65e6a5;
--red: #ff7c79;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: crosshair;
}
.glass {
background: var(--panel);
border: 1px solid var(--panel-border);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.brand {
position: fixed;
z-index: 5;
top: 18px;
left: 18px;
width: min(350px, calc(100vw - 36px));
padding: 18px 20px 17px;
border-radius: 16px;
pointer-events: none;
}
.eyebrow,
.panel-title,
.micro {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
text-transform: uppercase;
letter-spacing: 0.13em;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
}
h1 {
margin: 7px 0 5px;
font-size: clamp(26px, 3vw, 40px);
line-height: 0.98;
letter-spacing: -0.055em;
}
h1 span {
color: var(--carpet);
}
.brand p {
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.mission {
position: fixed;
z-index: 5;
top: 18px;
right: 18px;
width: 315px;
padding: 16px 17px;
border-radius: 14px;
pointer-events: none;
}
.mission-row {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.dot {
width: 10px;
height: 10px;
display: inline-block;
border-radius: 2px;
box-shadow: 0 0 14px currentColor;
}
.dot.start {
color: var(--green);
background: var(--green);
}
.dot.goal {
color: var(--amber);
background: var(--amber);
}
.mission strong {
display: block;
margin: 10px 0 6px;
font-size: 14px;
}
#readout {
color: var(--muted);
font: 11px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.model {
position: fixed;
z-index: 5;
top: 139px;
right: 18px;
width: 315px;
padding: 15px 17px 16px;
border-radius: 14px;
pointer-events: none;
}
.panel-title {
color: var(--cyan);
font-size: 10px;
font-weight: 900;
}
.model ol {
margin: 11px 0 13px;
padding-left: 19px;
color: #c4d8de;
font-size: 12px;
line-height: 1.48;
}
.model li {
margin: 6px 0;
padding-left: 2px;
}
.model b {
color: var(--text);
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 12px;
padding-top: 11px;
border-top: 1px solid rgba(255, 255, 255, 0.09);
color: var(--muted);
font: 10px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 14px;
height: 14px;
border: 1px solid rgba(255, 255, 255, 0.32);
border-radius: 2px;
}
.swatch.ice {
background: var(--ice);
}
.swatch.carpet {
background: var(--carpet);
}
.swatch.block {
background:
repeating-linear-gradient(
45deg,
#303b43 0 4px,
#ffd166 4px 7px
);
}
.controls {
position: fixed;
z-index: 6;
left: 18px;
bottom: 18px;
width: min(410px, calc(100vw - 36px));
padding: 14px;
border-radius: 15px;
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
button {
min-height: 36px;
padding: 8px 11px;
color: var(--text);
background: rgba(255, 255, 255, 0.065);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 8px;
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: background 120ms ease, border-color 120ms ease, transform 120ms ease;
}
button:hover {
background: rgba(121, 231, 239, 0.13);
border-color: rgba(121, 231, 239, 0.55);
}
button:active {
transform: translateY(1px);
}
button.primary {
color: #092128;
background: var(--cyan);
border-color: var(--cyan);
}
button.primary:hover {
background: #a0f4f7;
}
.speed-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 12px;
color: var(--muted);
font: 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
letter-spacing: 0.08em;
}
input[type="range"] {
flex: 1;
accent-color: var(--cyan);
}
.control-note {
margin-top: 10px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.control-note strong {
color: var(--text);
}
.toast {
position: fixed;
z-index: 8;
top: 18px;
left: 50%;
max-width: min(480px, calc(100vw - 40px));
padding: 10px 15px;
color: var(--text);
background: rgba(8, 20, 29, 0.94);
border: 1px solid rgba(121, 231, 239, 0.45);
border-radius: 999px;
box-shadow: 0 10px 35px rgba(0, 0, 0, 0.35);
font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
pointer-events: none;
opacity: 0;
transform: translate(-50%, -10px);
transition: opacity 160ms ease, transform 160ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.warn {
border-color: rgba(255, 124, 121, 0.75);
}
.toast.good {
border-color: rgba(101, 230, 165, 0.75);
}
.camera-hint {
position: fixed;
z-index: 5;
right: 18px;
bottom: 18px;
display: flex;
align-items: center;
gap: 10px;
padding: 8px 10px;
color: var(--muted);
background: rgba(7, 19, 29, 0.76);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 10px;
font: 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: auto;
}
.camera-hint button {
min-height: 28px;
padding: 5px 8px;
font-size: 10px;
}
.world-label {
position: fixed;
z-index: 3;
left: 0;
top: 0;
padding: 5px 8px;
color: #ecfaff;
background: rgba(7, 18, 27, 0.78);
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 5px;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.28);
font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
white-space: nowrap;
pointer-events: none;
transform: translate(-50%, -100%);
}
.world-label.start {
color: var(--green);
border-color: rgba(101, 230, 165, 0.45);
}
.world-label.goal {
color: var(--amber);
border-color: rgba(255, 209, 102, 0.5);
}
.world-label.ice {
color: var(--ice);
border-color: rgba(145, 223, 232, 0.38);
}
.world-label.carpet {
color: #ef9aab;
border-color: rgba(239, 154, 171, 0.38);
}
@media (max-width: 900px) {
.brand {
width: 280px;
}
.brand p {
display: none;
}
.mission {
top: 18px;
right: 18px;
width: 260px;
}
.model {
top: 135px;
right: 18px;
width: 260px;
}
.model ol {
font-size: 11px;
}
.legend {
display: none;
}
}
@media (max-width: 650px) {
.brand {
width: calc(100vw - 36px);
padding: 13px 15px;
}
.brand h1 {
font-size: 28px;
}
.mission,
.model {
display: none;
}
.controls {
bottom: 12px;
left: 12px;
width: calc(100vw - 24px);
}
.camera-hint {
display: none;
}
.toast {
top: 108px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel warehouse route planner"></canvas>
<header class="brand glass">
<div class="eyebrow">Warehouse Routing Lab / Bay 07</div>
<h1>ICE <span>& CARPET</span></h1>
<p>Plan a safe grid route across mixed-friction flooring and cargo barriers.</p>
</header>
<section class="mission glass">
<div class="mission-row">
<span class="dot start"></span>
Dispatch
<span style="flex:1"></span>
<span class="dot goal"></span>
Receiving
</div>
<strong>Route the carrier from green START to amber GOAL.</strong>
<div id="readout">0 steps · 0 turns · 0.0 s model time</div>
</section>
<section class="model glass">
<div class="panel-title">Declared motion model</div>
<ol>
<li><b>Four-way grid:</b> every move enters one adjacent tile.</li>
<li><b>Carpet, high friction:</b> the carrier can stop and turn.</li>
<li><b>Ice, low friction:</b> heading is locked until the carrier reaches carpet.</li>
<li><b>Cargo racks:</b> hard barriers. A slide can never cross one.</li>
<li><b>Completion:</b> arrive at GOAL and stop on its carpet tile.</li>
</ol>
<div class="legend">
<div class="legend-item"><span class="swatch ice"></span>ICE / LOW GRIP</div>
<div class="legend-item"><span class="swatch carpet"></span>CARPET / HIGH GRIP</div>
<div class="legend-item"><span class="swatch block"></span>HARD BARRIER</div>
<div class="legend-item"><span class="micro">μ illustrative</span></div>
</div>
</section>
<section class="controls glass">
<div class="button-row">
<button id="play" class="primary">▶ Test route</button>
<button id="undo">↶ Undo</button>
<button id="reset">Reset</button>
<button id="hint">Hint next</button>
<button id="autoPlan">Auto-plan</button>
</div>
<div class="speed-row">
<span>Playback</span>
<input id="speed" type="range" min="0.5" max="2" step="0.1" value="1" />
<span id="speedValue">1.0×</span>
</div>
<div class="control-note">
<strong>Click a floor tile</strong> to extend the route. Green outlines are legal next moves.
On ice, continue straight until carpet. Drag to orbit and use the wheel to zoom.
</div>
</section>
<div class="camera-hint">
<span>DRAG orbit · WHEEL zoom · SHIFT-drag pan</span>
<button id="isoView">ISO</button>
<button id="topView">TOP</button>
</div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const toastEl = document.querySelector("#toast");
const readoutEl = document.querySelector("#readout");
const playButton = document.querySelector("#play");
const speedInput = document.querySelector("#speed");
const speedValue = document.querySelector("#speedValue");
// -----------------------------------------------------------------------
// Grid and room definition
// -----------------------------------------------------------------------
const W = 28;
const H = 20;
const HALF_X = (W - 1) / 2;
const HALF_Z = (H - 1) / 2;
const START = { x: 2, z: 16 };
const GOAL = { x: 24, z: 2 };
const DIRS = [
{ x: 1, z: 0, name: "east" },
{ x: -1, z: 0, name: "west" },
{ x: 0, z: 1, name: "south" },
{ x: 0, z: -1, name: "north" }
];
const obstacleRects = [
{ x1: 5, x2: 9, z1: 7, z2: 7 },
{ x1: 5, x2: 8, z1: 12, z2: 12 },
{ x1: 10, x2: 10, z1: 14, z2: 17 },
{ x1: 17, x2: 21, z1: 10, z2: 10 },
{ x1: 21, x2: 25, z1: 6, z2: 6 },
{ x1: 18, x2: 18, z1: 2, z2: 4 }
];
const blocked = new Set();
for (const r of obstacleRects) {
for (let x = r.x1; x <= r.x2; x++) {
for (let z = r.z1; z <= r.z2; z++) {
blocked.add(`${x},${z}`);
}
}
}
function isBlocked(x, z) {
return blocked.has(`${x},${z}`);
}
function isCarpet(x, z) {
// Main carpet docks on both sides of the ice channel.
if (x <= 3 || x >= 14) return true;
// Small high-friction braking islands inside the ice field.
if (x >= 7 && x <= 8 && z >= 9 && z <= 10) return true;
if (x >= 11 && x <= 12 && z >= 5 && z <= 6) return true;
return false;
}
function surfaceAt(x, z) {
return isCarpet(x, z) ? "carpet" : "ice";
}
function worldX(x) {
return x - HALF_X;
}
function worldZ(z) {
return z - HALF_Z;
}
function directionBetween(a, b) {
const dx = b.x - a.x;
const dz = b.z - a.z;
if (Math.abs(dx) + Math.abs(dz) !== 1) return -1;
if (dx === 1) return 0;
if (dx === -1) return 1;
if (dz === 1) return 2;
if (dz === -1) return 3;
return -1;
}
function sameTile(a, b) {
return a.x === b.x && a.z === b.z;
}
// -----------------------------------------------------------------------
// Renderer, camera, lighting
// -----------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131d);
scene.fog = new THREE.Fog(0x07131d, 36, 74);
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
160
);
const cameraState = {
yaw: 0.63,
pitch: 0.77,
distance: 35,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const { yaw, pitch, distance, target } = cameraState;
const horizontal = Math.cos(pitch) * distance;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * distance,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xd6f7ff, 0x17202c, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff3dc, 2.25);
keyLight.position.set(-9, 19, 12);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -21;
keyLight.shadow.camera.right = 21;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 55;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x55dce8, 1.0);
rimLight.position.set(14, 8, -13);
scene.add(rimLight);
// -----------------------------------------------------------------------
// Materials and deterministic visual helpers
// -----------------------------------------------------------------------
let randomSeed = 73421;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
const materials = {
ice: new THREE.MeshStandardMaterial({
color: 0x8ddce6,
roughness: 0.22,
metalness: 0.05,
emissive: 0x102f38,
emissiveIntensity: 0.18
}),
carpet: new THREE.MeshStandardMaterial({
color: 0x793247,
roughness: 0.98,
metalness: 0
}),
underfloor: new THREE.MeshStandardMaterial({
color: 0x18252e,
roughness: 0.85
}),
outside: new THREE.MeshStandardMaterial({
color: 0x081119,
roughness: 1
}),
wall: new THREE.MeshStandardMaterial({
color: 0x263844,
roughness: 0.62,
metalness: 0.32
}),
wallTrim: new THREE.MeshStandardMaterial({
color: 0x6dd7df,
roughness: 0.4,
metalness: 0.2,
emissive: 0x1e5d64,
emissiveIntensity: 0.35
}),
rackBase: new THREE.MeshStandardMaterial({
color: 0x202a31,
roughness: 0.75,
metalness: 0.38
}),
crateA: new THREE.MeshStandardMaterial({
color: 0xb98b47,
roughness: 0.9
}),
crateB: new THREE.MeshStandardMaterial({
color: 0x3b7180,
roughness: 0.88
}),
crateC: new THREE.MeshStandardMaterial({
color: 0x96544c,
roughness: 0.92
}),
strap: new THREE.MeshStandardMaterial({
color: 0xe0bd73,
roughness: 0.75
}),
boundary: new THREE.MeshStandardMaterial({
color: 0xf4d37a,
roughness: 0.5,
emissive: 0x5a4315,
emissiveIntensity: 0.25
}),
route: new THREE.MeshBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.94
}),
routeDot: new THREE.MeshBasicMaterial({
color: 0xffe5a1
}),
legal: new THREE.MeshBasicMaterial({
color: 0x65e6a5,
transparent: true,
opacity: 0.26,
depthWrite: false
}),
hint: new THREE.MeshBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.34,
depthWrite: false
}),
hover: new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.2,
depthWrite: false
})
};
function box(parent, width, height, depth, material, x, y, z, cast = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -----------------------------------------------------------------------
// Floor: instanced voxel tiles, carpet flecks, ice glints, legible grid
// -----------------------------------------------------------------------
const outsideFloor = box(
scene,
80,
0.2,
80,
materials.outside,
0,
-0.25,
0,
false
);
outsideFloor.receiveShadow = true;
box(
scene,
W + 0.45,
0.22,
H + 0.45,
materials.underfloor,
0,
-0.12,
0,
false
);
const iceCells = [];
const carpetCells = [];
for (let x = 0; x < W; x++) {
for (let z = 0; z < H; z++) {
(surfaceAt(x, z) === "ice" ? iceCells : carpetCells).push({ x, z });
}
}
const tileGeometry = new THREE.BoxGeometry(0.94, 0.12, 0.94);
const iceTiles = new THREE.InstancedMesh(
tileGeometry,
materials.ice,
iceCells.length
);
const carpetTiles = new THREE.InstancedMesh(
tileGeometry,
materials.carpet,
carpetCells.length
);
iceTiles.receiveShadow = true;
carpetTiles.receiveShadow = true;
const dummy = new THREE.Object3D();
iceCells.forEach((cell, index) => {
dummy.position.set(worldX(cell.x), 0, worldZ(cell.z));
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
iceTiles.setMatrixAt(index, dummy.matrix);
});
carpetCells.forEach((cell, index) => {
dummy.position.set(worldX(cell.x), 0, worldZ(cell.z));
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
carpetTiles.setMatrixAt(index, dummy.matrix);
});
scene.add(iceTiles, carpetTiles);
// Carpet is represented by many tiny square fibers.
const fiberGeometry = new THREE.BoxGeometry(0.055, 0.016, 0.105);
const fibers = new THREE.InstancedMesh(
fiberGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
}),
carpetCells.length * 6
);
const fiberColorA = new THREE.Color(0xb76276);
const fiberColorB = new THREE.Color(0x5e2539);
let fiberIndex = 0;
for (const cell of carpetCells) {
for (let i = 0; i < 6; i++) {
dummy.position.set(
worldX(cell.x) + (random() - 0.5) * 0.78,
0.072,
worldZ(cell.z) + (random() - 0.5) * 0.78
);
dummy.rotation.set(0, random() > 0.5 ? Math.PI / 2 : 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
fibers.setMatrixAt(fiberIndex, dummy.matrix);
fibers.setColorAt(
fiberIndex,
random() > 0.45 ? fiberColorA : fiberColorB
);
fiberIndex++;
}
}
scene.add(fibers);
// Thin glints make the ice read as low-friction.
const glintGeometry = new THREE.BoxGeometry(0.54, 0.012, 0.025);
const glints = new THREE.InstancedMesh(
glintGeometry,
new THREE.MeshBasicMaterial({
color: 0xeaffff,
transparent: true,
opacity: 0.36,
depthWrite: false
}),
iceCells.length
);
iceCells.forEach((cell, index) => {
dummy.position.set(
worldX(cell.x) + (random() - 0.5) * 0.25,
0.069,
worldZ(cell.z) + (random() - 0.5) * 0.25
);
dummy.rotation.set(0, random() > 0.5 ? 0.85 : -0.55, 0);
dummy.scale.set(0.6 + random() * 0.8, 1, 1);
dummy.updateMatrix();
glints.setMatrixAt(index, dummy.matrix);
});
scene.add(glints);
// Individual tile outlines keep the planning grid unmistakable.
const linePositions = [];
const lineColors = [];
const iceLineColor = new THREE.Color(0xd9fbff);
const carpetLineColor = new THREE.Color(0xc87b8b);
for (const cell of [...iceCells, ...carpetCells]) {
const x = worldX(cell.x);
const z = worldZ(cell.z);
const half = 0.47;
const y = 0.073;
const color = surfaceAt(cell.x, cell.z) === "ice"
? iceLineColor
: carpetLineColor;
const corners = [
[x - half, z - half],
[x + half, z - half],
[x + half, z + half],
[x - half, z + half]
];
for (let i = 0; i < 4; i++) {
const a = corners[i];
const b = corners[(i + 1) % 4];
linePositions.push(a[0], y, a[1], b[0], y, b[1]);
lineColors.push(color.r, color.g, color.b, color.r, color.g, color.b);
}
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(linePositions, 3)
);
gridGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(lineColors, 3)
);
const gridLines = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.46,
depthWrite: false
})
);
scene.add(gridLines);
// Bright seams make every friction transition obvious.
const seamGeometryX = new THREE.BoxGeometry(0.065, 0.025, 0.96);
const seamGeometryZ = new THREE.BoxGeometry(0.96, 0.025, 0.065);
for (let x = 0; x < W; x++) {
for (let z = 0; z < H; z++) {
const current = surfaceAt(x, z);
if (x + 1 < W && surfaceAt(x + 1, z) !== current) {
box(
scene,
0.065,
0.025,
0.96,
materials.boundary,
worldX(x) + 0.49,
0.086,
worldZ(z),
false
);
}
if (z + 1 < H && surfaceAt(x, z + 1) !== current) {
box(
scene,
0.96,
0.025,
0.065,
materials.boundary,
worldX(x),
0.086,
worldZ(z) + 0.49,
false
);
}
}
}
// -----------------------------------------------------------------------
// Cargo barriers
// -----------------------------------------------------------------------
for (const [x, z] of blocked) {
const cellX = Number(x);
const cellZ = Number(z);
const wx = worldX(cellX);
const wz = worldZ(cellZ);
box(
scene,
0.92,
0.16,
0.92,
materials.rackBase,
wx,
0.14,
wz
);
const crateHeight = 0.48 + random() * 0.15;
const crateMaterial = random() > 0.66
? materials.crateB
: random() > 0.5
? materials.crateC
: materials.crateA;
box(
scene,
0.75,
crateHeight,
0.75,
crateMaterial,
wx,
0.22 + crateHeight / 2,
wz
);
box(
scene,
0.77,
0.055,
0.09,
materials.strap,
wx,
0.22 + crateHeight / 2,
wz + 0.382
);
if (random() > 0.42) {
const upperHeight = 0.34 + random() * 0.13;
box(
scene,
0.67,
upperHeight,
0.67,
random() > 0.5 ? materials.crateA : materials.crateB,
wx + (random() - 0.5) * 0.08,
0.22 + crateHeight + upperHeight / 2,
wz + (random() - 0.5) * 0.08
);
}
}
// -----------------------------------------------------------------------
// Low room walls and corner posts
// -----------------------------------------------------------------------
const wallHeight = 0.62;
box(
scene,
0.28,
wallHeight,
H + 0.55,
materials.wall,
-W / 2 - 0.14,
wallHeight / 2,
0
);
box(
scene,
0.28,
wallHeight,
H + 0.55,
materials.wall,
W / 2 + 0.14,
wallHeight / 2,
0
);
box(
scene,
W + 0.55,
wallHeight,
0.28,
materials.wall,
0,
wallHeight / 2,
-H / 2 - 0.14
);
box(
scene,
W + 0.55,
wallHeight,
0.28,
materials.wall,
0,
wallHeight / 2,
H / 2 + 0.14
);
box(
scene,
W + 0.58,
0.055,
0.07,
materials.wallTrim,
0,
wallHeight + 0.02,
-H / 2 - 0.14,
false
);
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
box(
scene,
0.42,
1.48,
0.42,
materials.wall,
sx * (W / 2 + 0.14),
0.74,
sz * (H / 2 + 0.14)
);
box(
scene,
0.48,
0.1,
0.48,
materials.wallTrim,
sx * (W / 2 + 0.14),
1.48,
sz * (H / 2 + 0.14)
);
}
}
// -----------------------------------------------------------------------
// Start and goal markers
// -----------------------------------------------------------------------
const startMaterial = new THREE.MeshStandardMaterial({
color: 0x45d990,
emissive: 0x1a8050,
emissiveIntensity: 0.75,
roughness: 0.42
});
const goalMaterial = new THREE.MeshStandardMaterial({
color: 0xffc857,
emissive: 0x9a5a0d,
emissiveIntensity: 0.75,
roughness: 0.38
});
function makeDockMarker(tile, material) {
const group = new THREE.Group();
group.position.set(worldX(tile.x), 0, worldZ(tile.z));
box(group, 0.86, 0.055, 0.86, material, 0, 0.105, 0, false);
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
box(
group,
0.12,
0.17,
0.12,
material,
sx * 0.36,
0.19,
sz * 0.36
);
}
}
scene.add(group);
return group;
}
const startMarker = makeDockMarker(START, startMaterial);
const goalMarker = makeDockMarker(GOAL, goalMaterial);
const goalBeacon = box(
scene,
0.34,
0.34,
0.34,
goalMaterial,
worldX(GOAL.x),
1.16,
worldZ(GOAL.z)
);
box(
scene,
0.045,
0.85,
0.045,
goalMaterial,
worldX(GOAL.x),
0.56,
worldZ(GOAL.z),
false
);
// -----------------------------------------------------------------------
// Route, carrier, legal-move overlays
// -----------------------------------------------------------------------
const routeGroup = new THREE.Group();
const legalGroup = new THREE.Group();
const hintGroup = new THREE.Group();
scene.add(routeGroup, legalGroup, hintGroup);
const routeSegmentGeometry = new THREE.BoxGeometry(1, 0.035, 0.14);
const routeDotGeometry = new THREE.BoxGeometry(0.17, 0.04, 0.17);
const legalGeometry = new THREE.BoxGeometry(0.86, 0.026, 0.86);
const hintGeometry = new THREE.BoxGeometry(0.88, 0.03, 0.88);
const endpointMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.35, 0.07, 0.35),
new THREE.MeshBasicMaterial({
color: 0x65e6a5,
transparent: true,
opacity: 0.72
})
);
scene.add(endpointMarker);
const hoverMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.91, 0.022, 0.91),
materials.hover
);
hoverMarker.visible = false;
scene.add(hoverMarker);
const agent = new THREE.Group();
const agentBodyMaterial = new THREE.MeshStandardMaterial({
color: 0xf47f45,
roughness: 0.5,
metalness: 0.18
});
const agentDarkMaterial = new THREE.MeshStandardMaterial({
color: 0x17222b,
roughness: 0.8
});
const agentWhiteMaterial = new THREE.MeshStandardMaterial({
color: 0xdce9e9,
roughness: 0.6
});
const agentBeaconMaterial = new THREE.MeshStandardMaterial({
color: 0x67edf2,
emissive: 0x1fabb6,
emissiveIntensity: 1.1,
roughness: 0.35
});
box(agent, 0.64, 0.48, 0.76, agentBodyMaterial, 0, 0.45, 0);
box(agent, 0.54, 0.22, 0.5, agentWhiteMaterial, 0, 0.79, -0.03);
box(agent, 0.67, 0.13, 0.16, agentWhiteMaterial, 0, 0.34, 0.43);
box(agent, 0.24, 0.18, 0.24, agentBeaconMaterial, 0, 1.0, -0.03);
const wheelMeshes = [];
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const wheel = box(
agent,
0.18,
0.2,
0.24,
agentDarkMaterial,
sx * 0.37,
0.2,
sz * 0.25
);
wheelMeshes.push(wheel);
}
}
scene.add(agent);
let route = [{ ...START }];
let routeTimes = [0];
let routeTotal = 0;
let hintTiles = [];
const playback = {
playing: false,
elapsed: 0,
speed: 1
};
function clearGroup(group) {
while (group.children.length) {
group.remove(group.children[group.children.length - 1]);
}
}
function estimateRouteTime() {
let total = 0;
const times = [0];
for (let i = 1; i < route.length; i++) {
const tile = route[i];
total += surfaceAt(tile.x, tile.z) === "ice" ? 0.34 : 0.52;
times.push(total);
}
return { total, times };
}
function countTurns() {
let turns = 0;
for (let i = 2; i < route.length; i++) {
const previous = directionBetween(route[i - 2], route[i - 1]);
const next = directionBetween(route[i - 1], route[i]);
if (previous !== next) turns++;
}
return turns;
}
function updateRouteVisuals() {
clearGroup(routeGroup);
for (let i = 1; i < route.length; i++) {
const a = route[i - 1];
const b = route[i];
const segment = new THREE.Mesh(routeSegmentGeometry, materials.route);
segment.position.set(
(worldX(a.x) + worldX(b.x)) / 2,
0.116,
(worldZ(a.z) + worldZ(b.z)) / 2
);
if (a.x !== b.x) {
segment.rotation.y = Math.PI / 2;
}
routeGroup.add(segment);
}
for (const tile of route) {
const dot = new THREE.Mesh(routeDotGeometry, materials.routeDot);
dot.position.set(worldX(tile.x), 0.14, worldZ(tile.z));
routeGroup.add(dot);
}
const end = route[route.length - 1];
endpointMarker.position.set(worldX(end.x), 0.17, worldZ(end.z));
const timing = estimateRouteTime();
routeTimes = timing.times;
routeTotal = timing.total;
playback.elapsed = 0;
playback.playing = false;
agent.position.set(worldX(START.x), 0.065, worldZ(START.z));
agent.rotation.y = 0;
if (route.length > 1) {
const a = route[route.length - 2];
const b = route[route.length - 1];
const dir = DIRS[directionBetween(a, b)];
agent.rotation.y = Math.atan2(dir.x, dir.z);
agent.position.set(worldX(end.x), 0.065, worldZ(end.z));
}
updateReadout();
updateLegalMoves();
updatePlayButton();
}
function updateReadout() {
readoutEl.textContent =
`${route.length - 1} steps · ` +
`${countTurns()} turns · ` +
`${routeTotal.toFixed(1)} s model time`;
}
function legalMovesFrom(tile) {
const result = [];
let allowed = DIRS;
if (surfaceAt(tile.x, tile.z) === "ice") {
const incoming =
route.length >= 2
? directionBetween(route[route.length - 2], tile)
: -1;
if (incoming >= 0) {
allowed = [DIRS[incoming]];
}
}
for (const dir of allowed) {
const next = { x: tile.x + dir.x, z: tile.z + dir.z };
if (
next.x >= 0 && next.x < W &&
next.z >= 0 && next.z < H &&
!isBlocked(next.x, next.z)
) {
result.push(next);
}
}
return result;
}
function updateLegalMoves() {
clearGroup(legalGroup);
clearGroup(hintGroup);
const end = route[route.length - 1];
if (!sameTile(end, GOAL)) {
for (const tile of legalMovesFrom(end)) {
const marker = new THREE.Mesh(legalGeometry, materials.legal);
marker.position.set(worldX(tile.x), 0.095, worldZ(tile.z));
legalGroup.add(marker);
}
}
for (const tile of hintTiles) {
const marker = new THREE.Mesh(hintGeometry, materials.hint);
marker.position.set(worldX(tile.x), 0.106, worldZ(tile.z));
hintGroup.add(marker);
}
}
function inspectRoute() {
for (let i = 1; i < route.length; i++) {
const previous = route[i - 1];
const current = route[i];
if (isBlocked(current.x, current.z)) {
return { valid: false, reason: "The route crosses a cargo barrier." };
}
const direction = directionBetween(previous, current);
if (direction < 0) {
return { valid: false, reason: "The route contains a non-cardinal move." };
}
if (surfaceAt(previous.x, previous.z) === "ice") {
const incoming =
i >= 2 ? directionBetween(route[i - 2], previous) : -1;
if (incoming !== direction) {
return {
valid: false,
reason: "The carrier turns or stops on a low-friction ice tile."
};
}
}
}
const end = route[route.length - 1];
if (!sameTile(end, GOAL)) {
return { valid: false, reason: "The route does not end at GOAL." };
}
if (surfaceAt(end.x, end.z) !== "carpet") {
return { valid: false, reason: "The carrier must stop on carpet." };
}
return { valid: true, reason: "Route valid." };
}
// -----------------------------------------------------------------------
// A* solver using the exact declared motion model
//
// Carpet states may choose any cardinal heading.
// Ice states may only continue in their incoming heading.
// -----------------------------------------------------------------------
function findSolution(startTile, forcedDirection = -1) {
const startKey = `${startTile.x},${startTile.z},${forcedDirection}`;
const startState = {
x: startTile.x,
z: startTile.z,
dir: forcedDirection
};
const states = new Map([[startKey, startState]]);
const parent = new Map();
const open = [{
key: startKey,
state: startState,
g: 0,
f: (Math.abs(startTile.x - GOAL.x) + Math.abs(startTile.z - GOAL.z)) * 0.34
}];
const closed = new Set();
while (open.length) {
open.sort((a, b) => a.f - b.f);
const current = open.shift();
if (closed.has(current.key)) continue;
closed.add(current.key);
const state = current.state;
if (state.x === GOAL.x && state.z === GOAL.z) {
const path = [];
let key = current.key;
while (key !== undefined) {
const item = states.get(key);
if (!item) break;
path.push({ x: item.x, z: item.z });
if (key === startKey) break;
key = parent.get(key);
}
path.reverse();
return path;
}
const isIce = surfaceAt(state.x, state.z) === "ice";
const allowed = isIce ? [DIRS[state.dir]] : DIRS;
for (const dir of allowed) {
const nextX = state.x + dir.x;
const nextZ = state.z + dir.z;
if (
nextX < 0 || nextX >= W ||
nextZ < 0 || nextZ >= H ||
isBlocked(nextX, nextZ)
) {
continue;
}
const nextDir = DIRS.indexOf(dir);
const nextKey = `${nextX},${nextZ},${nextDir}`;
if (closed.has(nextKey)) continue;
const nextState = {
x: nextX,
z: nextZ,
dir: nextDir
};
const stepCost = surfaceAt(nextX, nextZ) === "ice" ? 0.34 : 0.52;
const g = current.g + stepCost;
const old = states.get(nextKey);
if (!old || g < old.g) {
states.set(nextKey, { ...nextState, g });
parent.set(nextKey, current.key);
const heuristic =
(Math.abs(nextX - GOAL.x) + Math.abs(nextZ - GOAL.z)) * 0.34;
open.push({
key: nextKey,
state: nextState,
g,
f: g + heuristic
});
}
}
}
return null;
}
// -----------------------------------------------------------------------
// User route editing
// -----------------------------------------------------------------------
let toastTimer = null;
function announce(message, tone = "", duration = 3400) {
toastEl.textContent = message;
toastEl.className = `toast show ${tone}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toastEl.className = "toast";
}, duration);
}
function addTile(tile) {
if (sameTile(route[route.length - 1], GOAL)) {
announce("GOAL reached. Undo a step to extend the route further.", "warn");
return;
}
const from = route[route.length - 1];
const direction = directionBetween(from, tile);
if (direction < 0) {
announce("Grid rule: choose one orthogonally adjacent tile.", "warn");
return;
}
if (isBlocked(tile.x, tile.z)) {
announce("Cargo barrier: that tile is physically impassable.", "warn");
return;
}
if (surfaceAt(from.x, from.z) === "ice") {
const incoming =
route.length >= 2 ? directionBetween(route[route.length - 2], from) : -1;
if (incoming !== direction) {
const heading = incoming >= 0 ? DIRS[incoming].name : "current";
announce(
`ICE MOMENTUM: heading ${heading} is locked. Continue straight to a carpet tile.`,
"warn"
);
return;
}
}
const alreadyUsed = route
.slice(0, -1)
.some((entry) => sameTile(entry, tile));
if (alreadyUsed) {
announce("That tile is already in the route. Undo first to revisit it.", "warn");
return;
}
route.push({ x: tile.x, z: tile.z });
hintTiles = [];
updateRouteVisuals();
if (sameTile(tile, GOAL)) {
announce("Route complete. Press TEST ROUTE to validate the motion.", "good");
} else if (surfaceAt(tile.x, tile.z) === "ice") {
announce("Carrier is sliding on ice. The next move must remain straight ahead.", "warn");
} else {
announce("Carpet reached. The carrier may stop or change direction.");
}
}
document.querySelector("#undo").addEventListener("click", () => {
if (route.length <= 1) {
announce("The route is already at START.");
return;
}
route.pop();
hintTiles = [];
updateRouteVisuals();
announce("Last planned tile removed.");
});
document.querySelector("#reset").addEventListener("click", () => {
route = [{ ...START }];
hintTiles = [];
updateRouteVisuals();
announce("Route cleared. Plan again from START.");
});
document.querySelector("#hint").addEventListener("click", () => {
const end = route[route.length - 1];
if (sameTile(end, GOAL)) {
announce("Already at GOAL.");
return;
}
const forced =
surfaceAt(end.x, end.z) === "ice"
? directionBetween(route[route.length - 2], end)
: -1;
const solution = findSolution(end, forced);
if (!solution) {
announce("No valid continuation was found.", "warn");
return;
}
hintTiles = solution.slice(1, 5);
updateLegalMoves();
announce(
`Hint: the next legal sequence is ${hintTiles
.map((tile) => `(${tile.x},${tile.z})`)
.join(" → ")}.`,
"good",
5200
);
});
document.querySelector("#autoPlan").addEventListener("click", () => {
const solution = findSolution(START);
if (!solution) {
announce("No solution found.", "warn");
return;
}
route = solution;
hintTiles = [];
updateRouteVisuals();
announce(
"A valid route was plotted with the declared motion model. Test it or edit it.",
"good",
5000
);
});
// -----------------------------------------------------------------------
// Route playback
// -----------------------------------------------------------------------
function updatePlayButton() {
playButton.textContent = playback.playing ? "Ⅱ Pause" : "▶ Test route";
}
playButton.addEventListener("click", () => {
const result = inspectRoute();
if (!result.valid) {
announce(result.reason, "warn");
return;
}
if (playback.playing) {
playback.playing = false;
updatePlayButton();
announce("Playback paused.");
return;
}
if (playback.elapsed >= routeTotal) {
playback.elapsed = 0;
agent.position.set(worldX(START.x), 0.065, worldZ(START.z));
}
playback.playing = true;
updatePlayButton();
});
speedInput.addEventListener("input", () => {
playback.speed = Number(speedInput.value);
speedValue.textContent = `${playback.speed.toFixed(1)}×`;
});
function smoothStep(t) {
return t * t * (3 - 2 * t);
}
function shortestAngleDifference(a, b) {
let difference = (b - a + Math.PI) % (Math.PI * 2) - Math.PI;
if (difference < -Math.PI) difference += Math.PI * 2;
return difference;
}
function updatePlayback(delta) {
if (!playback.playing) return;
playback.elapsed += delta * playback.speed;
if (playback.elapsed >= routeTotal) {
playback.elapsed = routeTotal;
playback.playing = false;
updatePlayButton();
const end = route[route.length - 1];
agent.position.set(worldX(end.x), 0.065, worldZ(end.z));
announce("Test passed. The carrier stopped safely on carpet at GOAL.", "good");
return;
}
let segmentIndex = 1;
while (
segmentIndex < routeTimes.length &&
playback.elapsed > routeTimes[segmentIndex]
) {
segmentIndex++;
}
segmentIndex = Math.min(segmentIndex, route.length - 1);
const from = route[segmentIndex - 1];
const to = route[segmentIndex];
const startTime = routeTimes[segmentIndex - 1];
const duration = routeTimes[segmentIndex] - startTime;
const rawT = Math.max(0, Math.min(1, (playback.elapsed - startTime) / duration));
// Carpet braking is eased; an ice slide remains linear.
const t = surfaceAt(to.x, to.z) === "carpet" ? smoothStep(rawT) : rawT;
const x = THREE.MathUtils.lerp(worldX(from.x), worldX(to.x), t);
const z = THREE.MathUtils.lerp(worldZ(from.z), worldZ(to.z), t);
agent.position.set(x, 0.065, z);
const direction = DIRS[directionBetween(from, to)];
const targetAngle = Math.atan2(direction.x, direction.z);
agent.rotation.y +=
shortestAngleDifference(agent.rotation.y, targetAngle) * Math.min(1, delta * 12);
for (const wheel of wheelMeshes) {
wheel.rotation.x += delta * 9 * playback.speed;
}
}
// -----------------------------------------------------------------------
// DOM labels projected into the 3D scene
// -----------------------------------------------------------------------
const worldLabels = [];
function addWorldLabel(text, className, x, z, y) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
document.body.appendChild(element);
worldLabels.push({
element,
position: new THREE.Vector3(worldX(x), y, worldZ(z))
});
}
addWorldLabel("START", "start", START.x, START.z, 1.45);
addWorldLabel("GOAL", "goal", GOAL.x, GOAL.z, 1.6);
addWorldLabel("ICE / LOW GRIP", "ice", 7, 16, 0.38);
addWorldLabel("CARPET / HIGH GRIP", "carpet", 21, 16, 0.38);
addWorldLabel("BRAKE PAD A", "carpet", 7.5, 9.5, 0.35);
addWorldLabel("BRAKE PAD B", "carpet", 11.5, 5.5, 0.35);
const projected = new THREE.Vector3();
function updateWorldLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const label of worldLabels) {
projected.copy(label.position).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";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
// -----------------------------------------------------------------------
// Direct camera controls and tile picking
// -----------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
const floorPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.06);
const hitPoint = new THREE.Vector3();
const pointer = {
down: false,
button: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false
};
function pointerToNDC(event) {
const rect = canvas.getBoundingClientRect();
pointerNDC.set(
((event.clientX - rect.left) / rect.width) * 2 - 1,
-((event.clientY - rect.top) / rect.height) * 2 + 1
);
}
function tileUnderPointer(event) {
pointerToNDC(event);
raycaster.setFromCamera(pointerNDC, camera);
if (!raycaster.ray.intersectPlane(floorPlane, hitPoint)) return null;
const x = Math.round(hitPoint.x + HALF_X);
const z = Math.round(hitPoint.z + HALF_Z);
if (x < 0 || x >= W || z < 0 || z >= H) return null;
return { x, z };
}
function panCamera(dx, dy) {
const scale = cameraState.distance * 0.00135;
const yaw = cameraState.yaw;
cameraState.target.x -= dx * scale * Math.cos(yaw);
cameraState.target.z += dx * scale * Math.sin(yaw);
cameraState.target.x += dy * scale * Math.sin(yaw);
cameraState.target.z += dy * scale * Math.cos(yaw);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -9, 9);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -7, 7);
updateCamera();
}
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
pointer.down = true;
pointer.button = event.button;
pointer.startX = event.clientX;
pointer.startY = event.clientY;
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
pointer.moved = false;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (pointer.down) {
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
const totalDistance = Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
);
if (totalDistance > 4) pointer.moved = true;
if (event.shiftKey || pointer.button === 2) {
panCamera(dx, dy);
} else if (pointer.button === 0) {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.36,
1.45
);
updateCamera();
}
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
return;
}
const tile = tileUnderPointer(event);
if (tile) {
hoverMarker.visible = true;
hoverMarker.position.set(worldX(tile.x), 0.094, worldZ(tile.z));
} else {
hoverMarker.visible = false;
}
});
canvas.addEventListener("pointerup", (event) => {
if (pointer.down && !pointer.moved && pointer.button === 0) {
const tile = tileUnderPointer(event);
if (tile) addTile(tile);
}
pointer.down = false;
hoverMarker.visible = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointercancel", () => {
pointer.down = false;
hoverMarker.visible = false;
});
canvas.addEventListener("pointerleave", () => {
if (!pointer.down) hoverMarker.visible = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
18,
58
);
updateCamera();
},
{ passive: false }
);
document.querySelector("#isoView").addEventListener("click", () => {
cameraState.yaw = 0.63;
cameraState.pitch = 0.77;
cameraState.distance = 35;
cameraState.target.set(0, 0, 0);
updateCamera();
});
document.querySelector("#topView").addEventListener("click", () => {
cameraState.yaw = 0;
cameraState.pitch = 1.45;
cameraState.distance = 33;
cameraState.target.set(0, 0, 0);
updateCamera();
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
playButton.click();
} else if (event.key.toLowerCase() === "z") {
document.querySelector("#undo").click();
} else if (event.key.toLowerCase() === "r") {
document.querySelector("#reset").click();
} else if (event.key.toLowerCase() === "h") {
document.querySelector("#hint").click();
}
});
// -----------------------------------------------------------------------
// Resize and render loop
// -----------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updatePlayback(delta);
goalBeacon.position.y = 1.16 + Math.sin(elapsed * 2.2) * 0.08;
goalBeacon.rotation.y = elapsed * 0.8;
goalBeacon.rotation.x = elapsed * 0.35;
endpointMarker.rotation.y = elapsed * 0.9;
endpointMarker.scale.setScalar(1 + Math.sin(elapsed * 3.2) * 0.07);
agentBeaconMaterial.emissiveIntensity =
0.75 + Math.abs(Math.sin(elapsed * 4.2)) * 0.75;
startMarker.children[0].material.emissiveIntensity =
0.55 + Math.abs(Math.sin(elapsed * 2.7)) * 0.35;
updateWorldLabels();
renderer.render(scene, camera);
}
updateRouteVisuals();
animate();
announce(
"Plan from START. Click a neighboring tile; ice locks your heading until carpet.",
"good",
6500
);
</script>
</body>
</html>
```