Prompt specification
Build or customize the Three.js 3D scene "Tram Passes a Tight Street Corner" 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: Tram Passes a Tight Street Corner
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/tram-passes-a-tight-street-corner-x2146
Scene Description Prompt:
Create a standalone cutaway scene in one HTML file using Three.js from cdnjs. Animate a slow tram turn with nearby fixed clearance markers. Detect body-footprint conflicts and keep wheel or bogie positions consistent with the track.
Working Three.js Starter (tram-passes-a-tight-street-corner-x2146):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cutaway Tram Clearance Monitor</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(10, 17, 26, 0.88);
--border: rgba(148, 180, 205, 0.22);
--text: #eaf4ff;
--muted: #91a7b8;
--green: #52e5ad;
--amber: #ffbd59;
--red: #ff426c;
--cyan: #65d8ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #091018;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 2;
}
.panel {
position: absolute;
top: 18px;
left: 18px;
width: min(360px, calc(100vw - 36px));
padding: 17px;
border: 1px solid var(--border);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(14px);
pointer-events: auto;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 4px;
font-size: 21px;
line-height: 1.15;
letter-spacing: -0.03em;
}
.subtitle {
margin: 0 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.status {
display: flex;
align-items: center;
gap: 9px;
min-height: 42px;
padding: 10px 12px;
border: 1px solid rgba(82, 229, 173, 0.3);
border-radius: 10px;
background: rgba(82, 229, 173, 0.08);
color: var(--green);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.05em;
}
.status.conflict {
border-color: rgba(255, 66, 108, 0.48);
background: rgba(255, 66, 108, 0.1);
color: var(--red);
}
.status-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: 8px;
margin-top: 11px;
}
.metric {
padding: 9px 10px;
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 3px;
font-size: 13px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 13px;
}
button,
.toggle {
appearance: none;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 700;
padding: 8px 10px;
cursor: pointer;
}
button:hover,
.toggle:hover {
border-color: rgba(101, 216, 255, 0.65);
background: rgba(101, 216, 255, 0.1);
}
.toggle {
display: inline-flex;
align-items: center;
gap: 7px;
user-select: none;
}
input[type="checkbox"] {
accent-color: var(--cyan);
}
.speed-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 9px;
margin-top: 13px;
color: var(--muted);
font-size: 11px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
}
.legend {
position: absolute;
right: 18px;
bottom: 18px;
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
color: var(--muted);
font-size: 11px;
line-height: 1.7;
backdrop-filter: blur(12px);
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 18px;
height: 3px;
border-radius: 3px;
background: var(--green);
box-shadow: 0 0 8px currentColor;
}
.swatch.amber {
background: var(--amber);
}
.swatch.red {
background: var(--red);
}
#cameraHint {
position: absolute;
left: 18px;
bottom: 18px;
max-width: 360px;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--panel);
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
@media (max-width: 700px) {
.panel {
top: 10px;
left: 10px;
width: min(330px, calc(100vw - 20px));
padding: 13px;
}
.legend {
right: 10px;
bottom: 10px;
}
#cameraHint {
display: none;
}
}
</style>
</head>
<body>
<div id="hud">
<section class="panel">
<div class="eyebrow">Track Geometry / Clearance Lab</div>
<h1>Cutaway Tram Turn Monitor</h1>
<p class="subtitle">
A slow closed-loop turn with track-aligned bogies and fixed survey markers.
Red marker footprints indicate overlap with the tram body envelope.
</p>
<div id="status" class="status">
<span class="status-dot"></span>
<span id="statusText">CLEAR — NO BODY CONFLICTS</span>
</div>
<div class="metrics">
<div class="metric">
<span>Vehicle speed</span>
<strong id="speedMetric">0.55 m/s</strong>
</div>
<div class="metric">
<span>Track gauge</span>
<strong>1.435 m</strong>
</div>
<div class="metric">
<span>Body footprint</span>
<strong>6.50 × 2.24 m</strong>
</div>
<div class="metric">
<span>Active conflicts</span>
<strong id="conflictMetric">0</strong>
</div>
</div>
<div class="speed-row">
<span>Speed</span>
<input id="speed" type="range" min="0.2" max="1.4" step="0.05" value="0.55">
<span id="speedValue">0.55</span>
</div>
<div class="controls">
<button id="playButton">Pause</button>
<button id="focusButton">Focus tram</button>
<button id="overviewButton">Overview</button>
<label class="toggle">
<input id="follow" type="checkbox">
Follow
</label>
<label class="toggle">
<input id="footprint" type="checkbox" checked>
Footprint
</label>
</div>
</section>
<div id="cameraHint">
Drag to orbit · Wheel to zoom · Right-drag or Shift-drag to pan ·
Double-click to focus the tram
</div>
<div class="legend">
<div class="legend-row">
<span class="swatch"></span>
Clear body-footprint envelope
</div>
<div class="legend-row">
<span class="swatch amber"></span>
Fixed clearance marker
</div>
<div class="legend-row">
<span class="swatch red"></span>
Detected footprint conflict
</div>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene and camera
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x091018);
scene.fog = new THREE.Fog(0x091018, 30, 85);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
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.15;
document.body.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb9ddff, 0x17202a, 1.8);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.2);
sun.position.set(12, 24, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -28;
sun.shadow.camera.right = 28;
sun.shadow.camera.top = 28;
sun.shadow.camera.bottom = -28;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 70;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x54c8ff, 1.2);
rim.position.set(-12, 8, -14);
scene.add(rim);
// -------------------------------------------------------------------------
// Track geometry
// -------------------------------------------------------------------------
const PATH_Y = 0.12;
const GAUGE = 1.435;
const RAIL_OFFSET = GAUGE / 2;
const RAIL_RADIUS = 0.045;
const RAIL_TOP = PATH_Y + RAIL_RADIUS;
const WHEEL_RADIUS = 0.31;
const AXLE_Y = RAIL_TOP + WHEEL_RADIUS;
const routePoints = [
new THREE.Vector3(-10, PATH_Y, -4),
new THREE.Vector3(-4, PATH_Y, -9),
new THREE.Vector3(5, PATH_Y, -8),
new THREE.Vector3(10, PATH_Y, -2),
new THREE.Vector3(9, PATH_Y, 5),
new THREE.Vector3(3, PATH_Y, 10),
new THREE.Vector3(-6, PATH_Y, 8),
new THREE.Vector3(-10, PATH_Y, 3)
];
const route = new THREE.CatmullRomCurve3(
routePoints,
true,
"centripetal",
0.5
);
route.arcLengthDivisions = 1600;
route.updateArcLengths();
const routeLength = route.getLength();
const UP = new THREE.Vector3(0, 1, 0);
function wrapDistance(distance) {
return ((distance % routeLength) + routeLength) % routeLength;
}
function sampleRoute(distance) {
const u = wrapDistance(distance) / routeLength;
const point = route.getPointAt(u);
const tangent = route.getTangentAt(u).normalize();
const right = new THREE.Vector3()
.crossVectors(UP, tangent)
.normalize();
return { point, tangent, right };
}
function yawFromDirection(direction) {
// Local +Z is forward.
return Math.atan2(direction.x, direction.z);
}
class OffsetRouteCurve extends THREE.Curve {
constructor(baseCurve, offset) {
super();
this.baseCurve = baseCurve;
this.offset = offset;
this.closed = true;
}
getPoint(t, target = new THREE.Vector3()) {
const point = this.baseCurve.getPointAt(t);
const tangent = this.baseCurve.getTangentAt(t).normalize();
const right = new THREE.Vector3().crossVectors(UP, tangent);
return target.set(
point.x + right.x * this.offset,
point.y,
point.z + right.z * this.offset
);
}
}
// Ground and grid.
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({
color: 0x0b141c,
roughness: 0.95,
metalness: 0.05
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.025;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(80, 40, 0x355064, 0x1b2b37);
grid.position.y = 0.005;
grid.material.transparent = true;
grid.material.opacity = 0.28;
grid.material.depthWrite = false;
scene.add(grid);
// A ribbon under the track.
function createRoadbed() {
const segments = 320;
const positions = [];
const indices = [];
const halfWidth = 2.25;
for (let i = 0; i <= segments; i++) {
const u = i / segments;
const point = route.getPointAt(u);
const tangent = route.getTangentAt(u).normalize();
const right = new THREE.Vector3().crossVectors(UP, tangent);
for (const side of [-1, 1]) {
positions.push(
point.x + right.x * halfWidth * side,
0.018,
point.z + right.z * halfWidth * side
);
}
if (i < segments) {
const a = i * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: 0x26323a,
roughness: 0.92,
metalness: 0.12,
side: THREE.DoubleSide
})
);
mesh.receiveShadow = true;
return mesh;
}
scene.add(createRoadbed());
// Rails.
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x9aabb7,
roughness: 0.26,
metalness: 0.88
});
for (const offset of [-RAIL_OFFSET, RAIL_OFFSET]) {
const railCurve = new OffsetRouteCurve(route, offset);
const rail = new THREE.Mesh(
new THREE.TubeGeometry(railCurve, 420, RAIL_RADIUS, 8, true),
railMaterial
);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
}
// Sleepers.
const sleeperMaterial = new THREE.MeshStandardMaterial({
color: 0x4c4b45,
roughness: 0.9,
metalness: 0.08
});
const sleeperGeometry = new THREE.BoxGeometry(2.35, 0.11, 0.23);
for (let distance = 0; distance < routeLength; distance += 0.82) {
const sample = sampleRoute(distance);
const sleeper = new THREE.Mesh(sleeperGeometry, sleeperMaterial);
sleeper.position.set(sample.point.x, 0.072, sample.point.z);
sleeper.rotation.y = yawFromDirection(sample.tangent);
sleeper.castShadow = true;
sleeper.receiveShadow = true;
scene.add(sleeper);
}
// -------------------------------------------------------------------------
// Fixed clearance markers
// -------------------------------------------------------------------------
function createMarkerLabel(text) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 64;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(8, 15, 23, 0.92)";
context.fillRect(0, 0, 128, 64);
context.strokeStyle = "rgba(255, 189, 89, 0.9)";
context.lineWidth = 4;
context.strokeRect(2, 2, 124, 60);
context.fillStyle = "#ffffff";
context.font = "bold 31px sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 64, 34);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(0.86, 0.43, 1);
return sprite;
}
const markers = [];
const markerCount = 16;
for (let i = 0; i < markerCount; i++) {
const station =
wrapDistance((i / markerCount) * routeLength + 1.2);
const sample = sampleRoute(station);
// Most markers sit outside the body envelope. Two intentionally sit
// within it to demonstrate live conflict detection.
let offset = i % 2 === 0 ? 1.58 : -1.58;
if (i === 3) offset = -0.88;
if (i === 10) offset = 0.88;
const position = sample.point
.clone()
.addScaledVector(sample.right, offset);
const group = new THREE.Group();
group.position.copy(position);
group.rotation.y = yawFromDirection(sample.tangent);
scene.add(group);
const material = new THREE.MeshStandardMaterial({
color: 0xffbd59,
emissive: 0x5d2d00,
emissiveIntensity: 0.3,
roughness: 0.48,
metalness: 0.25
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(0.43, 0.13, 0.43),
material
);
base.position.y = 0.065;
base.castShadow = true;
group.add(base);
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.036, 0.045, 1.13, 10),
material
);
post.position.y = 0.63;
post.castShadow = true;
group.add(post);
const cap = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.16, 0.34),
material
);
cap.position.y = 1.25;
cap.castShadow = true;
group.add(cap);
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.2, 0.31, 32),
new THREE.MeshBasicMaterial({
color: 0xffbd59,
transparent: true,
opacity: 0.78,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.135;
group.add(ring);
const label = createMarkerLabel(String(i + 1).padStart(2, "0"));
label.position.set(0, 1.72, 0);
group.add(label);
const marker = {
id: `M-${String(i + 1).padStart(2, "0")}`,
group,
material,
ring,
station,
position,
tangent: sample.tangent.clone(),
right: sample.right.clone(),
active: false,
penetration: 0,
obb: {
center: new THREE.Vector2(position.x, position.z),
u: new THREE.Vector2(sample.tangent.x, sample.tangent.z),
v: new THREE.Vector2(sample.right.x, sample.right.z),
hu: 0.24,
hv: 0.24
}
};
markers.push(marker);
}
// -------------------------------------------------------------------------
// Tram cutaway model
// -------------------------------------------------------------------------
const bodyGroup = new THREE.Group();
scene.add(bodyGroup);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x1d9fb8,
roughness: 0.36,
metalness: 0.52
});
const darkMetal = new THREE.MeshStandardMaterial({
color: 0x26333c,
roughness: 0.45,
metalness: 0.75
});
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x1b2932,
roughness: 0.7,
metalness: 0.25
});
const glassMaterial = new THREE.MeshPhysicalMaterial({
color: 0x8ddfff,
roughness: 0.08,
metalness: 0.02,
transparent: true,
opacity: 0.2,
transmission: 0.15,
side: THREE.DoubleSide,
depthWrite: false
});
const roofGhostMaterial = new THREE.MeshBasicMaterial({
color: 0x75d8f3,
transparent: true,
opacity: 0.08,
side: THREE.DoubleSide,
depthWrite: false
});
const interiorMaterial = new THREE.MeshStandardMaterial({
color: 0xf1b75c,
roughness: 0.58,
metalness: 0.18
});
const seatMaterial = new THREE.MeshStandardMaterial({
color: 0x3276a8,
roughness: 0.74,
metalness: 0.05
});
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;
}
// Main chassis and floor.
addBox(
bodyGroup,
new THREE.Vector3(2.22, 0.23, 4.55),
new THREE.Vector3(0, 0.77, 0),
darkMetal
);
addBox(
bodyGroup,
new THREE.Vector3(2.20, 0.08, 4.52),
new THREE.Vector3(0, 0.93, 0),
floorMaterial
);
// Nose and tail lower shells.
addBox(
bodyGroup,
new THREE.Vector3(1.76, 0.53, 1.36),
new THREE.Vector3(0, 1.04, 2.70),
bodyMaterial
);
addBox(
bodyGroup,
new THREE.Vector3(1.76, 0.53, 1.36),
new THREE.Vector3(0, 1.04, -2.70),
bodyMaterial
);
// Far side wall remains visible; near side is intentionally cut away.
addBox(
bodyGroup,
new THREE.Vector3(0.055, 1.12, 4.52),
new THREE.Vector3(-1.10, 1.67, 0),
glassMaterial,
false
);
addBox(
bodyGroup,
new THREE.Vector3(0.07, 0.22, 4.52),
new THREE.Vector3(1.10, 1.01, 0),
bodyMaterial
);
// End glazing.
addBox(
bodyGroup,
new THREE.Vector3(1.66, 1.05, 0.055),
new THREE.Vector3(0, 1.78, 3.34),
glassMaterial,
false
);
addBox(
bodyGroup,
new THREE.Vector3(1.66, 1.05, 0.055),
new THREE.Vector3(0, 1.78, -3.34),
glassMaterial,
false
);
// Ghosted roof exposes the interior.
addBox(
bodyGroup,
new THREE.Vector3(2.28, 0.055, 4.62),
new THREE.Vector3(0, 2.75, 0),
roofGhostMaterial,
false
);
// Roof rails / cutaway edge.
addBox(
bodyGroup,
new THREE.Vector3(0.065, 0.065, 4.62),
new THREE.Vector3(-1.12, 2.74, 0),
bodyMaterial
);
addBox(
bodyGroup,
new THREE.Vector3(0.065, 0.065, 4.62),
new THREE.Vector3(1.12, 2.74, 0),
bodyMaterial
);
// Interior seats.
for (const z of [-1.35, -0.45, 0.45]) {
for (const x of [-0.67, 0.67]) {
addBox(
bodyGroup,
new THREE.Vector3(0.54, 0.11, 0.48),
new THREE.Vector3(x, 1.12, z),
seatMaterial
);
addBox(
bodyGroup,
new THREE.Vector3(0.54, 0.48, 0.1),
new THREE.Vector3(x, 1.37, z - 0.19),
seatMaterial
);
}
}
// Stanchions.
for (const z of [-1.75, -0.85, 0.05, 0.95]) {
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.025, 1.62, 8),
interiorMaterial
);
pole.position.set(-0.02, 1.76, z);
bodyGroup.add(pole);
}
// Driver console.
addBox(
bodyGroup,
new THREE.Vector3(1.35, 0.48, 0.45),
new THREE.Vector3(0, 1.20, 1.65),
darkMetal
);
const consoleTop = new THREE.Mesh(
new THREE.BoxGeometry(1.16, 0.035, 0.34),
new THREE.MeshBasicMaterial({ color: 0x43d4ff })
);
consoleTop.position.set(0, 1.46, 1.64);
bodyGroup.add(consoleTop);
// Headlights.
const lampMaterial = new THREE.MeshBasicMaterial({
color: 0xeafaff
});
for (const x of [-0.54, 0.54]) {
const lamp = new THREE.Mesh(
new THREE.CylinderGeometry(0.085, 0.085, 0.055, 16),
lampMaterial
);
lamp.rotation.x = Math.PI / 2;
lamp.position.set(x, 1.08, 3.40);
bodyGroup.add(lamp);
}
// -------------------------------------------------------------------------
// Bogies and wheelsets
// -------------------------------------------------------------------------
function createWheel() {
const spinGroup = new THREE.Group();
const tire = new THREE.Mesh(
new THREE.CylinderGeometry(
WHEEL_RADIUS,
WHEEL_RADIUS,
0.17,
24
),
new THREE.MeshStandardMaterial({
color: 0x151b20,
roughness: 0.7,
metalness: 0.65
})
);
// Default cylinder axis is Y; rotate it so its axis is local X.
tire.rotation.z = Math.PI / 2;
tire.castShadow = true;
spinGroup.add(tire);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.19, 16),
new THREE.MeshStandardMaterial({
color: 0x7c929f,
roughness: 0.34,
metalness: 0.85
})
);
hub.rotation.z = Math.PI / 2;
spinGroup.add(hub);
// Visible spokes make wheel rotation easier to read.
for (let i = 0; i < 3; i++) {
const spoke = new THREE.Mesh(
new THREE.BoxGeometry(0.205, 0.025, 0.47),
new THREE.MeshStandardMaterial({
color: 0xb5c7cf,
roughness: 0.35,
metalness: 0.8
})
);
spoke.rotation.x = (i / 3) * Math.PI;
spinGroup.add(spoke);
}
return spinGroup;
}
function createAxle() {
const group = new THREE.Group();
const wheels = [];
const axle = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.055, GAUGE, 12),
new THREE.MeshStandardMaterial({
color: 0x84939d,
roughness: 0.3,
metalness: 0.9
})
);
axle.rotation.z = Math.PI / 2;
group.add(axle);
for (const side of [-1, 1]) {
const wheel = createWheel();
wheel.position.x = side * RAIL_OFFSET;
group.add(wheel);
wheels.push(wheel);
}
return { group, wheels };
}
function createBogie() {
const group = new THREE.Group();
scene.add(group);
addBox(
group,
new THREE.Vector3(1.72, 0.16, 1.40),
new THREE.Vector3(0, 0.48, 0),
darkMetal
);
addBox(
group,
new THREE.Vector3(0.82, 0.13, 1.52),
new THREE.Vector3(0, 0.61, 0),
new THREE.MeshStandardMaterial({
color: 0x526675,
roughness: 0.4,
metalness: 0.72
})
);
const front = createAxle();
const rear = createAxle();
group.add(front.group, rear.group);
return { group, front, rear };
}
const frontBogie = createBogie();
const rearBogie = createBogie();
const BOGIE_SPACING = 3.55;
const AXLE_HALF_SPACING = 0.58;
function computeBogieState(centerStation) {
const frontSample = sampleRoute(centerStation + AXLE_HALF_SPACING);
const rearSample = sampleRoute(centerStation - AXLE_HALF_SPACING);
const center = frontSample.point
.clone()
.add(rearSample.point)
.multiplyScalar(0.5);
const forward = frontSample.point
.clone()
.sub(rearSample.point)
.normalize();
const right = new THREE.Vector3().crossVectors(UP, forward);
return {
center,
forward,
right,
yaw: yawFromDirection(forward),
axles: [
{
position: rearSample.point,
tangent: rearSample.tangent,
yaw: yawFromDirection(rearSample.tangent)
},
{
position: frontSample.point,
tangent: frontSample.tangent,
yaw: yawFromDirection(frontSample.tangent)
}
]
};
}
function updateBogie(bogie, state) {
bogie.group.position.set(state.center.x, 0, state.center.z);
bogie.group.rotation.y = state.yaw;
const axleObjects = [bogie.rear, bogie.front];
for (let i = 0; i < 2; i++) {
const axleState = state.axles[i];
const axleObject = axleObjects[i];
const difference = axleState.position
.clone()
.sub(state.center);
const localX = difference.dot(state.right);
const localZ = difference.dot(state.forward);
axleObject.group.position.set(localX, AXLE_Y, localZ);
axleObject.group.rotation.y = axleState.yaw - state.yaw;
}
}
// -------------------------------------------------------------------------
// Body footprint: three oriented rectangles matching the visible body
// -------------------------------------------------------------------------
const bodyParts = [];
function createBodyPart(name, halfU, halfV, localZ) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(12), 3)
);
const material = new THREE.LineBasicMaterial({
color: 0x52e5ad,
transparent: true,
opacity: 0.95,
depthTest: false
});
const line = new THREE.LineLoop(geometry, material);
line.renderOrder = 10;
scene.add(line);
const part = {
name,
halfU,
halfV,
localZ,
line,
conflict: false,
obb: {
center: new THREE.Vector2(),
u: new THREE.Vector2(0, 1),
v: new THREE.Vector2(1, 0),
hu: halfU,
hv: halfV
}
};
bodyParts.push(part);
return part;
}
createBodyPart("center", 2.26, 1.12, 0);
createBodyPart("nose", 0.55, 0.88, 2.70);
createBodyPart("tail", 0.55, 0.88, -2.70);
function updateBodyPart(part, bodyCenter, forward, right) {
const center = bodyCenter
.clone()
.addScaledVector(forward, part.localZ);
part.obb.center.set(center.x, center.z);
part.obb.u.set(forward.x, forward.z);
part.obb.v.set(right.x, right.z);
const corners = [
center.clone()
.addScaledVector(forward, -part.halfU)
.addScaledVector(right, -part.halfV),
center.clone()
.addScaledVector(forward, part.halfU)
.addScaledVector(right, -part.halfV),
center.clone()
.addScaledVector(forward, part.halfU)
.addScaledVector(right, part.halfV),
center.clone()
.addScaledVector(forward, -part.halfU)
.addScaledVector(right, part.halfV)
];
const attribute = part.line.geometry.attributes.position;
for (let i = 0; i < 4; i++) {
attribute.setXYZ(
i,
corners[i].x,
0.175,
corners[i].z
);
}
attribute.needsUpdate = true;
}
// -------------------------------------------------------------------------
// 2D oriented bounding-box SAT
// -------------------------------------------------------------------------
function obbOverlap(a, b) {
const delta = new THREE.Vector2().subVectors(b.center, a.center);
const axes = [a.u, a.v, b.u, b.v];
let minimumPenetration = Infinity;
for (const axis of axes) {
const distance = Math.abs(delta.dot(axis));
const radiusA =
a.hu * Math.abs(axis.dot(a.u)) +
a.hv * Math.abs(axis.dot(a.v));
const radiusB =
b.hu * Math.abs(axis.dot(b.u)) +
b.hv * Math.abs(axis.dot(b.v));
const overlap = radiusA + radiusB - distance;
if (overlap <= 0) return 0;
minimumPenetration = Math.min(minimumPenetration, overlap);
}
return minimumPenetration;
}
// -------------------------------------------------------------------------
// Custom orbit / pan / zoom camera
// -------------------------------------------------------------------------
const orbit = {
target: new THREE.Vector3(0, 0.9, 0),
radius: 26,
theta: 0.72,
phi: 0.96
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
let dragging = false;
let panning = false;
let lastX = 0;
let lastY = 0;
let pointerId = null;
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
panning = event.button === 2 || event.shiftKey;
pointerId = event.pointerId;
lastX = event.clientX;
lastY = event.clientY;
renderer.domElement.setPointerCapture(pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
if (panning) {
const scale = orbit.radius * 0.0015;
const right = new THREE.Vector3(
Math.cos(orbit.theta),
0,
-Math.sin(orbit.theta)
);
const forward = new THREE.Vector3(
Math.sin(orbit.theta),
0,
Math.cos(orbit.theta)
);
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(forward, -dy * scale);
} else {
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi + dy * 0.005,
0.16,
Math.PI / 2.03
);
}
});
function endPointer(event) {
dragging = false;
panning = false;
if (pointerId !== null) {
if (renderer.domElement.hasPointerCapture(pointerId)) {
renderer.domElement.releasePointerCapture(pointerId);
}
pointerId = null;
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
5,
55
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
focusTram();
});
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const statusElement = document.getElementById("status");
const statusTextElement = document.getElementById("statusText");
const conflictMetric = document.getElementById("conflictMetric");
const speedInput = document.getElementById("speed");
const speedValue = document.getElementById("speedValue");
const speedMetric = document.getElementById("speedMetric");
const playButton = document.getElementById("playButton");
const followInput = document.getElementById("follow");
const footprintInput = document.getElementById("footprint");
let speed = Number(speedInput.value);
let playing = true;
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedValue.textContent = speed.toFixed(2);
speedMetric.textContent = `${speed.toFixed(2)} m/s`;
});
playButton.addEventListener("click", () => {
playing = !playing;
playButton.textContent = playing ? "Pause" : "Play";
});
footprintInput.addEventListener("change", () => {
for (const part of bodyParts) {
part.line.visible = footprintInput.checked;
}
});
function focusTram() {
orbit.radius = 12;
orbit.phi = 0.91;
followInput.checked = true;
}
document.getElementById("focusButton").addEventListener("click", focusTram);
document.getElementById("overviewButton").addEventListener("click", () => {
orbit.target.set(0, 0.9, 0);
orbit.radius = 26;
orbit.theta = 0.72;
orbit.phi = 0.96;
followInput.checked = false;
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let bodyStation = 7.0;
let wheelRotation = 0;
let lastHUDState = "";
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const traveled = playing ? speed * dt : 0;
bodyStation = wrapDistance(bodyStation + traveled);
wheelRotation += traveled / WHEEL_RADIUS;
const frontState = computeBogieState(
bodyStation + BOGIE_SPACING / 2
);
const rearState = computeBogieState(
bodyStation - BOGIE_SPACING / 2
);
updateBogie(frontBogie, frontState);
updateBogie(rearBogie, rearState);
const bodyCenter = frontState.center
.clone()
.add(rearState.center)
.multiplyScalar(0.5);
const bodyForward = frontState.center
.clone()
.sub(rearState.center)
.normalize();
const bodyRight = new THREE.Vector3()
.crossVectors(UP, bodyForward)
.normalize();
bodyGroup.position.set(bodyCenter.x, 0, bodyCenter.z);
bodyGroup.rotation.y = yawFromDirection(bodyForward);
for (const bogie of [frontBogie, rearBogie]) {
for (const axle of [bogie.front, bogie.rear]) {
for (const wheel of axle.wheels) {
wheel.rotation.x = wheelRotation;
}
}
}
for (const part of bodyParts) {
updateBodyPart(part, bodyCenter, bodyForward, bodyRight);
}
// Detect every fixed marker against every body footprint rectangle.
const conflicts = [];
for (const marker of markers) {
marker.active = false;
marker.penetration = 0;
for (const part of bodyParts) {
const penetration = obbOverlap(part.obb, marker.obb);
if (penetration > 0) {
part.conflict = true;
marker.active = true;
marker.penetration = Math.max(
marker.penetration,
penetration
);
}
}
const color = marker.active ? 0xff426c : 0xffbd59;
const emissive = marker.active ? 0x8b0826 : 0x5d2d00;
marker.material.color.setHex(color);
marker.material.emissive.setHex(emissive);
marker.material.emissiveIntensity = marker.active ? 1.1 : 0.3;
marker.ring.material.color.setHex(color);
marker.ring.material.opacity = marker.active ? 1 : 0.72;
if (marker.active) {
conflicts.push(marker);
}
}
for (const part of bodyParts) {
part.line.material.color.setHex(
part.conflict ? 0xff426c : 0x52e5ad
);
part.conflict = false;
}
const hudState = conflicts
.map(marker => `${marker.id}:${marker.penetration.toFixed(2)}`)
.join("|");
if (hudState !== lastHUDState) {
lastHUDState = hudState;
conflictMetric.textContent = String(conflicts.length);
if (conflicts.length > 0) {
const largest = Math.max(
...conflicts.map(marker => marker.penetration)
);
statusElement.classList.add("conflict");
statusTextElement.textContent =
`CONFLICT — ${conflicts
.map(marker => marker.id)
.join(", ")} · ${largest.toFixed(2)} m`;
} else {
statusElement.classList.remove("conflict");
statusTextElement.textContent =
"CLEAR — NO BODY CONFLICTS";
}
}
if (followInput.checked) {
const desiredTarget = new THREE.Vector3(
bodyCenter.x,
1.0,
bodyCenter.z
);
orbit.target.lerp(
desiredTarget,
1 - Math.exp(-dt * 4.5)
);
}
updateCamera();
renderer.render(scene, camera);
}
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
updateCamera();
animate();
</script>
</body>
</html>
```