Prompt specification
Build or customize the Three.js 3D scene "Reference-frame comparison sandbox" 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: Reference-frame comparison sandbox
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/reference-frame-comparison-sandbox-x1428
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing relative motion in different reference frames. Allow selecting a translating frame for a few moving objects; update relative velocities and paths without introducing fictitious acceleration when the chosen frame moves at constant velocity. Voxel style.
Working Three.js Starter (reference-frame-comparison-sandbox-x1428):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Relative Motion Lab</title>
<style>
:root {
--bg: #071017;
--panel: rgba(8, 20, 28, 0.94);
--panel-solid: #0a1922;
--line: #27404d;
--line-bright: #416274;
--text: #e4f2f6;
--muted: #7f9ba7;
--cyan: #30d5c8;
--orange: #ff9f43;
--purple: #b794f4;
--yellow: #ffd166;
--blue: #4cc9f0;
--pink: #f15bb5;
--green: #72e6a2;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
}
button,
select,
input {
font: inherit;
}
button,
select {
color: var(--text);
border: 1px solid var(--line-bright);
border-radius: 0;
background: #0d222d;
}
button {
cursor: pointer;
box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.45);
}
button:hover {
border-color: var(--cyan);
color: var(--cyan);
}
button:active {
transform: translate(2px, 2px);
box-shadow: 1px 1px 0 rgba(0, 0, 0, 0.45);
}
select {
width: 100%;
padding: 8px 28px 8px 9px;
appearance: none;
background-image:
linear-gradient(45deg, transparent 50%, var(--muted) 50%),
linear-gradient(135deg, var(--muted) 50%, transparent 50%);
background-position:
calc(100% - 14px) 14px,
calc(100% - 9px) 14px;
background-size: 5px 5px, 5px 5px;
background-repeat: no-repeat;
cursor: pointer;
}
select:focus,
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
touch-action: none;
}
.hud {
position: fixed;
z-index: 5;
top: 18px;
left: 18px;
width: min(365px, calc(100vw - 36px));
pointer-events: none;
background: rgba(7, 18, 25, 0.84);
border: 1px solid var(--line);
box-shadow: 6px 6px 0 rgba(0, 0, 0, 0.35);
backdrop-filter: blur(8px);
}
.hud-head {
padding: 13px 15px 11px;
border-bottom: 1px solid var(--line);
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: bold;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.hud h1 {
margin: 7px 0 0;
font-size: clamp(22px, 3vw, 31px);
line-height: 1;
letter-spacing: -0.06em;
}
.hud-subtitle {
margin-top: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.hud-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1px;
background: var(--line);
}
.hud-metric {
min-height: 67px;
padding: 10px 14px;
background: rgba(9, 25, 33, 0.94);
}
.hud-metric span {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.hud-metric strong {
display: block;
font-size: 14px;
line-height: 1.35;
}
.hud-metric small {
color: var(--muted);
font-size: 9px;
font-weight: normal;
}
.hud-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 14px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.time-readout {
color: var(--text);
font-size: 14px;
white-space: nowrap;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
bottom: 18px;
width: 390px;
overflow-y: auto;
background: var(--panel);
border: 1px solid var(--line-bright);
box-shadow: 8px 8px 0 rgba(0, 0, 0, 0.42);
backdrop-filter: blur(12px);
scrollbar-color: var(--line-bright) var(--panel-solid);
scrollbar-width: thin;
}
.panel::-webkit-scrollbar {
width: 9px;
}
.panel::-webkit-scrollbar-track {
background: var(--panel-solid);
}
.panel::-webkit-scrollbar-thumb {
background: var(--line-bright);
border: 2px solid var(--panel-solid);
}
.panel-header {
padding: 17px 17px 15px;
border-bottom: 1px solid var(--line);
background:
linear-gradient(135deg, rgba(48, 213, 200, 0.08), transparent 55%),
var(--panel-solid);
}
.panel-title {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-top: 7px;
}
.panel-title h2 {
margin: 0;
font-size: 17px;
letter-spacing: -0.04em;
}
.unit-tag {
color: var(--muted);
font-size: 9px;
white-space: nowrap;
}
.control-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
.control-grid button {
min-height: 36px;
padding: 8px;
font-size: 10px;
font-weight: bold;
letter-spacing: 0.07em;
}
.primary-button {
color: #041512 !important;
background: var(--cyan) !important;
border-color: var(--cyan) !important;
}
.primary-button:hover {
color: #041512 !important;
background: #67eee4 !important;
}
.speed-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 10px;
margin-top: 12px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.speed-value {
min-width: 34px;
color: var(--text);
text-align: right;
}
.panel-section {
padding: 15px 16px;
border-bottom: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
color: var(--muted);
font-size: 9px;
font-weight: bold;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.section-title::after {
content: "";
flex: 1;
height: 1px;
margin-left: 10px;
background: var(--line);
}
.object-card {
position: relative;
margin-bottom: 10px;
padding: 12px;
background: rgba(13, 34, 45, 0.72);
border: 1px solid var(--line);
transition: border-color 120ms ease, background 120ms ease;
}
.object-card:last-child {
margin-bottom: 0;
}
.object-card.selected {
border-color: var(--object-color);
background: rgba(18, 43, 55, 0.9);
box-shadow: inset 4px 0 0 var(--object-color);
}
.card-top {
display: grid;
grid-template-columns: 1fr 132px;
align-items: center;
gap: 10px;
margin-bottom: 10px;
}
.object-name {
display: flex;
align-items: center;
gap: 8px;
padding: 0;
border: 0;
background: none;
box-shadow: none;
color: var(--text);
font-size: 11px;
font-weight: bold;
text-align: left;
}
.object-name:hover {
color: var(--text);
}
.swatch {
width: 11px;
height: 11px;
flex: 0 0 auto;
background: var(--object-color);
box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.45);
}
.card-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1px;
background: var(--line);
border: 1px solid var(--line);
}
.card-metric {
min-width: 0;
padding: 8px 9px;
background: rgba(5, 16, 22, 0.78);
}
.card-metric span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.card-metric strong {
display: block;
overflow: hidden;
font-size: 11px;
font-weight: normal;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-equation {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 9px;
color: var(--muted);
font-size: 8px;
line-height: 1.4;
}
.card-equation span:last-child {
color: var(--green);
text-align: right;
}
.registry {
width: 100%;
border-collapse: collapse;
font-size: 9px;
}
.registry th {
padding: 7px 5px;
color: var(--muted);
font-size: 8px;
font-weight: normal;
letter-spacing: 0.08em;
text-align: right;
text-transform: uppercase;
}
.registry th:first-child,
.registry td:first-child {
text-align: left;
}
.registry td {
padding: 9px 5px;
border-top: 1px solid var(--line);
text-align: right;
}
.registry .frame-name {
font-weight: bold;
}
.registry .watchers {
color: var(--muted);
}
.toggle-row {
display: flex;
flex-wrap: wrap;
gap: 10px 16px;
color: var(--muted);
font-size: 9px;
}
.toggle-row label {
display: flex;
align-items: center;
gap: 7px;
cursor: pointer;
}
.toggle-row input {
accent-color: var(--cyan);
}
.note {
margin: 0;
color: var(--muted);
font-size: 9px;
line-height: 1.65;
}
.note strong {
color: var(--text);
}
.formula {
margin-top: 10px;
padding: 10px;
color: var(--cyan);
background: rgba(48, 213, 200, 0.06);
border-left: 3px solid var(--cyan);
font-size: 10px;
line-height: 1.65;
}
.help {
position: fixed;
z-index: 4;
left: 18px;
bottom: 18px;
max-width: 365px;
padding: 9px 12px;
color: var(--muted);
background: rgba(7, 18, 25, 0.82);
border: 1px solid var(--line);
font-size: 9px;
line-height: 1.55;
pointer-events: none;
}
.help b {
color: var(--text);
}
#loading {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
color: var(--cyan);
background: var(--bg);
font-size: 12px;
letter-spacing: 0.18em;
}
@media (max-width: 800px) {
.hud {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
}
.hud-grid {
grid-template-columns: repeat(4, 1fr);
}
.hud-metric {
min-height: 55px;
padding: 8px;
}
.hud-metric strong {
font-size: 10px;
}
.hud-footer {
display: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 45vh;
}
.help {
display: none;
}
}
@media (max-width: 520px) {
.hud-grid {
grid-template-columns: 1fr 1fr;
}
.hud-subtitle {
display: none;
}
.panel-header,
.panel-section {
padding-left: 12px;
padding-right: 12px;
}
.card-top {
grid-template-columns: 1fr 120px;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive voxel relative-motion simulation"></div>
<section class="hud" aria-live="polite">
<div class="hud-head">
<div class="eyebrow">Voxel Kinematics Laboratory</div>
<h1>RELATIVE MOTION</h1>
<div class="hud-subtitle">
Choose a translating observer for each object. Velocity and path
measurements are transformed analytically in real time.
</div>
</div>
<div class="hud-grid">
<div class="hud-metric">
<span>Selected object</span>
<strong id="hudObject">RUNNER X</strong>
<small id="hudObserver">Observer: FRAME A</small>
</div>
<div class="hud-metric">
<span>Relative velocity</span>
<strong id="hudRelativeVelocity">+0.00, +0.00</strong>
<small>m/s in observer coordinates</small>
</div>
<div class="hud-metric">
<span>Relative acceleration</span>
<strong id="hudRelativeAcceleration">0.00, 0.00</strong>
<small>m/s² — no pseudo-acceleration</small>
</div>
<div class="hud-metric">
<span>Current displacement</span>
<strong id="hudRelativePosition">+0.00, +0.00</strong>
<small>m from observer to object</small>
</div>
</div>
<div class="hud-footer">
<span>
Orange: X Cyan: Y Purple: Z<br />
Hollow markers are translating reference frames.
</span>
<span class="time-readout" id="timeReadout">00:00.0</span>
</div>
</section>
<aside class="panel">
<header class="panel-header">
<div class="eyebrow">Simulation Control</div>
<div class="panel-title">
<h2>Frame Assignment</h2>
<span class="unit-tag">SI UNITS · m, s</span>
</div>
<div class="control-grid">
<button id="playButton" class="primary-button" type="button">PAUSE</button>
<button id="resetButton" type="button">RESET TIME</button>
<button id="cameraButton" type="button">RESET CAMERA</button>
<button id="zoomInButton" type="button">ZOOM +</button>
</div>
<div class="speed-row">
<label for="speedInput">TIME SCALE</label>
<input id="speedInput" type="range" min="0.25" max="3" step="0.25" value="1" />
<span class="speed-value" id="speedValue">1.00×</span>
</div>
</header>
<section class="panel-section">
<div class="section-title">Per-object observer</div>
<div id="objectCards"></div>
</section>
<section class="panel-section">
<div class="section-title">Available frames</div>
<table class="registry">
<thead>
<tr>
<th>Frame</th>
<th>vₓ</th>
<th>v_z</th>
<th>a</th>
<th>Used</th>
</tr>
</thead>
<tbody id="frameRegistry"></tbody>
</table>
</section>
<section class="panel-section">
<div class="section-title">Display layers</div>
<div class="toggle-row">
<label><input id="trailsToggle" type="checkbox" checked /> Lab trails</label>
<label><input id="pathsToggle" type="checkbox" checked /> Relative paths</label>
<label><input id="vectorsToggle" type="checkbox" checked /> Velocity vectors</label>
</div>
</section>
<section class="panel-section">
<div class="section-title">Inertial-frame accounting</div>
<p class="note">
Every moving frame has a <strong>constant LAB velocity</strong>.
Relative velocity is calculated directly from the velocities, rather
than by differentiating displayed positions. The relative acceleration
is therefore the actual difference in accelerations, with no fictitious
term introduced by changing observers.
</p>
<div class="formula">
v<sub>rel</sub> = v<sub>obj</sub> − v<sub>frame</sub><br />
a<sub>rel</sub> = a<sub>obj</sub> − a<sub>frame</sub><br />
r<sub>rel</sub>(t) = r<sub>rel</sub>(0) + v<sub>rel</sub>t
</div>
</section>
<section class="panel-section">
<div class="section-title">Interaction</div>
<p class="note">
Drag to orbit. Shift-drag or right-drag to pan. Scroll to zoom.
Click a voxel object to inspect it, or click a hollow frame marker
to assign that frame to the selected object. Keyboard:
<strong>Space</strong> pause, <strong>R</strong> reset,
<strong>C</strong> reset camera, <strong>1–3</strong> select object.
</p>
</section>
</aside>
<div class="help">
<b>LEFT DRAG</b> orbit · <b>SHIFT/RIGHT DRAG</b> pan ·
<b>WHEEL</b> zoom · <b>CLICK</b> select object/frame
</div>
<div id="loading">INITIALIZING VOXEL LAB...</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const V3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
const PATH_DURATION = 18;
const PATH_STEPS = 72;
const MAX_TRAIL_POINTS = 700;
const OBJECT_FLOOR_Y = -0.195;
const FRAME_FLOOR_Y = -0.35;
const frameDefinitions = {
LAB: {
id: "LAB",
name: "LAB / INERTIAL",
short: "LAB",
color: "#8fa3b0",
color3: 0x8fa3b0,
pos0: V3(0, 0, 0),
vel: V3(0, 0, 0),
acc: V3(0, 0, 0)
},
A: {
id: "A",
name: "FRAME A",
short: "A",
color: "#ffd166",
color3: 0xffd166,
pos0: V3(-10, 0, -6),
vel: V3(1.6, 0, 0.25),
acc: V3(0, 0, 0)
},
B: {
id: "B",
name: "FRAME B",
short: "B",
color: "#4cc9f0",
color3: 0x4cc9f0,
pos0: V3(10, 0, -6),
vel: V3(-0.45, 0, 1.1),
acc: V3(0, 0, 0)
},
C: {
id: "C",
name: "FRAME C",
short: "C",
color: "#f15bb5",
color3: 0xf15bb5,
pos0: V3(0, 0, 7),
vel: V3(0.75, 0, -0.65),
acc: V3(0, 0, 0)
}
};
const objectDefinitions = [
{
id: "X",
name: "RUNNER X",
short: "X",
color: "#ff9f43",
accent: "#ffe0a3",
color3: 0xff9f43,
accent3: 0xffe0a3,
pos0: V3(-6, 0, -2),
vel: V3(0.4, 0, 0.8),
acc: V3(0, 0, 0),
observer: "A",
voxels: [
{ x: -0.64, y: 0, z: 0 },
{ x: -0.32, y: 0, z: 0 },
{ x: 0, y: 0, z: 0, accent: true },
{ x: 0.32, y: 0, z: 0 },
{ x: -0.32, y: 0.32, z: 0 },
{ x: 0, y: 0.32, z: 0, accent: true },
{ x: 0, y: 0, z: 0.32, accent: true }
]
},
{
id: "Y",
name: "PACKET Y",
short: "Y",
color: "#30d5c8",
accent: "#b9fff8",
color3: 0x30d5c8,
accent3: 0xb9fff8,
pos0: V3(0, 0, 1),
vel: V3(1.2, 0, -0.35),
acc: V3(0, 0, 0),
observer: "LAB",
voxels: [
{ x: -0.32, y: 0, z: -0.32 },
{ x: 0.32, y: 0, z: -0.32 },
{ x: -0.32, y: 0, z: 0.32 },
{ x: 0.32, y: 0, z: 0.32, accent: true },
{ x: 0, y: 0.32, z: 0, accent: true },
{ x: 0, y: 0.64, z: 0 }
]
},
{
id: "Z",
name: "CARGO Z",
short: "Z",
color: "#b794f4",
accent: "#eadfff",
color3: 0xb794f4,
accent3: 0xeadfff,
pos0: V3(6, 0, 3),
vel: V3(-0.55, 0, 0.7),
acc: V3(0, 0, 0),
observer: "B",
voxels: [
{ x: 0, y: 0, z: 0 },
{ x: 0.32, y: 0, z: 0 },
{ x: 0, y: 0, z: 0.32 },
{ x: 0.32, y: 0, z: 0.32 },
{ x: 0.32, y: 0.32, z: 0.32, accent: true },
{ x: 0.64, y: 0, z: 0.64, accent: true }
]
}
];
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const loading = document.getElementById("loading");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071017);
scene.fog = new THREE.FogExp2(0x071017, 0.022);
const camera = new THREE.PerspectiveCamera(
44,
window.innerWidth / window.innerHeight,
0.1,
150
);
const hemisphere = new THREE.HemisphereLight(0xc8f5ff, 0x071017, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.2);
sun.position.set(9, 15, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -22;
sun.shadow.camera.right = 22;
sun.shadow.camera.top = 20;
sun.shadow.camera.bottom = -20;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 50;
sun.shadow.bias = -0.00025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x4cc9f0, 1.3);
rimLight.position.set(-12, 7, -9);
scene.add(rimLight);
// Voxel ground.
const groundBase = new THREE.Mesh(
new THREE.BoxGeometry(34, 0.25, 26),
new THREE.MeshStandardMaterial({
color: 0x071219,
roughness: 0.94,
metalness: 0.05
})
);
groundBase.position.y = -0.56;
groundBase.receiveShadow = true;
scene.add(groundBase);
const tileGeometry = new THREE.BoxGeometry(0.92, 0.08, 0.92);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.88,
metalness: 0.08
});
const tileColumns = 33;
const tileRows = 25;
const tileMesh = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileColumns * tileRows
);
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let z = 0; z < tileRows; z++) {
for (let x = 0; x < tileColumns; x++) {
dummy.position.set(x - 16, -0.395, z - 12);
dummy.updateMatrix();
tileMesh.setMatrixAt(tileIndex, dummy.matrix);
const checker = (x + z) & 1;
tileColor.setHex(checker ? 0x10242d : 0x0c1c24);
tileMesh.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tileMesh.instanceMatrix.needsUpdate = true;
if (tileMesh.instanceColor) tileMesh.instanceColor.needsUpdate = true;
tileMesh.receiveShadow = true;
scene.add(tileMesh);
// Lab coordinate axes.
const labXAxis = new THREE.ArrowHelper(
V3(1, 0, 0),
V3(0, -0.26, 0),
3.4,
0xff6677,
0.45,
0.25
);
const labZAxis = new THREE.ArrowHelper(
V3(0, 0, 1),
V3(0, -0.26, 0),
3.4,
0x4cc9f0,
0.45,
0.25
);
scene.add(labXAxis, labZAxis);
// -------------------------------------------------------------------------
// Procedural labels
// -------------------------------------------------------------------------
function makeTextSprite(text, color, scale = 1) {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 80;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 15, 21, 0.88)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = color;
context.lineWidth = 5;
context.strokeRect(3, 3, canvas.width - 6, canvas.height - 6);
context.fillStyle = color;
context.font = "bold 38px 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(2.3 * scale, 0.575 * scale, 1);
sprite.renderOrder = 20;
return sprite;
}
const xAxisLabel = makeTextSprite("LAB +X", "#ff6677", 0.8);
xAxisLabel.position.set(3.7, 0.05, 0);
scene.add(xAxisLabel);
const zAxisLabel = makeTextSprite("LAB +Z", "#4cc9f0", 0.8);
zAxisLabel.position.set(0, 0.05, 3.7);
scene.add(zAxisLabel);
// -------------------------------------------------------------------------
// Voxel objects
// -------------------------------------------------------------------------
const clickMeshes = [];
function createVoxelObject(definition) {
const group = new THREE.Group();
group.userData.objectId = definition.id;
const baseMaterial = new THREE.MeshStandardMaterial({
color: definition.color3,
emissive: definition.color3,
emissiveIntensity: 0.08,
roughness: 0.58,
metalness: 0.18,
flatShading: true
});
const accentMaterial = new THREE.MeshStandardMaterial({
color: definition.accent3,
emissive: definition.accent3,
emissiveIntensity: 0.06,
roughness: 0.48,
metalness: 0.12,
flatShading: true
});
const cubeGeometry = new THREE.BoxGeometry(0.32, 0.32, 0.32);
for (const voxel of definition.voxels) {
const material = voxel.accent ? accentMaterial : baseMaterial;
const cube = new THREE.Mesh(cubeGeometry, material);
cube.position.set(voxel.x, voxel.y, voxel.z);
cube.castShadow = true;
cube.receiveShadow = true;
cube.userData.objectId = definition.id;
group.add(cube);
clickMeshes.push(cube);
}
const label = makeTextSprite(definition.short, definition.color, 0.62);
label.position.set(0, 1.55, 0);
group.add(label);
scene.add(group);
const velocityArrow = new THREE.ArrowHelper(
definition.vel.clone().normalize(),
V3(),
2,
definition.color3,
0.38,
0.22
);
velocityArrow.line.material.transparent = true;
velocityArrow.line.material.opacity = 0.72;
velocityArrow.cone.material.transparent = true;
velocityArrow.cone.material.opacity = 0.82;
scene.add(velocityArrow);
return {
group,
baseMaterial,
accentMaterial,
velocityArrow,
currentPos: definition.pos0.clone()
};
}
for (const definition of objectDefinitions) {
definition.visual = createVoxelObject(definition);
definition.currentPos = definition.visual.currentPos;
}
// -------------------------------------------------------------------------
// Translating frame markers
// -------------------------------------------------------------------------
function createFrameMarker(definition) {
const group = new THREE.Group();
group.userData.frameId = definition.id;
const boxGeometry = new THREE.BoxGeometry(1.1, 1.1, 1.1);
const edgeMaterial = new THREE.LineBasicMaterial({
color: definition.color3,
transparent: true,
opacity: 0.72,
depthTest: true
});
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(boxGeometry),
edgeMaterial
);
edges.position.y = 0.55;
group.add(edges);
const centerMaterial = new THREE.MeshStandardMaterial({
color: definition.color3,
emissive: definition.color3,
emissiveIntensity: 0.35,
roughness: 0.42,
metalness: 0.2
});
const center = new THREE.Mesh(
new THREE.BoxGeometry(0.22, 0.22, 0.22),
centerMaterial
);
center.position.y = 0.55;
center.castShadow = true;
group.add(center);
const cornerGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
const cornerOffsets = [
[-0.55, 0, -0.55],
[0.55, 0, -0.55],
[-0.55, 0, 0.55],
[0.55, 0, 0.55]
];
for (const [x, y, z] of cornerOffsets) {
const corner = new THREE.Mesh(cornerGeometry, centerMaterial);
corner.position.set(x, y, z);
group.add(corner);
}
const label = makeTextSprite(definition.short, definition.color, 0.65);
label.position.set(0, 1.55, 0);
group.add(label);
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
hitMaterial.colorWrite = false;
const hitBox = new THREE.Mesh(
new THREE.BoxGeometry(1.45, 1.45, 1.45),
hitMaterial
);
hitBox.position.y = 0.55;
hitBox.userData.frameId = definition.id;
group.add(hitBox);
clickMeshes.push(hitBox);
scene.add(group);
const velocityArrow = new THREE.ArrowHelper(
definition.vel.clone().normalize(),
V3(),
2.3,
definition.color3,
0.4,
0.22
);
velocityArrow.line.material.transparent = true;
velocityArrow.line.material.opacity = 0.78;
velocityArrow.cone.material.transparent = true;
velocityArrow.cone.material.opacity = 0.85;
scene.add(velocityArrow);
return {
group,
edgeMaterial,
centerMaterial,
velocityArrow,
currentPos: definition.pos0.clone()
};
}
for (const definition of Object.values(frameDefinitions)) {
definition.visual = createFrameMarker(definition);
definition.currentPos = definition.visual.currentPos;
}
// -------------------------------------------------------------------------
// Trails, relative paths, and vectors
// -------------------------------------------------------------------------
function createTrail(color, opacity = 0.8) {
const positions = new Float32Array(MAX_TRAIL_POINTS * 3);
const geometry = new THREE.BufferGeometry();
const attribute = new THREE.BufferAttribute(positions, 3);
attribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute("position", attribute);
geometry.setDrawRange(0, 0);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
scene.add(line);
return {
line,
geometry,
attribute,
positions,
count: 0
};
}
function appendTrail(trail, point) {
if (trail.count < MAX_TRAIL_POINTS) {
const index = trail.count * 3;
trail.positions[index] = point.x;
trail.positions[index + 1] = point.y;
trail.positions[index + 2] = point.z;
trail.count++;
} else {
trail.positions.copyWithin(0, 3);
const index = (MAX_TRAIL_POINTS - 1) * 3;
trail.positions[index] = point.x;
trail.positions[index + 1] = point.y;
trail.positions[index + 2] = point.z;
}
trail.attribute.needsUpdate = true;
trail.geometry.setDrawRange(0, trail.count);
}
function clearTrail(trail) {
trail.count = 0;
trail.geometry.setDrawRange(0, 0);
trail.attribute.needsUpdate = true;
}
for (const definition of objectDefinitions) {
definition.trail = createTrail(definition.color3, 0.88);
}
for (const definition of Object.values(frameDefinitions)) {
definition.trail = createTrail(definition.color3, 0.46);
}
function createRelativePath(color) {
const positions = new Float32Array((PATH_STEPS + 1) * 3);
const geometry = new THREE.BufferGeometry();
const attribute = new THREE.BufferAttribute(positions, 3);
attribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute("position", attribute);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.85,
depthTest: true,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
scene.add(line);
return { line, geometry, attribute, positions };
}
for (const definition of objectDefinitions) {
definition.relativePath = createRelativePath(definition.color3);
}
const connectorGeometry = new THREE.BufferGeometry();
connectorGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
connectorGeometry.setAttribute(
"lineDistance",
new THREE.BufferAttribute(new Float32Array(2), 1)
);
const displacementLine = new THREE.Line(
connectorGeometry,
new THREE.LineDashedMaterial({
color: 0xeafcff,
dashSize: 0.25,
gapSize: 0.15,
transparent: true,
opacity: 0.9,
depthTest: false
})
);
displacementLine.frustumCulled = false;
displacementLine.renderOrder = 15;
scene.add(displacementLine);
const relativeVelocityArrow = new THREE.ArrowHelper(
V3(1, 0, 0),
V3(),
2,
0xffffff,
0.42,
0.24
);
relativeVelocityArrow.line.material.depthTest = false;
relativeVelocityArrow.cone.material.depthTest = false;
relativeVelocityArrow.renderOrder = 16;
scene.add(relativeVelocityArrow);
const observerXAxis = new THREE.ArrowHelper(
V3(1, 0, 0),
V3(),
1.35,
0xff6677,
0.24,
0.15
);
const observerZAxis = new THREE.ArrowHelper(
V3(0, 0, 1),
V3(),
1.35,
0x4cc9f0,
0.24,
0.15
);
scene.add(observerXAxis, observerZAxis);
// -------------------------------------------------------------------------
// UI construction
// -------------------------------------------------------------------------
const objectCards = {};
const objectCardsHost = document.getElementById("objectCards");
for (const definition of objectDefinitions) {
const card = document.createElement("article");
card.className = "object-card";
card.style.setProperty("--object-color", definition.color);
card.dataset.objectId = definition.id;
card.innerHTML = `
<div class="card-top">
<button class="object-name" type="button">
<span class="swatch"></span>
${definition.name}
</button>
<select aria-label="Observer frame for ${definition.name}">
${Object.values(frameDefinitions)
.map(
(frame) =>
`<option value="${frame.id}">${frame.name}</option>`
)
.join("")}
</select>
</div>
<div class="card-metrics">
<div class="card-metric">
<span>LAB velocity</span>
<strong data-field="labVelocity"></strong>
</div>
<div class="card-metric">
<span>Frame velocity</span>
<strong data-field="frameVelocity"></strong>
</div>
<div class="card-metric">
<span>Relative velocity</span>
<strong data-field="relativeVelocity"></strong>
</div>
<div class="card-metric">
<span>Relative speed</span>
<strong data-field="relativeSpeed"></strong>
</div>
<div class="card-metric">
<span>Relative acceleration</span>
<strong data-field="relativeAcceleration"></strong>
</div>
<div class="card-metric">
<span>Relative position</span>
<strong data-field="relativePosition"></strong>
</div>
</div>
<div class="card-equation">
<span>18 s relative path</span>
<span data-field="pathSummary"></span>
</div>
`;
const select = card.querySelector("select");
select.value = definition.observer;
select.addEventListener("change", (event) => {
definition.observer = event.target.value;
selectedObjectId = definition.id;
updateUI();
});
card.querySelector(".object-name").addEventListener("click", () => {
selectedObjectId = definition.id;
updateUI();
});
card.addEventListener("pointerdown", (event) => {
if (event.target.tagName !== "SELECT") {
selectedObjectId = definition.id;
}
});
objectCardsHost.appendChild(card);
objectCards[definition.id] = {
element: card,
select,
fields: Object.fromEntries(
[...card.querySelectorAll("[data-field]")].map((element) => [
element.dataset.field,
element
])
)
};
}
const frameRegistry = document.getElementById("frameRegistry");
const registryRows = {};
for (const definition of Object.values(frameDefinitions)) {
const row = document.createElement("tr");
row.innerHTML = `
<td class="frame-name" style="color:${definition.color}">
${definition.short}
</td>
<td>${definition.vel.x.toFixed(2)}</td>
<td>${definition.vel.z.toFixed(2)}</td>
<td>0.00</td>
<td class="watchers">0</td>
`;
frameRegistry.appendChild(row);
registryRows[definition.id] = row.querySelector(".watchers");
}
const hudObject = document.getElementById("hudObject");
const hudObserver = document.getElementById("hudObserver");
const hudRelativeVelocity = document.getElementById("hudRelativeVelocity");
const hudRelativeAcceleration = document.getElementById(
"hudRelativeAcceleration"
);
const hudRelativePosition = document.getElementById("hudRelativePosition");
const timeReadout = document.getElementById("timeReadout");
const playButton = document.getElementById("playButton");
const resetButton = document.getElementById("resetButton");
const cameraButton = document.getElementById("cameraButton");
const zoomInButton = document.getElementById("zoomInButton");
const speedInput = document.getElementById("speedInput");
const speedValue = document.getElementById("speedValue");
const trailsToggle = document.getElementById("trailsToggle");
const pathsToggle = document.getElementById("pathsToggle");
const vectorsToggle = document.getElementById("vectorsToggle");
let selectedObjectId = "X";
let simTime = 0;
let playing = true;
let timeScale = 1;
let lastTrailSample = -1;
// -------------------------------------------------------------------------
// Formatting and UI updates
// -------------------------------------------------------------------------
function signed(value, digits = 2) {
const normalized = Math.abs(value) < 0.000001 ? 0 : value;
return `${normalized >= 0 ? "+" : ""}${normalized.toFixed(digits)}`;
}
function formatVector(vector) {
return `${signed(vector.x)}, ${signed(vector.z)}`;
}
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const remaining = seconds - minutes * 60;
return `${String(minutes).padStart(2, "0")}:${remaining
.toFixed(1)
.padStart(4, "0")}`;
}
function updateUI() {
for (const definition of objectDefinitions) {
const frame = frameDefinitions[definition.observer];
const card = objectCards[definition.id];
const relativeVelocity = definition.vel.clone().sub(frame.vel);
const relativeAcceleration = definition.acc.clone().sub(frame.acc);
const relativePosition = definition.currentPos.clone().sub(frame.currentPos);
const pathDelta = relativeVelocity.clone().multiplyScalar(PATH_DURATION);
card.element.classList.toggle("selected", definition.id === selectedObjectId);
card.select.value = definition.observer;
card.fields.labVelocity.textContent = `${formatVector(definition.vel)} m/s`;
card.fields.frameVelocity.textContent = `${formatVector(frame.vel)} m/s`;
card.fields.relativeVelocity.textContent = `${formatVector(
relativeVelocity
)} m/s`;
card.fields.relativeSpeed.textContent = `${relativeVelocity.length().toFixed(
2
)} m/s`;
card.fields.relativeAcceleration.textContent = `${formatVector(
relativeAcceleration
)} m/s²`;
card.fields.relativePosition.textContent = `${formatVector(
relativePosition
)} m`;
card.fields.pathSummary.textContent = `Δ ${formatVector(pathDelta)} m · straight`;
const isSelected = definition.id === selectedObjectId;
definition.visual.baseMaterial.emissiveIntensity = isSelected ? 0.38 : 0.08;
definition.visual.accentMaterial.emissiveIntensity = isSelected ? 0.32 : 0.06;
definition.relativePath.line.material.opacity = isSelected ? 0.9 : 0.16;
}
const selectedDefinition = objectDefinitions.find(
(definition) => definition.id === selectedObjectId
);
const selectedFrame = frameDefinitions[selectedDefinition.observer];
const relativeVelocity = selectedDefinition.vel.clone().sub(selectedFrame.vel);
const relativeAcceleration = selectedDefinition.acc.clone().sub(
selectedFrame.acc
);
const relativePosition = selectedDefinition.currentPos.clone().sub(
selectedFrame.currentPos
);
hudObject.textContent = selectedDefinition.name;
hudObserver.textContent = `Observer: ${selectedFrame.name}`;
hudRelativeVelocity.textContent = formatVector(relativeVelocity);
hudRelativeAcceleration.textContent = formatVector(relativeAcceleration);
hudRelativePosition.textContent = formatVector(relativePosition);
timeReadout.textContent = formatTime(simTime);
const usage = {};
for (const definition of objectDefinitions) {
usage[definition.observer] = (usage[definition.observer] || 0) + 1;
}
for (const definition of Object.values(frameDefinitions)) {
registryRows[definition.id].textContent = usage[definition.id] || 0;
const used = (usage[definition.id] || 0) > 0;
const active = selectedDefinition.observer === definition.id;
definition.visual.edgeMaterial.opacity = active ? 1 : used ? 0.78 : 0.36;
definition.visual.centerMaterial.emissiveIntensity = active ? 0.75 : 0.3;
}
}
// -------------------------------------------------------------------------
// Simulation update
// -------------------------------------------------------------------------
function updateRelativePath(definition) {
const frame = frameDefinitions[definition.observer];
const relativeStart = definition.pos0.clone().sub(frame.pos0);
const relativeVelocity = definition.vel.clone().sub(frame.vel);
const path = definition.relativePath;
for (let index = 0; index <= PATH_STEPS; index++) {
const sampleTime = (index / PATH_STEPS) * PATH_DURATION;
const x =
relativeStart.x +
relativeVelocity.x * sampleTime +
frame.currentPos.x;
const z =
relativeStart.z +
relativeVelocity.z * sampleTime +
frame.currentPos.z;
path.positions[index * 3] = x;
path.positions[index * 3 + 1] = -0.325;
path.positions[index * 3 + 2] = z;
}
path.attribute.needsUpdate = true;
path.line.visible = pathsToggle.checked;
}
function updateSimulation(time) {
for (const definition of objectDefinitions) {
definition.currentPos
.copy(definition.pos0)
.addScaledVector(definition.vel, time);
definition.visual.group.position.set(
definition.currentPos.x,
OBJECT_FLOOR_Y,
definition.currentPos.z
);
const arrow = definition.visual.velocityArrow;
const speed = definition.vel.length();
if (speed > 0.0001) {
arrow.visible = vectorsToggle.checked;
arrow.position.set(
definition.currentPos.x,
0.25,
definition.currentPos.z
);
arrow.setDirection(definition.vel.clone().normalize());
arrow.setLength(Math.min(3.2, 0.8 + speed * 0.72), 0.38, 0.22);
} else {
arrow.visible = false;
}
}
for (const definition of Object.values(frameDefinitions)) {
definition.currentPos
.copy(definition.pos0)
.addScaledVector(definition.vel, time);
definition.visual.group.position.set(
definition.currentPos.x,
FRAME_FLOOR_Y,
definition.currentPos.z
);
const arrow = definition.visual.velocityArrow;
const speed = definition.vel.length();
if (speed > 0.0001) {
arrow.visible = vectorsToggle.checked;
arrow.position.set(
definition.currentPos.x,
0.18,
definition.currentPos.z
);
arrow.setDirection(definition.vel.clone().normalize());
arrow.setLength(Math.min(3.2, 0.8 + speed * 0.72), 0.4, 0.22);
} else {
arrow.visible = false;
}
}
if (time - lastTrailSample >= 0.045) {
for (const definition of objectDefinitions) {
appendTrail(
definition.trail,
V3(definition.currentPos.x, -0.31, definition.currentPos.z)
);
}
for (const definition of Object.values(frameDefinitions)) {
appendTrail(
definition.trail,
V3(definition.currentPos.x, -0.29, definition.currentPos.z)
);
}
lastTrailSample = time;
}
for (const definition of objectDefinitions) {
definition.trail.line.visible = trailsToggle.checked;
updateRelativePath(definition);
}
for (const definition of Object.values(frameDefinitions)) {
definition.trail.line.visible = trailsToggle.checked;
}
const selectedDefinition = objectDefinitions.find(
(definition) => definition.id === selectedObjectId
);
const selectedFrame = frameDefinitions[selectedDefinition.observer];
const relativePosition = selectedDefinition.currentPos.clone().sub(
selectedFrame.currentPos
);
const relativeVelocity = selectedDefinition.vel.clone().sub(
selectedFrame.vel
);
const connectorPositions =
connectorGeometry.getAttribute("position");
connectorPositions.setXYZ(
0,
selectedFrame.currentPos.x,
-0.18,
selectedFrame.currentPos.z
);
connectorPositions.setXYZ(
1,
selectedDefinition.currentPos.x,
-0.18,
selectedDefinition.currentPos.z
);
connectorPositions.needsUpdate = true;
const distances = connectorGeometry.getAttribute("lineDistance");
distances.setX(0, 0);
distances.setX(1, relativePosition.length());
distances.needsUpdate = true;
if (relativeVelocity.lengthSq() > 0.000001) {
relativeVelocityArrow.visible = vectorsToggle.checked;
relativeVelocityArrow.position.set(
selectedFrame.currentPos.x,
0.9,
selectedFrame.currentPos.z
);
relativeVelocityArrow.setDirection(relativeVelocity.clone().normalize());
relativeVelocityArrow.setLength(
Math.min(3.7, 0.75 + relativeVelocity.length() * 0.8),
0.42,
0.24
);
} else {
relativeVelocityArrow.visible = false;
}
observerXAxis.position.set(
selectedFrame.currentPos.x,
-0.15,
selectedFrame.currentPos.z
);
observerZAxis.position.copy(observerXAxis.position);
observerXAxis.visible = vectorsToggle.checked;
observerZAxis.visible = vectorsToggle.checked;
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom
// -------------------------------------------------------------------------
const cameraState = {
theta: 0.72,
phi: 1.03,
radius: 28,
target: V3(0, 0, 0)
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.theta = 0.72;
cameraState.phi = 1.03;
cameraState.radius = 28;
cameraState.target.set(0, 0, 0);
updateCamera();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = null;
function pickScene(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(clickMeshes, false);
if (!intersections.length) return;
const hit = intersections[0].object;
if (hit.userData.objectId) {
selectedObjectId = hit.userData.objectId;
updateUI();
} else if (hit.userData.frameId) {
const definition = objectDefinitions.find(
(item) => item.id === selectedObjectId
);
definition.observer = hit.userData.frameId;
objectCards[definition.id].select.value = definition.observer;
updateUI();
}
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = {
x: event.clientX,
y: event.clientY,
button: event.button,
moved: 0
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerDown) return;
const deltaX = event.clientX - pointerDown.x;
const deltaY = event.clientY - pointerDown.y;
pointerDown.moved += Math.abs(deltaX) + Math.abs(deltaY);
pointerDown.x = event.clientX;
pointerDown.y = event.clientY;
const panning = event.shiftKey || pointerDown.button === 2;
if (panning) {
const viewDirection = V3();
camera.getWorldDirection(viewDirection);
const right = V3()
.crossVectors(viewDirection, camera.up)
.normalize();
const forward = V3(-viewDirection.x, 0, -viewDirection.z).normalize();
const panScale = cameraState.radius * 0.0016;
cameraState.target.addScaledVector(right, -deltaX * panScale);
cameraState.target.addScaledVector(forward, deltaY * panScale);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-18,
18
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-14,
14
);
} else {
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.006,
0.25,
1.47
);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerDown) return;
const wasClick =
pointerDown.moved < 7 &&
pointerDown.button === 0 &&
!event.shiftKey;
if (wasClick) pickScene(event);
pointerDown = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = null;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
9,
55
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
function togglePlay() {
playing = !playing;
playButton.textContent = playing ? "PAUSE" : "PLAY";
}
function resetSimulation() {
simTime = 0;
lastTrailSample = -1;
for (const definition of objectDefinitions) {
clearTrail(definition.trail);
}
for (const definition of Object.values(frameDefinitions)) {
clearTrail(definition.trail);
}
updateSimulation(simTime);
updateUI();
}
playButton.addEventListener("click", togglePlay);
resetButton.addEventListener("click", resetSimulation);
cameraButton.addEventListener("click", resetCamera);
zoomInButton.addEventListener("click", () => {
cameraState.radius = Math.max(9, cameraState.radius * 0.84);
updateCamera();
});
speedInput.addEventListener("input", () => {
timeScale = Number(speedInput.value);
speedValue.textContent = `${timeScale.toFixed(2)}×`;
});
trailsToggle.addEventListener("change", updateSimulation.bind(null, simTime));
pathsToggle.addEventListener("change", updateSimulation.bind(null, simTime));
vectorsToggle.addEventListener("change", updateSimulation.bind(null, simTime));
window.addEventListener("keydown", (event) => {
const tag = event.target.tagName;
if (tag === "INPUT" || tag === "SELECT" || tag === "TEXTAREA") return;
if (event.code === "Space") {
event.preventDefault();
togglePlay();
} else if (event.key.toLowerCase() === "r") {
resetSimulation();
} else if (event.key.toLowerCase() === "c") {
resetCamera();
} else if (["1", "2", "3"].includes(event.key)) {
selectedObjectId = objectDefinitions[Number(event.key) - 1].id;
updateUI();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
if (playing) {
simTime += delta * timeScale;
}
updateSimulation(simTime);
updateUI();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
resetCamera();
updateSimulation(0);
updateUI();
renderer.render(scene, camera);
loading.remove();
animate();
</script>
</body>
</html>
```