/ proof-of-concept / bead-percussion
Sign in
proof-of-concept / bead-percussion
bead-percussion / src / worker.ts
169 lines · 6.6 KBBlameHistoryRaw
1// Web Worker: runs the numbl script, computes linear modes, and simulates.
3import { growthRate, relDiff } from "./sim/analysis";
4import { computeModes, isPlanar } from "./sim/modes";
5import { numblEig, runScript } from "./sim/runScript";
6import { simulate } from "./sim/solver";
7import { runTwin } from "./sim/twin";
8import type { BeadSystem, SimResult } from "./sim/types";
10const helperSources = import.meta.glob("../matlab/helpers/*.m", { query: "?raw", import: "default", eager: true }) as Record<string, string>;
11const helpers = Object.entries(helperSources).map(([path, source]) => ({ name: path.split("/").pop()!, source }));
13const MAX_MODE_BEADS = 1500;
14const MAX_TWIN_BYTES = 400e6;
16export interface RunPayload {
17 sys: {
18 n: number;
19 pos0: Float64Array;
20 pinned: Uint8Array;
21 si: Int32Array;
22 sj: Int32Array;
23 nDashpots: number;
24 listenBeads: Int32Array;
25 hitBeads: Int32Array;
26 method: string;
27 duration: number;
28 };
29 result: SimResult;
30 modeFreqs: Float64Array | null;
31 notes: string[];
32 check: { dt: number; windows: { t: number; rel: number }[] } | null;
33 // the same run with every hit scaled by 1e-3, its output scaled back up
34 linear: { audio: Float32Array; windows: { t: number; rel: number }[] } | null;
35 // the same run with every hit scaled by (1 + eps): separation of the bead
36 // positions (max over coordinates, relative to the largest displacement)
37 twin: { eps: number; audio: Float32Array; times: Float64Array; sep: Float64Array; rate: number | null } | null;
40export interface RunRequest {
41 type: "run";
42 script: string;
43 dtCheck: boolean;
44 linear: boolean;
45 twin: boolean;
48export type FromWorker =
49 | { type: "log"; text: string }
50 | { type: "stage"; text: string }
51 | { type: "progress"; t: number; duration: number; label: string }
52 | { type: "result"; payload: RunPayload }
53 | { type: "error"; message: string };
55const post = (m: FromWorker, transfer: Transferable[] = []) => (self as unknown as Worker).postMessage(m, transfer);
57const windowsOf = (duration: number) =>
58 [0.01, 0.03, 0.1, 0.3, 1, duration].filter((t, i, a) => t <= duration && a.indexOf(t) === i);
60self.onmessage = (ev: MessageEvent<RunRequest>) => {
61 const { script, dtCheck, linear, twin } = ev.data;
62 try {
63 post({ type: "stage", text: "Running script" });
64 const { sys, warnings } = runScript(script, helpers, text => post({ type: "log", text }));
65 const notes = [...warnings];
67 let modes = null;
68 const nFree = sys.pinned.reduce((a, p) => a + (p ? 0 : 1), 0);
69 if (sys.modes) {
70 if (!isPlanar(sys)) notes.push("Linear modes skipped: the beads do not rest in a plane z = const.");
71 else if (nFree > MAX_MODE_BEADS) notes.push(`Linear modes skipped: ${nFree} free beads (limit ${MAX_MODE_BEADS}).`);
72 else {
73 post({ type: "stage", text: `Computing linear modes (${nFree} free beads)` });
74 modes = computeModes(sys, numblEig);
75 }
76 }
78 // positions at every frame, kept for the perturbed twin
79 const saved: Float64Array[] = [];
80 const savedBytes = Math.round(sys.duration * sys.frameRate + 1) * 3 * sys.n * 8;
81 const keep = twin && savedBytes <= MAX_TWIN_BYTES;
82 if (twin && !keep) notes.push(`Perturbed twin skipped: it would store ${(savedBytes / 1e6).toFixed(0)} MB of positions (limit ${MAX_TWIN_BYTES / 1e6} MB). Lower sys.frameRate or sys.duration.`);
84 post({ type: "stage", text: "Simulating" });
85 const result = simulate(sys, {
86 modes,
87 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Simulating" }),
88 onFrame: keep ? (_f, _t, x) => saved.push(x.slice()) : undefined,
89 });
91 let checkOut: RunPayload["check"] = null;
92 if (dtCheck && !result.aborted) {
93 post({ type: "stage", text: "Simulating again with dt/2" });
94 const half: BeadSystem = { ...sys, dt: result.dt / 2 };
95 const r2 = simulate(half, {
96 maxAnimBytes: 0,
97 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Simulating with dt/2" }),
98 });
99 const fs = result.sampleRate;
100 const windows = windowsOf(sys.duration).map(t => ({ t, rel: relDiff(r2.audio, result.audio, Math.round(t * fs)) }));
101 checkOut = { dt: r2.dt, windows };
102 }
104 let linearOut: RunPayload["linear"] = null;
105 if (linear && !result.aborted) {
106 post({ type: "stage", text: "Simulating the small-strike reference" });
107 const s = 1e-3;
108 const small: BeadSystem = {
109 ...sys,
110 dt: result.dt,
111 hits: sys.hits.map(h => ({
112 ...h,
113 velocity: [h.velocity[0] * s, h.velocity[1] * s, h.velocity[2] * s],
114 force: [h.force[0] * s, h.force[1] * s, h.force[2] * s],
115 })),
116 };
117 const r3 = simulate(small, {
118 maxAnimBytes: 0,
119 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Small-strike reference" }),
120 });
121 const audio = r3.audio.map(v => v / s);
122 const fs = result.sampleRate;
123 const windows = windowsOf(sys.duration).map(t => ({ t, rel: relDiff(audio, result.audio, Math.round(t * fs)) }));
124 linearOut = { audio, windows };
125 }
127 let twinOut: RunPayload["twin"] = null;
128 if (keep && !result.aborted) {
129 post({ type: "stage", text: "Simulating the perturbed twin" });
130 const eps = 1e-9;
131 const { audio, sep } = runTwin(sys, saved, result.dt, eps, t =>
132 post({ type: "progress", t, duration: sys.duration, label: "Perturbed twin" })
133 );
134 const times = result.frameTimes.slice(0, saved.length);
135 twinOut = { eps, audio, times, sep, rate: growthRate(times, sep, eps) };
136 }
138 const hitBeads = Int32Array.from(new Set(sys.hits.flatMap(h => Array.from(h.beads))));
139 const payload: RunPayload = {
140 sys: {
141 n: sys.n,
142 pos0: sys.pos0,
143 pinned: sys.pinned,
144 si: sys.si,
145 sj: sys.sj,
146 nDashpots: sys.di.length,
147 listenBeads: sys.listenBeads,
148 hitBeads,
149 method: sys.method,
150 duration: sys.duration,
151 },
152 result,
153 modeFreqs: modes ? modes.freqs : null,
154 notes,
155 check: checkOut,
156 linear: linearOut,
157 twin: twinOut,
158 };
159 const transfer: Transferable[] = [result.audio.buffer, ...result.animFrames.map(f => f.buffer)];
160 if (result.modeEnergy) transfer.push(result.modeEnergy.buffer);
161 if (linearOut) transfer.push(linearOut.audio.buffer);
162 if (twinOut) transfer.push(twinOut.audio.buffer, twinOut.sep.buffer);
163 post({ type: "result", payload }, transfer);
164 } catch (e) {
165 const err = e as { message?: string; line?: number; file?: string };
166 const where = err.line ? ` (line ${err.line})` : "";
167 post({ type: "error", message: `${err.message ?? String(e)}${where}` });
168 }
169};
↑↓ move↵openescclose