Prompt specification
Build or customize the Three.js 3D scene "Closed Ford and Narrow Detour Bridge" 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: Closed Ford and Narrow Detour Bridge
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/closed-ford-and-narrow-detour-bridge-x2138
Scene Description Prompt:
A voxel closed-ford puzzle sends differently sized vehicles toward a narrow detour bridge; check real geometric clearance. Three.js from cdnjs, one HTML file.
Working Three.js Starter (closed-ford-and-narrow-detour-bridge-x2138):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Closed Ford — Voxel Detour</title>
<style>
:root {
--ink: #142333;
--muted: #5b6b78;
--paper: rgba(250, 252, 248, 0.94);
--line: rgba(24, 48, 64, 0.14);
--accent: #ef5b45;
--gold: #f3b83f;
--green: #238b66;
--shadow: 0 16px 45px rgba(23, 43, 56, 0.18);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b8dce5;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button { font: inherit; }
#scene {
position: fixed;
inset: 0;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.glass {
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.72);
box-shadow: var(--shadow);
backdrop-filter: blur(16px) saturate(1.15);
-webkit-backdrop-filter: blur(16px) saturate(1.15);
}
#brand {
position: fixed;
top: 20px;
left: 20px;
width: min(340px, calc(100vw - 40px));
padding: 16px 18px;
border-radius: 18px;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 5px;
color: var(--accent);
font-size: 11px;
font-weight: 900;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.cube-logo {
position: relative;
width: 15px;
height: 15px;
background: var(--accent);
border-radius: 3px;
transform: rotate(8deg);
box-shadow: 5px 4px 0 #f5b83d;
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 35px);
line-height: 0.95;
letter-spacing: -0.055em;
text-transform: uppercase;
}
#levelName {
margin-top: 8px;
color: var(--muted);
font-size: 13px;
font-weight: 650;
}
#statusRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--line);
font-size: 12px;
font-weight: 750;
}
#status {
display: flex;
align-items: center;
gap: 7px;
}
#status::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(35, 139, 102, 0.13);
}
#moveCount {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
#clearancePanel {
position: fixed;
top: 20px;
right: 20px;
width: min(310px, calc(100vw - 40px));
padding: 16px;
border-radius: 18px;
}
.panel-title {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.live-badge {
padding: 5px 8px;
border-radius: 999px;
background: #dceee7;
color: var(--green);
font-size: 9px;
letter-spacing: 0.08em;
}
.clearance-number {
display: flex;
align-items: baseline;
gap: 6px;
margin: 2px 0 3px;
}
#clearanceValue {
font-size: 36px;
font-weight: 900;
letter-spacing: -0.06em;
font-variant-numeric: tabular-nums;
}
.unit { color: var(--muted); font-size: 13px; font-weight: 750; }
#clearanceText {
min-height: 35px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.meter {
position: relative;
height: 9px;
margin: 13px 0 7px;
overflow: hidden;
border-radius: 99px;
background: #d9e1e3;
}
#clearanceFill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--green);
transition: width 180ms ease, background 180ms ease;
}
.meter-labels {
display: flex;
justify-content: space-between;
color: #7b8992;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#vehicleLabel {
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line);
font-size: 12px;
font-weight: 800;
}
#vehicleLabel span {
float: right;
color: var(--muted);
font-variant-numeric: tabular-nums;
}
#toolbar {
position: fixed;
left: 50%;
bottom: 20px;
display: flex;
gap: 8px;
padding: 8px;
border-radius: 16px;
transform: translateX(-50%);
}
.tool {
min-width: 42px;
height: 39px;
padding: 0 13px;
border: 0;
border-radius: 10px;
background: transparent;
color: var(--ink);
cursor: pointer;
font-size: 12px;
font-weight: 850;
transition: transform 120ms ease, background 120ms ease;
}
.tool:hover { background: #e8eeeb; transform: translateY(-1px); }
.tool:active { transform: translateY(1px); }
.tool.primary { background: var(--ink); color: white; }
.tool.primary:hover { background: #263e50; }
#instructions {
position: fixed;
left: 20px;
bottom: 20px;
width: min(335px, calc(100vw - 40px));
padding: 13px 15px;
border-radius: 15px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
pointer-events: none;
}
kbd {
display: inline-grid;
min-width: 21px;
height: 21px;
place-items: center;
margin: 0 1px;
padding: 0 5px;
border: 1px solid #bdc8cb;
border-bottom-width: 2px;
border-radius: 5px;
background: white;
color: var(--ink);
font: 800 10px ui-monospace, monospace;
}
#levels {
position: fixed;
top: 185px;
right: 20px;
display: flex;
gap: 6px;
padding: 6px;
border-radius: 13px;
}
.level-dot {
width: 34px;
height: 32px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 11px;
font-weight: 900;
}
.level-dot.active {
background: var(--ink);
color: white;
}
#toast {
position: fixed;
left: 50%;
top: 22px;
max-width: min(520px, calc(100vw - 40px));
padding: 12px 16px;
border-radius: 13px;
color: white;
background: rgba(20, 35, 51, 0.93);
box-shadow: var(--shadow);
opacity: 0;
pointer-events: none;
transform: translate(-50%, -18px);
transition: opacity 180ms ease, transform 180ms ease;
font-size: 12px;
font-weight: 750;
text-align: center;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.warn { background: rgba(181, 74, 53, 0.95); }
#dpad {
position: fixed;
right: 20px;
bottom: 78px;
display: none;
grid-template-columns: repeat(3, 40px);
grid-template-rows: repeat(2, 40px);
gap: 5px;
padding: 7px;
border-radius: 14px;
}
#dpad button {
border: 0;
border-radius: 9px;
background: var(--ink);
color: white;
cursor: pointer;
font-size: 18px;
font-weight: 900;
}
#dpad [data-dir="up"] { grid-column: 2; }
#dpad [data-dir="left"] { grid-column: 1; grid-row: 2; }
#dpad [data-dir="down"] { grid-column: 2; grid-row: 2; }
#dpad [data-dir="right"] { grid-column: 3; grid-row: 2; }
#win {
position: fixed;
inset: 0;
display: grid;
place-items: center;
padding: 20px;
background: rgba(23, 43, 56, 0.24);
opacity: 0;
pointer-events: none;
transition: opacity 220ms ease;
}
#win.show {
opacity: 1;
pointer-events: auto;
}
.win-card {
width: min(430px, 100%);
padding: 28px;
border-radius: 24px;
text-align: center;
}
.win-icon {
display: grid;
width: 58px;
height: 58px;
margin: 0 auto 15px;
place-items: center;
border-radius: 16px;
background: #dceee7;
color: var(--green);
font-size: 30px;
font-weight: 900;
}
.win-card h2 {
margin: 0 0 8px;
font-size: 30px;
letter-spacing: -0.05em;
}
.win-card p {
margin: 0 0 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.win-actions {
display: flex;
justify-content: center;
gap: 9px;
}
@media (max-width: 760px) {
#brand {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
#brand h1 { font-size: 25px; }
#levelName { margin-top: 5px; }
#statusRow { margin-top: 8px; padding-top: 8px; }
#clearancePanel {
top: auto;
right: 10px;
bottom: 68px;
width: 230px;
padding: 12px;
}
#clearanceValue { font-size: 27px; }
#clearanceText { min-height: auto; font-size: 10px; }
#vehicleLabel { margin-top: 9px; padding-top: 9px; }
#levels {
top: 130px;
right: 10px;
}
#toolbar {
left: 10px;
bottom: 10px;
transform: none;
}
#instructions { display: none; }
#dpad { display: grid; right: 10px; bottom: 205px; }
#toast { top: 124px; }
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<section id="brand" class="glass">
<div class="eyebrow"><span class="cube-logo"></span> Voxel traffic puzzle</div>
<h1>Closed Ford</h1>
<div id="levelName">Single Lane</div>
<div id="statusRow">
<div id="status">Traffic moving</div>
<div id="moveCount">0 moves</div>
</div>
</section>
<section id="clearancePanel" class="glass">
<div class="panel-title">
<span>Bridge clearance</span>
<span class="live-badge">GEOMETRY LIVE</span>
</div>
<div class="clearance-number">
<span id="clearanceValue">0.92</span><span class="unit">m clear</span>
</div>
<div id="clearanceText">Select a vehicle to inspect its exact swept envelope.</div>
<div class="meter"><div id="clearanceFill"></div></div>
<div class="meter-labels">
<span>Vehicle envelope</span>
<span>Rail limit</span>
</div>
<div id="vehicleLabel">RED BUS <span>—</span></div>
</section>
<section id="levels" class="glass">
<button class="level-dot active" data-level="0">01</button>
<button class="level-dot" data-level="1">02</button>
<button class="level-dot" data-level="2">03</button>
</section>
<section id="toolbar" class="glass">
<button class="tool" id="undoButton" title="Undo">↶ Undo</button>
<button class="tool" id="resetButton" title="Reset level">⟲ Reset</button>
<button class="tool" id="hintButton" title="Show a hint">? Hint</button>
<button class="tool" id="cameraButton" title="Reset camera">⌾ View</button>
</section>
<section id="instructions" class="glass">
<b>Select a vehicle</b>, then use <kbd>←</kbd><kbd>→</kbd><kbd>↑</kbd><kbd>↓</kbd>.
Vehicles move only along their own axle. Drag the scene to orbit and scroll to zoom.
The bridge is one vehicle wide; actual body width and rail contact are checked geometrically.
</section>
<section id="dpad" class="glass" aria-label="Movement controls">
<button data-dir="up" aria-label="Move up">↑</button>
<button data-dir="left" aria-label="Move left">←</button>
<button data-dir="down" aria-label="Move down">↓</button>
<button data-dir="right" aria-label="Move right">→</button>
</section>
<div id="toast" role="status"></div>
<section id="win">
<div class="win-card glass">
<div class="win-icon">✓</div>
<h2>Detour cleared</h2>
<p id="winText">The red bus passed the narrow bridge and exited the east gate.</p>
<div class="win-actions">
<button class="tool" id="winUndo">Undo</button>
<button class="tool primary" id="nextLevel">Next level →</button>
</div>
</div>
</section>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Puzzle data. Grid cells use integer x/z coordinates.
// x = 0..8, z = 0..7. The closed ford is column x=4.
// The only crossing is the one-lane bridge at the level's bridgeRow.
// -------------------------------------------------------------------------
const LEVELS = [
{
name: "Single Lane",
subtitle: "Clear the two vans, then guide the red bus across row 3.",
bridgeRow: 2,
vehicles: [
{ id: "red", name: "RED BUS", color: 0xef5145, len: 2, axis: "h", x: 2, z: 2, width: 0.66, goal: true },
{ id: "cream", name: "CREAM TRUCK", color: 0xe9d8ae, len: 2, axis: "h", x: 5, z: 0, width: 0.78 },
{ id: "blue", name: "BLUE VAN", color: 0x377fc1, len: 2, axis: "v", x: 5, z: 2, width: 0.72 },
{ id: "purple", name: "PURPLE VAN", color: 0x8566ae, len: 2, axis: "v", x: 6, z: 2, width: 0.76 }
],
hints: [
{ id: "cream", text: "Move CREAM TRUCK right two cells to unpin both vans." },
{ id: "blue", text: "Move BLUE VAN up two cells." },
{ id: "purple", text: "Move PURPLE VAN up two cells." },
{ id: "red", text: "The route is clear. Move RED BUS right to the east gate." }
]
},
{
name: "Tailgate",
subtitle: "A truck blocks the red bus before the bridge; more traffic waits beyond it.",
bridgeRow: 4,
vehicles: [
{ id: "red", name: "RED BUS", color: 0xef5145, len: 2, axis: "h", x: 0, z: 4, width: 0.68, goal: true },
{ id: "orange", name: "ORANGE VAN", color: 0xe68a32, len: 2, axis: "v", x: 2, z: 4, width: 0.74 },
{ id: "cream", name: "CREAM TRUCK", color: 0xe9d8ae, len: 2, axis: "h", x: 2, z: 2, width: 0.72 },
{ id: "teal", name: "TEAL TRUCK", color: 0x3a9e93, len: 2, axis: "h", x: 5, z: 2, width: 0.76 },
{ id: "blue", name: "BLUE VAN", color: 0x377fc1, len: 2, axis: "v", x: 5, z: 4, width: 0.70 },
{ id: "purple", name: "PURPLE VAN", color: 0x8566ae, len: 2, axis: "v", x: 6, z: 4, width: 0.78 },
{ id: "wide", name: "WIDE LOADER", color: 0x66727c, len: 2, axis: "h", x: 0, z: 0, width: 1.02 }
],
hints: [
{ id: "cream", text: "Move CREAM TRUCK left two cells." },
{ id: "orange", text: "Move ORANGE VAN up two cells." },
{ id: "teal", text: "Move TEAL TRUCK right two cells." },
{ id: "blue", text: "Move BLUE VAN up two cells." },
{ id: "purple", text: "Move PURPLE VAN up two cells." },
{ id: "red", text: "Move RED BUS right through the now-open detour." }
]
},
{
name: "Full Detour",
subtitle: "The bridge is at the far side of the board. Check every envelope before crossing.",
bridgeRow: 1,
vehicles: [
{ id: "red", name: "RED BUS", color: 0xef5145, len: 2, axis: "h", x: 0, z: 1, width: 0.70, goal: true },
{ id: "orange", name: "ORANGE VAN", color: 0xe68a32, len: 2, axis: "v", x: 2, z: 1, width: 0.72 },
{ id: "blue", name: "BLUE VAN", color: 0x377fc1, len: 2, axis: "v", x: 3, z: 3, width: 0.78 },
{ id: "cream", name: "CREAM TRUCK", color: 0xe9d8ae, len: 2, axis: "h", x: 2, z: 5, width: 0.74 },
{ id: "purple", name: "PURPLE VAN", color: 0x8566ae, len: 2, axis: "v", x: 5, z: 1, width: 0.80 },
{ id: "teal", name: "TEAL VAN", color: 0x3a9e93, len: 2, axis: "v", x: 6, z: 1, width: 0.84 },
{ id: "wide", name: "WIDE LOADER", color: 0x66727c, len: 2, axis: "h", x: 5, z: 4, width: 1.02 }
],
hints: [
{ id: "cream", text: "Move CREAM TRUCK left two cells." },
{ id: "orange", text: "Move ORANGE VAN down two cells." },
{ id: "wide", text: "Move WIDE LOADER right two cells; it is too wide for the bridge." },
{ id: "purple", text: "Move PURPLE VAN down one cell." },
{ id: "teal", text: "Move TEAL VAN down one cell." },
{ id: "red", text: "Move RED BUS right through the bridge." }
]
}
];
const COLS = 9;
const ROWS = 8;
const CELL = 1;
const BRIDGE_CLEAR = 0.92;
const RAIL_THICKNESS = 0.12;
const BOARD_LEFT = -4.5;
const BOARD_RIGHT = 4.5;
const BOARD_TOP = -4;
const BOARD_BOTTOM = 4;
const EPSILON = 1e-7;
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
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.1;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb8dce5);
scene.fog = new THREE.Fog(0xb8dce5, 18, 38);
const camera = new THREE.PerspectiveCamera(42, window.innerWidth / window.innerHeight, 0.1, 100);
const cameraState = {
yaw: 0.67,
pitch: 0.76,
radius: 15.5,
target: new THREE.Vector3(0, 0.15, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(pitch) * Math.sin(yaw),
target.y + radius * Math.cos(pitch),
target.z + radius * Math.sin(pitch) * Math.cos(yaw)
);
camera.lookAt(target);
}
updateCamera();
const ambient = new THREE.HemisphereLight(0xeafaff, 0x6b7561, 2.25);
scene.add(ambient);
const sun = new THREE.DirectionalLight(0xfff1d0, 3.0);
sun.position.set(-7, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -11;
sun.shadow.camera.right = 11;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -11;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9fc7ff, 0.75);
fill.position.set(8, 6, -8);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({ color: 0x91b68b, roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.72;
ground.receiveShadow = true;
scene.add(ground);
let boardGroup = null;
let vehicleLayer = null;
let vehicles = [];
let vehicleGroups = [];
let staticObstacles = [];
let waterTiles = [];
let laneGhost = null;
let currentLevelIndex = 0;
let currentLevel = LEVELS[0];
let selectedId = null;
let hoveredId = null;
let moveCount = 0;
let history = [];
let hintIndex = 0;
let won = false;
let busy = false;
const animations = new Map();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const ui = {
levelName: document.querySelector("#levelName"),
status: document.querySelector("#status"),
moveCount: document.querySelector("#moveCount"),
clearanceValue: document.querySelector("#clearanceValue"),
clearanceText: document.querySelector("#clearanceText"),
clearanceFill: document.querySelector("#clearanceFill"),
vehicleLabel: document.querySelector("#vehicleLabel"),
toast: document.querySelector("#toast"),
win: document.querySelector("#win"),
winText: document.querySelector("#winText"),
nextLevel: document.querySelector("#nextLevel"),
undoButton: document.querySelector("#undoButton"),
resetButton: document.querySelector("#resetButton"),
hintButton: document.querySelector("#hintButton"),
cameraButton: document.querySelector("#cameraButton")
};
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
function worldX(gridX) {
return gridX - 4;
}
function worldZ(gridZ) {
return gridZ - 3.5;
}
function vehicleLength(vehicle) {
return vehicle.len * CELL - 0.16;
}
function makeOBB(cx, cz, hx, hz, angle = 0) {
const ux = Math.cos(angle);
const uz = Math.sin(angle);
return {
cx, cz, hx, hz, angle,
ux, uz,
vx: -uz,
vz: ux
};
}
function footprint(vehicle, gridX = vehicle.x, gridZ = vehicle.z) {
const length = vehicleLength(vehicle);
const width = vehicle.width;
if (vehicle.axis === "h") {
return makeOBB(
worldX(gridX + (vehicle.len - 1) / 2),
worldZ(gridZ),
length / 2,
width / 2,
0
);
}
return makeOBB(
worldX(gridX),
worldZ(gridZ + (vehicle.len - 1) / 2),
length / 2,
width / 2,
Math.PI / 2
);
}
// Separating Axis Theorem for exact rectangle/OBB overlap.
function obbOverlap(a, b) {
const axes = [
[a.ux, a.uz], [a.vx, a.vz],
[b.ux, b.uz], [b.vx, b.vz]
];
for (const [ax, az] of axes) {
const dx = b.cx - a.cx;
const dz = b.cz - a.cz;
const centerDistance = Math.abs(dx * ax + dz * az);
const radiusA =
a.hx * Math.abs(ax * a.ux + az * a.uz) +
a.hz * Math.abs(ax * a.vx + az * a.vz);
const radiusB =
b.hx * Math.abs(ax * b.ux + az * b.uz) +
b.hz * Math.abs(ax * b.vx + az * b.vz);
if (centerDistance >= radiusA + radiusB - EPSILON) {
return false;
}
}
return true;
}
function vehicleCenter(vehicle, gridX = vehicle.x, gridZ = vehicle.z) {
const box = footprint(vehicle, gridX, gridZ);
return new THREE.Vector3(box.cx, 0, box.cz);
}
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabelSprite(text, background = "#172b3a", foreground = "#ffffff", width = 2.2) {
const c = document.createElement("canvas");
c.width = 512;
c.height = 128;
const ctx = c.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, c.width, c.height);
ctx.strokeStyle = "rgba(255,255,255,.22)";
ctx.lineWidth = 8;
ctx.strokeRect(8, 8, c.width - 16, c.height - 16);
ctx.fillStyle = foreground;
ctx.font = "900 48px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, c.width / 2, c.height / 2 + 2);
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({ map: texture, depthWrite: false });
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width / 4, 1);
return sprite;
}
// -------------------------------------------------------------------------
// Board construction
// -------------------------------------------------------------------------
function clearLayer(oldLayer) {
if (!oldLayer) return;
scene.remove(oldLayer);
oldLayer.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
}
function buildBoard(level) {
clearLayer(boardGroup);
boardGroup = new THREE.Group();
scene.add(boardGroup);
waterTiles = [];
staticObstacles = [];
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x68736c,
roughness: 0.95
});
addBox(
boardGroup,
new THREE.Vector3(4.25, 0.52, 8.25),
new THREE.Vector3(-2.38, -0.48, 0),
baseMaterial
);
addBox(
boardGroup,
new THREE.Vector3(4.25, 0.52, 8.25),
new THREE.Vector3(2.38, -0.48, 0),
baseMaterial
);
const landMaterials = [
new THREE.MeshStandardMaterial({ color: 0xd6c99e, roughness: 0.98 }),
new THREE.MeshStandardMaterial({ color: 0xcfc49c, roughness: 0.98 }),
new THREE.MeshStandardMaterial({ color: 0xd9cca3, roughness: 0.98 })
];
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x3b9eb4,
roughness: 0.38,
metalness: 0.05,
transparent: true,
opacity: 0.86
});
for (let gx = 0; gx < COLS; gx++) {
for (let gz = 0; gz < ROWS; gz++) {
const isWater = gx === 4 && gz !== level.bridgeRow;
const material = isWater
? waterMaterial
: landMaterials[(gx * 3 + gz) % landMaterials.length];
const tile = addBox(
boardGroup,
new THREE.Vector3(0.985, 0.30, 0.985),
new THREE.Vector3(worldX(gx), -0.17, worldZ(gz)),
material,
false
);
tile.receiveShadow = true;
if (isWater) {
waterTiles.push(tile);
}
}
}
// Subtle grid lines.
const gridPoints = [];
for (let gx = 0; gx < COLS; gx++) {
for (let gz = 0; gz < ROWS; gz++) {
const x = worldX(gx);
const z = worldZ(gz);
gridPoints.push(
x - 0.49, 0.002, z - 0.49, x + 0.49, 0.002, z - 0.49,
x - 0.49, 0.002, z + 0.49, x + 0.49, 0.002, z + 0.49
);
}
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute("position", new THREE.Float32BufferAttribute(gridPoints, 3));
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x6f786d,
transparent: true,
opacity: 0.24
})
);
boardGroup.add(grid);
const bridgeZ = worldZ(level.bridgeRow);
// Wooden bridge deck.
const woodMaterial = new THREE.MeshStandardMaterial({
color: 0xa86f3e,
roughness: 0.9
});
const woodLight = new THREE.MeshStandardMaterial({
color: 0xc18a51,
roughness: 0.9
});
for (let i = 0; i < 9; i++) {
addBox(
boardGroup,
new THREE.Vector3(0.115, 0.16, 1.13),
new THREE.Vector3(-0.46 + i * 0.115, 0.095, bridgeZ),
i % 2 ? woodMaterial : woodLight
);
}
const railMaterial = new THREE.MeshStandardMaterial({
color: 0xe9e2cc,
roughness: 0.7
});
const railZ = BRIDGE_CLEAR / 2 + RAIL_THICKNESS / 2;
for (const sign of [-1, 1]) {
addBox(
boardGroup,
new THREE.Vector3(1.40, 0.15, RAIL_THICKNESS),
new THREE.Vector3(0, 0.40, bridgeZ + sign * railZ),
railMaterial
);
for (const x of [-0.64, 0.64]) {
addBox(
boardGroup,
new THREE.Vector3(0.12, 0.58, 0.12),
new THREE.Vector3(x, 0.31, bridgeZ + sign * railZ),
new THREE.MeshStandardMaterial({ color: 0x6f7772, roughness: 0.8 })
);
}
}
// Exact collision geometry: water above/below the clear opening.
const upperBottom = bridgeZ - BRIDGE_CLEAR / 2;
const lowerTop = bridgeZ + BRIDGE_CLEAR / 2;
staticObstacles.push({
name: "closed ford water",
box: makeOBB(0, (BOARD_TOP + upperBottom) / 2, 0.5, (upperBottom - BOARD_TOP) / 2)
});
staticObstacles.push({
name: "closed ford water",
box: makeOBB(0, (lowerTop + BOARD_BOTTOM) / 2, 0.5, (BOARD_BOTTOM - lowerTop) / 2)
});
for (const sign of [-1, 1]) {
staticObstacles.push({
name: "bridge rail",
box: makeOBB(0, bridgeZ + sign * railZ, 0.70, RAIL_THICKNESS / 2)
});
}
// The transparent green strip visualizes the usable rail-to-rail lane.
laneGhost = new THREE.Mesh(
new THREE.BoxGeometry(1.42, 0.025, BRIDGE_CLEAR),
new THREE.MeshBasicMaterial({
color: 0x73f0b1,
transparent: true,
opacity: 0.15,
depthWrite: false
})
);
laneGhost.position.set(0, 0.19, bridgeZ);
boardGroup.add(laneGhost);
// Signs and gate.
const closedSign = makeLabelSprite("FORD CLOSED", "#bb4338", "#ffffff", 2.25);
closedSign.position.set(0, 1.18, worldZ(level.bridgeRow === 0 ? 2.5 : 0.5));
boardGroup.add(closedSign);
const detourSign = makeLabelSprite("NARROW DETOUR", "#173649", "#ffe16c", 2.35);
detourSign.position.set(0, 1.05, bridgeZ + 0.92);
boardGroup.add(detourSign);
const gateSign = makeLabelSprite("EAST GATE", "#23634f", "#ffffff", 1.65);
gateSign.position.set(4.75, 1.0, bridgeZ);
boardGroup.add(gateSign);
addBox(
boardGroup,
new THREE.Vector3(0.16, 1.25, 0.16),
new THREE.Vector3(4.62, 0.56, bridgeZ - 0.68),
new THREE.MeshStandardMaterial({ color: 0x3a765e, roughness: 0.85 })
);
addBox(
boardGroup,
new THREE.Vector3(0.16, 1.25, 0.16),
new THREE.Vector3(4.62, 0.56, bridgeZ + 0.68),
new THREE.MeshStandardMaterial({ color: 0x3a765e, roughness: 0.85 })
);
// A small closed-ford barricade floating in the water.
const barricade = new THREE.Group();
barricade.position.set(0, 0.32, worldZ(level.bridgeRow === 0 ? 2.5 : 0.5));
for (let i = 0; i < 4; i++) {
addBox(
barricade,
new THREE.Vector3(0.22, 0.18, 0.85),
new THREE.Vector3(-0.35 + i * 0.23, 0, 0),
new THREE.MeshStandardMaterial({
color: i % 2 ? 0xf5efe1 : 0xc84d42,
roughness: 0.75
})
);
}
boardGroup.add(barricade);
// Minimal voxel landscaping outside the puzzle grid.
addTree(-5.25, -3.7, 0x4f8e56);
addTree(5.15, -3.2, 0x477f50);
addTree(-5.3, 3.2, 0x5a985b);
addTree(5.35, 2.75, 0x3f8050);
}
function addTree(x, z, color) {
const tree = new THREE.Group();
tree.position.set(x, -0.63, z);
const trunk = new THREE.MeshStandardMaterial({ color: 0x79553c, roughness: 1 });
const leaves = new THREE.MeshStandardMaterial({ color, roughness: 1 });
addBox(tree, new THREE.Vector3(0.32, 1.3, 0.32), new THREE.Vector3(0, 0.65, 0), trunk);
addBox(tree, new THREE.Vector3(1.2, 0.9, 1.2), new THREE.Vector3(0, 1.55, 0), leaves);
addBox(tree, new THREE.Vector3(0.85, 0.65, 0.85), new THREE.Vector3(0.12, 2.15, -0.08), leaves);
scene.add(tree);
}
// -------------------------------------------------------------------------
// Voxel vehicle construction
// -------------------------------------------------------------------------
function createVehicle(vehicle) {
const group = new THREE.Group();
const length = vehicleLength(vehicle);
const width = vehicle.width;
group.userData.vehicleId = vehicle.id;
const paint = new THREE.MeshStandardMaterial({
color: vehicle.color,
roughness: 0.62,
metalness: 0.08
});
const dark = new THREE.MeshStandardMaterial({
color: 0x24323a,
roughness: 0.72
});
const glass = new THREE.MeshStandardMaterial({
color: 0x8bc2d4,
roughness: 0.32,
metalness: 0.12
});
const light = new THREE.MeshStandardMaterial({
color: 0xffefb1,
emissive: 0x9b6d21,
emissiveIntensity: 0.22,
roughness: 0.5
});
addBox(
group,
new THREE.Vector3(length, 0.38, width),
new THREE.Vector3(0, 0.43, 0),
paint
);
const cabinLength = vehicle.len === 1 ? 0.55 : Math.min(0.78, length * 0.43);
const cabinX = vehicle.len === 1 ? 0 : -length * 0.13;
addBox(
group,
new THREE.Vector3(cabinLength, 0.31, width * 0.86),
new THREE.Vector3(cabinX, 0.76, 0),
paint
);
// Side windows remain inside the physical width envelope.
for (const side of [-1, 1]) {
addBox(
group,
new THREE.Vector3(cabinLength * 0.72, 0.16, 0.035),
new THREE.Vector3(cabinX, 0.79, side * (width / 2 - 0.018)),
glass,
false
);
}
addBox(
group,
new THREE.Vector3(0.06, 0.14, width * 0.66),
new THREE.Vector3(cabinX + cabinLength / 2 + 0.01, 0.79, 0),
glass,
false
);
const wheelX = vehicle.len === 1 ? 0 : length * 0.28;
const wheelPositions = vehicle.len === 1
? [0]
: [-wheelX, wheelX];
for (const x of wheelPositions) {
for (const side of [-1, 1]) {
addBox(
group,
new THREE.Vector3(0.34, 0.22, 0.12),
new THREE.Vector3(x, 0.27, side * (width / 2 - 0.075)),
dark
);
}
}
for (const side of [-1, 1]) {
addBox(
group,
new THREE.Vector3(0.07, 0.10, width * 0.20),
new THREE.Vector3(length / 2 - 0.035, 0.48, side * width * 0.24),
light,
false
);
}
const outlineGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(length + 0.08, 0.76, width + 0.08)
);
const outlineMaterial = new THREE.LineBasicMaterial({
color: 0xffdf55,
transparent: true,
opacity: 0.95
});
const outline = new THREE.LineSegments(outlineGeometry, outlineMaterial);
outline.position.y = 0.46;
outline.visible = false;
group.add(outline);
vehicle.outline = outline;
vehicle.group = group;
if (vehicle.axis === "v") {
group.rotation.y = Math.PI / 2;
}
const center = vehicleCenter(vehicle);
group.position.copy(center);
vehicleLayer.add(group);
vehicleGroups.push(group);
}
// -------------------------------------------------------------------------
// Collision and movement
// -------------------------------------------------------------------------
function collisionReason(vehicle, nextX, nextZ) {
const candidate = footprint(vehicle, nextX, nextZ);
for (const other of vehicles) {
if (other.id === vehicle.id) continue;
if (obbOverlap(candidate, footprint(other))) {
return `${other.name} is in the swept path`;
}
}
for (const obstacle of staticObstacles) {
if (obbOverlap(candidate, obstacle.box)) {
return obstacle.name === "bridge rail"
? "The vehicle envelope touches a bridge rail"
: "The ford is closed — use the narrow bridge";
}
}
return null;
}
function tryMove(id, direction) {
if (busy || won) return;
const vehicle = vehicles.find(v => v.id === id);
if (!vehicle) return;
if (vehicle.axis === "h" && !["left", "right"].includes(direction)) {
showToast(`${vehicle.name} can only roll left or right.`, true);
return;
}
if (vehicle.axis === "v" && !["up", "down"].includes(direction)) {
showToast(`${vehicle.name} can only roll up or down.`, true);
return;
}
let nextX = vehicle.x;
let nextZ = vehicle.z;
if (direction === "left") nextX--;
if (direction === "right") nextX++;
if (direction === "up") nextZ--;
if (direction === "down") nextZ++;
let exiting = false;
if (vehicle.axis === "h") {
if (nextX < 0) {
showToast("Board edge reached.", true);
return;
}
if (nextX + vehicle.len - 1 > COLS - 1) {
const validExit =
vehicle.goal &&
nextX === COLS - 1 &&
vehicle.z === currentLevel.bridgeRow;
if (!validExit) {
showToast("Only the red bus can leave through the east gate.", true);
return;
}
exiting = true;
}
} else {
if (nextZ < 0 || nextZ + vehicle.len - 1 > ROWS - 1) {
showToast("Board edge reached.", true);
return;
}
}
const reason = collisionReason(vehicle, nextX, nextZ);
if (reason) {
showToast(reason + ".", true);
return;
}
history.push(snapshot());
const fromX = vehicle.x;
const fromZ = vehicle.z;
vehicle.x = nextX;
vehicle.z = nextZ;
moveCount++;
hintIndex = 0;
animateVehicle(vehicle, fromX, fromZ, nextX, nextZ, exiting);
updateHud();
if (!exiting) {
showToast(`${vehicle.name} moved ${direction}.`);
}
}
function snapshot() {
return vehicles.map(v => ({
id: v.id,
x: v.x,
z: v.z,
delivered: v.delivered,
exiting: v.exiting
}));
}
function restoreSnapshot(state) {
animations.clear();
busy = false;
for (const saved of state) {
const vehicle = vehicles.find(v => v.id === saved.id);
if (!vehicle) continue;
vehicle.x = saved.x;
vehicle.z = saved.z;
vehicle.delivered = saved.delivered;
vehicle.exiting = saved.exiting;
vehicle.group.visible = !vehicle.delivered;
vehicle.group.position.copy(vehicleCenter(vehicle));
}
ui.win.classList.remove("show");
won = false;
}
function animateVehicle(vehicle, fromX, fromZ, toX, toZ, exiting) {
const from = vehicleCenter(vehicle, fromX, fromZ);
const to = vehicleCenter(vehicle, toX, toZ);
if (exiting) {
to.x += 1.0;
}
vehicle.exiting = exiting;
animations.set(vehicle.id, {
vehicle,
from,
to,
exiting,
start: performance.now(),
duration: exiting ? 900 : 260
});
}
function undoMove() {
if (!history.length) {
showToast("Nothing to undo.");
return;
}
const previous = history.pop();
restoreSnapshot(previous);
moveCount = Math.max(0, moveCount - 1);
updateHud();
showToast("Last move undone.");
}
function resetLevel() {
loadLevel(currentLevelIndex);
showToast("Level reset.");
}
// -------------------------------------------------------------------------
// UI and level flow
// -------------------------------------------------------------------------
function showToast(message, warn = false) {
ui.toast.textContent = message;
ui.toast.classList.toggle("warn", warn);
ui.toast.classList.add("show");
clearTimeout(showToast.timer);
showToast.timer = setTimeout(() => ui.toast.classList.remove("show"), 2200);
}
function selectVehicle(id) {
selectedId = id;
for (const vehicle of vehicles) {
vehicle.outline.visible = vehicle.id === id;
}
updateHud();
}
function updateHud() {
const vehicle = vehicles.find(v => v.id === selectedId);
const level = currentLevel;
ui.levelName.textContent = `${String(currentLevelIndex + 1).padStart(2, "0")} / ${level.name} — ${level.subtitle}`;
ui.moveCount.textContent = `${moveCount} move${moveCount === 1 ? "" : "s"}`;
if (won) {
ui.status.textContent = "Detour cleared";
} else if (busy) {
ui.status.textContent = "Vehicle moving";
} else {
ui.status.textContent = "Traffic moving";
}
if (!vehicle) {
ui.clearanceValue.textContent = BRIDGE_CLEAR.toFixed(2);
ui.clearanceText.textContent = "Select a vehicle to inspect its exact swept envelope.";
ui.clearanceFill.style.width = "0%";
ui.vehicleLabel.innerHTML = "NO VEHICLE <span>—</span>";
return;
}
const sideClearance = (BRIDGE_CLEAR - vehicle.width) / 2;
const fits = vehicle.width < BRIDGE_CLEAR - EPSILON;
ui.clearanceValue.textContent = sideClearance.toFixed(2);
ui.clearanceFill.style.width = `${Math.min(100, vehicle.width / BRIDGE_CLEAR * 100)}%`;
ui.clearanceFill.style.background = fits ? "#238b66" : "#d94f43";
if (!fits) {
ui.clearanceText.textContent =
`${vehicle.name} is too wide for the ${BRIDGE_CLEAR.toFixed(2)} m opening. ` +
`Rail interference: ${Math.abs(sideClearance).toFixed(2)} m.`;
} else if (vehicle.axis === "h") {
ui.clearanceText.textContent =
`${vehicle.name} fits with ${sideClearance.toFixed(2)} m per side. ` +
`Its ${vehicle.len}-cell swept body clears the rails.`;
} else {
ui.clearanceText.textContent =
`${vehicle.name} has ${sideClearance.toFixed(2)} m per side, but its axle must be realigned for a crossing.`;
}
ui.vehicleLabel.innerHTML =
`${vehicle.name} <span>${vehicle.width.toFixed(2)} m wide</span>`;
}
function loadLevel(index) {
currentLevelIndex = (index + LEVELS.length) % LEVELS.length;
currentLevel = LEVELS[currentLevelIndex];
clearLayer(vehicleLayer);
vehicleLayer = new THREE.Group();
scene.add(vehicleLayer);
vehicles = currentLevel.vehicles.map(v => ({
...v,
delivered: false,
exiting: false,
group: null,
outline: null
}));
vehicleGroups = [];
history = [];
moveCount = 0;
hintIndex = 0;
selectedId = null;
hoveredId = null;
won = false;
busy = false;
animations.clear();
ui.win.classList.remove("show");
buildBoard(currentLevel);
for (const vehicle of vehicles) {
createVehicle(vehicle);
}
const goal = vehicles.find(v => v.goal);
if (goal) selectVehicle(goal.id);
document.querySelectorAll(".level-dot").forEach((button, i) => {
button.classList.toggle("active", i === currentLevelIndex);
});
updateHud();
}
function showWin() {
won = true;
busy = false;
updateHud();
const isLast = currentLevelIndex === LEVELS.length - 1;
ui.winText.textContent = isLast
? "All three detours are cleared. Every vehicle envelope passed the narrow bridge without touching a rail."
: "The red bus passed the narrow bridge and exited the east gate.";
ui.nextLevel.textContent = isLast ? "Play again ↻" : "Next level →";
ui.win.classList.add("show");
}
function showHint() {
const hints = currentLevel.hints;
if (!hints.length) return;
const hint = hints[hintIndex % hints.length];
hintIndex++;
selectVehicle(hint.id);
const vehicle = vehicles.find(v => v.id === hint.id);
if (vehicle) {
vehicle.outline.material.color.set(0xffdf55);
vehicle.outline.material.opacity = 1;
setTimeout(() => {
vehicle.outline.material.color.set(0xffdf55);
}, 1200);
}
showToast(hint.text);
}
ui.undoButton.addEventListener("click", undoMove);
ui.resetButton.addEventListener("click", resetLevel);
ui.hintButton.addEventListener("click", showHint);
ui.cameraButton.addEventListener("click", () => {
cameraState.yaw = 0.67;
cameraState.pitch = 0.76;
cameraState.radius = 15.5;
cameraState.target.set(0, 0.15, 0);
updateCamera();
});
ui.nextLevel.addEventListener("click", () => {
const next = currentLevelIndex === LEVELS.length - 1 ? 0 : currentLevelIndex + 1;
loadLevel(next);
});
document.querySelector("#winUndo").addEventListener("click", () => {
ui.win.classList.remove("show");
won = false;
undoMove();
});
document.querySelectorAll(".level-dot").forEach((button) => {
button.addEventListener("click", () => loadLevel(Number(button.dataset.level)));
});
document.querySelectorAll("#dpad button").forEach((button) => {
button.addEventListener("click", () => {
if (!selectedId) {
showToast("Select a vehicle first.", true);
return;
}
tryMove(selectedId, button.dataset.dir);
});
});
window.addEventListener("keydown", (event) => {
const keyMap = {
ArrowLeft: "left",
ArrowRight: "right",
ArrowUp: "up",
ArrowDown: "down",
a: "left",
d: "right",
w: "up",
s: "down"
};
const direction = keyMap[event.key];
if (direction) {
event.preventDefault();
if (!selectedId) {
showToast("Select a vehicle first.", true);
return;
}
tryMove(selectedId, direction);
}
if (event.key.toLowerCase() === "z" && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
undoMove();
}
if (event.key.toLowerCase() === "r") {
resetLevel();
}
});
// -------------------------------------------------------------------------
// Direct camera controls: no addons are used.
// -------------------------------------------------------------------------
let drag = null;
canvas.addEventListener("pointerdown", (event) => {
drag = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
startX: event.clientX,
startY: event.clientY,
moved: false
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!drag || event.pointerId !== drag.id) {
updateHover(event);
return;
}
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
if (Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > 5) {
drag.moved = true;
}
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * 0.0045, 0.34, 1.28);
drag.x = event.clientX;
drag.y = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
if (!drag || event.pointerId !== drag.id) return;
if (!drag.moved) {
const hit = pickVehicle(event);
if (hit) selectVehicle(hit);
}
drag = null;
});
canvas.addEventListener("pointercancel", () => {
drag = null;
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
9.5,
23
);
updateCamera();
}, { passive: false });
function updateHover(event) {
const hit = pickVehicle(event);
hoveredId = hit;
canvas.style.cursor = hit ? "pointer" : "grab";
}
function pickVehicle(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(vehicleGroups, true);
for (const hit of hits) {
let object = hit.object;
while (object) {
if (object.userData.vehicleId) return object.userData.vehicleId;
object = object.parent;
}
}
return null;
}
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate(now) {
const time = clock.getElapsedTime();
for (const animation of animations.values()) {
const t = THREE.MathUtils.clamp((now - animation.start) / animation.duration, 0, 1);
const eased = 1 - Math.pow(1 - t, 3);
animation.vehicle.group.position.lerpVectors(
animation.from,
animation.to,
eased
);
if (t >= 1) {
animations.delete(animation.vehicle.id);
if (animation.exiting) {
animation.vehicle.delivered = true;
animation.vehicle.exiting = false;
animation.vehicle.group.visible = false;
busy = false;
showWin();
}
}
}
busy = animations.size > 0;
for (let i = 0; i < waterTiles.length; i++) {
const tile = waterTiles[i];
tile.position.y = -0.17 + Math.sin(time * 1.8 + i * 0.75) * 0.018;
}
if (laneGhost) {
laneGhost.material.opacity = 0.11 + Math.sin(time * 2.2) * 0.035;
}
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
loadLevel(0);
</script>
</body>
</html>
```