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