1// The application: the design script, the two run modes (the linear modal
2// model on the CPU workers and the full nonlinear simulation on the GPU),
3// the plate view, the movie, the audio, and the spectrogram.
5import { compileDesign, evaluatePlate, isFlat, profileStats, type Design, DesignError } from "./design.ts";
6import { PRESETS, DEFAULT_PRESET, presetById } from "./presets.ts";
7import {
8 type Plate,
9 type SimParams,
10 defaultParams,
11 countInside,
12 massProperties,
13 meanThickness,
14 thicknessRange,
15 standRates,
16 strikePoint,
17 strikePatch,
18 listenerPosition,
19 dispersionFrequency,
20 inPlaneSpeed,
21 CFL,
22} from "./params.ts";
23import { fitSigma, fittedRate, t60At, LN1000, decayRate } from "./loss.ts";
24import { assemble, type LinearSystem } from "./model/assemble.ts";
25import { maxAngularFrequency, fullLoss, type FullLoss } from "./model/reference.ts";
26import { type ModeSet } from "./modal/modes.ts";
27import { WorkerPool } from "./modal/pool.ts";
28import { modalModel, modeShapeOnGrid, type ModalModel, type ContactResult } from "./modal/synth.ts";
29import { Simulation } from "./sim/simulation.ts";
30import { runSelfTest } from "./sim/selftest.ts";
31import { PlateRenderer, type ViewMode, type ColorMode } from "./render/renderer.ts";
32import { Spectrogram } from "./audio/spectrogram.ts";
33import { Player } from "./audio/player.ts";
34import { encodeWav } from "./audio/wav.ts";
35import { levelGain, applyLevel, peakDbfs, peakSpl, type LevelMode } from "./audio/level.ts";
36import { DesignEditor } from "./ui/editor.ts";
37import { ParamForm, formatNumber } from "./ui/form.ts";
38import { ModeBrowser } from "./ui/modes.ts";
39import { Tutorial } from "./tutorial/tutorial.ts";
40import { type Memo, type TutorialContext, type TutorialHost } from "./tutorial/steps.ts";
42type RunMode = "linear" | "full";
43type ViewState = "design" | "mode" | "live" | "movie";
45const $ = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T;
47/** Peak level [dBFS] from which a recording is considered loud enough to warn before playing. */
48const LOUD_DBFS = -6;
49/** A recording louder than the accepted level by this much prompts again [dB]. */
50const LOUD_STEP_DB = 3;
52/** A recording: the listener signal and the movie of one run, from either model. */
53interface Recording {
54 audio: Float32Array;
55 samples: number;
56 fs: number;
57 frames: Float32Array[];
58 fps: number;
59 source: RunMode;
60}
62class App {
63 // GPU
64 device: GPUDevice | null = null;
65 // Design and plate
66 design: Design | null = null;
67 plate: Plate | null = null;
68 plateSpacing = 0;
69 designGeneration = 0;
70 // Linear model
71 pool: WorkerPool | null = null;
72 sys: LinearSystem | null = null;
73 modes: ModeSet | null = null;
74 model: ModalModel | null = null;
75 modesBusy: Promise<void> = Promise.resolve();
76 /** Modes of recent designs, keyed by the script, the spacing and the cutoff; the newest entry is last. */
77 modesCache = new Map<string, { sys: LinearSystem; modes: ModeSet; model: ModalModel }>();
78 headProgress!: HTMLDivElement;
79 /** The cache key of the modes the pool currently holds. */
80 currentModesKey: string | null = null;
81 headProgressBar!: HTMLDivElement;
82 synthBusy = false;
83 synthPending = false;
84 synthesized = false;
85 lastContact: ContactResult | null = null;
86 // Full simulation
87 sim: Simulation | null = null;
88 running = false;
89 paused = false;
90 // Recording and view
91 rec: Recording | null = null;
92 view: ViewState = "design";
93 frameIndex = 0;
94 runMode: RunMode = "linear";
95 // UI
96 editor!: DesignEditor;
97 form!: ParamForm;
98 modeBrowser!: ModeBrowser;
99 renderer!: PlateRenderer;
100 spec!: Spectrogram;
101 tutorial: Tutorial | null = null;
102 tutorialMemo: Memo = {};
103 specOpts = { window: 2048, logFreq: false };
104 specWinSel!: HTMLSelectElement;
105 specLogChk!: HTMLInputElement;
106 colorSel!: HTMLSelectElement;
107 player = new Player();
108 levelMode: LevelMode = "absolute";
109 gainDb = -40;
110 showTicks = true;
111 viewOpts = { mode: "3d" as ViewMode, color: "height" as ColorMode, showProfile: true, exaggeration: 1, range: 0 };
112 // Controls
113 runModeSel!: HTMLSelectElement;
114 durationInput!: HTMLInputElement;
115 startBtn!: HTMLButtonElement;
116 pauseBtn!: HTMLButtonElement;
117 stopBtn!: HTMLButtonElement;
118 continueBtn!: HTMLButtonElement;
119 runStatus!: HTMLDivElement;
120 scrub!: HTMLInputElement;
121 timeLabel!: HTMLSpanElement;
122 playBtn!: HTMLButtonElement;
123 liveBtn!: HTMLButtonElement;
124 designBtn!: HTMLButtonElement;
125 peakLabel!: HTMLSpanElement;
126 downloadBtn!: HTMLButtonElement;
127 overlay!: HTMLDivElement;
128 synthTimer: number | null = null;
129 // Loudness warning
130 loudWarn!: HTMLDivElement;
131 loudWarnText!: HTMLSpanElement;
132 loudPlayBtn!: HTMLButtonElement;
133 loudGo: (() => void) | null = null;
134 /** The highest peak level [dBFS] the user has agreed to play; louder signals prompt again. */
135 acceptedPeakDb = -Infinity;
137 async init(): Promise<void> {
138 const url = new URLSearchParams(location.search);
139 if (!url.has("nogpu") && navigator.gpu) {
140 try {
141 const adapter = await navigator.gpu.requestAdapter();
142 if (adapter) this.device = await adapter.requestDevice();
143 } catch (e) {
144 console.warn("WebGPU unavailable", e);
145 }
146 }
147 if (typeof Worker !== "undefined") this.pool = new WorkerPool(WorkerPool.defaultSize());
149 this.buildControls();
150 this.buildForm();
151 this.buildViewToolbar();
152 this.buildMovieToolbar();
153 this.buildSpecToolbar();
154 this.buildSplitter();
156 this.renderer = new PlateRenderer($("view"), this.device);
157 if (!this.renderer.has3d) this.viewOpts.mode = "2d";
158 this.renderer.setOptions(this.viewOpts);
159 this.overlay = $("viewOverlay");
160 const p = this.form.get();
161 this.spec = new Spectrogram($("spec"), { fs: p.fs, window: 2048, hop: 256, maxHz: 12000, dbRange: 80, logFreq: false });
162 this.spec.setDuration(p.duration);
163 this.modeBrowser = new ModeBrowser($("modes"), (m) => this.showMode(m));
164 this.editor = new DesignEditor($("design"), { onSource: (src) => this.onSource(src) });
165 this.tutorial = new Tutorial($("tutorial"), this.tutorialHost(), (open) => {
166 $("tutorialBtn").classList.toggle("active", open);
167 this.renderer.resize(); this.spec.resize();
168 });
169 $("tutorialBtn").addEventListener("click", () => this.tutorial?.toggle());
171 if (url.has("mode")) this.setRunMode(url.get("mode") === "full" ? "full" : "linear");
172 else this.setRunMode(this.device ? "linear" : "linear");
173 // The parameters come first, so that the preset is evaluated at the requested spacing.
174 this.form.applyUrl(url);
175 this.durationInput.value = String(this.form.get().duration);
176 const preset = url.get("preset");
177 this.editor.selectPreset(preset && presetById(preset) ? preset : DEFAULT_PRESET);
178 // The tutorial opens on request (?tutorial=1 or ?tutorial=<step id>) or when it was open last time.
179 const tut = url.get("tutorial");
180 if (tut !== null) this.tutorial.open(tut === "1" || tut === "" ? undefined : tut);
181 else if (this.tutorial.wasOpen()) this.tutorial.open();
183 const loop = () => {
184 this.renderer.render();
185 requestAnimationFrame(loop);
186 };
187 requestAnimationFrame(loop);
188 window.addEventListener("resize", () => { this.renderer.resize(); this.spec.resize(); });
189 this.renderer.resize();
190 this.spec.resize();
192 // Test hooks.
193 (window as unknown as { cymbalsim: unknown }).cymbalsim = {
194 app: this,
195 selftest: () => this.selfTest(),
196 runLinear: () => this.runLinear(),
197 runFull: () => this.runFull(),
198 modesReady: () => this.modesBusy,
199 status: () => this.testStatus(),
200 tutorial: this.tutorial,
201 };
202 if (url.has("selftest")) {
203 const r = await this.selfTest();
204 this.overlay.textContent = r;
205 }
206 if (url.has("autostart")) {
207 await this.modesBusy;
208 this.start();
209 }
210 }
212 // ---------- Controls ----------
214 private buildControls(): void {
215 const c = $("controls");
216 this.runModeSel = document.createElement("select");
217 this.runModeSel.innerHTML = `<option value="linear">Linear (modal)</option><option value="full">Full (nonlinear, GPU)</option>`;
218 this.runModeSel.addEventListener("change", () => this.setRunMode(this.runModeSel.value as RunMode));
219 const durLabel = document.createElement("label");
220 durLabel.textContent = "Duration";
221 this.durationInput = document.createElement("input");
222 this.durationInput.type = "number"; this.durationInput.min = "0.1"; this.durationInput.step = "0.5"; this.durationInput.style.width = "60px";
223 this.durationInput.addEventListener("change", () => {
224 const d = Math.max(0.1, Number(this.durationInput.value) || 1);
225 this.form.set("duration", d);
226 this.spec.setDuration(d);
227 if (this.sim) this.sim.setDuration(d);
228 this.updateButtons();
229 });
230 const s = document.createElement("span"); s.textContent = " s";
231 durLabel.append(this.durationInput, s);
232 this.startBtn = this.button("Start", () => this.start(), "primary");
233 this.pauseBtn = this.button("Pause", () => this.pause());
234 this.stopBtn = this.button("Stop", () => this.stopRun());
235 this.continueBtn = this.button("Continue", () => this.continueRun());
236 c.append(this.runModeSel, durLabel, this.startBtn, this.pauseBtn, this.stopBtn, this.continueBtn);
237 this.headProgress = document.createElement("div");
238 this.headProgress.className = "progress";
239 this.headProgress.hidden = true;
240 this.headProgressBar = document.createElement("div");
241 this.headProgress.append(this.headProgressBar);
242 this.runStatus = document.createElement("div");
243 this.runStatus.className = "status";
244 $("sidebarHead").append(this.headProgress, this.runStatus);
245 }
247 /** The progress bar under the run controls (fraction 0..1, or null to hide) with a status message. */
248 private setProgress(fraction: number | null, message?: string): void {
249 this.headProgress.hidden = fraction === null;
250 if (fraction !== null) this.headProgressBar.style.width = `${Math.round(100 * fraction)}%`;
251 if (message !== undefined) this.runStatus.textContent = message;
252 }
254 private button(label: string, onClick: () => void, cls = ""): HTMLButtonElement {
255 const b = document.createElement("button");
256 b.textContent = label;
257 if (cls) b.className = cls;
258 b.addEventListener("click", onClick);
259 return b;
260 }
262 private buildForm(): void {
263 this.form = new ParamForm(
264 $("params"),
265 [
266 {
267 title: "Strike",
268 notes: true,
269 fields: [
270 { key: "strikeFracX", label: "Position x (fraction of width)", step: 0.05, min: 0, max: 1 },
271 { key: "strikeFracY", label: "Position y (fraction of height)", step: 0.05, min: 0, max: 1 },
272 { key: "strikeVelocity", label: "Stick speed", unit: "m/s", step: 0.5, min: 0.01 },
273 { key: "stickMass", label: "Stick mass", unit: "g", scale: 1e-3, step: 5, min: 1 },
274 { key: "contactStiffness", label: "Contact stiffness K", unit: "N/m^a", step: 1e8, min: 1e5 },
275 { key: "contactExponent", label: "Contact exponent a", step: 0.1, min: 1, max: 3 },
276 { key: "contactRadius", label: "Tip radius", unit: "mm", scale: 1e-3, step: 1, min: 0.5 },
277 ],
278 },
279 {
280 title: "Listener",
281 fields: [
282 { key: "listenerDist", label: "Distance", unit: "m", step: 0.1, min: 0.05, live: true },
283 { key: "listenerAngle", label: "Angle from the normal", unit: "deg", step: 5, min: 0, max: 90, live: true },
284 { key: "listenerAzimuth", label: "Azimuth", unit: "deg", step: 15, min: -180, max: 180, live: true },
285 ],
286 },
287 {
288 title: "Grid and numerics",
289 notes: true,
290 fields: [
291 { key: "spacing", label: "Grid spacing", unit: "mm", scale: 1e-3, step: 1, min: 2 },
292 { key: "modeMaxFreq", label: "Modes up to", unit: "Hz", step: 1000, min: 200 },
293 { key: "padLiftoff", label: "Pads lift off (full model)", kind: "checkbox" },
294 { key: "fs", label: "Sample rate", kind: "select", options: [{ value: 44100, label: "44.1 kHz" }, { value: 48000, label: "48 kHz" }, { value: 96000, label: "96 kHz" }] },
295 { key: "fps", label: "Movie frame rate", kind: "select", options: [{ value: 60, label: "60" }, { value: 120, label: "120" }, { value: 240, label: "240" }] },
296 ],
297 },
298 ],
299 defaultParams,
300 (key, _value, live) => this.onParam(key, live),
301 );
302 }
304 private onParam(key: keyof SimParams, live: boolean): void {
305 const p = this.form.get();
306 if (key === "spacing" || key === "modeMaxFreq" || key === "fs") {
307 if (this.design) this.rebuildPlate(this.design);
308 return;
309 }
310 if (key === "fps") { this.updateNotes(); return; }
311 if (key === "padLiftoff") { this.updateNotes(); return; }
312 if (live && this.sim) this.sim.setListener(p);
313 if (key.startsWith("strike") || key.startsWith("stick") || key.startsWith("contact") || key.startsWith("listener")) {
314 this.updateMarkers();
315 this.updateNotes();
316 if (this.runMode === "linear" && this.synthesized) this.scheduleSynth();
317 }
318 this.tutorial?.refresh();
319 }
321 private buildViewToolbar(): void {
322 const t = $("viewToolbar");
323 const modeSel = document.createElement("select");
324 modeSel.innerHTML = `<option value="3d">3D</option><option value="2d">2D</option>`;
325 modeSel.addEventListener("change", () => { this.viewOpts.mode = modeSel.value as ViewMode; this.renderer.setOptions(this.viewOpts); });
326 const colorSel = document.createElement("select");
327 colorSel.innerHTML = `<option value="height">Height</option><option value="thickness">Thickness</option>`;
328 colorSel.addEventListener("change", () => { this.viewOpts.color = colorSel.value as ColorMode; this.renderer.setOptions(this.viewOpts); });
329 this.colorSel = colorSel;
330 const exag = document.createElement("input");
331 exag.type = "number"; exag.min = "1"; exag.step = "5"; exag.value = String(this.viewOpts.exaggeration); exag.style.width = "60px";
332 exag.addEventListener("change", () => { this.viewOpts.exaggeration = Math.max(0.1, Number(exag.value) || 1); this.renderer.setOptions(this.viewOpts); });
333 const range = document.createElement("input");
334 range.type = "number"; range.min = "0"; range.step = "0.1"; range.value = "0"; range.style.width = "60px";
335 range.addEventListener("change", () => { this.viewOpts.range = Math.max(0, Number(range.value) || 0) * 1e-3; this.renderer.setOptions(this.viewOpts); });
336 const prof = document.createElement("input");
337 prof.type = "checkbox"; prof.checked = this.viewOpts.showProfile;
338 prof.addEventListener("change", () => { this.viewOpts.showProfile = prof.checked; this.renderer.setOptions(this.viewOpts); });
339 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
340 t.append(lab("View", modeSel), lab("Color", colorSel), lab("Exaggeration", exag), lab("Range (mm, 0 = auto)", range), lab("Show profile", prof));
341 if (!this.device) {
342 modeSel.value = "2d"; modeSel.disabled = true;
343 const w = document.createElement("span"); w.id = "nogpu"; w.textContent = "WebGPU is not available: the 2D view and the linear model only.";
344 t.append(w);
345 }
346 }
348 private buildMovieToolbar(): void {
349 const t = $("movieToolbar");
350 this.playBtn = this.button("Play", () => this.togglePlay());
351 this.liveBtn = this.button("Live", () => this.setView("live"));
352 this.designBtn = this.button("Design", () => this.setView("design"));
353 this.scrub = document.createElement("input");
354 this.scrub.type = "range"; this.scrub.className = "scrub"; this.scrub.min = "0"; this.scrub.max = "0"; this.scrub.value = "0";
355 this.scrub.addEventListener("input", () => { this.frameIndex = Number(this.scrub.value); this.setView("movie"); this.showFrame(); });
356 this.timeLabel = document.createElement("span");
357 this.timeLabel.textContent = "0.000 s";
358 const levelSel = document.createElement("select");
359 levelSel.innerHTML = `<option value="absolute">Absolute level</option><option value="loudness">Normalize loudness</option><option value="peak">Normalize peak</option>`;
360 levelSel.addEventListener("change", () => { this.levelMode = levelSel.value as LevelMode; this.updatePeak(); });
361 const gain = document.createElement("input");
362 gain.type = "range"; gain.min = "-60"; gain.max = "40"; gain.step = "1"; gain.value = String(this.gainDb);
363 const gainLabel = document.createElement("span"); gainLabel.textContent = `${this.gainDb} dB`;
364 gain.addEventListener("input", () => { this.gainDb = Number(gain.value); gainLabel.textContent = `${this.gainDb} dB`; this.updatePeak(); });
365 this.peakLabel = document.createElement("span");
366 this.downloadBtn = this.button("Download .wav", () => this.download());
367 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
368 t.append(this.playBtn, this.liveBtn, this.designBtn, this.scrub, this.timeLabel, levelSel, lab("Gain", gain, gainLabel), this.peakLabel, this.downloadBtn);
369 // The loudness warning, shown in place of playing when the signal peaks near full scale.
370 this.loudWarn = document.createElement("div");
371 this.loudWarn.className = "loud-warn";
372 this.loudWarn.hidden = true;
373 this.loudWarnText = document.createElement("span");
374 this.loudPlayBtn = this.button("Play anyway", () => { const go = this.loudGo; this.hideLoudWarning(); go?.(); });
375 const cancel = this.button("Cancel", () => this.hideLoudWarning());
376 this.loudWarn.append(this.loudWarnText, this.loudPlayBtn, cancel);
377 t.append(this.loudWarn);
378 }
380 /** Shows the loudness warning; `go` starts the playback if the user accepts. */
381 private showLoudWarning(peakDb: number, go: () => void): void {
382 this.loudGo = go;
383 this.loudWarnText.textContent = `This recording peaks at ${peakDb.toFixed(1)} dBFS, loud enough to hurt in headphones. Turn your volume down before playing.`;
384 this.loudWarn.hidden = false;
385 this.loudPlayBtn.focus();
386 }
388 private hideLoudWarning(): void {
389 this.loudWarn.hidden = true;
390 this.loudGo = null;
391 }
393 private buildSpecToolbar(): void {
394 const t = $("specToolbar");
395 const sel = (opts: [string, string][], value: string, onChange: (v: string) => void) => {
396 const s = document.createElement("select");
397 for (const [v, l] of opts) { const o = document.createElement("option"); o.value = v; o.textContent = l; s.append(o); }
398 s.value = value;
399 s.addEventListener("change", () => onChange(s.value));
400 return s;
401 };
402 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
403 const win = sel([["512", "512"], ["1024", "1024"], ["2048", "2048"], ["4096", "4096"]], "2048", (v) => { this.specOpts.window = Number(v); this.spec.setOptions({ window: Number(v), hop: Number(v) / 8 }); this.tutorial?.refresh(); });
404 const maxHz = sel([["4000", "4 kHz"], ["8000", "8 kHz"], ["12000", "12 kHz"], ["16000", "16 kHz"], ["20000", "20 kHz"]], "12000", (v) => this.spec.setOptions({ maxHz: Number(v) }));
405 const db = sel([["60", "60 dB"], ["80", "80 dB"], ["100", "100 dB"]], "80", (v) => this.spec.setOptions({ dbRange: Number(v) }));
406 const log = document.createElement("input"); log.type = "checkbox";
407 log.addEventListener("change", () => { this.specOpts.logFreq = log.checked; this.spec.setOptions({ logFreq: log.checked }); this.tutorial?.refresh(); });
408 this.specWinSel = win; this.specLogChk = log;
409 const ticks = document.createElement("input"); ticks.type = "checkbox"; ticks.checked = this.showTicks;
410 ticks.addEventListener("change", () => { this.showTicks = ticks.checked; this.updateTicks(); });
411 t.append(lab("Spectrogram window", win), lab("Max", maxHz), lab("Range", db), lab("Log frequency", log), lab("Modal frequencies", ticks));
412 }
414 private buildSplitter(): void {
415 const sp = $("splitter"), sb = $("sidebar");
416 const saved = localStorage.getItem("cymbalsim.sidebar");
417 if (saved) sb.style.width = saved;
418 let dragging = false;
419 sp.addEventListener("mousedown", (e) => { dragging = true; e.preventDefault(); });
420 window.addEventListener("mousemove", (e) => {
421 if (!dragging) return;
422 const w = Math.max(280, Math.min(window.innerWidth - 300, e.clientX));
423 sb.style.width = `${w}px`;
424 this.renderer.resize(); this.spec.resize();
425 });
426 window.addEventListener("mouseup", () => { if (dragging) { dragging = false; localStorage.setItem("cymbalsim.sidebar", sb.style.width); } });
427 sp.addEventListener("dblclick", () => { sb.style.width = ""; localStorage.removeItem("cymbalsim.sidebar"); this.renderer.resize(); this.spec.resize(); });
428 }
430 // ---------- Design ----------
432 private onSource(source: string): void {
433 if (this.running) return;
434 let d: Design;
435 try {
436 d = compileDesign(source);
437 } catch (e) {
438 this.editor.setStatus(e instanceof Error ? e.message : String(e), "error");
439 return;
440 }
441 this.editor.setStatus(`Compiled: ${d.name}`, "ok");
442 this.rebuildPlate(d);
443 }
445 private rebuildPlate(d: Design): void {
446 const p = this.form.get();
447 let plate: Plate;
448 try {
449 plate = evaluatePlate(d, p.spacing);
450 } catch (e) {
451 this.editor.setStatus(e instanceof DesignError ? e.message : String(e), "error");
452 return;
453 }
454 this.design = d;
455 this.plate = plate;
456 this.plateSpacing = p.spacing;
457 this.designGeneration++;
458 this.modes = null; this.model = null; this.sys = null;
459 this.synthesized = false;
460 this.lastContact = null;
461 this.rec = null;
462 this.spec.reset();
463 this.spec.setOptions({ fs: p.fs });
464 this.renderer.setPlate(plate);
465 this.setView("design");
466 this.updateMarkers();
467 this.updateDesignInfo();
468 this.updateNotes();
469 this.updateButtons();
470 if (this.runMode === "linear") this.useCachedModes();
471 else this.modeBrowser.clear("Switch to the linear model to compute the modes.");
472 this.tutorial?.refresh();
473 }
475 /** The cache key of the modes of the current design and numerics. */
476 private modesKey(): string | null {
477 if (!this.design || !this.plate) return null;
478 const p = this.form.get();
479 return `${this.plateSpacing}|${Math.min(p.modeMaxFreq, p.fs / 2)}|${this.design.source}`;
480 }
482 /** Installs cached modes for the current design if there are any; otherwise leaves the browser empty. */
483 private useCachedModes(): void {
484 const key = this.modesKey();
485 const hit = key ? this.modesCache.get(key) : undefined;
486 if (hit && this.plate) {
487 this.installModes(hit.sys, hit.modes, hit.model, null);
488 if (this.pool) void this.pool.setModel(hit.model);
489 } else this.modeBrowser.clear("Press Synthesize to compute the modes of this design.");
490 }
492 /** Shows a mode set in the browser, the notes and the spectrogram ticks. */
493 private installModes(sys: LinearSystem, modes: ModeSet, model: ModalModel, secs: number | null): void {
494 const pl = this.plate!;
495 const p = this.form.get();
496 const fMax = Math.min(p.modeMaxFreq, p.fs / 2);
497 this.sys = sys; this.modes = modes; this.model = model;
498 const rows = Array.from(modes.freqs).map((f, m) => ({ freq: f, t60: LN1000 / Math.min(decayRate(pl.loss, f) + model.padSigma[m], 0.99 * 2 * Math.PI * f) }));
499 const kind = sys.fields === 1 ? "bending modes" : "modes (bending coupled to stretching)";
500 const when = secs === null ? "cached" : `in ${secs.toFixed(1)} s`;
501 this.modeBrowser.setModes(rows, `${modes.count} ${kind} up to ${(fMax / 1e3).toFixed(1)} kHz, ${when} (${sys.n} unknowns${modes.missing ? `, ${modes.missing} missing` : ""}). Click a mode to see its shape.`);
502 this.updateNotes();
503 this.updateTicks();
504 this.updateButtons();
505 this.tutorial?.refresh();
506 }
508 private updateDesignInfo(): void {
509 const pl = this.plate;
510 if (!pl) return;
511 const p = this.form.get();
512 const g = pl.grid;
513 const { mass } = massProperties(pl);
514 const hr = thicknessRange(pl);
515 const ps = profileStats(pl);
516 const sr = standRates(pl);
517 const lines: string[] = [];
518 lines.push(`${pl.name}: ${(pl.Lx * 1e3).toFixed(0)} x ${(pl.Ly * 1e3).toFixed(0)} mm, E = ${(pl.mat.E / 1e9).toFixed(0)} GPa, nu = ${pl.mat.nu}, rho = ${pl.mat.rho} kg/m^3`);
519 lines.push(`Thickness ${(hr.min * 1e3).toFixed(2)} to ${(hr.max * 1e3).toFixed(2)} mm, mass ${(mass * 1e3).toFixed(0)} g, grid ${g.nx} x ${g.ny} at ${(g.hx * 1e3).toFixed(2)} mm (${countInside(g)} nodes)`);
520 if (ps.peakToPeak > 0) {
521 const warn = ps.maxSlope > 0.1 ? ` <span class="warn">(above the shallow-shell range of about 0.1)</span>` : "";
522 lines.push(`Profile ${(ps.peakToPeak * 1e3).toFixed(1)} mm peak to peak, largest slope ${ps.maxSlope.toFixed(3)}${warn}`);
523 } else lines.push("Flat plate (no profile): the linear model is bending only");
524 if (pl.stand && sr) {
525 const pad = pl.stand.pad;
526 lines.push(`Stand: ${pl.stand.topPad ? "two pads" : "bottom pad only"}, ${(pad.innerRadius * 1e3).toFixed(0)} to ${(pad.outerRadius * 1e3).toFixed(0)} mm, ${(pad.thickness * 1e3).toFixed(0)} mm felt at ${(pad.E / 1e6).toFixed(2)} MPa; ${(sr.totalKw / 1e3).toFixed(0)} kN/m, bounce ${sr.bounceHz.toFixed(0)} Hz, ${sr.nodes.length} pad nodes, preload ${(sr.preloadTop * 1e3).toFixed(2)} / ${(sr.preloadBottom * 1e3).toFixed(2)} mm`);
527 } else lines.push("Free plate (no stand)");
528 lines.push(`Decay T60: ${t60At(pl.loss, 100).toFixed(2)} s at 100 Hz, ${t60At(pl.loss, 1000).toFixed(2)} s at 1 kHz, ${t60At(pl.loss, 5000).toFixed(2)} s at 5 kHz`);
529 void p;
530 $("designInfo").innerHTML = lines.join("\n");
531 }
533 private updateNotes(): void {
534 const pl = this.plate;
535 if (!pl) return;
536 const p = this.form.get();
537 const g = pl.grid;
538 const hm = meanThickness(pl);
539 const f3 = dispersionFrequency(pl.mat, hm, g.hx, 0.03), f10 = dispersionFrequency(pl.mat, hm, g.hx, 0.1);
540 const wmax = maxAngularFrequency(g, pl.mat, thicknessRange(pl).max);
541 const dtMax = (CFL * 2) / wmax;
542 const sps = Math.ceil(1 / (p.fs * dtMax));
543 const dt = 1 / (p.fs * sps);
544 const fit = fitSigma(pl.loss, pl.mat, hm);
545 const t60f = (f: number) => (LN1000 / fittedRate(fit, f)).toFixed(2);
546 const lines = [
547 `Grid ${g.nx} x ${g.ny}, ${countInside(g)} plate nodes. Grid dispersion lowers the bending partials by 3% near ${(f3 / 1e3).toFixed(1)} kHz and by 10% near ${(f10 / 1e3).toFixed(1)} kHz (at the mean thickness).`,
548 `Linear model: modes up to ${(p.modeMaxFreq / 1e3).toFixed(1)} kHz${this.modes ? `, ${this.modes.count} found in ${this.modes.seconds.toFixed(1)} s` : ""}${this.modes && this.modes.missing ? ` <span class="warn">(${this.modes.missing} missing)</span>` : ""}.`,
549 `Full model: time step ${(dt * 1e6).toFixed(2)} us (${sps} per sample, in-plane wave speed ${inPlaneSpeed(pl.mat).toFixed(0)} m/s), ${((p.duration * p.fs * sps) / 1e6).toFixed(1)} million steps for ${p.duration} s. Losses fitted as sigma0 = ${fit.sigma0.toFixed(2)} 1/s, sigma1 = ${fit.sigma1.toExponential(2)} m^2/s: T60 ${t60f(100)} / ${t60f(1000)} / ${t60f(5000)} s at 100 Hz / 1 kHz / 5 kHz (requested ${t60At(pl.loss, 100).toFixed(2)} / ${t60At(pl.loss, 1000).toFixed(2)} / ${t60At(pl.loss, 5000).toFixed(2)}).`,
550 ];
551 this.form.setNotes("Grid and numerics", lines.join("\n"));
552 const patch = strikePatch(pl, p);
553 const sp = strikePoint(pl, p);
554 const sl = [`Strike at (${(sp.x * 1e3).toFixed(0)}, ${(sp.y * 1e3).toFixed(0)}) mm on ${patch.nodes.length} node${patch.nodes.length === 1 ? "" : "s"} (${(patch.mass * 1e3).toFixed(2)} g).`];
555 if (this.lastContact) sl.push(`Last linear strike: peak force ${this.lastContact.peakForce.toFixed(0)} N, contact ${(this.lastContact.contactTime * 1e3).toFixed(2)} ms.`);
556 if (this.sim) { const st = this.sim.status().stick; sl.push(`Full simulation: peak force ${st.maxForce.toFixed(0)} N${st.withdrawn ? ", stick withdrawn" : ""}.`); }
557 this.form.setNotes("Strike", sl.join("\n"));
558 }
560 private updateMarkers(): void {
561 const pl = this.plate;
562 if (!pl) return;
563 const p = this.form.get();
564 const sp = strikePoint(pl, p);
565 const L = listenerPosition(p);
566 this.renderer.setMarkers({
567 strike: { x: sp.x, y: sp.y, radius: p.contactRadius },
568 stand: pl.stand ? { x: pl.stand.x, y: pl.stand.y, innerRadius: pl.stand.pad.innerRadius, outerRadius: pl.stand.pad.outerRadius } : null,
569 listener: L,
570 });
571 }
573 // ---------- Linear model ----------
575 /** Computes the modes of the current design unless they are cached; resolves when they are installed (or with an error). */
576 private computeModes(): Promise<void> {
577 const pl = this.plate, gen = this.designGeneration, key = this.modesKey();
578 if (!pl || !key) return Promise.resolve();
579 const hit = this.modesCache.get(key);
580 if (hit) {
581 if (this.model !== hit.model) { this.installModes(hit.sys, hit.modes, hit.model, null); if (this.pool) return this.pool.setModel(hit.model); }
582 return Promise.resolve();
583 }
584 const p = this.form.get();
585 const fMax = Math.min(p.modeMaxFreq, p.fs / 2);
586 this.modeBrowser.clear("Computing the modes...");
587 this.setProgress(0, "Computing the modes...");
588 this.updateButtons();
589 this.modesBusy = this.modesBusy.then(async () => {
590 if (gen !== this.designGeneration) return;
591 const t0 = performance.now();
592 let sys: LinearSystem;
593 try {
594 sys = assemble(pl);
595 } catch (e) {
596 this.setProgress(null, `Assembly failed: ${e instanceof Error ? e.message : String(e)}`);
597 throw e;
598 }
599 let modes: ModeSet;
600 try {
601 if (this.pool) modes = await this.pool.modes(sys, fMax, (d, t) => { if (gen === this.designGeneration) this.setProgress(t ? d / t : 0, `Computing the modes: slice ${d} of ${t}`); });
602 else {
603 const { computeModes, localRunner } = await import("./modal/modes.ts");
604 modes = await computeModes(sys, fMax, localRunner(sys));
605 }
606 } catch (e) {
607 this.setProgress(null, `Mode computation failed: ${e instanceof Error ? e.message : String(e)}`);
608 throw e;
609 }
610 const model = modalModel(pl, sys, modes);
611 this.modesCache.set(key, { sys, modes, model });
612 while (this.modesCache.size > 4) this.modesCache.delete(this.modesCache.keys().next().value!);
613 if (gen !== this.designGeneration) { this.setProgress(null); return; }
614 if (this.pool) await this.pool.setModel(model);
615 this.setProgress(null, "");
616 this.installModes(sys, modes, model, (performance.now() - t0) / 1000);
617 });
618 return this.modesBusy;
619 }
621 private showMode(m: number | null): void {
622 if (m === null) { this.setView(this.rec ? "movie" : "design"); return; }
623 if (!this.model) return;
624 this.view = "mode";
625 const shape = modeShapeOnGrid(this.model, m);
626 // Scale the mass-normalized shape to a visible amplitude: 1 mm peak.
627 let peak = 0;
628 for (const v of shape) peak = Math.max(peak, Math.abs(v));
629 const w = new Float32Array(shape.length);
630 for (let k = 0; k < w.length; k++) w[k] = (shape[k] / (peak || 1)) * 1e-3;
631 this.renderer.setField(w);
632 this.overlay.textContent = `Mode ${m + 1}: ${this.model.freqs[m].toFixed(1)} Hz (shape scaled to 1 mm)`;
633 }
635 private scheduleSynth(): void {
636 if (this.synthTimer !== null) clearTimeout(this.synthTimer);
637 this.synthTimer = window.setTimeout(() => { this.synthTimer = null; void this.runLinear(); }, 250);
638 }
640 /** Makes sure the modes of the current design are computed and installed in the pool. */
641 async ensureModes(): Promise<void> {
642 if (!this.plate) return;
643 if (!this.model || this.modesKey() !== this.currentModesKey) {
644 await this.computeModes();
645 this.currentModesKey = this.modesKey();
646 }
647 }
649 /** Synthesizes the strike with the current parameters (linear model). */
650 async runLinear(): Promise<void> {
651 if (!this.plate) return;
652 if (this.synthBusy) { this.synthPending = true; return; }
653 try {
654 await this.ensureModes();
655 } catch {
656 return;
657 }
658 const pl = this.plate, model = this.model;
659 if (!pl || !model) return;
660 this.synthBusy = true;
661 const p = this.form.get();
662 const gen = this.designGeneration;
663 const t0 = performance.now();
664 this.runStatus.textContent = "Synthesizing...";
665 try {
666 let audio: Float32Array, frames: Float32Array, nFrames: number, contact: ContactResult;
667 if (this.pool) {
668 const r = await this.pool.synthesize(model, pl, pl.loss, p, (a, c) => {
669 if (gen !== this.designGeneration) return;
670 this.installRecording(a, [], p, "linear");
671 this.lastContact = c;
672 this.runStatus.textContent = `Audio ready in ${((performance.now() - t0) / 1000).toFixed(2)} s; movie frames...`;
673 });
674 audio = r.audio; frames = r.frames; nFrames = r.nFrames; contact = r.contact;
675 } else {
676 const { synthesize } = await import("./modal/synth.ts");
677 const r = synthesize(model, pl, pl.loss, p, true);
678 audio = r.audio; frames = r.frames; nFrames = r.nFrames; contact = r.contact;
679 }
680 if (gen !== this.designGeneration) return;
681 const n = pl.grid.n;
682 const frameList: Float32Array[] = [];
683 for (let f = 0; f < nFrames; f++) frameList.push(frames.subarray(f * n, (f + 1) * n));
684 this.installRecording(audio, frameList, p, "linear");
685 this.lastContact = contact;
686 this.synthesized = true;
687 const secs = (performance.now() - t0) / 1000;
688 this.runStatus.textContent = `Linear model: ${model.count} modes, ${p.duration} s synthesized in ${secs.toFixed(2)} s. Peak ${peakSpl(audio).toFixed(0)} dB SPL, contact ${(contact.contactTime * 1e3).toFixed(2)} ms, peak force ${contact.peakForce.toFixed(0)} N.`;
689 this.updateNotes();
690 } catch (e) {
691 this.runStatus.textContent = `Synthesis failed: ${e instanceof Error ? e.message : String(e)}`;
692 } finally {
693 this.synthBusy = false;
694 this.tutorial?.refresh();
695 if (this.synthPending) { this.synthPending = false; void this.runLinear(); }
696 }
697 }
699 // ---------- Full simulation ----------
701 async runFull(): Promise<void> {
702 const pl = this.plate;
703 if (!pl || !this.device || this.running) return;
704 const p = this.form.get();
705 this.sim?.destroy();
706 const hm = meanThickness(pl);
707 const fit = fitSigma(pl.loss, pl.mat, hm);
708 const loss: FullLoss = fullLoss(fit, standRates(pl), decayRate(pl.loss, 5000));
709 this.sim = new Simulation(this.device, pl, p, loss);
710 this.rec = { audio: new Float32Array(0), samples: 0, fs: p.fs, frames: [new Float32Array(pl.grid.n)], fps: p.fps, source: "full" };
711 this.spec.reset();
712 this.spec.setOptions({ fs: p.fs });
713 this.spec.setDuration(p.duration);
714 this.running = true;
715 this.paused = false;
716 this.setLocked(true);
717 this.setView("live");
718 this.updateButtons();
719 await this.fullLoop();
720 }
722 private async fullLoop(): Promise<void> {
723 const sim = this.sim;
724 if (!sim) return;
725 const t0 = performance.now();
726 let lastUi = 0;
727 while (this.running && sim.phase === "recording") {
728 if (this.paused) { await new Promise((r) => setTimeout(r, 50)); continue; }
729 await sim.runBatch();
730 if (!this.rec || this.sim !== sim) break;
731 // New audio and frames.
732 const rec = this.rec;
733 const newSamples = sim.samples - rec.samples;
734 if (newSamples > 0) {
735 const chunk = sim.audio.subarray(rec.samples, sim.samples);
736 this.spec.append(chunk);
737 rec.audio = sim.audio; rec.samples = sim.samples;
738 }
739 rec.frames = sim.frames;
740 if (this.view === "live") this.renderer.setField(sim.frames[sim.frames.length - 1]);
741 const now = performance.now();
742 if (now - lastUi > 100) {
743 lastUi = now;
744 const st = sim.status();
745 const elapsed = (now - t0) / 1000;
746 this.runStatus.textContent = `Full model: t = ${st.t.toFixed(3)} s, ${(st.totalSteps / elapsed / 1000).toFixed(0)}k steps/s (${(elapsed / Math.max(st.t, 1e-3)).toFixed(0)} s per second of sound), peak ${peakSpl(sim.recordedAudio()).toFixed(0)} dB SPL, stick force ${st.stick.force.toFixed(0)} N${st.delayClamped ? ", delay spread clamped" : ""}`;
747 this.scrub.max = String(Math.max(0, rec.frames.length - 1));
748 this.updatePeak();
749 }
750 }
751 if (this.sim === sim) {
752 this.running = false;
753 this.setLocked(false);
754 const st = sim.status();
755 this.runStatus.textContent = `Full model: ${st.t.toFixed(2)} s recorded, peak ${peakSpl(sim.recordedAudio()).toFixed(0)} dB SPL, peak force ${st.stick.maxForce.toFixed(0)} N, largest displacement ${(st.wmax * 1e3).toFixed(2)} mm.`;
756 if (this.rec) { this.rec.audio = sim.recordedAudio(); this.rec.samples = sim.samples; this.rec.frames = sim.frames; }
757 this.updateNotes();
758 this.updateButtons();
759 this.updatePeak();
760 this.tutorial?.refresh();
761 }
762 }
764 // ---------- Run control ----------
766 private setRunMode(mode: RunMode): void {
767 if (mode === "full" && !this.device) mode = "linear";
768 this.runMode = mode;
769 this.runModeSel.value = mode;
770 if (mode === "linear" && this.plate && !this.modes) this.useCachedModes();
771 if (mode === "full") this.modeBrowser.clear("Switch to the linear model to compute the modes.");
772 this.updateButtons();
773 this.tutorial?.refresh();
774 }
776 private start(): void {
777 if (this.runMode === "linear") void this.runLinear();
778 else void this.runFull();
779 }
780 private pause(): void {
781 if (!this.running) return;
782 this.paused = !this.paused;
783 this.pauseBtn.textContent = this.paused ? "Resume" : "Pause";
784 }
785 private stopRun(): void {
786 if (this.sim && this.running) { this.sim.stop(); this.running = false; }
787 this.paused = false;
788 this.pauseBtn.textContent = "Pause";
789 this.setLocked(false);
790 this.updateButtons();
791 }
792 private continueRun(): void {
793 const sim = this.sim;
794 if (!sim || this.running || !sim.canContinue()) return;
795 sim.setDuration(this.form.get().duration);
796 this.running = true;
797 this.setLocked(true);
798 this.setView("live");
799 this.updateButtons();
800 void this.fullLoop();
801 }
803 private setLocked(locked: boolean): void {
804 this.editor.setLocked(locked);
805 this.form.setLocked(locked);
806 this.runModeSel.disabled = locked;
807 }
809 private updateButtons(): void {
810 const linear = this.runMode === "linear";
811 const canLinear = linear && !!this.plate && !this.synthBusy;
812 const canFull = !linear && !!this.plate && !!this.device && !this.running;
813 this.startBtn.disabled = !(canLinear || canFull);
814 this.startBtn.textContent = linear ? "Synthesize" : "Start";
815 this.pauseBtn.disabled = linear || !this.running;
816 this.stopBtn.disabled = linear || !this.running;
817 this.continueBtn.disabled = linear || this.running || !this.sim || !this.sim.canContinue() || this.sim.samples >= Math.round(this.form.get().duration * this.form.get().fs);
818 this.pauseBtn.hidden = linear; this.stopBtn.hidden = linear; this.continueBtn.hidden = linear;
819 this.liveBtn.hidden = linear;
820 }
822 // ---------- Recording, view, playback ----------
824 private installRecording(audio: Float32Array, frames: Float32Array[], p: SimParams, source: RunMode): void {
825 this.rec = { audio, samples: audio.length, fs: p.fs, frames, fps: p.fps, source };
826 this.spec.setOptions({ fs: p.fs });
827 this.spec.setDuration(p.duration);
828 this.spec.setSignal(audio);
829 this.scrub.max = String(Math.max(0, frames.length - 1));
830 if (frames.length > 0) {
831 this.frameIndex = 0;
832 if (this.view !== "mode") { this.setView("movie"); this.showFrame(); }
833 }
834 this.updatePeak();
835 this.updateButtons();
836 }
838 private setView(v: ViewState): void {
839 this.view = v;
840 if (v === "design") { this.renderer.setField(null); this.overlay.textContent = this.plate ? "Stress-free shape" : ""; }
841 else if (v === "live") { this.overlay.textContent = "Live"; if (this.sim) this.renderer.setField(this.sim.frames[this.sim.frames.length - 1]); }
842 else if (v === "movie") this.showFrame();
843 }
845 private showFrame(): void {
846 const rec = this.rec;
847 if (!rec || rec.frames.length === 0) return;
848 const f = Math.max(0, Math.min(rec.frames.length - 1, this.frameIndex));
849 this.frameIndex = f;
850 this.scrub.value = String(f);
851 this.timeLabel.textContent = `${(f / rec.fps).toFixed(3)} s`;
852 this.renderer.setField(rec.frames[f]);
853 this.overlay.textContent = `${rec.source === "linear" ? "Linear" : "Full"} model, t = ${(f / rec.fps).toFixed(3)} s`;
854 }
856 private playable(): Float32Array | null {
857 const rec = this.rec;
858 if (!rec || rec.samples === 0) return null;
859 const sig = rec.audio.subarray(0, rec.samples);
860 return applyLevel(sig, levelGain(sig, rec.fs, this.levelMode, this.gainDb));
861 }
863 private updatePeak(): void {
864 this.hideLoudWarning();
865 const s = this.playable();
866 if (!s) { this.peakLabel.textContent = ""; this.downloadBtn.disabled = true; this.playBtn.disabled = true; return; }
867 const db = peakDbfs(s);
868 this.peakLabel.textContent = `Peak ${db.toFixed(1)} dBFS${db > -0.5 ? " (clipping)" : ""}`;
869 this.peakLabel.className = db > -0.5 ? "badge warn" : "badge";
870 this.downloadBtn.disabled = false;
871 this.playBtn.disabled = false;
872 }
874 private togglePlay(): void {
875 if (this.player.playing) { this.player.stop(); this.playBtn.textContent = "Play"; this.spec.setCursor(null); return; }
876 const s = this.playable(), rec = this.rec;
877 if (!s || !rec) return;
878 // A signal that peaks near full scale can hurt in headphones: warn before the first
879 // playback at such a level, and again whenever the level is well above the one accepted.
880 const peak = peakDbfs(s);
881 if (peak >= LOUD_DBFS && peak > this.acceptedPeakDb + LOUD_STEP_DB) {
882 this.showLoudWarning(peak, () => { this.acceptedPeakDb = peak; this.startPlayback(s, rec); });
883 return;
884 }
885 this.hideLoudWarning();
886 this.startPlayback(s, rec);
887 }
889 private startPlayback(s: Float32Array, rec: Recording): void {
890 // Play from the scrubbed position only when the user has scrubbed to one; from the live
891 // view, or from the end of the recording, start over.
892 const atEnd = rec.frames.length > 1 && this.frameIndex >= rec.frames.length - 1;
893 const start = this.view === "movie" && rec.frames.length > 1 && !atEnd ? this.frameIndex / rec.fps : 0;
894 this.playBtn.textContent = "Stop";
895 const prevView = this.view;
896 this.player.play(s, rec.fs, start, () => { this.playBtn.textContent = "Play"; this.spec.setCursor(null); if (prevView === "live") this.setView("live"); });
897 const tick = () => {
898 if (!this.player.playing) return;
899 const t = this.player.position();
900 this.spec.setCursor(t);
901 if (rec.frames.length > 1) { this.frameIndex = Math.round(t * rec.fps); this.view = "movie"; this.showFrame(); }
902 requestAnimationFrame(tick);
903 };
904 requestAnimationFrame(tick);
905 }
907 private download(): void {
908 const s = this.playable(), rec = this.rec;
909 if (!s || !rec) return;
910 const blob = encodeWav(s, rec.fs);
911 const a = document.createElement("a");
912 a.href = URL.createObjectURL(blob);
913 a.download = `${(this.plate?.name ?? "cymbalsim").replace(/[^a-z0-9]+/gi, "-").toLowerCase()}-${rec.source}.wav`;
914 a.click();
915 setTimeout(() => URL.revokeObjectURL(a.href), 1000);
916 }
918 private updateTicks(): void {
919 this.spec.setTicks(this.showTicks && this.modes ? Array.from(this.modes.freqs) : null);
920 }
922 // ---------- Tutorial ----------
924 /** The state the tutorial's pages read. */
925 private tutorialContext(): TutorialContext {
926 const rec = this.rec;
927 const st = this.sim ? this.sim.status() : null;
928 return {
929 plate: this.plate,
930 design: this.design,
931 params: this.form.get(),
932 spacing: this.plateSpacing,
933 sys: this.sys,
934 modes: this.modes,
935 model: this.model,
936 lastContact: this.lastContact,
937 recording: rec && rec.samples > 0 ? { source: rec.source, seconds: rec.samples / rec.fs } : null,
938 full: st && st.totalSteps > 0 ? { peakForce: st.stick.maxForce, wmax: st.wmax, t: st.t, done: st.phase === "done" } : null,
939 gpu: this.device !== null,
940 runMode: this.runMode,
941 spectrogram: { ...this.specOpts },
942 memo: this.tutorialMemo,
943 };
944 }
946 /** The actions the tutorial's pages can take. */
947 private tutorialHost(): TutorialHost {
948 return {
949 ctx: () => this.tutorialContext(),
950 loadPreset: async (id) => { this.editor.selectPreset(id); },
951 loadScript: async (src) => { this.editor.setSource(src); this.onSource(src); },
952 setParam: (key, value) => {
953 if (key === "duration") {
954 this.durationInput.value = String(value);
955 this.durationInput.dispatchEvent(new Event("change"));
956 return;
957 }
958 this.form.set(key, value);
959 this.onParam(key, false);
960 },
961 computeModes: () => this.ensureModes(),
962 showMode: (m) => this.modeBrowser.select(m),
963 synthesize: async () => {
964 if (this.runMode !== "linear") this.setRunMode("linear");
965 await this.runLinear();
966 },
967 play: () => { if (!this.player.playing) this.togglePlay(); },
968 setRunMode: (mode) => this.setRunMode(mode),
969 runFull: () => this.runFull(),
970 setSpectrogram: (o) => {
971 if (o.window !== undefined) { this.specOpts.window = o.window; this.specWinSel.value = String(o.window); this.spec.setOptions({ window: o.window, hop: o.window / 8 }); }
972 if (o.logFreq !== undefined) { this.specOpts.logFreq = o.logFreq; this.specLogChk.checked = o.logFreq; this.spec.setOptions({ logFreq: o.logFreq }); }
973 this.tutorial?.refresh();
974 },
975 setViewOptions: (o) => {
976 if (o.color !== undefined) { this.viewOpts.color = o.color; this.colorSel.value = o.color; }
977 if (o.exaggeration !== undefined) this.viewOpts.exaggeration = o.exaggeration;
978 this.renderer.setOptions(this.viewOpts);
979 },
980 };
981 }
983 // ---------- Tests ----------
985 async selfTest(): Promise<string> {
986 if (!this.device) return "no WebGPU";
987 const lines: string[] = [];
988 for (const id of ["flat-rectangle", "bowed-rectangle", "crash-16", "crash-bell-16", "ellipse"]) {
989 const pr = presetById(id)!;
990 const d = compileDesign(pr.source);
991 const pl = evaluatePlate(d, 0.012);
992 const r = await runSelfTest(this.device, pl, this.form.get());
993 lines.push(`${id}: max relative error ${r.maxRel.toExponential(2)} (${r.n} nodes)`);
994 }
995 return lines.join("\n");
996 }
998 private testStatus(): unknown {
999 return {
1000 design: this.design?.name ?? null,
1001 modes: this.modes ? { count: this.modes.count, missing: this.modes.missing, first: Array.from(this.modes.freqs.slice(0, 5)) } : null,
1002 synthesized: this.synthesized,
1003 running: this.running,
1004 samples: this.rec?.samples ?? 0,
1005 frames: this.rec?.frames.length ?? 0,
1006 source: this.rec?.source ?? null,
1007 peakPressure: this.rec ? Array.from(this.rec.audio.subarray(0, this.rec.samples)).reduce((m, v) => Math.max(m, Math.abs(v)), 0) : 0,
1008 sim: this.sim ? this.sim.status() : null,
1009 contact: this.lastContact ? { peakForce: this.lastContact.peakForce, contactTime: this.lastContact.contactTime } : null,
1010 editorStatus: ($("design").querySelector(".editor-status") as HTMLElement | null)?.textContent ?? "",
1011 };
1012 }
1013}
1015const app = new App();
1016app.init().catch((e) => {
1017 console.error(e);
1018 $("viewOverlay").textContent = `Failed to start: ${e instanceof Error ? e.message : String(e)}`;
1019});
1021export { app, PRESETS, isFlat, formatNumber };