Prompt specification
Build or customize the Three.js 3D scene "Same drop different track shape comparison" 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: Same drop different track shape comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/same-drop-different-track-shape-comparison-x1378
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts gravitational and kinetic energy along a track. Release identical balls through two idealized tracks with equal vertical drop; compare final speeds under the same loss assumptions while allowing different travel times. Stylized solid forms.
Working Three.js Starter (same-drop-different-track-shape-comparison-x1378):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gravity Lab — Energy Along Two Tracks</title>
<style>
:root {
--ink: #243044;
--muted: #6f7783;
--paper: #f6f2e9;
--panel: rgba(250, 247, 240, 0.94);
--line: rgba(36, 48, 68, 0.14);
--orange: #ef6b4f;
--teal: #258487;
--gold: #efa53b;
--navy: #2d4059;
--loss: #b7afa2;
--shadow: 0 18px 50px rgba(42, 46, 50, 0.13);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e3d8;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
button {
border: 0;
cursor: pointer;
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 5;
}
.hero {
position: absolute;
top: 24px;
left: 26px;
max-width: 510px;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
color: #596474;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 25px;
height: 3px;
border-radius: 3px;
background: var(--orange);
}
h1 {
margin: 0;
font-size: clamp(29px, 3vw, 47px);
line-height: 0.98;
letter-spacing: -0.055em;
font-weight: 850;
}
.hero p {
max-width: 450px;
margin: 13px 0 0;
color: #596474;
font-size: 14px;
line-height: 1.55;
}
.top-actions {
position: absolute;
top: 24px;
right: 24px;
display: flex;
gap: 8px;
pointer-events: auto;
}
.control,
.view-button {
min-height: 40px;
padding: 0 14px;
border: 1px solid rgba(36, 48, 68, 0.13);
border-radius: 12px;
background: rgba(250, 247, 240, 0.88);
box-shadow: 0 7px 22px rgba(45, 48, 50, 0.08);
font-size: 12px;
font-weight: 750;
transition: transform 140ms ease, background 140ms ease;
}
.control:hover,
.view-button:hover {
transform: translateY(-1px);
background: #fffaf1;
}
.control.primary {
min-width: 86px;
color: white;
background: var(--ink);
border-color: var(--ink);
}
.panel {
border: 1px solid rgba(36, 48, 68, 0.12);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.energy-panel {
position: absolute;
top: 92px;
right: 24px;
width: 318px;
padding: 17px;
pointer-events: auto;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.panel-heading h2 {
margin: 0 0 4px;
font-size: 14px;
letter-spacing: -0.015em;
}
.panel-heading p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.live-dot {
display: flex;
align-items: center;
gap: 6px;
margin-top: 2px;
color: #68717e;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
white-space: nowrap;
}
.live-dot::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: #42a66d;
box-shadow: 0 0 0 4px rgba(66, 166, 109, 0.12);
}
.energy-card {
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.45);
}
.energy-card + .energy-card { margin-top: 10px; }
.energy-title {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
font-size: 12px;
font-weight: 800;
}
.lane-badge {
display: inline-grid;
place-items: center;
width: 22px;
height: 22px;
border-radius: 7px;
color: white;
font-size: 10px;
font-weight: 900;
}
.badge-a { background: var(--orange); }
.badge-b { background: var(--teal); }
.meter {
display: grid;
grid-template-columns: 1fr auto;
gap: 5px 10px;
align-items: center;
margin-top: 8px;
font-size: 10px;
}
.meter-label {
color: #596474;
font-weight: 700;
}
.meter-value {
min-width: 48px;
text-align: right;
font-variant-numeric: tabular-nums;
font-weight: 800;
}
.meter-track {
grid-column: 1 / -1;
height: 6px;
overflow: hidden;
border-radius: 20px;
background: #ded9cf;
}
.meter-fill {
width: 0;
height: 100%;
border-radius: inherit;
transition: width 45ms linear;
}
.fill-gravity { background: var(--navy); }
.fill-kinetic { background: var(--gold); }
.fill-loss { background: var(--loss); }
.energy-note {
margin: 12px 2px 0;
color: #747b84;
font-size: 10px;
line-height: 1.5;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
margin-top: 11px;
color: #65707e;
font-size: 9px;
font-weight: 750;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 7px;
height: 7px;
border-radius: 2px;
}
.camera-hint {
position: absolute;
left: 24px;
bottom: 24px;
width: 218px;
padding: 13px;
pointer-events: auto;
}
.camera-hint strong {
display: block;
margin-bottom: 5px;
font-size: 11px;
}
.camera-hint p {
margin: 0 0 10px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.view-buttons {
display: flex;
gap: 5px;
}
.view-button {
flex: 1;
min-height: 30px;
padding: 0 6px;
border-radius: 8px;
font-size: 9px;
}
.comparison {
position: absolute;
left: 50%;
bottom: 24px;
width: min(690px, calc(100vw - 48px));
padding: 14px;
transform: translateX(-50%);
pointer-events: auto;
}
.transport {
display: grid;
grid-template-columns: auto 1fr auto;
gap: 12px;
align-items: center;
padding: 0 2px 11px;
border-bottom: 1px solid var(--line);
}
.transport button {
width: 34px;
height: 34px;
border-radius: 10px;
color: white;
background: var(--ink);
font-size: 14px;
}
.transport input {
width: 100%;
accent-color: var(--ink);
cursor: pointer;
}
.time {
min-width: 76px;
color: #596474;
text-align: right;
font-size: 11px;
font-variant-numeric: tabular-nums;
font-weight: 750;
}
.comparison-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
padding-top: 11px;
}
.track-card {
position: relative;
overflow: hidden;
padding: 12px 13px 11px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.43);
}
.track-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 4px;
background: var(--orange);
}
.track-card.b::before { background: var(--teal); }
.track-card header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
.track-card h3 {
margin: 0;
font-size: 12px;
letter-spacing: -0.01em;
}
.current-speed {
color: #697483;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 9px;
}
.metric span {
display: block;
margin-bottom: 3px;
color: #858b93;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.progress-track {
height: 3px;
margin-top: 10px;
overflow: hidden;
border-radius: 10px;
background: #ded9cf;
}
.progress-fill {
width: 0;
height: 100%;
background: var(--orange);
}
.b .progress-fill { background: var(--teal); }
.conclusion {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 10px;
padding: 9px 11px;
border-radius: 10px;
color: #4e5968;
background: #eae5da;
font-size: 10px;
line-height: 1.4;
}
.conclusion strong { color: var(--ink); }
.equation {
flex: none;
color: var(--ink);
font-family: Georgia, serif;
font-size: 13px;
font-style: italic;
font-weight: 700;
}
.world-label {
position: fixed;
z-index: 3;
transform: translate(-50%, -50%);
padding: 7px 10px;
border: 1px solid rgba(36, 48, 68, 0.14);
border-radius: 9px;
background: rgba(250, 247, 240, 0.92);
box-shadow: 0 6px 18px rgba(40, 45, 50, 0.1);
color: var(--ink);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.04em;
pointer-events: none;
white-space: nowrap;
}
.world-label .dot {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 6px;
border-radius: 50%;
background: var(--orange);
}
.world-label.b .dot { background: var(--teal); }
.world-label.height {
color: white;
background: var(--ink);
border-color: var(--ink);
font-size: 9px;
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
color: var(--ink);
background: #e9e3d8;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
@media (max-width: 980px) {
.hero { max-width: 390px; }
.hero p { display: none; }
.energy-panel { width: 282px; }
.camera-hint { display: none; }
}
@media (max-width: 700px) {
.hero {
top: 16px;
left: 16px;
max-width: 270px;
}
h1 { font-size: 29px; }
.eyebrow { font-size: 9px; }
.top-actions {
top: 16px;
right: 14px;
flex-direction: column;
align-items: flex-end;
}
.control {
min-height: 34px;
padding: 0 10px;
font-size: 10px;
}
.energy-panel {
top: 105px;
right: 12px;
width: 240px;
padding: 12px;
}
.energy-card { padding: 9px; }
.energy-note { display: none; }
.comparison {
bottom: 12px;
width: calc(100vw - 24px);
padding: 10px;
}
.comparison-grid { gap: 6px; }
.track-card { padding: 10px; }
.metrics { gap: 5px; }
.metric strong { font-size: 10px; }
.conclusion { font-size: 9px; }
.equation { font-size: 11px; }
}
@media (max-width: 470px) {
.energy-panel {
top: auto;
bottom: 188px;
width: calc(100vw - 24px);
}
.energy-card {
display: grid;
grid-template-columns: 1fr 1fr;
column-gap: 12px;
}
.energy-title { grid-column: 1 / -1; }
.energy-card + .energy-card { display: none; }
.legend { display: none; }
.metric span { font-size: 7px; }
.conclusion .equation { display: none; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D comparison of two ball tracks"></canvas>
<div class="ui">
<header class="hero">
<div class="eyebrow">Gravity Lab / 02</div>
<h1>Same drop.<br>Different journey.</h1>
<p>
Two identical 1 kg balls descend through tracks with the same vertical drop.
Equal energy conversion means equal final speeds—even when the routes take
different amounts of time.
</p>
</header>
<div class="top-actions">
<button class="control primary" id="playButton" type="button">Pause</button>
<button class="control" id="resetButton" type="button">Reset</button>
<button class="control" id="speedButton" type="button">1×</button>
</div>
<aside class="energy-panel panel">
<div class="panel-heading">
<div>
<h2>Energy at the ball</h2>
<p>Live partition of the initial gravitational energy.</p>
</div>
<div class="live-dot">Live</div>
</div>
<section class="energy-card">
<div class="energy-title">
<span class="lane-badge badge-a">A</span>
Direct descent
</div>
<div class="meter">
<span class="meter-label">Gravitational</span>
<span class="meter-value" id="gpeValueA">60.3 J</span>
<div class="meter-track"><div class="meter-fill fill-gravity" id="gpeBarA"></div></div>
</div>
<div class="meter">
<span class="meter-label">Kinetic</span>
<span class="meter-value" id="keValueA">0.0 J</span>
<div class="meter-track"><div class="meter-fill fill-kinetic" id="keBarA"></div></div>
</div>
<div class="meter">
<span class="meter-label">Dissipated</span>
<span class="meter-value" id="lossValueA">0.0 J</span>
<div class="meter-track"><div class="meter-fill fill-loss" id="lossBarA"></div></div>
</div>
</section>
<section class="energy-card">
<div class="energy-title">
<span class="lane-badge badge-b">B</span>
Scenic descent
</div>
<div class="meter">
<span class="meter-label">Gravitational</span>
<span class="meter-value" id="gpeValueB">60.3 J</span>
<div class="meter-track"><div class="meter-fill fill-gravity" id="gpeBarB"></div></div>
</div>
<div class="meter">
<span class="meter-label">Kinetic</span>
<span class="meter-value" id="keValueB">0.0 J</span>
<div class="meter-track"><div class="meter-fill fill-kinetic" id="keBarB"></div></div>
</div>
<div class="meter">
<span class="meter-label">Dissipated</span>
<span class="meter-value" id="lossValueB">0.0 J</span>
<div class="meter-track"><div class="meter-fill fill-loss" id="lossBarB"></div></div>
</div>
</section>
<div class="legend">
<span><i style="background:var(--navy)"></i>Potential</span>
<span><i style="background:var(--gold)"></i>Kinetic</span>
<span><i style="background:var(--loss)"></i>Loss</span>
</div>
<p class="energy-note">
Model: 86% of each vertical drop becomes kinetic energy; 14% is dissipated.
Potential energy is measured above the common finish line.
</p>
</aside>
<div class="camera-hint panel">
<strong>Explore the scene</strong>
<p>Drag to orbit · right-drag to pan · scroll to zoom</p>
<div class="view-buttons">
<button class="view-button" data-view="oblique" type="button">Oblique</button>
<button class="view-button" data-view="front" type="button">Front</button>
<button class="view-button" data-view="top" type="button">Top</button>
</div>
</div>
<section class="comparison panel">
<div class="transport">
<button id="transportButton" type="button" aria-label="Pause simulation">Ⅱ</button>
<input id="timeline" type="range" min="0" max="10" step="0.01" value="0" aria-label="Simulation time">
<span class="time" id="timeReadout">0.00 / 0.00 s</span>
</div>
<div class="comparison-grid">
<article class="track-card a">
<header>
<h3><span class="lane-badge badge-a">A</span> Direct descent</h3>
<span class="current-speed"><span id="liveSpeedA">0.0</span> m/s</span>
</header>
<div class="metrics">
<div class="metric"><span>Path</span><strong id="pathLengthA">—</strong></div>
<div class="metric"><span>Finish time</span><strong id="finishTimeA">—</strong></div>
<div class="metric"><span>Final speed</span><strong id="finalSpeedA">—</strong></div>
</div>
<div class="progress-track"><div class="progress-fill" id="progressA"></div></div>
</article>
<article class="track-card b">
<header>
<h3><span class="lane-badge badge-b">B</span> Scenic descent</h3>
<span class="current-speed"><span id="liveSpeedB">0.0</span> m/s</span>
</header>
<div class="metrics">
<div class="metric"><span>Path</span><strong id="pathLengthB">—</strong></div>
<div class="metric"><span>Finish time</span><strong id="finishTimeB">—</strong></div>
<div class="metric"><span>Final speed</span><strong id="finalSpeedB">—</strong></div>
</div>
<div class="progress-track"><div class="progress-fill" id="progressB"></div></div>
</article>
</div>
<div class="conclusion">
<span><strong>Equal drop + equal loss ⇒ equal exit speed.</strong> Route length changes travel time.</span>
<span class="equation">v<sub>f</sub> = √(2ηgΔh)</span>
</div>
</section>
</div>
<div class="world-label" id="labelA"><span class="dot"></span>A · DIRECT</div>
<div class="world-label b" id="labelB"><span class="dot"></span>B · SCENIC</div>
<div class="world-label height" id="labelHeight">COMMON DROP · Δh 6.15 m</div>
<div id="loading">Loading gravity lab…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Physical model
// -------------------------------------------------------------------------
const MASS = 1.0; // kg
const GRAVITY = 9.81; // m/s²
const ETA = 0.86; // fraction of vertical drop converted to kinetic energy
const START_Y = 7.40;
const FINISH_Y = 1.25;
const DROP = START_Y - FINISH_Y;
const INITIAL_ENERGY = MASS * GRAVITY * DROP;
const FINAL_SPEED = Math.sqrt(2 * ETA * GRAVITY * DROP);
const BALL_RADIUS = 0.42;
const state = {
elapsed: 0,
playing: true,
timeScale: 1,
maxDuration: 1
};
const $ = (id) => document.getElementById(id);
// -------------------------------------------------------------------------
// Renderer, scene, and lighting
// -------------------------------------------------------------------------
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 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;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e3d8);
scene.fog = new THREE.Fog(0xe9e3d8, 25, 55);
const camera = new THREE.PerspectiveCamera(
39,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(0xfff8e9, 0x8b94a1, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4dc, 3.2);
sun.position.set(-9, 17, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -19;
sun.shadow.camera.right = 19;
sun.shadow.camera.top = 17;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbad7e0, 0.8);
fill.position.set(10, 7, -12);
scene.add(fill);
const materials = {
floor: new THREE.MeshStandardMaterial({
color: 0xe5ded2,
roughness: 0.95,
metalness: 0
}),
support: new THREE.MeshStandardMaterial({
color: 0x66717d,
roughness: 0.72,
metalness: 0.12
}),
supportDark: new THREE.MeshStandardMaterial({
color: 0x3e4b59,
roughness: 0.76,
metalness: 0.1
}),
tie: new THREE.MeshStandardMaterial({
color: 0xd0c9bc,
roughness: 0.86
}),
a: new THREE.MeshStandardMaterial({
color: 0xef6b4f,
roughness: 0.53,
metalness: 0.04
}),
b: new THREE.MeshStandardMaterial({
color: 0x258487,
roughness: 0.53,
metalness: 0.04
}),
ball: new THREE.MeshStandardMaterial({
color: 0xf9f4e9,
roughness: 0.42,
metalness: 0.03
}),
ballStripe: new THREE.MeshStandardMaterial({
color: 0x29374a,
roughness: 0.48,
metalness: 0.06
}),
gravity: new THREE.MeshStandardMaterial({
color: 0x2d4059,
roughness: 0.7
}),
kinetic: new THREE.MeshStandardMaterial({
color: 0xefa53b,
roughness: 0.62
}),
loss: new THREE.MeshStandardMaterial({
color: 0xb7afa2,
roughness: 0.9
}),
meterBack: new THREE.MeshStandardMaterial({
color: 0xd8d2c7,
roughness: 0.95
})
};
const floor = new THREE.Mesh(new THREE.PlaneGeometry(55, 42), materials.floor);
floor.rotation.x = -Math.PI / 2;
floor.position.set(0, -0.08, -0.2);
floor.receiveShadow = true;
scene.add(floor);
const floorInset = new THREE.Mesh(
new THREE.BoxGeometry(28, 0.12, 14),
new THREE.MeshStandardMaterial({ color: 0xded7cb, roughness: 0.92 })
);
floorInset.position.set(0, -0.03, -0.4);
floorInset.receiveShadow = true;
scene.add(floorInset);
// -------------------------------------------------------------------------
// Curves and track construction
// -------------------------------------------------------------------------
class OffsetYCurve extends THREE.Curve {
constructor(base, offset) {
super();
this.base = base;
this.offset = offset;
}
getPoint(t, target = new THREE.Vector3()) {
return this.base.getPointAt(t, target).add(
new THREE.Vector3(0, this.offset, 0)
);
}
}
function makeCurve(points) {
const curve = new THREE.CatmullRomCurve3(
points.map((p) => new THREE.Vector3(...p)),
false,
"catmullrom",
0.45
);
curve.arcLengthDivisions = 1400;
curve.updateArcLengths();
return curve;
}
function addGate(curve, material, isFinish = false) {
const group = new THREE.Group();
const point = curve.getPointAt(isFinish ? 1 : 0);
const tangent = curve.getTangentAt(isFinish ? 1 : 0);
group.position.copy(point);
group.rotation.y = Math.atan2(tangent.x, tangent.z);
const postGeometry = new THREE.BoxGeometry(0.14, 1.42, 0.16);
const crossGeometry = new THREE.BoxGeometry(1.75, 0.14, 0.16);
const padGeometry = new THREE.BoxGeometry(1.85, 0.18, 1.0);
for (const x of [-0.78, 0.78]) {
const post = new THREE.Mesh(postGeometry, material);
post.position.set(x, 0.71, 0);
post.castShadow = true;
group.add(post);
}
const cross = new THREE.Mesh(crossGeometry, material);
cross.position.y = 1.42;
cross.castShadow = true;
group.add(cross);
const pad = new THREE.Mesh(padGeometry, materials.supportDark);
pad.position.y = -0.57;
pad.receiveShadow = true;
group.add(pad);
scene.add(group);
}
function buildTrack(curve, accentMaterial) {
const railCurve = new OffsetYCurve(curve, -0.54);
const rail = new THREE.Mesh(
new THREE.TubeGeometry(railCurve, 260, 0.13, 10, false),
accentMaterial
);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
const length = curve.getLength();
// Solid cross-ties make the route and its length easy to read.
const tieCount = Math.floor(length / 0.72);
const tieGeometry = new THREE.BoxGeometry(1.02, 0.09, 0.15);
const localForward = new THREE.Vector3(0, 0, 1);
for (let i = 1; i < tieCount; i++) {
const u = i / tieCount;
const point = curve.getPointAt(u);
const tangent = curve.getTangentAt(u).normalize();
const tie = new THREE.Mesh(tieGeometry, materials.tie);
tie.position.copy(point).add(new THREE.Vector3(0, -0.50, 0));
tie.quaternion.setFromUnitVectors(localForward, tangent);
tie.castShadow = true;
scene.add(tie);
}
// Supports descend to the laboratory floor.
const supportCount = Math.max(3, Math.floor(length / 1.8));
for (let i = 1; i < supportCount; i++) {
const u = i / supportCount;
const point = curve.getPointAt(u);
const railPoint = point.clone().add(new THREE.Vector3(0, -0.58, 0));
const height = Math.max(0.18, railPoint.y);
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.065, 0.085, height, 10),
materials.support
);
stem.position.set(railPoint.x, height / 2, railPoint.z);
stem.castShadow = true;
scene.add(stem);
const foot = new THREE.Mesh(
new THREE.CylinderGeometry(0.23, 0.28, 0.10, 16),
materials.supportDark
);
foot.position.set(railPoint.x, 0.05, railPoint.z);
foot.castShadow = true;
scene.add(foot);
}
addGate(curve, accentMaterial, false);
addGate(curve, accentMaterial, true);
}
const curveA = makeCurve([
[-8.0, 7.40, 2.60],
[-6.9, 6.55, 2.60],
[-5.7, 5.45, 2.60],
[-4.3, 4.25, 2.60],
[-2.6, 3.05, 2.60],
[-0.8, 2.05, 2.60],
[ 1.2, 1.48, 2.60],
[ 2.8, 1.25, 2.60]
]);
const curveB = makeCurve([
[-8.0, 7.40, -2.60],
[-7.5, 6.92, -3.55],
[-5.8, 6.45, -3.90],
[-4.0, 5.95, -3.25],
[-2.4, 5.48, -4.05],
[-0.6, 5.02, -3.35],
[ 0.8, 4.55, -4.10],
[ 2.4, 4.05, -3.40],
[ 3.8, 3.55, -4.00],
[ 5.3, 3.02, -3.45],
[ 6.5, 2.40, -3.75],
[ 7.5, 1.75, -3.10],
[ 8.2, 1.25, -2.60]
]);
buildTrack(curveA, materials.a);
buildTrack(curveB, materials.b);
// -------------------------------------------------------------------------
// Common release/finish height indicator
// -------------------------------------------------------------------------
const measurePoints = [
new THREE.Vector3(-9.35, FINISH_Y, 0),
new THREE.Vector3(-9.35, START_Y, 0)
];
const measureLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(measurePoints),
new THREE.LineDashedMaterial({
color: 0x536071,
dashSize: 0.16,
gapSize: 0.11,
transparent: true,
opacity: 0.7
})
);
measureLine.computeLineDistances();
scene.add(measureLine);
const capMaterial = new THREE.LineBasicMaterial({ color: 0x536071 });
for (const y of [START_Y, FINISH_Y]) {
const cap = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-9.55, y, 0),
new THREE.Vector3(-8.9, y, 0)
]),
capMaterial
);
scene.add(cap);
}
// -------------------------------------------------------------------------
// Timing lookup tables
//
// Speed is derived from the vertical drop:
// v(u) = sqrt(2 η g Δh(u)).
// Travel time is integrated as dt = ds / v along each arc.
// -------------------------------------------------------------------------
function buildTiming(curve) {
const samples = 700;
const length = curve.getLength();
const segmentLength = length / samples;
const cumulative = new Float64Array(samples + 1);
const velocities = new Float64Array(samples + 1);
for (let i = 0; i <= samples; i++) {
const u = i / samples;
const y = curve.getPointAt(u).y;
const drop = Math.max(0, START_Y - y);
velocities[i] = Math.sqrt(2 * ETA * GRAVITY * drop);
}
for (let i = 0; i < samples; i++) {
const midpointVelocity = Math.max(
0.08,
(velocities[i] + velocities[i + 1]) * 0.5
);
cumulative[i + 1] =
cumulative[i] + segmentLength / midpointVelocity;
}
return {
curve,
length,
samples,
cumulative,
velocities,
duration: cumulative[samples]
};
}
function timeToU(timing, time) {
if (time <= 0) return 0;
if (time >= timing.duration) return 1;
let low = 0;
let high = timing.samples;
while (high - low > 1) {
const mid = Math.floor((low + high) * 0.5);
if (timing.cumulative[mid] <= time) low = mid;
else high = mid;
}
const span = timing.cumulative[high] - timing.cumulative[low];
const fraction = span > 0
? (time - timing.cumulative[low]) / span
: 0;
return (low + fraction) / timing.samples;
}
const timingA = buildTiming(curveA);
const timingB = buildTiming(curveB);
state.maxDuration = Math.max(timingA.duration, timingB.duration);
$("timeline").max = state.maxDuration.toFixed(3);
$("pathLengthA").textContent = `${timingA.length.toFixed(1)} m`;
$("pathLengthB").textContent = `${timingB.length.toFixed(1)} m`;
$("finishTimeA").textContent = `${timingA.duration.toFixed(2)} s`;
$("finishTimeB").textContent = `${timingB.duration.toFixed(2)} s`;
$("finalSpeedA").textContent = `${FINAL_SPEED.toFixed(1)} m/s`;
$("finalSpeedB").textContent = `${FINAL_SPEED.toFixed(1)} m/s`;
// -------------------------------------------------------------------------
// Identical rolling balls
// -------------------------------------------------------------------------
function makeBall() {
const group = new THREE.Group();
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(BALL_RADIUS, 32, 20),
materials.ball
);
sphere.castShadow = true;
sphere.receiveShadow = true;
group.add(sphere);
const stripe = new THREE.Mesh(
new THREE.TorusGeometry(BALL_RADIUS * 1.006, 0.033, 10, 44),
materials.ballStripe
);
stripe.castShadow = true;
group.add(stripe);
const stripeTwo = stripe.clone();
stripeTwo.rotation.y = Math.PI / 2;
group.add(stripeTwo);
scene.add(group);
return group;
}
function makeTrail(color) {
const geometry = new THREE.SphereGeometry(0.065, 8, 6);
const material = new THREE.MeshBasicMaterial({ color });
const dots = [];
for (let i = 0; i < 15; i++) {
const dot = new THREE.Mesh(geometry, material);
dot.visible = false;
scene.add(dot);
dots.push(dot);
}
return dots;
}
const ballA = makeBall();
const ballB = makeBall();
const trailA = makeTrail(0xef6b4f);
const trailB = makeTrail(0x258487);
// -------------------------------------------------------------------------
// Moving in-scene energy columns
//
// Each column has a constant total height. Its colored segments show the
// live partition into kinetic energy, remaining gravitational energy,
// and dissipated energy.
// -------------------------------------------------------------------------
function makeEnergyColumn() {
const group = new THREE.Group();
const back = new THREE.Mesh(
new THREE.BoxGeometry(0.22, 1, 0.22),
materials.meterBack
);
back.position.y = 0.5;
group.add(back);
const segmentGeometry = new THREE.BoxGeometry(0.16, 1, 0.16);
const kinetic = new THREE.Mesh(segmentGeometry, materials.kinetic);
const gravity = new THREE.Mesh(segmentGeometry, materials.gravity);
const loss = new THREE.Mesh(segmentGeometry, materials.loss);
group.add(kinetic, gravity, loss);
scene.add(group);
return { group, kinetic, gravity, loss };
}
const columnA = makeEnergyColumn();
const columnB = makeEnergyColumn();
function updateEnergyColumn(column, kineticEnergy, gravityEnergy, lossEnergy) {
const totalHeight = 0.88;
const parts = [
[column.kinetic, kineticEnergy],
[column.gravity, gravityEnergy],
[column.loss, lossEnergy]
];
let cursor = 0;
for (const [mesh, energy] of parts) {
const height = Math.max(
0.0001,
totalHeight * (energy / INITIAL_ENERGY)
);
mesh.visible = energy > 0.015;
mesh.scale.y = height;
mesh.position.y = cursor + height / 2;
cursor += height;
}
}
// -------------------------------------------------------------------------
// Camera controls implemented without addons
// -------------------------------------------------------------------------
const desiredCamera = {
theta: 0.02,
phi: 1.13,
radius: 22.5,
target: new THREE.Vector3(0, 3.35, -0.2)
};
const currentCamera = {
theta: desiredCamera.theta,
phi: desiredCamera.phi,
radius: desiredCamera.radius,
target: desiredCamera.target.clone()
};
function updateCamera() {
currentCamera.theta +=
(desiredCamera.theta - currentCamera.theta) * 0.12;
currentCamera.phi +=
(desiredCamera.phi - currentCamera.phi) * 0.12;
currentCamera.radius +=
(desiredCamera.radius - currentCamera.radius) * 0.12;
currentCamera.target.lerp(desiredCamera.target, 0.12);
const sinPhi = Math.sin(currentCamera.phi);
camera.position.set(
currentCamera.target.x +
currentCamera.radius * sinPhi * Math.sin(currentCamera.theta),
currentCamera.target.y +
currentCamera.radius * Math.cos(currentCamera.phi),
currentCamera.target.z +
currentCamera.radius * sinPhi * Math.cos(currentCamera.theta)
);
camera.lookAt(currentCamera.target);
}
const pointers = new Map();
let dragMode = "orbit";
let previousX = 0;
let previousY = 0;
let previousPinchDistance = 0;
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
dragMode = event.button === 2 || event.button === 1 ? "pan" : "orbit";
previousX = event.clientX;
previousY = event.clientY;
} else if (pointers.size === 2) {
dragMode = "pinch";
previousPinchDistance = pointerDistance();
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (dragMode === "pinch" && pointers.size >= 2) {
const distance = pointerDistance();
if (distance > 0 && previousPinchDistance > 0) {
desiredCamera.radius *=
previousPinchDistance / distance;
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius,
10,
35
);
}
previousPinchDistance = distance;
return;
}
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
if (dragMode === "orbit") {
desiredCamera.theta -= dx * 0.006;
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi - dy * 0.005,
0.23,
1.48
);
} else if (dragMode === "pan") {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const panScale = currentCamera.radius * 0.00135;
desiredCamera.target.addScaledVector(right, -dx * panScale);
desiredCamera.target.addScaledVector(up, dy * panScale);
desiredCamera.target.x = THREE.MathUtils.clamp(
desiredCamera.target.x, -9, 9
);
desiredCamera.target.y = THREE.MathUtils.clamp(
desiredCamera.target.y, 0.5, 8
);
desiredCamera.target.z = THREE.MathUtils.clamp(
desiredCamera.target.z, -7, 7
);
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 0) dragMode = "orbit";
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
desiredCamera.radius *= Math.exp(event.deltaY * 0.001);
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius,
10,
35
);
}, { passive: false });
document.querySelectorAll("[data-view]").forEach((button) => {
button.addEventListener("click", () => {
const view = button.dataset.view;
if (view === "oblique") {
desiredCamera.theta = 0.02;
desiredCamera.phi = 1.13;
desiredCamera.radius = 22.5;
desiredCamera.target.set(0, 3.35, -0.2);
} else if (view === "front") {
desiredCamera.theta = 0;
desiredCamera.phi = 1.38;
desiredCamera.radius = 21;
desiredCamera.target.set(0, 3.5, 0);
} else {
desiredCamera.theta = 0;
desiredCamera.phi = 0.36;
desiredCamera.radius = 24;
desiredCamera.target.set(0, 2.5, -0.2);
}
});
});
// -------------------------------------------------------------------------
// Simulation and UI
// -------------------------------------------------------------------------
const up = new THREE.Vector3(0, 1, 0);
const tangent = new THREE.Vector3();
const side = new THREE.Vector3();
const rollAxis = new THREE.Vector3();
const rollQuaternion = new THREE.Quaternion();
function setMeter(prefix, gravityEnergy, kineticEnergy, lossEnergy) {
const gravityPercent = 100 * gravityEnergy / INITIAL_ENERGY;
const kineticPercent = 100 * kineticEnergy / INITIAL_ENERGY;
const lossPercent = 100 * lossEnergy / INITIAL_ENERGY;
$(`gpeBar${prefix}`).style.width = `${gravityPercent}%`;
$(`keBar${prefix}`).style.width = `${kineticPercent}%`;
$(`lossBar${prefix}`).style.width = `${lossPercent}%`;
$(`gpeValue${prefix}`).textContent = `${gravityEnergy.toFixed(1)} J`;
$(`keValue${prefix}`).textContent = `${kineticEnergy.toFixed(1)} J`;
$(`lossValue${prefix}`).textContent = `${lossEnergy.toFixed(1)} J`;
}
function updateLane(timing, ball, trail, column, prefix, elapsed) {
const u = timeToU(timing, elapsed);
const point = timing.curve.getPointAt(u);
const pathTangent = timing.curve.getTangentAt(u).normalize();
const verticalDrop = Math.max(0, START_Y - point.y);
const speed = Math.sqrt(
2 * ETA * GRAVITY * verticalDrop
);
const gravityEnergy = Math.max(
0,
MASS * GRAVITY * (point.y - FINISH_Y)
);
const kineticEnergy = 0.5 * MASS * speed * speed;
const lossEnergy = Math.max(
0,
INITIAL_ENERGY - gravityEnergy - kineticEnergy
);
ball.position.copy(point);
// Rotate around the axis perpendicular to the local path direction.
rollAxis.crossVectors(pathTangent, up);
if (rollAxis.lengthSq() < 0.0001) {
rollAxis.set(1, 0, 0);
} else {
rollAxis.normalize();
}
const rollAngle = timing.length * u / BALL_RADIUS;
rollQuaternion.setFromAxisAngle(rollAxis, rollAngle);
ball.quaternion.premultiply(rollQuaternion);
// Solid trail dots remain on the traveled route.
trail.forEach((dot, index) => {
const trailU = u - (index + 1) * 0.009;
if (trailU <= 0.001) {
dot.visible = false;
} else {
dot.visible = true;
dot.position.copy(timing.curve.getPointAt(trailU));
}
});
// Place the moving energy partition beside the ball.
side.crossVectors(pathTangent, up).normalize();
side.multiplyScalar(prefix === "A" ? -1 : 1);
column.group.position.copy(point)
.addScaledVector(side, 1.05)
.add(new THREE.Vector3(0, 0.76, 0));
updateEnergyColumn(
column,
kineticEnergy,
gravityEnergy,
lossEnergy
);
setMeter(prefix, gravityEnergy, kineticEnergy, lossEnergy);
$(`liveSpeed${prefix}`).textContent = speed.toFixed(1);
$(`progress${prefix}`).style.width = `${u * 100}%`;
return { u, point, speed };
}
function updatePlayUI() {
const label = state.playing ? "Pause" : "Play";
$("playButton").textContent = label;
$("transportButton").textContent = state.playing ? "Ⅱ" : "▶";
$("transportButton").setAttribute(
"aria-label",
state.playing ? "Pause simulation" : "Play simulation"
);
}
function togglePlayback() {
if (!state.playing && state.elapsed >= state.maxDuration - 0.001) {
state.elapsed = 0;
}
state.playing = !state.playing;
updatePlayUI();
}
function resetSimulation() {
state.elapsed = 0;
state.playing = true;
updatePlayUI();
}
$("playButton").addEventListener("click", togglePlayback);
$("transportButton").addEventListener("click", togglePlayback);
$("resetButton").addEventListener("click", resetSimulation);
const timeScales = [0.5, 1, 1.5];
let timeScaleIndex = 1;
$("speedButton").addEventListener("click", () => {
timeScaleIndex = (timeScaleIndex + 1) % timeScales.length;
state.timeScale = timeScales[timeScaleIndex];
$("speedButton").textContent = `${state.timeScale}×`;
});
$("timeline").addEventListener("input", (event) => {
state.elapsed = Number(event.target.value);
state.playing = false;
updatePlayUI();
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
togglePlayback();
} else if (event.code === "KeyR") {
resetSimulation();
}
});
// -------------------------------------------------------------------------
// Projected world labels
// -------------------------------------------------------------------------
function positionLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
const labelAPosition = curveA.getPointAt(0.16).add(new THREE.Vector3(0, 1.55, 0));
const labelBPosition = curveB.getPointAt(0.11).add(new THREE.Vector3(0, 1.55, 0));
const labelHeightPosition = new THREE.Vector3(-9.35, 4.4, 0);
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (state.playing) {
state.elapsed += delta * state.timeScale;
if (state.elapsed >= state.maxDuration) {
state.elapsed = state.maxDuration;
state.playing = false;
updatePlayUI();
}
}
$("timeline").value = state.elapsed.toFixed(3);
$("timeReadout").textContent =
`${state.elapsed.toFixed(2)} / ${state.maxDuration.toFixed(2)} s`;
updateCamera();
updateLane(
timingA,
ballA,
trailA,
columnA,
"A",
state.elapsed
);
updateLane(
timingB,
ballB,
trailB,
columnB,
"B",
state.elapsed
);
positionLabel($("labelA"), labelAPosition);
positionLabel($("labelB"), labelBPosition);
positionLabel($("labelHeight"), labelHeightPosition);
renderer.render(scene, camera);
}
updatePlayUI();
animate();
$("loading").remove();
</script>
</body>
</html>
```