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 felt?: { radius: number; gap: number; y: number }; // centre support: felt washers above and below (0, y, 0)
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.felt) {
295 const o = new THREE.Vector3(-this.center.x, spec.felt.y - this.center.y, -this.center.z).multiplyScalar(this.scale);
296 const fr = spec.felt.radius * this.scale;
297 const gap = Math.max(spec.felt.gap * this.scale, 0.006);
298 const feltMat = new THREE.MeshStandardMaterial({ color: cInk, roughness: 0.95, transparent: true, opacity: 0.55 });
299 for (const side of [1, -1]) {
300 const washer = new THREE.Mesh(new THREE.CylinderGeometry(fr, fr, 0.012, 32), feltMat);
301 washer.position.copy(o).add(new THREE.Vector3(0, side * (gap + 0.006), 0));
302 this.model.add(washer);
303 }
304 const rodLen = o.y + 0.22;
305 const rod = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, rodLen + 0.06, 10), new THREE.MeshStandardMaterial({ color: cMuted }));
306 rod.position.copy(o).add(new THREE.Vector3(0, 0.03 - rodLen / 2, 0));
307 this.model.add(rod);
308 }
309 if (spec.mic) {
310 const o = new THREE.Vector3(...spec.mic.from).sub(this.center).multiplyScalar(this.scale);
311 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));
312 }
313 if (!spec.hoop && !spec.felt) sys.anchors.forEach((a) => {
314 const at = this.nodePos(sys, sys.n + sys.anchors.indexOf(a), new THREE.Vector3());
315 const side = at.x < 0 ? -1 : 1;
316 if (a.slideBead < 0) {
317 const wall = new THREE.Mesh(
318 new THREE.BoxGeometry(0.02, wallSize, wallSize),
319 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.8 }),
320 );
321 wall.position.copy(at).add(new THREE.Vector3(side * 0.01, 0, 0));
322 this.model.add(wall);
323 } else {
324 const plane = new THREE.Mesh(
325 new THREE.PlaneGeometry(wallSize, wallSize),
326 new THREE.MeshBasicMaterial({ color: cMuted, transparent: true, opacity: 0.18, side: THREE.DoubleSide, depthWrite: false }),
327 );
328 plane.rotation.y = Math.PI / 2;
329 plane.position.copy(at);
330 this.model.add(plane);
331 const edges = new THREE.LineSegments(new THREE.EdgesGeometry(plane.geometry), new THREE.LineBasicMaterial({ color: cMuted }));
332 edges.rotation.y = Math.PI / 2;
333 edges.position.copy(at);
334 this.model.add(edges);
335 const ring = new THREE.Mesh(new THREE.TorusGeometry(1.3 * r, 0.35 * r, 8, 24), new THREE.MeshStandardMaterial({ color: cInk }));
336 ring.rotation.y = Math.PI / 2;
337 ring.position.copy(at);
338 this.model.add(ring);
339 this.slideRings.push({ mesh: ring, bead: a.slideBead });
340 }
341 });
343 // excitation glyphs
344 const legend: string[] = [];
345 const sw = (c: THREE.Color, shape = 'dot') => `<i class="glyph ${shape}" style="--c:#${c.getHexString()}"></i>`;
346 legend.push(`<span>${sw(cBead)}bead</span>`);
347 if (pinned.length) legend.push(`<span>${sw(cInk, 'square')}pinned bead</span>`);
348 if (spec.hoop) legend.push(`<span>${sw(cMuted, 'ring')}clamped rim</span>`);
349 else if (spec.felt) legend.push(`<span>${sw(cInk, 'square')}felt washers (centre support)</span>`);
350 else if (sys.anchors.some((a) => a.slideBead < 0)) legend.push(`<span>${sw(cMuted, 'square')}clamped end (wall)</span>`);
351 if (sys.anchors.some((a) => a.slideBead >= 0)) legend.push(`<span>${sw(cInk, 'ring')}sliding end (ring on a frictionless plane)</span>`);
352 const size0 = modelSize(sys);
353 const dirs = (field: Float64Array) => {
354 let m = 0;
355 for (let i = 0; i < n; i++) m = Math.max(m, Math.hypot(field[3 * i], field[3 * i + 1], field[3 * i + 2]));
356 return m;
357 };
358 if (this.mode === 'setup' && spec.excKind === 'pluck') {
359 const m = dirs(exc.u0);
360 if (m > 0) {
361 const E = (GLYPH * size0) / m;
362 const pts: THREE.Vector3[] = [];
363 const left = sys.anchors.find((a) => a.pos[0] < sys.rest[0]);
364 const right = sys.anchors.find((a) => a.pos[0] > sys.rest[3 * (n - 1)]);
365 if (left) pts.push(this.nodePos(sys, n + sys.anchors.indexOf(left), new THREE.Vector3()));
366 for (let i = 0; i < n; i++) {
367 const w = new THREE.Vector3(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]).multiplyScalar(E * this.scale);
368 pts.push(this.nodePos(sys, i, new THREE.Vector3()).add(w));
369 }
370 if (right) pts.push(this.nodePos(sys, n + sys.anchors.indexOf(right), new THREE.Vector3()));
371 const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineDashedMaterial({ color: cExc, dashSize: 0.015, gapSize: 0.01 }));
372 line.computeLineDistances();
373 this.model.add(line);
374 let peak = 0;
375 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;
376 const from = this.nodePos(sys, peak, new THREE.Vector3());
377 const to = pts[peak + (left ? 1 : 0)];
378 const len = from.distanceTo(to);
379 if (len > 0) this.model.add(new THREE.ArrowHelper(to.clone().sub(from).normalize(), from, len, cExc, 0.25 * len, 0.12 * len));
380 legend.push(`<span>${sw(cExc, 'dash')}pluck: initial shape, drawn ×${fmtNum(E)} (${fmtNum(m * 1000)} mm peak)</span>`);
381 }
382 }
383 if (spec.excKind === 'strike' && this.mode === 'setup') {
384 const m = dirs(exc.v0);
385 if (m > 0) this.model.add(this.arrows(sys, exc.v0, m, cExc, false));
386 legend.push(`<span>${sw(cExc, 'arrow')}strike: initial velocity (${fmtNum(m)} m/s peak)</span>`);
387 }
388 if (this.mode === 'setup' && spec.excKind === 'press') {
389 const m = dirs(exc.u0);
390 if (m > 0) {
391 const E = (0.5 * GLYPH * size0) / m;
392 const pts: THREE.Vector3[] = [];
393 for (let i = 0; i < n; i++) {
394 if (Math.hypot(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]) < 0.02 * m) continue;
395 const w = new THREE.Vector3(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]).multiplyScalar(E * this.scale);
396 pts.push(this.nodePos(sys, i, new THREE.Vector3()).add(w));
397 }
398 const dots = new THREE.Points(new THREE.BufferGeometry().setFromPoints(pts), new THREE.PointsMaterial({ color: cExc, size: 1.2 * r }));
399 this.model.add(dots);
400 legend.push(`<span>${sw(cExc)}press: initial shape, drawn ×${fmtNum(E)} (${fmtNum(m * 1000)} mm deep)</span>`);
401 }
402 }
403 if (exc.mallet) {
404 const ml = exc.mallet;
405 const dir = new THREE.Vector3(...ml.vel0).normalize(); // the stick travels along its own axis
406 const contact = new THREE.Vector3();
407 for (let i = 0; i < n; i++) if (ml.weights[i] > 0) contact.addScaledVector(this.nodePos(sys, i, new THREE.Vector3()), ml.weights[i]);
408 const head = Math.max(1.6 * r, 0.025);
409 const group = new THREE.Group();
410 const felt = new THREE.Mesh(new THREE.SphereGeometry(head, 24, 16), new THREE.MeshStandardMaterial({ color: cExc, roughness: 0.9 }));
411 felt.position.copy(dir).multiplyScalar(-head);
412 const stick = new THREE.Mesh(
413 new THREE.CylinderGeometry(0.15 * head, 0.15 * head, 0.3, 10),
414 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.6 }),
415 );
416 stick.position.copy(dir).multiplyScalar(-(2 * head + 0.15));
417 stick.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir);
418 group.add(felt, stick);
419 this.model.add(group);
420 this.mallet = { group, contact, dir };
421 const speed = Math.hypot(...ml.vel0);
422 const what = spec.excKind === 'stick' ? 'stick' : 'mallet';
423 legend.push(
424 `<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>`,
425 );
426 }
427 if ((spec.excKind === 'hammer' || spec.excKind === 'force') && exc.force) {
428 const m = dirs(exc.force.shape);
429 if (m > 0) {
430 this.hammerArrows = this.arrows(sys, exc.force.shape, m, cExc, true);
431 this.model.add(this.hammerArrows);
432 }
433 legend.push(
434 `<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>`,
435 );
436 }
438 // pickup
439 const pk: number[] = [];
440 for (let i = 0; i < n; i++) if (pickBead(i)) pk.push(i);
441 if (pk.length === 1) {
442 const i = pk[0];
443 const d = new THREE.Vector3(pickup[3 * i], pickup[3 * i + 1], pickup[3 * i + 2]).normalize();
444 const len = Math.max(0.05, 6 * r);
445 const arrow = new THREE.ArrowHelper(d, this.nodePos(sys, i, new THREE.Vector3()), len, cPick, 0.3 * len, 0.18 * len);
446 this.model.add(arrow);
447 this.pickupArrow = { arrow, bead: i };
448 }
449 legend.push(spec.mic ? `<span>${sw(cPick, 'arrow')}${spec.mic.label}</span>` : `<span>${sw(cPick)}pickup: ${spec.pickupLabel}</span>`);
450 this.legend.innerHTML = legend.join('');
451 this.update();
452 }
454 // arrows proportional to a per-bead vector field; `into` = arrow ends at the bead (a push)
455 private arrows(sys: BeadSystem, field: Float64Array, max: number, color: THREE.Color, into: boolean): THREE.Group {
456 const g = new THREE.Group();
457 for (let i = 0; i < sys.n; i++) {
458 const d = new THREE.Vector3(field[3 * i], field[3 * i + 1], field[3 * i + 2]);
459 const mag = d.length();
460 if (mag < 0.05 * max) continue;
461 const len = GLYPH * (mag / max);
462 d.normalize();
463 const at = this.nodePos(sys, i, new THREE.Vector3());
464 const origin = into ? at.clone().addScaledVector(d, -len) : at;
465 const arrow = new THREE.ArrowHelper(d, origin, len, color, Math.min(0.03, 0.3 * len), Math.min(0.016, 0.18 * len));
466 arrow.userData = { bead: i, dir: d.clone(), len };
467 g.add(arrow);
468 }
469 return g;
470 }
472 // position everything for the current frame (or rest, in setup)
473 private update() {
474 const spec = this.spec;
475 if (!spec || !this.beads) return this.render();
476 const { sys } = spec;
477 const n = sys.n;
478 const frames = this.frames;
479 const off = frames ? this.tl.frame * 3 * n : 0;
480 const E = this.exaggeration * this.scale;
481 const P = new Array<THREE.Vector3>(n + sys.anchors.length);
482 for (let i = 0; i < n; i++) {
483 const p = this.nodePos(sys, i, new THREE.Vector3());
484 if (frames) p.add(new THREE.Vector3(frames[off + 3 * i], frames[off + 3 * i + 1], frames[off + 3 * i + 2]).multiplyScalar(E));
485 P[i] = p;
486 }
487 sys.anchors.forEach((a, k) => {
488 const p = this.nodePos(sys, n + k, new THREE.Vector3());
489 if (a.slideBead >= 0) {
490 p.y = P[a.slideBead].y;
491 p.z = P[a.slideBead].z;
492 }
493 P[n + k] = p;
494 });
495 const m = new THREE.Matrix4();
496 const { pinned } = this.beads.userData as { free: number[]; pinned: number[] };
497 for (let i = 0; i < n; i++) {
498 // hide pinned beads' spheres (cubes stand in)
499 m.makeScale(sys.pinned[i] ? 0 : 1, sys.pinned[i] ? 0 : 1, sys.pinned[i] ? 0 : 1).setPosition(P[i]);
500 this.beads.setMatrixAt(i, m);
501 }
502 this.beads.instanceMatrix.needsUpdate = true;
503 if (this.beads.instanceColor) this.beads.instanceColor.needsUpdate = true;
504 if (this.pins) {
505 pinned.forEach((i, k) => this.pins!.setMatrixAt(k, m.makeTranslation(P[i].x, P[i].y, P[i].z)));
506 this.pins.instanceMatrix.needsUpdate = true;
507 }
508 if (this.springs) {
509 const arr = (this.springs.geometry.getAttribute('position') as THREE.BufferAttribute).array as Float32Array;
510 for (let s = 0; s < sys.si.length; s++) {
511 const a = P[sys.si[s]];
512 const b = P[sys.sj[s]];
513 arr.set([a.x, a.y, a.z, b.x, b.y, b.z], 6 * s);
514 }
515 this.springs.geometry.getAttribute('position').needsUpdate = true;
516 this.springs.geometry.computeBoundingSphere();
517 }
518 for (const { mesh, bead } of this.slideRings) {
519 mesh.position.y = P[bead].y;
520 mesh.position.z = P[bead].z;
521 }
522 if (this.pickupArrow) this.pickupArrow.arrow.position.copy(P[this.pickupArrow.bead]);
523 if (this.mallet) {
524 const mp = this.mode === 'replay' ? this.replaySpec?.malletPos : undefined;
525 const g = this.mallet.group.position.copy(this.mallet.contact);
526 // in setup it hovers back along its path; in replay it follows the run
527 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));
528 else g.addScaledVector(this.mallet.dir, -0.6 * GLYPH);
529 }
530 if (this.hammerArrows && spec.exc.force) {
531 const f = spec.exc.force;
532 const t = frames ? this.tl.times[this.tl.frame] : f.tau / 2;
533 const s = t >= 0 && t <= f.tau ? 0.5 * (1 - Math.cos((2 * Math.PI * t) / f.tau)) : 0;
534 this.hammerArrows.visible = s > 0.02;
535 for (const c of this.hammerArrows.children) {
536 const { bead, dir, len } = c.userData as { bead: number; dir: THREE.Vector3; len: number };
537 const l = Math.max(1e-4, len * (frames ? s : 1));
538 const arrow = c as THREE.ArrowHelper;
539 arrow.position.copy(P[bead]).addScaledVector(dir, -l);
540 arrow.setLength(l, Math.min(0.03, 0.3 * l), Math.min(0.016, 0.18 * l));
541 }
542 }
543 if (this.mode === 'replay' && frames) {
544 this.note.textContent =
545 `Displacements drawn ×${fmtNum(this.exaggeration)} (all three components, so longitudinal motion is exaggerated too). ` +
546 `Drag to rotate; pinch or scroll to zoom; two-finger or right-drag to pan.`;
547 } else {
548 this.note.textContent = 'Beads at rest. Drag to rotate; pinch or scroll to zoom; two-finger or right-drag to pan.';
549 }
550 this.render();
551 }
552}
554function modelSize(sys: BeadSystem): number {
555 let lo = Infinity;
556 let hi = -Infinity;
557 for (let i = 0; i < sys.n; i++) {
558 lo = Math.min(lo, sys.rest[3 * i]);
559 hi = Math.max(hi, sys.rest[3 * i]);
560 }
561 for (const a of sys.anchors) {
562 lo = Math.min(lo, a.pos[0]);
563 hi = Math.max(hi, a.pos[0]);
564 }
565 return Math.max(hi - lo, 1e-12);
566}
568function textSprite(text: string, color: THREE.Color): THREE.Sprite {
569 const c = document.createElement('canvas');
570 c.width = c.height = 64;
571 const ctx = c.getContext('2d')!;
572 ctx.fillStyle = `#${color.getHexString()}`;
573 ctx.font = '600 44px system-ui, sans-serif';
574 ctx.textAlign = 'center';
575 ctx.textBaseline = 'middle';
576 ctx.fillText(text, 32, 34);
577 const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), depthTest: false }));
578 s.scale.set(0.04, 0.04, 1);
579 return s;
580}
582function axisTriad(at: THREE.Vector3, len: number, ink: THREE.Color): THREE.Group {
583 const g = new THREE.Group();
584 const axes: [string, THREE.Vector3][] = [
585 ['x', new THREE.Vector3(1, 0, 0)],
586 ['y', new THREE.Vector3(0, 1, 0)],
587 ['z', new THREE.Vector3(0, 0, 1)],
588 ];
589 for (const [name, d] of axes) {
590 g.add(new THREE.ArrowHelper(d, at, len, ink, 0.2 * len, 0.1 * len));
591 const label = textSprite(name, ink);
592 label.position.copy(at).addScaledVector(d, len * 1.3);
593 g.add(label);
594 }
595 return g;
596}
598function disposeGroup(g: THREE.Group) {
599 g.traverse((o) => {
600 const m = o as THREE.Mesh;
601 m.geometry?.dispose();
602 const mat = m.material as THREE.Material | THREE.Material[] | undefined;
603 if (Array.isArray(mat)) mat.forEach((x) => x.dispose());
604 else mat?.dispose();
605 });
606 g.clear();
607}