Prompt specification
Build or customize the Three.js 3D scene "Motion-graph drawing explorer" 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: Motion-graph drawing explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/motion-graph-drawing-explorer-x1408
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Allow choosing a few piecewise-constant acceleration intervals; derive velocity and position consistently and animate the cart with continuity at interval boundaries.
Working Three.js Starter (motion-graph-drawing-explorer-x1408):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Piecewise Acceleration Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #101820;
--panel: #17232d;
--panel-2: #1e2d38;
--line: #304552;
--text: #edf5f7;
--muted: #9db1bc;
--accent: #42d6bd;
--negative: #ff806d;
--neutral: #91a1ad;
}
* {
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,
select {
font: inherit;
}
button,
select,
input[type="number"] {
color: var(--text);
background: #101a22;
border: 1px solid var(--line);
border-radius: 8px;
}
button {
cursor: pointer;
}
button:hover:not(:disabled) {
border-color: var(--accent);
}
button:disabled {
cursor: not-allowed;
opacity: 0.4;
}
.app {
display: grid;
grid-template-columns: 370px minmax(0, 1fr);
width: 100%;
height: 100%;
}
.sidebar {
position: relative;
z-index: 2;
overflow-y: auto;
padding: 22px;
background: var(--panel);
border-right: 1px solid var(--line);
box-shadow: 8px 0 24px rgb(0 0 0 / 20%);
}
h1 {
margin: 0 0 8px;
font-size: 25px;
line-height: 1.1;
}
.intro {
margin: 0 0 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.section-title {
margin: 20px 0 9px;
color: #cfe0e6;
font-size: 12px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
label {
display: grid;
gap: 5px;
color: var(--muted);
font-size: 11px;
}
input[type="number"],
select {
width: 100%;
min-width: 0;
padding: 8px 9px;
outline: none;
}
input[type="number"]:focus,
select:focus {
border-color: var(--accent);
box-shadow: 0 0 0 2px rgb(66 214 189 / 12%);
}
.preset-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-bottom: 12px;
}
.preset-row button {
padding: 7px 9px;
color: #c8d9df;
font-size: 11px;
}
#intervalList {
display: grid;
gap: 9px;
}
.interval {
position: relative;
display: grid;
grid-template-columns: 1fr 1fr 30px;
gap: 9px;
padding: 12px 10px 10px 14px;
overflow: hidden;
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: 10px;
}
.interval::before {
position: absolute;
inset: 0 auto 0 0;
width: 4px;
background: var(--interval-color, var(--neutral));
content: "";
}
.interval.active {
border-color: var(--accent);
box-shadow: 0 0 0 1px rgb(66 214 189 / 20%);
}
.interval label {
color: #a9bdc6;
font-size: 10px;
}
.interval input {
padding: 7px;
}
.remove {
align-self: center;
width: 29px;
height: 29px;
padding: 0;
color: #ffad9f;
font-size: 18px;
line-height: 1;
}
.interval-math {
grid-column: 1 / -1;
display: grid;
gap: 3px;
padding-top: 8px;
border-top: 1px solid rgb(255 255 255 / 7%);
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.45;
}
.interval-math b {
color: #dce9ed;
font-weight: 650;
}
.actions {
display: flex;
gap: 8px;
margin-top: 11px;
}
.actions button {
padding: 9px 12px;
font-size: 12px;
}
#addInterval {
flex: 1;
color: var(--accent);
}
.formula {
padding: 12px;
color: #bfd0d7;
background: #111c24;
border: 1px solid var(--line);
border-radius: 10px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
line-height: 1.55;
}
.formula strong {
color: var(--accent);
}
#plot {
display: block;
width: 100%;
height: 190px;
margin-top: 8px;
background: #111b23;
border: 1px solid var(--line);
border-radius: 10px;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #a8d2df;
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#viewport canvas:active {
cursor: grabbing;
}
.hud {
position: absolute;
top: 16px;
right: 16px;
display: grid;
grid-template-columns: repeat(2, minmax(120px, 1fr));
gap: 8px;
width: min(390px, calc(100% - 32px));
pointer-events: none;
}
.hud-card {
padding: 10px 12px;
background: rgb(13 25 33 / 82%);
border: 1px solid rgb(255 255 255 / 14%);
border-radius: 10px;
box-shadow: 0 6px 20px rgb(0 0 0 / 15%);
backdrop-filter: blur(8px);
}
.hud-label {
display: block;
margin-bottom: 3px;
color: #a9c1cb;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.hud-value {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 15px;
font-weight: 700;
}
.scene-help {
position: absolute;
top: 16px;
left: 16px;
padding: 8px 11px;
color: #d9eef4;
background: rgb(13 25 33 / 70%);
border: 1px solid rgb(255 255 255 / 12%);
border-radius: 8px;
font-size: 11px;
pointer-events: none;
backdrop-filter: blur(7px);
}
.transport {
position: absolute;
right: 16px;
bottom: 16px;
left: 16px;
padding: 12px;
background: rgb(13 25 33 / 88%);
border: 1px solid rgb(255 255 255 / 15%);
border-radius: 12px;
box-shadow: 0 12px 30px rgb(0 0 0 / 22%);
backdrop-filter: blur(10px);
}
.transport-top {
display: flex;
align-items: center;
gap: 8px;
}
.transport button {
min-height: 34px;
padding: 7px 12px;
font-size: 12px;
}
#play {
min-width: 83px;
color: #09251f;
background: var(--accent);
border-color: var(--accent);
font-weight: 750;
}
#speed {
width: 78px;
}
.time-readout {
margin-left: auto;
color: #c8dce3;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
#scrub {
width: 100%;
margin: 12px 0 9px;
accent-color: var(--accent);
cursor: pointer;
}
#segments {
display: flex;
gap: 3px;
height: 25px;
}
.segment {
min-width: 0;
overflow: hidden;
padding: 0 5px;
color: #102029;
border: 0;
border-radius: 5px;
font-size: 9px;
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.segment.active {
outline: 2px solid white;
outline-offset: -2px;
}
@media (max-width: 820px) {
.app {
grid-template-columns: 1fr;
grid-template-rows: 58vh minmax(0, 1fr);
}
.sidebar {
grid-row: 2;
padding: 18px;
border-top: 1px solid var(--line);
border-right: 0;
}
.stage {
grid-row: 1;
}
.scene-help {
display: none;
}
.hud {
top: 10px;
right: 10px;
width: min(350px, calc(100% - 20px));
}
.transport {
right: 10px;
bottom: 10px;
left: 10px;
}
}
</style>
</head>
<body>
<div class="app">
<aside class="sidebar">
<h1>Motion Lab</h1>
<p class="intro">
Choose a piecewise-constant acceleration profile. Velocity and position
are integrated continuously through every interval boundary.
</p>
<div class="section-title">Initial state</div>
<div class="field-grid">
<label>
Initial velocity, m/s
<input id="initialVelocity" type="number" min="-10" max="10"
step="0.1" value="0">
</label>
<label>
Initial position, m
<input id="initialPosition" type="number" min="-50" max="50"
step="0.1" value="0">
</label>
</div>
<div class="section-title">Presets</div>
<div class="preset-row">
<button type="button" data-preset="balanced">Balanced</button>
<button type="button" data-preset="stop">Stop cleanly</button>
<button type="button" data-preset="reverse">Reverse</button>
</div>
<div class="section-title">Acceleration intervals</div>
<div id="intervalList"></div>
<div class="actions">
<button id="addInterval" type="button">+ Add interval</button>
<button id="resetProfile" type="button">Reset</button>
</div>
<div class="section-title">Boundary integration</div>
<div class="formula">
For each interval of duration Δt:<br>
<strong>v(t₀+Δt) = v₀ + aΔt</strong><br>
<strong>x(t₀+Δt) = x₀ + v₀Δt + ½aΔt²</strong><br><br>
The ending velocity and position of one interval become the starting
velocity and position of the next.
</div>
<div class="section-title">Motion plot</div>
<canvas id="plot" aria-label="Acceleration, velocity, and position plot"></canvas>
</aside>
<main class="stage">
<div id="viewport"></div>
<div class="scene-help">
Drag to orbit · Scroll to zoom · Double-click to reset view
</div>
<div class="hud">
<div class="hud-card">
<span class="hud-label">Time</span>
<span id="hudTime" class="hud-value">0.00 s</span>
</div>
<div class="hud-card">
<span class="hud-label">Velocity</span>
<span id="hudVelocity" class="hud-value">0.00 m/s</span>
</div>
<div class="hud-card">
<span class="hud-label">Position</span>
<span id="hudPosition" class="hud-value">0.00 m</span>
</div>
<div class="hud-card">
<span class="hud-label">Acceleration / interval</span>
<span id="hudAcceleration" class="hud-value">+0.00 m/s²</span>
</div>
</div>
<div class="transport">
<div class="transport-top">
<button id="play" type="button">❚❚ Pause</button>
<button id="restart" type="button">↺ Restart</button>
<select id="speed" aria-label="Playback speed">
<option value="0.25">0.25×</option>
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="2">2×</option>
</select>
<span id="timeReadout" class="time-readout">0.00 / 7.50 s</span>
</div>
<input id="scrub" type="range" min="0" max="7.5" step="0.001" value="0"
aria-label="Simulation time">
<div id="segments" aria-label="Acceleration intervals"></div>
</div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.querySelector("#viewport");
const intervalList = document.querySelector("#intervalList");
const initialVelocityInput = document.querySelector("#initialVelocity");
const initialPositionInput = document.querySelector("#initialPosition");
const addIntervalButton = document.querySelector("#addInterval");
const resetProfileButton = document.querySelector("#resetProfile");
const playButton = document.querySelector("#play");
const restartButton = document.querySelector("#restart");
const speedSelect = document.querySelector("#speed");
const scrub = document.querySelector("#scrub");
const segmentsElement = document.querySelector("#segments");
const plot = document.querySelector("#plot");
const hudTime = document.querySelector("#hudTime");
const hudVelocity = document.querySelector("#hudVelocity");
const hudPosition = document.querySelector("#hudPosition");
const hudAcceleration = document.querySelector("#hudAcceleration");
const MAX_INTERVALS = 6;
const MAX_TOTAL_TIME = 30;
const MAX_INTERVAL_TIME = 10;
const WHEEL_RADIUS = 0.28;
const presets = {
balanced: {
velocity: 0,
position: 0,
intervals: [
{ duration: 2.5, acceleration: 1.5 },
{ duration: 2, acceleration: 0 },
{ duration: 3, acceleration: -1.25 }
]
},
stop: {
velocity: 0,
position: 0,
intervals: [
{ duration: 2, acceleration: 2 },
{ duration: 2, acceleration: -2 },
{ duration: 2, acceleration: 0 }
]
},
reverse: {
velocity: 0,
position: 0,
intervals: [
{ duration: 1.5, acceleration: 1 },
{ duration: 1, acceleration: -1 },
{ duration: 1.5, acceleration: -1 }
]
}
};
const state = {
initialVelocity: 0,
initialPosition: 0,
intervals: presets.balanced.intervals.map(interval => ({ ...interval }))
};
let simulation;
let currentTime = 0;
let playing = true;
let playbackSpeed = 1;
let lastCartX = 0;
let wheelAngle = 0;
let uiTimer = 0;
// ----- Three.js scene -----------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xa9d3df);
scene.fog = new THREE.Fog(0xa9d3df, 38, 135);
const camera = new THREE.PerspectiveCamera(
43,
viewport.clientWidth / viewport.clientHeight,
0.1,
300
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(viewport.clientWidth, viewport.clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xe9f7ff, 0x6b7452, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3d8, 2.6);
sun.position.set(12, 24, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -16;
sun.shadow.camera.right = 16;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.00025;
scene.add(sun);
scene.add(sun.target);
const trackGroup = new THREE.Group();
scene.add(trackGroup);
const materials = {
ground: new THREE.MeshStandardMaterial({
color: 0x8ca66f,
roughness: 1,
flatShading: true
}),
ballast: new THREE.MeshStandardMaterial({
color: 0x68716e,
roughness: 1,
flatShading: true
}),
tie: new THREE.MeshStandardMaterial({
color: 0x594b3d,
roughness: 1,
flatShading: true
}),
rail: new THREE.MeshStandardMaterial({
color: 0xb8c3c5,
metalness: 0.65,
roughness: 0.42
}),
post: new THREE.MeshStandardMaterial({
color: 0xf1eee4,
roughness: 0.8,
flatShading: true
}),
hillA: new THREE.MeshStandardMaterial({
color: 0x6f8d64,
roughness: 1,
flatShading: true
}),
hillB: new THREE.MeshStandardMaterial({
color: 0x829b70,
roughness: 1,
flatShading: true
}),
cart: new THREE.MeshStandardMaterial({
color: 0xe35c43,
roughness: 0.6,
flatShading: true
}),
cartDark: new THREE.MeshStandardMaterial({
color: 0x273740,
roughness: 0.55,
metalness: 0.2,
flatShading: true
}),
cargo: new THREE.MeshStandardMaterial({
color: 0xf0b74b,
roughness: 0.7,
flatShading: true
}),
window: new THREE.MeshStandardMaterial({
color: 0x75c5d5,
roughness: 0.2,
metalness: 0.25,
flatShading: true
}),
wheel: new THREE.MeshStandardMaterial({
color: 0x22292d,
roughness: 0.85,
flatShading: true
})
};
const cart = new THREE.Group();
const cartTilt = new THREE.Group();
const wheels = [];
cart.add(cartTilt);
scene.add(cart);
function addBox(parent, size, position, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
addBox(cartTilt, [2.25, 0.34, 1.2], [0, 0.58, 0], materials.cart);
addBox(cartTilt, [0.82, 0.72, 1.02], [0.48, 1.08, 0], materials.cart);
addBox(cartTilt, [0.84, 0.52, 0.94], [-0.58, 1.0, 0], materials.cargo);
addBox(cartTilt, [0.54, 0.27, 1.035], [0.48, 1.19, 0], materials.window);
addBox(cartTilt, [0.03, 0.26, 0.75], [0.9, 1.19, 0], materials.window);
addBox(cartTilt, [1.25, 0.08, 0.08], [-0.2, 0.83, 0.63], materials.cartDark);
addBox(cartTilt, [1.25, 0.08, 0.08], [-0.2, 0.83, -0.63], materials.cartDark);
const wheelGeometry = new THREE.CylinderGeometry(
WHEEL_RADIUS,
WHEEL_RADIUS,
0.2,
10
);
wheelGeometry.rotateX(Math.PI / 2);
for (const x of [-0.72, 0.72]) {
for (const z of [-0.68, 0.68]) {
const wheel = new THREE.Mesh(wheelGeometry, materials.wheel);
wheel.position.set(x, 0.39, z);
wheel.castShadow = true;
cartTilt.add(wheel);
wheels.push(wheel);
}
}
// ----- Physics ------------------------------------------------------------
function clamp(value, minimum, maximum) {
return Math.min(maximum, Math.max(minimum, value));
}
function intervalColor(acceleration) {
if (acceleration > 0.001) return "#42d6bd";
if (acceleration < -0.001) return "#ff806d";
return "#91a1ad";
}
function buildSimulation() {
const boundaries = [{
time: 0,
velocity: state.initialVelocity,
position: state.initialPosition
}];
let time = 0;
let velocity = state.initialVelocity;
let position = state.initialPosition;
for (const interval of state.intervals) {
const startVelocity = velocity;
const startPosition = position;
time += interval.duration;
velocity = startVelocity + interval.acceleration * interval.duration;
position =
startPosition +
startVelocity * interval.duration +
0.5 * interval.acceleration * interval.duration * interval.duration;
boundaries.push({
time,
velocity,
position
});
}
const total = time;
let minX = state.initialPosition;
let maxX = state.initialPosition;
for (const boundary of boundaries) {
minX = Math.min(minX, boundary.position);
maxX = Math.max(maxX, boundary.position);
}
function indexAt(t) {
const clampedTime = clamp(t, 0, total);
for (let i = 0; i < state.intervals.length; i++) {
if (
clampedTime < boundaries[i + 1].time ||
i === state.intervals.length - 1
) {
return i;
}
}
return state.intervals.length - 1;
}
function sample(t) {
const clampedTime = clamp(t, 0, total);
const index = indexAt(clampedTime);
const interval = state.intervals[index];
const start = boundaries[index];
const dt = clampedTime - start.time;
return {
time: clampedTime,
index,
acceleration: interval.acceleration,
velocity: start.velocity + interval.acceleration * dt,
position:
start.position +
start.velocity * dt +
0.5 * interval.acceleration * dt * dt
};
}
return {
total,
boundaries,
indexAt,
sample,
minX,
maxX
};
}
// ----- Track and environment ---------------------------------------------
function clearGroup(group) {
for (const child of [...group.children]) {
group.remove(child);
child.traverse(object => {
if (object.geometry) object.geometry.dispose();
});
}
}
function seededRandomFactory(seed) {
return function () {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
};
}
function buildWorld() {
clearGroup(trackGroup);
const random = seededRandomFactory(92831);
const minX = simulation.minX - 9;
const maxX = simulation.maxX + 9;
const length = Math.max(20, maxX - minX);
const centerX = (minX + maxX) * 0.5;
const ground = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.2, 18),
materials.ground
);
ground.position.set(centerX, -0.19, 0);
ground.receiveShadow = true;
trackGroup.add(ground);
const ballast = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.16, 3.25),
materials.ballast
);
ballast.position.set(centerX, -0.025, 0);
ballast.receiveShadow = true;
trackGroup.add(ballast);
for (const z of [-0.7, 0.7]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.12, 0.1),
materials.rail
);
rail.position.set(centerX, 0.12, z);
rail.castShadow = true;
rail.receiveShadow = true;
trackGroup.add(rail);
}
const tieSpacing = Math.max(1.45, length / 4000);
const tieCount = Math.max(2, Math.ceil(length / tieSpacing));
const ties = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.24, 0.08, 1.85),
materials.tie,
tieCount
);
const matrix = new THREE.Matrix4();
for (let i = 0; i < tieCount; i++) {
matrix.makeTranslation(minX + i * tieSpacing, 0.055, 0);
ties.setMatrixAt(i, matrix);
}
ties.instanceMatrix.needsUpdate = true;
ties.receiveShadow = true;
trackGroup.add(ties);
const postSpacing = Math.max(10, length / 70);
const postCount = Math.max(1, Math.floor(length / postSpacing));
for (let i = 0; i < postCount; i++) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 1.05, 0.12),
materials.post
);
post.position.set(minX + (i + 0.5) * postSpacing, 0.47, 2.3);
post.castShadow = true;
trackGroup.add(post);
}
for (let i = 0; i < 26; i++) {
const radius = 1.7 + random() * 3.8;
const height = 2.2 + random() * 5.2;
const x = minX + ((i + random()) / 26) * length;
const side = i % 2 === 0 ? -1 : 1;
const z = side * (8 + random() * 5);
const hill = new THREE.Mesh(
new THREE.ConeGeometry(1, 1, 5),
i % 3 === 0 ? materials.hillB : materials.hillA
);
hill.scale.set(radius, height, radius);
hill.position.set(x, height * 0.5 - 0.12, z);
hill.rotation.y = random() * Math.PI;
hill.castShadow = true;
hill.receiveShadow = true;
trackGroup.add(hill);
}
}
// ----- UI construction ----------------------------------------------------
function renderIntervalRows() {
intervalList.replaceChildren();
state.intervals.forEach((interval, index) => {
const row = document.createElement("div");
row.className = "interval";
row.dataset.index = String(index);
row.style.setProperty(
"--interval-color",
intervalColor(interval.acceleration)
);
row.innerHTML = `
<label>
Duration, s
<input class="duration" type="number"
min="0.25" max="10" step="0.25"
value="${interval.duration}">
</label>
<label>
Acceleration, m/s²
<input class="acceleration" type="number"
min="-6" max="6" step="0.25"
value="${interval.acceleration}">
</label>
<button class="remove" type="button"
title="Remove interval" aria-label="Remove interval">×</button>
<div class="interval-math"></div>
`;
const durationInput = row.querySelector(".duration");
const accelerationInput = row.querySelector(".acceleration");
durationInput.addEventListener("change", () => {
const otherDuration = state.intervals.reduce(
(sum, item, itemIndex) =>
itemIndex === index ? sum : sum + item.duration,
0
);
const maximum = Math.max(
0.25,
Math.min(
MAX_INTERVAL_TIME,
MAX_TOTAL_TIME - otherDuration
)
);
const value = clamp(
Number(durationInput.value) || 0.25,
0.25,
maximum
);
durationInput.value = value;
state.intervals[index].duration = value;
recompute();
});
accelerationInput.addEventListener("change", () => {
const value = clamp(
Number(accelerationInput.value) || 0,
-6,
6
);
accelerationInput.value = value;
state.intervals[index].acceleration = value;
recompute();
});
row.querySelector(".remove").addEventListener("click", () => {
if (state.intervals.length <= 1) return;
state.intervals.splice(index, 1);
renderIntervalRows();
recompute();
});
intervalList.appendChild(row);
});
}
function refreshIntervalRows() {
[...intervalList.children].forEach((row, index) => {
const interval = state.intervals[index];
const start = simulation.boundaries[index];
const end = simulation.boundaries[index + 1];
row.style.setProperty(
"--interval-color",
intervalColor(interval.acceleration)
);
row.querySelector(".interval-math").innerHTML = `
<span><b>Δv = aΔt</b> ${format(start.velocity)} →
${format(end.velocity)} m/s</span>
<span><b>Δx = v₀Δt + ½aΔt²</b> ${format(start.position)} →
${format(end.position)} m</span>
<span>boundary at t = ${end.time.toFixed(2)} s</span>
`;
});
}
function renderSegments() {
segmentsElement.replaceChildren();
state.intervals.forEach((interval, index) => {
const button = document.createElement("button");
button.type = "button";
button.className = "segment";
button.dataset.index = String(index);
button.style.flexGrow = String(interval.duration);
button.style.background = intervalColor(interval.acceleration);
button.textContent = `${index + 1}: ${interval.acceleration >= 0 ? "+" : ""}${interval.acceleration}`;
button.title =
`Interval ${index + 1}: ${interval.duration} s, ` +
`${interval.acceleration} m/s²`;
button.addEventListener("click", () => {
currentTime = simulation.boundaries[index].time;
playing = false;
updateUI();
});
segmentsElement.appendChild(button);
});
}
function format(value) {
const rounded = Math.abs(value) < 0.0005 ? 0 : value;
return rounded.toFixed(2);
}
function recompute(resetTime = false) {
simulation = buildSimulation();
if (resetTime) {
currentTime = 0;
} else {
currentTime = clamp(currentTime, 0, simulation.total);
}
const sample = simulation.sample(currentTime);
lastCartX = sample.position;
cart.position.x = sample.position;
buildWorld();
refreshIntervalRows();
renderSegments();
scrub.max = String(simulation.total);
scrub.value = String(currentTime);
updateUI();
drawPlot();
}
function updateUI() {
const sample = simulation.sample(currentTime);
const atEnd = currentTime >= simulation.total - 0.0001;
hudTime.textContent = `${sample.time.toFixed(2)} s`;
hudVelocity.textContent = `${format(sample.velocity)} m/s`;
hudPosition.textContent = `${format(sample.position)} m`;
if (atEnd) {
hudAcceleration.textContent = "Complete";
} else {
const acceleration = state.intervals[sample.index].acceleration;
hudAcceleration.textContent =
`${acceleration >= 0 ? "+" : ""}${acceleration.toFixed(2)} m/s² · ` +
`I${sample.index + 1}`;
}
timeReadout.textContent =
`${currentTime.toFixed(2)} / ${simulation.total.toFixed(2)} s`;
scrub.value = String(currentTime);
playButton.textContent = playing
? "❚❚ Pause"
: atEnd
? "↻ Replay"
: "▶ Play";
[...intervalList.children].forEach((row, index) => {
row.classList.toggle(
"active",
!atEnd && index === sample.index
);
});
[...segmentsElement.children].forEach((segment, index) => {
segment.classList.toggle(
"active",
!atEnd && index === sample.index
);
});
}
// ----- Motion plot --------------------------------------------------------
function drawPlot() {
if (!simulation) return;
const width = Math.max(260, plot.clientWidth);
const height = 190;
const pixelRatio = Math.min(window.devicePixelRatio || 1, 2);
plot.width = Math.round(width * pixelRatio);
plot.height = Math.round(height * pixelRatio);
const context = plot.getContext("2d");
context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
context.clearRect(0, 0, width, height);
const left = 43;
const right = 10;
const top = 15;
const panelHeight = 43;
const gap = 10;
const plotWidth = width - left - right;
const samples = [];
const sampleCount = 420;
for (let i = 0; i <= sampleCount; i++) {
const t = simulation.total * i / sampleCount;
samples.push(simulation.sample(t));
}
const maxAcceleration = Math.max(
0.5,
...state.intervals.map(interval => Math.abs(interval.acceleration))
);
const maxVelocity = Math.max(
0.5,
...samples.map(sample => Math.abs(sample.velocity))
);
let minPosition = simulation.minX;
let maxPosition = simulation.maxX;
if (Math.abs(maxPosition - minPosition) < 0.5) {
minPosition -= 1;
maxPosition += 1;
}
const panels = [
{
label: "a",
unit: "m/s²",
color: "#42d6bd",
minimum: -maxAcceleration,
maximum: maxAcceleration
},
{
label: "v",
unit: "m/s",
color: "#ffb65c",
minimum: -maxVelocity,
maximum: maxVelocity
},
{
label: "x",
unit: "m",
color: "#6fc8ff",
minimum: minPosition,
maximum: maxPosition
}
];
function timeToX(time) {
return left + simulation.total === 0
? left
: left + (time / simulation.total) * plotWidth;
}
function valueToY(value, panel, panelTop) {
const range = panel.maximum - panel.minimum || 1;
return (
panelTop +
panelHeight -
((value - panel.minimum) / range) * panelHeight
);
}
panels.forEach((panel, panelIndex) => {
const panelTop = top + panelIndex * (panelHeight + gap);
context.fillStyle = "#0d171e";
context.fillRect(left, panelTop, plotWidth, panelHeight);
context.strokeStyle = "#2a3b47";
context.lineWidth = 1;
for (let tick = 0; tick <= 6; tick++) {
const x = left + (tick / 6) * plotWidth;
context.beginPath();
context.moveTo(x, panelTop);
context.lineTo(x, panelTop + panelHeight);
context.stroke();
}
if (panel.minimum <= 0 && panel.maximum >= 0) {
const zeroY = valueToY(0, panel, panelTop);
context.strokeStyle = "#50636f";
context.beginPath();
context.moveTo(left, zeroY);
context.lineTo(left + plotWidth, zeroY);
context.stroke();
}
context.fillStyle = panel.color;
context.font = "700 11px system-ui";
context.fillText(panel.label, 5, panelTop + 15);
context.fillStyle = "#819aa7";
context.font = "9px system-ui";
context.fillText(panel.maximum.toFixed(1), 3, panelTop + 10);
context.fillText(panel.minimum.toFixed(1), 3, panelTop + panelHeight);
context.strokeStyle = panel.color;
context.lineWidth = 2;
context.beginPath();
if (panelIndex === 0) {
for (let i = 0; i < state.intervals.length; i++) {
const interval = state.intervals[i];
const startTime = simulation.boundaries[i].time;
const endTime = simulation.boundaries[i + 1].time;
const y = valueToY(interval.acceleration, panel, panelTop);
if (i === 0) context.moveTo(timeToX(startTime), y);
else context.lineTo(timeToX(startTime), y);
context.lineTo(timeToX(endTime), y);
}
} else {
const key = panelIndex === 1 ? "velocity" : "position";
samples.forEach((sample, index) => {
const x = timeToX(sample.time);
const y = valueToY(sample[key], panel, panelTop);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
}
context.stroke();
});
const currentX = timeToX(currentTime);
context.strokeStyle = "#ffffff";
context.globalAlpha = 0.75;
context.lineWidth = 1;
context.beginPath();
context.moveTo(currentX, top);
context.lineTo(currentX, top + panels.length * (panelHeight + gap) - gap);
context.stroke();
context.globalAlpha = 1;
context.fillStyle = "#8ea5b1";
context.font = "9px system-ui";
context.fillText("0 s", left, height - 3);
context.textAlign = "right";
context.fillText(`${simulation.total.toFixed(2)} s`, width - right, height - 3);
context.textAlign = "left";
}
// ----- Direct camera controls ---------------------------------------------
let yaw = 0.62;
let pitch = 0.43;
let cameraRadius = 17;
let followX = state.initialPosition;
let dragging = false;
let pointerX = 0;
let pointerY = 0;
const cameraTarget = new THREE.Vector3(
followX,
0.9,
0
);
function updateCamera() {
const horizontalRadius = cameraRadius * Math.cos(pitch);
camera.position.set(
cameraTarget.x + horizontalRadius * Math.sin(yaw),
cameraTarget.y + cameraRadius * Math.sin(pitch),
cameraTarget.z + horizontalRadius * Math.cos(yaw)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
yaw = 0.62;
pitch = 0.43;
cameraRadius = 17;
updateCamera();
}
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 dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
yaw -= dx * 0.006;
pitch = clamp(pitch + dy * 0.005, 0.12, 1.15);
});
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("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraRadius = clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
7,
55
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// ----- UI events ----------------------------------------------------------
initialVelocityInput.addEventListener("change", () => {
state.initialVelocity = clamp(
Number(initialVelocityInput.value) || 0,
-10,
10
);
initialVelocityInput.value = state.initialVelocity;
recompute();
});
initialPositionInput.addEventListener("change", () => {
state.initialPosition = clamp(
Number(initialPositionInput.value) || 0,
-50,
50
);
initialPositionInput.value = state.initialPosition;
recompute();
});
addIntervalButton.addEventListener("click", () => {
const total = state.intervals.reduce(
(sum, interval) => sum + interval.duration,
0
);
if (
state.intervals.length >= MAX_INTERVALS ||
total >= MAX_TOTAL_TIME - 0.25
) {
return;
}
state.intervals.push({
duration: Math.min(2, MAX_TOTAL_TIME - total),
acceleration: 0
});
renderIntervalRows();
recompute();
});
resetProfileButton.addEventListener("click", () => {
const preset = presets.balanced;
state.initialVelocity = preset.velocity;
state.initialPosition = preset.position;
state.intervals = preset.intervals.map(interval => ({ ...interval }));
initialVelocityInput.value = state.initialVelocity;
initialPositionInput.value = state.initialPosition;
renderIntervalRows();
recompute(true);
playing = true;
});
document.querySelectorAll("[data-preset]").forEach(button => {
button.addEventListener("click", () => {
const preset = presets[button.dataset.preset];
state.initialVelocity = preset.velocity;
state.initialPosition = preset.position;
state.intervals = preset.intervals.map(interval => ({ ...interval }));
initialVelocityInput.value = state.initialVelocity;
initialPositionInput.value = state.initialPosition;
renderIntervalRows();
recompute(true);
playing = true;
});
});
playButton.addEventListener("click", () => {
if (currentTime >= simulation.total - 0.0001) {
currentTime = 0;
playing = true;
} else {
playing = !playing;
}
updateUI();
});
restartButton.addEventListener("click", () => {
currentTime = 0;
playing = true;
updateUI();
});
speedSelect.addEventListener("change", () => {
playbackSpeed = Number(speedSelect.value);
});
scrub.addEventListener("input", () => {
currentTime = clamp(Number(scrub.value), 0, simulation.total);
playing = false;
updateUI();
});
// ----- Resize and animation ------------------------------------------------
function resizeRenderer() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
drawPlot();
}
const viewportObserver = new ResizeObserver(resizeRenderer);
viewportObserver.observe(viewport);
const plotObserver = new ResizeObserver(drawPlot);
plotObserver.observe(plot);
renderIntervalRows();
recompute(true);
resetCamera();
let previousTime = performance.now();
renderer.setAnimationLoop(now => {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (playing) {
currentTime = Math.min(
simulation.total,
currentTime + delta * playbackSpeed
);
if (currentTime >= simulation.total) {
playing = false;
}
}
const sample = simulation.sample(currentTime);
const displacement = sample.position - lastCartX;
cart.position.x = sample.position;
wheelAngle -= displacement / WHEEL_RADIUS;
for (const wheel of wheels) {
wheel.rotation.z = wheelAngle;
}
const targetTilt = sample.acceleration * 0.012;
cartTilt.rotation.z +=
(targetTilt - cartTilt.rotation.z) * (1 - Math.exp(-delta * 10));
lastCartX = sample.position;
const followFactor = 1 - Math.exp(-delta * 6);
followX += (sample.position - followX) * followFactor;
cameraTarget.x = followX;
sun.position.x = followX + 12;
sun.target.position.set(followX, 0, 0);
sun.target.updateMatrixWorld();
updateCamera();
uiTimer += delta;
if (uiTimer >= 0.05) {
uiTimer = 0;
updateUI();
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```