Prompt specification
Build or customize the Three.js 3D scene "Miniature coaster energy exhibition" 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: Miniature coaster energy exhibition
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/miniature-coaster-energy-exhibition-x1379
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Compose a bounded coaster track with hill, valley, and stopping zone; show potential, kinetic, and dissipated energy indicators consistent with the chosen motion model.
Working Three.js Starter (miniature-coaster-energy-exhibition-x1379):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Energy Coaster</title>
<style>
:root {
--cyan: #55e6ff;
--yellow: #ffd166;
--red: #ff5d73;
--panel: rgba(8, 17, 35, 0.88);
--border: rgba(140, 210, 255, 0.22);
--text: #eaf6ff;
--muted: #9bb4ca;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #071222;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: absolute;
z-index: 10;
border: 1px solid var(--border);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(12px);
}
#info {
top: 18px;
left: 18px;
width: min(330px, calc(100vw - 36px));
padding: 18px;
}
h1 {
margin: 0 0 5px;
font-size: 20px;
letter-spacing: 0.07em;
}
.subtitle {
margin: 0 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#status {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 14px;
padding: 7px 10px;
border-radius: 999px;
background: rgba(85, 230, 255, 0.09);
color: var(--cyan);
font: 700 11px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
#status::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
}
.energy-row {
margin: 12px 0;
}
.energy-heading {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 6px;
font-size: 12px;
font-weight: 750;
letter-spacing: 0.04em;
}
.energy-heading strong {
font: 700 13px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.track {
height: 8px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.08);
}
.fill {
width: 0;
height: 100%;
border-radius: inherit;
transition: width 80ms linear;
}
#potentialFill {
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
#kineticFill {
background: var(--yellow);
box-shadow: 0 0 12px var(--yellow);
}
#dissipatedFill {
background: var(--red);
box-shadow: 0 0 12px var(--red);
}
#ledger {
margin-top: 15px;
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
background: rgba(0, 0, 0, 0.18);
color: var(--muted);
font: 11px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
}
#readouts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.readout {
padding: 9px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
}
.readout span {
display: block;
color: var(--muted);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.readout b {
display: block;
margin-top: 3px;
font: 700 13px ui-monospace, SFMono-Regular, Menlo, monospace;
}
details {
margin-top: 13px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
summary {
cursor: pointer;
color: var(--text);
font-weight: 700;
}
details code {
color: #c6e8ff;
}
#controls {
right: 18px;
bottom: 18px;
width: min(330px, calc(100vw - 36px));
padding: 14px;
}
.button-row {
display: flex;
gap: 8px;
margin-bottom: 12px;
}
button {
flex: 1;
padding: 10px 12px;
border: 1px solid rgba(130, 220, 255, 0.3);
border-radius: 8px;
background: rgba(85, 230, 255, 0.1);
color: var(--text);
font: 750 11px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
cursor: pointer;
}
button:hover {
background: rgba(85, 230, 255, 0.2);
}
button.secondary {
background: rgba(255, 255, 255, 0.05);
}
.slider-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 11px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
}
#progressTrack {
height: 5px;
margin-top: 13px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.08);
}
#progressFill {
width: 0;
height: 100%;
background: linear-gradient(90deg, var(--cyan), var(--yellow), var(--red));
}
.hint {
margin-top: 9px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
@media (max-width: 760px) {
#info {
top: 10px;
left: 10px;
width: min(290px, calc(100vw - 20px));
padding: 13px;
}
h1 {
font-size: 16px;
}
.subtitle,
details {
display: none;
}
#controls {
right: 10px;
bottom: 10px;
width: min(290px, calc(100vw - 20px));
}
}
</style>
</head>
<body>
<div id="app"></div>
<section id="info" class="panel">
<h1>VOXEL ENERGY COASTER</h1>
<p class="subtitle">
A bounded rail ride through a hill, valley, and service-brake zone.
The gauges show the same energy budget used by the motion model.
</p>
<div id="status">RUNNING</div>
<div class="energy-row">
<div class="energy-heading">
<span style="color: var(--cyan)">POTENTIAL</span>
<strong id="potentialValue">0.0 J</strong>
</div>
<div class="track"><div id="potentialFill" class="fill"></div></div>
</div>
<div class="energy-row">
<div class="energy-heading">
<span style="color: var(--yellow)">KINETIC</span>
<strong id="kineticValue">0.0 J</strong>
</div>
<div class="track"><div id="kineticFill" class="fill"></div></div>
</div>
<div class="energy-row">
<div class="energy-heading">
<span style="color: var(--red)">DISSIPATED</span>
<strong id="dissipatedValue">0.0 J</strong>
</div>
<div class="track"><div id="dissipatedFill" class="fill"></div></div>
</div>
<div id="ledger"></div>
<div id="readouts">
<div class="readout">
<span>Speed</span>
<b id="speedValue">0.00 m/s</b>
</div>
<div class="readout">
<span>Track position</span>
<b id="positionValue">0 m</b>
</div>
</div>
<details>
<summary>Energy and motion model</summary>
<p>
The cart is constrained to the rail and moves by arc length.
<code>U = mg(h - h_min)</code>,
<code>K = ½mv²</code>.
Gravity acts along the local rail slope. Linear rolling drag
<code>F_d = bv</code> and a constant service brake
<code>F_b = 8.5 N</code> remove mechanical energy.
</p>
<p>
The displayed dissipated energy is
<code>D = E₀ - (K + U)</code>, so
<code>E₀ = K + U + D</code> remains consistent throughout the run.
</p>
</details>
</section>
<section id="controls" class="panel">
<div class="button-row">
<button id="pauseButton">PAUSE</button>
<button id="resetButton" class="secondary">RESET RUN</button>
</div>
<div class="slider-label">
<span>Launch speed</span>
<strong id="speedSliderValue">12.0 m/s</strong>
</div>
<input
id="speedSlider"
type="range"
min="8"
max="16"
step="0.5"
value="12"
aria-label="Launch speed"
>
<div id="progressTrack"><div id="progressFill"></div></div>
<div class="hint">
Drag to orbit · Wheel to zoom · Space to pause · R to reset.<br>
The red section is the service-brake zone.
</div>
</section>
<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");
// ------------------------------------------------------------
// Renderer, scene, camera
// ------------------------------------------------------------
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.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071222);
scene.fog = new THREE.Fog(0x071222, 48, 100);
const camera = new THREE.PerspectiveCamera(
48,
window.innerWidth / window.innerHeight,
0.1,
180
);
const cameraTarget = new THREE.Vector3(0, 3.5, 0);
const cameraState = {
yaw: 0.72,
pitch: 0.57,
radius: 55,
targetYaw: 0.72,
targetPitch: 0.57,
targetRadius: 55
};
const hemisphere = new THREE.HemisphereLight(0x9bdfff, 0x182137, 1.65);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 2.6);
sun.position.set(-18, 32, 22);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -42;
sun.shadow.camera.right = 42;
sun.shadow.camera.top = 32;
sun.shadow.camera.bottom = -32;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 90;
sun.shadow.bias = -0.0003;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x4fc8ff, 1.1);
rim.position.set(20, 12, -24);
scene.add(rim);
// ------------------------------------------------------------
// Shared helpers
// ------------------------------------------------------------
const clamp = THREE.MathUtils.clamp;
const UP = new THREE.Vector3(0, 1, 0);
function seededRandom(seed) {
return function () {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function basisFromTangent(tangent) {
const forward = tangent.clone().normalize();
const right = new THREE.Vector3().crossVectors(UP, forward).normalize();
const up = new THREE.Vector3().crossVectors(forward, right).normalize();
const matrix = new THREE.Matrix4().makeBasis(right, up, forward);
const quaternion = new THREE.Quaternion().setFromRotationMatrix(matrix);
return { forward, right, up, quaternion };
}
function makeLabel(text, color = "#dff7ff", background = "#10243a") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = color;
context.lineWidth = 7;
context.strokeRect(7, 7, canvas.width - 14, canvas.height - 14);
context.fillStyle = color;
context.font = "bold 42px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(7.4, 1.85, 1);
sprite.renderOrder = 20;
return sprite;
}
// ------------------------------------------------------------
// Voxel terrain
// ------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.BoxGeometry(66, 0.7, 44),
new THREE.MeshStandardMaterial({
color: 0x101d32,
roughness: 0.94,
metalness: 0.05
})
);
ground.position.y = -0.35;
ground.receiveShadow = true;
scene.add(ground);
const terrainGeometry = new THREE.BoxGeometry(1, 1, 1);
const terrainMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.95
});
const terrainColumns = 37;
const terrainRows = 21;
const terrainCount = terrainColumns * terrainRows;
const terrain = new THREE.InstancedMesh(
terrainGeometry,
terrainMaterial,
terrainCount
);
const random = seededRandom(9173);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let terrainIndex = 0;
for (let iz = 0; iz < terrainRows; iz++) {
for (let ix = 0; ix < terrainColumns; ix++) {
const x = -27 + ix * 1.5;
const z = -15 + iz * 1.5;
const rolling =
0.18 +
random() * 0.34 +
0.12 * Math.sin(ix * 0.63 + iz * 0.27);
dummy.position.set(x, rolling / 2, z);
dummy.scale.set(1.46, rolling, 1.46);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
terrain.setMatrixAt(terrainIndex, dummy.matrix);
color.setHSL(
0.54 + random() * 0.035,
0.34,
0.19 + random() * 0.08
);
terrain.setColorAt(terrainIndex, color);
terrainIndex++;
}
}
terrain.instanceMatrix.needsUpdate = true;
terrain.instanceColor.needsUpdate = true;
terrain.receiveShadow = true;
terrain.castShadow = true;
scene.add(terrain);
// ------------------------------------------------------------
// Track curve
// ------------------------------------------------------------
const controlPoints = [
new THREE.Vector3(-24, 4.0, 0),
new THREE.Vector3(-18, 4.2, -4),
new THREE.Vector3(-12, 8.0, -8),
new THREE.Vector3(-5, 9.0, -4),
new THREE.Vector3(2, 6.0, 4),
new THREE.Vector3(7, 1.6, 9),
new THREE.Vector3(13, 2.0, 11),
new THREE.Vector3(19, 3.5, 7),
new THREE.Vector3(24, 2.5, 3)
];
const curve = new THREE.CatmullRomCurve3(
controlPoints,
false,
"centripetal",
0.5
);
curve.arcLengthDivisions = 2400;
curve.updateArcLengths();
const trackLength = curve.getLength();
const trackSamples = curve.getSpacedPoints(1400);
const zoneStart = trackLength * 0.76;
let minimumHeight = Infinity;
let maximumHeight = -Infinity;
let minimumIndex = 0;
let maximumIndex = 0;
trackSamples.forEach((point, index) => {
if (point.y < minimumHeight) {
minimumHeight = point.y;
minimumIndex = index;
}
if (point.y > maximumHeight) {
maximumHeight = point.y;
maximumIndex = index;
}
});
function heightAt(distance) {
const s = clamp(distance, 0, trackLength);
const position = (s / trackLength) * (trackSamples.length - 1);
const index = Math.floor(position);
const next = Math.min(index + 1, trackSamples.length - 1);
const fraction = position - index;
return THREE.MathUtils.lerp(
trackSamples[index].y,
trackSamples[next].y,
fraction
);
}
function slopeAt(distance) {
const epsilon = 0.12;
const before = heightAt(distance - epsilon);
const after = heightAt(distance + epsilon);
return (after - before) / (2 * epsilon);
}
// ------------------------------------------------------------
// Voxel rails, ties, and supports
// ------------------------------------------------------------
const railSegments = 520;
const railGeometry = new THREE.BoxGeometry(0.18, 0.18, 1);
const railMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
metalness: 0.65,
roughness: 0.28
});
const rails = new THREE.InstancedMesh(
railGeometry,
railMaterial,
railSegments * 2
);
rails.castShadow = true;
rails.receiveShadow = true;
const segmentLength = trackLength / railSegments;
let railIndex = 0;
for (let i = 0; i < railSegments; i++) {
const s0 = i * segmentLength;
const s1 = (i + 1) * segmentLength;
const p0 = curve.getPointAt(s0 / trackLength);
const p1 = curve.getPointAt(s1 / trackLength);
const midpoint = p0.clone().lerp(p1, 0.5);
const tangent = p1.clone().sub(p0);
const basis = basisFromTangent(tangent);
for (const side of [-1, 1]) {
dummy.position.copy(midpoint).addScaledVector(basis.right, side * 0.72);
dummy.quaternion.copy(basis.quaternion);
dummy.scale.set(1, 1, segmentLength * 1.08);
dummy.updateMatrix();
rails.setMatrixAt(railIndex, dummy.matrix);
color.set(
s0 >= zoneStart
? 0xff9b35
: (i % 4 === 0 ? 0xd8f3ff : 0x9db7c8)
);
rails.setColorAt(railIndex, color);
railIndex++;
}
}
rails.instanceMatrix.needsUpdate = true;
rails.instanceColor.needsUpdate = true;
scene.add(rails);
const tieCount = Math.floor(trackLength / 0.72);
const ties = new THREE.InstancedMesh(
new THREE.BoxGeometry(2.05, 0.22, 0.38),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.8
}),
tieCount
);
ties.castShadow = true;
ties.receiveShadow = true;
for (let i = 0; i < tieCount; i++) {
const u = i / (tieCount - 1);
const p = curve.getPointAt(u);
const tangent = curve.getTangentAt(u);
const basis = basisFromTangent(tangent);
dummy.position.copy(p).addScaledVector(basis.up, -0.27);
dummy.quaternion.copy(basis.quaternion);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
ties.setMatrixAt(i, dummy.matrix);
const distance = u * trackLength;
if (distance >= zoneStart) {
color.set(i % 2 ? 0xffc857 : 0xff5d73);
} else {
color.set(i % 3 ? 0x263c55 : 0x314b66);
}
ties.setColorAt(i, color);
}
ties.instanceMatrix.needsUpdate = true;
ties.instanceColor.needsUpdate = true;
scene.add(ties);
const supportMatrices = [];
const supportColors = [];
for (let distance = 1; distance < trackLength - 0.5; distance += 1.9) {
const u = distance / trackLength;
const p = curve.getPointAt(u);
const top = Math.max(0.2, p.y - 0.48);
const blockHeight = 0.5;
const blocks = Math.ceil(top / blockHeight);
for (let block = 0; block < blocks; block++) {
dummy.position.set(
p.x,
block * blockHeight + blockHeight / 2,
p.z
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
supportMatrices.push(dummy.matrix.clone());
supportColors.push(
new THREE.Color(block % 2 ? 0x244b65 : 0x1b3a53)
);
}
}
const supports = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.48, 0.48, 0.48),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.72,
metalness: 0.16
}),
supportMatrices.length
);
supportMatrices.forEach((matrix, index) => {
supports.setMatrixAt(index, matrix);
supports.setColorAt(index, supportColors[index]);
});
supports.instanceMatrix.needsUpdate = true;
supports.instanceColor.needsUpdate = true;
supports.castShadow = true;
supports.receiveShadow = true;
scene.add(supports);
// ------------------------------------------------------------
// Start and stop bumpers
// ------------------------------------------------------------
function createBumper(distance, isStop) {
const u = clamp(distance / trackLength, 0, 1);
const p = curve.getPointAt(u);
const tangent = curve.getTangentAt(u);
const basis = basisFromTangent(tangent);
for (let i = 0; i < 5; i++) {
const material = new THREE.MeshStandardMaterial({
color: isStop
? (i % 2 ? 0xffffff : 0xff425f)
: (i % 2 ? 0x55e6ff : 0x17334c),
roughness: 0.58,
metalness: 0.12
});
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.52, 0.34, 0.42),
material
);
block.position
.copy(p)
.addScaledVector(basis.right, (i - 2) * 0.52)
.addScaledVector(basis.up, 0.42);
block.quaternion.copy(basis.quaternion);
block.castShadow = true;
scene.add(block);
}
for (const side of [-1, 1]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 1.25, 0.28),
new THREE.MeshStandardMaterial({
color: isStop ? 0xff5d73 : 0x55e6ff,
roughness: 0.6
})
);
post.position
.copy(p)
.addScaledVector(basis.right, side * 1.25)
.addScaledVector(basis.up, 0.2);
post.castShadow = true;
scene.add(post);
}
}
createBumper(0, false);
createBumper(trackLength, true);
// Track labels
const hillLabel = makeLabel("HILL", "#ffd166", "#293044");
hillLabel.position.copy(trackSamples[maximumIndex]);
hillLabel.position.y += 3.0;
scene.add(hillLabel);
const valleyLabel = makeLabel("VALLEY", "#55e6ff", "#152b42");
valleyLabel.position.copy(trackSamples[minimumIndex]);
valleyLabel.position.y += 2.4;
scene.add(valleyLabel);
const brakeLabel = makeLabel("BRAKE ZONE", "#ff8a65", "#3b1f2d");
brakeLabel.position.copy(curve.getPointAt(zoneStart / trackLength));
brakeLabel.position.y += 3.1;
scene.add(brakeLabel);
const startLabel = makeLabel("LAUNCH", "#55e6ff", "#10283b");
startLabel.position.copy(curve.getPointAt(0));
startLabel.position.y += 2.7;
scene.add(startLabel);
// ------------------------------------------------------------
// Voxel cart
// ------------------------------------------------------------
const cart = new THREE.Group();
scene.add(cart);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xff9f1c,
roughness: 0.42,
metalness: 0.18
});
const trimMaterial = new THREE.MeshStandardMaterial({
color: 0xfff0b3,
roughness: 0.48
});
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x10151f,
roughness: 0.84
});
const seatMaterial = new THREE.MeshStandardMaterial({
color: 0x197b9b,
roughness: 0.58
});
function cartBlock(size, position, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
cart.add(mesh);
return mesh;
}
cartBlock(
new THREE.Vector3(1.45, 0.56, 1.85),
new THREE.Vector3(0, 0.66, 0),
bodyMaterial
);
cartBlock(
new THREE.Vector3(1.12, 0.22, 1.25),
new THREE.Vector3(0, 1.02, -0.08),
trimMaterial
);
cartBlock(
new THREE.Vector3(1.05, 0.48, 0.38),
new THREE.Vector3(0, 0.52, 1.02),
trimMaterial
);
for (const x of [-0.79, 0.79]) {
for (const z of [-0.62, 0.62]) {
cartBlock(
new THREE.Vector3(0.38, 0.38, 0.38),
new THREE.Vector3(x, 0.18, z),
wheelMaterial
);
}
}
cartBlock(
new THREE.Vector3(0.62, 0.45, 0.32),
new THREE.Vector3(0, 1.12, -0.25),
seatMaterial
);
cartBlock(
new THREE.Vector3(0.38, 0.38, 0.38),
new THREE.Vector3(0, 1.48, -0.25),
new THREE.MeshStandardMaterial({
color: 0xffd4b8,
roughness: 0.9
})
);
const headlightMaterial = new THREE.MeshStandardMaterial({
color: 0xe9fbff,
emissive: 0x8deaff,
emissiveIntensity: 1.6
});
cartBlock(
new THREE.Vector3(0.25, 0.22, 0.12),
new THREE.Vector3(-0.34, 0.66, 1.25),
headlightMaterial
);
cartBlock(
new THREE.Vector3(0.25, 0.22, 0.12),
new THREE.Vector3(0.34, 0.66, 1.25),
headlightMaterial
);
// ------------------------------------------------------------
// In-world voxel energy gauges
// ------------------------------------------------------------
function createGauge(position, gaugeColor, title, shortTitle) {
const group = new THREE.Group();
group.position.copy(position);
scene.add(group);
const cubes = [];
for (let i = 0; i < 10; i++) {
const material = new THREE.MeshStandardMaterial({
color: 0x203348,
emissive: 0x000000,
roughness: 0.5
});
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.3, 0.58),
material
);
cube.position.y = 0.15 + i * 0.34;
cube.castShadow = true;
group.add(cube);
cubes.push(cube);
}
const label = makeLabel(shortTitle, gaugeColor, "#101c30");
label.position.y = 4.1;
label.scale.set(4.7, 1.18, 1);
group.add(label);
const base = new THREE.Mesh(
new THREE.BoxGeometry(0.9, 0.18, 0.9),
new THREE.MeshStandardMaterial({
color: 0x22354a,
roughness: 0.8
})
);
base.position.y = -0.09;
base.receiveShadow = true;
group.add(base);
return { cubes, color: new THREE.Color(gaugeColor) };
}
const gauges = {
potential: createGauge(
new THREE.Vector3(-27, 0, 4.2),
"#55e6ff",
"Potential",
"POT"
),
kinetic: createGauge(
new THREE.Vector3(-27, 0, 6.8),
"#ffd166",
"Kinetic",
"KIN"
),
dissipated: createGauge(
new THREE.Vector3(-27, 0, 9.4),
"#ff5d73",
"Dissipated",
"HEAT"
)
};
function updateGauge(gauge, ratio) {
const normalized = clamp(ratio, 0, 1);
const activeCount = normalized * gauge.cubes.length;
gauge.cubes.forEach((cube, index) => {
const lit = index + 0.001 < activeCount;
const partial = index < Math.floor(activeCount);
const intensity = partial ? 1 : 0.12;
cube.material.color.copy(gauge.color).multiplyScalar(intensity);
cube.material.emissive.copy(gauge.color);
cube.material.emissiveIntensity = lit ? 0.42 : 0.015;
});
}
// ------------------------------------------------------------
// Physics and energy
// ------------------------------------------------------------
const MASS = 1.0;
const GRAVITY = 9.81;
const DRAG = 0.08;
const BRAKE_FORCE = 8.5;
let launchSpeed = 12;
let initialEnergy = 0;
const simulation = {
s: 0,
velocity: launchSpeed,
running: true,
stopped: false,
stalled: false
};
function potentialAt(distance) {
return MASS * GRAVITY * (heightAt(distance) - minimumHeight);
}
function kineticFromVelocity(velocity) {
return 0.5 * MASS * velocity * velocity;
}
function energyState(distance, velocity) {
const potential = potentialAt(distance);
const kinetic = kineticFromVelocity(velocity);
const mechanical = potential + kinetic;
const dissipated = Math.max(0, initialEnergy - mechanical);
return {
potential,
kinetic,
mechanical,
dissipated
};
}
function resetRun() {
simulation.s = 0;
simulation.velocity = launchSpeed;
simulation.running = true;
simulation.stopped = false;
simulation.stalled = false;
initialEnergy =
kineticFromVelocity(launchSpeed) + potentialAt(0);
updateHUD();
}
function derivative(distance, velocity) {
const slope = slopeAt(distance);
let force = -MASS * GRAVITY * slope - DRAG * velocity;
if (distance >= zoneStart && velocity !== 0) {
force -= BRAKE_FORCE * Math.sign(velocity);
}
return {
ds: velocity,
dv: force / MASS
};
}
function integratePhysics(dt) {
const oldS = simulation.s;
const oldV = simulation.velocity;
const k1 = derivative(oldS, oldV);
const k2 = derivative(
oldS + 0.5 * dt * k1.ds,
oldV + 0.5 * dt * k1.dv
);
const k3 = derivative(
oldS + 0.5 * dt * k2.ds,
oldV + 0.5 * dt * k2.dv
);
const k4 = derivative(
oldS + dt * k3.ds,
oldV + dt * k3.dv
);
let nextS =
oldS +
(dt / 6) * (k1.ds + 2 * k2.ds + 2 * k3.ds + k4.ds);
let nextV =
oldV +
(dt / 6) * (k1.dv + 2 * k2.dv + 2 * k3.dv + k4.dv);
// Detect the first zero-velocity event in the braking zone.
if (nextV <= 0 && oldV > 0 && nextS >= zoneStart) {
const fraction = clamp(oldV / (oldV - nextV), 0, 1);
const stoppingDistance =
oldS + (nextS - oldS) * fraction;
simulation.s = clamp(
stoppingDistance,
zoneStart,
trackLength - 0.05
);
simulation.velocity = 0;
simulation.stopped = true;
simulation.running = false;
return;
}
// The rear bumper prevents the cart from leaving the bounded track.
if (nextS <= 0 && nextV < 0) {
simulation.s = 0;
simulation.velocity = 0;
simulation.stalled = true;
simulation.running = false;
return;
}
if (nextS >= trackLength) {
simulation.s = trackLength - 0.05;
simulation.velocity = 0;
simulation.stopped = true;
simulation.running = false;
return;
}
simulation.s = nextS;
simulation.velocity = nextV;
}
// ------------------------------------------------------------
// HUD and controls
// ------------------------------------------------------------
const statusElement = document.getElementById("status");
const potentialValue = document.getElementById("potentialValue");
const kineticValue = document.getElementById("kineticValue");
const dissipatedValue = document.getElementById("dissipatedValue");
const potentialFill = document.getElementById("potentialFill");
const kineticFill = document.getElementById("kineticFill");
const dissipatedFill = document.getElementById("dissipatedFill");
const ledger = document.getElementById("ledger");
const speedValue = document.getElementById("speedValue");
const positionValue = document.getElementById("positionValue");
const progressFill = document.getElementById("progressFill");
const pauseButton = document.getElementById("pauseButton");
const resetButton = document.getElementById("resetButton");
const speedSlider = document.getElementById("speedSlider");
const speedSliderValue = document.getElementById("speedSliderValue");
function updateHUD() {
const energy = energyState(
simulation.s,
simulation.velocity
);
const safeTotal = Math.max(initialEnergy, 0.001);
potentialValue.textContent = `${energy.potential.toFixed(1)} J`;
kineticValue.textContent = `${energy.kinetic.toFixed(1)} J`;
dissipatedValue.textContent = `${energy.dissipated.toFixed(1)} J`;
potentialFill.style.width =
`${clamp(energy.potential / safeTotal, 0, 1) * 100}%`;
kineticFill.style.width =
`${clamp(energy.kinetic / safeTotal, 0, 1) * 100}%`;
dissipatedFill.style.width =
`${clamp(energy.dissipated / safeTotal, 0, 1) * 100}%`;
ledger.textContent =
`E₀ ${initialEnergy.toFixed(1)} J = ` +
`K ${energy.kinetic.toFixed(1)} + ` +
`U ${energy.potential.toFixed(1)} + ` +
`D ${energy.dissipated.toFixed(1)} J`;
speedValue.textContent = `${simulation.velocity.toFixed(2)} m/s`;
positionValue.textContent = `${simulation.s.toFixed(1)} m`;
progressFill.style.width =
`${clamp(simulation.s / trackLength, 0, 1) * 100}%`;
updateGauge(
gauges.potential,
energy.potential / safeTotal
);
updateGauge(
gauges.kinetic,
energy.kinetic / safeTotal
);
updateGauge(
gauges.dissipated,
energy.dissipated / safeTotal
);
if (simulation.stopped) {
statusElement.textContent = "STOPPED · BRAKE ZONE";
statusElement.style.color = "#ff8a65";
} else if (simulation.stalled) {
statusElement.textContent = "STALLED · ADD LAUNCH ENERGY";
statusElement.style.color = "#ff5d73";
} else if (!simulation.running) {
statusElement.textContent = "PAUSED";
statusElement.style.color = "#ffd166";
} else {
statusElement.textContent = "RUNNING";
statusElement.style.color = "#55e6ff";
}
}
pauseButton.addEventListener("click", () => {
if (!simulation.stopped && !simulation.stalled) {
simulation.running = !simulation.running;
pauseButton.textContent =
simulation.running ? "PAUSE" : "RESUME";
}
});
resetButton.addEventListener("click", () => {
pauseButton.textContent = "PAUSE";
resetRun();
});
speedSlider.addEventListener("input", () => {
launchSpeed = Number(speedSlider.value);
speedSliderValue.textContent = `${launchSpeed.toFixed(1)} m/s`;
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
}
if (event.code === "KeyR") {
resetRun();
pauseButton.textContent = "PAUSE";
}
});
// ------------------------------------------------------------
// Custom camera controls — no addons
// ------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.targetYaw -= deltaX * 0.006;
cameraState.targetPitch = clamp(
cameraState.targetPitch + deltaY * 0.005,
0.22,
1.32
);
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.targetRadius = clamp(
cameraState.targetRadius + event.deltaY * 0.045,
27,
86
);
},
{ passive: false }
);
function updateCamera(dt) {
const damping = 1 - Math.exp(-10 * dt);
cameraState.yaw = THREE.MathUtils.lerp(
cameraState.yaw,
cameraState.targetYaw,
damping
);
cameraState.pitch = THREE.MathUtils.lerp(
cameraState.pitch,
cameraState.targetPitch,
damping
);
cameraState.radius = THREE.MathUtils.lerp(
cameraState.radius,
cameraState.targetRadius,
damping
);
const horizontalRadius =
cameraState.radius * Math.sin(cameraState.pitch);
camera.position.set(
cameraTarget.x +
horizontalRadius * Math.sin(cameraState.yaw),
cameraTarget.y +
cameraState.radius * Math.cos(cameraState.pitch),
cameraTarget.z +
horizontalRadius * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraTarget);
}
// ------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------
function updateCart() {
const u = clamp(simulation.s / trackLength, 0, 1);
const position = curve.getPointAt(u);
const tangent = curve.getTangentAt(u);
const basis = basisFromTangent(tangent);
cart.position.copy(position);
cart.quaternion.copy(basis.quaternion);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
resetRun();
const fixedStep = 1 / 120;
let accumulator = 0;
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (simulation.running && !simulation.stopped) {
accumulator += dt;
let steps = 0;
while (accumulator >= fixedStep && steps < 12) {
integratePhysics(fixedStep);
accumulator -= fixedStep;
steps++;
if (!simulation.running) {
accumulator = 0;
break;
}
}
} else {
accumulator = 0;
}
updateCamera(dt);
updateCart();
updateHUD();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```