Prompt specification
Build or customize the Three.js 3D scene "Open-loop and closed-loop disturbance 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: Open-loop and closed-loop disturbance comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/open-loop-and-closed-loop-disturbance-comparison-x1870
Scene Description Prompt:
Open-loop and closed-loop disturbance comparison. Move identical toy carts toward a target, adding the same disturbance to both; compare preset action with feedback correction under matched physical assumptions. Please build this with Three.js from cdnjs in one self-contained HTML file, using stylized solid shapes.
Working Three.js Starter (open-loop-and-closed-loop-disturbance-comparison-x1870):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Disturbance Lab — Open Loop vs Feedback</title>
<style>
:root {
--ink: #172522;
--muted: #66736f;
--panel: rgba(250, 252, 248, 0.88);
--panel-border: rgba(23, 37, 34, 0.10);
--open: #ef695c;
--closed: #169c91;
--accent: #f1b84b;
--shadow: 0 16px 40px rgba(34, 55, 49, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9eee8;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
button:focus-visible,
input:focus-visible,
select:focus-visible {
outline: 3px solid rgba(22, 156, 145, 0.25);
outline-offset: 2px;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas.dragging {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.intro {
top: 22px;
left: 22px;
width: min(390px, calc(100vw - 44px));
padding: 20px 22px;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: var(--closed);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--closed);
content: "";
box-shadow: 0 0 0 5px rgba(22, 156, 145, 0.12);
}
h1 {
margin: 0;
font-size: clamp(1.7rem, 3vw, 2.35rem);
line-height: 1;
letter-spacing: -0.045em;
}
.intro p {
margin: 12px 0 0;
color: var(--muted);
font-size: 0.91rem;
line-height: 1.55;
}
.mini-pills {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 15px;
}
.mini-pill {
padding: 6px 9px;
border: 1px solid rgba(23, 37, 34, 0.09);
border-radius: 999px;
background: rgba(255, 255, 255, 0.55);
color: #53615d;
font-size: 0.69rem;
font-weight: 750;
}
.setup {
top: 22px;
right: 22px;
width: 274px;
padding: 18px;
}
.section-title {
margin: 0 0 12px;
color: #43514d;
font-size: 0.7rem;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.setup-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.setup-item {
padding: 10px 11px;
border: 1px solid rgba(23, 37, 34, 0.08);
border-radius: 12px;
background: rgba(255, 255, 255, 0.48);
}
.setup-item span {
display: block;
color: var(--muted);
font-size: 0.66rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.07em;
}
.setup-item strong {
display: block;
margin-top: 4px;
font-size: 0.94rem;
}
.setup-note {
margin: 11px 2px 0;
color: var(--muted);
font-size: 0.74rem;
line-height: 1.45;
}
.metrics {
right: 22px;
top: 250px;
width: 274px;
padding: 15px;
}
.metric {
padding: 11px 10px;
border-radius: 13px;
background: rgba(255, 255, 255, 0.52);
border: 1px solid rgba(23, 37, 34, 0.07);
}
.metric + .metric {
margin-top: 8px;
}
.metric-head {
display: flex;
align-items: center;
gap: 8px;
color: #45534f;
font-size: 0.77rem;
font-weight: 800;
}
.dot {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 50%;
}
.dot.open {
background: var(--open);
}
.dot.closed {
background: var(--closed);
}
.metric-values {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-top: 7px;
}
.metric-values strong {
font-size: 1.3rem;
letter-spacing: -0.04em;
}
.metric-values span {
color: var(--muted);
font-size: 0.69rem;
}
.result {
margin-top: 10px;
padding: 10px 11px;
border-radius: 12px;
background: rgba(22, 156, 145, 0.10);
color: #176c65;
font-size: 0.76rem;
font-weight: 800;
line-height: 1.35;
}
.result.neutral {
background: rgba(23, 37, 34, 0.06);
color: #596560;
}
.controls {
left: 50%;
bottom: 22px;
width: min(720px, calc(100vw - 44px));
transform: translateX(-50%);
padding: 14px 16px;
}
.control-row {
display: flex;
align-items: center;
gap: 10px;
}
.button {
min-height: 40px;
padding: 0 15px;
border: 0;
border-radius: 11px;
cursor: pointer;
font-weight: 850;
transition:
transform 120ms ease,
filter 120ms ease,
background 120ms ease;
}
.button:hover {
filter: brightness(0.97);
transform: translateY(-1px);
}
.button:active {
transform: translateY(0);
}
.button.primary {
min-width: 138px;
color: white;
background: var(--ink);
box-shadow: 0 7px 18px rgba(23, 37, 34, 0.18);
}
.button.secondary {
color: var(--ink);
background: rgba(23, 37, 34, 0.08);
}
.slider-wrap {
display: flex;
min-width: 220px;
flex: 1;
align-items: center;
gap: 10px;
padding: 0 3px;
}
.slider-wrap label {
color: #52605c;
font-size: 0.72rem;
font-weight: 800;
white-space: nowrap;
}
input[type="range"] {
min-width: 90px;
width: 100%;
accent-color: var(--accent);
cursor: pointer;
}
.range-value {
min-width: 46px;
color: var(--ink);
font-size: 0.76rem;
font-weight: 850;
text-align: right;
}
select {
height: 40px;
padding: 0 28px 0 11px;
border: 1px solid rgba(23, 37, 34, 0.10);
border-radius: 11px;
color: var(--ink);
background: rgba(255, 255, 255, 0.68);
font-weight: 750;
cursor: pointer;
}
.timeline {
position: relative;
height: 7px;
margin-top: 13px;
overflow: hidden;
border-radius: 999px;
background: rgba(23, 37, 34, 0.10);
}
.timeline-fill {
position: absolute;
inset: 0 auto 0 0;
width: 0;
border-radius: inherit;
background: linear-gradient(90deg, var(--closed), #65c7a9);
}
.event-window {
position: absolute;
top: 0;
bottom: 0;
left: 28.75%;
width: 35%;
background: rgba(241, 184, 75, 0.58);
}
.timeline-meta {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: var(--muted);
font-size: 0.66rem;
font-weight: 700;
}
.event-banner {
position: fixed;
top: 24px;
left: 50%;
z-index: 20;
padding: 9px 14px;
border: 1px solid rgba(172, 116, 14, 0.18);
border-radius: 999px;
background: rgba(255, 239, 197, 0.92);
color: #8b5a0a;
box-shadow: 0 8px 24px rgba(96, 67, 16, 0.12);
font-size: 0.75rem;
font-weight: 850;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -8px);
transition:
opacity 160ms ease,
transform 160ms ease;
}
.event-banner.show {
opacity: 1;
transform: translate(-50%, 0);
}
.cart-tag {
position: fixed;
z-index: 5;
display: flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid rgba(23, 37, 34, 0.11);
border-radius: 999px;
background: rgba(255, 255, 255, 0.88);
box-shadow: 0 8px 18px rgba(23, 37, 34, 0.12);
color: var(--ink);
font-size: 0.7rem;
font-weight: 850;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
.camera-hint {
position: fixed;
right: 24px;
bottom: 22px;
z-index: 4;
color: rgba(23, 37, 34, 0.55);
font-size: 0.67rem;
font-weight: 700;
pointer-events: none;
}
@media (max-width: 980px) {
.setup {
display: none;
}
.metrics {
top: 22px;
right: 22px;
width: 250px;
}
.intro {
width: min(350px, calc(100vw - 310px));
}
}
@media (max-width: 700px) {
.intro {
top: 14px;
left: 14px;
width: calc(100vw - 28px);
padding: 15px 17px;
}
.intro p,
.mini-pills {
display: none;
}
.metrics {
top: 106px;
right: 14px;
width: 205px;
padding: 10px;
}
.metric {
padding: 8px;
}
.metric-values strong {
font-size: 1rem;
}
.controls {
bottom: 12px;
width: calc(100vw - 24px);
padding: 11px;
}
.control-row {
flex-wrap: wrap;
}
.button.primary {
flex: 1;
}
.slider-wrap {
order: 3;
min-width: 100%;
padding-top: 4px;
}
.camera-hint {
display: none;
}
.event-banner {
top: 108px;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive 3D open-loop and closed-loop cart comparison"></div>
<header class="panel intro">
<div class="eyebrow">Matched physical assumptions</div>
<h1>Disturbance Lab</h1>
<p>
Two identical carts follow the same planned move. A shared backward gust
hits both. One executes a preset motion; the other corrects its motion
using position and velocity feedback.
</p>
<div class="mini-pills">
<span class="mini-pill">1.00 kg each</span>
<span class="mini-pill">Same drag</span>
<span class="mini-pill">Same pulse</span>
<span class="mini-pill">4.0 second trial</span>
</div>
</header>
<aside class="panel setup">
<h2 class="section-title">Shared physical plant</h2>
<div class="setup-grid">
<div class="setup-item">
<span>Mass</span>
<strong>1.00 kg</strong>
</div>
<div class="setup-item">
<span>Drag</span>
<strong>0.42 N·s/m</strong>
</div>
<div class="setup-item">
<span>Max thrust</span>
<strong>9.5 N</strong>
</div>
<div class="setup-item">
<span>Goal</span>
<strong>4.30 m</strong>
</div>
</div>
<p class="setup-note">
The preset controller uses a precomputed trajectory and never measures the
cart. The feedback controller adds position and velocity correction.
</p>
</aside>
<aside class="panel metrics">
<h2 class="section-title">Target error</h2>
<div class="metric">
<div class="metric-head">
<span class="dot open"></span>
Preset action
</div>
<div class="metric-values">
<strong id="openGap">0.00 m</strong>
<span>peak <b id="openPeak">0.00</b></span>
</div>
</div>
<div class="metric">
<div class="metric-head">
<span class="dot closed"></span>
Feedback correction
</div>
<div class="metric-values">
<strong id="closedGap">0.00 m</strong>
<span>peak <b id="closedPeak">0.00</b></span>
</div>
</div>
<div id="result" class="result neutral" aria-live="polite">
Run the trial to compare the final target misses.
</div>
</aside>
<div id="openTag" class="cart-tag">
<span class="dot open"></span>
Preset action
</div>
<div id="closedTag" class="cart-tag">
<span class="dot closed"></span>
Feedback
</div>
<div id="eventBanner" class="event-banner">Shared gust active</div>
<section class="panel controls">
<div class="control-row">
<button id="runButton" class="button primary" type="button">Run comparison</button>
<button id="resetButton" class="button secondary" type="button">Reset</button>
<div class="slider-wrap">
<label for="peak">Gust strength</label>
<input
id="peak"
type="range"
min="0"
max="6"
step="0.1"
value="3.4"
aria-label="Disturbance peak force"
>
<span id="peakValue" class="range-value">3.4 N</span>
</div>
<select id="speed" aria-label="Playback speed">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="1.5">1.5×</option>
</select>
</div>
<div class="timeline" aria-hidden="true">
<div class="event-window"></div>
<div id="timelineFill" class="timeline-fill"></div>
</div>
<div class="timeline-meta">
<span id="timeLabel">0.00 / 4.00 s</span>
<span>Amber band = identical disturbance interval</span>
</div>
</section>
<div class="camera-hint">Drag to orbit · Scroll to zoom · Double-click resets view</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Simulation constants. Both carts use exactly the same mass, drag, thrust
// limit, initial state, trajectory, and disturbance force.
// -------------------------------------------------------------------------
const PLANT = Object.freeze({
mass: 1.0,
drag: 0.42,
maxThrust: 9.5
});
const FEEDBACK = Object.freeze({
kp: 4.2,
kd: 2.4
});
const START_X = -5.2;
const TARGET_X = 4.3;
const TRIAL_DURATION = 4.0;
const FIXED_STEP = 1 / 120;
const DISTURBANCE_START = 1.15;
const DISTURBANCE_DURATION = 1.4;
const laneZ = {
open: -1.25,
closed: 1.25
};
const clamp = THREE.MathUtils.clamp;
let peakForce = 3.4;
let playbackSpeed = 1;
let simulationTime = 0;
let accumulator = 0;
let running = false;
let complete = false;
const states = {
open: {
x: START_X,
v: 0,
maxError: 0,
squaredError: 0
},
closed: {
x: START_X,
v: 0,
maxError: 0,
squaredError: 0
}
};
// Quintic smoothstep trajectory: zero velocity and acceleration at both
// endpoints. Its inverse nominal control is used for the open-loop cart.
function referenceAt(t) {
const u = clamp(t / TRIAL_DURATION, 0, 1);
const distance = TARGET_X - START_X;
const s =
10 * u * u * u -
15 * u * u * u * u +
6 * u * u * u * u * u;
const ds =
30 * u * u -
60 * u * u * u +
30 * u * u * u * u;
const dds =
60 * u -
180 * u * u +
120 * u * u * u;
return {
x: START_X + distance * s,
v: (distance / TRIAL_DURATION) * ds,
a: (distance / (TRIAL_DURATION * TRIAL_DURATION)) * dds
};
}
function disturbanceAt(t) {
if (
t < DISTURBANCE_START ||
t >= DISTURBANCE_START + DISTURBANCE_DURATION
) {
return 0;
}
const phase =
(t - DISTURBANCE_START) / DISTURBANCE_DURATION;
// Smooth, zero-endpoint force pulse directed backward along the track.
return -peakForce * Math.sin(Math.PI * phase) ** 2;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9eee8);
scene.fog = new THREE.Fog(0xe9eee8, 21, 38);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
// Custom orbit state. No external camera-control module is used.
const cameraTarget = new THREE.Vector3(-0.35, 0.25, 0);
const defaultView = {
yaw: 0.08,
pitch: 0.82,
radius: 16.0
};
let cameraYaw = defaultView.yaw;
let cameraPitch = defaultView.pitch;
let cameraRadius = defaultView.radius;
function updateCamera() {
const horizontal = cameraRadius * Math.sin(cameraPitch);
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.cos(cameraPitch),
cameraTarget.z + horizontal * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(
0xf7fbf4,
0x81918a,
2.2
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(
0xfff4d6,
3.1
);
sun.position.set(-3.5, 10, 7.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xcce8ef, 1.0);
fill.position.set(7, 5, -7);
scene.add(fill);
const material = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.0,
flatShading: true,
...options
});
const boardMaterial = material(0xd4ddd5);
const boardEdgeMaterial = material(0xaab9ae);
const trackMaterial = material(0x596762);
const laneLineMaterial = material(0xe9efea);
const dashMaterial = material(0xb9c7bd);
const targetMaterial = material(0x6bbf88);
const targetInnerMaterial = material(0x9ed8aa);
const startMaterial = material(0xf3cf76);
// Raised diorama board.
const board = new THREE.Mesh(
new THREE.BoxGeometry(15.4, 0.34, 7.25),
boardMaterial
);
board.position.set(0, -0.25, 0);
board.receiveShadow = true;
scene.add(board);
const boardEdge = new THREE.Mesh(
new THREE.BoxGeometry(15.65, 0.14, 7.5),
boardEdgeMaterial
);
boardEdge.position.set(0, -0.43, 0);
boardEdge.receiveShadow = true;
scene.add(boardEdge);
// Two parallel tracks.
function makeTrack(z) {
const track = new THREE.Mesh(
new THREE.BoxGeometry(10.9, 0.075, 1.06),
trackMaterial
);
track.position.set(-0.45, 0.015, z);
track.receiveShadow = true;
scene.add(track);
for (const side of [-1, 1]) {
const edge = new THREE.Mesh(
new THREE.BoxGeometry(10.75, 0.025, 0.042),
laneLineMaterial
);
edge.position.set(-0.45, 0.066, z + side * 0.47);
edge.receiveShadow = true;
scene.add(edge);
}
for (let x = -5.45; x <= 4.55; x += 0.82) {
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.026, 0.055),
dashMaterial
);
dash.position.set(x, 0.069, z);
dash.receiveShadow = true;
scene.add(dash);
}
const startPad = new THREE.Mesh(
new THREE.CylinderGeometry(0.61, 0.61, 0.035, 40),
startMaterial
);
startPad.position.set(START_X, 0.075, z);
startPad.receiveShadow = true;
scene.add(startPad);
const startInner = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.34, 0.041, 40),
laneLineMaterial
);
startInner.position.set(START_X, 0.081, z);
startInner.receiveShadow = true;
scene.add(startInner);
}
makeTrack(laneZ.open);
makeTrack(laneZ.closed);
function makeTarget(z) {
const pad = new THREE.Mesh(
new THREE.CylinderGeometry(0.68, 0.68, 0.04, 48),
targetMaterial
);
pad.position.set(TARGET_X, 0.074, z);
pad.receiveShadow = true;
scene.add(pad);
const innerPad = new THREE.Mesh(
new THREE.CylinderGeometry(0.37, 0.37, 0.048, 48),
targetInnerMaterial
);
innerPad.position.set(TARGET_X, 0.08, z);
innerPad.receiveShadow = true;
scene.add(innerPad);
const hoop = new THREE.Mesh(
new THREE.TorusGeometry(0.72, 0.075, 12, 52),
targetMaterial
);
hoop.position.set(TARGET_X + 0.02, 0.94, z);
hoop.rotation.y = Math.PI / 2;
hoop.castShadow = true;
scene.add(hoop);
const innerHoop = new THREE.Mesh(
new THREE.TorusGeometry(0.37, 0.04, 10, 40),
targetInnerMaterial
);
innerHoop.position.set(TARGET_X + 0.02, 0.94, z);
innerHoop.rotation.y = Math.PI / 2;
innerHoop.castShadow = true;
scene.add(innerHoop);
for (const side of [-1, 1]) {
const foot = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.14, 0.22, 12),
targetMaterial
);
foot.position.set(TARGET_X, 0.13, z + side * 0.72);
foot.castShadow = true;
scene.add(foot);
}
}
makeTarget(laneZ.open);
makeTarget(laneZ.closed);
// Low-poly decorative shrubs.
function makeShrub(x, z, scale = 1) {
const group = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.11, 0.14, 0.65, 8),
material(0x8b7659)
);
trunk.position.y = 0.24;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.48, 0),
material(0x78a985)
);
crown.position.y = 0.78;
crown.scale.set(1, 1.15, 1);
crown.castShadow = true;
group.add(crown);
group.position.set(x, 0, z);
group.scale.setScalar(scale);
scene.add(group);
}
makeShrub(-6.45, -2.8, 1.05);
makeShrub(-6.35, 2.75, 0.85);
makeShrub(6.35, -2.75, 0.9);
makeShrub(6.4, 2.75, 1.1);
// Small signal blocks at the start of each lane.
function makeStartMarker(z, color) {
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.045, 0.055, 0.85, 10),
material(0x76847e)
);
pole.position.set(START_X - 0.72, 0.42, z - 0.57);
pole.castShadow = true;
scene.add(pole);
const flag = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.25, 0.055),
material(color)
);
flag.position.set(START_X - 0.54, 0.73, z - 0.57);
flag.castShadow = true;
scene.add(flag);
}
makeStartMarker(laneZ.open, 0xef695c);
makeStartMarker(laneZ.closed, 0x169c91);
// -------------------------------------------------------------------------
// Toy carts
// -------------------------------------------------------------------------
function makeCart(bodyColor, accentColor) {
const group = new THREE.Group();
const chassisMaterial = material(0x394541);
const bodyMaterial = material(bodyColor);
const accentMaterial = material(accentColor);
const tireMaterial = material(0x26302d);
const hubMaterial = material(0xc8d0cb);
const glassMaterial = material(0xbfe4e6, {
roughness: 0.28,
metalness: 0.05
});
const chassis = new THREE.Mesh(
new THREE.BoxGeometry(1.16, 0.22, 0.73),
chassisMaterial
);
chassis.position.y = 0.29;
chassis.castShadow = true;
chassis.receiveShadow = true;
group.add(chassis);
const lowerBody = new THREE.Mesh(
new THREE.BoxGeometry(0.92, 0.23, 0.63),
accentMaterial
);
lowerBody.position.set(-0.04, 0.47, 0);
lowerBody.castShadow = true;
group.add(lowerBody);
const cabin = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.38, 0.54),
bodyMaterial
);
cabin.position.set(-0.13, 0.71, 0);
cabin.castShadow = true;
group.add(cabin);
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.025, 0.20, 0.40),
glassMaterial
);
windowMesh.position.set(0.17, 0.75, 0);
windowMesh.castShadow = true;
group.add(windowMesh);
const headlight = new THREE.Mesh(
new THREE.SphereGeometry(0.085, 16, 10),
material(0xffe7a6, {
emissive: 0x9c6a18,
emissiveIntensity: 0.22
})
);
headlight.position.set(0.61, 0.45, 0);
group.add(headlight);
// Small arrow on top indicates the direction of motion.
const arrowShaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 0.26, 8),
accentMaterial
);
arrowShaft.rotation.z = -Math.PI / 2;
arrowShaft.position.set(0.24, 0.94, 0);
group.add(arrowShaft);
const arrowTip = new THREE.Mesh(
new THREE.ConeGeometry(0.09, 0.18, 10),
accentMaterial
);
arrowTip.rotation.z = -Math.PI / 2;
arrowTip.position.set(0.44, 0.94, 0);
group.add(arrowTip);
const wheelPivots = [];
for (const x of [-0.38, 0.38]) {
for (const z of [-0.41, 0.41]) {
const pivot = new THREE.Group();
pivot.position.set(x, 0.22, z);
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.21, 0.21, 0.13, 18),
tireMaterial
);
wheel.rotation.x = Math.PI / 2;
wheel.castShadow = true;
pivot.add(wheel);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, 0.145, 12),
hubMaterial
);
hub.rotation.x = Math.PI / 2;
pivot.add(hub);
group.add(pivot);
wheelPivots.push(pivot);
}
}
group.userData.wheelPivots = wheelPivots;
group.position.set(START_X, 0.075, 0);
scene.add(group);
return group;
}
const openCart = makeCart(0xef695c, 0xf7a64e);
const closedCart = makeCart(0x169c91, 0x85d6c7);
// -------------------------------------------------------------------------
// Shared disturbance visualization
// -------------------------------------------------------------------------
const gustGroup = new THREE.Group();
scene.add(gustGroup);
const gustMaterial = new THREE.MeshBasicMaterial({
color: 0xf1b84b,
transparent: true,
opacity: 0,
depthWrite: false
});
const gustShaftGeometry = new THREE.CylinderGeometry(
0.025,
0.025,
0.34,
8
);
const gustTipGeometry = new THREE.ConeGeometry(
0.095,
0.22,
10
);
const gustArrows = [];
// Fixed deterministic offsets keep the visualization repeatable.
for (let i = 0; i < 18; i++) {
const arrow = new THREE.Group();
const shaft = new THREE.Mesh(gustShaftGeometry, gustMaterial);
arrow.add(shaft);
const tip = new THREE.Mesh(gustTipGeometry, gustMaterial);
tip.position.y = 0.27;
arrow.add(tip);
// Local +Y is rotated to world -X, indicating a backward gust.
arrow.rotation.z = Math.PI / 2;
const z =
i % 2 === 0
? laneZ.open + (i % 4 - 1.5) * 0.16
: laneZ.closed + (i % 4 - 1.5) * 0.16;
arrow.position.set(
4.7 - (i / 18) * 10.2,
0.66 + (i % 3) * 0.25,
z
);
arrow.userData.offset = i / 18;
gustArrows.push(arrow);
gustGroup.add(arrow);
}
gustGroup.visible = false;
// -------------------------------------------------------------------------
// UI elements
// -------------------------------------------------------------------------
const runButton = document.getElementById("runButton");
const resetButton = document.getElementById("resetButton");
const peakInput = document.getElementById("peak");
const peakValue = document.getElementById("peakValue");
const speedSelect = document.getElementById("speed");
const openGap = document.getElementById("openGap");
const closedGap = document.getElementById("closedGap");
const openPeak = document.getElementById("openPeak");
const closedPeak = document.getElementById("closedPeak");
const result = document.getElementById("result");
const timelineFill = document.getElementById("timelineFill");
const timeLabel = document.getElementById("timeLabel");
const eventBanner = document.getElementById("eventBanner");
const openTag = document.getElementById("openTag");
const closedTag = document.getElementById("closedTag");
function formatSignedForce(value) {
if (Math.abs(value) < 0.001) return "0.0 N";
return `${value < 0 ? "−" : "+"}${Math.abs(value).toFixed(1)} N`;
}
function resetSimulation() {
running = false;
complete = false;
simulationTime = 0;
accumulator = 0;
for (const key of Object.keys(states)) {
states[key].x = START_X;
states[key].v = 0;
states[key].maxError = 0;
states[key].squaredError = 0;
}
openCart.position.set(START_X, 0.075, laneZ.open);
closedCart.position.set(START_X, 0.075, laneZ.closed);
for (const pivot of openCart.userData.wheelPivots) {
pivot.rotation.z = 0;
}
for (const pivot of closedCart.userData.wheelPivots) {
pivot.rotation.z = 0;
}
runButton.textContent = "Run comparison";
result.className = "result neutral";
result.textContent = "Run the trial to compare the final target misses.";
updateUI();
}
function toggleRunning() {
if (complete) resetSimulation();
running = !running;
accumulator = 0;
runButton.textContent = running ? "Pause trial" : "Run comparison";
}
runButton.addEventListener("click", toggleRunning);
resetButton.addEventListener("click", resetSimulation);
peakInput.addEventListener("input", () => {
peakForce = Number(peakInput.value);
peakValue.textContent = `${peakForce.toFixed(1)} N`;
resetSimulation();
});
speedSelect.addEventListener("change", () => {
playbackSpeed = Number(speedSelect.value);
});
window.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (
event.code === "Space" &&
tag !== "INPUT" &&
tag !== "SELECT" &&
tag !== "BUTTON"
) {
event.preventDefault();
toggleRunning();
}
});
function updateUI() {
const openDistance = Math.max(0, TARGET_X - states.open.x);
const closedDistance = Math.abs(TARGET_X - states.closed.x);
openGap.textContent = `${openDistance.toFixed(2)} m`;
closedGap.textContent = `${closedDistance.toFixed(2)} m`;
openPeak.textContent = `${states.open.maxError.toFixed(2)} m`;
closedPeak.textContent = `${states.closed.maxError.toFixed(2)} m`;
timelineFill.style.width =
`${clamp(simulationTime / TRIAL_DURATION, 0, 1) * 100}%`;
timeLabel.textContent =
`${simulationTime.toFixed(2)} / ${TRIAL_DURATION.toFixed(2)} s`;
const force = disturbanceAt(simulationTime);
const eventActive = Math.abs(force) > 0.015;
eventBanner.classList.toggle("show", eventActive && running);
eventBanner.textContent = `Shared gust active · ${formatSignedForce(force)}`;
}
// -------------------------------------------------------------------------
// Fixed-step simulation
// -------------------------------------------------------------------------
function simulateStep(dt) {
const nextTime = Math.min(
simulationTime + dt,
TRIAL_DURATION
);
const reference = referenceAt(nextTime);
const disturbance = disturbanceAt(nextTime);
// Open loop: precomputed nominal inverse dynamics, no state feedback.
const openControl = clamp(
PLANT.mass * reference.a + PLANT.drag * reference.v,
-PLANT.maxThrust,
PLANT.maxThrust
);
// Closed loop: same nominal feed-forward action plus position/velocity
// feedback. The correction is based only on measured cart state.
const closedPositionError =
states.closed.x - reference.x;
const closedVelocityError =
states.closed.v - reference.v;
const closedControl = clamp(
PLANT.mass * reference.a +
PLANT.drag * reference.v -
FEEDBACK.kp * closedPositionError -
FEEDBACK.kd * closedVelocityError,
-PLANT.maxThrust,
PLANT.maxThrust
);
const controls = {
open: openControl,
closed: closedControl
};
for (const key of Object.keys(states)) {
const state = states[key];
const acceleration =
(controls[key] -
PLANT.drag * state.v +
disturbance) /
PLANT.mass;
state.v += acceleration * dt;
state.x += state.v * dt;
const trajectoryError = Math.abs(state.x - reference.x);
state.maxError = Math.max(state.maxError, trajectoryError);
state.squaredError += trajectoryError * trajectoryError * dt;
}
simulationTime = nextTime;
if (simulationTime >= TRIAL_DURATION - 1e-8) {
finishSimulation();
}
}
function finishSimulation() {
complete = true;
running = false;
runButton.textContent = "Run again";
const openMiss = Math.abs(TARGET_X - states.open.x);
const closedMiss = Math.abs(TARGET_X - states.closed.x);
result.className = "result";
if (closedMiss < 0.25 && openMiss > closedMiss + 0.3) {
result.textContent =
`Feedback holds the goal: ${closedMiss.toFixed(2)} m miss, ` +
`versus ${openMiss.toFixed(2)} m for the preset action.`;
} else {
result.textContent =
`Final target misses — preset: ${openMiss.toFixed(2)} m, ` +
`feedback: ${closedMiss.toFixed(2)} m.`;
}
updateUI();
}
// -------------------------------------------------------------------------
// Custom pointer camera controls
// -------------------------------------------------------------------------
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
cameraYaw -= dx * 0.005;
cameraPitch = clamp(
cameraPitch + dy * 0.0045,
0.36,
1.24
);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
updateCamera();
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (event.pointerId !== undefined) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = clamp(
cameraRadius + event.deltaY * 0.012,
9.5,
24
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraYaw = defaultView.yaw;
cameraPitch = defaultView.pitch;
cameraRadius = defaultView.radius;
updateCamera();
});
// -------------------------------------------------------------------------
// Visual updates
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function placeTag(element, x, y, z) {
projected.set(x, y, z).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "flex" : "none";
if (!visible) return;
element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function updateGust() {
const force = disturbanceAt(simulationTime);
const active = Math.abs(force) > 0.012;
gustGroup.visible = active;
if (!active) {
gustMaterial.opacity = 0;
return;
}
const envelope =
peakForce > 0
? Math.abs(force) / peakForce
: 0;
gustMaterial.opacity = 0.18 + envelope * 0.64;
const phase =
(simulationTime - DISTURBANCE_START) / DISTURBANCE_DURATION;
for (const arrow of gustArrows) {
const travel = (phase * 1.8 + arrow.userData.offset) % 1;
arrow.position.x = 5.2 - travel * 11.0;
}
}
function updateCartVisual(cart, state, lane, previousX) {
cart.position.x = state.x;
cart.position.z = lane;
const travel = state.x - previousX;
for (const pivot of cart.userData.wheelPivots) {
pivot.rotation.z -= travel / 0.21;
}
}
let previousOpenX = START_X;
let previousClosedX = START_X;
function updateVisuals() {
updateCartVisual(openCart, states.open, laneZ.open, previousOpenX);
updateCartVisual(
closedCart,
states.closed,
laneZ.closed,
previousClosedX
);
previousOpenX = states.open.x;
previousClosedX = states.closed.x;
updateGust();
placeTag(openTag, states.open.x, 1.35, laneZ.open);
placeTag(closedTag, states.closed.x, 1.35, laneZ.closed);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio, 2)
);
renderer.setSize(
window.innerWidth,
window.innerHeight
);
}
window.addEventListener("resize", resize);
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
let lastFrameTime = performance.now();
let uiAccumulator = 0;
function animate(now) {
requestAnimationFrame(animate);
const frameDelta = Math.min(
(now - lastFrameTime) / 1000,
0.08
);
lastFrameTime = now;
if (running && !complete) {
accumulator += frameDelta * playbackSpeed;
while (accumulator >= FIXED_STEP && running) {
simulateStep(FIXED_STEP);
accumulator -= FIXED_STEP;
}
}
uiAccumulator += frameDelta;
if (uiAccumulator > 0.05) {
updateUI();
uiAccumulator = 0;
}
updateVisuals();
renderer.render(scene, camera);
}
resetSimulation();
requestAnimationFrame(animate);
</script>
</body>
</html>
```