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