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