Prompt specification
Build or customize the Three.js 3D scene "Articulated Tram on a Curved Centerline" 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: Articulated Tram on a Curved Centerline
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/articulated-tram-on-a-curved-centerline-x2145
Scene Description Prompt:
I'd like to see this as a low-poly Three.js scene: articulated tram on a curved centerline. Model a simple articulated tram following a curved track centerline. Show body overhang and joint angles rather than treating the vehicle as a point. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (articulated-tram-on-a-curved-centerline-x2145):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Articulated Tram — Curved Track Kinematics</title>
<style>
:root {
--ink: #17272d;
--muted: #60757b;
--paper: rgba(247, 244, 232, 0.91);
--line: rgba(23, 39, 45, 0.14);
--orange: #e56b3f;
--teal: #159c91;
--cyan: #23b9c5;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #cbd9d2;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app, #app canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
#labels {
position: fixed;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.joint-label {
position: absolute;
padding: 6px 9px;
border: 1px solid rgba(229, 107, 63, 0.45);
border-radius: 7px;
background: rgba(255, 249, 235, 0.92);
color: #9c3d20;
box-shadow: 0 5px 18px rgba(24, 42, 44, 0.14);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
white-space: nowrap;
transform: translate(-50%, -100%);
}
.panel {
position: fixed;
border: 1px solid rgba(255, 255, 255, 0.55);
background: var(--paper);
box-shadow: 0 12px 35px rgba(29, 49, 50, 0.14);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.title-panel {
top: 22px;
left: 22px;
width: min(350px, calc(100vw - 44px));
padding: 18px 19px 16px;
border-radius: 14px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--teal);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--orange);
transform: rotate(45deg);
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 31px);
line-height: 1.02;
letter-spacing: -0.045em;
}
.subtitle {
margin: 9px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.controls {
top: 22px;
right: 22px;
width: 260px;
padding: 15px;
border-radius: 14px;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 34px;
color: var(--muted);
font-size: 12px;
font-weight: 650;
}
.control-row + .control-row {
margin-top: 8px;
padding-top: 9px;
border-top: 1px solid var(--line);
}
button {
appearance: none;
border: 0;
border-radius: 8px;
padding: 8px 11px;
background: var(--ink);
color: white;
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
}
button:hover { background: #294148; }
button:active { transform: translateY(1px); }
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 12px;
}
input[type="range"] {
width: 118px;
accent-color: var(--orange);
}
input[type="checkbox"] {
width: 16px;
height: 16px;
accent-color: var(--teal);
}
.speed-value {
min-width: 55px;
color: var(--ink);
text-align: right;
font-variant-numeric: tabular-nums;
}
.stats {
bottom: 22px;
left: 22px;
width: min(390px, calc(100vw - 44px));
padding: 14px 16px;
border-radius: 14px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
}
.stat {
min-width: 0;
padding-right: 7px;
border-right: 1px solid var(--line);
}
.stat:last-child {
border-right: 0;
padding-right: 0;
}
.stat-label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 8px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.stat-value {
display: block;
font-size: 16px;
font-weight: 850;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.progress {
height: 3px;
margin-top: 13px;
overflow: hidden;
border-radius: 3px;
background: rgba(23, 39, 45, 0.1);
}
.progress i {
display: block;
width: 0;
height: 100%;
background: linear-gradient(90deg, var(--teal), var(--orange));
}
.legend {
position: fixed;
right: 22px;
bottom: 22px;
padding: 10px 13px;
border-radius: 10px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.02em;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
white-space: nowrap;
}
.legend-row + .legend-row { margin-top: 6px; }
.swatch {
width: 20px;
height: 3px;
border-radius: 2px;
}
.swatch.orange { background: var(--orange); }
.swatch.cyan { background: var(--cyan); }
.hint {
margin-top: 9px;
padding-top: 8px;
border-top: 1px solid var(--line);
color: #819196;
font-size: 9px;
font-weight: 650;
}
@media (max-width: 720px) {
.title-panel {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 13px 15px;
}
.subtitle { display: none; }
.controls {
top: auto;
right: 12px;
bottom: 135px;
width: 205px;
padding: 11px;
}
.stats {
bottom: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 11px 12px;
}
.stat-value { font-size: 13px; }
.legend { display: none; }
}
</style>
</head>
<body>
<div id="app"></div>
<div id="labels"></div>
<section class="panel title-panel">
<div class="eyebrow">Curve / 03</div>
<h1>Articulated tram</h1>
<p class="subtitle">
A three-section tram constrained to a curved track centerline. Amber guides show
body overhang beyond bogie pivots; cyan arcs expose articulation yaw.
</p>
</section>
<section class="panel controls">
<div class="button-row">
<button id="pauseButton" type="button">PAUSE</button>
<button id="resetButton" type="button">RESET VIEW</button>
</div>
<div class="control-row">
<label for="speed">Speed</label>
<div>
<input id="speed" type="range" min="1" max="10" step="0.5" value="4.5">
<span id="speedValue" class="speed-value">4.5 m/s</span>
</div>
</div>
<div class="control-row">
<label for="follow">Follow tram</label>
<input id="follow" type="checkbox" checked>
</div>
<div class="control-row">
<label for="analysis">Kinematic guides</label>
<input id="analysis" type="checkbox" checked>
</div>
</section>
<section class="panel stats">
<div class="stats-grid">
<div class="stat">
<span class="stat-label">Joint 01</span>
<span id="joint1" class="stat-value">0.0°</span>
</div>
<div class="stat">
<span class="stat-label">Joint 02</span>
<span id="joint2" class="stat-value">0.0°</span>
</div>
<div class="stat">
<span class="stat-label">Overhang</span>
<span id="overhang" class="stat-value">0.00 m</span>
</div>
<div class="stat">
<span class="stat-label">Track gauge</span>
<span class="stat-value">1.44 m</span>
</div>
</div>
<div class="progress"><i id="progressFill"></i></div>
</section>
<aside class="panel legend">
<div class="legend-row">
<span class="swatch orange"></span>
Body end → bogie overhang
</div>
<div class="legend-row">
<span class="swatch cyan"></span>
Articulation angle / pivots
</div>
<div class="hint">Drag to orbit · Shift/right-drag to pan · Wheel to zoom</div>
</aside>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const app = document.getElementById("app");
const labels = document.getElementById("labels");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xcbd9d2);
scene.fog = new THREE.Fog(0xcbd9d2, 62, 138);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
240
);
const hemisphere = new THREE.HemisphereLight(0xf4f1dc, 0x536e60, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0d3, 3.1);
sun.position.set(32, 48, 24);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -52;
sun.shadow.camera.right = 52;
sun.shadow.camera.top = 52;
sun.shadow.camera.bottom = -52;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 130;
sun.shadow.bias = -0.00035;
scene.add(sun);
const standard = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.02,
flatShading: true,
...options
});
const ground = new THREE.Mesh(
new THREE.CircleGeometry(86, 48),
standard(0x91aa7e)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.11;
ground.receiveShadow = true;
scene.add(ground);
// Closed, continuously curved track centerline.
const centerline = new THREE.CatmullRomCurve3(
[
new THREE.Vector3(-34, 0, -20),
new THREE.Vector3(-15, 0, -27),
new THREE.Vector3(10, 0, -30),
new THREE.Vector3(32, 0, -16),
new THREE.Vector3(38, 0, 4),
new THREE.Vector3(24, 0, 24),
new THREE.Vector3(-4, 0, 30),
new THREE.Vector3(-28, 0, 17)
],
true,
"catmullrom",
0.48
);
centerline.arcLengthDivisions = 1600;
const pathLength = centerline.getLength();
const wrap01 = value => ((value % 1) + 1) % 1;
const wrapAngle = value => Math.atan2(Math.sin(value), Math.cos(value));
function trackFrame(t) {
const point = centerline.getPointAt(wrap01(t));
const tangent = centerline.getTangentAt(wrap01(t)).normalize();
const normal = new THREE.Vector3(-tangent.z, 0, tangent.x).normalize();
return { point, tangent, normal };
}
function createBallastRibbon(width) {
const count = 520;
const positions = [];
const uvs = [];
const indices = [];
for (let i = 0; i < count; i++) {
const { point, normal } = trackFrame(i / count);
const left = point.clone().addScaledVector(normal, width);
const right = point.clone().addScaledVector(normal, -width);
positions.push(left.x, 0.015, left.z, right.x, 0.015, right.z);
uvs.push(0, i / count, 1, i / count);
const a = i * 2;
const b = ((i + 1) % count) * 2;
indices.push(a, b, a + 1, b, b + 1, a + 1);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
standard(0x8a806c, { side: THREE.DoubleSide })
);
mesh.receiveShadow = true;
scene.add(mesh);
}
createBallastRibbon(1.55);
const railMaterial = standard(0x697477, {
metalness: 0.72,
roughness: 0.28
});
for (const side of [-1, 1]) {
const railPoints = [];
const samples = 100;
for (let i = 0; i < samples; i++) {
const { point, normal } = trackFrame(i / samples);
railPoints.push(
point.clone().addScaledVector(normal, side * 0.72).setY(0.235)
);
}
const railCurve = new THREE.CatmullRomCurve3(railPoints, true, "catmullrom", 0.5);
const rail = new THREE.Mesh(
new THREE.TubeGeometry(railCurve, 520, 0.065, 6, true),
railMaterial
);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
}
const sleeperCount = Math.floor(pathLength / 1.2);
const sleepers = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.26, 0.15, 2.38),
standard(0x625d50),
sleeperCount
);
sleepers.castShadow = true;
sleepers.receiveShadow = true;
const dummy = new THREE.Object3D();
for (let i = 0; i < sleeperCount; i++) {
const { point, tangent } = trackFrame(i / sleeperCount);
dummy.position.set(point.x, 0.09, point.z);
dummy.rotation.set(0, -Math.atan2(tangent.z, tangent.x), 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
sleepers.setMatrixAt(i, dummy.matrix);
}
sleepers.instanceMatrix.needsUpdate = true;
scene.add(sleepers);
// Scenery.
let seed = 1783;
function random() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
const trackSamples = Array.from({ length: 90 }, (_, i) =>
centerline.getPointAt(i / 90)
);
function distanceToTrack(position) {
let distance = Infinity;
for (const point of trackSamples) {
distance = Math.min(distance, point.distanceToSquared(position));
}
return Math.sqrt(distance);
}
const buildingColors = [
0xb8aa91, 0xc8b9a0, 0x9ca99d, 0xc4b39d, 0xaeb7ae
];
for (let i = 0; i < 22; i++) {
const angle = random() * Math.PI * 2;
const radius = 44 + random() * 24;
const position = new THREE.Vector3(
Math.cos(angle) * radius,
0,
Math.sin(angle) * radius
);
if (distanceToTrack(position) < 8) continue;
const width = 4 + random() * 6;
const depth = 4 + random() * 5;
const height = 4 + random() * 12;
const material = standard(
buildingColors[Math.floor(random() * buildingColors.length)]
);
const building = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
building.position.set(position.x, height / 2, position.z);
building.rotation.y = random() * Math.PI;
building.castShadow = true;
building.receiveShadow = true;
scene.add(building);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.86, 0.4, depth * 0.86),
standard(0x6e7770)
);
roof.position.set(position.x, height + 0.2, position.z);
roof.rotation.y = building.rotation.y;
roof.castShadow = true;
scene.add(roof);
}
const trunkMaterial = standard(0x71543d);
const foliageMaterials = [
standard(0x4d7655),
standard(0x62835a),
standard(0x76915f)
];
for (let i = 0; i < 42; i++) {
const angle = random() * Math.PI * 2;
const radius = 10 + random() * 58;
const position = new THREE.Vector3(
Math.cos(angle) * radius,
0,
Math.sin(angle) * radius
);
if (distanceToTrack(position) < 3.7) continue;
const tree = new THREE.Group();
tree.position.copy(position);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.18, 0.24, 1.7, 6),
trunkMaterial
);
trunk.position.y = 0.85;
trunk.castShadow = true;
tree.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(1.35, 3.4, 6),
foliageMaterials[Math.floor(random() * foliageMaterials.length)]
);
crown.position.y = 2.75;
crown.rotation.y = random() * Math.PI;
crown.castShadow = true;
tree.add(crown);
scene.add(tree);
}
// Small station beside the track.
{
const { point, normal, tangent } = trackFrame(0.55);
const station = new THREE.Group();
station.position.copy(point).addScaledVector(normal, 3.25);
station.rotation.y = -Math.atan2(tangent.z, tangent.x);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(9, 0.34, 2.65),
standard(0xb8b6a8)
);
platform.position.y = 0.13;
platform.receiveShadow = true;
station.add(platform);
const shelter = new THREE.Mesh(
new THREE.BoxGeometry(3.5, 0.18, 1.75),
standard(0x36565a)
);
shelter.position.set(0, 2.8, 0);
shelter.castShadow = true;
station.add(shelter);
for (const x of [-1.35, 1.35]) {
for (const z of [-0.62, 0.62]) {
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.07, 2.65, 6),
standard(0x45585a)
);
post.position.set(x, 1.45, z);
post.castShadow = true;
station.add(post);
}
}
scene.add(station);
}
// Tram construction.
const BODY_SHELL_LENGTH = 4.16;
const BODY_CENTER_SPACING = 4.0;
const BOGIE_OFFSETS = [0.85, 3.15, 4.85, 7.15, 8.85, 11.15];
const bodyColors = [0x238d83, 0x2d9d91, 0xe36b42];
const bodyGroups = [];
const bogieGroups = [];
const wheelPivots = [];
const sections = [];
function addBox(parent, size, position, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function createRod(parent, a, b, radius, material) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = end.clone().sub(start);
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, direction.length(), 6),
material
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
mesh.castShadow = true;
parent.add(mesh);
return mesh;
}
const windowMaterial = standard(0x183b48, {
roughness: 0.26,
metalness: 0.22,
emissive: 0x0b252b,
emissiveIntensity: 0.22
});
const rubberMaterial = standard(0x20282a);
const steelMaterial = standard(0x677477, {
metalness: 0.55,
roughness: 0.36
});
function createBody(index) {
const group = new THREE.Group();
const bodyMaterial = standard(bodyColors[index]);
const creamMaterial = standard(0xf0e7cb);
const darkMaterial = standard(0x263d42);
addBox(
group,
[BODY_SHELL_LENGTH, 0.58, 2.48],
[0, 1.06, 0],
bodyMaterial
);
addBox(
group,
[BODY_SHELL_LENGTH - 0.04, 1.25, 2.42],
[0, 2.00, 0],
bodyMaterial
);
addBox(
group,
[BODY_SHELL_LENGTH - 0.12, 0.12, 2.51],
[0, 1.57, 0],
creamMaterial
);
addBox(
group,
[BODY_SHELL_LENGTH - 0.22, 0.18, 2.54],
[0, 2.72, 0],
creamMaterial
);
addBox(
group,
[BODY_SHELL_LENGTH - 0.28, 0.16, 2.15],
[0, 0.76, 0],
darkMaterial
);
for (const side of [-1, 1]) {
for (const x of [-1.38, -0.46, 0.46, 1.38]) {
addBox(
group,
[0.72, 0.64, 0.035],
[x, 2.09, side * 1.224],
windowMaterial
);
}
}
if (index === 2) {
addBox(group, [0.045, 0.72, 1.98], [2.065, 2.10, 0], windowMaterial);
for (const z of [-0.78, 0.78]) {
addBox(
group,
[0.08, 0.16, 0.25],
[2.10, 1.25, z],
standard(0xffe8a8, { emissive: 0xffd56a, emissiveIntensity: 0.8 })
);
}
} else {
addBox(group, [0.045, 0.65, 1.94], [-2.065, 2.10, 0], windowMaterial);
}
if (index === 2) {
createRod(group, [-0.62, 2.82, 0], [0, 3.48, 0], 0.045, steelMaterial);
createRod(group, [0, 3.48, 0], [-0.62, 4.02, 0], 0.04, steelMaterial);
createRod(group, [0, 3.48, 0], [0.62, 4.02, 0], 0.04, steelMaterial);
createRod(group, [-0.62, 4.02, 0], [0.62, 4.02, 0], 0.035, steelMaterial);
addBox(group, [1.25, 0.055, 0.14], [0, 4.04, 0], darkMaterial);
}
scene.add(group);
bodyGroups.push(group);
return group;
}
function createBogie() {
const group = new THREE.Group();
addBox(group, [1.08, 0.2, 1.72], [0, 0.78, 0], steelMaterial);
addBox(group, [0.72, 0.13, 0.75], [0, 0.94, 0], rubberMaterial);
for (const x of [-0.31, 0.31]) {
const axle = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.07, 1.88, 8),
steelMaterial
);
axle.rotation.x = Math.PI / 2;
axle.position.set(x, 0.58, 0);
axle.castShadow = true;
group.add(axle);
for (const z of [-0.91, 0.91]) {
const pivot = new THREE.Group();
pivot.position.set(x, 0.58, z);
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.30, 0.30, 0.18, 10),
rubberMaterial
);
wheel.rotation.x = Math.PI / 2;
wheel.castShadow = true;
pivot.add(wheel);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.105, 0.105, 0.195, 8),
steelMaterial
);
hub.rotation.x = Math.PI / 2;
pivot.add(hub);
group.add(pivot);
wheelPivots.push(pivot);
}
}
scene.add(group);
bogieGroups.push(group);
return group;
}
for (let i = 0; i < 3; i++) createBody(i);
for (let i = 0; i < 6; i++) createBogie(i);
// Articulation bellows.
const jointGroups = [];
for (let i = 0; i < 2; i++) {
const joint = new THREE.Group();
addBox(joint, [0.46, 1.76, 2.43], [0, 1.76, 0], rubberMaterial);
for (const x of [-0.18, -0.09, 0, 0.09, 0.18]) {
addBox(joint, [0.045, 1.83, 2.48], [x, 1.76, 0], steelMaterial);
}
scene.add(joint);
jointGroups.push(joint);
}
// Analysis overlays.
const analysisGroup = new THREE.Group();
scene.add(analysisGroup);
const overhangMaterial = new THREE.LineBasicMaterial({
color: 0xe56b3f,
transparent: true,
opacity: 0.98,
depthTest: false
});
const pivotMaterial = new THREE.MeshBasicMaterial({
color: 0x23b9c5,
depthTest: false,
transparent: true,
opacity: 0.92
});
const markerGeometry = new THREE.SphereGeometry(0.16, 8, 6);
for (let i = 0; i < 6; i++) {
const marker = new THREE.Mesh(markerGeometry, pivotMaterial);
marker.renderOrder = 30;
analysisGroup.add(marker);
}
for (let i = 0; i < 3; i++) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(12), 3)
);
const line = new THREE.LineSegments(geometry, overhangMaterial);
line.renderOrder = 31;
analysisGroup.add(line);
sections.push({
group: bodyGroups[i],
bogieA: bogieGroups[i * 2],
bogieB: bogieGroups[i * 2 + 1],
p0: new THREE.Vector3(),
p1: new THREE.Vector3(),
endRear: new THREE.Vector3(),
endFront: new THREE.Vector3(),
heading: new THREE.Vector3(),
bogieAPosition: new THREE.Vector3(),
bogieBPosition: new THREE.Vector3(),
overhangLine: line
});
}
const jointVisuals = [];
for (let i = 0; i < 2; i++) {
const arcGeometry = new THREE.BufferGeometry();
arcGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(33 * 3), 3)
);
const arc = new THREE.Line(arcGeometry, overhangMaterial);
arc.renderOrder = 32;
analysisGroup.add(arc);
const spokeGeometry = new THREE.BufferGeometry();
spokeGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(12), 3)
);
const spokes = new THREE.LineSegments(spokeGeometry, overhangMaterial);
spokes.renderOrder = 32;
analysisGroup.add(spokes);
const label = document.createElement("div");
label.className = "joint-label";
labels.appendChild(label);
jointVisuals.push({ arc, spokes, label, angle: 0 });
}
const vehicleCenter = new THREE.Vector3();
let vehicleS = 0.035;
let running = true;
let speed = 4.5;
function updateVehicle(dt) {
const base = wrap01(vehicleS);
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
const startOffset = i * BODY_CENTER_SPACING;
const frameA = trackFrame(base + startOffset / pathLength);
const frameB = trackFrame(base + (startOffset + BODY_CENTER_SPACING) / pathLength);
const frameBA = trackFrame(base + BOGIE_OFFSETS[i * 2] / pathLength);
const frameBB = trackFrame(base + BOGIE_OFFSETS[i * 2 + 1] / pathLength);
section.p0.copy(frameA.point);
section.p1.copy(frameB.point);
section.bogieAPosition.copy(frameBA.point);
section.bogieBPosition.copy(frameBB.point);
const center = section.p0.clone().add(section.p1).multiplyScalar(0.5);
const direction = section.p1.clone().sub(section.p0).normalize();
section.heading.copy(direction);
section.endRear.copy(center).addScaledVector(direction, -BODY_SHELL_LENGTH / 2);
section.endFront.copy(center).addScaledVector(direction, BODY_SHELL_LENGTH / 2);
section.group.position.copy(center);
section.group.rotation.y = -Math.atan2(direction.z, direction.x);
section.bogieA.position.copy(frameBA.point);
section.bogieA.rotation.y = -Math.atan2(frameBA.tangent.z, frameBA.tangent.x);
section.bogieB.position.copy(frameBB.point);
section.bogieB.rotation.y = -Math.atan2(frameBB.tangent.z, frameBB.tangent.x);
const positions = section.overhangLine.geometry.attributes.position.array;
positions.set([
section.endRear.x, 0.48, section.endRear.z,
section.bogieAPosition.x, 0.48, section.bogieAPosition.z,
section.bogieBPosition.x, 0.48, section.bogieBPosition.z,
section.endFront.x, 0.48, section.endFront.z
]);
section.overhangLine.geometry.attributes.position.needsUpdate = true;
}
vehicleCenter.copy(sections[1].p0).add(sections[1].p1).multiplyScalar(0.5);
for (let i = 0; i < 2; i++) {
const rear = sections[i];
const front = sections[i + 1];
const thetaRear = Math.atan2(rear.heading.z, rear.heading.x);
const thetaFront = Math.atan2(front.heading.z, front.heading.x);
const delta = wrapAngle(thetaFront - thetaRear);
const jointPosition = rear.p1;
jointGroups[i].position.copy(jointPosition);
jointGroups[i].rotation.y = -(thetaRear + delta / 2);
jointVisuals[i].angle = Math.abs(delta) * THREE.MathUtils.RAD2DEG;
jointVisuals[i].label.textContent =
`J${String(i + 1).padStart(2, "0")} ${jointVisuals[i].angle.toFixed(1)}°`;
const radius = 2.12;
const arcPositions = jointVisuals[i].arc.geometry.attributes.position.array;
for (let step = 0; step <= 32; step++) {
const t = step / 32;
const theta = thetaRear + delta * t;
arcPositions[step * 3] = jointPosition.x + Math.cos(theta) * radius;
arcPositions[step * 3 + 1] = 0.49;
arcPositions[step * 3 + 2] = jointPosition.z + Math.sin(theta) * radius;
}
jointVisuals[i].arc.geometry.attributes.position.needsUpdate = true;
const spokes = jointVisuals[i].spokes.geometry.attributes.position.array;
spokes.set([
jointPosition.x, 0.49, jointPosition.z,
jointPosition.x + Math.cos(thetaRear) * radius, 0.49,
jointPosition.z + Math.sin(thetaRear) * radius,
jointPosition.x, 0.49, jointPosition.z,
jointPosition.x + Math.cos(thetaFront) * radius, 0.49,
jointPosition.z + Math.sin(thetaFront) * radius
]);
jointVisuals[i].spokes.geometry.attributes.position.needsUpdate = true;
}
for (let i = 0; i < 6; i++) {
const marker = analysisGroup.children[i];
const point = sections[Math.floor(i / 2)][i % 2 === 0 ? "bogieAPosition" : "bogieBPosition"];
marker.position.set(point.x, 0.49, point.z);
}
if (running) {
const wheelRotation = -speed * dt / 0.30;
for (const pivot of wheelPivots) pivot.rotation.z += wheelRotation;
}
}
// Custom camera controls; no external controls module is used.
const cameraControl = {
target: new THREE.Vector3(),
radius: 27,
theta: 0.82,
phi: 1.04,
dragging: false,
panning: false,
lastX: 0,
lastY: 0
};
const canvas = renderer.domElement;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
cameraControl.dragging = true;
cameraControl.panning = event.button === 2 || event.shiftKey;
cameraControl.lastX = event.clientX;
cameraControl.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!cameraControl.dragging) return;
const dx = event.clientX - cameraControl.lastX;
const dy = event.clientY - cameraControl.lastY;
cameraControl.lastX = event.clientX;
cameraControl.lastY = event.clientY;
if (cameraControl.panning) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const scale = cameraControl.radius * 0.0014;
cameraControl.target.addScaledVector(right, -dx * scale);
cameraControl.target.addScaledVector(up, dy * scale);
} else {
cameraControl.theta -= dx * 0.006;
cameraControl.phi = THREE.MathUtils.clamp(
cameraControl.phi - dy * 0.005,
0.24,
1.46
);
}
});
function endDrag(event) {
cameraControl.dragging = false;
cameraControl.panning = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraControl.radius = THREE.MathUtils.clamp(
cameraControl.radius * Math.exp(event.deltaY * 0.001),
8,
80
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
cameraControl.target.copy(vehicleCenter);
});
function updateCamera(dt) {
if (followCheckbox.checked) {
cameraControl.target.lerp(
vehicleCenter,
1 - Math.exp(-dt * 2.8)
);
}
const sinPhi = Math.sin(cameraControl.phi);
camera.position.set(
cameraControl.target.x + cameraControl.radius * sinPhi * Math.sin(cameraControl.theta),
cameraControl.target.y + cameraControl.radius * Math.cos(cameraControl.phi),
cameraControl.target.z + cameraControl.radius * sinPhi * Math.cos(cameraControl.theta)
);
camera.lookAt(cameraControl.target);
camera.updateMatrixWorld();
}
const pauseButton = document.getElementById("pauseButton");
const speedInput = document.getElementById("speed");
const speedValue = document.getElementById("speedValue");
const followCheckbox = document.getElementById("follow");
const analysisCheckbox = document.getElementById("analysis");
const joint1Readout = document.getElementById("joint1");
const joint2Readout = document.getElementById("joint2");
const overhangReadout = document.getElementById("overhang");
const progressFill = document.getElementById("progressFill");
pauseButton.addEventListener("click", () => {
running = !running;
pauseButton.textContent = running ? "PAUSE" : "RESUME";
});
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedValue.textContent = `${speed.toFixed(1)} m/s`;
});
analysisCheckbox.addEventListener("change", () => {
analysisGroup.visible = analysisCheckbox.checked;
for (const visual of jointVisuals) {
visual.label.style.display = analysisCheckbox.checked ? "block" : "none";
}
});
document.getElementById("resetButton").addEventListener("click", () => {
cameraControl.target.copy(vehicleCenter);
cameraControl.radius = 27;
cameraControl.theta = 0.82;
cameraControl.phi = 1.04;
});
window.addEventListener("keydown", event => {
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
}
if (event.key.toLowerCase() === "r") {
cameraControl.target.copy(vehicleCenter);
cameraControl.radius = 27;
cameraControl.theta = 0.82;
cameraControl.phi = 1.04;
}
});
function updateReadouts() {
joint1Readout.textContent = `${jointVisuals[0].angle.toFixed(1)}°`;
joint2Readout.textContent = `${jointVisuals[1].angle.toFixed(1)}°`;
const overhangs = [];
for (const section of sections) {
overhangs.push(section.endRear.distanceTo(section.bogieAPosition));
overhangs.push(section.endFront.distanceTo(section.bogieBPosition));
}
const average = overhangs.reduce((sum, value) => sum + value, 0) / overhangs.length;
overhangReadout.textContent = `${average.toFixed(2)} m`;
progressFill.style.width = `${vehicleS * 100}%`;
}
function updateJointLabels() {
for (let i = 0; i < jointVisuals.length; i++) {
if (!analysisCheckbox.checked) continue;
const point = sections[i].p1;
const projected = new THREE.Vector3(point.x, 3.55, point.z).project(camera);
const visible = projected.z > -1 && projected.z < 1;
jointVisuals[i].label.style.display = visible ? "block" : "none";
if (!visible) continue;
jointVisuals[i].label.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
jointVisuals[i].label.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
updateVehicle(0);
cameraControl.target.copy(vehicleCenter);
updateCamera(1);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (running) {
vehicleS = wrap01(vehicleS + speed * dt / pathLength);
}
updateVehicle(dt);
updateCamera(dt);
updateReadouts();
updateJointLabels();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```