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 // set the replay's displacement exaggeration (kept for later replays)
156 setExaggeration(x: number) {
157 this.opts.exaggeration = this.exaggeration = x;
158 this.exagInput.value = fmtNum(x);
159 this.update();
160 }
162 // redraw with the current colors (after a theme change the view cannot see by itself)
163 restyle() {
164 this.rebuild();
165 }
167 showSetup(spec: SceneSpec) {
168 this.setupSpec = spec;
169 if (this.mode === 'setup') this.rebuild();
170 else this.setMode('setup');
171 }
173 // keep = true: more frames of the replay already shown (a partial result
174 // growing); keeps the mode and any exaggeration the user set
175 showReplay(spec: ReplaySpec, keep = false) {
176 this.replaySpec = spec;
177 let tmax = 0;
178 for (let i = 0; i < spec.frames.length; i++) if (i % 3 !== 0) tmax = Math.max(tmax, Math.abs(spec.frames[i]));
179 const size = modelSize(spec.sys);
180 const wasAuto = this.exaggeration === this.autoExaggeration;
181 this.autoExaggeration = tmax > 0 ? Math.max(1, (GLYPH * size) / tmax) : 1;
182 if (this.opts.exaggeration) this.exaggeration = this.opts.exaggeration;
183 else if (!keep || wasAuto) this.exaggeration = this.autoExaggeration;
184 this.exagInput.value = fmtNum(this.exaggeration);
185 if (keep) {
186 if (this.mode === 'replay') {
187 this.frames = spec.frames;
188 this.update();
189 }
190 return;
191 }
192 (this.tabs.querySelector('[data-v="replay"]') as HTMLButtonElement).disabled = false;
193 this.setMode('replay');
194 }
196 private setMode(m: Mode) {
197 this.mode = m;
198 this.tabs.querySelectorAll<HTMLButtonElement>('button').forEach((b) => b.classList.toggle('on', b.dataset.v === m));
199 this.bar.hidden = this.exagRow.hidden = m !== 'replay' || !!this.opts.simple;
200 if (m === 'setup') this.tl.pause();
201 this.rebuild();
202 }
204 private setView(v: View) {
205 this.view = v;
206 const dirs: Record<View, [number, number, number]> = {
207 persp: [-0.45, 0.42, 1.05],
208 front: [0, 0, 1],
209 top: [0, 1, 0.0001],
210 end: [1, 0, 0],
211 };
212 // back off far enough that the model (about 1.4 wide with its supports) fits horizontally
213 const half = Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2));
214 const fit = 0.75 / (half * this.camera.aspect) + 0.3;
215 const dist = Math.max(this.view === 'persp' ? 1.2 : 1.45, fit);
216 this.camera.position.set(...dirs[v]).setLength(dist);
217 this.camera.up.set(0, 1, 0);
218 if (v === 'top') this.camera.up.set(0, 0, -1);
219 this.controls?.target.set(0, 0, 0);
220 this.camera.lookAt(0, 0, 0);
221 this.controls?.update();
222 this.render();
223 }
225 private resize() {
226 if (!this.renderer) return;
227 const w = this.wrap.clientWidth;
228 const h = this.wrap.clientHeight;
229 if (w === 0 || h === 0) return;
230 this.renderer.setSize(w, h);
231 const narrowBefore = this.camera.aspect < 1;
232 this.camera.aspect = w / h;
233 this.camera.updateProjectionMatrix();
234 // refit when the view turns portrait or landscape (phone rotation, first layout)
235 if (narrowBefore !== this.camera.aspect < 1 || !this.fitted) {
236 this.fitted = true;
237 this.setView(this.view);
238 } else this.render();
239 }
241 private render() {
242 this.renderer?.render(this.scene, this.camera);
243 }
245 // node position (beads and anchors), normalized
246 private nodePos(sys: BeadSystem, node: number, out: THREE.Vector3): THREE.Vector3 {
247 if (node < sys.n) out.set(sys.rest[3 * node], sys.rest[3 * node + 1], sys.rest[3 * node + 2]);
248 else out.set(...sys.anchors[node - sys.n].pos);
249 return out.sub(this.center).multiplyScalar(this.scale);
250 }
252 private rebuild() {
253 const spec = this.mode === 'replay' ? this.replaySpec : this.setupSpec;
254 disposeGroup(this.model);
255 this.beads = this.pins = this.springs = this.hammerArrows = null;
256 this.slideRings = [];
257 this.pickupArrow = null;
258 this.mallet = null;
259 this.spec = spec;
260 this.frames = this.mode === 'replay' && this.replaySpec ? this.replaySpec.frames : null;
261 if (!spec) return this.render();
262 if (this.renderer) this.renderer.setClearColor(new THREE.Color(css('--surface-1', this.wrap)));
263 const { sys, exc, pickup } = spec;
264 const n = sys.n;
266 // normalize: longest extent of beads and anchors -> 1, centered
267 const box = new THREE.Box3();
268 const v = new THREE.Vector3();
269 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]));
270 for (const a of sys.anchors) box.expandByPoint(v.set(...a.pos));
271 box.getCenter(this.center);
272 const size = box.getSize(new THREE.Vector3());
273 this.scale = 1 / Math.max(size.x, size.y, size.z, 1e-12);
275 // bead size from nearest-neighbour spacing
276 let minLen = Infinity;
277 const p = new THREE.Vector3();
278 const q = new THREE.Vector3();
279 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)));
280 if (!Number.isFinite(minLen)) minLen = 0.05;
281 const r = Math.min(0.32 * minLen, 0.022);
283 const cBead = new THREE.Color(css('--series-1', this.wrap));
284 const cExc = new THREE.Color(css('--series-2', this.wrap));
285 const cPick = new THREE.Color(css('--series-3', this.wrap));
286 const cInk = new THREE.Color(css('--text-primary', this.wrap));
287 const cMuted = new THREE.Color(css('--text-muted', this.wrap));
289 // grid floor for depth cues
290 const grid = new THREE.GridHelper(1.4, 14, cMuted, cMuted);
291 (grid.material as THREE.Material).transparent = true;
292 (grid.material as THREE.Material).opacity = 0.25;
293 grid.position.y = -0.22;
294 this.model.add(grid);
295 this.model.add(axisTriad(new THREE.Vector3(-0.58, -0.22, -0.3), 0.08, cInk));
297 // beads (pinned beads are drawn as cubes instead)
298 const pickBead = (i: number) => pickup[3 * i] !== 0 || pickup[3 * i + 1] !== 0 || pickup[3 * i + 2] !== 0;
299 const free: number[] = [];
300 const pinned: number[] = [];
301 for (let i = 0; i < n; i++) (sys.pinned[i] ? pinned : free).push(i);
302 const beadMat = new THREE.MeshStandardMaterial({ roughness: 0.55, metalness: 0.1 });
303 this.beads = new THREE.InstancedMesh(new THREE.SphereGeometry(r, 20, 14), beadMat, Math.max(1, n));
304 this.beads.count = n;
305 // a pickup over every bead is named in the legend rather than painting the whole model
306 let nPick = 0;
307 for (let i = 0; i < n; i++) if (pickBead(i)) nPick++;
308 for (let i = 0; i < n; i++) this.beads.setColorAt(i, pickBead(i) && nPick < n ? cPick : cBead);
309 this.model.add(this.beads);
310 if (pinned.length) {
311 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);
312 this.model.add(this.pins);
313 }
314 (this.beads.userData as { free: number[]; pinned: number[] }) = { free, pinned };
316 // springs
317 const sg = new THREE.BufferGeometry();
318 sg.setAttribute('position', new THREE.BufferAttribute(new Float32Array(sys.si.length * 6), 3));
319 this.springs = new THREE.LineSegments(sg, new THREE.LineBasicMaterial({ color: cMuted }));
320 this.model.add(this.springs);
322 // supports
323 const wallSize = 0.16;
324 if (spec.hoop) {
325 const hoop = new THREE.Mesh(
326 new THREE.TorusGeometry(spec.hoop.radius * this.scale, 0.012, 10, 96),
327 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.7 }),
328 );
329 hoop.rotation.x = Math.PI / 2;
330 hoop.position.set(-this.center.x * this.scale, -this.center.y * this.scale, -this.center.z * this.scale);
331 this.model.add(hoop);
332 }
333 if (spec.post) {
334 const o = new THREE.Vector3(-this.center.x, spec.post.y - this.center.y, -this.center.z).multiplyScalar(this.scale);
335 const rodLen = o.y + 0.22;
336 const rod = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, rodLen + 0.04, 10), new THREE.MeshStandardMaterial({ color: cMuted }));
337 rod.position.copy(o).add(new THREE.Vector3(0, 0.02 - rodLen / 2, 0));
338 this.model.add(rod);
339 }
340 if (spec.mic) {
341 const o = new THREE.Vector3(...spec.mic.from).sub(this.center).multiplyScalar(this.scale);
342 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));
343 }
344 if (!spec.hoop) sys.anchors.forEach((a) => {
345 const at = this.nodePos(sys, sys.n + sys.anchors.indexOf(a), new THREE.Vector3());
346 const side = at.x < 0 ? -1 : 1;
347 if (a.slideBead < 0) {
348 const wall = new THREE.Mesh(
349 new THREE.BoxGeometry(0.02, wallSize, wallSize),
350 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.8 }),
351 );
352 wall.position.copy(at).add(new THREE.Vector3(side * 0.01, 0, 0));
353 this.model.add(wall);
354 } else {
355 const plane = new THREE.Mesh(
356 new THREE.PlaneGeometry(wallSize, wallSize),
357 new THREE.MeshBasicMaterial({ color: cMuted, transparent: true, opacity: 0.18, side: THREE.DoubleSide, depthWrite: false }),
358 );
359 plane.rotation.y = Math.PI / 2;
360 plane.position.copy(at);
361 this.model.add(plane);
362 const edges = new THREE.LineSegments(new THREE.EdgesGeometry(plane.geometry), new THREE.LineBasicMaterial({ color: cMuted }));
363 edges.rotation.y = Math.PI / 2;
364 edges.position.copy(at);
365 this.model.add(edges);
366 const ring = new THREE.Mesh(new THREE.TorusGeometry(1.3 * r, 0.35 * r, 8, 24), new THREE.MeshStandardMaterial({ color: cInk }));
367 ring.rotation.y = Math.PI / 2;
368 ring.position.copy(at);
369 this.model.add(ring);
370 this.slideRings.push({ mesh: ring, bead: a.slideBead });
371 }
372 });
374 // excitation glyphs
375 const legend: string[] = [];
376 const sw = (c: THREE.Color, shape = 'dot') => `<i class="glyph ${shape}" style="--c:#${c.getHexString()}"></i>`;
377 legend.push(`<span>${sw(cBead)}bead</span>`);
378 if (pinned.length) legend.push(`<span>${sw(cInk, 'square')}${spec.post ? 'bead held at the hub' : 'pinned bead'}</span>`);
379 if (spec.hoop) legend.push(`<span>${sw(cMuted, 'ring')}clamped rim</span>`);
381 else if (sys.anchors.some((a) => a.slideBead < 0)) legend.push(`<span>${sw(cMuted, 'square')}clamped end (wall)</span>`);
382 if (sys.anchors.some((a) => a.slideBead >= 0)) legend.push(`<span>${sw(cInk, 'ring')}sliding end (ring on a frictionless plane)</span>`);
383 const size0 = modelSize(sys);
384 const dirs = (field: Float64Array) => {
385 let m = 0;
386 for (let i = 0; i < n; i++) m = Math.max(m, Math.hypot(field[3 * i], field[3 * i + 1], field[3 * i + 2]));
387 return m;
388 };
389 if (this.mode === 'setup' && spec.excKind === 'pluck') {
390 const m = dirs(exc.u0);
391 if (m > 0) {
392 const E = (GLYPH * size0) / m;
393 const pts: THREE.Vector3[] = [];
394 const left = sys.anchors.find((a) => a.pos[0] < sys.rest[0]);
395 const right = sys.anchors.find((a) => a.pos[0] > sys.rest[3 * (n - 1)]);
396 if (left) pts.push(this.nodePos(sys, n + sys.anchors.indexOf(left), new THREE.Vector3()));
397 for (let i = 0; i < n; i++) {
398 const w = new THREE.Vector3(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]).multiplyScalar(E * this.scale);
399 pts.push(this.nodePos(sys, i, new THREE.Vector3()).add(w));
400 }
401 if (right) pts.push(this.nodePos(sys, n + sys.anchors.indexOf(right), new THREE.Vector3()));
402 const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineDashedMaterial({ color: cExc, dashSize: 0.015, gapSize: 0.01 }));
403 line.computeLineDistances();
404 this.model.add(line);
405 let peak = 0;
406 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;
407 const from = this.nodePos(sys, peak, new THREE.Vector3());
408 const to = pts[peak + (left ? 1 : 0)];
409 const len = from.distanceTo(to);
410 if (len > 0) this.model.add(new THREE.ArrowHelper(to.clone().sub(from).normalize(), from, len, cExc, 0.25 * len, 0.12 * len));
411 legend.push(`<span>${sw(cExc, 'dash')}pluck: initial shape, drawn ×${fmtNum(E)} (${fmtNum(m * 1000)} mm peak)</span>`);
412 }
413 }
414 if (spec.excKind === 'strike' && this.mode === 'setup') {
415 const m = dirs(exc.v0);
416 if (m > 0) this.model.add(this.arrows(sys, exc.v0, m, cExc, false));
417 legend.push(`<span>${sw(cExc, 'arrow')}strike: initial velocity (${fmtNum(m)} m/s peak)</span>`);
418 }
419 if (this.mode === 'setup' && spec.excKind === 'press') {
420 const m = dirs(exc.u0);
421 if (m > 0) {
422 const E = (0.5 * GLYPH * size0) / m;
423 const pts: THREE.Vector3[] = [];
424 for (let i = 0; i < n; i++) {
425 if (Math.hypot(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]) < 0.02 * m) continue;
426 const w = new THREE.Vector3(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]).multiplyScalar(E * this.scale);
427 pts.push(this.nodePos(sys, i, new THREE.Vector3()).add(w));
428 }
429 const dots = new THREE.Points(new THREE.BufferGeometry().setFromPoints(pts), new THREE.PointsMaterial({ color: cExc, size: 1.2 * r }));
430 this.model.add(dots);
431 legend.push(`<span>${sw(cExc)}press: initial shape, drawn ×${fmtNum(E)} (${fmtNum(m * 1000)} mm deep)</span>`);
432 }
433 }
434 if (exc.mallet) {
435 const ml = exc.mallet;
436 const dir = new THREE.Vector3(...ml.vel0).normalize(); // the stick travels along its own axis
437 const contact = new THREE.Vector3();
438 for (let i = 0; i < n; i++) if (ml.weights[i] > 0) contact.addScaledVector(this.nodePos(sys, i, new THREE.Vector3()), ml.weights[i]);
439 const head = Math.max(1.6 * r, 0.025);
440 const group = new THREE.Group();
441 const felt = new THREE.Mesh(new THREE.SphereGeometry(head, 24, 16), new THREE.MeshStandardMaterial({ color: cExc, roughness: 0.9 }));
442 felt.position.copy(dir).multiplyScalar(-head);
443 const stick = new THREE.Mesh(
444 new THREE.CylinderGeometry(0.15 * head, 0.15 * head, 0.3, 10),
445 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.6 }),
446 );
447 stick.position.copy(dir).multiplyScalar(-(2 * head + 0.15));
448 stick.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir);
449 group.add(felt, stick);
450 this.model.add(group);
451 this.mallet = { group, contact, dir };
452 const speed = Math.hypot(...ml.vel0);
453 const what = spec.excKind === 'stick' ? 'stick' : 'mallet';
454 legend.push(
455 `<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>`,
456 );
457 }
458 if ((spec.excKind === 'hammer' || spec.excKind === 'force') && exc.force) {
459 const m = dirs(exc.force.shape);
460 if (m > 0) {
461 this.hammerArrows = this.arrows(sys, exc.force.shape, m, cExc, true);
462 this.model.add(this.hammerArrows);
463 }
464 legend.push(
465 `<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>`,
466 );
467 }
469 // pickup
470 const pk: number[] = [];
471 for (let i = 0; i < n; i++) if (pickBead(i)) pk.push(i);
472 if (pk.length === 1) {
473 const i = pk[0];
474 const d = new THREE.Vector3(pickup[3 * i], pickup[3 * i + 1], pickup[3 * i + 2]).normalize();
475 const len = Math.max(0.05, 6 * r);
476 const arrow = new THREE.ArrowHelper(d, this.nodePos(sys, i, new THREE.Vector3()), len, cPick, 0.3 * len, 0.18 * len);
477 this.model.add(arrow);
478 this.pickupArrow = { arrow, bead: i };
479 }
480 legend.push(spec.mic ? `<span>${sw(cPick, 'arrow')}${spec.mic.label}</span>` : `<span>${sw(cPick)}pickup: ${spec.pickupLabel}</span>`);
481 if (spec.note) legend.push(`<span>${spec.note}</span>`);
482 this.legend.innerHTML = legend.join('');
483 this.update();
484 }
486 // arrows proportional to a per-bead vector field; `into` = arrow ends at the bead (a push)
487 private arrows(sys: BeadSystem, field: Float64Array, max: number, color: THREE.Color, into: boolean): THREE.Group {
488 const g = new THREE.Group();
489 for (let i = 0; i < sys.n; i++) {
490 const d = new THREE.Vector3(field[3 * i], field[3 * i + 1], field[3 * i + 2]);
491 const mag = d.length();
492 if (mag < 0.05 * max) continue;
493 const len = GLYPH * (mag / max);
494 d.normalize();
495 const at = this.nodePos(sys, i, new THREE.Vector3());
496 const origin = into ? at.clone().addScaledVector(d, -len) : at;
497 const arrow = new THREE.ArrowHelper(d, origin, len, color, Math.min(0.03, 0.3 * len), Math.min(0.016, 0.18 * len));
498 arrow.userData = { bead: i, dir: d.clone(), len };
499 g.add(arrow);
500 }
501 return g;
502 }
504 // position everything for the current frame (or rest, in setup)
505 private update() {
506 const spec = this.spec;
507 if (!spec || !this.beads) return this.render();
508 const { sys } = spec;
509 const n = sys.n;
510 const frames = this.frames;
511 const off = frames ? this.tl.frame * 3 * n : 0;
512 const E = this.exaggeration * this.scale;
513 const P = new Array<THREE.Vector3>(n + sys.anchors.length);
514 for (let i = 0; i < n; i++) {
515 const p = this.nodePos(sys, i, new THREE.Vector3());
516 if (frames) p.add(new THREE.Vector3(frames[off + 3 * i], frames[off + 3 * i + 1], frames[off + 3 * i + 2]).multiplyScalar(E));
517 P[i] = p;
518 }
519 sys.anchors.forEach((a, k) => {
520 const p = this.nodePos(sys, n + k, new THREE.Vector3());
521 if (a.slideBead >= 0) {
522 p.y = P[a.slideBead].y;
523 p.z = P[a.slideBead].z;
524 }
525 P[n + k] = p;
526 });
527 const m = new THREE.Matrix4();
528 const { pinned } = this.beads.userData as { free: number[]; pinned: number[] };
529 for (let i = 0; i < n; i++) {
530 // hide pinned beads' spheres (cubes stand in)
531 m.makeScale(sys.pinned[i] ? 0 : 1, sys.pinned[i] ? 0 : 1, sys.pinned[i] ? 0 : 1).setPosition(P[i]);
532 this.beads.setMatrixAt(i, m);
533 }
534 this.beads.instanceMatrix.needsUpdate = true;
535 if (this.beads.instanceColor) this.beads.instanceColor.needsUpdate = true;
536 if (this.pins) {
537 pinned.forEach((i, k) => this.pins!.setMatrixAt(k, m.makeTranslation(P[i].x, P[i].y, P[i].z)));
538 this.pins.instanceMatrix.needsUpdate = true;
539 }
540 if (this.springs) {
541 const arr = (this.springs.geometry.getAttribute('position') as THREE.BufferAttribute).array as Float32Array;
542 for (let s = 0; s < sys.si.length; s++) {
543 const a = P[sys.si[s]];
544 const b = P[sys.sj[s]];
545 arr.set([a.x, a.y, a.z, b.x, b.y, b.z], 6 * s);
546 }
547 this.springs.geometry.getAttribute('position').needsUpdate = true;
548 this.springs.geometry.computeBoundingSphere();
549 }
550 for (const { mesh, bead } of this.slideRings) {
551 mesh.position.y = P[bead].y;
552 mesh.position.z = P[bead].z;
553 }
554 if (this.pickupArrow) this.pickupArrow.arrow.position.copy(P[this.pickupArrow.bead]);
555 if (this.mallet) {
556 const mp = this.mode === 'replay' ? this.replaySpec?.malletPos : undefined;
557 const g = this.mallet.group.position.copy(this.mallet.contact);
558 // in setup it hovers back along its path; in replay it follows the run
559 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));
560 else g.addScaledVector(this.mallet.dir, -0.6 * GLYPH);
561 }
562 if (this.hammerArrows && spec.exc.force) {
563 const f = spec.exc.force;
564 const t = frames ? this.tl.times[this.tl.frame] : f.tau / 2;
565 const s = t >= 0 && t <= f.tau ? 0.5 * (1 - Math.cos((2 * Math.PI * t) / f.tau)) : 0;
566 this.hammerArrows.visible = s > 0.02;
567 for (const c of this.hammerArrows.children) {
568 const { bead, dir, len } = c.userData as { bead: number; dir: THREE.Vector3; len: number };
569 const l = Math.max(1e-4, len * (frames ? s : 1));
570 const arrow = c as THREE.ArrowHelper;
571 arrow.position.copy(P[bead]).addScaledVector(dir, -l);
572 arrow.setLength(l, Math.min(0.03, 0.3 * l), Math.min(0.016, 0.18 * l));
573 }
574 }
575 if (this.mode === 'replay' && frames) {
576 this.note.textContent =
577 `Displacements drawn ×${fmtNum(this.exaggeration)} (all three components, so longitudinal motion is exaggerated too). ` +
578 `Drag to rotate; pinch or scroll to zoom; two-finger or right-drag to pan.`;
579 } else {
580 this.note.textContent = 'Beads at rest. Drag to rotate; pinch or scroll to zoom; two-finger or right-drag to pan.';
581 }
582 this.render();
583 }
584}
586function modelSize(sys: BeadSystem): number {
587 let lo = Infinity;
588 let hi = -Infinity;
589 for (let i = 0; i < sys.n; i++) {
590 lo = Math.min(lo, sys.rest[3 * i]);
591 hi = Math.max(hi, sys.rest[3 * i]);
592 }
593 for (const a of sys.anchors) {
594 lo = Math.min(lo, a.pos[0]);
595 hi = Math.max(hi, a.pos[0]);
596 }
597 return Math.max(hi - lo, 1e-12);
598}
600function textSprite(text: string, color: THREE.Color): THREE.Sprite {
601 const c = document.createElement('canvas');
602 c.width = c.height = 64;
603 const ctx = c.getContext('2d')!;
604 ctx.fillStyle = `#${color.getHexString()}`;
605 ctx.font = '600 44px system-ui, sans-serif';
606 ctx.textAlign = 'center';
607 ctx.textBaseline = 'middle';
608 ctx.fillText(text, 32, 34);
609 const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), depthTest: false }));
610 s.scale.set(0.04, 0.04, 1);
611 return s;
612}
614function axisTriad(at: THREE.Vector3, len: number, ink: THREE.Color): THREE.Group {
615 const g = new THREE.Group();
616 const axes: [string, THREE.Vector3][] = [
617 ['x', new THREE.Vector3(1, 0, 0)],
618 ['y', new THREE.Vector3(0, 1, 0)],
619 ['z', new THREE.Vector3(0, 0, 1)],
620 ];
621 for (const [name, d] of axes) {
622 g.add(new THREE.ArrowHelper(d, at, len, ink, 0.2 * len, 0.1 * len));
623 const label = textSprite(name, ink);
624 label.position.copy(at).addScaledVector(d, len * 1.3);
625 g.add(label);
626 }
627 return g;
628}
630function disposeGroup(g: THREE.Group) {
631 g.traverse((o) => {
632 const m = o as THREE.Mesh;
633 m.geometry?.dispose();
634 const mat = m.material as THREE.Material | THREE.Material[] | undefined;
635 if (Array.isArray(mat)) mat.forEach((x) => x.dispose());
636 else mat?.dispose();
637 });
638 g.clear();
639}