Prompt specification
Build or customize the Three.js 3D scene "One Vehicle Joins a Circular Stream" 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: One Vehicle Joins a Circular Stream
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/one-vehicle-joins-a-circular-stream-x2134
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a roundabout and its entry merges. Animate a toy vehicle waiting for a defined gap before entering a circular stream. State the fictional priority rule and avoid overlapping moving footprints. Voxel style.
Working Three.js Starter (one-vehicle-joins-a-circular-stream-x2134):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Roundabout Priority</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(17, 25, 31, 0.90);
--border: rgba(255, 255, 255, 0.14);
--muted: #aebbc3;
--yellow: #ffd84d;
--green: #70e6a6;
--red: #ff7b75;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #9fd3e2;
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
z-index: 0;
}
.hud {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: min(390px, calc(100vw - 36px));
padding: 17px;
border: 1px solid var(--border);
border-radius: 17px;
color: #f6fbfd;
background: var(--panel);
box-shadow: 0 18px 45px rgba(8, 18, 25, 0.28);
backdrop-filter: blur(14px);
user-select: none;
}
.eyebrow {
margin-bottom: 5px;
color: var(--yellow);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(21px, 3vw, 29px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 8px 0 14px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.rule {
padding: 12px;
border: 1px solid rgba(255, 216, 77, 0.25);
border-radius: 12px;
background: rgba(255, 216, 77, 0.07);
font-size: 12px;
line-height: 1.48;
}
.rule strong {
color: var(--yellow);
}
.status {
display: flex;
align-items: center;
gap: 9px;
margin-top: 14px;
padding: 11px 12px;
border-radius: 11px;
background: rgba(255, 255, 255, 0.065);
font-size: 12px;
font-weight: 850;
letter-spacing: 0.065em;
}
.status[data-tone="wait"] {
color: var(--yellow);
}
.status[data-tone="go"] {
color: var(--green);
}
.status[data-tone="stream"] {
color: #8ed8ff;
}
.dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 13px currentColor;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 10px;
}
.metric {
min-width: 0;
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 10px;
background: rgba(0, 0, 0, 0.12);
}
.metric-label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
display: block;
overflow: hidden;
color: #fff;
font-size: 15px;
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-value.safe {
color: var(--green);
}
.metric-value.hold {
color: var(--yellow);
}
.progress {
height: 7px;
margin-top: 12px;
overflow: hidden;
border-radius: 20px;
background: rgba(255, 255, 255, 0.10);
}
.progress > div {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #ffd84d, #70e6a6);
transition: width 80ms linear;
}
.buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 13px;
}
button {
appearance: none;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 9px;
color: #fff;
background: rgba(255, 255, 255, 0.075);
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
transition: background 150ms, transform 150ms;
}
button:hover {
background: rgba(255, 255, 255, 0.14);
transform: translateY(-1px);
}
button.primary {
border-color: rgba(255, 216, 77, 0.35);
color: #231c00;
background: var(--yellow);
}
.help {
position: fixed;
z-index: 9;
right: 18px;
bottom: 17px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 10px;
color: #15313d;
background: rgba(255, 255, 255, 0.76);
box-shadow: 0 8px 22px rgba(14, 39, 50, 0.13);
font-size: 11px;
font-weight: 750;
pointer-events: none;
}
#toy-tag {
position: fixed;
z-index: 8;
display: none;
padding: 5px 8px;
border: 2px solid #fff2a6;
border-radius: 7px;
color: #241d00;
background: #ffd84d;
box-shadow: 0 5px 14px rgba(20, 25, 30, 0.22);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.05em;
pointer-events: none;
transform: translate(-50%, -100%);
}
#loading {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
color: #fff;
background: #172a32;
font-weight: 800;
letter-spacing: 0.08em;
}
@media (max-width: 620px) {
.hud {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px;
}
.subtitle {
margin-bottom: 10px;
}
.rule {
font-size: 11px;
}
.help {
right: 10px;
bottom: 10px;
}
}
</style>
</head>
<body>
<div id="loading">BUILDING VOXEL ROUNDABOUT…</div>
<section class="hud" aria-label="Roundabout simulation information">
<div class="eyebrow">Fictional Traffic Rule</div>
<h1>Roundabout Priority</h1>
<p class="subtitle">
A toy vehicle approaches from the south, yields, then joins the
clockwise circular stream when the merge window is safe.
</p>
<div class="rule">
<strong>Circulating vehicles always have priority.</strong>
An entering vehicle may merge only when the 6-meter merge box is
empty and the next circulating vehicle is at least
<strong>2.5 seconds</strong> away. If projected vehicle footprints
overlap, the entering vehicle pauses instead of forcing its way in.
</div>
<div id="status" class="status" data-tone="wait" aria-live="polite">
<span class="dot"></span>
<span id="status-text">WAITING FOR A GAP</span>
</div>
<div class="metrics">
<div class="metric">
<span class="metric-label">Required gap</span>
<span class="metric-value">2.5 seconds</span>
</div>
<div class="metric">
<span class="metric-label">Next car ETA</span>
<span id="eta" class="metric-value hold">—</span>
</div>
<div class="metric">
<span class="metric-label">Merge box</span>
<span id="merge-state" class="metric-value hold">BUSY</span>
</div>
<div class="metric">
<span class="metric-label">Moving footprints</span>
<span id="footprints" class="metric-value safe">0 overlaps</span>
</div>
</div>
<div class="progress" aria-label="Entry progress">
<div id="progress-fill"></div>
</div>
<div class="buttons">
<button id="replay" class="primary" type="button">REPLAY</button>
<button id="pause" type="button">PAUSE</button>
<button id="camera-reset" type="button">RESET CAMERA</button>
</div>
</section>
<div id="toy-tag">TOY VEHICLE</div>
<div class="help">Drag to orbit · Scroll to zoom · R to replay</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const LANE_RADIUS = 7.2;
const CIRCULAR_SPEED = 3.0;
const ENTRY_SPEED = 4.2;
const ANGULAR_SPEED = CIRCULAR_SPEED / LANE_RADIUS;
const TARGET_ANGLE = 0.42;
const REQUIRED_GAP_SECONDS = 2.5;
const MERGE_CLEAR_RADIUS = 2.6;
const CAR_WIDTH = 1.35;
const CAR_LENGTH = 2.25;
const FOOTPRINT_MARGIN = 0.08;
const TARGET_X = LANE_RADIUS * Math.sin(TARGET_ANGLE);
const TARGET_Z = -LANE_RADIUS * Math.cos(TARGET_ANGLE);
const TARGET_YAW = Math.atan2(
Math.cos(TARGET_ANGLE),
Math.sin(TARGET_ANGLE)
);
const ui = {
status: document.querySelector("#status"),
statusText: document.querySelector("#status-text"),
eta: document.querySelector("#eta"),
mergeState: document.querySelector("#merge-state"),
footprints: document.querySelector("#footprints"),
progress: document.querySelector("#progress-fill"),
replay: document.querySelector("#replay"),
pause: document.querySelector("#pause"),
cameraReset: document.querySelector("#camera-reset"),
toyTag: document.querySelector("#toy-tag"),
loading: document.querySelector("#loading")
};
// -------------------------------------------------------------------------
// Renderer, scene and lighting
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x9fd3e2);
scene.fog = new THREE.Fog(0x9fd3e2, 43, 82);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
140
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xdff5ff, 0x60724b, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff0cf, 3.1);
sun.position.set(-18, 31, 20);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -31;
sun.shadow.camera.right = 31;
sun.shadow.camera.top = 31;
sun.shadow.camera.bottom = -31;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 75;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9fd7ff, 0.7);
fill.position.set(22, 12, -24);
scene.add(fill);
// -------------------------------------------------------------------------
// Materials and voxel helpers
// -------------------------------------------------------------------------
const material = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.02,
...options
});
const mats = {
grass: material(0x7eae58),
grassLight: material(0x91bd67),
grassDark: material(0x69974b),
road: material(0x45515a),
roadArm: material(0x4b575f),
curb: material(0xe9dfbd),
marking: material(0xf7f0d3),
yellow: material(0xffd84d),
trunk: material(0x795039),
leaves: material(0x3f7d48),
leavesLight: material(0x579b52),
soil: material(0x826346),
dark: material(0x202a31),
glass: material(0x8bc7df, { roughness: 0.28, metalness: 0.12 }),
red: material(0xe55345),
cream: material(0xfff0c9),
blue: material(0x356d9d),
cloud: material(0xf3fbff)
};
function addBox(
width,
height,
depth,
mat,
x = 0,
y = 0,
z = 0,
parent = scene
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
mat
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addInstanceBatch(geometry, mat, transforms) {
const mesh = new THREE.InstancedMesh(
geometry,
mat,
transforms.length
);
const dummy = new THREE.Object3D();
transforms.forEach((t, index) => {
dummy.position.set(t.x, t.y, t.z);
dummy.rotation.set(0, t.yaw || 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Ground and road
// -------------------------------------------------------------------------
addBox(54, 0.55, 54, mats.grass, 0, -0.36, 0);
// Small voxel grass variations.
const grassTransforms = [];
let randomSeed = 8127;
function seededRandom() {
randomSeed =
(randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
for (let i = 0; i < 150; i++) {
const x = (seededRandom() - 0.5) * 51;
const z = (seededRandom() - 0.5) * 51;
const radius = Math.hypot(x, z);
// Keep the central roundabout and road corridors clear.
if (radius < 10.5) continue;
if (
(Math.abs(x) < 3.0 && Math.abs(z) > 8.5) ||
(Math.abs(z) < 3.0 && Math.abs(x) > 8.5)
) continue;
grassTransforms.push({
x,
y: -0.065,
z,
yaw: Math.floor(seededRandom() * 4) * Math.PI / 2
});
}
addInstanceBatch(
new THREE.BoxGeometry(0.35, 0.13, 0.35),
mats.grassLight,
grassTransforms
);
// Pixelated circular roadway.
const ringTransforms = [];
const tileSize = 0.8;
for (let ix = -12; ix < 12; ix++) {
for (let iz = -12; iz < 12; iz++) {
const x = (ix + 0.5) * tileSize;
const z = (iz + 0.5) * tileSize;
const radius = Math.hypot(x, z);
if (radius >= 4.45 && radius <= 9.7) {
ringTransforms.push({ x, y: 0.08, z });
}
}
}
addInstanceBatch(
new THREE.BoxGeometry(0.78, 0.16, 0.78),
mats.road,
ringTransforms
);
// Four approaches made from square asphalt voxels.
const armTransforms = [];
const arms = [
{ dx: 0, dz: -1 },
{ dx: 0, dz: 1 },
{ dx: 1, dz: 0 },
{ dx: -1, dz: 0 }
];
for (const arm of arms) {
for (let row = 0; row < 17; row++) {
for (let column = 0; column < 7; column++) {
const outward = 9.25 + row * 0.8;
const across = (column - 3) * 0.8;
const x =
arm.dx * outward + arm.dz * across;
const z =
arm.dz * outward - arm.dx * across;
armTransforms.push({ x, y: 0.09, z });
}
}
}
addInstanceBatch(
new THREE.BoxGeometry(0.78, 0.17, 0.78),
mats.roadArm,
armTransforms
);
// Raised voxel center island.
const islandTransforms = [];
for (let ix = -5; ix < 5; ix++) {
for (let iz = -5; iz < 5; iz++) {
const x = (ix + 0.5) * 0.8;
const z = (iz + 0.5) * 0.8;
if (Math.hypot(x, z) <= 4.05) {
islandTransforms.push({
x,
y: 0.20,
z,
yaw: ((ix + iz) & 1) * Math.PI / 2
});
}
}
}
addInstanceBatch(
new THREE.BoxGeometry(0.79, 0.40, 0.79),
mats.grassLight,
islandTransforms
);
// Inner curb and outer curb, with openings at the four road entries.
for (let i = 0; i < 78; i++) {
const angle = (i / 78) * Math.PI * 2;
const innerX = 4.35 * Math.sin(angle);
const innerZ = -4.35 * Math.cos(angle);
addBox(
0.45,
0.30,
0.45,
mats.curb,
innerX,
0.20,
innerZ
);
const outerX = 9.78 * Math.sin(angle);
const outerZ = -9.78 * Math.cos(angle);
const atRoadOpening =
Math.abs(outerX) < 1.45 || Math.abs(outerZ) < 1.45;
if (!atRoadOpening) {
addBox(
0.48,
0.28,
0.48,
mats.curb,
outerX,
0.19,
outerZ
);
}
}
// Dashed circular lane divider.
for (let i = 0; i < 25; i++) {
const angle = (i / 25) * Math.PI * 2;
const x = 5.35 * Math.sin(angle);
const z = -5.35 * Math.cos(angle);
const yaw = Math.atan2(Math.cos(angle), Math.sin(angle));
addBox(
0.62,
0.035,
0.13,
mats.marking,
x,
0.185,
z
).rotation.y = yaw;
}
// Stop line on the southern approach.
for (let i = -4; i <= 4; i++) {
addBox(
0.54,
0.045,
0.28,
mats.marking,
i * 0.55,
0.19,
-10.58
);
}
// South approach lane dashes.
for (let z = -13.1; z > -22.5; z -= 2.0) {
addBox(
0.16,
0.04,
0.90,
mats.yellow,
0,
0.19,
z
);
}
// Yield lines on the other entries.
const yieldPositions = [
[0, 10.58, 0],
[10.58, 0, Math.PI / 2],
[0, -10.58, 0],
[-10.58, 0, Math.PI / 2]
];
for (const [x, z, yaw] of yieldPositions) {
const line = addBox(
4.7,
0.04,
0.24,
mats.marking,
x,
0.19,
z
);
line.rotation.y = yaw;
}
// -------------------------------------------------------------------------
// Merge-zone indicator
// -------------------------------------------------------------------------
const mergeMaterial = material(0xffcc45, {
emissive: 0x6d4a00,
emissiveIntensity: 0.55,
transparent: true,
opacity: 0.92
});
const mergePadMaterial = material(0xffcc45, {
emissive: 0x6d4a00,
emissiveIntensity: 0.3,
transparent: true,
opacity: 0.13,
depthWrite: false
});
const mergeMarker = new THREE.Group();
mergeMarker.position.set(TARGET_X, 0, TARGET_Z);
mergeMarker.rotation.y = TARGET_YAW;
scene.add(mergeMarker);
const mergePad = addBox(
1.85,
0.025,
2.95,
mergePadMaterial,
0,
0.205,
0,
mergeMarker
);
mergePad.castShadow = false;
for (const x of [-0.82, 0.82]) {
for (const z of [-1.35, 1.35]) {
addBox(
0.18,
0.09,
0.18,
mergeMaterial,
x,
0.25,
z,
mergeMarker
);
}
}
// -------------------------------------------------------------------------
// Voxel scenery
// -------------------------------------------------------------------------
function addTree(x, z, scale = 1, island = false) {
const group = new THREE.Group();
group.position.set(x, island ? 0.4 : -0.05, z);
group.scale.setScalar(scale);
scene.add(group);
addBox(
0.48,
1.45,
0.48,
mats.trunk,
0,
0.72,
0,
group
);
addBox(
1.55,
1.10,
1.55,
mats.leaves,
0,
1.85,
0,
group
);
addBox(
0.95,
0.90,
0.95,
mats.leavesLight,
-0.55,
2.40,
0.15,
group
);
addBox(
0.90,
0.85,
0.90,
mats.leaves,
0.55,
2.35,
-0.20,
group
);
}
[
[-2.55, -1.65, 0.92],
[2.55, 1.60, 0.90],
[1.50, -2.45, 0.72],
[-18, -18, 1.20],
[18, -18, 1.05],
[-18, 18, 1.10],
[18, 18, 1.25],
[-12.5, 13.5, 0.90],
[13.0, 13.0, 0.92]
].forEach(([x, z, scale]) => addTree(x, z, scale));
// Central monument, entirely block-shaped.
addBox(1.45, 0.35, 1.45, mats.soil, 0, 0.58, 0);
addBox(0.95, 1.15, 0.95, mats.cream, 0, 1.25, 0);
addBox(0.65, 0.65, 0.65, mats.yellow, 0, 2.02, 0);
addBox(0.28, 0.55, 0.28, mats.cream, 0, 2.55, 0);
function addBuilding(x, z, width, depth, height, color) {
const wallMaterial = material(color);
addBox(width, height, depth, wallMaterial, x, height / 2, z);
addBox(
width + 0.35,
0.35,
depth + 0.35,
mats.blue,
x,
height + 0.15,
z
);
const windowMaterial = material(0xffd98b, {
emissive: 0x7d4a12,
emissiveIntensity: 0.35
});
for (let wx = -width / 2 + 0.8; wx < width / 2; wx += 1.35) {
addBox(
0.55,
0.55,
0.06,
windowMaterial,
x + wx,
height * 0.58,
z + depth / 2 + 0.035
);
}
}
addBuilding(-18.3, 13.8, 5.8, 4.3, 4.0, 0xd7835f);
addBuilding(17.6, 13.0, 6.5, 4.5, 5.2, 0x7898b4);
addBuilding(-17.8, -13.6, 6.0, 4.0, 4.8, 0xc5a664);
addBuilding(18.0, -13.0, 5.5, 4.0, 3.8, 0x8f76a5);
function addYieldSign(x, z, yaw = 0) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = yaw;
scene.add(group);
addBox(
0.13,
1.85,
0.13,
mats.dark,
0,
0.9,
0,
group
);
addBox(
0.82,
0.82,
0.13,
mats.red,
0,
1.85,
0,
group
);
// Pixel-like cream yield symbol.
addBox(
0.48,
0.12,
0.15,
mats.cream,
0,
1.97,
0,
group
);
addBox(
0.12,
0.28,
0.15,
mats.cream,
-0.15,
1.79,
0,
group
);
addBox(
0.12,
0.28,
0.15,
mats.cream,
0.15,
1.79,
0,
group
);
}
addYieldSign(3.05, -10.15);
addYieldSign(-3.05, 10.15, Math.PI);
addYieldSign(10.15, 3.05, -Math.PI / 2);
addYieldSign(-10.15, -3.05, Math.PI / 2);
// Cube-shaped street lamps.
function addLamp(x, z, yaw = 0) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = yaw;
scene.add(group);
addBox(
0.15,
3.4,
0.15,
mats.dark,
0,
1.7,
0,
group
);
addBox(
0.18,
0.18,
0.90,
mats.dark,
0,
3.35,
0.35,
group
);
addBox(
0.48,
0.22,
0.48,
mats.cream,
0,
3.17,
0.72,
group
);
}
addLamp(3.25, -15.5);
addLamp(-3.25, -19.0);
addLamp(14.4, 3.25, -Math.PI / 2);
addLamp(-14.4, -3.25, Math.PI / 2);
// Block clouds.
for (const [x, y, z] of [
[-19, 17, -18],
[13, 20, -21],
[24, 16, 9]
]) {
const cloud = new THREE.Group();
cloud.position.set(x, y, z);
scene.add(cloud);
addBox(4.5, 1.1, 1.8, mats.cloud, 0, 0, 0, cloud);
addBox(2.3, 1.5, 1.8, mats.cloud, -0.6, 0.55, 0, cloud);
addBox(2.0, 1.2, 1.8, mats.cloud, 1.0, 0.4, 0, cloud);
}
// -------------------------------------------------------------------------
// Toy cars
// -------------------------------------------------------------------------
function makeCar(color, isToy = false) {
const group = new THREE.Group();
scene.add(group);
const bodyMaterial = material(color, { roughness: 0.62 });
const body = addBox(
CAR_WIDTH,
0.50,
CAR_LENGTH,
bodyMaterial,
0,
0.54,
0,
group
);
body.castShadow = true;
addBox(
1.08,
0.54,
1.06,
bodyMaterial,
0,
1.03,
-0.18,
group
);
addBox(
0.94,
0.32,
0.055,
mats.glass,
0,
1.06,
0.37,
group
);
addBox(
0.94,
0.28,
0.055,
mats.glass,
0,
1.03,
-0.72,
group
);
for (const x of [-0.73, 0.73]) {
for (const z of [-0.72, 0.72]) {
addBox(
0.30,
0.42,
0.48,
mats.dark,
x,
0.34,
z,
group
);
}
}
for (const x of [-0.43, 0.43]) {
addBox(
0.25,
0.20,
0.07,
mats.cream,
x,
0.60,
1.15,
group
);
addBox(
0.23,
0.18,
0.07,
mats.red,
x,
0.58,
-1.15,
group
);
}
if (isToy) {
addBox(
0.72,
0.16,
0.72,
mats.yellow,
0,
1.42,
-0.18,
group
);
addBox(
0.28,
0.06,
0.28,
mats.red,
0,
1.54,
-0.18,
group
);
}
// A subtle, block-shaped ground shadow.
const shadow = addBox(
CAR_WIDTH + 0.20,
0.025,
CAR_LENGTH + 0.20,
new THREE.MeshBasicMaterial({
color: 0x182126,
transparent: true,
opacity: 0.18,
depthWrite: false
}),
0,
0.185,
0,
group
);
shadow.castShadow = false;
shadow.receiveShadow = false;
return group;
}
const circleColors = [
0xe75d50,
0x4d91d9,
0xe9e4d2,
0x48a98d
];
const initialPhases = [
TARGET_ANGLE - 0.78,
TARGET_ANGLE + 0.78,
TARGET_ANGLE + 2.36,
TARGET_ANGLE + 3.93
].map((angle) => THREE.MathUtils.euclideanModulo(angle, Math.PI * 2));
const circleCars = circleColors.map((color, index) => ({
object: makeCar(color),
phase: initialPhases[index],
pose: null
}));
const entryCar = {
object: makeCar(0xffca38, true),
state: "waiting",
distance: 0,
joinTime: 0,
pose: null
};
// -------------------------------------------------------------------------
// Entry path: straight approach, then a smooth voxel-world merge curve
// -------------------------------------------------------------------------
function cubicBezier(p0, p1, p2, p3, t) {
const u = 1 - t;
return {
x:
u * u * u * p0.x +
3 * u * u * t * p1.x +
3 * u * t * t * p2.x +
t * t * t * p3.x,
z:
u * u * u * p0.z +
3 * u * u * t * p1.z +
3 * u * t * t * p2.z +
t * t * t * p3.z
};
}
const pathPoints = [];
for (let i = 0; i <= 18; i++) {
const t = i / 18;
pathPoints.push({
x: 0,
z: THREE.MathUtils.lerp(-12.2, -9.4, t)
});
}
const bezier = {
p0: { x: 0, z: -9.4 },
p1: { x: 0, z: -7.9 },
p2: { x: 1.0, z: -7.35 },
p3: { x: TARGET_X, z: TARGET_Z }
};
for (let i = 1; i <= 48; i++) {
pathPoints.push(
cubicBezier(
bezier.p0,
bezier.p1,
bezier.p2,
bezier.p3,
i / 48
)
);
}
const cumulativeLengths = [0];
for (let i = 1; i < pathPoints.length; i++) {
cumulativeLengths.push(
cumulativeLengths[i - 1] +
Math.hypot(
pathPoints[i].x - pathPoints[i - 1].x,
pathPoints[i].z - pathPoints[i - 1].z
)
);
}
const entryPathLength = cumulativeLengths.at(-1);
function sampleEntryPath(distance) {
const d = THREE.MathUtils.clamp(distance, 0, entryPathLength);
let segment = 0;
while (
segment < cumulativeLengths.length - 2 &&
cumulativeLengths[segment + 1] < d
) {
segment++;
}
const start = pathPoints[segment];
const end = pathPoints[segment + 1];
const segmentLength =
cumulativeLengths[segment + 1] - cumulativeLengths[segment];
const t =
segmentLength === 0
? 0
: (d - cumulativeLengths[segment]) / segmentLength;
const dx = end.x - start.x;
const dz = end.z - start.z;
const length = Math.hypot(dx, dz) || 1;
return {
x: THREE.MathUtils.lerp(start.x, end.x, t),
z: THREE.MathUtils.lerp(start.z, end.z, t),
yaw: Math.atan2(dx / length, dz / length)
};
}
// -------------------------------------------------------------------------
// Oriented-box footprint collision test
// -------------------------------------------------------------------------
function makeFootprint(pose) {
const right = {
x: Math.cos(pose.yaw),
z: -Math.sin(pose.yaw)
};
const forward = {
x: Math.sin(pose.yaw),
z: Math.cos(pose.yaw)
};
return {
x: pose.x,
z: pose.z,
right,
forward,
halfWidth: CAR_WIDTH / 2,
halfLength: CAR_LENGTH / 2
};
}
function dot2(a, b) {
return a.x * b.x + a.z * b.z;
}
function footprintsOverlap(a, b, margin = FOOTPRINT_MARGIN) {
const axes = [
a.right,
a.forward,
b.right,
b.forward
];
const centerDelta = {
x: b.x - a.x,
z: b.z - a.z
};
for (const axis of axes) {
const distance = Math.abs(dot2(centerDelta, axis));
const radiusA =
a.halfWidth * Math.abs(dot2(axis, a.right)) +
a.halfLength * Math.abs(dot2(axis, a.forward));
const radiusB =
b.halfWidth * Math.abs(dot2(axis, b.right)) +
b.halfLength * Math.abs(dot2(axis, b.forward));
if (distance > radiusA + radiusB + margin) {
return false;
}
}
return true;
}
function setPose(object, pose) {
object.position.set(pose.x, 0, pose.z);
object.rotation.y = pose.yaw;
}
function circlePose(car, time) {
const theta = car.phase + ANGULAR_SPEED * time;
const x = LANE_RADIUS * Math.sin(theta);
const z = -LANE_RADIUS * Math.cos(theta);
return {
x,
z,
yaw: Math.atan2(Math.cos(theta), Math.sin(theta))
};
}
// -------------------------------------------------------------------------
// Gap logic and simulation state
// -------------------------------------------------------------------------
let elapsed = 0;
let paused = false;
function getGapInfo() {
let nextArrival = Infinity;
let occupied = false;
for (const car of circleCars) {
const theta =
car.phase + ANGULAR_SPEED * elapsed;
const forwardAngle = THREE.MathUtils.euclideanModulo(
TARGET_ANGLE - theta,
Math.PI * 2
);
const arrival =
(forwardAngle * LANE_RADIUS) / CIRCULAR_SPEED;
nextArrival = Math.min(nextArrival, arrival);
const distanceToMerge = Math.hypot(
car.pose.x - TARGET_X,
car.pose.z - TARGET_Z
);
if (distanceToMerge < MERGE_CLEAR_RADIUS) {
occupied = true;
}
}
const targetFootprint = makeFootprint({
x: TARGET_X,
z: TARGET_Z,
yaw: TARGET_YAW
});
for (const car of circleCars) {
if (
footprintsOverlap(
targetFootprint,
makeFootprint(car.pose),
0
)
) {
occupied = true;
}
}
return {
nextArrival,
occupied,
canEnter:
!occupied &&
nextArrival >= REQUIRED_GAP_SECONDS
};
}
function resetSimulation() {
elapsed = 0;
entryCar.state = "waiting";
entryCar.distance = 0;
entryCar.joinTime = 0;
entryCar.pose = sampleEntryPath(0);
for (const car of circleCars) {
car.pose = circlePose(car, elapsed);
setPose(car.object, car.pose);
}
setPose(entryCar.object, entryCar.pose);
updateHUD(getGapInfo(), countOverlaps());
}
function countOverlaps() {
const cars = [
...circleCars.map((car) => car.pose),
entryCar.pose
].filter(Boolean);
let overlaps = 0;
for (let i = 0; i < cars.length; i++) {
for (let j = i + 1; j < cars.length; j++) {
if (
footprintsOverlap(
makeFootprint(cars[i]),
makeFootprint(cars[j])
)
) {
overlaps++;
}
}
}
return overlaps;
}
function updateSimulation(delta) {
elapsed += delta;
// Update the circular stream first.
for (const car of circleCars) {
car.pose = circlePose(car, elapsed);
setPose(car.object, car.pose);
}
if (entryCar.state === "waiting") {
const gap = getGapInfo();
if (gap.canEnter) {
entryCar.state = "entering";
}
}
if (entryCar.state === "entering") {
const nextDistance = Math.min(
entryPathLength,
entryCar.distance + ENTRY_SPEED * delta
);
const candidate = sampleEntryPath(nextDistance);
const candidateFootprint = makeFootprint(candidate);
// The entering car cannot advance into any circular footprint.
const blocked = circleCars.some((car) =>
footprintsOverlap(
candidateFootprint,
makeFootprint(car.pose)
)
);
if (!blocked) {
entryCar.distance = nextDistance;
entryCar.pose = candidate;
if (entryCar.distance >= entryPathLength - 0.001) {
const finalFootprint = makeFootprint(entryCar.pose);
const finalBlocked = circleCars.some((car) =>
footprintsOverlap(
finalFootprint,
makeFootprint(car.pose)
)
);
if (!finalBlocked) {
entryCar.state = "circle";
entryCar.joinTime = elapsed;
}
}
}
setPose(entryCar.object, entryCar.pose);
}
if (entryCar.state === "circle") {
const theta =
TARGET_ANGLE +
ANGULAR_SPEED * (elapsed - entryCar.joinTime);
entryCar.pose = {
x: LANE_RADIUS * Math.sin(theta),
z: -LANE_RADIUS * Math.cos(theta),
yaw: Math.atan2(Math.cos(theta), Math.sin(theta))
};
setPose(entryCar.object, entryCar.pose);
}
}
// -------------------------------------------------------------------------
// HUD
// -------------------------------------------------------------------------
function updateHUD(gap, overlaps) {
if (entryCar.state === "waiting") {
if (gap.occupied) {
ui.status.dataset.tone = "wait";
ui.statusText.textContent = "WAIT — MERGE BOX OCCUPIED";
} else if (gap.nextArrival < REQUIRED_GAP_SECONDS) {
ui.status.dataset.tone = "wait";
ui.statusText.textContent = "YIELD — CIRCULAR CAR APPROACHING";
} else {
ui.status.dataset.tone = "go";
ui.statusText.textContent = "GAP FOUND — PREPARING TO MERGE";
}
} else if (entryCar.state === "entering") {
ui.status.dataset.tone = "go";
ui.statusText.textContent = "MERGING INTO CIRCULAR STREAM";
} else {
ui.status.dataset.tone = "stream";
ui.statusText.textContent = "CIRCULATING — PRIORITY MAINTAINED";
}
ui.eta.textContent = `${gap.nextArrival.toFixed(1)} s`;
ui.eta.className =
"metric-value " +
(gap.nextArrival >= REQUIRED_GAP_SECONDS && !gap.occupied
? "safe"
: "hold");
ui.mergeState.textContent = gap.occupied ? "BUSY" : "CLEAR";
ui.mergeState.className =
"metric-value " + (gap.occupied ? "hold" : "safe");
ui.footprints.textContent =
overlaps === 0 ? "0 overlaps" : `${overlaps} overlap`;
ui.footprints.className =
"metric-value " + (overlaps === 0 ? "safe" : "hold");
let progress = 0;
if (entryCar.state === "entering") {
progress = entryCar.distance / entryPathLength;
} else if (entryCar.state === "circle") {
progress = 1;
}
ui.progress.style.width = `${progress * 100}%`;
const markerColor = gap.occupied
? 0xff6259
: gap.nextArrival >= REQUIRED_GAP_SECONDS
? 0x70e6a6
: 0xffcc45;
mergeMaterial.color.setHex(markerColor);
mergeMaterial.emissive.setHex(markerColor);
mergeMaterial.emissiveIntensity = gap.occupied ? 0.8 : 0.4;
mergePadMaterial.color.setHex(markerColor);
mergePadMaterial.emissive.setHex(markerColor);
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom and keyboard shortcuts
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0, -0.4),
radius: 37,
azimuth: 0.70,
polar: 0.80
};
function updateCamera() {
const sinPolar = Math.sin(cameraState.polar);
camera.position.set(
cameraState.target.x +
cameraState.radius *
sinPolar *
Math.sin(cameraState.azimuth),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.polar),
cameraState.target.z +
cameraState.radius *
sinPolar *
Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.radius = 37;
cameraState.azimuth = 0.70;
cameraState.polar = 0.80;
updateCamera();
}
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar - dy * 0.005,
0.40,
1.28
);
updateCamera();
});
function stopDragging() {
dragging = false;
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.025,
20,
58
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Buttons and keyboard
// -------------------------------------------------------------------------
ui.replay.addEventListener("click", resetSimulation);
ui.pause.addEventListener("click", () => {
paused = !paused;
ui.pause.textContent = paused ? "RESUME" : "PAUSE";
});
ui.cameraReset.addEventListener("click", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") {
resetSimulation();
}
});
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const projectedTag = new THREE.Vector3();
let firstFrame = true;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (!paused) {
updateSimulation(delta);
}
const gap = getGapInfo();
const overlaps = countOverlaps();
updateHUD(gap, overlaps);
// Project the toy label above the vehicle.
projectedTag.set(
entryCar.object.position.x,
2.55,
entryCar.object.position.z
);
projectedTag.project(camera);
const visible =
projectedTag.z > -1 &&
projectedTag.z < 1 &&
Math.abs(projectedTag.x) < 1.15 &&
Math.abs(projectedTag.y) < 1.15;
ui.toyTag.style.display = visible ? "block" : "none";
if (visible) {
ui.toyTag.style.left =
`${(projectedTag.x * 0.5 + 0.5) * innerWidth}px`;
ui.toyTag.style.top =
`${(-projectedTag.y * 0.5 + 0.5) * innerHeight}px`;
ui.toyTag.textContent =
entryCar.state === "circle"
? "TOY • CIRCULATING"
: entryCar.state === "entering"
? "TOY • MERGING"
: "TOY • WAITING";
}
renderer.render(scene, camera);
if (firstFrame) {
firstFrame = false;
ui.loading.remove();
}
}
resetCamera();
resetSimulation();
animate();
</script>
</body>
</html>
```