Prompt specification
Build or customize the Three.js 3D scene "Position-feedback toy 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: Position-feedback toy controller
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/position-feedback-toy-controller-x1016
Scene Description Prompt:
Let users compare open-loop and feedback-corrected motion in a simplified arm rig; display target error and state that the controller is an engineering analogy for proprioception. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (position-feedback-toy-controller-x1016):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Open Loop vs Feedback Motion</title>
<style>
:root {
--bg: #eef2f6;
--panel: #ffffff;
--ink: #17212b;
--muted: #657383;
--line: #d8e0e8;
--open: #ed8747;
--feedback: #18aa9d;
--target: #526ee8;
--danger: #e65353;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
color: var(--ink);
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
header {
z-index: 5;
flex: 0 0 auto;
padding: 14px 22px 12px;
background: rgba(255, 255, 255, 0.92);
border-bottom: 1px solid var(--line);
box-shadow: 0 5px 20px rgba(35, 48, 65, 0.06);
}
.title-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
}
h1 {
margin: 0;
font-size: clamp(18px, 2vw, 25px);
line-height: 1.15;
letter-spacing: -0.025em;
}
.subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 13px;
}
.analogy {
max-width: 560px;
padding: 10px 13px;
color: #425162;
background: #f3f6fa;
border: 1px solid #dde5ed;
border-radius: 12px;
font-size: 12px;
line-height: 1.45;
}
.analogy strong {
color: #263747;
}
#stage {
position: relative;
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.rig-card {
position: absolute;
top: 15px;
width: 218px;
padding: 10px 12px;
pointer-events: none;
background: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(209, 219, 229, 0.95);
border-top-width: 4px;
border-radius: 12px;
box-shadow: 0 8px 24px rgba(33, 47, 65, 0.09);
backdrop-filter: blur(8px);
}
.rig-card.open {
left: 25%;
transform: translateX(-50%);
border-top-color: var(--open);
}
.rig-card.feedback {
left: 75%;
transform: translateX(-50%);
border-top-color: var(--feedback);
}
.rig-name {
font-size: 11px;
font-weight: 800;
letter-spacing: 0.11em;
}
.rig-card.open .rig-name {
color: #c5682f;
}
.rig-card.feedback .rig-name {
color: #087f77;
}
.rig-description {
margin-top: 2px;
color: var(--muted);
font-size: 11px;
}
.error-value {
display: flex;
align-items: baseline;
gap: 7px;
margin-top: 7px;
}
.error-value strong {
font-size: 25px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.error-value span {
color: var(--muted);
font-size: 11px;
}
.comparison-chip {
position: absolute;
top: 16px;
left: 50%;
transform: translateX(-50%);
max-width: 230px;
padding: 8px 11px;
color: #425162;
background: rgba(255, 255, 255, 0.86);
border: 1px solid var(--line);
border-radius: 999px;
box-shadow: 0 5px 16px rgba(33, 47, 65, 0.07);
font-size: 11px;
text-align: center;
pointer-events: none;
}
.camera-hint {
position: absolute;
right: 12px;
bottom: 10px;
padding: 6px 9px;
color: #526171;
background: rgba(255, 255, 255, 0.75);
border: 1px solid rgba(213, 222, 231, 0.9);
border-radius: 8px;
font-size: 10px;
pointer-events: none;
}
#event-toast {
position: absolute;
left: 50%;
bottom: 28px;
transform: translate(-50%, 10px);
padding: 9px 14px;
color: white;
background: rgba(35, 48, 63, 0.9);
border-radius: 999px;
font-size: 12px;
opacity: 0;
transition:
opacity 160ms ease,
transform 160ms ease;
pointer-events: none;
}
#event-toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
footer {
z-index: 4;
flex: 0 0 auto;
padding: 11px 18px 12px;
background: rgba(255, 255, 255, 0.95);
border-top: 1px solid var(--line);
box-shadow: 0 -5px 20px rgba(35, 48, 65, 0.05);
}
.footer-grid {
display: grid;
grid-template-columns: minmax(360px, 1fr) minmax(430px, 1.25fr);
gap: 15px;
align-items: stretch;
}
.control-panel,
.chart-panel {
min-width: 0;
padding: 10px 12px;
background: #f7f9fb;
border: 1px solid #e0e7ee;
border-radius: 12px;
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
button {
appearance: none;
padding: 8px 11px;
color: #293848;
background: white;
border: 1px solid #d4dde6;
border-radius: 8px;
font: inherit;
font-size: 12px;
font-weight: 650;
cursor: pointer;
transition:
background 120ms ease,
transform 120ms ease,
border-color 120ms ease;
}
button:hover {
background: #f0f4f8;
border-color: #bdc9d6;
}
button:active {
transform: translateY(1px);
}
button.primary {
color: white;
background: #344a5f;
border-color: #344a5f;
}
button.primary:hover {
background: #25394b;
}
button.load {
color: #9a3737;
background: #fff4f3;
border-color: #f0c9c5;
}
.options-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 13px;
margin-top: 9px;
color: #526171;
font-size: 11px;
}
.options-row label {
display: inline-flex;
align-items: center;
gap: 5px;
cursor: pointer;
}
input[type="range"] {
width: 95px;
accent-color: #425d73;
}
input[type="checkbox"] {
accent-color: #425d73;
}
.speed-label {
min-width: 42px;
font-variant-numeric: tabular-nums;
}
.chart-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.chart-card {
min-width: 0;
}
.chart-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 5px;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.05em;
}
.chart-title .open-text {
color: #c5682f;
}
.chart-title .feedback-text {
color: #087f77;
}
.chart-title small {
color: var(--muted);
font-size: 9px;
font-weight: 500;
letter-spacing: 0;
}
canvas.chart {
display: block;
width: 100%;
height: 82px;
background: white;
border: 1px solid #e1e7ed;
border-radius: 7px;
}
.analogy-note {
margin-top: 8px;
color: #637181;
font-size: 10px;
line-height: 1.35;
}
.analogy-note strong {
color: #405162;
}
@media (max-width: 900px) {
.title-row {
align-items: flex-start;
}
.analogy {
max-width: 410px;
}
.footer-grid {
grid-template-columns: 1fr;
}
body {
height: auto;
min-height: 100vh;
overflow: auto;
}
#stage {
flex: none;
height: 58vh;
min-height: 430px;
}
}
@media (max-width: 650px) {
header {
padding: 12px;
}
.title-row {
display: block;
}
.analogy {
margin-top: 10px;
}
.rig-card {
top: 10px;
width: 170px;
padding: 8px 9px;
}
.rig-description {
display: none;
}
.error-value strong {
font-size: 21px;
}
.comparison-chip {
top: 92px;
max-width: 250px;
}
.chart-grid {
grid-template-columns: 1fr;
}
footer {
padding: 10px;
}
}
</style>
</head>
<body>
<header>
<div class="title-row">
<div>
<h1>Open Loop vs. Feedback Motion</h1>
<p class="subtitle">
Same moving target, same external load, two different control policies.
</p>
</div>
<div class="analogy">
<strong>Engineering analogy for proprioception:</strong>
the feedback arm uses sensed pose error to correct its motion.
This is a control-system illustration, not a biological model.
</div>
</div>
</header>
<main id="stage">
<section class="rig-card open">
<div class="rig-name">OPEN LOOP</div>
<div class="rig-description">Pre-planned joint trajectory</div>
<div class="error-value">
<strong id="open-error">0.0</strong>
<span>cm target error</span>
</div>
</section>
<section class="rig-card feedback">
<div class="rig-name">FEEDBACK</div>
<div class="rig-description">Error-driven joint correction</div>
<div class="error-value">
<strong id="feedback-error">0.0</strong>
<span>cm target error</span>
</div>
</section>
<div class="comparison-chip" id="comparison-chip">
Waiting for simulation…
</div>
<div class="camera-hint">
Drag to orbit · wheel to zoom · double-click to reset view
</div>
<div id="event-toast">External load pulse applied to both arms</div>
</main>
<footer>
<div class="footer-grid">
<section class="control-panel">
<div class="button-row">
<button id="pause-button" class="primary" type="button">Pause</button>
<button id="disturb-button" class="load" type="button">
Apply load pulse
</button>
<button id="reset-button" type="button">Reset trial</button>
<button id="camera-button" type="button">Reset camera</button>
</div>
<div class="options-row">
<label>
Speed
<input id="speed-input" type="range" min="0.25" max="2" step="0.25" value="1">
<span class="speed-label" id="speed-label">1.00×</span>
</label>
<label>
<input id="auto-input" type="checkbox" checked>
Auto pulse every 7.5 s
</label>
<label>
<input id="trails-input" type="checkbox" checked>
Show motion trails
</label>
</div>
<div class="analogy-note">
<strong>Controller analogy:</strong>
proprioception compares sensed limb state with intended state and helps
correct action. Here, the feedback controller measures end-effector
error and updates its joint commands.
</div>
</section>
<section class="chart-panel">
<div class="chart-grid">
<div class="chart-card">
<div class="chart-title">
<span class="open-text">OPEN LOOP ERROR</span>
<small>centimeters</small>
</div>
<canvas id="open-chart" class="chart"></canvas>
</div>
<div class="chart-card">
<div class="chart-title">
<span class="feedback-text">FEEDBACK ERROR</span>
<small>centimeters</small>
</div>
<canvas id="feedback-chart" class="chart"></canvas>
</div>
</div>
</section>
</div>
</footer>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and simulation state
// -------------------------------------------------------------------------
const L1 = 1.35;
const L2 = 1.25;
const SHOULDER_Y = 2.25;
const CM_PER_UNIT = 20;
const PLANT_RATE = 5.2;
const KP = 0.45;
const KI = 0.55;
const MAX_TRAIL_POINTS = 220;
const stage = document.querySelector("#stage");
const openErrorElement = document.querySelector("#open-error");
const feedbackErrorElement = document.querySelector("#feedback-error");
const comparisonChip = document.querySelector("#comparison-chip");
const pauseButton = document.querySelector("#pause-button");
const disturbButton = document.querySelector("#disturb-button");
const resetButton = document.querySelector("#reset-button");
const cameraButton = document.querySelector("#camera-button");
const speedInput = document.querySelector("#speed-input");
const speedLabel = document.querySelector("#speed-label");
const autoInput = document.querySelector("#auto-input");
const trailsInput = document.querySelector("#trails-input");
const eventToast = document.querySelector("#event-toast");
let paused = false;
let simulationTime = 0;
let disturbanceStart = -Infinity;
let nextAutomaticDisturbance = 4;
let trailSampleAccumulator = 0;
let errorSampleAccumulator = 0;
let toastTimer = 0;
const openHistory = [];
const feedbackHistory = [];
// -------------------------------------------------------------------------
// Renderer, scene, lighting, and camera
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D comparison of open-loop and feedback-corrected robotic arms"
);
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeaf0f5);
scene.fog = new THREE.Fog(0xeaf0f5, 17, 34);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const cameraState = {
yaw: 0.02,
pitch: 0.47,
radius: 11.4,
target: new THREE.Vector3(0, 1.15, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
const horizontal = radius * Math.cos(pitch);
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * radius,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.yaw = 0.02;
cameraState.pitch = 0.47;
const aspect = stage.clientWidth / Math.max(stage.clientHeight, 1);
cameraState.radius = THREE.MathUtils.clamp(14.3 / aspect, 10.8, 24);
updateCamera();
}
const hemisphere = new THREE.HemisphereLight(0xf7fbff, 0x82909c, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(-5, 10, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 30;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xb9d5ff, 1.0);
fillLight.position.set(7, 5, -5);
scene.add(fillLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 30),
new THREE.MeshStandardMaterial({
color: 0xdce4eb,
roughness: 0.96,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.32;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(30, 30, 0xb9c6d1, 0xcbd5df);
grid.position.y = -0.305;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
// -------------------------------------------------------------------------
// Kinematics
// -------------------------------------------------------------------------
function clamp(value, minimum, maximum) {
return Math.max(minimum, Math.min(maximum, value));
}
function targetAt(time) {
return {
x: 0.78 * Math.sin(1.15 * time + 0.20),
y: 0.68 + 0.28 * Math.sin(2.30 * time + 0.80)
};
}
function inverseKinematics(target) {
const dx = target.x;
const dy = target.y - SHOULDER_Y;
const distanceSquared = dx * dx + dy * dy;
const cosineB = clamp(
(distanceSquared - L1 * L1 - L2 * L2) / (2 * L1 * L2),
-1,
1
);
// Choose one consistent elbow branch for both arms.
const b = -Math.acos(cosineB);
const offset = Math.atan2(
L2 * Math.sin(b),
L1 + L2 * Math.cos(b)
);
const a = Math.atan2(dx, -dy) - offset;
return [a, b];
}
function forwardKinematics(angles) {
const [a, b] = angles;
return {
x: L1 * Math.sin(a) + L2 * Math.sin(a + b),
y:
SHOULDER_Y -
L1 * Math.cos(a) -
L2 * Math.cos(a + b)
};
}
function jacobian(angles) {
const [a, b] = angles;
return {
j00: L1 * Math.cos(a) + L2 * Math.cos(a + b),
j01: L2 * Math.cos(a + b),
j10: L1 * Math.sin(a) + L2 * Math.sin(a + b),
j11: L2 * Math.sin(a + b)
};
}
function solveJointDelta(angles, errorX, errorY) {
const J = jacobian(angles);
const determinant = J.j00 * J.j11 - J.j01 * J.j10;
// Damped fallback near a singular configuration.
if (Math.abs(determinant) < 0.035) {
return [
0.28 * (J.j00 * errorX + J.j10 * errorY),
0.28 * (J.j01 * errorX + J.j11 * errorY)
];
}
return [
(errorX * J.j11 - J.j01 * errorY) / determinant,
(J.j00 * errorY - errorX * J.j10) / determinant
];
}
function disturbanceEnvelope() {
const age = simulationTime - disturbanceStart;
if (age < 0 || age >= 2.7) {
return 0;
}
if (age < 0.25) {
return age / 0.25;
}
if (age < 2.0) {
return 1;
}
return 1 - (age - 2.0) / 0.7;
}
function disturbanceBias() {
const envelope = disturbanceEnvelope();
// Identical external bias is applied to both rigs.
return [
0.30 * envelope,
-0.20 * envelope
];
}
// -------------------------------------------------------------------------
// Low-poly rig construction
// -------------------------------------------------------------------------
function createTrail() {
const positions = new Float32Array(MAX_TRAIL_POINTS * 3);
const geometry = new THREE.BufferGeometry();
const attribute = new THREE.BufferAttribute(positions, 3);
attribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute("position", attribute);
geometry.setDrawRange(0, 0);
const line = new THREE.Line(
geometry,
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.7
})
);
line.frustumCulled = false;
return {
line,
count: 0,
add(x, y) {
if (this.count < MAX_TRAIL_POINTS) {
const index = this.count * 3;
positions[index] = x;
positions[index + 1] = y;
positions[index + 2] = 0.36;
this.count++;
} else {
positions.copyWithin(0, 3);
const index = (MAX_TRAIL_POINTS - 1) * 3;
positions[index] = x;
positions[index + 1] = y;
positions[index + 2] = 0.36;
}
attribute.needsUpdate = true;
geometry.setDrawRange(0, this.count);
},
clear() {
this.count = 0;
geometry.setDrawRange(0, 0);
}
};
}
function createRig(xPosition, accentColor, type) {
const group = new THREE.Group();
group.position.x = xPosition;
scene.add(group);
const accent = new THREE.Color(accentColor);
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0xf4f7fa,
roughness: 0.86,
metalness: 0.03
});
const platform = new THREE.Mesh(
new THREE.BoxGeometry(4.55, 0.18, 3.0),
platformMaterial
);
platform.position.y = -0.19;
platform.receiveShadow = true;
platform.castShadow = true;
group.add(platform);
const accentStrip = new THREE.Mesh(
new THREE.BoxGeometry(3.9, 0.055, 0.08),
new THREE.MeshStandardMaterial({
color: accent,
emissive: accent,
emissiveIntensity: 0.08,
roughness: 0.6
})
);
accentStrip.position.set(0, -0.07, 1.47);
group.add(accentStrip);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.48, 0.56, 0.28, 8),
new THREE.MeshStandardMaterial({
color: 0x657586,
roughness: 0.72,
metalness: 0.18,
flatShading: true
})
);
base.position.y = 0.03;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const column = new THREE.Mesh(
new THREE.BoxGeometry(0.32, 1.85, 0.32),
new THREE.MeshStandardMaterial({
color: 0x8794a2,
roughness: 0.72,
metalness: 0.12,
flatShading: true
})
);
column.position.set(0, 1.08, -0.15);
column.castShadow = true;
group.add(column);
const armMaterial = new THREE.MeshStandardMaterial({
color: accent,
roughness: 0.56,
metalness: 0.08,
flatShading: true
});
const jointMaterial = new THREE.MeshStandardMaterial({
color: 0x334253,
roughness: 0.45,
metalness: 0.32,
flatShading: true
});
const shoulderGroup = new THREE.Group();
shoulderGroup.position.set(0, SHOULDER_Y, 0.14);
group.add(shoulderGroup);
const shoulderJoint = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.25, 0),
jointMaterial
);
shoulderJoint.castShadow = true;
shoulderGroup.add(shoulderJoint);
const upperArm = new THREE.Mesh(
new THREE.CylinderGeometry(0.17, 0.20, L1, 6),
armMaterial
);
upperArm.position.y = -L1 / 2;
upperArm.castShadow = true;
shoulderGroup.add(upperArm);
const elbowGroup = new THREE.Group();
elbowGroup.position.set(0, -L1, 0);
shoulderGroup.add(elbowGroup);
const elbowJoint = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.205, 0),
jointMaterial
);
elbowJoint.castShadow = true;
elbowGroup.add(elbowJoint);
const forearm = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.155, L2, 6),
armMaterial
);
forearm.position.y = -L2 / 2;
forearm.castShadow = true;
elbowGroup.add(forearm);
const hand = new THREE.Mesh(
new THREE.OctahedronGeometry(0.15, 0),
jointMaterial
);
hand.position.y = -L2;
hand.castShadow = true;
elbowGroup.add(hand);
// A visible sensor marker emphasizes the feedback rig.
const sensorMaterial = new THREE.MeshStandardMaterial({
color: type === "feedback" ? 0xb9fff7 : 0xffe0c9,
emissive: type === "feedback" ? 0x19b8aa : 0xe88747,
emissiveIntensity: 0.65,
roughness: 0.4
});
const sensor = new THREE.Mesh(
new THREE.OctahedronGeometry(0.075, 0),
sensorMaterial
);
sensor.position.set(0.15, -L2 * 0.58, 0.07);
elbowGroup.add(sensor);
// Static path guide.
const pathPoints = [];
for (let i = 0; i <= 160; i++) {
const pathTarget = targetAt((i / 160) * 10.7);
pathPoints.push(
new THREE.Vector3(pathTarget.x, pathTarget.y, 0.31)
);
}
const pathLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(pathPoints),
new THREE.LineBasicMaterial({
color: 0x526ee8,
transparent: true,
opacity: 0.22
})
);
group.add(pathLine);
// Moving target beacon.
const targetGroup = new THREE.Group();
targetGroup.position.z = 0.38;
group.add(targetGroup);
const targetCore = new THREE.Mesh(
new THREE.OctahedronGeometry(0.105, 0),
new THREE.MeshStandardMaterial({
color: 0x526ee8,
emissive: 0x526ee8,
emissiveIntensity: 0.7,
roughness: 0.35,
flatShading: true
})
);
targetGroup.add(targetCore);
const targetRing = new THREE.Mesh(
new THREE.TorusGeometry(0.205, 0.022, 4, 18),
new THREE.MeshBasicMaterial({
color: 0x526ee8,
transparent: true,
opacity: 0.75
})
);
targetGroup.add(targetRing);
// End-effector error connector.
const errorGeometry = new THREE.BufferGeometry();
errorGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const errorLine = new THREE.Line(
errorGeometry,
new THREE.LineBasicMaterial({
color: accent,
transparent: true,
opacity: 0.85
})
);
errorLine.frustumCulled = false;
group.add(errorLine);
// Load-pulse indicator.
const loadMaterial = new THREE.MeshStandardMaterial({
color: 0x7f3030,
emissive: 0xe65353,
emissiveIntensity: 0.03,
roughness: 0.4
});
const loadLamp = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
loadMaterial
);
loadLamp.position.set(1.78, 2.48, 0.12);
group.add(loadLamp);
const trail = createTrail();
trail.line.material.color.copy(accent);
group.add(trail.line);
const initialAngles = inverseKinematics(targetAt(0));
return {
type,
group,
shoulderGroup,
elbowGroup,
targetGroup,
targetCore,
targetRing,
errorLine,
trail,
loadLamp,
loadMaterial,
angles: [...initialAngles],
integral: [0, 0],
errorCm: 0
};
}
const openRig = createRig(-3.08, 0xed8747, "open");
const feedbackRig = createRig(3.08, 0x18aa9d, "feedback");
// -------------------------------------------------------------------------
// Simulation
// -------------------------------------------------------------------------
function updateRig(rig, dt) {
const target = targetAt(simulationTime);
const nominalAngles = inverseKinematics(target);
const [biasA, biasB] = disturbanceBias();
const blend = 1 - Math.exp(-PLANT_RATE * dt);
if (rig.type === "open") {
// The open-loop controller executes a time-indexed joint program.
// It never uses the measured end-effector error.
const desiredA = nominalAngles[0] + biasA;
const desiredB = nominalAngles[1] + biasB;
rig.angles[0] += (desiredA - rig.angles[0]) * blend;
rig.angles[1] += (desiredB - rig.angles[1]) * blend;
} else {
const endpoint = forwardKinematics(rig.angles);
const errorX = target.x - endpoint.x;
const errorY = target.y - endpoint.y;
const delta = solveJointDelta(rig.angles, errorX, errorY);
// Integral feedback estimates and cancels persistent disturbance.
rig.integral[0] = clamp(
rig.integral[0] + delta[0] * dt,
-0.8,
0.8
);
rig.integral[1] = clamp(
rig.integral[1] + delta[1] * dt,
-0.8,
0.8
);
const correctionA = clamp(
KP * delta[0] + KI * rig.integral[0],
-0.65,
0.65
);
const correctionB = clamp(
KP * delta[1] + KI * rig.integral[1],
-0.65,
0.65
);
const commandA = nominalAngles[0] + correctionA;
const commandB = nominalAngles[1] + correctionB;
const desiredA = commandA + biasA;
const desiredB = commandB + biasB;
rig.angles[0] += (desiredA - rig.angles[0]) * blend;
rig.angles[1] += (desiredB - rig.angles[1]) * blend;
}
const endpoint = forwardKinematics(rig.angles);
const errorDistance = Math.hypot(
target.x - endpoint.x,
target.y - endpoint.y
);
rig.errorCm = errorDistance * CM_PER_UNIT;
}
function updateRigVisuals(rig) {
const target = targetAt(simulationTime);
const endpoint = forwardKinematics(rig.angles);
rig.shoulderGroup.rotation.z = rig.angles[0];
rig.elbowGroup.rotation.z = rig.angles[1];
rig.targetGroup.position.x = target.x;
rig.targetGroup.position.y = target.y;
const pulse = 1 + 0.12 * Math.sin(simulationTime * 6);
rig.targetRing.scale.setScalar(pulse);
rig.targetCore.rotation.z = simulationTime * 1.8;
rig.targetCore.rotation.y = simulationTime * 2.3;
const errorPositions = rig.errorLine.geometry.attributes.position;
errorPositions.setXYZ(0, endpoint.x, endpoint.y, 0.36);
errorPositions.setXYZ(1, target.x, target.y, 0.36);
errorPositions.needsUpdate = true;
const disturbanceActive = disturbanceEnvelope() > 0.001;
rig.loadMaterial.emissiveIntensity = disturbanceActive
? 0.7 + 0.8 * Math.abs(Math.sin(simulationTime * 12))
: 0.03;
rig.loadLamp.rotation.y = simulationTime * 2;
}
function triggerDisturbance(manual = true) {
disturbanceStart = simulationTime;
if (manual && autoInput.checked) {
nextAutomaticDisturbance = simulationTime + 7.5;
}
eventToast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
eventToast.classList.remove("visible");
}, 1800);
}
function sampleErrors() {
openHistory.push(openRig.errorCm);
feedbackHistory.push(feedbackRig.errorCm);
if (openHistory.length > 180) {
openHistory.shift();
}
if (feedbackHistory.length > 180) {
feedbackHistory.shift();
}
}
function updateReadouts() {
openErrorElement.textContent = openRig.errorCm.toFixed(1);
feedbackErrorElement.textContent = feedbackRig.errorCm.toFixed(1);
const difference = openRig.errorCm - feedbackRig.errorCm;
if (Math.abs(difference) < 0.15) {
comparisonChip.textContent = "Tracking errors are currently similar";
} else if (difference > 0) {
comparisonChip.textContent =
`Feedback is ${difference.toFixed(1)} cm closer to target`;
} else {
comparisonChip.textContent =
`Open loop is ${Math.abs(difference).toFixed(1)} cm closer right now`;
}
}
function resetTrial() {
simulationTime = 0;
disturbanceStart = -Infinity;
nextAutomaticDisturbance = 4;
trailSampleAccumulator = 0;
errorSampleAccumulator = 0;
const initialAngles = inverseKinematics(targetAt(0));
for (const rig of [openRig, feedbackRig]) {
rig.angles = [...initialAngles];
rig.integral = [0, 0];
rig.errorCm = 0;
rig.trail.clear();
}
openHistory.length = 0;
feedbackHistory.length = 0;
sampleErrors();
paused = false;
pauseButton.textContent = "Pause";
updateRigVisuals(openRig);
updateRigVisuals(feedbackRig);
updateReadouts();
drawCharts();
}
// -------------------------------------------------------------------------
// Error-history charts
// -------------------------------------------------------------------------
function prepareChart(canvas) {
const width = Math.max(canvas.clientWidth, 1);
const height = Math.max(canvas.clientHeight, 1);
const ratio = Math.min(window.devicePixelRatio, 2);
const pixelWidth = Math.round(width * ratio);
const pixelHeight = Math.round(height * ratio);
if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
canvas.width = pixelWidth;
canvas.height = pixelHeight;
}
const context = canvas.getContext("2d");
context.setTransform(ratio, 0, 0, ratio, 0, 0);
return { context, width, height };
}
function drawErrorChart(canvas, values, color) {
const { context, width, height } = prepareChart(canvas);
context.clearRect(0, 0, width, height);
let maximum = 4;
for (const value of values) {
maximum = Math.max(maximum, value * 1.12);
}
maximum = Math.ceil(maximum);
context.strokeStyle = "#e7edf2";
context.lineWidth = 1;
for (let i = 0; i <= 2; i++) {
const y = 7 + ((height - 17) * i) / 2;
context.beginPath();
context.moveTo(4, y);
context.lineTo(width - 4, y);
context.stroke();
}
context.fillStyle = "#8a98a6";
context.font = "9px system-ui, sans-serif";
context.fillText(`${maximum}`, 5, 10);
context.fillText("0", 5, height - 3);
if (values.length === 0) {
return;
}
const xForIndex = (index) =>
5 + (index / Math.max(values.length - 1, 1)) * (width - 10);
const yForValue = (value) =>
height - 7 - (value / maximum) * (height - 17);
const gradient = context.createLinearGradient(0, 0, 0, height);
gradient.addColorStop(0, `${color}55`);
gradient.addColorStop(1, `${color}05`);
context.beginPath();
context.moveTo(xForIndex(0), height - 5);
values.forEach((value, index) => {
context.lineTo(xForIndex(index), yForValue(value));
});
context.lineTo(xForIndex(values.length - 1), height - 5);
context.closePath();
context.fillStyle = gradient;
context.fill();
context.beginPath();
values.forEach((value, index) => {
const x = xForIndex(index);
const y = yForValue(value);
if (index === 0) {
context.moveTo(x, y);
} else {
context.lineTo(x, y);
}
});
context.strokeStyle = color;
context.lineWidth = 2;
context.lineJoin = "round";
context.stroke();
}
function drawCharts() {
drawErrorChart(
document.querySelector("#open-chart"),
openHistory,
"#ed8747"
);
drawErrorChart(
document.querySelector("#feedback-chart"),
feedbackHistory,
"#18aa9d"
);
}
// -------------------------------------------------------------------------
// Direct camera controls: no external controls addon
// -------------------------------------------------------------------------
const pointer = {
active: false,
id: null,
previousX: 0,
previousY: 0
};
renderer.domElement.addEventListener("pointerdown", (event) => {
pointer.active = true;
pointer.id = event.pointerId;
pointer.previousX = event.clientX;
pointer.previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer.active || event.pointerId !== pointer.id) {
return;
}
const deltaX = event.clientX - pointer.previousX;
const deltaY = event.clientY - pointer.previousY;
pointer.previousX = event.clientX;
pointer.previousY = event.clientY;
cameraState.yaw -= deltaX * 0.006;
cameraState.pitch = clamp(
cameraState.pitch + deltaY * 0.005,
0.18,
1.25
);
updateCamera();
});
function endPointer(event) {
if (event.pointerId === pointer.id) {
pointer.active = false;
pointer.id = null;
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7.5,
28
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// UI controls
// -------------------------------------------------------------------------
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
disturbButton.addEventListener("click", () => {
triggerDisturbance(true);
});
resetButton.addEventListener("click", resetTrial);
cameraButton.addEventListener("click", resetCamera);
speedInput.addEventListener("input", () => {
speedLabel.textContent = `${Number(speedInput.value).toFixed(2)}×`;
});
trailsInput.addEventListener("change", () => {
openRig.trail.line.visible = trailsInput.checked;
feedbackRig.trail.line.visible = trailsInput.checked;
});
// -------------------------------------------------------------------------
// Resize handling
// -------------------------------------------------------------------------
function resize() {
const width = Math.max(stage.clientWidth, 1);
const height = Math.max(stage.clientHeight, 1);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
drawCharts();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resizeObserver.observe(document.querySelector("#open-chart"));
resizeObserver.observe(document.querySelector("#feedback-chart"));
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let previousFrameTime = performance.now();
let chartAccumulator = 0;
function animate(now) {
requestAnimationFrame(animate);
const realDelta = Math.min((now - previousFrameTime) / 1000, 0.05);
previousFrameTime = now;
const simulationDelta = paused ? 0 : realDelta * Number(speedInput.value);
if (!paused) {
simulationTime += simulationDelta;
if (
autoInput.checked &&
simulationTime >= nextAutomaticDisturbance
) {
triggerDisturbance(false);
nextAutomaticDisturbance = simulationTime + 7.5;
}
updateRig(openRig, simulationDelta);
updateRig(feedbackRig, simulationDelta);
trailSampleAccumulator += simulationDelta;
errorSampleAccumulator += simulationDelta;
while (trailSampleAccumulator >= 0.04) {
const openEndpoint = forwardKinematics(openRig.angles);
const feedbackEndpoint = forwardKinematics(feedbackRig.angles);
openRig.trail.add(openEndpoint.x, openEndpoint.y);
feedbackRig.trail.add(feedbackEndpoint.x, feedbackEndpoint.y);
trailSampleAccumulator -= 0.04;
}
while (errorSampleAccumulator >= 0.06) {
sampleErrors();
errorSampleAccumulator -= 0.06;
}
}
updateRigVisuals(openRig);
updateRigVisuals(feedbackRig);
updateReadouts();
chartAccumulator += realDelta;
if (chartAccumulator >= 0.1) {
drawCharts();
chartAccumulator = 0;
}
renderer.render(scene, camera);
}
// Initial setup.
resetCamera();
resetTrial();
resize();
requestAnimationFrame(animate);
</script>
</body>
</html>
```