Prompt specification
Build or customize the Three.js 3D scene "Target-tracking cart controller" 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: Target-tracking cart controller
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/target-tracking-cart-controller-x1869
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: target-tracking cart controller. Build a cart, target marker, measured-position indicator, and error arrow; use a stated proportional controller with bounded force and show overshoot when appropriate. Return one self-contained HTML file.
Working Three.js Starter (target-tracking-cart-controller-x1869):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Target-Tracking Cart Controller</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 22, 38, 0.88);
--panel-border: rgba(145, 184, 220, 0.16);
--text: #eaf4ff;
--muted: #8ea6bd;
--cyan: #39d7ff;
--orange: #ffad55;
--yellow: #ffd36a;
--green: #5ee6a8;
--red: #ff786d;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.brand {
position: fixed;
top: 22px;
left: 24px;
z-index: 5;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.55);
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 4px;
font-size: clamp(24px, 3vw, 38px);
line-height: 1;
letter-spacing: -0.04em;
}
.subtitle {
margin: 0;
color: #a9bed1;
font-size: 13px;
}
.metrics {
position: fixed;
top: 112px;
left: 24px;
z-index: 5;
display: grid;
grid-template-columns: repeat(2, minmax(128px, 155px));
gap: 8px;
pointer-events: none;
}
.metric {
min-height: 67px;
padding: 11px 13px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(8, 19, 34, 0.72);
backdrop-filter: blur(12px);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18);
}
.metric-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
display: block;
font-variant-numeric: tabular-nums;
font-size: 19px;
font-weight: 760;
letter-spacing: -0.025em;
}
.metric-value.cyan { color: var(--cyan); }
.metric-value.yellow { color: var(--yellow); }
.metric-value.green { color: var(--green); }
.panel {
position: fixed;
z-index: 10;
top: 92px;
right: 20px;
width: 340px;
max-height: calc(100vh - 114px);
overflow: auto;
padding: 17px;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: var(--panel);
backdrop-filter: blur(18px);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.38);
scrollbar-width: thin;
scrollbar-color: #34516e transparent;
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.panel h2 {
margin: 0;
font-size: 14px;
letter-spacing: 0.02em;
}
.live-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px var(--green);
}
.equation {
padding: 13px 12px;
border: 1px solid rgba(57, 215, 255, 0.13);
border-radius: 12px;
background: rgba(4, 13, 25, 0.62);
text-align: center;
}
.equation-main {
color: #f4f9ff;
font-family: Georgia, "Times New Roman", serif;
font-size: 17px;
line-height: 1.4;
}
.equation-note {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.control {
margin-top: 15px;
}
.control-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
}
.control-row label {
color: #b8cadb;
font-size: 12px;
font-weight: 650;
}
.control-value {
color: var(--cyan);
font-size: 12px;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
border-radius: 99px;
appearance: none;
background: linear-gradient(90deg, #244159, #153047);
cursor: pointer;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #092039;
border-radius: 50%;
appearance: none;
background: var(--cyan);
box-shadow: 0 0 0 1px rgba(57, 215, 255, 0.35);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #092039;
border-radius: 50%;
background: var(--cyan);
}
.force-section {
margin-top: 17px;
padding-top: 14px;
border-top: 1px solid rgba(145, 184, 220, 0.12);
}
.force-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
color: #b8cadb;
font-size: 12px;
font-weight: 650;
}
.chip {
padding: 4px 7px;
border-radius: 99px;
background: rgba(94, 230, 168, 0.11);
color: var(--green);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.chip.saturated {
background: rgba(255, 173, 85, 0.12);
color: var(--orange);
}
.force-track {
position: relative;
height: 10px;
overflow: hidden;
border-radius: 99px;
background:
linear-gradient(90deg,
rgba(255, 120, 109, 0.18) 0%,
rgba(94, 230, 168, 0.13) 44%,
rgba(94, 230, 168, 0.13) 56%,
rgba(255, 120, 109, 0.18) 100%);
}
.force-track::after {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
background: rgba(255, 255, 255, 0.6);
}
.force-fill {
position: absolute;
top: 2px;
bottom: 2px;
left: 50%;
width: 0;
border-radius: 99px;
background: var(--green);
transition: width 50ms linear, left 50ms linear;
}
.force-scale {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #657d93;
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 15px;
}
button {
min-height: 36px;
padding: 8px 10px;
border: 1px solid rgba(145, 184, 220, 0.17);
border-radius: 9px;
background: rgba(26, 48, 70, 0.62);
color: #dceaf7;
font-size: 11px;
font-weight: 720;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease, transform 120ms ease;
}
button:hover {
border-color: rgba(57, 215, 255, 0.4);
background: rgba(35, 65, 91, 0.8);
}
button:active {
transform: translateY(1px);
}
button.primary {
grid-column: 1 / -1;
border-color: rgba(57, 215, 255, 0.35);
background: linear-gradient(135deg, rgba(21, 119, 154, 0.65), rgba(24, 76, 111, 0.8));
color: #ecfbff;
}
.status {
display: flex;
align-items: center;
gap: 10px;
margin-top: 14px;
padding: 11px;
border: 1px solid rgba(94, 230, 168, 0.16);
border-radius: 11px;
background: rgba(94, 230, 168, 0.06);
}
.status.overshoot {
border-color: rgba(255, 120, 109, 0.24);
background: rgba(255, 120, 109, 0.07);
}
.status-icon {
display: grid;
width: 28px;
height: 28px;
place-items: center;
flex: 0 0 auto;
border-radius: 8px;
background: rgba(94, 230, 168, 0.13);
color: var(--green);
font-weight: 900;
}
.status.overshoot .status-icon {
background: rgba(255, 120, 109, 0.13);
color: var(--red);
}
.status-title {
color: var(--green);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status.overshoot .status-title {
color: var(--red);
}
.status-detail {
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px 12px;
margin-top: 15px;
padding-top: 14px;
border-top: 1px solid rgba(145, 184, 220, 0.12);
color: #9fb4c7;
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 12px;
height: 4px;
border-radius: 99px;
background: var(--cyan);
}
.swatch.target { background: var(--orange); }
.swatch.error { background: var(--yellow); }
.swatch.force { background: var(--green); }
.instructions {
margin: 12px 0 0;
color: #6f879b;
font-size: 10px;
line-height: 1.5;
}
.plot-panel {
position: fixed;
z-index: 6;
left: 24px;
bottom: 22px;
width: min(650px, calc(100vw - 405px));
height: 205px;
padding: 12px 13px 8px;
overflow: hidden;
border: 1px solid var(--panel-border);
border-radius: 15px;
background: rgba(8, 19, 34, 0.78);
backdrop-filter: blur(14px);
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.28);
pointer-events: none;
}
.plot-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.plot-title {
color: #dceaf7;
font-size: 11px;
font-weight: 750;
}
.plot-legend {
display: flex;
gap: 12px;
color: #8ea6bd;
font-size: 9px;
}
.plot-legend span::before {
content: "";
display: inline-block;
width: 12px;
height: 3px;
margin: 0 5px 2px 0;
border-radius: 99px;
background: var(--cyan);
}
.plot-legend .target-key::before {
background: repeating-linear-gradient(90deg, var(--orange) 0 4px, transparent 4px 7px);
}
.plot-legend .over-key::before {
background: var(--red);
}
#plot {
display: block;
width: 100%;
height: 157px;
}
.scene-hint {
position: fixed;
z-index: 4;
left: 50%;
bottom: 21px;
transform: translateX(-50%);
padding: 7px 11px;
border: 1px solid rgba(145, 184, 220, 0.12);
border-radius: 99px;
background: rgba(8, 19, 34, 0.62);
color: #7690a6;
font-size: 10px;
pointer-events: none;
}
.world-label {
position: fixed;
z-index: 3;
transform: translate(-50%, -100%);
padding: 4px 7px;
border: 1px solid currentColor;
border-radius: 6px;
background: rgba(4, 12, 23, 0.82);
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.04em;
white-space: nowrap;
pointer-events: none;
box-shadow: 0 5px 16px rgba(0, 0, 0, 0.28);
}
.world-label.target-label { color: var(--orange); }
.world-label.cart-label { color: #a7d8ff; }
@media (max-width: 980px) {
.plot-panel {
width: calc(100vw - 390px);
}
.scene-hint {
display: none;
}
}
@media (max-width: 820px) {
.brand {
top: 14px;
left: 14px;
}
.subtitle {
display: none;
}
.metrics {
top: 78px;
left: 14px;
grid-template-columns: repeat(2, 120px);
}
.metric {
min-height: 58px;
padding: 9px 10px;
}
.metric-value {
font-size: 16px;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 42vh;
}
.plot-panel {
display: none;
}
.legend,
.instructions {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D target-tracking cart simulation"></canvas>
<header class="brand">
<div class="eyebrow">Control Lab / 01</div>
<h1>Target-Tracking Cart</h1>
<p class="subtitle">Proportional control with a bounded actuator and visible inertia</p>
</header>
<section class="metrics" aria-label="Live controller measurements">
<div class="metric">
<span class="metric-label">Target position</span>
<span class="metric-value" id="targetValue">2.20 m</span>
</div>
<div class="metric">
<span class="metric-label">Measured position</span>
<span class="metric-value cyan" id="measuredValue">-0.60 m</span>
</div>
<div class="metric">
<span class="metric-label">Tracking error</span>
<span class="metric-value yellow" id="errorValue">+2.80 m</span>
</div>
<div class="metric">
<span class="metric-label">Applied force</span>
<span class="metric-value green" id="forceValue">+9.00 N</span>
</div>
</section>
<aside class="panel">
<div class="panel-header">
<h2>Controller Parameters</h2>
<span class="live-dot" aria-hidden="true"></span>
</div>
<div class="equation">
<div class="equation-main">
m ẍ = sat<sub>±Fmax</sub>(K<sub>p</sub>(r − y))
</div>
<div class="equation-note">
r = target, y = measured position, m = 1.20 kg<br />
y = x + n(t), with a small deterministic sensor disturbance
</div>
</div>
<div class="control">
<div class="control-row">
<label for="targetRange">Target position, r</label>
<span class="control-value" id="targetControlValue">2.20 m</span>
</div>
<input id="targetRange" type="range" min="-4.6" max="4.6" step="0.05" value="2.2" />
</div>
<div class="control">
<div class="control-row">
<label for="gainRange">Proportional gain, Kp</label>
<span class="control-value" id="gainValue">18.0 N/m</span>
</div>
<input id="gainRange" type="range" min="4" max="32" step="0.5" value="18" />
</div>
<div class="control">
<div class="control-row">
<label for="forceRange">Force limit, Fmax</label>
<span class="control-value" id="forceValueControl">9.0 N</span>
</div>
<input id="forceRange" type="range" min="2" max="14" step="0.5" value="9" />
</div>
<div class="force-section">
<div class="force-heading">
<span>Signed actuator force</span>
<span class="chip" id="saturationChip">Saturated</span>
</div>
<div class="force-track">
<div class="force-fill" id="forceFill"></div>
</div>
<div class="force-scale">
<span id="negativeForceLabel">−9.0 N</span>
<span>0</span>
<span id="positiveForceLabel">+9.0 N</span>
</div>
</div>
<div class="button-grid">
<button id="stepLeft" type="button">Target −1.2 m</button>
<button id="stepRight" type="button">Target +1.2 m</button>
<button id="resetButton" type="button">Reset experiment</button>
<button id="pauseButton" type="button">Pause</button>
<button id="demoButton" class="primary" type="button">Replay overshoot scenario</button>
<button id="cameraButton" type="button">Reset camera view</button>
</div>
<div class="status" id="statusBox">
<div class="status-icon" id="statusIcon">P</div>
<div>
<div class="status-title" id="statusTitle">Tracking</div>
<div class="status-detail" id="statusDetail">The controller is accelerating toward the target.</div>
</div>
</div>
<div class="legend">
<div class="legend-item"><span class="swatch target"></span>Target marker</div>
<div class="legend-item"><span class="swatch"></span>Measured indicator</div>
<div class="legend-item"><span class="swatch error"></span>Error arrow</div>
<div class="legend-item"><span class="swatch force"></span>Applied-force arrow</div>
</div>
<p class="instructions">
Drag the scene to orbit, use the wheel to zoom, or click the rail to move the target.
This pure P controller intentionally has no damping, so a target step produces overshoot.
</p>
</aside>
<section class="plot-panel" aria-label="Controller response graph">
<div class="plot-heading">
<div class="plot-title">Position response</div>
<div class="plot-legend">
<span>Measured</span>
<span class="target-key">Target</span>
<span class="over-key">Beyond target</span>
</div>
</div>
<canvas id="plot"></canvas>
</section>
<div class="scene-hint">Drag to orbit · wheel to zoom · click rail to place target</div>
<div id="targetLabel" class="world-label target-label">TARGET</div>
<div id="measuredLabel" class="world-label">MEASURED</div>
<div id="cartLabel" class="world-label cart-label">CART</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
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.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 16, 34);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
azimuth: 0.62,
polar: 1.10,
radius: 14.5,
target: new THREE.Vector3(0, 0.72, 0)
};
function updateCamera() {
const { azimuth, polar, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(polar) * Math.sin(azimuth),
target.y + radius * Math.cos(polar),
target.z + radius * Math.sin(polar) * Math.cos(azimuth)
);
camera.lookAt(target);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0x9fd8ff, 0x18202d, 2.1);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1d5, 3.3);
sun.position.set(4.5, 10, 6.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 7;
sun.shadow.camera.bottom = -7;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 25;
sun.shadow.bias = -0.0003;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x398dff, 1.25);
rim.position.set(-7, 5, -6);
scene.add(rim);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.76,
metalness: 0.08,
flatShading: true,
...options
});
}
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(42, 30),
material(0x081321, { roughness: 0.96, metalness: 0 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.045;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(30, 30, 0x29425d, 0x15283c);
grid.position.y = -0.035;
grid.material.transparent = true;
grid.material.opacity = 0.27;
scene.add(grid);
// Track
const trackGroup = new THREE.Group();
scene.add(trackGroup);
const bed = new THREE.Mesh(
new THREE.BoxGeometry(12.4, 0.14, 1.5),
material(0x24384b)
);
bed.position.y = 0.08;
bed.receiveShadow = true;
trackGroup.add(bed);
const railMaterial = material(0x668097, { metalness: 0.42, roughness: 0.42 });
for (const z of [-0.5, 0.5]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(12.4, 0.13, 0.13),
railMaterial
);
rail.position.set(0, 0.245, z);
rail.castShadow = true;
rail.receiveShadow = true;
trackGroup.add(rail);
}
const tieMaterial = material(0x17283a);
for (let i = -6; i <= 6; i++) {
const tie = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.06, 1.92),
tieMaterial
);
tie.position.set(i, 0.005, 0);
tie.receiveShadow = true;
trackGroup.add(tie);
}
for (const x of [-6.12, 6.12]) {
const stop = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 0.42, 1.65),
material(0x39526a)
);
stop.position.set(x, 0.24, 0);
stop.castShadow = true;
trackGroup.add(stop);
}
// Low-poly cart
const cart = new THREE.Group();
scene.add(cart);
const cartBlue = material(0x2e91c9, { metalness: 0.15 });
const cartDark = material(0x173c57);
const cartLight = material(0xa9d7ea);
const glass = material(0x0c2639, { metalness: 0.35, roughness: 0.28 });
const chassis = new THREE.Mesh(
new THREE.BoxGeometry(1.38, 0.25, 1.08),
cartDark
);
chassis.position.y = 0.67;
chassis.castShadow = true;
cart.add(chassis);
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.34, 0.42, 0.96),
cartBlue
);
body.position.y = 0.91;
body.castShadow = true;
body.receiveShadow = true;
cart.add(body);
const cab = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 0.5, 0.82),
cartBlue
);
cab.position.set(-0.24, 1.34, 0);
cab.castShadow = true;
cart.add(cab);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(0.82, 0.1, 0.9),
cartLight
);
roof.position.set(-0.24, 1.62, 0);
roof.castShadow = true;
cart.add(roof);
const windshield = new THREE.Mesh(
new THREE.BoxGeometry(0.025, 0.24, 0.62),
glass
);
windshield.position.set(0.135, 1.39, 0);
cart.add(windshield);
const sideWindow = new THREE.Mesh(
new THREE.BoxGeometry(0.5, 0.22, 0.025),
glass
);
sideWindow.position.set(-0.25, 1.4, 0.421);
cart.add(sideWindow);
const bumper = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.13, 1.1),
cartLight
);
bumper.position.set(0.71, 0.69, 0);
bumper.castShadow = true;
cart.add(bumper);
const wheels = [];
const tireGeometry = new THREE.CylinderGeometry(0.22, 0.22, 0.16, 10);
tireGeometry.rotateX(Math.PI / 2);
const hubGeometry = new THREE.CylinderGeometry(0.095, 0.095, 0.185, 8);
hubGeometry.rotateX(Math.PI / 2);
const spokeGeometry = new THREE.BoxGeometry(0.34, 0.045, 0.19);
for (const x of [-0.44, 0.44]) {
for (const z of [-0.54, 0.54]) {
const wheel = new THREE.Group();
wheel.position.set(x, 0.52, z);
const tire = new THREE.Mesh(tireGeometry, material(0x101820, { roughness: 0.96 }));
tire.castShadow = true;
wheel.add(tire);
const hub = new THREE.Mesh(hubGeometry, cartLight);
wheel.add(hub);
const spoke = new THREE.Mesh(spokeGeometry, cartDark);
wheel.add(spoke);
cart.add(wheel);
wheels.push(wheel);
}
}
// Target marker
const targetMarker = new THREE.Group();
scene.add(targetMarker);
const targetMaterial = material(0xff9f43, {
emissive: 0x4b1b00,
emissiveIntensity: 0.7,
roughness: 0.46
});
const targetPole = new THREE.Mesh(
new THREE.CylinderGeometry(0.022, 0.022, 1.8, 6),
targetMaterial
);
targetPole.position.y = 1.2;
targetPole.castShadow = true;
targetMarker.add(targetPole);
const targetDiamond = new THREE.Mesh(
new THREE.OctahedronGeometry(0.22, 0),
targetMaterial
);
targetDiamond.position.y = 2.18;
targetDiamond.castShadow = true;
targetDiamond.userData.isTarget = true;
targetMarker.add(targetDiamond);
const targetRing = new THREE.Mesh(
new THREE.TorusGeometry(0.33, 0.045, 6, 20),
targetMaterial
);
targetRing.rotation.x = Math.PI / 2;
targetRing.position.y = 0.34;
targetRing.userData.isTarget = true;
targetMarker.add(targetRing);
// Measured-position indicator
const measuredMarker = new THREE.Group();
scene.add(measuredMarker);
const measuredMaterial = material(0x39d7ff, {
emissive: 0x073a52,
emissiveIntensity: 0.9,
roughness: 0.4
});
const measuredStem = new THREE.Mesh(
new THREE.CylinderGeometry(0.018, 0.018, 0.72, 6),
measuredMaterial
);
measuredStem.position.y = 0.76;
measuredMarker.add(measuredStem);
const measuredTip = new THREE.Mesh(
new THREE.ConeGeometry(0.11, 0.25, 6),
measuredMaterial
);
measuredTip.rotation.z = Math.PI;
measuredTip.position.y = 1.18;
measuredMarker.add(measuredTip);
const measuredRing = new THREE.Mesh(
new THREE.TorusGeometry(0.16, 0.025, 6, 16),
measuredMaterial
);
measuredRing.rotation.x = Math.PI / 2;
measuredRing.position.y = 0.38;
measuredMarker.add(measuredRing);
// Error and applied-force arrows
const errorArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0xffd36a,
0.18,
0.12
);
scene.add(errorArrow);
const forceArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0x5ee6a8,
0.16,
0.11
);
scene.add(forceArrow);
for (const arrow of [errorArrow, forceArrow]) {
arrow.line.material.depthTest = false;
arrow.cone.material.depthTest = false;
arrow.line.renderOrder = 8;
arrow.cone.renderOrder = 8;
arrow.line.material.transparent = true;
arrow.cone.material.transparent = true;
arrow.line.material.opacity = 0.92;
arrow.cone.material.opacity = 0.92;
}
// Simulation state
const state = {
x: -0.6,
v: 0,
measured: -0.6,
target: 2.2,
kp: 18,
maxForce: 9,
mass: 1.2,
rawForce: 0,
force: 0,
time: 0,
paused: false,
overshoot: false,
overshootPeak: 0
};
const history = [];
const FIXED_DT = 1 / 120;
let accumulator = 0;
let lastSampleTime = 0;
const clamp = THREE.MathUtils.clamp;
function sensorNoise(time) {
return (
0.018 * Math.sin(time * 8.7) +
0.012 * Math.sin(time * 19.1 + 0.7)
);
}
function stepSimulation(dt) {
state.time += dt;
const measurementBeforeUpdate = state.x + sensorNoise(state.time);
const error = state.target - measurementBeforeUpdate;
state.rawForce = state.kp * error;
state.force = clamp(
state.rawForce,
-state.maxForce,
state.maxForce
);
// Pure proportional controller:
// m * x'' = sat_{[-Fmax,Fmax]} (Kp * (r - y))
const acceleration = state.force / state.mass;
state.v += acceleration * dt;
state.x += state.v * dt;
// Hard end stops prevent the visualization from leaving the track.
if (state.x > 5.35) {
state.x = 5.35;
state.v = -Math.abs(state.v) * 0.15;
} else if (state.x < -5.35) {
state.x = -5.35;
state.v = Math.abs(state.v) * 0.15;
}
state.measured = state.x + sensorNoise(state.time);
if (state.measured > state.target + 0.08) {
state.overshoot = true;
state.overshootPeak = Math.max(
state.overshootPeak,
state.measured - state.target
);
}
if (state.time - lastSampleTime >= 0.04) {
lastSampleTime = state.time;
history.push({
t: state.time,
target: state.target,
measured: state.measured,
x: state.x
});
if (history.length > 900) history.shift();
}
}
function setTarget(value) {
state.target = clamp(value, -4.6, 4.6);
state.overshoot = false;
state.overshootPeak = 0;
targetRange.value = state.target.toFixed(2);
}
function resetSimulation() {
state.x = -0.6;
state.v = 0;
state.measured = -0.6;
state.target = 2.2;
state.kp = 18;
state.maxForce = 9;
state.time = 0;
state.rawForce = 0;
state.force = 0;
state.overshoot = false;
state.overshootPeak = 0;
state.paused = false;
accumulator = 0;
lastSampleTime = 0;
history.length = 0;
history.push({ t: 0, target: state.target, measured: state.measured, x: state.x });
targetRange.value = state.target.toFixed(2);
gainRange.value = state.kp.toFixed(1);
forceRange.value = state.maxForce.toFixed(1);
pauseButton.textContent = "Pause";
}
// UI references
const targetRange = document.getElementById("targetRange");
const gainRange = document.getElementById("gainRange");
const forceRange = document.getElementById("forceRange");
const pauseButton = document.getElementById("pauseButton");
const targetValue = document.getElementById("targetValue");
const measuredValue = document.getElementById("measuredValue");
const errorValue = document.getElementById("errorValue");
const forceValue = document.getElementById("forceValue");
const targetControlValue = document.getElementById("targetControlValue");
const gainValue = document.getElementById("gainValue");
const forceValueControl = document.getElementById("forceValueControl");
const saturationChip = document.getElementById("saturationChip");
const forceFill = document.getElementById("forceFill");
const negativeForceLabel = document.getElementById("negativeForceLabel");
const positiveForceLabel = document.getElementById("positiveForceLabel");
const statusBox = document.getElementById("statusBox");
const statusIcon = document.getElementById("statusIcon");
const statusTitle = document.getElementById("statusTitle");
const statusDetail = document.getElementById("statusDetail");
targetRange.addEventListener("input", () => {
setTarget(Number(targetRange.value));
});
gainRange.addEventListener("input", () => {
state.kp = Number(gainRange.value);
});
forceRange.addEventListener("input", () => {
state.maxForce = Number(forceRange.value);
});
document.getElementById("stepLeft").addEventListener("click", () => {
setTarget(state.target - 1.2);
});
document.getElementById("stepRight").addEventListener("click", () => {
setTarget(state.target + 1.2);
});
document.getElementById("resetButton").addEventListener("click", resetSimulation);
document.getElementById("demoButton").addEventListener("click", resetSimulation);
pauseButton.addEventListener("click", () => {
state.paused = !state.paused;
pauseButton.textContent = state.paused ? "Resume" : "Pause";
});
document.getElementById("cameraButton").addEventListener("click", () => {
cameraState.azimuth = 0.62;
cameraState.polar = 1.10;
cameraState.radius = 14.5;
updateCamera();
});
function signed(value, digits = 2) {
return `${value >= 0 ? "+" : ""}${value.toFixed(digits)}`;
}
function updateUI() {
const error = state.target - state.measured;
const saturated = Math.abs(state.rawForce) > state.maxForce + 1e-6;
targetValue.textContent = `${state.target.toFixed(2)} m`;
measuredValue.textContent = `${state.measured.toFixed(2)} m`;
errorValue.textContent = `${signed(error)} m`;
forceValue.textContent = `${signed(state.force)} N`;
targetControlValue.textContent = `${state.target.toFixed(2)} m`;
gainValue.textContent = `${state.kp.toFixed(1)} N/m`;
forceValueControl.textContent = `${state.maxForce.toFixed(1)} N`;
saturationChip.textContent = saturated ? "Saturated" : "Within limit";
saturationChip.classList.toggle("saturated", saturated);
const forceRatio = clamp(state.force / state.maxForce, -1, 1);
const width = Math.abs(forceRatio) * 50;
forceFill.style.width = `${width}%`;
forceFill.style.left = `${forceRatio >= 0 ? 50 : 50 - width}%`;
forceFill.style.background = saturated ? "var(--orange)" : "var(--green)";
negativeForceLabel.textContent = `−${state.maxForce.toFixed(1)} N`;
positiveForceLabel.textContent = `+${state.maxForce.toFixed(1)} N`;
if (state.overshoot) {
statusBox.classList.add("overshoot");
statusIcon.textContent = "!";
statusTitle.textContent = "Overshoot observed";
statusDetail.textContent =
`Measured position passed the target by ${state.overshootPeak.toFixed(2)} m.`;
} else if (Math.abs(error) < 0.08) {
statusBox.classList.remove("overshoot");
statusIcon.textContent = "✓";
statusTitle.textContent = "On target";
statusDetail.textContent = "The tracking error is within the 8 cm display tolerance.";
} else {
statusBox.classList.remove("overshoot");
statusIcon.textContent = "P";
statusTitle.textContent = saturated ? "Actuator saturated" : "Tracking";
statusDetail.textContent = saturated
? "The force demand exceeds the bounded actuator limit."
: "The proportional controller is moving toward the target.";
}
}
const targetLabel = document.getElementById("targetLabel");
const measuredLabel = document.getElementById("measuredLabel");
const cartLabel = document.getElementById("cartLabel");
const labelPoint = new THREE.Vector3();
function positionLabel(element, x, y, z) {
labelPoint.set(x, y, z).project(camera);
const visible = labelPoint.z > -1 && labelPoint.z < 1;
element.style.opacity = visible ? "1" : "0";
element.style.left = `${(labelPoint.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-labelPoint.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function updateVisuals() {
cart.position.x = state.x;
for (const wheel of wheels) {
wheel.rotation.z = -state.x / 0.22;
}
targetMarker.position.x = state.target;
targetDiamond.rotation.y = state.time * 0.8;
targetDiamond.position.y = 2.18 + Math.sin(state.time * 2.1) * 0.045;
measuredMarker.position.x = state.measured;
const error = state.target - state.measured;
const errorLength = Math.abs(error);
errorArrow.visible = errorLength > 0.025;
if (errorArrow.visible) {
errorArrow.position.set(state.measured, 1.08, 0.66);
errorArrow.setDirection(
new THREE.Vector3(error >= 0 ? 1 : -1, 0, 0)
);
errorArrow.setLength(
errorLength,
Math.min(0.22, errorLength * 0.3),
Math.min(0.14, errorLength * 0.2)
);
}
const forceDirection = state.force >= 0 ? 1 : -1;
const forceLength = Math.abs(state.force) / state.maxForce * 1.12;
forceArrow.visible = forceLength > 0.015;
if (forceArrow.visible) {
forceArrow.position.set(state.x, 1.55, -0.72);
forceArrow.setDirection(new THREE.Vector3(forceDirection, 0, 0));
forceArrow.setLength(forceLength, 0.17, 0.11);
}
targetLabel.textContent = `TARGET r = ${state.target.toFixed(2)} m`;
measuredLabel.textContent = `MEASURED y = ${state.measured.toFixed(2)} m`;
cartLabel.textContent = `CART x = ${state.x.toFixed(2)} m`;
positionLabel(targetLabel, state.target, 2.55, 0);
positionLabel(measuredLabel, state.measured, 0.42, 0.45);
positionLabel(cartLabel, state.x, 1.92, 0);
}
// Response graph
const plot = document.getElementById("plot");
const plotContext = plot.getContext("2d");
function drawPlot() {
const rect = plot.getBoundingClientRect();
if (rect.width < 2 || rect.height < 2) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const pixelWidth = Math.round(rect.width * dpr);
const pixelHeight = Math.round(rect.height * dpr);
if (plot.width !== pixelWidth || plot.height !== pixelHeight) {
plot.width = pixelWidth;
plot.height = pixelHeight;
}
const ctx = plotContext;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, rect.width, rect.height);
const pad = { left: 37, right: 12, top: 12, bottom: 25 };
const w = rect.width - pad.left - pad.right;
const h = rect.height - pad.top - pad.bottom;
const minX = -5.5;
const maxX = 5.5;
const minY = -5.5;
const maxY = 5.5;
const mapX = x => pad.left + ((x - minX) / (maxX - minX)) * w;
const mapY = y => pad.top + ((maxY - y) / (maxY - minY)) * h;
ctx.font = "9px system-ui, sans-serif";
ctx.textBaseline = "middle";
for (const value of [-5, -2.5, 0, 2.5, 5]) {
const y = mapY(value);
ctx.strokeStyle = "rgba(126, 158, 188, 0.11)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(pad.left, y);
ctx.lineTo(pad.left + w, y);
ctx.stroke();
ctx.fillStyle = "#627b91";
ctx.textAlign = "right";
ctx.fillText(value.toFixed(1), pad.left - 7, y);
}
ctx.textAlign = "center";
for (const value of [-5, 0, 5]) {
ctx.fillStyle = "#627b91";
ctx.fillText(`${value} m`, mapX(value), rect.height - 10);
}
if (history.length < 2) return;
// Actual cart position.
ctx.strokeStyle = "rgba(116, 170, 208, 0.22)";
ctx.lineWidth = 1;
ctx.beginPath();
history.forEach((sample, i) => {
const px = mapX(sample.x);
const py = mapY(sample.x);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
// Target trajectory.
ctx.strokeStyle = "rgba(255, 173, 85, 0.78)";
ctx.lineWidth = 1.4;
ctx.setLineDash([5, 4]);
ctx.beginPath();
history.forEach((sample, i) => {
const px = mapX(sample.target);
const py = mapY(sample.target);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
ctx.stroke();
ctx.setLineDash([]);
// Measured response, with portions beyond the target highlighted.
ctx.lineWidth = 2.1;
for (let i = 1; i < history.length; i++) {
const a = history[i - 1];
const b = history[i];
const beyond = a.measured > a.target + 0.05 || b.measured > b.target + 0.05;
ctx.strokeStyle = beyond ? "#ff786d" : "#39d7ff";
ctx.beginPath();
ctx.moveTo(mapX(a.x), mapY(a.measured));
ctx.lineTo(mapX(b.x), mapY(b.measured));
ctx.stroke();
}
}
// Custom camera controls; no add-ons are used.
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
const drag = {
active: false,
moved: 0,
x: 0,
y: 0
};
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
drag.active = true;
drag.moved = 0;
drag.x = event.clientX;
drag.y = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!drag.active) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
drag.moved += Math.abs(dx) + Math.abs(dy);
drag.x = event.clientX;
drag.y = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.polar = clamp(
cameraState.polar - dy * 0.005,
0.48,
1.43
);
updateCamera();
});
canvas.addEventListener("pointerup", event => {
if (!drag.active) return;
drag.active = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (drag.moved < 7) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(
[bed, targetDiamond, targetRing],
false
);
if (hits.length > 0) {
const hit = hits[0];
if (!hit.object.userData.isTarget) {
setTarget(hit.point.x);
}
}
}
});
canvas.addEventListener("pointercancel", () => {
drag.active = false;
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius + event.deltaY * 0.012,
8.5,
23
);
updateCamera();
}, { passive: false });
window.addEventListener("resize", () => {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
resetSimulation();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const frameDelta = Math.min(clock.getDelta(), 0.05);
if (!state.paused) {
accumulator = Math.min(accumulator + frameDelta, 0.15);
while (accumulator >= FIXED_DT) {
stepSimulation(FIXED_DT);
accumulator -= FIXED_DT;
}
}
updateVisuals();
updateUI();
drawPlot();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```