Prompt specification
Build or customize the Three.js 3D scene "Vehicle Length Changes a Junction Fit" 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: Vehicle Length Changes a Junction Fit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/vehicle-length-changes-a-junction-fit-x2148
Scene Description Prompt:
Compare two voxel tram lengths on one curve, showing swept envelopes and clearance violations. Build one HTML file with Three.js from cdnjs.
Working Three.js Starter (vehicle-length-changes-a-junction-fit-x2148):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Tram Curve Clearance Study</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: #0c1726;
--panel-2: #101e30;
--line: #24354d;
--text: #e9f1fb;
--muted: #91a4bc;
--cyan: #36d8d3;
--orange: #ffb44d;
--red: #ff4f70;
--blue: #8196ff;
}
* {
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;
}
button,
input {
font: inherit;
}
.app {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
header {
z-index: 10;
display: flex;
align-items: center;
justify-content: space-between;
min-height: 66px;
padding: 10px 18px;
border-bottom: 1px solid var(--line);
background: rgba(7, 16, 29, 0.96);
gap: 16px;
}
.brand {
min-width: 235px;
}
.brand strong {
display: block;
font-size: 15px;
letter-spacing: 0.12em;
}
.brand span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.04em;
}
.toolbar {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 8px;
}
.segmented {
display: flex;
padding: 3px;
border: 1px solid var(--line);
border-radius: 9px;
background: #091321;
}
.segmented button,
.plain-button {
border: 0;
border-radius: 6px;
color: var(--muted);
background: transparent;
padding: 8px 11px;
cursor: pointer;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.03em;
}
.segmented button:hover,
.plain-button:hover {
color: white;
background: #17263a;
}
.segmented button.active {
color: #07101d;
background: #dce9f7;
}
.plain-button {
border: 1px solid var(--line);
background: #0b1727;
}
.toggles {
display: flex;
align-items: center;
gap: 12px;
color: var(--muted);
font-size: 12px;
}
.toggles label {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
cursor: pointer;
}
input[type="checkbox"] {
accent-color: var(--cyan);
}
.workspace {
display: grid;
grid-template-columns: minmax(0, 1fr) 330px;
flex: 1;
min-height: 0;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #08111f;
}
#stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.split-divider {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
background: linear-gradient(
to bottom,
transparent,
rgba(145, 164, 188, 0.55) 15%,
rgba(145, 164, 188, 0.55) 85%,
transparent
);
pointer-events: none;
}
.split-divider::after {
content: "SAME R24 CURVE";
position: absolute;
top: 50%;
left: 9px;
padding: 5px 7px;
border: 1px solid #33455e;
border-radius: 4px;
color: #8ea1ba;
background: rgba(7, 16, 29, 0.86);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
white-space: nowrap;
}
.panel-head {
position: absolute;
top: 18px;
z-index: 3;
min-width: 145px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(7, 16, 29, 0.84);
backdrop-filter: blur(8px);
pointer-events: none;
text-align: center;
}
.panel-head strong {
display: block;
font-size: 13px;
letter-spacing: 0.08em;
}
.panel-head span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
#headShort {
left: 25%;
transform: translateX(-50%);
border-top: 2px solid var(--cyan);
}
#headLong {
left: 75%;
transform: translateX(-50%);
border-top: 2px solid var(--orange);
}
#headShort strong {
color: var(--cyan);
}
#headLong strong {
color: var(--orange);
}
.world-tag {
position: absolute;
z-index: 4;
display: none;
transform: translate(-50%, -100%);
padding: 6px 8px;
border: 1px solid currentColor;
border-radius: 5px;
color: var(--cyan);
background: rgba(7, 16, 29, 0.88);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
white-space: nowrap;
pointer-events: none;
}
#shortTag {
color: var(--cyan);
}
#longTag {
color: var(--orange);
}
#violationTag {
color: var(--red);
}
.legend {
position: absolute;
left: 16px;
bottom: 14px;
z-index: 4;
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
max-width: calc(100% - 32px);
padding: 9px 11px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(7, 16, 29, 0.84);
backdrop-filter: blur(8px);
color: #bdc9d8;
font-size: 10px;
pointer-events: none;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
width: 15px;
height: 5px;
border-radius: 2px;
background: currentColor;
}
.swatch.cyan {
color: var(--cyan);
}
.swatch.orange {
color: var(--orange);
}
.swatch.red {
color: var(--red);
}
.swatch.blue {
color: var(--blue);
}
.hint {
position: absolute;
right: 14px;
bottom: 14px;
z-index: 4;
padding: 7px 9px;
border-radius: 6px;
color: #8094ad;
background: rgba(7, 16, 29, 0.76);
font-size: 9px;
letter-spacing: 0.03em;
pointer-events: none;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 18px;
border-left: 1px solid var(--line);
background: linear-gradient(180deg, #0c1726, #091320);
}
.aside-title {
margin-bottom: 15px;
}
.aside-title h2 {
margin: 0;
font-size: 13px;
letter-spacing: 0.12em;
}
.aside-title p {
margin: 6px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.case-card {
position: relative;
margin-bottom: 12px;
padding: 14px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(16, 30, 48, 0.76);
}
.case-card::before {
content: "";
position: absolute;
top: 0;
right: 0;
left: 0;
height: 2px;
background: var(--card-color);
}
.case-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.case-head strong {
color: var(--card-color);
font-size: 13px;
}
.status {
padding: 4px 7px;
border: 1px solid currentColor;
border-radius: 999px;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
}
.pass {
color: var(--cyan);
}
.fail {
color: var(--red);
}
.metric {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-top: 13px;
color: var(--muted);
font-size: 10px;
}
.metric b {
color: var(--text);
font-size: 16px;
font-weight: 750;
}
.metric b.negative {
color: var(--red);
}
.meter {
position: relative;
height: 7px;
margin-top: 7px;
overflow: hidden;
border-radius: 999px;
background: #1c2b3f;
}
.meter-fill {
height: 100%;
border-radius: inherit;
background: var(--card-color);
}
.meter-limit {
position: absolute;
top: -2px;
bottom: -2px;
left: 83.33%;
width: 1px;
background: white;
opacity: 0.8;
}
.case-note {
margin-top: 10px;
color: #8fa1b8;
font-size: 10px;
line-height: 1.45;
}
.parameters {
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
.parameters h3 {
margin: 0 0 9px;
font-size: 11px;
letter-spacing: 0.1em;
}
.parameter-row {
display: flex;
justify-content: space-between;
margin: 7px 0;
color: var(--muted);
font-size: 11px;
}
.parameter-row b {
color: #dce6f2;
font-weight: 650;
}
.formula {
margin-top: 12px;
padding: 10px;
border: 1px solid #253851;
border-radius: 7px;
color: #aabbd0;
background: #08121f;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.55;
}
.interpretation {
margin-top: 14px;
padding: 11px;
border-left: 2px solid var(--orange);
color: #9fb0c4;
background: rgba(255, 180, 77, 0.05);
font-size: 10px;
line-height: 1.55;
}
.interpretation strong {
color: #e9f1fb;
}
.controls-help {
margin-top: 14px;
color: #71869f;
font-size: 9px;
line-height: 1.6;
}
@media (max-width: 920px) {
html,
body {
overflow: auto;
}
.app {
min-height: 100%;
height: auto;
}
header {
align-items: flex-start;
flex-direction: column;
}
.toolbar {
justify-content: flex-start;
}
.workspace {
grid-template-columns: 1fr;
}
#stage {
height: 68vh;
min-height: 520px;
}
aside {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.hint {
display: none;
}
}
@media (max-width: 600px) {
header {
padding: 10px;
}
.toggles {
gap: 8px;
}
.panel-head {
top: 10px;
min-width: 112px;
padding: 7px;
}
.panel-head strong {
font-size: 10px;
}
.panel-head span {
font-size: 8px;
}
.legend {
left: 8px;
bottom: 8px;
gap: 6px 9px;
}
.split-divider::after {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<strong>CURVE / CLEARANCE LAB</strong>
<span>Voxel tram rigid-body envelope comparison</span>
</div>
<div class="toolbar">
<div class="segmented" aria-label="Comparison mode">
<button class="active" data-mode="compare">Compare</button>
<button data-mode="short">18 m</button>
<button data-mode="long">30 m</button>
</div>
<div class="toggles">
<label>
<input id="showEnvelopes" type="checkbox" checked />
Swept envelopes
</label>
<label>
<input id="showClearance" type="checkbox" checked />
Clearance corridor
</label>
</div>
<button id="resetView" class="plain-button">Reset view</button>
</div>
</header>
<div class="workspace">
<section id="stage" aria-label="Interactive Three.js clearance visualization">
<div id="splitDivider" class="split-divider"></div>
<div id="headShort" class="panel-head">
<strong>18 M / PASS</strong>
<span>Equivalent rigid tram chord</span>
</div>
<div id="headLong" class="panel-head">
<strong>30 M / FAIL</strong>
<span>Inside-clearance violation</span>
</div>
<div id="shortTag" class="world-tag">18 m · +2.63 m margin</div>
<div id="longTag" class="world-tag">30 m · −0.87 m margin</div>
<div id="violationTag" class="world-tag">CLEARANCE −0.87 m</div>
<div class="legend">
<span><i class="swatch cyan"></i>18 m swept envelope</span>
<span><i class="swatch orange"></i>30 m swept envelope</span>
<span><i class="swatch red"></i>outside clearance</span>
<span><i class="swatch blue"></i>±6 m corridor</span>
</div>
<div class="hint">
Drag: orbit · Right/shift-drag: pan · Wheel: zoom · R: reset
</div>
</section>
<aside>
<div class="aside-title">
<h2>ENVELOPE RESULTS</h2>
<p>
Both views use the exact same centerline, camera, clearance limit,
and vehicle width.
</p>
</div>
<div class="case-card" style="--card-color: var(--cyan)">
<div class="case-head">
<strong>18 m tram</strong>
<span class="status pass">PASS</span>
</div>
<div class="metric">
<span>Peak inward sweep</span>
<b id="shortReach">3.37 m</b>
</div>
<div class="meter">
<div id="shortMeter" class="meter-fill"></div>
<i class="meter-limit"></i>
</div>
<div class="metric">
<span>Clearance margin</span>
<b id="shortMargin">+2.63 m</b>
</div>
<div class="case-note">
The short chord remains entirely inside the 6.0 m clearance corridor.
</div>
</div>
<div class="case-card" style="--card-color: var(--orange)">
<div class="case-head">
<strong>30 m tram</strong>
<span class="status fail">FAIL</span>
</div>
<div class="metric">
<span>Peak inward sweep</span>
<b id="longReach">6.87 m</b>
</div>
<div class="meter">
<div id="longMeter" class="meter-fill"></div>
<i class="meter-limit"></i>
</div>
<div class="metric">
<span>Clearance margin</span>
<b id="longMargin" class="negative">−0.87 m</b>
</div>
<div class="case-note" id="longNote">
The long chord crosses the inside clearance boundary.
</div>
</div>
<div class="parameters">
<h3>MODEL PARAMETERS</h3>
<div class="parameter-row">
<span>Curve radius</span>
<b>24.0 m</b>
</div>
<div class="parameter-row">
<span>Vehicle width</span>
<b>3.2 m</b>
</div>
<div class="parameter-row">
<span>Clearance limit</span>
<b>±6.0 m</b>
</div>
<div class="parameter-row">
<span>Bend arc length</span>
<b>37.70 m</b>
</div>
<div class="formula">
sagitta = R − √(R² − (L / 2)²)<br />
inward reach = sagitta + W / 2
</div>
<div class="interpretation">
<strong>Interpretation.</strong>
On a circular bend, a longer rigid chord cuts farther toward the
inside of the curve. The 30 m case exceeds the inside clearance
boundary by approximately 0.87 m.
</div>
<div class="controls-help">
The body is displayed at the critical chord pose so the geometric
cause of the clearance conflict is visible. The envelope is a
conservative rigid-body model, not an articulated-rail vehicle
dynamics simulation.
</div>
</div>
</aside>
</div>
</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 shortTag = document.querySelector("#shortTag");
const longTag = document.querySelector("#longTag");
const violationTag = document.querySelector("#violationTag");
const headShort = document.querySelector("#headShort");
const headLong = document.querySelector("#headLong");
const splitDivider = document.querySelector("#splitDivider");
const COLORS = {
background: 0x08111f,
grid: 0x24354d,
gridCenter: 0x526780,
ground: 0x0a1422,
track: 0x526273,
ties: 0x263548,
clearance: 0x8196ff,
clearanceEdge: 0x9caeff,
short: 0x36d8d3,
long: 0xffb44d,
red: 0xff4f70,
window: 0x0a1b2d,
windowGlow: 0x37bde8,
rail: 0x8a9baa
};
const LAYER_COMMON = 0;
const LAYER_SHORT = 1;
const LAYER_LONG = 2;
const ROUTE_RADIUS = 24;
const VEHICLE_WIDTH = 3.2;
const CLEARANCE = 6.0;
const HALF_WIDTH = VEHICLE_WIDTH / 2;
const SHORT_LENGTH = 18;
const LONG_LENGTH = 30;
let mode = "compare";
let showEnvelopes = true;
let showClearance = true;
function sagitta(length) {
const half = length / 2;
return ROUTE_RADIUS -
Math.sqrt(ROUTE_RADIUS * ROUTE_RADIUS - half * half);
}
const shortReach = sagitta(SHORT_LENGTH) + HALF_WIDTH;
const longReach = sagitta(LONG_LENGTH) + HALF_WIDTH;
const shortMargin = CLEARANCE - shortReach;
const longMargin = CLEARANCE - longReach;
document.querySelector("#shortReach").textContent =
`${shortReach.toFixed(2)} m`;
document.querySelector("#longReach").textContent =
`${longReach.toFixed(2)} m`;
document.querySelector("#shortMargin").textContent =
`${shortMargin >= 0 ? "+" : "−"}${Math.abs(shortMargin).toFixed(2)} m`;
document.querySelector("#longMargin").textContent =
`${longMargin >= 0 ? "+" : "−"}${Math.abs(longMargin).toFixed(2)} m`;
document.querySelector("#shortMeter").style.width =
`${Math.min(100, shortReach / CLEARANCE * 100)}%`;
document.querySelector("#longMeter").style.width =
`${Math.min(100, longReach / CLEARANCE * 100)}%`;
document.querySelector("#longMeter").style.background = "var(--red)";
shortTag.textContent =
`18 m · ${shortMargin >= 0 ? "+" : "−"}${Math.abs(shortMargin).toFixed(2)} m margin`;
longTag.textContent =
`30 m · ${longMargin >= 0 ? "+" : "−"}${Math.abs(longMargin).toFixed(2)} m margin`;
violationTag.textContent =
`CLEARANCE ${longMargin >= 0 ? "+" : "−"}${Math.abs(longMargin).toFixed(2)} m`;
// ------------------------------------------------------------
// Renderer, scene, and camera
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.background);
scene.fog = new THREE.FogExp2(COLORS.background, 0.0035);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
stage.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 600);
camera.layers.enable(LAYER_COMMON);
const hemisphere = new THREE.HemisphereLight(0xb9d8ff, 0x101725, 1.7);
hemisphere.layers.enable(LAYER_SHORT);
hemisphere.layers.enable(LAYER_LONG);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.7);
keyLight.position.set(-45, 90, 55);
keyLight.layers.enable(LAYER_SHORT);
keyLight.layers.enable(LAYER_LONG);
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x668cff, 1.1);
fillLight.position.set(80, 35, -40);
fillLight.layers.enable(LAYER_SHORT);
fillLight.layers.enable(LAYER_LONG);
scene.add(fillLight);
// ------------------------------------------------------------
// Route construction: straight → R24 quarter bend → straight
// ------------------------------------------------------------
const route = [];
let totalDistance = 0;
function pushPoint(position, tangent, normal, kind) {
route.push({
p: position.clone(),
t: tangent.clone().normalize(),
n: normal.clone().normalize(),
kind,
s: totalDistance
});
}
{
const start = new THREE.Vector3(-72, 0, 0);
const end = new THREE.Vector3(-36, 0, 0);
const tangent = new THREE.Vector3(1, 0, 0);
const normal = new THREE.Vector3(0, 0, 1);
const length = start.distanceTo(end);
const steps = 30;
for (let i = 0; i < steps; i++) {
const f = i / steps;
const p = start.clone().lerp(end, f);
totalDistance += length / steps;
pushPoint(p, tangent, normal, "straight");
}
}
{
const center = new THREE.Vector3(-36, 0, 24);
const startAngle = -Math.PI / 2;
const endAngle = 0;
const steps = 180;
const arcLength = ROUTE_RADIUS * (endAngle - startAngle);
const segmentLength = arcLength / steps;
for (let i = 0; i < steps; i++) {
const f = i / steps;
const angle = THREE.MathUtils.lerp(startAngle, endAngle, f);
const p = new THREE.Vector3(
center.x + ROUTE_RADIUS * Math.cos(angle),
0,
center.z + ROUTE_RADIUS * Math.sin(angle)
);
const tangent = new THREE.Vector3(
-Math.sin(angle),
0,
Math.cos(angle)
);
const normal = new THREE.Vector3(-tangent.z, 0, tangent.x);
totalDistance += segmentLength;
pushPoint(p, tangent, normal, "arc");
}
}
{
const start = new THREE.Vector3(-12, 0, 24);
const end = new THREE.Vector3(-12, 0, 72);
const tangent = new THREE.Vector3(0, 0, 1);
const normal = new THREE.Vector3(-1, 0, 0);
const length = start.distanceTo(end);
const steps = 60;
for (let i = 0; i < steps; i++) {
const f = i / steps;
const p = start.clone().lerp(end, f);
totalDistance += length / steps;
pushPoint(p, tangent, normal, "straight");
}
}
const routeLength = totalDistance;
const criticalIndex = 30 + 90;
const critical = route[criticalIndex];
// ------------------------------------------------------------
// Shared scene: ground, rails, ties, corridor, and route line
// ------------------------------------------------------------
const commonGroup = new THREE.Group();
scene.add(commonGroup);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(240, 240),
new THREE.MeshStandardMaterial({
color: COLORS.ground,
roughness: 0.95,
metalness: 0.05
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.set(-30, -0.035, 28);
commonGroup.add(ground);
const grid = new THREE.GridHelper(220, 44, COLORS.gridCenter, COLORS.grid);
grid.position.set(-30, 0.005, 28);
grid.material.transparent = true;
grid.material.opacity = 0.28;
commonGroup.add(grid);
const railMaterial = new THREE.MeshStandardMaterial({
color: COLORS.rail,
roughness: 0.34,
metalness: 0.75
});
const tieMaterial = new THREE.MeshStandardMaterial({
color: COLORS.ties,
roughness: 0.88,
metalness: 0.05
});
const railGeometry = new THREE.BoxGeometry(1, 0.16, 0.16);
const tieGeometry = new THREE.BoxGeometry(0.46, 0.18, 3.7);
for (let i = 0; i < route.length - 1; i++) {
const a = route[i];
const b = route[i + 1];
for (const side of [-1, 1]) {
const p1 = a.p.clone().addScaledVector(a.n, side * 1.12);
const p2 = b.p.clone().addScaledVector(b.n, side * 1.12);
const direction = p2.clone().sub(p1);
const length = direction.length();
const rail = new THREE.Mesh(railGeometry, railMaterial);
rail.scale.x = length;
rail.position.copy(p1).lerp(p2, 0.5);
rail.position.y = 0.34;
rail.rotation.y = -Math.atan2(direction.z, direction.x);
commonGroup.add(rail);
}
}
let lastTieDistance = -10;
for (const sample of route) {
if (sample.s - lastTieDistance < 1.45) continue;
lastTieDistance = sample.s;
const tie = new THREE.Mesh(tieGeometry, tieMaterial);
tie.position.copy(sample.p);
tie.position.y = 0.13;
tie.rotation.y = -Math.atan2(sample.t.z, sample.t.x);
commonGroup.add(tie);
}
const centerLinePoints = route.map(
sample => new THREE.Vector3(sample.p.x, 0.19, sample.p.z)
);
const centerLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(centerLinePoints),
new THREE.LineDashedMaterial({
color: 0x9bb0ca,
dashSize: 1.8,
gapSize: 1.2,
transparent: true,
opacity: 0.45
})
);
centerLine.computeLineDistances();
commonGroup.add(centerLine);
function offsetSample(sample, distance) {
return sample.p.clone().addScaledVector(sample.n, distance);
}
function makeRibbon(boundaryA, boundaryB, y, material) {
const positions = [];
const indices = [];
for (let i = 0; i < route.length; i++) {
positions.push(
boundaryA[i].x, y, boundaryA[i].z,
boundaryB[i].x, y, boundaryB[i].z
);
if (i < route.length - 1) {
const a = i * 2;
indices.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
return new THREE.Mesh(geometry, material);
}
const clearanceGroup = new THREE.Group();
commonGroup.add(clearanceGroup);
const clearanceLeft = route.map(sample => offsetSample(sample, -CLEARANCE));
const clearanceRight = route.map(sample => offsetSample(sample, CLEARANCE));
const corridor = makeRibbon(
clearanceLeft,
clearanceRight,
0.035,
new THREE.MeshBasicMaterial({
color: COLORS.clearance,
transparent: true,
opacity: 0.09,
side: THREE.DoubleSide,
depthWrite: false
})
);
clearanceGroup.add(corridor);
for (const points of [clearanceLeft, clearanceRight]) {
const linePoints = points.map(p => new THREE.Vector3(p.x, 0.11, p.z));
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(linePoints),
new THREE.LineBasicMaterial({
color: COLORS.clearanceEdge,
transparent: true,
opacity: 0.72
})
);
clearanceGroup.add(line);
}
// ------------------------------------------------------------
// Swept envelope construction
// ------------------------------------------------------------
function makeEnvelope(length, color, layer) {
const group = new THREE.Group();
const s = sagitta(length);
const outerBoundary = [];
const innerBoundary = [];
const clearanceBoundary = [];
const violationBoundary = [];
for (const sample of route) {
const localSagitta = sample.kind === "arc" ? s : 0;
outerBoundary.push(
offsetSample(sample, localSagitta - HALF_WIDTH)
);
innerBoundary.push(
offsetSample(sample, localSagitta + HALF_WIDTH)
);
const limitPoint = offsetSample(sample, CLEARANCE);
clearanceBoundary.push(limitPoint.clone());
const reaches = localSagitta + HALF_WIDTH > CLEARANCE;
violationBoundary.push(
reaches
? offsetSample(sample, localSagitta + HALF_WIDTH)
: limitPoint.clone()
);
}
const envelope = makeRibbon(
outerBoundary,
innerBoundary,
0.085,
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.25,
side: THREE.DoubleSide,
depthWrite: false
})
);
group.add(envelope);
const edgeMaterial = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.88
});
for (const boundary of [outerBoundary, innerBoundary]) {
const points = boundary.map(p => new THREE.Vector3(p.x, 0.18, p.z));
group.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
edgeMaterial
)
);
}
const violation = makeRibbon(
clearanceBoundary,
violationBoundary,
0.12,
new THREE.MeshBasicMaterial({
color: COLORS.red,
transparent: true,
opacity: 0.78,
side: THREE.DoubleSide,
depthWrite: false
})
);
group.add(violation);
group.traverse(object => object.layers.set(layer));
return group;
}
const shortEnvelope = makeEnvelope(
SHORT_LENGTH,
COLORS.short,
LAYER_SHORT
);
const longEnvelope = makeEnvelope(
LONG_LENGTH,
COLORS.long,
LAYER_LONG
);
scene.add(shortEnvelope, longEnvelope);
// ------------------------------------------------------------
// Voxel tram construction
// ------------------------------------------------------------
function createVoxelTram(length, color, layer) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.55,
metalness: 0.16
});
const lightBodyMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(color).lerp(new THREE.Color(0xffffff), 0.22),
roughness: 0.48,
metalness: 0.12
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x142236,
roughness: 0.72,
metalness: 0.25
});
const windowMaterial = new THREE.MeshStandardMaterial({
color: COLORS.window,
emissive: COLORS.windowGlow,
emissiveIntensity: 0.42,
roughness: 0.18,
metalness: 0.28
});
const blackMaterial = new THREE.MeshStandardMaterial({
color: 0x080d14,
roughness: 0.9,
metalness: 0.08
});
const headlightMaterial = new THREE.MeshStandardMaterial({
color: 0xfff2bf,
emissive: 0xffe48a,
emissiveIntensity: 2.2,
roughness: 0.25
});
function box(w, h, d, x, y, z, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
material
);
mesh.position.set(x, y, z);
group.add(mesh);
return mesh;
}
box(length, 0.42, 2.85, 0, 1.02, 0, darkMaterial);
box(length - 0.45, 1.12, VEHICLE_WIDTH, 0, 1.78, 0, bodyMaterial);
box(length - 0.75, 0.34, 2.92, 0, 2.62, 0, lightBodyMaterial);
const modules = Math.max(6, Math.round(length / 2.75));
const moduleLength = length / modules;
for (let i = 0; i < modules; i++) {
const x = -length / 2 + moduleLength * (i + 0.5);
const windowLength = moduleLength * 0.69;
for (const side of [-1, 1]) {
box(
windowLength,
0.76,
0.09,
x,
2.17,
side * (VEHICLE_WIDTH / 2 + 0.025),
windowMaterial
);
box(
length - 0.9,
0.16,
0.07,
0,
1.52,
side * (VEHICLE_WIDTH / 2 + 0.03),
lightBodyMaterial
);
}
if (i % 2 === 0) {
box(
moduleLength * 0.34,
0.23,
1.35,
x,
2.87,
0,
darkMaterial
);
}
}
// End caps and windscreens.
box(0.38, 1.65, 3.28, length / 2 - 0.12, 1.83, 0, lightBodyMaterial);
box(0.38, 1.65, 3.28, -length / 2 + 0.12, 1.83, 0, lightBodyMaterial);
box(0.09, 0.92, 2.5, length / 2 + 0.10, 2.12, 0, windowMaterial);
for (const side of [-1, 1]) {
box(
0.12,
0.2,
0.28,
length / 2 + 0.14,
1.48,
side * 0.9,
headlightMaterial
);
}
// Voxel bogies and wheels.
for (const x of [-length * 0.32, 0, length * 0.32]) {
box(1.45, 0.38, 2.2, x, 0.66, 0, darkMaterial);
for (const side of [-1, 1]) {
box(
0.78,
0.72,
0.46,
x,
0.48,
side * 1.12,
blackMaterial
);
}
}
// Simple pantograph made from block segments.
box(0.18, 0.72, 0.18, length * 0.08, 3.12, 0, darkMaterial);
box(0.18, 0.72, 0.18, length * 0.08 - 0.52, 3.54, 0, darkMaterial);
box(1.25, 0.12, 0.16, length * 0.08 - 0.26, 3.89, 0, darkMaterial);
const s = sagitta(length);
group.position.copy(critical.p).addScaledVector(critical.n, s);
group.rotation.y = -Math.atan2(critical.t.z, critical.t.x);
group.traverse(object => object.layers.set(layer));
return group;
}
const shortTram = createVoxelTram(
SHORT_LENGTH,
COLORS.short,
LAYER_SHORT
);
const longTram = createVoxelTram(
LONG_LENGTH,
COLORS.long,
LAYER_LONG
);
scene.add(shortTram, longTram);
// ------------------------------------------------------------
// Clearance violation marker
// ------------------------------------------------------------
const violationMarker = new THREE.Group();
const violationPosition = critical.p.clone().addScaledVector(
critical.n,
longReach
);
violationMarker.position.copy(violationPosition);
const markerMaterial = new THREE.MeshStandardMaterial({
color: COLORS.red,
emissive: COLORS.red,
emissiveIntensity: 1.7,
roughness: 0.32
});
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.58, 0),
markerMaterial
);
marker.position.y = 2.65;
violationMarker.add(marker);
const markerStem = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 4.7, 0.16),
markerMaterial
);
markerStem.position.y = 0.05;
violationMarker.add(markerStem);
const markerFoot = new THREE.Mesh(
new THREE.BoxGeometry(0.8, 0.18, 0.8),
markerMaterial
);
markerFoot.position.y = -2.25;
violationMarker.add(markerFoot);
violationMarker.traverse(object => object.layers.set(LAYER_LONG));
scene.add(violationMarker);
// ------------------------------------------------------------
// Direct camera controls
// ------------------------------------------------------------
const controls = {
target: new THREE.Vector3(-36, 1.0, 25),
radius: 158,
phi: 1.02,
theta: 0.72
};
function resetCamera() {
controls.target.set(-36, 1.0, 25);
controls.radius = 158;
controls.phi = 1.02;
controls.theta = 0.72;
}
function updateCamera() {
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x +
controls.radius * sinPhi * Math.sin(controls.theta),
controls.target.y +
controls.radius * Math.cos(controls.phi),
controls.target.z +
controls.radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
camera.updateMatrixWorld();
}
const pointers = new Map();
let gesture = null;
const canvas = renderer.domElement;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
gesture = {
type:
event.button === 2 || event.button === 1 || event.shiftKey
? "pan"
: "orbit",
x: event.clientX,
y: event.clientY
};
} else if (pointers.size === 2) {
const values = [...pointers.values()];
gesture = {
type: "pinch",
distance: Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
),
midpoint: {
x: (values[0].x + values[1].x) / 2,
y: (values[0].y + values[1].y) / 2
}
};
}
});
function panCamera(dx, dy) {
const right = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
0
);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const scale = controls.radius * 0.00135;
controls.target.addScaledVector(right, -dx * scale);
controls.target.addScaledVector(up, dy * scale);
}
canvas.addEventListener("pointermove", event => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1 && gesture) {
const dx = event.clientX - gesture.x;
const dy = event.clientY - gesture.y;
if (gesture.type === "orbit") {
controls.theta -= dx * 0.006;
controls.phi -= dy * 0.006;
controls.phi = THREE.MathUtils.clamp(
controls.phi,
0.14,
1.47
);
} else {
panCamera(dx, dy);
}
gesture.x = event.clientX;
gesture.y = event.clientY;
} else if (pointers.size === 2 && gesture?.type === "pinch") {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
const midpoint = {
x: (values[0].x + values[1].x) / 2,
y: (values[0].y + values[1].y) / 2
};
if (gesture.distance > 0 && distance > 0) {
controls.radius = THREE.MathUtils.clamp(
controls.radius * (gesture.distance / distance),
55,
240
);
panCamera(
midpoint.x - gesture.midpoint.x,
midpoint.y - gesture.midpoint.y
);
}
gesture.distance = distance;
gesture.midpoint = midpoint;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 1) {
const remaining = [...pointers.values()][0];
gesture = {
type: "orbit",
x: remaining.x,
y: remaining.y
};
} else if (pointers.size === 0) {
gesture = null;
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
controls.radius = THREE.MathUtils.clamp(
controls.radius * Math.exp(event.deltaY * 0.001),
55,
240
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", event => {
if (event.key.toLowerCase() === "r") resetCamera();
if (event.key === "0") setMode("compare");
if (event.key === "1") setMode("short");
if (event.key === "2") setMode("long");
});
// ------------------------------------------------------------
// UI and viewport rendering
// ------------------------------------------------------------
function setMode(nextMode) {
mode = nextMode;
document.querySelectorAll("[data-mode]").forEach(button => {
button.classList.toggle("active", button.dataset.mode === mode);
});
const isCompare = mode === "compare";
splitDivider.style.display = isCompare ? "block" : "none";
headShort.style.display = mode === "long" ? "none" : "block";
headLong.style.display = mode === "short" ? "none" : "block";
if (isCompare) {
headShort.style.left = "25%";
headLong.style.left = "75%";
} else {
headShort.style.left = "50%";
headLong.style.left = "50%";
}
}
document.querySelectorAll("[data-mode]").forEach(button => {
button.addEventListener("click", () => setMode(button.dataset.mode));
});
document.querySelector("#showEnvelopes").addEventListener("change", event => {
showEnvelopes = event.target.checked;
shortEnvelope.visible = showEnvelopes;
longEnvelope.visible = showEnvelopes;
});
document.querySelector("#showClearance").addEventListener("change", event => {
showClearance = event.target.checked;
clearanceGroup.visible = showClearance;
});
document.querySelector("#resetView").addEventListener("click", resetCamera);
function resizeRenderer() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(stage);
resizeRenderer();
function projectElement(element, worldPosition, viewport) {
const projected = worldPosition.clone().project(camera);
if (
projected.z < -1 ||
projected.z > 1 ||
projected.x < -1.15 ||
projected.x > 1.15 ||
projected.y < -1.15 ||
projected.y > 1.15
) {
element.style.display = "none";
return;
}
const x = viewport.x + (projected.x * 0.5 + 0.5) * viewport.w;
const y = (1 - (projected.y * 0.5 + 0.5)) * viewport.h;
element.style.display = "block";
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function renderViewport(viewport) {
camera.aspect = viewport.w / viewport.h;
camera.updateProjectionMatrix();
camera.layers.set(LAYER_COMMON);
camera.layers.enable(viewport.layer);
renderer.setViewport(viewport.x, 0, viewport.w, viewport.h);
renderer.setScissor(viewport.x, 0, viewport.w, viewport.h);
renderer.render(scene, camera);
if (viewport.key === "short") {
const anchor = shortTram.position.clone();
anchor.y = 4.3;
projectElement(shortTag, anchor, viewport);
} else {
const anchor = longTram.position.clone();
anchor.y = 4.3;
projectElement(longTag, anchor, viewport);
const violationAnchor = violationPosition.clone();
violationAnchor.y = 4.8;
projectElement(violationTag, violationAnchor, viewport);
}
}
function render() {
const width = stage.clientWidth;
const height = stage.clientHeight;
updateCamera();
renderer.setScissorTest(true);
if (mode === "compare") {
const half = Math.floor(width / 2);
renderViewport({
x: 0,
w: half,
h: height,
layer: LAYER_SHORT,
key: "short"
});
renderViewport({
x: half,
w: width - half,
h: height,
layer: LAYER_LONG,
key: "long"
});
} else if (mode === "short") {
renderViewport({
x: 0,
w: width,
h: height,
layer: LAYER_SHORT,
key: "short"
});
} else {
renderViewport({
x: 0,
w: width,
h: height,
layer: LAYER_LONG,
key: "long"
});
}
renderer.setScissorTest(false);
}
renderer.setAnimationLoop(render);
</script>
</body>
</html>
```