1import * as THREE from 'three';
2import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
3import type { BeadSystem, Excitation } from '../sim/types';
4import { css, fmtNum } from './plot';
5import { timelineBar, type Timeline } from './timeline';
7// 3D view of a bead-spring system. "Setup" shows the geometry at rest with
8// supports, pins, excitation and pickup marked; "Replay" animates saved
9// displacement frames (exaggerated) on the shared timeline.
11export interface SceneSpec {
12 sys: BeadSystem;
13 exc: Excitation;
14 excKind: 'pluck' | 'strike' | 'hammer' | 'mallet' | 'stick' | 'force' | 'press';
15 pickup: Float64Array; // 3n weights
16 pickupLabel: string;
17 hoop?: { radius: number }; // round rim in the x-z plane, centred on the origin (instead of walls)
18 post?: { y: number }; // centre support: a stand rod from (0, y, 0) down to the floor
19 mic?: { dir: [number, number, number]; label: string; from: [number, number, number] }; // direction to a far-field microphone
20}
22export interface ReplaySpec extends SceneSpec {
23 frames: Float32Array; // nFrames x 3n, matches the timeline
24 malletPos?: Float32Array; // mallet position (3 per frame)
25}
27type Mode = 'setup' | 'replay';
28type View = 'persp' | 'front' | 'top' | 'end';
30const GLYPH = 0.12; // length of the largest excitation glyph, in units of the model size
32export class BeadScene {
33 private renderer: THREE.WebGLRenderer | null = null;
34 private scene = new THREE.Scene();
35 private camera = new THREE.PerspectiveCamera(35, 1, 0.01, 100);
36 private controls: OrbitControls | null = null;
37 private model = new THREE.Group();
38 private wrap: HTMLDivElement;
39 private legend: HTMLDivElement;
40 private note: HTMLParagraphElement;
41 private bar: HTMLElement;
42 private exagRow: HTMLElement;
43 private exagInput: HTMLInputElement;
44 private tabs: HTMLElement;
46 private mode: Mode = 'setup';
47 private view: View = 'persp';
48 private fitted = false;
49 private setupSpec: SceneSpec | null = null;
50 private replaySpec: ReplaySpec | null = null;
51 private exaggeration = 1;
52 private autoExaggeration = 1;
54 // geometry of the current build, in normalized scene units
55 private scale = 1;
56 private center = new THREE.Vector3();
57 private beads: THREE.InstancedMesh | null = null;
58 private pins: THREE.InstancedMesh | null = null;
59 private springs: THREE.LineSegments | null = null;
60 private slideRings: { mesh: THREE.Mesh; bead: number }[] = [];
61 private hammerArrows: THREE.Group | null = null;
62 private pickupArrow: { arrow: THREE.ArrowHelper; bead: number } | null = null;
63 private mallet: { group: THREE.Group; contact: THREE.Vector3; dir: THREE.Vector3 } | null = null;
64 private spec: SceneSpec | null = null;
65 private frames: Float32Array | null = null;
67 constructor(root: HTMLElement, private tl: Timeline) {
68 root.innerHTML = `
69 <div class="card-head">
70 <div class="seg" data-r="tabs"><button data-v="setup" class="on">Setup</button><button data-v="replay" disabled>Replay</button></div>
71 <div class="seg" data-r="views"><button data-v="persp" class="on">3D</button><button data-v="front">Front x–y</button><button data-v="top">Top x–z</button><button data-v="end">End y–z</button></div>
72 </div>
73 <div class="scene-wrap" data-r="wrap"></div>
74 <div class="legend scene-legend" data-r="legend"></div>
75 <div class="viewer-bar" data-r="exag" hidden>
76 <label class="inline">exaggeration × <input type="number" min="1" step="any" data-r="exag-in" style="width:110px"></label>
77 <button class="btn-small" data-r="exag-auto">Auto</button>
78 </div>
79 <div data-r="bar" hidden></div>
80 <p class="note" data-r="note"></p>`;
81 const q = <T extends HTMLElement>(r: string) => root.querySelector(`[data-r="${r}"]`) as T;
82 this.wrap = q('wrap');
83 this.legend = q('legend');
84 this.note = q('note');
85 this.tabs = q('tabs');
86 this.exagRow = q('exag');
87 this.exagInput = q('exag-in');
88 this.bar = timelineBar(tl);
89 this.bar.hidden = true;
90 q('bar').replaceWith(this.bar);
92 this.tabs.addEventListener('click', (e) => {
93 const b = (e.target as HTMLElement).closest('button');
94 if (b && !b.disabled) this.setMode(b.dataset.v as Mode);
95 });
96 q('views').addEventListener('click', (e) => {
97 const b = (e.target as HTMLElement).closest('button');
98 if (!b) return;
99 q('views').querySelectorAll('button').forEach((x) => x.classList.toggle('on', x === b));
100 this.setView(b.dataset.v as View);
101 });
102 this.exagInput.addEventListener('change', () => {
103 const v = Number(this.exagInput.value);
104 if (v > 0) {
105 this.exaggeration = v;
106 this.update();
107 }
108 });
109 q('exag-auto').addEventListener('click', () => {
110 this.exaggeration = this.autoExaggeration;
111 this.exagInput.value = fmtNum(this.exaggeration);
112 this.update();
113 });
115 try {
116 this.renderer = new THREE.WebGLRenderer({ antialias: true });
117 this.renderer.setPixelRatio(window.devicePixelRatio || 1);
118 this.wrap.append(this.renderer.domElement);
119 this.controls = new OrbitControls(this.camera, this.renderer.domElement);
120 this.controls.addEventListener('change', () => this.render());
121 } catch {
122 this.wrap.innerHTML = '<p class="note">WebGL is not available in this browser, so the 3D view is off.</p>';
123 }
124 this.scene.add(new THREE.AmbientLight(0xffffff, 1.6));
125 const sun = new THREE.DirectionalLight(0xffffff, 2.2);
126 sun.position.set(0.4, 1, 0.8);
127 this.scene.add(sun);
128 this.scene.add(this.model);
129 this.setView('persp');
131 tl.onChange(() => {
132 if (this.mode === 'replay') this.update();
133 });
134 new ResizeObserver(() => this.resize()).observe(this.wrap);
135 window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => this.rebuild());
136 }
138 showSetup(spec: SceneSpec) {
139 this.setupSpec = spec;
140 if (this.mode === 'setup') this.rebuild();
141 else this.setMode('setup');
142 }
144 showReplay(spec: ReplaySpec) {
145 this.replaySpec = spec;
146 let tmax = 0;
147 for (let i = 0; i < spec.frames.length; i++) if (i % 3 !== 0) tmax = Math.max(tmax, Math.abs(spec.frames[i]));
148 const size = modelSize(spec.sys);
149 this.autoExaggeration = tmax > 0 ? Math.max(1, (GLYPH * size) / tmax) : 1;
150 this.exaggeration = this.autoExaggeration;
151 this.exagInput.value = fmtNum(this.exaggeration);
152 (this.tabs.querySelector('[data-v="replay"]') as HTMLButtonElement).disabled = false;
153 this.setMode('replay');
154 }
156 private setMode(m: Mode) {
157 this.mode = m;
158 this.tabs.querySelectorAll<HTMLButtonElement>('button').forEach((b) => b.classList.toggle('on', b.dataset.v === m));
159 this.bar.hidden = m !== 'replay';
160 this.exagRow.hidden = m !== 'replay';
161 if (m === 'setup') this.tl.pause();
162 this.rebuild();
163 }
165 private setView(v: View) {
166 this.view = v;
167 const dirs: Record<View, [number, number, number]> = {
168 persp: [-0.45, 0.42, 1.05],
169 front: [0, 0, 1],
170 top: [0, 1, 0.0001],
171 end: [1, 0, 0],
172 };
173 // back off far enough that the model (about 1.4 wide with its supports) fits horizontally
174 const half = Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2));
175 const fit = 0.75 / (half * this.camera.aspect) + 0.3;
176 const dist = Math.max(this.view === 'persp' ? 1.2 : 1.45, fit);
177 this.camera.position.set(...dirs[v]).setLength(dist);
178 this.camera.up.set(0, 1, 0);
179 if (v === 'top') this.camera.up.set(0, 0, -1);
180 this.controls?.target.set(0, 0, 0);
181 this.camera.lookAt(0, 0, 0);
182 this.controls?.update();
183 this.render();
184 }
186 private resize() {
187 if (!this.renderer) return;
188 const w = this.wrap.clientWidth;
189 const h = this.wrap.clientHeight;
190 if (w === 0 || h === 0) return;
191 this.renderer.setSize(w, h);
192 const narrowBefore = this.camera.aspect < 1;
193 this.camera.aspect = w / h;
194 this.camera.updateProjectionMatrix();
195 // refit when the view turns portrait or landscape (phone rotation, first layout)
196 if (narrowBefore !== this.camera.aspect < 1 || !this.fitted) {
197 this.fitted = true;
198 this.setView(this.view);
199 } else this.render();
200 }
202 private render() {
203 this.renderer?.render(this.scene, this.camera);
204 }
206 // node position (beads and anchors), normalized
207 private nodePos(sys: BeadSystem, node: number, out: THREE.Vector3): THREE.Vector3 {
208 if (node < sys.n) out.set(sys.rest[3 * node], sys.rest[3 * node + 1], sys.rest[3 * node + 2]);
209 else out.set(...sys.anchors[node - sys.n].pos);
210 return out.sub(this.center).multiplyScalar(this.scale);
211 }
213 private rebuild() {
214 const spec = this.mode === 'replay' ? this.replaySpec : this.setupSpec;
215 disposeGroup(this.model);
216 this.beads = this.pins = this.springs = this.hammerArrows = null;
217 this.slideRings = [];
218 this.pickupArrow = null;
219 this.mallet = null;
220 this.spec = spec;
221 this.frames = this.mode === 'replay' && this.replaySpec ? this.replaySpec.frames : null;
222 if (!spec) return this.render();
223 if (this.renderer) this.renderer.setClearColor(new THREE.Color(css('--surface-1')));
224 const { sys, exc, pickup } = spec;
225 const n = sys.n;
227 // normalize: longest extent of beads and anchors -> 1, centered
228 const box = new THREE.Box3();
229 const v = new THREE.Vector3();
230 for (let i = 0; i < n; i++) box.expandByPoint(v.set(sys.rest[3 * i], sys.rest[3 * i + 1], sys.rest[3 * i + 2]));
231 for (const a of sys.anchors) box.expandByPoint(v.set(...a.pos));
232 box.getCenter(this.center);
233 const size = box.getSize(new THREE.Vector3());
234 this.scale = 1 / Math.max(size.x, size.y, size.z, 1e-12);
236 // bead size from nearest-neighbour spacing
237 let minLen = Infinity;
238 const p = new THREE.Vector3();
239 const q = new THREE.Vector3();
240 for (let s = 0; s < sys.si.length; s++) minLen = Math.min(minLen, this.nodePos(sys, sys.si[s], p).distanceTo(this.nodePos(sys, sys.sj[s], q)));
241 if (!Number.isFinite(minLen)) minLen = 0.05;
242 const r = Math.min(0.32 * minLen, 0.022);
244 const cBead = new THREE.Color(css('--series-1'));
245 const cExc = new THREE.Color(css('--series-2'));
246 const cPick = new THREE.Color(css('--series-3'));
247 const cInk = new THREE.Color(css('--text-primary'));
248 const cMuted = new THREE.Color(css('--text-muted'));
250 // grid floor for depth cues
251 const grid = new THREE.GridHelper(1.4, 14, cMuted, cMuted);
252 (grid.material as THREE.Material).transparent = true;
253 (grid.material as THREE.Material).opacity = 0.25;
254 grid.position.y = -0.22;
255 this.model.add(grid);
256 this.model.add(axisTriad(new THREE.Vector3(-0.58, -0.22, -0.3), 0.08, cInk));
258 // beads (pinned beads are drawn as cubes instead)
259 const pickBead = (i: number) => pickup[3 * i] !== 0 || pickup[3 * i + 1] !== 0 || pickup[3 * i + 2] !== 0;
260 const free: number[] = [];
261 const pinned: number[] = [];
262 for (let i = 0; i < n; i++) (sys.pinned[i] ? pinned : free).push(i);
263 const beadMat = new THREE.MeshStandardMaterial({ roughness: 0.55, metalness: 0.1 });
264 this.beads = new THREE.InstancedMesh(new THREE.SphereGeometry(r, 20, 14), beadMat, Math.max(1, n));
265 this.beads.count = n;
266 // a pickup over every bead is named in the legend rather than painting the whole model
267 let nPick = 0;
268 for (let i = 0; i < n; i++) if (pickBead(i)) nPick++;
269 for (let i = 0; i < n; i++) this.beads.setColorAt(i, pickBead(i) && nPick < n ? cPick : cBead);
270 this.model.add(this.beads);
271 if (pinned.length) {
272 this.pins = new THREE.InstancedMesh(new THREE.BoxGeometry(2.4 * r, 2.4 * r, 2.4 * r), new THREE.MeshStandardMaterial({ color: cInk, roughness: 0.6 }), pinned.length);
273 this.model.add(this.pins);
274 }
275 (this.beads.userData as { free: number[]; pinned: number[] }) = { free, pinned };
277 // springs
278 const sg = new THREE.BufferGeometry();
279 sg.setAttribute('position', new THREE.BufferAttribute(new Float32Array(sys.si.length * 6), 3));
280 this.springs = new THREE.LineSegments(sg, new THREE.LineBasicMaterial({ color: cMuted }));
281 this.model.add(this.springs);
283 // supports
284 const wallSize = 0.16;
285 if (spec.hoop) {
286 const hoop = new THREE.Mesh(
287 new THREE.TorusGeometry(spec.hoop.radius * this.scale, 0.012, 10, 96),
288 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.7 }),
289 );
290 hoop.rotation.x = Math.PI / 2;
291 hoop.position.set(-this.center.x * this.scale, -this.center.y * this.scale, -this.center.z * this.scale);
292 this.model.add(hoop);
293 }
294 if (spec.post) {
295 const o = new THREE.Vector3(-this.center.x, spec.post.y - this.center.y, -this.center.z).multiplyScalar(this.scale);
296 const rodLen = o.y + 0.22;
297 const rod = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, rodLen + 0.04, 10), new THREE.MeshStandardMaterial({ color: cMuted }));
298 rod.position.copy(o).add(new THREE.Vector3(0, 0.02 - rodLen / 2, 0));
299 this.model.add(rod);
300 }
301 if (spec.mic) {
302 const o = new THREE.Vector3(...spec.mic.from).sub(this.center).multiplyScalar(this.scale);
303 this.model.add(new THREE.ArrowHelper(new THREE.Vector3(...spec.mic.dir).normalize(), o, 0.42, new THREE.Color(css('--series-3')), 0.05, 0.025));
304 }
305 if (!spec.hoop) sys.anchors.forEach((a) => {
306 const at = this.nodePos(sys, sys.n + sys.anchors.indexOf(a), new THREE.Vector3());
307 const side = at.x < 0 ? -1 : 1;
308 if (a.slideBead < 0) {
309 const wall = new THREE.Mesh(
310 new THREE.BoxGeometry(0.02, wallSize, wallSize),
311 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.8 }),
312 );
313 wall.position.copy(at).add(new THREE.Vector3(side * 0.01, 0, 0));
314 this.model.add(wall);
315 } else {
316 const plane = new THREE.Mesh(
317 new THREE.PlaneGeometry(wallSize, wallSize),
318 new THREE.MeshBasicMaterial({ color: cMuted, transparent: true, opacity: 0.18, side: THREE.DoubleSide, depthWrite: false }),
319 );
320 plane.rotation.y = Math.PI / 2;
321 plane.position.copy(at);
322 this.model.add(plane);
323 const edges = new THREE.LineSegments(new THREE.EdgesGeometry(plane.geometry), new THREE.LineBasicMaterial({ color: cMuted }));
324 edges.rotation.y = Math.PI / 2;
325 edges.position.copy(at);
326 this.model.add(edges);
327 const ring = new THREE.Mesh(new THREE.TorusGeometry(1.3 * r, 0.35 * r, 8, 24), new THREE.MeshStandardMaterial({ color: cInk }));
328 ring.rotation.y = Math.PI / 2;
329 ring.position.copy(at);
330 this.model.add(ring);
331 this.slideRings.push({ mesh: ring, bead: a.slideBead });
332 }
333 });
335 // excitation glyphs
336 const legend: string[] = [];
337 const sw = (c: THREE.Color, shape = 'dot') => `<i class="glyph ${shape}" style="--c:#${c.getHexString()}"></i>`;
338 legend.push(`<span>${sw(cBead)}bead</span>`);
339 if (pinned.length) legend.push(`<span>${sw(cInk, 'square')}${spec.post ? 'bead held at the hub' : 'pinned bead'}</span>`);
340 if (spec.hoop) legend.push(`<span>${sw(cMuted, 'ring')}clamped rim</span>`);
342 else if (sys.anchors.some((a) => a.slideBead < 0)) legend.push(`<span>${sw(cMuted, 'square')}clamped end (wall)</span>`);
343 if (sys.anchors.some((a) => a.slideBead >= 0)) legend.push(`<span>${sw(cInk, 'ring')}sliding end (ring on a frictionless plane)</span>`);
344 const size0 = modelSize(sys);
345 const dirs = (field: Float64Array) => {
346 let m = 0;
347 for (let i = 0; i < n; i++) m = Math.max(m, Math.hypot(field[3 * i], field[3 * i + 1], field[3 * i + 2]));
348 return m;
349 };
350 if (this.mode === 'setup' && spec.excKind === 'pluck') {
351 const m = dirs(exc.u0);
352 if (m > 0) {
353 const E = (GLYPH * size0) / m;
354 const pts: THREE.Vector3[] = [];
355 const left = sys.anchors.find((a) => a.pos[0] < sys.rest[0]);
356 const right = sys.anchors.find((a) => a.pos[0] > sys.rest[3 * (n - 1)]);
357 if (left) pts.push(this.nodePos(sys, n + sys.anchors.indexOf(left), new THREE.Vector3()));
358 for (let i = 0; i < n; i++) {
359 const w = new THREE.Vector3(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]).multiplyScalar(E * this.scale);
360 pts.push(this.nodePos(sys, i, new THREE.Vector3()).add(w));
361 }
362 if (right) pts.push(this.nodePos(sys, n + sys.anchors.indexOf(right), new THREE.Vector3()));
363 const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineDashedMaterial({ color: cExc, dashSize: 0.015, gapSize: 0.01 }));
364 line.computeLineDistances();
365 this.model.add(line);
366 let peak = 0;
367 for (let i = 1; i < n; i++) if (Math.hypot(exc.u0[3 * i + 1], exc.u0[3 * i + 2]) > Math.hypot(exc.u0[3 * peak + 1], exc.u0[3 * peak + 2])) peak = i;
368 const from = this.nodePos(sys, peak, new THREE.Vector3());
369 const to = pts[peak + (left ? 1 : 0)];
370 const len = from.distanceTo(to);
371 if (len > 0) this.model.add(new THREE.ArrowHelper(to.clone().sub(from).normalize(), from, len, cExc, 0.25 * len, 0.12 * len));
372 legend.push(`<span>${sw(cExc, 'dash')}pluck: initial shape, drawn ×${fmtNum(E)} (${fmtNum(m * 1000)} mm peak)</span>`);
373 }
374 }
375 if (spec.excKind === 'strike' && this.mode === 'setup') {
376 const m = dirs(exc.v0);
377 if (m > 0) this.model.add(this.arrows(sys, exc.v0, m, cExc, false));
378 legend.push(`<span>${sw(cExc, 'arrow')}strike: initial velocity (${fmtNum(m)} m/s peak)</span>`);
379 }
380 if (this.mode === 'setup' && spec.excKind === 'press') {
381 const m = dirs(exc.u0);
382 if (m > 0) {
383 const E = (0.5 * GLYPH * size0) / m;
384 const pts: THREE.Vector3[] = [];
385 for (let i = 0; i < n; i++) {
386 if (Math.hypot(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]) < 0.02 * m) continue;
387 const w = new THREE.Vector3(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]).multiplyScalar(E * this.scale);
388 pts.push(this.nodePos(sys, i, new THREE.Vector3()).add(w));
389 }
390 const dots = new THREE.Points(new THREE.BufferGeometry().setFromPoints(pts), new THREE.PointsMaterial({ color: cExc, size: 1.2 * r }));
391 this.model.add(dots);
392 legend.push(`<span>${sw(cExc)}press: initial shape, drawn ×${fmtNum(E)} (${fmtNum(m * 1000)} mm deep)</span>`);
393 }
394 }
395 if (exc.mallet) {
396 const ml = exc.mallet;
397 const dir = new THREE.Vector3(...ml.vel0).normalize(); // the stick travels along its own axis
398 const contact = new THREE.Vector3();
399 for (let i = 0; i < n; i++) if (ml.weights[i] > 0) contact.addScaledVector(this.nodePos(sys, i, new THREE.Vector3()), ml.weights[i]);
400 const head = Math.max(1.6 * r, 0.025);
401 const group = new THREE.Group();
402 const felt = new THREE.Mesh(new THREE.SphereGeometry(head, 24, 16), new THREE.MeshStandardMaterial({ color: cExc, roughness: 0.9 }));
403 felt.position.copy(dir).multiplyScalar(-head);
404 const stick = new THREE.Mesh(
405 new THREE.CylinderGeometry(0.15 * head, 0.15 * head, 0.3, 10),
406 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.6 }),
407 );
408 stick.position.copy(dir).multiplyScalar(-(2 * head + 0.15));
409 stick.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir);
410 group.add(felt, stick);
411 this.model.add(group);
412 this.mallet = { group, contact, dir };
413 const speed = Math.hypot(...ml.vel0);
414 const what = spec.excKind === 'stick' ? 'stick' : 'mallet';
415 legend.push(
416 `<span>${sw(cExc)}${what}: ${fmtNum(ml.mass * 1000)} g at ${fmtNum(speed)} m/s, contact F = K δ^${fmtNum(ml.p)}${this.mode === 'replay' ? ' (motion exaggerated like the beads)' : ''}</span>`,
417 );
418 }
419 if ((spec.excKind === 'hammer' || spec.excKind === 'force') && exc.force) {
420 const m = dirs(exc.force.shape);
421 if (m > 0) {
422 this.hammerArrows = this.arrows(sys, exc.force.shape, m, cExc, true);
423 this.model.add(this.hammerArrows);
424 }
425 legend.push(
426 `<span>${sw(cExc, 'arrow')}${spec.excKind === 'hammer' ? 'hammer' : 'force'}: force pulse, ${fmtNum(exc.force.F0)} N peak over ${fmtNum(exc.force.tau * 1000)} ms${this.mode === 'replay' ? ' (shown while it acts)' : ''}</span>`,
427 );
428 }
430 // pickup
431 const pk: number[] = [];
432 for (let i = 0; i < n; i++) if (pickBead(i)) pk.push(i);
433 if (pk.length === 1) {
434 const i = pk[0];
435 const d = new THREE.Vector3(pickup[3 * i], pickup[3 * i + 1], pickup[3 * i + 2]).normalize();
436 const len = Math.max(0.05, 6 * r);
437 const arrow = new THREE.ArrowHelper(d, this.nodePos(sys, i, new THREE.Vector3()), len, cPick, 0.3 * len, 0.18 * len);
438 this.model.add(arrow);
439 this.pickupArrow = { arrow, bead: i };
440 }
441 legend.push(spec.mic ? `<span>${sw(cPick, 'arrow')}${spec.mic.label}</span>` : `<span>${sw(cPick)}pickup: ${spec.pickupLabel}</span>`);
442 this.legend.innerHTML = legend.join('');
443 this.update();
444 }
446 // arrows proportional to a per-bead vector field; `into` = arrow ends at the bead (a push)
447 private arrows(sys: BeadSystem, field: Float64Array, max: number, color: THREE.Color, into: boolean): THREE.Group {
448 const g = new THREE.Group();
449 for (let i = 0; i < sys.n; i++) {
450 const d = new THREE.Vector3(field[3 * i], field[3 * i + 1], field[3 * i + 2]);
451 const mag = d.length();
452 if (mag < 0.05 * max) continue;
453 const len = GLYPH * (mag / max);
454 d.normalize();
455 const at = this.nodePos(sys, i, new THREE.Vector3());
456 const origin = into ? at.clone().addScaledVector(d, -len) : at;
457 const arrow = new THREE.ArrowHelper(d, origin, len, color, Math.min(0.03, 0.3 * len), Math.min(0.016, 0.18 * len));
458 arrow.userData = { bead: i, dir: d.clone(), len };
459 g.add(arrow);
460 }
461 return g;
462 }
464 // position everything for the current frame (or rest, in setup)
465 private update() {
466 const spec = this.spec;
467 if (!spec || !this.beads) return this.render();
468 const { sys } = spec;
469 const n = sys.n;
470 const frames = this.frames;
471 const off = frames ? this.tl.frame * 3 * n : 0;
472 const E = this.exaggeration * this.scale;
473 const P = new Array<THREE.Vector3>(n + sys.anchors.length);
474 for (let i = 0; i < n; i++) {
475 const p = this.nodePos(sys, i, new THREE.Vector3());
476 if (frames) p.add(new THREE.Vector3(frames[off + 3 * i], frames[off + 3 * i + 1], frames[off + 3 * i + 2]).multiplyScalar(E));
477 P[i] = p;
478 }
479 sys.anchors.forEach((a, k) => {
480 const p = this.nodePos(sys, n + k, new THREE.Vector3());
481 if (a.slideBead >= 0) {
482 p.y = P[a.slideBead].y;
483 p.z = P[a.slideBead].z;
484 }
485 P[n + k] = p;
486 });
487 const m = new THREE.Matrix4();
488 const { pinned } = this.beads.userData as { free: number[]; pinned: number[] };
489 for (let i = 0; i < n; i++) {
490 // hide pinned beads' spheres (cubes stand in)
491 m.makeScale(sys.pinned[i] ? 0 : 1, sys.pinned[i] ? 0 : 1, sys.pinned[i] ? 0 : 1).setPosition(P[i]);
492 this.beads.setMatrixAt(i, m);
493 }
494 this.beads.instanceMatrix.needsUpdate = true;
495 if (this.beads.instanceColor) this.beads.instanceColor.needsUpdate = true;
496 if (this.pins) {
497 pinned.forEach((i, k) => this.pins!.setMatrixAt(k, m.makeTranslation(P[i].x, P[i].y, P[i].z)));
498 this.pins.instanceMatrix.needsUpdate = true;
499 }
500 if (this.springs) {
501 const arr = (this.springs.geometry.getAttribute('position') as THREE.BufferAttribute).array as Float32Array;
502 for (let s = 0; s < sys.si.length; s++) {
503 const a = P[sys.si[s]];
504 const b = P[sys.sj[s]];
505 arr.set([a.x, a.y, a.z, b.x, b.y, b.z], 6 * s);
506 }
507 this.springs.geometry.getAttribute('position').needsUpdate = true;
508 this.springs.geometry.computeBoundingSphere();
509 }
510 for (const { mesh, bead } of this.slideRings) {
511 mesh.position.y = P[bead].y;
512 mesh.position.z = P[bead].z;
513 }
514 if (this.pickupArrow) this.pickupArrow.arrow.position.copy(P[this.pickupArrow.bead]);
515 if (this.mallet) {
516 const mp = this.mode === 'replay' ? this.replaySpec?.malletPos : undefined;
517 const g = this.mallet.group.position.copy(this.mallet.contact);
518 // in setup it hovers back along its path; in replay it follows the run
519 if (mp) g.add(new THREE.Vector3(mp[3 * this.tl.frame], mp[3 * this.tl.frame + 1], mp[3 * this.tl.frame + 2]).multiplyScalar(E));
520 else g.addScaledVector(this.mallet.dir, -0.6 * GLYPH);
521 }
522 if (this.hammerArrows && spec.exc.force) {
523 const f = spec.exc.force;
524 const t = frames ? this.tl.times[this.tl.frame] : f.tau / 2;
525 const s = t >= 0 && t <= f.tau ? 0.5 * (1 - Math.cos((2 * Math.PI * t) / f.tau)) : 0;
526 this.hammerArrows.visible = s > 0.02;
527 for (const c of this.hammerArrows.children) {
528 const { bead, dir, len } = c.userData as { bead: number; dir: THREE.Vector3; len: number };
529 const l = Math.max(1e-4, len * (frames ? s : 1));
530 const arrow = c as THREE.ArrowHelper;
531 arrow.position.copy(P[bead]).addScaledVector(dir, -l);
532 arrow.setLength(l, Math.min(0.03, 0.3 * l), Math.min(0.016, 0.18 * l));
533 }
534 }
535 if (this.mode === 'replay' && frames) {
536 this.note.textContent =
537 `Displacements drawn ×${fmtNum(this.exaggeration)} (all three components, so longitudinal motion is exaggerated too). ` +
538 `Drag to rotate; pinch or scroll to zoom; two-finger or right-drag to pan.`;
539 } else {
540 this.note.textContent = 'Beads at rest. Drag to rotate; pinch or scroll to zoom; two-finger or right-drag to pan.';
541 }
542 this.render();
543 }
544}
546function modelSize(sys: BeadSystem): number {
547 let lo = Infinity;
548 let hi = -Infinity;
549 for (let i = 0; i < sys.n; i++) {
550 lo = Math.min(lo, sys.rest[3 * i]);
551 hi = Math.max(hi, sys.rest[3 * i]);
552 }
553 for (const a of sys.anchors) {
554 lo = Math.min(lo, a.pos[0]);
555 hi = Math.max(hi, a.pos[0]);
556 }
557 return Math.max(hi - lo, 1e-12);
558}
560function textSprite(text: string, color: THREE.Color): THREE.Sprite {
561 const c = document.createElement('canvas');
562 c.width = c.height = 64;
563 const ctx = c.getContext('2d')!;
564 ctx.fillStyle = `#${color.getHexString()}`;
565 ctx.font = '600 44px system-ui, sans-serif';
566 ctx.textAlign = 'center';
567 ctx.textBaseline = 'middle';
568 ctx.fillText(text, 32, 34);
569 const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), depthTest: false }));
570 s.scale.set(0.04, 0.04, 1);
571 return s;
572}
574function axisTriad(at: THREE.Vector3, len: number, ink: THREE.Color): THREE.Group {
575 const g = new THREE.Group();
576 const axes: [string, THREE.Vector3][] = [
577 ['x', new THREE.Vector3(1, 0, 0)],
578 ['y', new THREE.Vector3(0, 1, 0)],
579 ['z', new THREE.Vector3(0, 0, 1)],
580 ];
581 for (const [name, d] of axes) {
582 g.add(new THREE.ArrowHelper(d, at, len, ink, 0.2 * len, 0.1 * len));
583 const label = textSprite(name, ink);
584 label.position.copy(at).addScaledVector(d, len * 1.3);
585 g.add(label);
586 }
587 return g;
588}
590function disposeGroup(g: THREE.Group) {
591 g.traverse((o) => {
592 const m = o as THREE.Mesh;
593 m.geometry?.dispose();
594 const mat = m.material as THREE.Material | THREE.Material[] | undefined;
595 if (Array.isArray(mat)) mat.forEach((x) => x.dispose());
596 else mat?.dispose();
597 });
598 g.clear();
599}