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