Prompt specification
Build or customize the Three.js 3D scene "Collision parameter exploration lab" 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: Collision parameter exploration lab
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/collision-parameter-exploration-lab-x1372
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: collision parameter exploration lab. Allow mass ratio, initial velocity, and restitution controls within valid bounds; calculate post-collision velocities and show conservation checks without implying lost kinetic energy vanishes physically. Return one self-contained HTML file.
Working Three.js Starter (collision-parameter-exploration-lab-x1372):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Collision Lab — Kinetic Energy Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #07111b;
--panel: #0d1924;
--panel-2: #111f2c;
--line: #223446;
--text: #edf5f7;
--muted: #91a6b4;
--a: #ff7166;
--b: #42d5c5;
--energy: #ffc857;
--good: #75e09a;
--radius: 18px;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
display: grid;
grid-template-rows: 70px minmax(0, 1fr);
width: 100%;
height: 100dvh;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(7, 17, 27, 0.92);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 38px;
height: 38px;
flex: 0 0 auto;
border: 1px solid #365167;
border-radius: 12px;
background: linear-gradient(145deg, #152b3b, #0a151f);
overflow: hidden;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
top: 9px;
width: 14px;
height: 14px;
border-radius: 50%;
}
.brand-mark::before {
left: 5px;
background: var(--a);
box-shadow: 0 0 15px rgba(255, 113, 102, 0.45);
}
.brand-mark::after {
right: 5px;
background: var(--b);
box-shadow: 0 0 15px rgba(66, 213, 197, 0.45);
}
.brand h1 {
margin: 0;
font-size: 17px;
line-height: 1.15;
letter-spacing: 0.015em;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
}
.header-chips {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
.chip {
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 999px;
color: #b9cad4;
background: #0b1721;
font-size: 11px;
letter-spacing: 0.03em;
white-space: nowrap;
}
.chip.accent {
color: var(--b);
border-color: rgba(66, 213, 197, 0.28);
background: rgba(66, 213, 197, 0.07);
}
.workspace {
display: grid;
grid-template-columns: minmax(0, 1fr) 400px;
min-height: 0;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 48% 38%, rgba(48, 91, 113, 0.14), transparent 42%),
#08131e;
}
#sceneRoot,
#sceneRoot canvas {
display: block;
width: 100%;
height: 100%;
}
#sceneRoot canvas {
cursor: grab;
touch-action: none;
}
#sceneRoot canvas:active {
cursor: grabbing;
}
.stage-overlay {
position: absolute;
inset: 0;
pointer-events: none;
}
.stage-heading {
position: absolute;
top: 24px;
left: 25px;
max-width: 390px;
}
.eyebrow {
color: var(--b);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.stage-heading h2 {
margin: 7px 0 6px;
font-size: clamp(21px, 2.2vw, 31px);
line-height: 1.08;
letter-spacing: -0.035em;
}
.stage-heading p {
margin: 0;
max-width: 340px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.stage-actions {
position: absolute;
top: 22px;
right: 22px;
display: flex;
gap: 8px;
pointer-events: auto;
}
.small-button {
border: 1px solid var(--line);
border-radius: 10px;
padding: 9px 12px;
color: #c8d6de;
background: rgba(12, 27, 39, 0.86);
cursor: pointer;
backdrop-filter: blur(12px);
font-size: 12px;
}
.small-button:hover {
border-color: #496276;
background: rgba(24, 44, 59, 0.94);
}
.legend {
position: absolute;
left: 22px;
bottom: 58px;
display: flex;
gap: 15px;
align-items: center;
padding: 10px 12px;
border: 1px solid rgba(70, 94, 111, 0.45);
border-radius: 12px;
background: rgba(7, 17, 27, 0.68);
backdrop-filter: blur(10px);
color: #b9c9d3;
font-size: 11px;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--a);
box-shadow: 0 0 10px rgba(255, 113, 102, 0.45);
}
.swatch.b {
background: var(--b);
box-shadow: 0 0 10px rgba(66, 213, 197, 0.45);
}
.swatch.energy {
background: var(--energy);
box-shadow: 0 0 10px rgba(255, 200, 87, 0.45);
}
.stage-caption {
position: absolute;
left: 24px;
right: 24px;
bottom: 18px;
display: flex;
justify-content: space-between;
gap: 16px;
color: #728998;
font-size: 11px;
line-height: 1.4;
}
.body-label {
position: absolute;
z-index: 4;
min-width: 142px;
padding: 8px 10px;
border: 1px solid rgba(85, 112, 130, 0.48);
border-radius: 10px;
background: rgba(8, 20, 30, 0.88);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(10px);
transform: translate(-50%, -100%);
pointer-events: none;
font-size: 11px;
line-height: 1.4;
text-align: center;
}
.body-label strong {
display: block;
font-size: 12px;
}
.body-label.a strong {
color: var(--a);
}
.body-label.b strong {
color: var(--b);
}
.panel {
min-height: 0;
overflow-y: auto;
padding: 22px;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(18, 34, 47, 0.44), transparent 260px),
var(--panel);
scrollbar-width: thin;
scrollbar-color: #32495b transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 15px;
margin-bottom: 18px;
}
.panel-heading h2 {
margin: 5px 0 0;
font-size: 21px;
letter-spacing: -0.025em;
}
.fixed-mass {
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 9px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
text-align: right;
}
.card {
margin-bottom: 13px;
padding: 16px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(16, 31, 44, 0.9);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.09);
}
.card-title {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-bottom: 15px;
}
.card-title h3 {
margin: 0;
font-size: 13px;
letter-spacing: 0.01em;
}
.card-title span {
color: var(--muted);
font-size: 10px;
}
.control {
margin-bottom: 19px;
}
.control:last-child {
margin-bottom: 0;
}
.control-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
.control-top label {
color: #c7d5dc;
font-size: 12px;
}
.control-output {
min-width: 77px;
padding: 5px 8px;
border: 1px solid #294052;
border-radius: 8px;
color: #f5fbfc;
background: #0a1620;
font-variant-numeric: tabular-nums;
font-size: 12px;
font-weight: 700;
text-align: right;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 7px 0;
border-radius: 999px;
outline: none;
appearance: none;
background: linear-gradient(
90deg,
var(--range-color, var(--b)) 0%,
var(--range-color, var(--b)) var(--fill, 50%),
#263a49 var(--fill, 50%),
#263a49 100%
);
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid #0d1b27;
border-radius: 50%;
appearance: none;
background: var(--range-color, var(--b));
box-shadow: 0 0 0 1px var(--range-color, var(--b));
cursor: grab;
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #0d1b27;
border-radius: 50%;
background: var(--range-color, var(--b));
box-shadow: 0 0 0 1px var(--range-color, var(--b));
cursor: grab;
}
.range-limits {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: #667f90;
font-size: 10px;
}
.mass-readout {
margin-top: 14px;
padding: 10px 11px;
border: 1px solid #253b4b;
border-radius: 10px;
color: var(--muted);
background: #0a1721;
font-size: 11px;
line-height: 1.5;
}
.run-button {
width: 100%;
margin-top: 13px;
padding: 12px 16px;
border: 0;
border-radius: 11px;
color: #062019;
background: linear-gradient(135deg, #58e5d5, #32bbae);
box-shadow: 0 10px 24px rgba(50, 187, 174, 0.16);
cursor: pointer;
font-size: 13px;
font-weight: 800;
transition: transform 0.15s ease, filter 0.15s ease;
}
.run-button:hover {
filter: brightness(1.08);
transform: translateY(-1px);
}
.run-button:active {
transform: translateY(0);
}
.run-button:disabled {
cursor: wait;
filter: saturate(0.6);
opacity: 0.75;
}
.velocity-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.velocity-card {
padding: 12px;
border: 1px solid #273b4b;
border-radius: 12px;
background: #0b1823;
}
.velocity-card.a {
border-top: 2px solid var(--a);
}
.velocity-card.b {
border-top: 2px solid var(--b);
}
.velocity-name {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
color: var(--muted);
font-size: 10px;
}
.velocity-name strong {
color: var(--text);
font-size: 12px;
}
.velocity-row {
display: flex;
justify-content: space-between;
gap: 8px;
padding: 6px 0;
border-top: 1px solid #1d3040;
color: #7f97a7;
font-size: 10px;
}
.velocity-row span:last-child {
color: #dce8ed;
font-variant-numeric: tabular-nums;
text-align: right;
}
.velocity-row.final span:last-child {
color: #fff;
font-weight: 700;
}
.metric-line {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 8px 0;
border-top: 1px solid #203341;
color: var(--muted);
font-size: 11px;
}
.metric-line:first-of-type {
border-top: 0;
}
.metric-line strong {
color: #eef7f9;
font-variant-numeric: tabular-nums;
text-align: right;
}
.metric-line strong.good {
color: var(--good);
}
.energy-meter {
display: flex;
width: 100%;
height: 13px;
margin: 12px 0 9px;
overflow: hidden;
border: 1px solid #2a3f4f;
border-radius: 999px;
background: #07111a;
}
.energy-bar {
min-width: 0;
height: 100%;
transition: width 0.25s ease;
}
.energy-bar.after {
background: linear-gradient(90deg, #31bfae, #58e5d5);
}
.energy-bar.internal {
background: repeating-linear-gradient(
135deg,
#f3b83f,
#f3b83f 7px,
#ffd777 7px,
#ffd777 14px
);
}
.energy-legend {
display: flex;
justify-content: space-between;
gap: 12px;
color: #7f96a5;
font-size: 10px;
}
.energy-legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.tiny-swatch {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--b);
}
.tiny-swatch.internal {
background: var(--energy);
}
.balance {
margin-top: 13px;
padding: 10px 11px;
border-left: 2px solid var(--energy);
border-radius: 0 9px 9px 0;
color: #c7d4dc;
background: rgba(255, 200, 87, 0.055);
font-size: 11px;
line-height: 1.55;
font-variant-numeric: tabular-nums;
}
.check {
display: grid;
grid-template-columns: 29px 1fr;
gap: 10px;
padding: 11px 0;
border-top: 1px solid #203341;
}
.check:first-of-type {
border-top: 0;
}
.check-icon {
display: grid;
place-items: center;
width: 26px;
height: 26px;
border-radius: 8px;
color: #0c1b1c;
background: var(--good);
font-size: 13px;
font-weight: 900;
}
.check.accounted .check-icon {
color: #251a04;
background: var(--energy);
}
.check strong {
display: block;
margin-bottom: 3px;
font-size: 11px;
}
.check p {
margin: 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.note {
color: #8ca0ae;
font-size: 10px;
line-height: 1.55;
}
.note strong {
color: #d5e0e6;
}
.formula {
margin-top: 11px;
padding: 11px;
border: 1px solid #263b4b;
border-radius: 10px;
color: #b8cad4;
background: #091620;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 10px;
line-height: 1.75;
}
.formula .highlight {
color: var(--b);
}
.scenario {
margin-top: 12px;
padding: 11px 12px;
border: 1px solid #294052;
border-radius: 11px;
color: #afc1cb;
background: #0a1822;
font-size: 11px;
line-height: 1.5;
}
@media (max-width: 900px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100dvh;
grid-template-rows: 70px auto;
}
.workspace {
grid-template-columns: 1fr;
}
.stage {
height: 58dvh;
min-height: 430px;
}
.panel {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
}
@media (max-width: 560px) {
header {
padding: 0 15px;
}
.header-chips .chip:not(.accent) {
display: none;
}
.brand p {
display: none;
}
.panel {
padding: 17px;
}
.stage-heading {
top: 18px;
left: 17px;
max-width: 260px;
}
.stage-actions {
top: 16px;
right: 14px;
}
.stage-actions .small-button {
padding: 8px 9px;
font-size: 10px;
}
.legend {
left: 14px;
bottom: 55px;
gap: 9px;
font-size: 9px;
}
.stage-caption {
left: 15px;
right: 15px;
bottom: 13px;
}
.stage-caption span:last-child {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Collision Lab</h1>
<p>Parameter exploration for momentum and kinetic-energy transfer</p>
</div>
</div>
<div class="header-chips">
<span class="chip">1D head-on impact</span>
<span class="chip">Cart B initially at rest</span>
<span class="chip accent">Three.js r160</span>
</div>
</header>
<main class="workspace">
<section class="stage" id="stage" aria-label="Interactive low-poly collision scene">
<div id="sceneRoot"></div>
<div class="stage-overlay">
<div class="stage-heading">
<div class="eyebrow">Live model</div>
<h2>Watch the energy ledger.</h2>
<p>
Change the impact parameters, then run the collision. Momentum is
checked directly; kinetic energy is tracked through the impact.
</p>
</div>
<div class="stage-actions">
<button class="small-button" id="cameraReset" type="button">
Reset camera
</button>
</div>
<div class="legend" aria-hidden="true">
<div class="legend-item">
<span class="swatch"></span>
Cart A
</div>
<div class="legend-item">
<span class="swatch b"></span>
Cart B
</div>
<div class="legend-item">
<span class="swatch energy"></span>
Internal transfer
</div>
</div>
<div class="stage-caption">
<span>Motion is schematic; all numerical calculations use SI units.</span>
<span>Drag to orbit · wheel to zoom · double-click to reset</span>
</div>
</div>
<div class="body-label a" id="labelA">
<strong>Cart A</strong>
<span>1.00 kg</span>
</div>
<div class="body-label b" id="labelB">
<strong>Cart B</strong>
<span>1.00 kg</span>
</div>
</section>
<aside class="panel">
<div class="panel-heading">
<div>
<div class="eyebrow">Parameters</div>
<h2>Collision setup</h2>
</div>
<div class="fixed-mass">
m₁ = 1.00 kg<br />
fixed reference mass
</div>
</div>
<section class="card">
<div class="card-title">
<h3>Impact controls</h3>
<span>Valid physical bounds</span>
</div>
<div class="control">
<div class="control-top">
<label for="ratio">Mass ratio m₂ / m₁</label>
<output class="control-output" id="ratioValue">1.00×</output>
</div>
<input
id="ratio"
type="range"
min="0.25"
max="4"
step="0.05"
value="1"
style="--range-color: var(--b); --fill: 20%"
/>
<div class="range-limits">
<span>0.25× lighter</span>
<span>4.00× heavier</span>
</div>
</div>
<div class="control">
<div class="control-top">
<label for="speed">Initial velocity u₁</label>
<output class="control-output" id="speedValue">2.40 m/s</output>
</div>
<input
id="speed"
type="range"
min="0.2"
max="4"
step="0.05"
value="2.4"
style="--range-color: var(--a); --fill: 55%"
/>
<div class="range-limits">
<span>0.20 m/s</span>
<span>4.00 m/s</span>
</div>
</div>
<div class="control">
<div class="control-top">
<label for="restitution">Restitution e</label>
<output class="control-output" id="restitutionValue">0.80</output>
</div>
<input
id="restitution"
type="range"
min="0"
max="1"
step="0.01"
value="0.8"
style="--range-color: var(--energy); --fill: 80%"
/>
<div class="range-limits">
<span>0 · perfectly inelastic</span>
<span>1 · elastic limit</span>
</div>
</div>
<div class="mass-readout" id="massReadout">
m₁ = 1.00 kg · m₂ = 1.00 kg
</div>
<button class="run-button" id="runButton" type="button">Run collision</button>
</section>
<section class="card" aria-live="polite">
<div class="card-title">
<h3>Post-collision velocities</h3>
<span>1D collision equations</span>
</div>
<div class="velocity-grid">
<div class="velocity-card a">
<div class="velocity-name">
<strong>Cart A</strong>
<span id="massA">1.00 kg</span>
</div>
<div class="velocity-row">
<span>Before</span>
<span id="v1Before">+2.400 m/s →</span>
</div>
<div class="velocity-row final">
<span>After</span>
<span id="v1After">−0.300 m/s ←</span>
</div>
</div>
<div class="velocity-card b">
<div class="velocity-name">
<strong>Cart B</strong>
<span id="massB">1.00 kg</span>
</div>
<div class="velocity-row">
<span>Before</span>
<span id="v2Before">0.000 m/s</span>
</div>
<div class="velocity-row final">
<span>After</span>
<span id="v2After">+1.200 m/s →</span>
</div>
</div>
</div>
</section>
<section class="card">
<div class="card-title">
<h3>Conservation checks</h3>
<span>Calculated in real time</span>
</div>
<div class="metric-line">
<span>Momentum before</span>
<strong id="momentumBefore">2.400 kg·m/s</strong>
</div>
<div class="metric-line">
<span>Momentum after</span>
<strong id="momentumAfter">2.400 kg·m/s</strong>
</div>
<div class="metric-line">
<span>Momentum difference</span>
<strong class="good" id="momentumError">0.000e+0</strong>
</div>
<div class="check ok" id="momentumCheck">
<div class="check-icon">✓</div>
<div>
<strong id="momentumCheckTitle">Linear momentum conserved</strong>
<p id="momentumCheckText">
The modeled collision has no net external impulse along the rail.
</p>
</div>
</div>
<div class="check" id="energyCheck">
<div class="check-icon">↗</div>
<div>
<strong id="energyCheckTitle">Kinetic energy converted</strong>
<p id="energyCheckText">
The reduction is tracked as internal energy rather than discarded.
</p>
</div>
</div>
</section>
<section class="card">
<div class="card-title">
<h3>Energy ledger</h3>
<span>Before = after kinetic + internal</span>
</div>
<div class="metric-line">
<span>Kinetic energy before</span>
<strong id="kineticBefore">2.880 J</strong>
</div>
<div class="metric-line">
<span>Kinetic energy after</span>
<strong id="kineticAfter">2.304 J</strong>
</div>
<div class="metric-line">
<span>Transferred to internal forms</span>
<strong id="kineticInternal" style="color: var(--energy)">0.576 J</strong>
</div>
<div class="energy-meter" aria-label="Energy distribution">
<div class="energy-bar after" id="energyAfterBar" style="width: 80%"></div>
<div class="energy-bar internal" id="energyInternalBar" style="width: 20%"></div>
</div>
<div class="energy-legend">
<span><i class="tiny-swatch"></i>Kinetic <b id="afterPercent">80.0%</b></span>
<span><i class="tiny-swatch internal"></i>Internal <b id="internalPercent">20.0%</b></span>
</div>
<div class="balance" id="balanceEquation">
2.880 J = 2.304 J kinetic + 0.576 J internal
</div>
<p class="note" style="margin: 12px 0 0">
<strong>Energy is not destroyed.</strong> “Internal” is a bookkeeping
category for deformation, vibration, sound, heat, and other microscopic
or internal processes. This compact model does not partition those
channels individually.
</p>
</section>
<section class="card">
<div class="card-title">
<h3>Model details</h3>
<span>u₂ = 0 · μ = <b id="muValue">0.500</b> kg</span>
</div>
<div class="formula">
v₁′ = <span class="highlight">(m₁ − e m₂)</span>u₁ / (m₁ + m₂)<br />
v₂′ = <span class="highlight">(1 + e)m₁</span>u₁ / (m₁ + m₂)<br />
ΔK = ½μ(1 − e²)u₁²
</div>
<div class="scenario" id="scenarioText">
Partially elastic impact: part of the initial kinetic energy remains
kinetic, while the rest is transferred into internal forms.
</div>
</section>
</aside>
</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 $ = (selector) => document.querySelector(selector);
const params = {
ratio: 1,
speed: 2.4,
restitution: 0.8
};
const bounds = {
ratio: [0.25, 4],
speed: [0.2, 4],
restitution: [0, 1]
};
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
function calculate() {
const m1 = 1;
const m2 = params.ratio;
const u1 = params.speed;
const u2 = 0;
const e = params.restitution;
const totalMass = m1 + m2;
const v1 =
((m1 - e * m2) * u1 + (1 + e) * m2 * u2) / totalMass;
const v2 =
((1 + e) * m1 * u1 + (m2 - e * m1) * u2) / totalMass;
const momentumBefore = m1 * u1 + m2 * u2;
const momentumAfter = m1 * v1 + m2 * v2;
const kineticBefore = 0.5 * m1 * u1 * u1 + 0.5 * m2 * u2 * u2;
const kineticAfter = 0.5 * m1 * v1 * v1 + 0.5 * m2 * v2 * v2;
const internalEnergy = Math.max(0, kineticBefore - kineticAfter);
const reducedMass = (m1 * m2) / totalMass;
return {
m1,
m2,
u1,
u2,
e,
v1,
v2,
momentumBefore,
momentumAfter,
momentumError: Math.abs(momentumBefore - momentumAfter),
kineticBefore,
kineticAfter,
internalEnergy,
kineticFraction: kineticBefore > 0 ? kineticAfter / kineticBefore : 0,
internalFraction:
kineticBefore > 0 ? internalEnergy / kineticBefore : 0,
reducedMass
};
}
function signedVelocity(value, includeDirection = true) {
const magnitude = Math.abs(value);
const sign = value > 0.0005 ? "+" : value < -0.0005 ? "−" : "";
let text = `${sign}${magnitude.toFixed(3)} m/s`;
if (includeDirection && Math.abs(value) > 0.0005) {
text += value > 0 ? " →" : " ←";
}
return text;
}
let results = calculate();
function updateRangeFill(input, color) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
const percentage = ((value - min) / (max - min)) * 100;
input.style.setProperty("--fill", `${percentage}%`);
input.style.setProperty("--range-color", color);
}
function renderResults() {
results = calculate();
const r = results;
$("#ratioValue").textContent = `${r.m2.toFixed(2)}×`;
$("#speedValue").textContent = `${r.u1.toFixed(2)} m/s`;
$("#restitutionValue").textContent = r.e.toFixed(2);
$("#massReadout").textContent =
`m₁ = ${r.m1.toFixed(2)} kg · m₂ = ${r.m2.toFixed(2)} kg · ` +
`ratio = ${(r.m2 / r.m1).toFixed(2)}`;
$("#massA").textContent = `${r.m1.toFixed(2)} kg`;
$("#massB").textContent = `${r.m2.toFixed(2)} kg`;
$("#v1Before").textContent = signedVelocity(r.u1);
$("#v2Before").textContent = signedVelocity(r.u2, false);
$("#v1After").textContent = signedVelocity(r.v1);
$("#v2After").textContent = signedVelocity(r.v2);
$("#momentumBefore").textContent =
`${r.momentumBefore.toFixed(3)} kg·m/s`;
$("#momentumAfter").textContent =
`${r.momentumAfter.toFixed(3)} kg·m/s`;
$("#momentumError").textContent = r.momentumError.toExponential(2);
$("#kineticBefore").textContent = `${r.kineticBefore.toFixed(3)} J`;
$("#kineticAfter").textContent = `${r.kineticAfter.toFixed(3)} J`;
$("#kineticInternal").textContent = `${r.internalEnergy.toFixed(3)} J`;
const kineticPercent = r.kineticFraction * 100;
const internalPercent = r.internalFraction * 100;
$("#energyAfterBar").style.width = `${kineticPercent}%`;
$("#energyInternalBar").style.width = `${internalPercent}%`;
$("#afterPercent").textContent = `${kineticPercent.toFixed(1)}%`;
$("#internalPercent").textContent = `${internalPercent.toFixed(1)}%`;
$("#balanceEquation").textContent =
`${r.kineticBefore.toFixed(3)} J = ` +
`${r.kineticAfter.toFixed(3)} J kinetic + ` +
`${r.internalEnergy.toFixed(3)} J internal`;
const momentumCheck = $("#momentumCheck");
momentumCheck.classList.add("ok");
$("#momentumCheckTitle").textContent = "Linear momentum conserved";
$("#momentumCheckText").textContent =
`The calculated difference is ${r.momentumError.toExponential(2)} kg·m/s, ` +
"which is only floating-point rounding.";
const energyCheck = $("#energyCheck");
if (r.e >= 0.999999) {
energyCheck.classList.add("accounted");
energyCheck.classList.remove("ok");
$("#energyCheckTitle").textContent = "Kinetic energy conserved";
$("#energyCheckText").textContent =
"At e = 1, the modeled impact is elastic and no kinetic energy is converted.";
} else {
energyCheck.classList.add("accounted");
energyCheck.classList.remove("ok");
$("#energyCheckTitle").textContent = "Kinetic-energy reduction accounted for";
$("#energyCheckText").textContent =
`${r.internalEnergy.toFixed(3)} J remains as deformation, vibration, ` +
"sound, heat, or other internal energy; it is not discarded.";
}
$("#muValue").textContent = r.reducedMass.toFixed(3);
if (r.e === 0) {
$("#scenarioText").textContent =
"Perfectly inelastic impact: both carts leave the collision with the " +
"same center-of-mass velocity. Initial kinetic energy is transferred " +
"into internal forms rather than disappearing.";
} else if (r.e >= 0.999999) {
$("#scenarioText").textContent =
"Elastic limit: the carts separate with the same relative speed at " +
"which they approached, and the system's kinetic energy is unchanged.";
} else {
$("#scenarioText").textContent =
"Partially elastic impact: part of the initial kinetic energy remains " +
"kinetic, while the rest is transferred into internal forms.";
}
const ratioInput = $("#ratio");
const speedInput = $("#speed");
const restitutionInput = $("#restitution");
updateRangeFill(ratioInput, "var(--b)");
updateRangeFill(speedInput, "var(--a)");
updateRangeFill(restitutionInput, "var(--energy)");
}
// ---------- Three.js scene ----------
const sceneRoot = $("#sceneRoot");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08131e);
scene.fog = new THREE.Fog(0x08131e, 11, 27);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D model of two carts colliding on a laboratory rail"
);
sceneRoot.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const hemisphere = new THREE.HemisphereLight(0xb7e7ff, 0x18202a, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-4, 8, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 25;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x49d9d0, 1.5);
rimLight.position.set(5, 4, -6);
scene.add(rimLight);
const impactLight = new THREE.PointLight(0xffc857, 0, 7, 2);
impactLight.position.set(0, 1.5, 0);
scene.add(impactLight);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x0e1b26,
roughness: 0.96,
metalness: 0.02
});
const ground = new THREE.Mesh(new THREE.PlaneGeometry(30, 18), groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.025;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(30, 30, 0x315064, 0x1b3040);
grid.position.y = -0.012;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
const trackBedMaterial = new THREE.MeshStandardMaterial({
color: 0x142633,
roughness: 0.82,
metalness: 0.18,
flatShading: true
});
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x78909d,
roughness: 0.48,
metalness: 0.65,
flatShading: true
});
const trackBed = new THREE.Mesh(
new THREE.BoxGeometry(15.5, 0.12, 1.8),
trackBedMaterial
);
trackBed.position.y = 0.06;
trackBed.receiveShadow = true;
scene.add(trackBed);
for (const z of [-0.84, 0.84]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(15.5, 0.11, 0.09),
railMaterial
);
rail.position.set(0, 0.18, z);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
}
const tieMaterial = new THREE.MeshStandardMaterial({
color: 0x263b48,
roughness: 0.92,
flatShading: true
});
for (let x = -7; x <= 7; x += 0.8) {
const tie = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.075, 1.95),
tieMaterial
);
tie.position.set(x, 0.01, 0);
tie.receiveShadow = true;
scene.add(tie);
}
const centerStripe = new THREE.Mesh(
new THREE.BoxGeometry(0.035, 0.025, 1.75),
new THREE.MeshBasicMaterial({ color: 0x42d5c5 })
);
centerStripe.position.set(0, 0.135, 0);
scene.add(centerStripe);
const gateMaterial = new THREE.MeshBasicMaterial({
color: 0x42d5c5,
transparent: true,
opacity: 0.3
});
const gate = new THREE.Mesh(
new THREE.TorusGeometry(1.18, 0.022, 6, 40),
gateMaterial
);
gate.rotation.y = Math.PI / 2;
gate.position.set(0, 1.0, 0);
scene.add(gate);
const lowPolyMaterial = (color, extra = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.68,
metalness: 0.08,
flatShading: true,
...extra
});
function createCart(color) {
const group = new THREE.Group();
const chassis = new THREE.Mesh(
new THREE.BoxGeometry(1.05, 0.5, 0.82),
lowPolyMaterial(color)
);
chassis.position.y = 0.66;
chassis.castShadow = true;
chassis.receiveShadow = true;
group.add(chassis);
const pod = new THREE.Mesh(
new THREE.CylinderGeometry(0.33, 0.42, 0.34, 6),
lowPolyMaterial(color, { roughness: 0.58 })
);
pod.position.set(-0.08, 1.07, 0);
pod.castShadow = true;
group.add(pod);
const windowMaterial = lowPolyMaterial(0xbfeff0, {
metalness: 0.25,
roughness: 0.3
});
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.025, 0.22, 0.47),
windowMaterial
);
windowMesh.position.set(0.23, 1.08, 0);
group.add(windowMesh);
const wheelGeometry = new THREE.CylinderGeometry(
0.18,
0.18,
0.13,
8
);
const wheelMaterial = lowPolyMaterial(0x101820, {
roughness: 0.9,
metalness: 0.05
});
for (const x of [-0.32, 0.32]) {
for (const z of [-0.47, 0.47]) {
const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(x, 0.27, z);
wheel.castShadow = true;
group.add(wheel);
}
}
const bumper = new THREE.Mesh(
new THREE.BoxGeometry(0.1, 0.2, 0.9),
railMaterial
);
bumper.position.set(0.575, 0.58, 0);
bumper.castShadow = true;
group.add(bumper);
scene.add(group);
return group;
}
const cartA = createCart(0xff7166);
const cartB = createCart(0x42d5c5);
const arrowA = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0xffc2bb,
0.22,
0.13
);
const arrowB = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0x8ff3e9,
0.22,
0.13
);
for (const arrow of [arrowA, arrowB]) {
arrow.line.material.depthTest = false;
arrow.cone.material.depthTest = false;
arrow.line.renderOrder = 10;
arrow.cone.renderOrder = 10;
scene.add(arrow);
}
const pulseMaterial = new THREE.MeshBasicMaterial({
color: 0xffc857,
wireframe: true,
transparent: true,
opacity: 0
});
const impactPulse = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.56, 1),
pulseMaterial
);
impactPulse.position.set(0, 0.72, 0);
impactPulse.visible = false;
scene.add(impactPulse);
const particleGeometry = new THREE.TetrahedronGeometry(0.055, 0);
const particleMaterial = new THREE.MeshBasicMaterial({
color: 0xffc857
});
const particles = [];
function clearParticles() {
for (const particle of particles) {
scene.remove(particle.mesh);
}
particles.length = 0;
}
function spawnTransferParticles() {
const fraction = results.internalFraction;
if (fraction < 0.005) return;
const count = Math.round(4 + fraction * 18);
for (let i = 0; i < count; i++) {
const mesh = new THREE.Mesh(particleGeometry, particleMaterial);
mesh.position.set(
(Math.random() - 0.5) * 0.28,
0.6 + Math.random() * 0.45,
(Math.random() - 0.5) * 0.28
);
mesh.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
scene.add(mesh);
particles.push({
mesh,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 2.1,
0.8 + Math.random() * 1.8,
(Math.random() - 0.5) * 2.1
),
life: 0.75 + Math.random() * 0.55,
maxLife: 1.3
});
}
}
// ---------- Direct camera controls ----------
const cameraTarget = new THREE.Vector3(0, 0.65, 0);
let cameraYaw = 0.62;
let cameraPitch = 0.49;
let cameraRadius = 10.4;
function updateCamera() {
const horizontal = cameraRadius * Math.cos(cameraPitch);
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.sin(cameraPitch),
cameraTarget.z + horizontal * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraYaw = 0.62;
cameraPitch = 0.49;
cameraRadius = 10.4;
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraYaw -= dx * 0.006;
cameraPitch = clamp(cameraPitch + dy * 0.0045, 0.12, 1.22);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
6.1,
17
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
$("#cameraReset").addEventListener("click", resetCamera);
// ---------- Animation ----------
const CONTACT_X = 0.63;
const START_X = -2.7;
const PRE_DURATION = 1.18;
const POST_DURATION = 2.45;
const VISUAL_VELOCITY_SCALE = 0.33;
let running = false;
let phase = "idle";
let elapsed = 0;
let displayedVelocityA = params.speed;
let displayedVelocityB = 0;
let pulseTime = 0;
function updateArrow(arrow, cart, velocity) {
if (Math.abs(velocity) < 0.015) {
arrow.visible = false;
return;
}
arrow.visible = true;
arrow.position.set(cart.position.x, 1.52, 0);
arrow.setDirection(
new THREE.Vector3(velocity > 0 ? 1 : -1, 0, 0)
);
arrow.setLength(
clamp(0.34 + Math.abs(velocity) * 0.34, 0.34, 2.35),
0.22,
0.13
);
}
function resetScene() {
running = false;
phase = "idle";
elapsed = 0;
pulseTime = 0;
clearParticles();
impactPulse.visible = false;
impactLight.intensity = 0;
cartA.position.set(START_X, 0, 0);
cartB.position.set(CONTACT_X, 0, 0);
displayedVelocityA = params.speed;
displayedVelocityB = 0;
updateArrow(arrowA, cartA, displayedVelocityA);
updateArrow(arrowB, cartB, displayedVelocityB);
$("#runButton").disabled = false;
$("#runButton").textContent = "Run collision";
}
function startCollision() {
resetScene();
phase = "pre";
elapsed = 0;
running = true;
$("#runButton").disabled = true;
$("#runButton").textContent = "Collision running…";
}
function triggerImpact() {
pulseTime = 0;
impactPulse.visible = true;
impactPulse.scale.setScalar(1);
if (results.internalEnergy > 0.0001) {
impactPulse.material.color.set(0xffc857);
impactLight.color.set(0xffc857);
impactLight.intensity = 6;
spawnTransferParticles();
} else {
impactPulse.material.color.set(0x42d5c5);
impactLight.color.set(0x42d5c5);
impactLight.intensity = 3;
}
}
const labelA = $("#labelA");
const labelB = $("#labelB");
const projected = new THREE.Vector3();
function positionLabel(element, x, velocity, mass) {
projected.set(x, 1.65, 0).project(camera);
const width = sceneRoot.clientWidth;
const height = sceneRoot.clientHeight;
const visible = projected.z < 1;
element.style.display = visible ? "block" : "none";
element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
element.innerHTML =
`<strong>Cart ${element === labelA ? "A" : "B"}</strong>` +
`<span>${mass.toFixed(2)} kg · ${signedVelocity(velocity, false)}</span>`;
}
function updateLabels() {
positionLabel(labelA, cartA.position.x, displayedVelocityA, results.m1);
positionLabel(labelB, cartB.position.x, displayedVelocityB, results.m2);
}
function resize() {
const width = sceneRoot.clientWidth;
const height = sceneRoot.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(sceneRoot);
let previousTime = performance.now();
function animate(now) {
const dt = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (running) {
elapsed += dt;
if (phase === "pre") {
const t = clamp(elapsed / PRE_DURATION, 0, 1);
cartA.position.x = THREE.MathUtils.lerp(
START_X,
-CONTACT_X,
t
);
cartB.position.x = CONTACT_X;
displayedVelocityA = results.u1;
displayedVelocityB = 0;
if (t >= 1) {
phase = "post";
elapsed = 0;
triggerImpact();
}
} else if (phase === "post") {
cartA.position.x =
-CONTACT_X +
results.v1 * VISUAL_VELOCITY_SCALE * elapsed;
cartB.position.x =
CONTACT_X +
results.v2 * VISUAL_VELOCITY_SCALE * elapsed;
displayedVelocityA = results.v1;
displayedVelocityB = results.v2;
if (elapsed >= POST_DURATION) {
running = false;
phase = "done";
$("#runButton").disabled = false;
$("#runButton").textContent = "Run again";
}
}
}
updateArrow(arrowA, cartA, displayedVelocityA);
updateArrow(arrowB, cartB, displayedVelocityB);
if (impactPulse.visible) {
pulseTime += dt;
const life = clamp(pulseTime / 0.65, 0, 1);
impactPulse.scale.setScalar(1 + life * 3.2);
pulseMaterial.opacity = (1 - life) * 0.8;
if (life >= 1) {
impactPulse.visible = false;
}
}
impactLight.intensity = Math.max(
0,
impactLight.intensity - dt * 11
);
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
particle.life -= dt;
particle.velocity.y -= 2.35 * dt;
particle.mesh.position.addScaledVector(particle.velocity, dt);
particle.mesh.rotation.x += dt * 4;
particle.mesh.rotation.y += dt * 3;
const scale = clamp(particle.life / 0.35, 0, 1);
particle.mesh.scale.setScalar(scale);
if (particle.life <= 0 || particle.mesh.position.y < 0.03) {
scene.remove(particle.mesh);
particles.splice(i, 1);
}
}
updateLabels();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
// ---------- UI events ----------
function bindRange(id, key, color) {
const input = $(id);
input.addEventListener("input", () => {
const [min, max] = bounds[key];
params[key] = clamp(Number(input.value), min, max);
input.value = params[key];
updateRangeFill(input, color);
renderResults();
resetScene();
});
}
bindRange("#ratio", "ratio", "var(--b)");
bindRange("#speed", "speed", "var(--a)");
bindRange("#restitution", "restitution", "var(--energy)");
$("#runButton").addEventListener("click", startCollision);
window.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (
event.code === "Space" &&
tag !== "INPUT" &&
tag !== "BUTTON" &&
!event.repeat
) {
event.preventDefault();
startCollision();
}
});
renderResults();
resetScene();
resetCamera();
resize();
requestAnimationFrame(animate);
</script>
</body>
</html>
```