Prompt specification
Build or customize the Three.js 3D scene "Friction Coefficient Counterfactual Level" 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: Friction Coefficient Counterfactual Level
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/friction-coefficient-counterfactual-level-x3512
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: friction coefficient counterfactual level. Create one playable layout with a friction slider and fixed initial conditions. Show how stopping positions change, and identify values that make the original route infeasible. Return one self-contained HTML file.
Working Three.js Starter (friction-coefficient-counterfactual-level-x3512):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Friction Counterfactual — Level 01</title>
<style>
:root {
color-scheme: light;
--ink: #102d35;
--panel: rgba(247, 250, 242, 0.92);
--panel-strong: rgba(255, 255, 255, 0.97);
--line: rgba(16, 45, 53, 0.15);
--accent: #ed7d32;
--green: #218b62;
--red: #c84b42;
--blue: #248db4;
--muted: #60777b;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b8d7cc;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#worldLabels {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -100%);
padding: 5px 8px;
border: 1px solid currentColor;
border-radius: 6px;
background: rgba(255, 255, 255, 0.9);
box-shadow: 0 4px 14px rgba(16, 45, 53, 0.12);
color: var(--ink);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
white-space: nowrap;
}
.brand {
position: fixed;
z-index: 4;
top: 22px;
left: 24px;
max-width: 360px;
pointer-events: none;
text-shadow: 0 1px 0 rgba(255,255,255,.55);
}
.brand .kicker {
display: inline-block;
padding: 6px 9px;
border-radius: 5px;
background: var(--ink);
color: #f8f6e9;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.15em;
}
.brand h1 {
margin: 9px 0 3px;
font-size: clamp(25px, 3vw, 42px);
line-height: 0.96;
letter-spacing: -0.055em;
}
.brand p {
margin: 8px 0 0;
color: #36585e;
font-size: 13px;
font-weight: 650;
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid rgba(255,255,255,.62);
border-radius: 14px;
background: var(--panel);
box-shadow:
0 16px 45px rgba(16, 45, 53, 0.18),
inset 0 0 0 1px rgba(16, 45, 53, 0.04);
backdrop-filter: blur(14px) saturate(1.1);
}
#controls {
left: 24px;
bottom: 24px;
width: 350px;
padding: 16px;
}
#analysis {
top: 22px;
right: 24px;
width: 334px;
max-height: calc(100vh - 44px);
overflow: auto;
padding: 15px;
scrollbar-width: thin;
}
.section-label {
margin-bottom: 8px;
color: var(--muted);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.mu-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
margin-bottom: 8px;
}
.mu-row .symbol {
color: var(--muted);
font-size: 14px;
font-weight: 800;
}
#muValue {
font-size: 38px;
line-height: 0.9;
letter-spacing: -0.06em;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
--fill: 45%;
width: 100%;
height: 22px;
margin: 0;
appearance: none;
background: transparent;
cursor: pointer;
}
input[type="range"]::-webkit-slider-runnable-track {
height: 7px;
border-radius: 20px;
background: linear-gradient(
to right,
var(--accent) 0 var(--fill),
rgba(16,45,53,.14) var(--fill) 100%
);
}
input[type="range"]::-moz-range-track {
height: 7px;
border-radius: 20px;
background: rgba(16,45,53,.14);
}
input[type="range"]::-moz-range-progress {
height: 7px;
border-radius: 20px;
background: var(--accent);
}
input[type="range"]::-webkit-slider-thumb {
width: 21px;
height: 21px;
margin-top: -7px;
appearance: none;
border: 3px solid white;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 2px 8px rgba(16,45,53,.3);
}
input[type="range"]::-moz-range-thumb {
width: 16px;
height: 16px;
border: 3px solid white;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 2px 8px rgba(16,45,53,.3);
}
.range-labels {
display: flex;
justify-content: space-between;
margin: 1px 2px 11px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.button-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-bottom: 8px;
}
button {
border: 0;
border-radius: 8px;
padding: 10px 13px;
background: var(--ink);
color: white;
cursor: pointer;
font-size: 12px;
font-weight: 850;
letter-spacing: .035em;
transition: transform .12s ease, background .12s ease, opacity .12s ease;
}
button:hover { transform: translateY(-1px); }
button:active { transform: translateY(1px); }
button:focus-visible { outline: 3px solid rgba(237,125,50,.45); outline-offset: 2px; }
button.secondary {
background: rgba(16,45,53,.09);
color: var(--ink);
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 11px;
}
.presets button {
padding: 7px 4px;
background: rgba(255,255,255,.72);
color: var(--ink);
border: 1px solid var(--line);
font-size: 10px;
}
.fixed-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 10px;
}
.fixed-grid div {
padding: 8px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255,255,255,.52);
}
.fixed-grid span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: .08em;
}
.fixed-grid strong {
display: block;
margin-top: 3px;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
#liveStatus {
min-height: 40px;
padding: 9px 10px;
border-left: 4px solid var(--green);
border-radius: 5px;
background: rgba(33,139,98,.09);
font-size: 11px;
font-weight: 750;
line-height: 1.35;
}
#liveStatus[data-state="infeasible"] {
border-color: var(--red);
background: rgba(200,75,66,.09);
}
#liveStatus[data-state="running"] {
border-color: var(--accent);
background: rgba(237,125,50,.10);
}
.verdict {
padding: 11px;
border-radius: 9px;
background: rgba(33,139,98,.11);
border: 1px solid rgba(33,139,98,.25);
}
.verdict.infeasible {
background: rgba(200,75,66,.10);
border-color: rgba(200,75,66,.27);
}
#verdictTitle {
display: block;
color: var(--green);
font-size: 12px;
font-weight: 950;
letter-spacing: .07em;
}
.verdict.infeasible #verdictTitle { color: var(--red); }
#verdictCopy {
display: block;
margin-top: 4px;
color: #3c5a60;
font-size: 11px;
line-height: 1.38;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin: 9px 0;
}
.stats div {
min-width: 0;
padding: 8px 5px;
text-align: center;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255,255,255,.55);
}
.stats span {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 850;
letter-spacing: .07em;
text-transform: uppercase;
}
.stats strong {
display: block;
margin-top: 3px;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
#graph {
display: block;
width: 100%;
height: 172px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255,255,255,.65);
cursor: crosshair;
}
.rule-box {
margin-top: 9px;
padding: 9px 10px;
border-radius: 8px;
background: rgba(16,45,53,.055);
color: #466267;
font-size: 10px;
line-height: 1.42;
}
.rule-box b { color: var(--ink); }
.history {
margin-top: 9px;
}
.history-row {
display: grid;
grid-template-columns: 1fr 1fr 68px;
gap: 5px;
align-items: center;
padding: 7px 0;
border-top: 1px solid var(--line);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.history-row b {
text-align: right;
font-size: 9px;
letter-spacing: .06em;
}
.history-row b.success { color: var(--green); }
.history-row b.short,
.history-row b.overrun { color: var(--red); }
.history-empty {
padding: 10px 0 2px;
color: var(--muted);
font-size: 10px;
}
.model-note {
margin: 8px 2px 0;
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
#hint {
position: fixed;
z-index: 3;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
padding: 7px 10px;
border-radius: 20px;
background: rgba(16,45,53,.78);
color: white;
font-size: 10px;
font-weight: 750;
letter-spacing: .025em;
pointer-events: none;
white-space: nowrap;
}
@media (max-width: 820px) {
.brand { top: 12px; left: 12px; }
.brand h1 { font-size: 25px; }
.brand p { display: none; }
#controls {
top: 105px;
bottom: auto;
left: 12px;
width: min(330px, calc(100vw - 24px));
padding: 12px;
}
#analysis {
top: auto;
right: 12px;
bottom: 12px;
width: min(330px, calc(100vw - 24px));
max-height: 42vh;
padding: 12px;
}
#hint { display: none; }
.fixed-grid { display: none; }
}
@media (max-height: 680px) {
#analysis { max-height: calc(100vh - 24px); }
#controls { bottom: 12px; }
.brand p { display: none; }
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive low-poly friction simulation"></div>
<div id="worldLabels" aria-hidden="true"></div>
<header class="brand">
<div class="kicker">COUNTERFACTUAL LEVEL 01</div>
<h1>Friction<br>Decision Gate</h1>
<p>One route. One launch. Change only the friction coefficient.</p>
</header>
<section id="controls" class="panel" aria-label="Simulation controls">
<div class="section-label">Counterfactual parameter</div>
<div class="mu-row">
<span class="symbol">Friction coefficient μ</span>
<strong id="muValue">0.110</strong>
</div>
<input
id="friction"
type="range"
min="0.050"
max="0.220"
step="0.001"
value="0.110"
aria-label="Friction coefficient"
/>
<div class="range-labels">
<span>0.050 · TOO SLICK</span>
<span>0.220 · TOO GRIPPY</span>
</div>
<div class="button-row">
<button id="launch" type="button">Launch puck ▶</button>
<button id="reset" class="secondary" type="button">Reset</button>
</div>
<div class="presets" aria-label="Friction presets">
<button type="button" data-mu="0.060">TOO SLICK</button>
<button type="button" data-mu="0.110">REFERENCE μ₀</button>
<button type="button" data-mu="0.180">TOO GRIPPY</button>
</div>
<div class="section-label">Fixed initial conditions</div>
<div class="fixed-grid">
<div><span>INITIAL SPEED</span><strong>7.2 m/s</strong></div>
<div><span>START</span><strong>GATE S</strong></div>
<div><span>SLOPE</span><strong>0°</strong></div>
</div>
<div id="liveStatus" role="status" aria-live="polite" data-state="feasible">
Ready to launch.
</div>
</section>
<aside id="analysis" class="panel" aria-label="Route analysis">
<div class="section-label">Original route verdict</div>
<div id="verdict" class="verdict">
<span id="verdictTitle">FEASIBLE</span>
<span id="verdictCopy"></span>
</div>
<div class="stats">
<div><span>Predicted stop</span><strong id="predictedStop">24.02 m</strong></div>
<div><span>Checkpoint</span><strong>22.00 m</strong></div>
<div><span>Live speed</span><strong id="liveSpeed">7.20 m/s</strong></div>
</div>
<div class="section-label">Stop distance sweep · click to set μ</div>
<canvas id="graph" aria-label="Graph of stopping distance versus friction coefficient"></canvas>
<div id="routeRule" class="rule-box"></div>
<div class="section-label" style="margin-top:12px">Measured stop positions</div>
<div id="history" class="history">
<div class="history-empty">No launches yet. Move μ and launch to compare stops.</div>
</div>
<p class="model-note">
Model: constant Coulomb deceleration along route distance,
v(t) = max(0, v₀ − μgt), so s_stop = v₀² / (2μg).
Turns are visual and do not add a steering penalty.
</p>
</aside>
<div id="hint">Drag to orbit · Wheel to zoom · Space launches · R resets</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const params = {
v0: 7.2,
g: 9.81,
goalDistance: 22,
runoutDistance: 32,
muMin: 0.050,
muMax: 0.220,
referenceMu: 0.110
};
// Exact boundaries for the fixed route requirements.
const muMaxForGoal = params.v0 ** 2 / (2 * params.g * params.goalDistance);
const muMinForRunout = params.v0 ** 2 / (2 * params.g * params.runoutDistance);
let mu = params.referenceMu;
let state = "ready";
let routeDistance = 0;
let speed = params.v0;
let elapsed = 0;
let crossedGoal = false;
let accumulator = 0;
const fixedStep = 1 / 120;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb8d7cc);
scene.fog = new THREE.Fog(0xb8d7cc, 58, 125);
const camera = new THREE.PerspectiveCamera(43, innerWidth / innerHeight, 0.1, 180);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.domElement.setAttribute("aria-label", "Low-poly route simulation");
$("scene").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf8fff3, 0x66826c, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4d6, 3.2);
sun.position.set(-16, 30, 16);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -45;
sun.shadow.camera.right = 45;
sun.shadow.camera.top = 40;
sun.shadow.camera.bottom = -40;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 85;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9ed4e4, 0.7);
fill.position.set(25, 12, -18);
scene.add(fill);
// The route is a polyline measured by arc length.
const route = [
new THREE.Vector3(-16, 0.25, 12),
new THREE.Vector3(-6, 0.25, 12),
new THREE.Vector3(-6, 0.25, 4),
new THREE.Vector3(4, 0.25, 4),
new THREE.Vector3(4, 0.25, 12),
new THREE.Vector3(22, 0.25, 12)
];
const cumulative = [0];
for (let i = 1; i < route.length; i++) {
cumulative.push(cumulative[i - 1] + route[i].distanceTo(route[i - 1]));
}
const routeLength = cumulative[cumulative.length - 1];
function sampleRoute(distance) {
const s = THREE.MathUtils.clamp(distance, 0, routeLength);
let index = 0;
while (index < route.length - 2 && s > cumulative[index + 1]) index++;
const start = route[index];
const end = route[index + 1];
const segmentLength = cumulative[index + 1] - cumulative[index];
const t = (s - cumulative[index]) / segmentLength;
const position = start.clone().lerp(end, t);
const tangent = end.clone().sub(start).normalize();
return { position, tangent, index };
}
function routeAngle(tangent) {
return -Math.atan2(tangent.z, tangent.x);
}
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(110, 90, 12, 10),
new THREE.MeshStandardMaterial({
color: 0x93b98c,
roughness: 1,
flatShading: true
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.29;
ground.receiveShadow = true;
scene.add(ground);
// Low-poly terrain and environmental props.
const propMaterials = {
hill: new THREE.MeshStandardMaterial({ color: 0x789b7a, flatShading: true, roughness: 1 }),
hillDark: new THREE.MeshStandardMaterial({ color: 0x668b70, flatShading: true, roughness: 1 }),
trunk: new THREE.MeshStandardMaterial({ color: 0x74533c, flatShading: true, roughness: 1 }),
leaf: new THREE.MeshStandardMaterial({ color: 0x2f7456, flatShading: true, roughness: 1 }),
leafLight: new THREE.MeshStandardMaterial({ color: 0x4f9367, flatShading: true, roughness: 1 }),
rock: new THREE.MeshStandardMaterial({ color: 0x8a9b91, flatShading: true, roughness: 1 })
};
const hills = [
[-32, -18, 11, 17, propMaterials.hill],
[-27, 27, 13, 20, propMaterials.hillDark],
[27, -18, 10, 15, propMaterials.hill],
[34, 25, 14, 22, propMaterials.hillDark],
[7, -27, 9, 13, propMaterials.hill]
];
for (const [x, z, radius, height, material] of hills) {
const hill = new THREE.Mesh(new THREE.ConeGeometry(radius, height, 6), material);
hill.position.set(x, height * 0.5 - 0.5, z);
hill.rotation.y = x * 0.17;
hill.receiveShadow = true;
scene.add(hill);
}
function addTree(x, z, scale = 1) {
const tree = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.18 * scale, 0.25 * scale, 1.6 * scale, 5),
propMaterials.trunk
);
trunk.position.y = 0.65 * scale;
trunk.castShadow = true;
const crown = new THREE.Mesh(
new THREE.ConeGeometry(1.25 * scale, 3.6 * scale, 6),
Math.random() > 0.5 ? propMaterials.leaf : propMaterials.leafLight
);
crown.position.y = 2.6 * scale;
crown.castShadow = true;
tree.add(trunk, crown);
tree.position.set(x, -0.25, z);
tree.rotation.y = x * 0.6 + z;
scene.add(tree);
}
[
[-23, 4, 1.0], [-20, 20, 0.8], [-13, 2, 0.85], [-9, 19, 1.15],
[-1, 21, 0.85], [4, 22, 1.1], [11, 19, 0.9], [18, 21, 1.15],
[22, 2, 0.9], [27, 15, 1.0], [18, -7, 1.1], [10, -10, 0.85],
[-10, -10, 1.0], [-2, -8, 0.75], [2, -5, 1.0], [25, -4, 0.8]
].forEach((args) => addTree(...args));
const rockPositions = [
[-19, -3, 1.2], [-11, 16, .8], [-2, 16, 1.0], [8, 17, .7],
[17, 3, 1.3], [25, 5, .8], [12, -7, 1.0], [-5, -5, .8]
];
for (const [x, z, scale] of rockPositions) {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(scale, 0),
propMaterials.rock
);
rock.position.set(x, scale * 0.42 - 0.25, z);
rock.rotation.set(x * 0.13, z * 0.21, x * 0.07);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
// Build the raised route.
const trackColors = [0xd5c59d, 0xe0d2ae, 0xcbb98f, 0xdacba3, 0xc8b78f];
const railMaterial = new THREE.MeshStandardMaterial({
color: 0xf1e9cf,
roughness: 0.85
});
const stripeMaterial = new THREE.MeshStandardMaterial({
color: 0xfff9df,
roughness: 0.8
});
for (let i = 0; i < route.length - 1; i++) {
const a = route[i];
const b = route[i + 1];
const direction = b.clone().sub(a);
const length = direction.length();
direction.normalize();
const midpoint = a.clone().add(b).multiplyScalar(0.5);
const angle = routeAngle(direction);
const base = new THREE.Mesh(
new THREE.BoxGeometry(length + 0.08, 0.42, 3.45),
new THREE.MeshStandardMaterial({
color: trackColors[i % trackColors.length],
roughness: 0.92,
flatShading: true
})
);
base.position.set(midpoint.x, -0.02, midpoint.z);
base.rotation.y = angle;
base.receiveShadow = true;
scene.add(base);
const top = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.08, 3.12),
new THREE.MeshStandardMaterial({
color: trackColors[(i + 1) % trackColors.length],
roughness: 0.95,
flatShading: true
})
);
top.position.set(midpoint.x, 0.23, midpoint.z);
top.rotation.y = angle;
top.receiveShadow = true;
scene.add(top);
const perpendicular = new THREE.Vector3(-direction.z, 0, direction.x);
for (const side of [-1, 1]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.15, 0.13),
railMaterial
);
rail.position.copy(midpoint).addScaledVector(perpendicular, side * 1.73);
rail.position.y = 0.31;
rail.rotation.y = angle;
scene.add(rail);
}
}
// Dashed centerline.
for (let s = 0.65; s < routeLength - 0.3; s += 1.35) {
const sample = sampleRoute(s);
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.52, 0.035, 0.12),
stripeMaterial
);
dash.position.copy(sample.position);
dash.position.y = 0.30;
dash.rotation.y = routeAngle(sample.tangent);
scene.add(dash);
}
function makeArch(distance, color, height = 3.6) {
const sample = sampleRoute(distance);
const group = new THREE.Group();
group.position.copy(sample.position);
group.position.y = 0.27;
group.rotation.y = routeAngle(sample.tangent);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.22,
roughness: 0.65
});
for (const side of [-1, 1]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.24, height, 0.24),
material
);
post.position.set(0, height * 0.5, side * 1.78);
post.castShadow = true;
group.add(post);
}
const beam = new THREE.Mesh(
new THREE.BoxGeometry(0.24, 0.24, 3.8),
material
);
beam.position.set(0, height, 0);
beam.castShadow = true;
group.add(beam);
scene.add(group);
return { group, material };
}
const startArch = makeArch(0, 0x248db4, 3.3);
const goalArch = makeArch(params.goalDistance, 0x27b879, 3.8);
// Checkered checkpoint line.
const checkpoint = sampleRoute(params.goalDistance);
const checkpointLine = new THREE.Group();
checkpointLine.position.copy(checkpoint.position);
checkpointLine.position.y = 0.31;
checkpointLine.rotation.y = routeAngle(checkpoint.tangent);
for (let i = 0; i < 10; i++) {
const tile = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.055, 0.31),
new THREE.MeshStandardMaterial({
color: i % 2 === 0 ? 0xf8f5df : 0x244b4d,
roughness: 0.9
})
);
tile.position.set(0, 0, -1.55 + i * 0.345);
checkpointLine.add(tile);
}
scene.add(checkpointLine);
// Hazard line at the approved runout boundary.
const limit = sampleRoute(params.runoutDistance);
const hazardLine = new THREE.Group();
hazardLine.position.copy(limit.position);
hazardLine.position.y = 0.33;
hazardLine.rotation.y = routeAngle(limit.tangent);
for (let i = 0; i < 10; i++) {
const stripe = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.06, 0.31),
new THREE.MeshStandardMaterial({
color: i % 2 === 0 ? 0xf0b332 : 0xb6413a,
roughness: 0.85
})
);
stripe.position.set(0, 0, -1.55 + i * 0.345);
hazardLine.add(stripe);
}
scene.add(hazardLine);
// Puck.
const puck = new THREE.Group();
const puckMaterial = new THREE.MeshStandardMaterial({
color: 0xed7d32,
roughness: 0.58,
flatShading: true,
emissive: 0xed7d32,
emissiveIntensity: 0.05
});
const puckBody = new THREE.Mesh(
new THREE.CylinderGeometry(0.72, 0.78, 0.48, 8),
puckMaterial
);
puckBody.castShadow = true;
puckBody.receiveShadow = true;
const puckTop = new THREE.Mesh(
new THREE.CylinderGeometry(0.47, 0.61, 0.12, 8),
new THREE.MeshStandardMaterial({
color: 0xffc36b,
roughness: 0.5,
flatShading: true
})
);
puckTop.position.y = 0.28;
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.20, 0.58, 4),
new THREE.MeshStandardMaterial({
color: 0x173e4b,
roughness: 0.55,
flatShading: true
})
);
arrow.rotation.z = -Math.PI / 2;
arrow.position.set(0.34, 0.37, 0);
puck.add(puckBody, puckTop, arrow);
scene.add(puck);
// Stop-position markers.
function makeMarker(color, opacity = 1) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.5,
transparent: true,
opacity,
depthWrite: false
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.65, 0.08, 6, 18),
material
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.04;
const beam = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 1.55, 6),
material
);
beam.position.y = 0.82;
const diamond = new THREE.Mesh(
new THREE.OctahedronGeometry(0.23),
material
);
diamond.position.y = 1.72;
group.add(ring, beam, diamond);
scene.add(group);
return { group, material };
}
const predictedMarker = makeMarker(0xf2aa3c, 0.85);
const referenceMarker = makeMarker(0x248db4, 0.48);
// World-space DOM labels.
const worldLabels = [];
function addWorldLabel(text, position, color = "#173e4b") {
const element = document.createElement("div");
element.className = "world-label";
element.textContent = text;
element.style.color = color;
$("worldLabels").appendChild(element);
const label = { element, anchor: position.clone() };
worldLabels.push(label);
return label;
}
addWorldLabel(
"START · v₀ 7.2 m/s",
sampleRoute(0).position.clone().add(new THREE.Vector3(0, 4.0, 0)),
"#176d91"
);
addWorldLabel(
"CHECKPOINT · 22 m",
sampleRoute(params.goalDistance).position.clone().add(new THREE.Vector3(0, 4.5, 0)),
"#16734d"
);
addWorldLabel(
"RUNOUT LIMIT · 32 m",
sampleRoute(params.runoutDistance).position.clone().add(new THREE.Vector3(0, 3.4, 0)),
"#a23d37"
);
const predictedLabel = addWorldLabel(
"PREDICTED STOP",
new THREE.Vector3(),
"#9b5d08"
);
const referenceLabel = addWorldLabel(
"REFERENCE μ₀ · 0.110",
sampleRoute(params.v0 ** 2 / (2 * params.g * params.referenceMu))
.position.clone().add(new THREE.Vector3(0, 1.25, 0)),
"#176d91"
);
// Reusable trail buffer.
const trailCapacity = 1600;
const trailArray = new Float32Array(trailCapacity * 3);
const trailGeometry = new THREE.BufferGeometry();
trailGeometry.setAttribute("position", new THREE.BufferAttribute(trailArray, 3));
trailGeometry.setDrawRange(0, 0);
const trailLine = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: 0xed7d32,
transparent: true,
opacity: 0.85
})
);
trailLine.frustumCulled = false;
scene.add(trailLine);
let trailCount = 0;
function addTrailPoint(position) {
if (trailCount >= trailCapacity) return;
const index = trailCount * 3;
trailArray[index] = position.x;
trailArray[index + 1] = position.y + 0.08;
trailArray[index + 2] = position.z;
trailCount++;
trailGeometry.attributes.position.needsUpdate = true;
trailGeometry.setDrawRange(0, trailCount);
}
const particles = [];
const particleGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
const particleMaterials = [
0xed7d32, 0x27b879, 0x248db4, 0xf3d358, 0xd85e50
].map(color => new THREE.MeshStandardMaterial({ color, roughness: 0.65 }));
function spawnConfetti() {
const origin = sampleRoute(params.goalDistance).position;
for (let i = 0; i < 32; i++) {
const mesh = new THREE.Mesh(
particleGeometry,
particleMaterials[i % particleMaterials.length]
);
mesh.position.copy(origin).add(new THREE.Vector3(
(Math.random() - 0.5) * 1.2,
2.2 + Math.random(),
(Math.random() - 0.5) * 1.2
));
mesh.rotation.set(Math.random() * 3, Math.random() * 3, Math.random() * 3);
scene.add(mesh);
particles.push({
mesh,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 3.4,
2.5 + Math.random() * 3.5,
(Math.random() - 0.5) * 3.4
),
life: 2.2
});
}
}
function updateParticles(dt) {
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.life -= dt;
p.velocity.y -= 5.5 * dt;
p.mesh.position.addScaledVector(p.velocity, dt);
p.mesh.rotation.x += dt * 5;
p.mesh.rotation.z += dt * 4;
if (p.life <= 0) {
scene.remove(p.mesh);
particles.splice(i, 1);
}
}
}
// Analysis and state helpers.
function predictedStoppingDistance(value = mu) {
return params.v0 ** 2 / (2 * params.g * value);
}
function classifyStop(stopDistance) {
if (stopDistance < params.goalDistance - 0.005) return "short";
if (stopDistance > params.runoutDistance + 0.005) return "overrun";
return "success";
}
function predictedOutcome() {
return classifyStop(predictedStoppingDistance());
}
function outcomeInfo(outcome) {
if (outcome === "short") {
return {
title: "INFEASIBLE · STOPS SHORT",
copy: `Predicted stop is before the ${params.goalDistance.toFixed(0)} m checkpoint. Too much friction removes the required travel distance.`,
color: 0xc84b42
};
}
if (outcome === "overrun") {
return {
title: "INFEASIBLE · RUNOUT OVERRUN",
copy: `Predicted stop is beyond the ${params.runoutDistance.toFixed(0)} m approved runout. Too little friction leaves the puck moving too far.`,
color: 0xc84b42
};
}
return {
title: "FEASIBLE · SAFE STOP",
copy: `Predicted stop is after the ${params.goalDistance.toFixed(0)} m checkpoint and before the ${params.runoutDistance.toFixed(0)} m runout limit.`,
color: 0x218b62
};
}
function updatePuckTransform() {
const sample = sampleRoute(routeDistance);
puck.position.copy(sample.position);
puck.position.y = 0.69;
puck.rotation.y = routeAngle(sample.tangent);
}
function updatePredictedMarker() {
const stop = predictedStoppingDistance();
const sample = sampleRoute(stop);
const info = outcomeInfo(predictedOutcome());
predictedMarker.group.position.copy(sample.position);
predictedMarker.group.position.y = 0.30;
predictedMarker.material.color.setHex(info.color);
predictedMarker.material.emissive.setHex(info.color);
predictedLabel.anchor.copy(sample.position).add(new THREE.Vector3(0, 2.85, 0));
predictedLabel.element.textContent = `PREDICTED STOP · ${stop.toFixed(2)} m`;
predictedLabel.element.style.color = info.color === 0x218b62 ? "#16734d" : "#9b3d36";
}
function updateLiveStatus() {
const status = $("liveStatus");
if (state === "running") {
status.dataset.state = "running";
status.textContent = `RUNNING · ${routeDistance.toFixed(1)} m traveled · ${speed.toFixed(2)} m/s remaining`;
return;
}
if (state === "stopped") {
const outcome = classifyStop(routeDistance);
const info = outcomeInfo(outcome);
status.dataset.state = outcome === "success" ? "feasible" : "infeasible";
status.textContent = outcome === "success"
? `ROUTE COMPLETE · Stopped ${routeDistance.toFixed(2)} m from start, inside the approved runout.`
: outcome === "short"
? `ROUTE FAILED · Stopped ${routeDistance.toFixed(2)} m from start, before the checkpoint.`
: `ROUTE FAILED · Stopped ${routeDistance.toFixed(2)} m from start, beyond the runout limit.`;
return;
}
const outcome = predictedOutcome();
const info = outcomeInfo(outcome);
status.dataset.state = outcome === "success" ? "feasible" : "infeasible";
status.textContent = outcome === "success"
? `READY · Predicted safe stop at ${predictedStoppingDistance().toFixed(2)} m. Launch to measure it.`
: `READY · ${info.title.replace("INFEASIBLE · ", "")}. Predicted stop: ${predictedStoppingDistance().toFixed(2)} m.`;
}
const history = [];
function updateHistory() {
const container = $("history");
if (!history.length) {
container.innerHTML = '<div class="history-empty">No launches yet. Move μ and launch to compare stops.</div>';
return;
}
container.innerHTML = history.slice(0, 6).map(run => `
<div class="history-row">
<span>μ ${run.mu.toFixed(3)}</span>
<span>${run.stop.toFixed(2)} m</span>
<b class="${run.outcome}">${
run.outcome === "success" ? "COMPLETE" :
run.outcome === "short" ? "SHORT" : "OVERRUN"
}</b>
</div>
`).join("");
}
function updateAnalysis() {
const stop = predictedStoppingDistance();
const outcome = predictedOutcome();
const info = outcomeInfo(outcome);
$("muValue").textContent = mu.toFixed(3);
$("predictedStop").textContent = `${stop.toFixed(2)} m`;
$("liveSpeed").textContent = `${speed.toFixed(2)} m/s`;
$("verdict").classList.toggle("infeasible", outcome !== "success");
$("verdictTitle").textContent = info.title;
$("verdictCopy").textContent = info.copy;
$("friction").style.setProperty(
"--fill",
`${(mu - params.muMin) / (params.muMax - params.muMin) * 100}%`
);
drawGraph();
}
function resetRun() {
state = "ready";
routeDistance = 0;
speed = params.v0;
elapsed = 0;
crossedGoal = false;
accumulator = 0;
trailCount = 0;
trailGeometry.setDrawRange(0, 0);
const start = sampleRoute(0);
addTrailPoint(start.position);
updatePuckTransform();
puckMaterial.color.setHex(0xed7d32);
puckMaterial.emissive.setHex(0xed7d32);
puckMaterial.emissiveIntensity = 0.05;
updateLiveStatus();
}
function finishRun() {
state = "stopped";
speed = 0;
const outcome = classifyStop(routeDistance);
const color = outcome === "success" ? 0x27b879 : 0xc84b42;
puckMaterial.color.setHex(color);
puckMaterial.emissive.setHex(color);
puckMaterial.emissiveIntensity = 0.12;
history.unshift({
mu,
stop: routeDistance,
outcome,
elapsed
});
updateHistory();
const sample = sampleRoute(routeDistance);
const marker = makeMarker(color, 0.9);
marker.group.position.copy(sample.position);
marker.group.position.y = 0.30;
const label = addWorldLabel(
`μ ${mu.toFixed(3)} · ${routeDistance.toFixed(1)} m`,
sample.position.clone().add(new THREE.Vector3(0, 2.25, 0)),
outcome === "success" ? "#16734d" : "#a23d37"
);
if (outcome === "success") spawnConfetti();
updateLiveStatus();
updateAnalysis();
}
function launch() {
resetRun();
state = "running";
updateLiveStatus();
}
function applyFriction(value) {
mu = THREE.MathUtils.clamp(value, params.muMin, params.muMax);
$("friction").value = mu.toFixed(3);
resetRun();
updatePredictedMarker();
updateAnalysis();
}
function stepPhysics(dt) {
if (state !== "running") return;
const deceleration = mu * params.g;
const nextSpeed = Math.max(0, speed - deceleration * dt);
routeDistance += (speed + nextSpeed) * 0.5 * dt;
speed = nextSpeed;
elapsed += dt;
if (!crossedGoal && routeDistance >= params.goalDistance) {
crossedGoal = true;
}
if (speed <= 0.00001) {
speed = 0;
finishRun();
}
}
// Friction sweep graph.
const graphCanvas = $("graph");
const graphContext = graphCanvas.getContext("2d");
let graphWidth = 0;
let graphHeight = 0;
function graphBounds() {
return {
left: 43,
right: 13,
top: 13,
bottom: 28,
width: graphWidth - 43 - 13,
height: graphHeight - 13 - 28
};
}
function drawGraph() {
const rect = graphCanvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(devicePixelRatio, 2);
const width = Math.round(rect.width * dpr);
const height = Math.round(rect.height * dpr);
if (graphCanvas.width !== width || graphCanvas.height !== height) {
graphCanvas.width = width;
graphCanvas.height = height;
}
graphWidth = rect.width;
graphHeight = rect.height;
const ctx = graphContext;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, graphWidth, graphHeight);
const b = graphBounds();
const xMin = params.muMin;
const xMax = params.muMax;
const yMax = routeLength;
const mapX = value => b.left + (value - xMin) / (xMax - xMin) * b.width;
const mapY = value => b.top + (1 - value / yMax) * b.height;
// Feasible μ band.
ctx.fillStyle = "rgba(33,139,98,0.12)";
ctx.fillRect(
mapX(muMinForRunout),
b.top,
mapX(muMaxForGoal) - mapX(muMinForRunout),
b.height
);
// Safe distance band.
ctx.fillStyle = "rgba(33,139,98,0.08)";
ctx.fillRect(
b.left,
mapY(params.runoutDistance),
b.width,
mapY(params.goalDistance) - mapY(params.runoutDistance)
);
// Grid.
ctx.strokeStyle = "rgba(16,45,53,0.10)";
ctx.lineWidth = 1;
ctx.font = "10px system-ui";
ctx.fillStyle = "#687e80";
ctx.textAlign = "right";
ctx.textBaseline = "middle";
for (const tick of [0, 20, 40]) {
const y = mapY(tick);
ctx.beginPath();
ctx.moveTo(b.left, y);
ctx.lineTo(b.left + b.width, y);
ctx.stroke();
ctx.fillText(`${tick}m`, b.left - 6, y);
}
ctx.textAlign = "center";
ctx.textBaseline = "top";
for (const tick of [0.05, 0.10, 0.15, 0.20]) {
const x = mapX(tick);
ctx.strokeStyle = "rgba(16,45,53,0.07)";
ctx.beginPath();
ctx.moveTo(x, b.top);
ctx.lineTo(x, b.top + b.height);
ctx.stroke();
ctx.fillText(tick.toFixed(2), x, b.top + b.height + 7);
}
// Goal and limit.
ctx.strokeStyle = "#218b62";
ctx.lineWidth = 1.7;
ctx.beginPath();
ctx.moveTo(b.left, mapY(params.goalDistance));
ctx.lineTo(b.left + b.width, mapY(params.goalDistance));
ctx.stroke();
ctx.setLineDash([5, 4]);
ctx.strokeStyle = "#c84b42";
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(b.left, mapY(params.runoutDistance));
ctx.lineTo(b.left + b.width, mapY(params.runoutDistance));
ctx.stroke();
ctx.setLineDash([]);
// Feasibility boundaries.
for (const boundary of [muMinForRunout, muMaxForGoal]) {
ctx.setLineDash([3, 4]);
ctx.strokeStyle = "rgba(24,118,78,0.6)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(mapX(boundary), b.top);
ctx.lineTo(mapX(boundary), b.top + b.height);
ctx.stroke();
ctx.setLineDash([]);
}
// Stop-distance curve.
ctx.strokeStyle = "#ed7d32";
ctx.lineWidth = 2.5;
ctx.beginPath();
for (let i = 0; i <= 180; i++) {
const xValue = xMin + (xMax - xMin) * i / 180;
const stop = predictedStoppingDistance(xValue);
const x = mapX(xValue);
const y = mapY(stop);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
// Reference dot.
const referenceStop = predictedStoppingDistance(params.referenceMu);
ctx.fillStyle = "#248db4";
ctx.beginPath();
ctx.arc(mapX(params.referenceMu), mapY(referenceStop), 4, 0, Math.PI * 2);
ctx.fill();
// Current dot.
const currentStop = predictedStoppingDistance();
ctx.fillStyle = "#102d35";
ctx.strokeStyle = "white";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(mapX(mu), mapY(currentStop), 5.5, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#536d70";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("STOP DISTANCE", 8, 2);
ctx.textAlign = "center";
ctx.fillText("FRICTION COEFFICIENT μ", b.left + b.width / 2, graphHeight - 12);
}
graphCanvas.addEventListener("pointerdown", (event) => {
const rect = graphCanvas.getBoundingClientRect();
const b = graphBounds();
const localX = event.clientX - rect.left;
if (localX < b.left || localX > b.left + b.width) return;
const fraction = (localX - b.left) / b.width;
const value = params.muMin + fraction * (params.muMax - params.muMin);
applyFriction(value);
});
// UI events.
$("friction").addEventListener("input", (event) => {
applyFriction(Number(event.target.value));
});
$("launch").addEventListener("click", launch);
$("reset").addEventListener("click", () => {
resetRun();
updateAnalysis();
});
document.querySelectorAll(".presets button").forEach(button => {
button.addEventListener("click", () => {
applyFriction(Number(button.dataset.mu));
});
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
launch();
}
if (event.key.toLowerCase() === "r") {
resetRun();
updateAnalysis();
}
if (event.key === "ArrowLeft") {
event.preventDefault();
applyFriction(mu - 0.001);
}
if (event.key === "ArrowRight") {
event.preventDefault();
applyFriction(mu + 0.001);
}
});
// Custom camera controls, implemented without Three.js addons.
const cameraTarget = new THREE.Vector3(2, 0, 7);
let cameraTheta = 0.78;
let cameraPhi = 1.03;
let cameraRadius = 48;
let dragging = false;
let dragX = 0;
let dragY = 0;
function updateCamera() {
cameraPhi = THREE.MathUtils.clamp(cameraPhi, 0.35, 1.42);
cameraRadius = THREE.MathUtils.clamp(cameraRadius, 25, 78);
const spherical = new THREE.Spherical(cameraRadius, cameraPhi, cameraTheta);
camera.position.copy(cameraTarget).add(new THREE.Vector3().setFromSpherical(spherical));
camera.lookAt(cameraTarget);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
cameraTheta -= dx * 0.006;
cameraPhi -= dy * 0.005;
updateCamera();
});
const endDrag = () => { dragging = false; };
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraRadius *= Math.exp(event.deltaY * 0.001);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraTheta = 0.78;
cameraPhi = 1.03;
cameraRadius = 48;
updateCamera();
});
function updateWorldLabels() {
for (const label of worldLabels) {
const projected = label.anchor.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * innerWidth;
const y = (-projected.y * 0.5 + 0.5) * innerHeight;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
drawGraph();
});
// Explicit route feasibility boundaries.
$("routeRule").innerHTML = `
<b>Original route rule:</b> stop after the 22 m checkpoint and no later than
the 32 m runout limit.<br>
Infeasible for <b>μ < ${muMinForRunout.toFixed(4)}</b> (overrun) or
<b>μ > ${muMaxForGoal.toFixed(4)}</b> (stops short).<br>
Feasible window: <b>μ ∈ [${muMinForRunout.toFixed(4)}, ${muMaxForGoal.toFixed(4)}]</b>.
`;
const referenceStop = predictedStoppingDistance(params.referenceMu);
const referenceSample = sampleRoute(referenceStop);
referenceMarker.group.position.copy(referenceSample.position);
referenceMarker.group.position.y = 0.29;
updateCamera();
resetRun();
updatePredictedMarker();
updateAnalysis();
updateHistory();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (state === "running") {
accumulator += dt;
while (accumulator >= fixedStep) {
stepPhysics(fixedStep);
accumulator -= fixedStep;
}
updatePuckTransform();
updateLiveStatus();
}
const time = performance.now() * 0.001;
goalArch.material.emissiveIntensity = crossedGoal
? 0.8 + Math.sin(time * 7) * 0.35
: 0.22 + Math.sin(time * 2.5) * 0.08;
startArch.material.emissiveIntensity = 0.18 + Math.sin(time * 2) * 0.05;
updateParticles(dt);
renderer.render(scene, camera);
updateWorldLabels();
}
animate();
</script>
</body>
</html>
```