Prompt specification
Build or customize the Three.js 3D scene "Track Block With an Occupancy Marker" 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: Track Block With an Occupancy Marker
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/track-block-with-an-occupancy-marker-x2125
Scene Description Prompt:
I'd like to see this as a stylized Three.js scene: track block with an occupancy marker. Model one short track section with entry and exit markers and a train token. Keep the occupied interval visible even when only part of the train is inside. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (track-block-with-an-occupancy-marker-x2125):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Track Block Occupancy</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(9, 23, 39, 0.82);
--line: rgba(137, 190, 218, 0.2);
--text: #e8f5fb;
--muted: #8da9ba;
--cyan: #4df4d0;
--amber: #ffc857;
--coral: #ff6b62;
}
* {
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;
}
#stage,
#stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
#stage canvas {
display: block;
touch-action: none;
outline: none;
}
.brand,
.telemetry,
.legend,
.hint {
position: absolute;
z-index: 10;
pointer-events: none;
}
.brand {
top: 24px;
left: 26px;
max-width: 360px;
text-shadow: 0 2px 16px rgba(0, 0, 0, 0.65);
}
.eyebrow {
margin-bottom: 8px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 40px);
font-weight: 760;
letter-spacing: -0.035em;
}
.subtitle {
max-width: 330px;
margin: 8px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.telemetry {
top: 24px;
right: 24px;
width: 286px;
padding: 17px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
pointer-events: auto;
}
.telemetry-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.block-id {
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 6px 9px;
border-radius: 999px;
color: var(--cyan);
background: rgba(77, 244, 208, 0.1);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.09em;
white-space: nowrap;
}
.status::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
content: "";
}
.status[data-state="entering"],
.status[data-state="exiting"] {
color: #ffb454;
background: rgba(255, 180, 84, 0.1);
}
.status[data-state="inside"] {
color: #ff6678;
background: rgba(255, 102, 120, 0.1);
}
.metric {
margin-top: 12px;
}
.metric-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 11px;
}
.metric-label strong {
color: var(--text);
font-variant-numeric: tabular-nums;
}
.meter {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
#meter-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #2fcbb0, var(--cyan));
box-shadow: 0 0 14px rgba(77, 244, 208, 0.65);
transition: width 80ms linear;
}
.range {
margin-top: 9px;
color: #6f91a5;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 16px;
}
button {
min-height: 36px;
border: 1px solid rgba(143, 192, 217, 0.2);
border-radius: 10px;
color: var(--text);
background: rgba(255, 255, 255, 0.055);
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition:
border-color 150ms ease,
background 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(77, 244, 208, 0.45);
background: rgba(77, 244, 208, 0.09);
}
button:active {
transform: translateY(1px);
}
.legend {
bottom: 24px;
left: 26px;
display: flex;
flex-wrap: wrap;
gap: 15px;
padding: 11px 14px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(9, 23, 39, 0.7);
color: var(--muted);
font-size: 10px;
backdrop-filter: blur(12px);
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 17px;
height: 4px;
border-radius: 999px;
background: var(--cyan);
box-shadow: 0 0 9px rgba(77, 244, 208, 0.55);
}
.swatch.amber {
background: var(--amber);
box-shadow: 0 0 9px rgba(255, 200, 87, 0.45);
}
.swatch.coral {
background: var(--coral);
box-shadow: 0 0 9px rgba(255, 107, 98, 0.45);
}
.hint {
right: 24px;
bottom: 24px;
color: #6f91a5;
font-size: 10px;
letter-spacing: 0.03em;
}
#loading {
position: absolute;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
color: var(--muted);
background: var(--bg);
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 720px) {
.brand {
top: 17px;
left: 18px;
}
.subtitle {
display: none;
}
.telemetry {
top: auto;
right: 14px;
bottom: 62px;
width: 246px;
padding: 13px;
}
.legend {
left: 14px;
bottom: 14px;
gap: 10px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<header class="brand">
<div class="eyebrow">Rail signal lab</div>
<h1>Track block occupancy</h1>
<p class="subtitle">
The teal segment is the exact intersection between the train and the
protected block, including partial entry and partial exit.
</p>
</header>
<section class="telemetry" aria-label="Block telemetry">
<div class="telemetry-head">
<div class="block-id">Block A-17</div>
<div class="status" id="status" data-state="clear">CLEAR</div>
</div>
<div class="metric">
<div class="metric-label">
<span>Occupied length</span>
<strong id="occupied-length">0.00 m</strong>
</div>
<div class="meter">
<div id="meter-fill"></div>
</div>
<div class="range" id="interval-range">No occupied interval</div>
</div>
<div class="buttons">
<button id="pause-button" type="button">Pause</button>
<button id="reset-button" type="button">Reset train</button>
</div>
</section>
<div class="legend" aria-hidden="true">
<span class="legend-item">
<span class="swatch"></span>
occupied interval
</span>
<span class="legend-item">
<span class="swatch amber"></span>
block boundary
</span>
<span class="legend-item">
<span class="swatch coral"></span>
train token
</span>
</div>
<div class="hint">Drag to orbit · Scroll to zoom · Space to pause</div>
<div id="loading">Loading track scene</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.querySelector("#stage");
const loading = document.querySelector("#loading");
const statusElement = document.querySelector("#status");
const occupiedLengthElement = document.querySelector("#occupied-length");
const meterFill = document.querySelector("#meter-fill");
const intervalRange = document.querySelector("#interval-range");
const pauseButton = document.querySelector("#pause-button");
const resetButton = document.querySelector("#reset-button");
// ---------------------------------------------------------------------
// Scene setup
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 19, 38);
const camera = new THREE.PerspectiveCamera(
39,
innerWidth / innerHeight,
0.1,
80
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional railway track occupancy scene"
);
stage.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb9e8ff, 0x172231, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xe6f6ff, 3.1);
keyLight.position.set(3.5, 11, 7.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 32;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const cyanRim = new THREE.PointLight(0x27d9c2, 14, 18, 2);
cyanRim.position.set(-7, 3.8, -4.5);
scene.add(cyanRim);
const amberRim = new THREE.PointLight(0xffa94d, 9, 15, 2);
amberRim.position.set(7, 3, 5);
scene.add(amberRim);
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.68,
metalness: 0,
...options
});
}
// ---------------------------------------------------------------------
// Diorama and track
// ---------------------------------------------------------------------
const platformMaterial = standardMaterial(0x12263a, {
roughness: 0.86,
metalness: 0.08
});
const platformSideMaterial = standardMaterial(0x091624, {
roughness: 0.8
});
const bedMaterial = standardMaterial(0x182a35, {
roughness: 0.96
});
const sleeperMaterial = standardMaterial(0x70513e, {
roughness: 0.9
});
const sleeperAltMaterial = standardMaterial(0x634938, {
roughness: 0.92
});
const railMaterial = standardMaterial(0xb8cbd5, {
roughness: 0.24,
metalness: 0.78
});
const platform = new THREE.Mesh(
new THREE.BoxGeometry(19.5, 0.42, 5.2),
platformMaterial
);
platform.position.y = -0.46;
platform.receiveShadow = true;
scene.add(platform);
const platformInset = new THREE.Mesh(
new THREE.BoxGeometry(19.1, 0.025, 4.82),
standardMaterial(0x0e2133, { roughness: 0.9 })
);
platformInset.position.y = -0.235;
platformInset.receiveShadow = true;
scene.add(platformInset);
const frontTrim = new THREE.Mesh(
new THREE.BoxGeometry(19.15, 0.055, 0.065),
standardMaterial(0x37d7c2, {
emissive: 0x0f7669,
emissiveIntensity: 1.4,
roughness: 0.35
})
);
frontTrim.position.set(0, -0.205, 2.49);
scene.add(frontTrim);
const grid = new THREE.GridHelper(44, 44, 0x28516b, 0x17354a);
grid.position.y = -0.68;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
const trackBed = new THREE.Mesh(
new THREE.BoxGeometry(18.2, 0.18, 2.08),
bedMaterial
);
trackBed.position.y = -0.14;
trackBed.receiveShadow = true;
scene.add(trackBed);
const sleeperGeometry = new THREE.BoxGeometry(0.18, 0.14, 1.72);
for (let x = -9; x <= 9.001; x += 0.72) {
const sleeper = new THREE.Mesh(
sleeperGeometry,
Math.round(x * 100) % 2 === 0
? sleeperMaterial
: sleeperAltMaterial
);
sleeper.position.set(x, 0.02, 0);
sleeper.castShadow = true;
sleeper.receiveShadow = true;
scene.add(sleeper);
}
for (const z of [-0.43, 0.43]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(18.25, 0.14, 0.1),
railMaterial
);
rail.position.set(0, 0.13, z);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
}
const edgeLampGeometry = new THREE.BoxGeometry(0.18, 0.045, 0.09);
const edgeLampMaterial = standardMaterial(0x57e7d5, {
emissive: 0x1aa996,
emissiveIntensity: 1.7,
roughness: 0.3
});
for (let x = -9; x <= 9.001; x += 1.8) {
const lamp = new THREE.Mesh(edgeLampGeometry, edgeLampMaterial);
lamp.position.set(x, -0.2, 2.49);
scene.add(lamp);
}
// ---------------------------------------------------------------------
// Block, entry/exit markers, and occupancy interval
// ---------------------------------------------------------------------
const BLOCK_MIN = -3.2;
const BLOCK_MAX = 3.2;
const BLOCK_LENGTH = BLOCK_MAX - BLOCK_MIN;
const TRAIN_HALF_LENGTH = 1.48;
const blockZone = new THREE.Mesh(
new THREE.BoxGeometry(BLOCK_LENGTH, 0.035, 1.38),
standardMaterial(0xf2b84b, {
emissive: 0x6d4810,
emissiveIntensity: 0.42,
transparent: true,
opacity: 0.16,
depthWrite: false,
roughness: 0.5
})
);
blockZone.position.y = 0.103;
scene.add(blockZone);
const boundaryMaterial = standardMaterial(0xffc857, {
emissive: 0xb56a09,
emissiveIntensity: 1.35,
roughness: 0.38
});
for (const x of [BLOCK_MIN, BLOCK_MAX]) {
const boundary = new THREE.Mesh(
new THREE.BoxGeometry(0.075, 0.055, 2.18),
boundaryMaterial
);
boundary.position.set(x, 0.135, 0);
scene.add(boundary);
for (const z of [-0.91, 0.91]) {
const corner = new THREE.Mesh(
new THREE.BoxGeometry(0.19, 0.08, 0.17),
boundaryMaterial
);
corner.position.set(x, 0.13, z);
scene.add(corner);
}
}
const signalBulbMaterials = [];
function roundedRectPath(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeLabel(text, accent = "#ffc857", width = 1.5) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRectPath(ctx, 8, 14, 496, 100, 24);
ctx.fillStyle = "rgba(7, 18, 31, 0.92)";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = accent;
ctx.stroke();
ctx.fillStyle = accent;
ctx.font = "800 44px Inter, system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65, 455);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.anisotropy = Math.min(
4,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: true
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width / 4, 1);
return sprite;
}
function createSignal(x, text, accent) {
const signal = new THREE.Group();
signal.position.x = x;
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.18, 0.22, 0.2, 16),
standardMaterial(0x182b39, { roughness: 0.72 })
);
base.position.set(0, -0.12, 1.3);
base.castShadow = true;
signal.add(base);
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.065, 0.075, 1.3, 12),
railMaterial
);
pole.position.set(0, 0.52, 1.3);
pole.castShadow = true;
signal.add(pole);
const housing = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.4, 0.23),
standardMaterial(0x0c1b28, { roughness: 0.55 })
);
housing.position.set(0, 1.17, 1.3);
housing.castShadow = true;
signal.add(housing);
const bulbMaterial = standardMaterial(0x4df4d0, {
emissive: 0x1da88f,
emissiveIntensity: 1.8,
roughness: 0.25
});
const bulb = new THREE.Mesh(
new THREE.SphereGeometry(0.095, 20, 14),
bulbMaterial
);
bulb.position.set(0, 1.17, 1.44);
signal.add(bulb);
signalBulbMaterials.push(bulbMaterial);
const label = makeLabel(text, accent, 1.45);
label.position.set(0, 1.74, 1.3);
signal.add(label);
scene.add(signal);
}
createSignal(BLOCK_MIN, "ENTRY", "#ffc857");
createSignal(BLOCK_MAX, "EXIT", "#ffc857");
const blockLabel = makeLabel("BLOCK A-17", "#8adfff", 2.15);
blockLabel.position.set(0, 0.03, 1.92);
scene.add(blockLabel);
// The occupancy mesh is scaled to the intersection of the train's
// footprint with the block. It remains visible for partial entry/exit.
const occupancyMaterial = standardMaterial(0x4df4d0, {
emissive: 0x18c9aa,
emissiveIntensity: 1.4,
transparent: true,
opacity: 0.64,
depthWrite: false,
roughness: 0.28,
metalness: 0.12
});
const occupancyMesh = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.055, 1.3),
occupancyMaterial
);
occupancyMesh.position.y = 0.132;
occupancyMesh.visible = false;
scene.add(occupancyMesh);
const occupancyCapMaterial = standardMaterial(0x83ffe4, {
emissive: 0x2ddfbd,
emissiveIntensity: 1.9,
transparent: true,
opacity: 0.9,
depthWrite: false,
roughness: 0.25
});
const occupancyCapGeometry = new THREE.BoxGeometry(0.055, 0.09, 1.4);
const occupancyStartCap = new THREE.Mesh(
occupancyCapGeometry,
occupancyCapMaterial
);
const occupancyEndCap = new THREE.Mesh(
occupancyCapGeometry,
occupancyCapMaterial
);
occupancyStartCap.position.y = 0.145;
occupancyEndCap.position.y = 0.145;
occupancyStartCap.visible = false;
occupancyEndCap.visible = false;
scene.add(occupancyStartCap, occupancyEndCap);
const occupiedLabel = makeLabel("OCCUPIED", "#4df4d0", 1.65);
occupiedLabel.position.set(0, 1.48, -1.3);
occupiedLabel.visible = false;
scene.add(occupiedLabel);
// ---------------------------------------------------------------------
// Stylized train token
// ---------------------------------------------------------------------
function roundedPrism(width, height, depth, radius) {
const x = -width / 2;
const y = -height / 2;
const shape = new THREE.Shape();
shape.moveTo(x + radius, y);
shape.lineTo(x + width - radius, y);
shape.quadraticCurveTo(x + width, y, x + width, y + radius);
shape.lineTo(x + width, y + height - radius);
shape.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
shape.lineTo(x + radius, y + height);
shape.quadraticCurveTo(x, y + height, x, y + height - radius);
shape.lineTo(x, y + radius);
shape.quadraticCurveTo(x, y, x + radius, y);
const geometry = new THREE.ExtrudeGeometry(shape, {
depth,
steps: 1,
curveSegments: 8,
bevelEnabled: true,
bevelSegments: 2,
bevelSize: 0.045,
bevelThickness: 0.045
});
geometry.translate(0, 0, -depth / 2);
return geometry;
}
const train = new THREE.Group();
scene.add(train);
const trainBodyMaterial = standardMaterial(0xff6b62, {
roughness: 0.43,
metalness: 0.12
});
const trainDarkMaterial = standardMaterial(0x17232d, {
roughness: 0.58,
metalness: 0.25
});
const trainWindowMaterial = standardMaterial(0x123544, {
emissive: 0x0b4d5a,
emissiveIntensity: 0.52,
roughness: 0.18,
metalness: 0.3
});
const creamMaterial = standardMaterial(0xffe3aa, {
roughness: 0.45
});
const chassis = new THREE.Mesh(
new THREE.BoxGeometry(2.78, 0.18, 1.02),
trainDarkMaterial
);
chassis.position.y = 0.38;
chassis.castShadow = true;
train.add(chassis);
const body = new THREE.Mesh(
roundedPrism(2.56, 0.58, 0.86, 0.16),
trainBodyMaterial
);
body.position.y = 0.73;
body.castShadow = true;
body.receiveShadow = true;
train.add(body);
const roof = new THREE.Mesh(
roundedPrism(2.22, 0.14, 0.82, 0.06),
trainDarkMaterial
);
roof.position.set(-0.05, 1.06, 0);
roof.castShadow = true;
train.add(roof);
const stripeGeometry = new THREE.BoxGeometry(2.27, 0.075, 0.025);
for (const side of [-1, 1]) {
const stripe = new THREE.Mesh(stripeGeometry, creamMaterial);
stripe.position.set(-0.04, 0.59, side * 0.443);
train.add(stripe);
for (const x of [-0.7, -0.12, 0.46]) {
const window = new THREE.Mesh(
new THREE.BoxGeometry(0.43, 0.28, 0.026),
trainWindowMaterial
);
window.position.set(x, 0.79, side * 0.445);
train.add(window);
}
}
const windshield = new THREE.Mesh(
new THREE.BoxGeometry(0.028, 0.3, 0.64),
trainWindowMaterial
);
windshield.position.set(1.31, 0.8, 0);
train.add(windshield);
const rearWindow = new THREE.Mesh(
new THREE.BoxGeometry(0.028, 0.26, 0.59),
trainWindowMaterial
);
rearWindow.position.set(-1.31, 0.79, 0);
train.add(rearWindow);
const wheelGeometry = new THREE.CylinderGeometry(0.19, 0.19, 0.13, 20);
const wheelHubGeometry = new THREE.CylinderGeometry(0.1, 0.1, 0.145, 16);
for (const x of [-0.84, 0.84]) {
for (const z of [-0.49, 0.49]) {
const wheel = new THREE.Mesh(wheelGeometry, trainDarkMaterial);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(x, 0.27, z);
wheel.castShadow = true;
train.add(wheel);
const hub = new THREE.Mesh(wheelHubGeometry, railMaterial);
hub.rotation.x = Math.PI / 2;
hub.position.set(x, 0.27, z);
train.add(hub);
}
}
const frontCoupler = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.11, 0.14),
trainDarkMaterial
);
frontCoupler.position.set(1.43, 0.36, 0);
train.add(frontCoupler);
const headlightMaterial = standardMaterial(0xfff1b8, {
emissive: 0xffc857,
emissiveIntensity: 2.4,
roughness: 0.2
});
for (const z of [-0.23, 0.23]) {
const headlight = new THREE.Mesh(
new THREE.SphereGeometry(0.065, 16, 12),
headlightMaterial
);
headlight.position.set(1.365, 0.57, z);
train.add(headlight);
}
const roofBeacon = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.11, 0.13, 16),
standardMaterial(0xffb454, {
emissive: 0xdc6e12,
emissiveIntensity: 1.3
})
);
roofBeacon.position.set(0.78, 1.19, 0);
train.add(roofBeacon);
const antenna = new THREE.Mesh(
new THREE.CylinderGeometry(0.018, 0.018, 0.42, 8),
trainDarkMaterial
);
antenna.position.set(-0.54, 1.33, 0);
train.add(antenna);
const antennaTop = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.035, 0.035),
trainDarkMaterial
);
antennaTop.position.set(-0.54, 1.52, 0);
train.add(antennaTop);
// ---------------------------------------------------------------------
// Custom camera controls: no external controls module is used.
// ---------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.38, 0);
const initialRadius = innerWidth < 720 ? 22 : 17.8;
const desiredView = {
theta: 0.63,
phi: 1.0,
radius: initialRadius
};
const currentView = {
theta: desiredView.theta,
phi: desiredView.phi,
radius: desiredView.radius
};
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
desiredView.theta -= deltaX * 0.006;
desiredView.phi = THREE.MathUtils.clamp(
desiredView.phi + deltaY * 0.005,
0.38,
1.38
);
});
function stopDragging(event) {
dragging = false;
if (
event &&
renderer.domElement.hasPointerCapture &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredView.radius = THREE.MathUtils.clamp(
desiredView.radius * Math.exp(event.deltaY * 0.001),
8,
29
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
desiredView.theta = 0.63;
desiredView.phi = 1.0;
desiredView.radius = innerWidth < 720 ? 22 : 17.8;
});
function updateCamera(deltaTime) {
const damping = 1 - Math.exp(-10 * deltaTime);
currentView.theta +=
(desiredView.theta - currentView.theta) * damping;
currentView.phi += (desiredView.phi - currentView.phi) * damping;
currentView.radius +=
(desiredView.radius - currentView.radius) * damping;
const sinPhi = Math.sin(currentView.phi);
camera.position.set(
cameraTarget.x +
currentView.radius * sinPhi * Math.sin(currentView.theta),
cameraTarget.y + currentView.radius * Math.cos(currentView.phi),
cameraTarget.z +
currentView.radius * sinPhi * Math.cos(currentView.theta)
);
camera.lookAt(cameraTarget);
}
// ---------------------------------------------------------------------
// Simulation and occupancy calculation
// ---------------------------------------------------------------------
const reducedMotion = matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
let paused = reducedMotion;
let simulationTime = 5.25;
let trainRotation = 0;
function setPaused(value) {
paused = value;
pauseButton.textContent = paused ? "Play" : "Pause";
}
pauseButton.addEventListener("click", () => setPaused(!paused));
resetButton.addEventListener("click", () => {
simulationTime = 5.25;
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
setPaused(!paused);
}
});
function updateTelemetry(state, occupiedLength) {
const metadata = {
clear: { label: "CLEAR", color: "#4df4d0" },
entering: { label: "ENTERING", color: "#ffb454" },
inside: { label: "OCCUPIED", color: "#ff6678" },
exiting: { label: "EXITING", color: "#ffb454" }
}[state];
statusElement.textContent = metadata.label;
statusElement.dataset.state = state;
occupiedLengthElement.textContent = `${occupiedLength.toFixed(2)} m`;
meterFill.style.width = `${(occupiedLength / BLOCK_LENGTH) * 100}%`;
}
function updateOccupancy(trainX, movingRight, elapsedTime) {
const trainRear = trainX - TRAIN_HALF_LENGTH;
const trainFront = trainX + TRAIN_HALF_LENGTH;
// Clip the train footprint to the protected block interval.
const occupiedStart = Math.max(BLOCK_MIN, trainRear);
const occupiedEnd = Math.min(BLOCK_MAX, trainFront);
const occupiedLength = Math.max(0, occupiedEnd - occupiedStart);
const isOccupied = occupiedLength > 0.005;
let state = "clear";
if (isOccupied) {
if (movingRight) {
if (trainFront > BLOCK_MAX) state = "exiting";
else if (trainRear < BLOCK_MIN) state = "entering";
else state = "inside";
} else {
if (trainRear < BLOCK_MIN) state = "exiting";
else if (trainFront > BLOCK_MAX) state = "entering";
else state = "inside";
}
}
occupancyMesh.visible = isOccupied;
occupancyStartCap.visible = isOccupied;
occupancyEndCap.visible = isOccupied;
occupiedLabel.visible = isOccupied;
if (isOccupied) {
const center = (occupiedStart + occupiedEnd) / 2;
occupancyMesh.position.x = center;
occupancyMesh.scale.x = Math.max(0.001, occupiedLength);
occupancyStartCap.position.x = occupiedStart;
occupancyEndCap.position.x = occupiedEnd;
occupiedLabel.position.x = center;
occupancyMaterial.opacity = 0.61 + Math.sin(elapsedTime * 4.2) * 0.055;
occupancyMaterial.emissiveIntensity =
1.35 + Math.sin(elapsedTime * 4.2) * 0.22;
occupancyCapMaterial.emissiveIntensity =
1.85 + Math.sin(elapsedTime * 4.2) * 0.25;
intervalRange.textContent =
`Interval ${(occupiedStart - BLOCK_MIN).toFixed(2)}–` +
`${(occupiedEnd - BLOCK_MIN).toFixed(2)} m from entry`;
} else {
intervalRange.textContent = "No occupied interval";
}
const occupiedColor = state === "inside" ? 0xff6678 : 0xffb454;
for (const material of signalBulbMaterials) {
material.color.setHex(isOccupied ? occupiedColor : 0x4df4d0);
material.emissive.setHex(isOccupied ? occupiedColor : 0x1da88f);
material.emissiveIntensity = isOccupied ? 2.1 : 1.7;
}
blockZone.material.emissive.setHex(
isOccupied ? 0x74402d : 0x6d4810
);
blockZone.material.opacity = isOccupied ? 0.2 : 0.15;
updateTelemetry(state, occupiedLength);
}
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const deltaTime = Math.min(clock.getDelta(), 0.05);
elapsed += deltaTime;
if (!paused) {
simulationTime += deltaTime;
}
// A smooth shuttle motion keeps the token inside the diorama.
const phase = (Math.PI * simulationTime) / 16;
const pathProgress = 0.5 - 0.5 * Math.cos(phase);
const trainX = -8.4 + 16.8 * pathProgress;
const movingRight = Math.sin(phase) >= 0;
train.position.x = trainX;
const targetRotation = movingRight ? 0 : Math.PI;
const rotationDelta = Math.atan2(
Math.sin(targetRotation - trainRotation),
Math.cos(targetRotation - trainRotation)
);
trainRotation += rotationDelta * (1 - Math.exp(-8 * deltaTime));
train.rotation.y = trainRotation;
updateOccupancy(trainX, movingRight, elapsed);
updateCamera(deltaTime);
renderer.render(scene, camera);
}
setPaused(paused);
loading.remove();
animate();
</script>
</body>
</html>
```