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