/ proof-of-concept / cymbalsim
Sign in
proof-of-concept / cymbalsim
cymbalsim / src / main.ts
1033 lines · 47.5 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 strikePoint,
16 strikePatch,
17 listenerPosition,
18 dispersionFrequency,
19 inPlaneSpeed,
20 CFL,
21} from "./params.ts";
22import { fitSigma, fittedRate, LN1000, plateGeometry, estimatedRate, inPlaneRate, rateText } from "./loss.ts";
23import { dampingPlate, computeDamping } from "./modal/damping.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, modalRates, 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, loudness, 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;
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: "fs", label: "Sample rate", kind: "select", options: [{ value: 44100, label: "44.1 kHz" }, { value: 48000, label: "48 kHz" }, { value: 96000, label: "96 kHz" }] },
291 { key: "fps", label: "Movie frame rate", kind: "select", options: [{ value: 60, label: "60" }, { value: 120, label: "120" }, { value: 240, label: "240" }] },
292 ],
293 },
294 ],
295 defaultParams,
296 (key, _value, live) => this.onParam(key, live),
297 );
298 }
300 private onParam(key: keyof SimParams, live: boolean): void {
301 const p = this.form.get();
302 if (key === "spacing" || key === "modeMaxFreq" || key === "fs") {
303 if (this.design) this.rebuildPlate(this.design);
304 return;
305 }
306 if (key === "fps") { this.updateNotes(); return; }
307 if (live && this.sim) this.sim.setListener(p);
308 if (key.startsWith("strike") || key.startsWith("stick") || key.startsWith("contact") || key.startsWith("listener")) {
309 this.updateMarkers();
310 this.updateNotes();
311 if (this.runMode === "linear" && this.synthesized) this.scheduleSynth();
312 }
313 this.tutorial?.refresh();
314 }
316 private buildViewToolbar(): void {
317 const t = $("viewToolbar");
318 const modeSel = document.createElement("select");
319 modeSel.innerHTML = `<option value="3d">3D</option><option value="2d">2D</option>`;
320 modeSel.addEventListener("change", () => { this.viewOpts.mode = modeSel.value as ViewMode; this.renderer.setOptions(this.viewOpts); });
321 const colorSel = document.createElement("select");
322 colorSel.innerHTML = `<option value="height">Height</option><option value="thickness">Thickness</option>`;
323 colorSel.addEventListener("change", () => { this.viewOpts.color = colorSel.value as ColorMode; this.renderer.setOptions(this.viewOpts); });
324 this.colorSel = colorSel;
325 const exag = document.createElement("input");
326 exag.type = "number"; exag.min = "1"; exag.step = "5"; exag.value = String(this.viewOpts.exaggeration); exag.style.width = "60px";
327 exag.addEventListener("change", () => { this.viewOpts.exaggeration = Math.max(0.1, Number(exag.value) || 1); this.renderer.setOptions(this.viewOpts); });
328 const range = document.createElement("input");
329 range.type = "number"; range.min = "0"; range.step = "0.1"; range.value = "0"; range.style.width = "60px";
330 range.addEventListener("change", () => { this.viewOpts.range = Math.max(0, Number(range.value) || 0) * 1e-3; this.renderer.setOptions(this.viewOpts); });
331 const prof = document.createElement("input");
332 prof.type = "checkbox"; prof.checked = this.viewOpts.showProfile;
333 prof.addEventListener("change", () => { this.viewOpts.showProfile = prof.checked; this.renderer.setOptions(this.viewOpts); });
334 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
335 t.append(lab("View", modeSel), lab("Color", colorSel), lab("Exaggeration", exag), lab("Range (mm, 0 = auto)", range), lab("Show profile", prof));
336 if (!this.device) {
337 modeSel.value = "2d"; modeSel.disabled = true;
338 const w = document.createElement("span"); w.id = "nogpu"; w.textContent = "WebGPU is not available: the 2D view and the linear model only.";
339 t.append(w);
340 }
341 }
343 private buildMovieToolbar(): void {
344 const t = $("movieToolbar");
345 this.playBtn = this.button("Play", () => this.togglePlay());
346 this.liveBtn = this.button("Live", () => this.setView("live"));
347 this.designBtn = this.button("Design", () => this.setView("design"));
348 this.scrub = document.createElement("input");
349 this.scrub.type = "range"; this.scrub.className = "scrub"; this.scrub.min = "0"; this.scrub.max = "0"; this.scrub.value = "0";
350 this.scrub.addEventListener("input", () => { this.frameIndex = Number(this.scrub.value); this.setView("movie"); this.showFrame(); });
351 this.timeLabel = document.createElement("span");
352 this.timeLabel.textContent = "0.000 s";
353 const levelSel = document.createElement("select");
354 levelSel.innerHTML = `<option value="absolute">Absolute level</option><option value="loudness">Normalize loudness</option><option value="peak">Normalize peak</option>`;
355 levelSel.addEventListener("change", () => { this.levelMode = levelSel.value as LevelMode; this.resetLoudness(); this.updatePeak(); });
356 const gain = document.createElement("input");
357 gain.type = "range"; gain.min = "-60"; gain.max = "40"; gain.step = "1"; gain.value = String(this.gainDb);
358 const gainLabel = document.createElement("span"); gainLabel.textContent = `${this.gainDb} dB`;
359 gain.addEventListener("input", () => { this.gainDb = Number(gain.value); gainLabel.textContent = `${this.gainDb} dB`; this.resetLoudness(); this.updatePeak(); });
360 this.peakLabel = document.createElement("span");
361 this.downloadBtn = this.button("Download .wav", () => this.download());
362 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
363 t.append(this.playBtn, this.liveBtn, this.designBtn, this.scrub, this.timeLabel, levelSel, lab("Gain", gain, gainLabel), this.peakLabel, this.downloadBtn);
364 // The loudness warning, shown in place of playing when the signal peaks near full scale.
365 this.loudWarn = document.createElement("div");
366 this.loudWarn.className = "loud-warn";
367 this.loudWarn.hidden = true;
368 this.loudWarnText = document.createElement("span");
369 this.loudPlayBtn = this.button("Play anyway", () => { const go = this.loudGo; this.hideLoudWarning(); go?.(); });
370 const cancel = this.button("Cancel", () => this.hideLoudWarning());
371 this.loudWarn.append(this.loudWarnText, this.loudPlayBtn, cancel);
372 t.append(this.loudWarn);
373 }
375 /** Shows the loudness warning; `go` starts the playback if the user accepts. */
376 private showLoudWarning(peakDb: number, shortTermDb: number, go: () => void): void {
377 this.loudGo = go;
378 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.`;
379 this.loudWarn.hidden = false;
380 this.loudPlayBtn.focus();
381 }
383 private hideLoudWarning(): void {
384 this.loudWarn.hidden = true;
385 this.loudGo = null;
386 }
388 private buildSpecToolbar(): void {
389 const t = $("specToolbar");
390 const sel = (opts: [string, string][], value: string, onChange: (v: string) => void) => {
391 const s = document.createElement("select");
392 for (const [v, l] of opts) { const o = document.createElement("option"); o.value = v; o.textContent = l; s.append(o); }
393 s.value = value;
394 s.addEventListener("change", () => onChange(s.value));
395 return s;
396 };
397 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
398 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(); });
399 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) }));
400 const db = sel([["60", "60 dB"], ["80", "80 dB"], ["100", "100 dB"]], "80", (v) => this.spec.setOptions({ dbRange: Number(v) }));
401 const log = document.createElement("input"); log.type = "checkbox";
402 log.addEventListener("change", () => { this.specOpts.logFreq = log.checked; this.spec.setOptions({ logFreq: log.checked }); this.tutorial?.refresh(); });
403 this.specWinSel = win; this.specLogChk = log;
404 const ticks = document.createElement("input"); ticks.type = "checkbox"; ticks.checked = this.showTicks;
405 ticks.addEventListener("change", () => { this.showTicks = ticks.checked; this.updateTicks(); });
406 t.append(lab("Spectrogram window", win), lab("Max", maxHz), lab("Range", db), lab("Log frequency", log), lab("Modal frequencies", ticks));
407 }
409 private buildSplitter(): void {
410 const sp = $("splitter"), sb = $("sidebar");
411 const saved = localStorage.getItem("cymbalsim.sidebar");
412 if (saved) sb.style.width = saved;
413 let dragging = false;
414 sp.addEventListener("mousedown", (e) => { dragging = true; e.preventDefault(); });
415 window.addEventListener("mousemove", (e) => {
416 if (!dragging) return;
417 const w = Math.max(280, Math.min(window.innerWidth - 300, e.clientX));
418 sb.style.width = `${w}px`;
419 this.renderer.resize(); this.spec.resize();
420 });
421 window.addEventListener("mouseup", () => { if (dragging) { dragging = false; localStorage.setItem("cymbalsim.sidebar", sb.style.width); } });
422 sp.addEventListener("dblclick", () => { sb.style.width = ""; localStorage.removeItem("cymbalsim.sidebar"); this.renderer.resize(); this.spec.resize(); });
423 }
425 // ---------- Design ----------
427 private onSource(source: string): void {
428 if (this.running) return;
429 let d: Design;
430 try {
431 d = compileDesign(source);
432 } catch (e) {
433 this.editor.setStatus(e instanceof Error ? e.message : String(e), "error");
434 return;
435 }
436 this.editor.setStatus(`Compiled: ${d.name}`, "ok");
437 this.rebuildPlate(d);
438 }
440 private rebuildPlate(d: Design): void {
441 const p = this.form.get();
442 let plate: Plate;
443 try {
444 plate = evaluatePlate(d, p.spacing);
445 } catch (e) {
446 this.editor.setStatus(e instanceof DesignError ? e.message : String(e), "error");
447 return;
448 }
449 this.design = d;
450 this.plate = plate;
451 this.plateSpacing = p.spacing;
452 this.designGeneration++;
453 this.modes = null; this.model = null; this.sys = null;
454 this.synthesized = false;
455 this.lastContact = null;
456 this.rec = null;
457 this.spec.reset();
458 this.spec.setOptions({ fs: p.fs });
459 this.renderer.setPlate(plate);
460 this.setView("design");
461 this.updateMarkers();
462 this.updateDesignInfo();
463 this.updateNotes();
464 this.updateButtons();
465 if (this.runMode === "linear") this.useCachedModes();
466 else this.modeBrowser.clear("Switch to the linear model to compute the modes.");
467 this.tutorial?.refresh();
468 }
470 /** The cache key of the modes of the current design and numerics. */
471 private modesKey(): string | null {
472 if (!this.design || !this.plate) return null;
473 const p = this.form.get();
474 return `${this.plateSpacing}|${Math.min(p.modeMaxFreq, p.fs / 2)}|${this.design.source}`;
475 }
477 /** Installs cached modes for the current design if there are any; otherwise leaves the browser empty. */
478 private useCachedModes(): void {
479 const key = this.modesKey();
480 const hit = key ? this.modesCache.get(key) : undefined;
481 if (hit && this.plate) {
482 this.installModes(hit.sys, hit.modes, hit.model, null);
483 if (this.pool) void this.pool.setModel(hit.model, null);
484 } else this.modeBrowser.clear("Press Synthesize to compute the modes of this design.");
485 }
487 /** Shows a mode set in the browser, the notes and the spectrogram ticks. */
488 private installModes(sys: LinearSystem, modes: ModeSet, model: ModalModel, secs: number | null): void {
489 const p = this.form.get();
490 const fMax = Math.min(p.modeMaxFreq, p.fs / 2);
491 this.sys = sys; this.modes = modes; this.model = model;
492 const sigma = modalRates(model);
493 const t60 = (s: number) => (s > 0 ? LN1000 / s : Infinity);
494 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]) }));
495 const kind = sys.fields === 1 ? "bending modes" : "modes (bending coupled to stretching)";
496 const when = secs === null ? "cached" : `in ${secs.toFixed(1)} s`;
497 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.`);
498 this.updateNotes();
499 this.updateTicks();
500 this.updateButtons();
501 this.tutorial?.refresh();
502 }
504 private updateDesignInfo(): void {
505 const pl = this.plate;
506 if (!pl) return;
507 const p = this.form.get();
508 const g = pl.grid;
509 const { mass } = massProperties(pl);
510 const hr = thicknessRange(pl);
511 const ps = profileStats(pl);
512 const lines: string[] = [];
513 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`);
514 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)`);
515 if (ps.peakToPeak > 0) {
516 const warn = ps.maxSlope > 0.1 ? ` <span class="warn">(above the shallow-shell range of about 0.1)</span>` : "";
517 lines.push(`Profile ${(ps.peakToPeak * 1e3).toFixed(1)} mm peak to peak, largest slope ${ps.maxSlope.toFixed(3)}${warn}`);
518 } else lines.push("Flat plate (no profile): the linear model is bending only");
519 const geom = plateGeometry(pl);
520 const est = (f: number) => estimatedRate(pl, geom, f);
521 const t60 = rateText;
522 const th = pl.mat.thermal;
523 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`);
524 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.`);
525 void p;
526 $("designInfo").innerHTML = lines.join("\n");
527 }
529 private updateNotes(): void {
530 const pl = this.plate;
531 if (!pl) return;
532 const p = this.form.get();
533 const g = pl.grid;
534 const hm = meanThickness(pl);
535 const f3 = dispersionFrequency(pl.mat, hm, g.hx, 0.03), f10 = dispersionFrequency(pl.mat, hm, g.hx, 0.1);
536 const wmax = maxAngularFrequency(g, pl.mat, thicknessRange(pl).max);
537 const dtMax = (CFL * 2) / wmax;
538 const sps = Math.ceil(1 / (p.fs * dtMax));
539 const dt = 1 / (p.fs * sps);
540 const geom = plateGeometry(pl);
541 const fit = fitSigma(pl, geom);
542 const t60f = (f: number) => (LN1000 / fittedRate(fit, f)).toFixed(2);
543 const t60e = (f: number) => (LN1000 / estimatedRate(pl, geom, f).total).toFixed(2);
544 const lines = [
545 `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).`,
546 `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>` : ""}.`,
547 `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.`,
548 ];
549 this.form.setNotes("Grid and numerics", lines.join("\n"));
550 const patch = strikePatch(pl, p);
551 const sp = strikePoint(pl, p);
552 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).`];
553 if (this.lastContact) sl.push(`Last linear strike: peak force ${this.lastContact.peakForce.toFixed(0)} N, contact ${(this.lastContact.contactTime * 1e3).toFixed(2)} ms.`);
554 if (this.sim) { const st = this.sim.status().stick; sl.push(`Full simulation: peak force ${st.maxForce.toFixed(0)} N${st.withdrawn ? ", stick withdrawn" : ""}.`); }
555 this.form.setNotes("Strike", sl.join("\n"));
556 }
558 private updateMarkers(): void {
559 const pl = this.plate;
560 if (!pl) return;
561 const p = this.form.get();
562 const sp = strikePoint(pl, p);
563 const L = listenerPosition(p);
564 this.renderer.setMarkers({
565 strike: { x: sp.x, y: sp.y, radius: p.contactRadius },
566 listener: L,
567 });
568 }
570 // ---------- Linear model ----------
572 /** Computes the modes of the current design unless they are cached; resolves when they are installed (or with an error). */
573 private computeModes(): Promise<void> {
574 const pl = this.plate, gen = this.designGeneration, key = this.modesKey();
575 if (!pl || !key) return Promise.resolve();
576 const hit = this.modesCache.get(key);
577 if (hit) {
578 if (this.model !== hit.model) { this.installModes(hit.sys, hit.modes, hit.model, null); if (this.pool) return this.pool.setModel(hit.model, null); }
579 return Promise.resolve();
580 }
581 const p = this.form.get();
582 const fMax = Math.min(p.modeMaxFreq, p.fs / 2);
583 this.modeBrowser.clear("Computing the modes...");
584 this.setProgress(0, "Computing the modes...");
585 this.updateButtons();
586 this.modesBusy = this.modesBusy.then(async () => {
587 if (gen !== this.designGeneration) return;
588 const t0 = performance.now();
589 let sys: LinearSystem;
590 try {
591 sys = assemble(pl);
592 } catch (e) {
593 this.setProgress(null, `Assembly failed: ${e instanceof Error ? e.message : String(e)}`);
594 throw e;
595 }
596 let modes: ModeSet;
597 try {
598 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}`); });
599 else {
600 const { computeModes, localRunner } = await import("./modal/modes.ts");
601 modes = await computeModes(sys, fMax, localRunner(sys));
602 }
603 } catch (e) {
604 this.setProgress(null, `Mode computation failed: ${e instanceof Error ? e.message : String(e)}`);
605 throw e;
606 }
607 const model = modalModel(pl, sys, modes);
608 // The radiation and the thermoelastic loss of every mode, from its shape.
609 this.setProgress(1, "Computing the radiation of the modes...");
610 const dp = dampingPlate(pl);
611 try {
612 if (this.pool) { await this.pool.setModel(model, dp); await this.pool.rates(model); }
613 else computeDamping(model, dp);
614 } catch (e) {
615 this.setProgress(null, `Loss computation failed: ${e instanceof Error ? e.message : String(e)}`);
616 throw e;
617 }
618 this.modesCache.set(key, { sys, modes, model });
619 while (this.modesCache.size > 4) this.modesCache.delete(this.modesCache.keys().next().value!);
620 if (gen !== this.designGeneration) { this.setProgress(null); return; }
621 this.setProgress(null, "");
622 this.installModes(sys, modes, model, (performance.now() - t0) / 1000);
623 });
624 return this.modesBusy;
625 }
627 private showMode(m: number | null): void {
628 if (m === null) { this.setView(this.rec ? "movie" : "design"); return; }
629 if (!this.model) return;
630 this.view = "mode";
631 const shape = modeShapeOnGrid(this.model, m);
632 // Scale the mass-normalized shape to a visible amplitude: 1 mm peak.
633 let peak = 0;
634 for (const v of shape) peak = Math.max(peak, Math.abs(v));
635 const w = new Float32Array(shape.length);
636 for (let k = 0; k < w.length; k++) w[k] = (shape[k] / (peak || 1)) * 1e-3;
637 this.renderer.setField(w);
638 this.overlay.textContent = `Mode ${m + 1}: ${this.model.freqs[m].toFixed(1)} Hz (shape scaled to 1 mm)`;
639 }
641 private scheduleSynth(): void {
642 if (this.synthTimer !== null) clearTimeout(this.synthTimer);
643 this.synthTimer = window.setTimeout(() => { this.synthTimer = null; void this.runLinear(); }, 250);
644 }
646 /** Makes sure the modes of the current design are computed and installed in the pool. */
647 async ensureModes(): Promise<void> {
648 if (!this.plate) return;
649 if (!this.model || this.modesKey() !== this.currentModesKey) {
650 await this.computeModes();
651 this.currentModesKey = this.modesKey();
652 }
653 }
655 /** Synthesizes the strike with the current parameters (linear model). */
656 async runLinear(): Promise<void> {
657 if (!this.plate) return;
658 if (this.synthBusy) { this.synthPending = true; return; }
659 try {
660 await this.ensureModes();
661 } catch {
662 return;
663 }
664 const pl = this.plate, model = this.model;
665 if (!pl || !model) return;
666 this.synthBusy = true;
667 const p = this.form.get();
668 const gen = this.designGeneration;
669 const t0 = performance.now();
670 this.runStatus.textContent = "Synthesizing...";
671 try {
672 let audio: Float32Array, frames: Float32Array, nFrames: number, contact: ContactResult;
673 if (this.pool) {
674 const r = await this.pool.synthesize(model, pl, p, (a, c) => {
675 if (gen !== this.designGeneration) return;
676 this.installRecording(a, [], p, "linear");
677 this.lastContact = c;
678 this.runStatus.textContent = `Audio ready in ${((performance.now() - t0) / 1000).toFixed(2)} s; movie frames...`;
679 });
680 audio = r.audio; frames = r.frames; nFrames = r.nFrames; contact = r.contact;
681 } else {
682 const { synthesize } = await import("./modal/synth.ts");
683 const r = synthesize(model, pl, p, true);
684 audio = r.audio; frames = r.frames; nFrames = r.nFrames; contact = r.contact;
685 }
686 if (gen !== this.designGeneration) return;
687 const n = pl.grid.n;
688 const frameList: Float32Array[] = [];
689 for (let f = 0; f < nFrames; f++) frameList.push(frames.subarray(f * n, (f + 1) * n));
690 this.installRecording(audio, frameList, p, "linear");
691 this.lastContact = contact;
692 this.synthesized = true;
693 const secs = (performance.now() - t0) / 1000;
694 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.`;
695 this.updateNotes();
696 } catch (e) {
697 this.runStatus.textContent = `Synthesis failed: ${e instanceof Error ? e.message : String(e)}`;
698 } finally {
699 this.synthBusy = false;
700 this.tutorial?.refresh();
701 if (this.synthPending) { this.synthPending = false; void this.runLinear(); }
702 }
703 }
705 // ---------- Full simulation ----------
707 async runFull(): Promise<void> {
708 const pl = this.plate;
709 if (!pl || !this.device || this.running) return;
710 const p = this.form.get();
711 this.sim?.destroy();
712 const fit = fitSigma(pl);
713 const loss: FullLoss = fullLoss(fit, inPlaneRate(pl));
714 this.sim = new Simulation(this.device, pl, p, loss);
715 this.rec = { audio: new Float32Array(0), samples: 0, fs: p.fs, frames: [new Float32Array(pl.grid.n)], fps: p.fps, source: "full" };
716 this.resetLoudness();
717 this.spec.reset();
718 this.spec.setOptions({ fs: p.fs });
719 this.spec.setDuration(p.duration);
720 this.running = true;
721 this.paused = false;
722 this.setLocked(true);
723 this.setView("live");
724 this.updateButtons();
725 await this.fullLoop();
726 }
728 private async fullLoop(): Promise<void> {
729 const sim = this.sim;
730 if (!sim) return;
731 const t0 = performance.now();
732 let lastUi = 0;
733 while (this.running && sim.phase === "recording") {
734 if (this.paused) { await new Promise((r) => setTimeout(r, 50)); continue; }
735 await sim.runBatch();
736 if (!this.rec || this.sim !== sim) break;
737 // New audio and frames.
738 const rec = this.rec;
739 const newSamples = sim.samples - rec.samples;
740 if (newSamples > 0) {
741 const chunk = sim.audio.subarray(rec.samples, sim.samples);
742 this.spec.append(chunk);
743 rec.audio = sim.audio; rec.samples = sim.samples;
744 }
745 rec.frames = sim.frames;
746 if (this.view === "live") this.renderer.setField(sim.frames[sim.frames.length - 1]);
747 const now = performance.now();
748 if (now - lastUi > 100) {
749 lastUi = now;
750 const st = sim.status();
751 const elapsed = (now - t0) / 1000;
752 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" : ""}`;
753 this.scrub.max = String(Math.max(0, rec.frames.length - 1));
754 this.updatePeak();
755 }
756 }
757 if (this.sim === sim) {
758 this.running = false;
759 this.setLocked(false);
760 const st = sim.status();
761 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.`;
762 if (this.rec) { this.rec.audio = sim.recordedAudio(); this.rec.samples = sim.samples; this.rec.frames = sim.frames; }
763 this.updateNotes();
764 this.updateButtons();
765 this.updatePeak();
766 this.tutorial?.refresh();
767 }
768 }
770 // ---------- Run control ----------
772 private setRunMode(mode: RunMode): void {
773 if (mode === "full" && !this.device) mode = "linear";
774 this.runMode = mode;
775 this.runModeSel.value = mode;
776 if (mode === "linear" && this.plate && !this.modes) this.useCachedModes();
777 if (mode === "full") this.modeBrowser.clear("Switch to the linear model to compute the modes.");
778 this.updateButtons();
779 this.tutorial?.refresh();
780 }
782 private start(): void {
783 if (this.runMode === "linear") void this.runLinear();
784 else void this.runFull();
785 }
786 private pause(): void {
787 if (!this.running) return;
788 this.paused = !this.paused;
789 this.pauseBtn.textContent = this.paused ? "Resume" : "Pause";
790 }
791 private stopRun(): void {
792 if (this.sim && this.running) { this.sim.stop(); this.running = false; }
793 this.paused = false;
794 this.pauseBtn.textContent = "Pause";
795 this.setLocked(false);
796 this.updateButtons();
797 }
798 private continueRun(): void {
799 const sim = this.sim;
800 if (!sim || this.running || !sim.canContinue()) return;
801 sim.setDuration(this.form.get().duration);
802 this.running = true;
803 this.setLocked(true);
804 this.setView("live");
805 this.updateButtons();
806 void this.fullLoop();
807 }
809 private setLocked(locked: boolean): void {
810 this.editor.setLocked(locked);
811 this.form.setLocked(locked);
812 this.runModeSel.disabled = locked;
813 }
815 private updateButtons(): void {
816 const linear = this.runMode === "linear";
817 const canLinear = linear && !!this.plate && !this.synthBusy;
818 const canFull = !linear && !!this.plate && !!this.device && !this.running;
819 this.startBtn.disabled = !(canLinear || canFull);
820 this.startBtn.textContent = linear ? "Synthesize" : "Start";
821 this.pauseBtn.disabled = linear || !this.running;
822 this.stopBtn.disabled = linear || !this.running;
823 this.continueBtn.disabled = linear || this.running || !this.sim || !this.sim.canContinue() || this.sim.samples >= Math.round(this.form.get().duration * this.form.get().fs);
824 this.pauseBtn.hidden = linear; this.stopBtn.hidden = linear; this.continueBtn.hidden = linear;
825 this.liveBtn.hidden = linear;
826 }
828 // ---------- Recording, view, playback ----------
830 private installRecording(audio: Float32Array, frames: Float32Array[], p: SimParams, source: RunMode): void {
831 this.rec = { audio, samples: audio.length, fs: p.fs, frames, fps: p.fps, source };
832 this.resetLoudness();
833 this.spec.setOptions({ fs: p.fs });
834 this.spec.setDuration(p.duration);
835 this.spec.setSignal(audio);
836 this.scrub.max = String(Math.max(0, frames.length - 1));
837 if (frames.length > 0) {
838 this.frameIndex = 0;
839 if (this.view !== "mode") { this.setView("movie"); this.showFrame(); }
840 }
841 this.updatePeak();
842 this.updateButtons();
843 }
845 private setView(v: ViewState): void {
846 this.view = v;
847 if (v === "design") { this.renderer.setField(null); this.overlay.textContent = this.plate ? "Stress-free shape" : ""; }
848 else if (v === "live") { this.overlay.textContent = "Live"; if (this.sim) this.renderer.setField(this.sim.frames[this.sim.frames.length - 1]); }
849 else if (v === "movie") this.showFrame();
850 }
852 private showFrame(): void {
853 const rec = this.rec;
854 if (!rec || rec.frames.length === 0) return;
855 const f = Math.max(0, Math.min(rec.frames.length - 1, this.frameIndex));
856 this.frameIndex = f;
857 this.scrub.value = String(f);
858 this.timeLabel.textContent = `${(f / rec.fps).toFixed(3)} s`;
859 this.renderer.setField(rec.frames[f]);
860 this.overlay.textContent = `${rec.source === "linear" ? "Linear" : "Full"} model, t = ${(f / rec.fps).toFixed(3)} s`;
861 }
863 private playable(): Float32Array | null {
864 const rec = this.rec;
865 if (!rec || rec.samples === 0) return null;
866 const sig = rec.audio.subarray(0, rec.samples);
867 return applyLevel(sig, levelGain(sig, rec.fs, this.levelMode, this.gainDb));
868 }
870 /** 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. */
871 private resetLoudness(): void {
872 this.hideLoudWarning();
873 this.loudAccepted = false;
874 }
876 private updatePeak(): void {
877 const s = this.playable();
878 if (!s) { this.peakLabel.textContent = ""; this.downloadBtn.disabled = true; this.playBtn.disabled = true; return; }
879 const db = peakDbfs(s);
880 this.peakLabel.textContent = `Peak ${db.toFixed(1)} dBFS${db > -0.5 ? " (clipping)" : ""}`;
881 this.peakLabel.className = db > -0.5 ? "badge warn" : "badge";
882 this.downloadBtn.disabled = false;
883 this.playBtn.disabled = false;
884 }
886 private togglePlay(): void {
887 if (this.player.playing) { this.player.stop(); this.playBtn.textContent = "Play"; this.spec.setCursor(null); return; }
888 const s = this.playable(), rec = this.rec;
889 if (!s || !rec) return;
890 // A loud signal can hurt in headphones: warn before playing it, once per signal; any
891 // change of the recording, the level mode or the gain asks again.
892 const l = loudness(s, rec.fs);
893 if (l.loud && !this.loudAccepted) {
894 this.showLoudWarning(l.peakDb, l.shortTermDb, () => { this.loudAccepted = true; this.startPlayback(s, rec); });
895 return;
896 }
897 this.hideLoudWarning();
898 this.startPlayback(s, rec);
899 }
901 private startPlayback(s: Float32Array, rec: Recording): void {
902 // Play from the scrubbed position only when the user has scrubbed to one; from the live
903 // view, or from the end of the recording, start over.
904 const atEnd = rec.frames.length > 1 && this.frameIndex >= rec.frames.length - 1;
905 const start = this.view === "movie" && rec.frames.length > 1 && !atEnd ? this.frameIndex / rec.fps : 0;
906 this.playBtn.textContent = "Stop";
907 const prevView = this.view;
908 this.player.play(s, rec.fs, start, () => { this.playBtn.textContent = "Play"; this.spec.setCursor(null); if (prevView === "live") this.setView("live"); });
909 const tick = () => {
910 if (!this.player.playing) return;
911 const t = this.player.position();
912 this.spec.setCursor(t);
913 if (rec.frames.length > 1) { this.frameIndex = Math.round(t * rec.fps); this.view = "movie"; this.showFrame(); }
914 requestAnimationFrame(tick);
915 };
916 requestAnimationFrame(tick);
917 }
919 private download(): void {
920 const s = this.playable(), rec = this.rec;
921 if (!s || !rec) return;
922 const blob = encodeWav(s, rec.fs);
923 const a = document.createElement("a");
924 a.href = URL.createObjectURL(blob);
925 a.download = `${(this.plate?.name ?? "cymbalsim").replace(/[^a-z0-9]+/gi, "-").toLowerCase()}-${rec.source}.wav`;
926 a.click();
927 setTimeout(() => URL.revokeObjectURL(a.href), 1000);
928 }
930 private updateTicks(): void {
931 this.spec.setTicks(this.showTicks && this.modes ? Array.from(this.modes.freqs) : null);
932 }
934 // ---------- Tutorial ----------
936 /** The state the tutorial's pages read. */
937 private tutorialContext(): TutorialContext {
938 const rec = this.rec;
939 const st = this.sim ? this.sim.status() : null;
940 return {
941 plate: this.plate,
942 design: this.design,
943 params: this.form.get(),
944 spacing: this.plateSpacing,
945 sys: this.sys,
946 modes: this.modes,
947 model: this.model,
948 lastContact: this.lastContact,
949 recording: rec && rec.samples > 0 ? { source: rec.source, seconds: rec.samples / rec.fs } : null,
950 full: st && st.totalSteps > 0 ? { peakForce: st.stick.maxForce, wmax: st.wmax, t: st.t, done: st.phase === "done" } : null,
951 gpu: this.device !== null,
952 runMode: this.runMode,
953 spectrogram: { ...this.specOpts },
954 memo: this.tutorialMemo,
955 };
956 }
958 /** The actions the tutorial's pages can take. */
959 private tutorialHost(): TutorialHost {
960 return {
961 ctx: () => this.tutorialContext(),
962 loadPreset: async (id) => { this.editor.selectPreset(id); },
963 loadScript: async (src) => { this.editor.setSource(src); this.onSource(src); },
964 setParam: (key, value) => {
965 if (key === "duration") {
966 this.durationInput.value = String(value);
967 this.durationInput.dispatchEvent(new Event("change"));
968 return;
969 }
970 this.form.set(key, value);
971 this.onParam(key, false);
972 },
973 computeModes: () => this.ensureModes(),
974 showMode: (m) => this.modeBrowser.select(m),
975 synthesize: async () => {
976 if (this.runMode !== "linear") this.setRunMode("linear");
977 await this.runLinear();
978 },
979 play: () => { if (!this.player.playing) this.togglePlay(); },
980 setRunMode: (mode) => this.setRunMode(mode),
981 runFull: () => this.runFull(),
982 setSpectrogram: (o) => {
983 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 }); }
984 if (o.logFreq !== undefined) { this.specOpts.logFreq = o.logFreq; this.specLogChk.checked = o.logFreq; this.spec.setOptions({ logFreq: o.logFreq }); }
985 this.tutorial?.refresh();
986 },
987 setViewOptions: (o) => {
988 if (o.color !== undefined) { this.viewOpts.color = o.color; this.colorSel.value = o.color; }
989 if (o.exaggeration !== undefined) this.viewOpts.exaggeration = o.exaggeration;
990 this.renderer.setOptions(this.viewOpts);
991 },
992 };
993 }
995 // ---------- Tests ----------
997 async selfTest(): Promise<string> {
998 if (!this.device) return "no WebGPU";
999 const lines: string[] = [];
1000 for (const id of ["flat-rectangle", "bowed-rectangle", "crash-16", "crash-bell-16", "ellipse"]) {
1001 const pr = presetById(id)!;
1002 const d = compileDesign(pr.source);
1003 const pl = evaluatePlate(d, 0.012);
1004 const r = await runSelfTest(this.device, pl, this.form.get());
1005 lines.push(`${id}: max relative error ${r.maxRel.toExponential(2)} (${r.n} nodes)`);
1007 return lines.join("\n");
1010 private testStatus(): unknown {
1011 return {
1012 design: this.design?.name ?? null,
1013 modes: this.modes ? { count: this.modes.count, missing: this.modes.missing, first: Array.from(this.modes.freqs.slice(0, 5)) } : null,
1014 synthesized: this.synthesized,
1015 running: this.running,
1016 samples: this.rec?.samples ?? 0,
1017 frames: this.rec?.frames.length ?? 0,
1018 source: this.rec?.source ?? null,
1019 peakPressure: this.rec ? Array.from(this.rec.audio.subarray(0, this.rec.samples)).reduce((m, v) => Math.max(m, Math.abs(v)), 0) : 0,
1020 sim: this.sim ? this.sim.status() : null,
1021 contact: this.lastContact ? { peakForce: this.lastContact.peakForce, contactTime: this.lastContact.contactTime } : null,
1022 editorStatus: ($("design").querySelector(".editor-status") as HTMLElement | null)?.textContent ?? "",
1023 };
1027const app = new App();
1028app.init().catch((e) => {
1029 console.error(e);
1030 $("viewOverlay").textContent = `Failed to start: ${e instanceof Error ? e.message : String(e)}`;
1031});
1033export { app, PRESETS, isFlat, formatNumber };
↑↓ move↵openescclose