/ proof-of-concept / steelsim21
Sign in
proof-of-concept / steelsim21
steelsim21 / src / main.ts
700 lines · 27.2 KBCodeBlameHistory
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 1// UI wiring: parameters, run loop, live and movie views, playback, downloads.
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 3import { defaultParams, makeGrid, makeMaterial, t60, type BowShape, type Excitation, type PhysParams } from "./params.ts";
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 4import { Simulation } from "./sim/simulation.ts";
5import { Renderer, type ViewMode } from "./render/renderer.ts";
6import { Spectrogram } from "./audio/spectrogram.ts";
7import { Player } from "./audio/player.ts";
8import { encodeWav } from "./audio/wav.ts";
de24345Absolute playback level with gain slider and peak readoutJeremy Magland 9import { levelGain, peakDbfs, type LevelMode } from "./audio/level.ts";
11const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
13// ---------- Parameter form ----------
15interface FieldSpec {
16 key: keyof PhysParams;
17 label: string;
18 unit: string;
19 scale: number; // UI value = SI value / scale
20 step?: number;
21 live?: boolean; // may be changed while a simulation runs
24const groups: { title: string; open: boolean; fields: FieldSpec[] }[] = [
25 {
26 title: "Plate",
27 open: true,
28 fields: [
29 { key: "Lx", label: "Width", unit: "in", scale: 0.0254, step: 0.5 },
30 { key: "Ly", label: "Height", unit: "in", scale: 0.0254, step: 0.5 },
31 { key: "h", label: "Thickness", unit: "mm", scale: 1e-3, step: 0.01 },
32 { key: "E", label: "Young's modulus", unit: "GPa", scale: 1e9, step: 1 },
33 { key: "nu", label: "Poisson ratio", unit: "", scale: 1, step: 0.01 },
34 { key: "rho", label: "Density", unit: "kg/m³", scale: 1, step: 10 },
35 ],
36 },
37 {
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 38 title: "Excitation: push and release",
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 39 open: true,
40 fields: [
41 { key: "pushAmount", label: "Push at corner", unit: "mm", scale: 1e-3, step: 0.5 },
42 { key: "fingerRadius", label: "Finger radius", unit: "mm", scale: 1e-3, step: 1 },
43 { key: "rampTime", label: "Push ramp", unit: "s", scale: 1, step: 0.01 },
44 { key: "holdMax", label: "Max settle time", unit: "s", scale: 1, step: 0.1 },
adc495dFinite finger release: ramp the recorded reaction force to zero over a release timeJeremy Magland 45 { key: "releaseTime", label: "Release time", unit: "ms", scale: 1e-3, step: 1 },
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 46 { key: "settleSigma0", label: "Settle damping σ₀", unit: "1/s", scale: 1, step: 10 },
47 { key: "holeInset", label: "Hole inset", unit: "mm", scale: 1e-3, step: 1 },
48 ],
49 },
51 title: "Excitation: drumstick strike",
52 open: false,
53 fields: [
54 { key: "strikeFracX", label: "Strike x (fraction of width)", unit: "", scale: 1, step: 0.05 },
55 { key: "strikeFracY", label: "Strike y (fraction of height)", unit: "", scale: 1, step: 0.05 },
56 { key: "strikeVelocity", label: "Stick speed", unit: "m/s", scale: 1, step: 0.5 },
57 { key: "stickMass", label: "Stick mass", unit: "g", scale: 1e-3, step: 5 },
58 { key: "contactStiffness", label: "Contact stiffness K", unit: "N/mᵅ", scale: 1, step: 1e8 },
59 { key: "contactExponent", label: "Contact exponent α", unit: "", scale: 1, step: 0.1 },
60 { key: "contactRadius", label: "Tip radius", unit: "mm", scale: 1e-3, step: 1 },
61 ],
62 },
64 title: "Initial shape",
65 open: true,
66 fields: [{ key: "bowAmplitude", label: "Bow (center vs edges)", unit: "mm", scale: 1e-3, step: 0.5 }],
67 },
69 title: "Damping",
70 open: true,
71 fields: [
72 { key: "sigma0", label: "σ₀ (freq. independent)", unit: "1/s", scale: 1, step: 0.1, live: true },
73 { key: "sigma1", label: "σ₁ (freq. dependent)", unit: "m²/s", scale: 1, step: 1e-5, live: true },
bfde5e4High-frequency ringing: in-plane loss, band-limited listener sum, damping defaultsJeremy Magland 74 { key: "sigmaIn", label: "In-plane loss", unit: "1/s", scale: 1, step: 5, live: true },
76 },
77 {
78 title: "Listener",
79 open: true,
80 fields: [
81 { key: "listenerDist", label: "Distance", unit: "m", scale: 1, step: 0.1, live: true },
82 { key: "listenerAzimuth", label: "Azimuth", unit: "deg", scale: 1, step: 5, live: true },
83 { key: "listenerElevation", label: "Elevation", unit: "deg", scale: 1, step: 5, live: true },
84 ],
85 },
86 {
87 title: "Numerics",
88 open: false,
89 fields: [
90 { key: "spacing", label: "Grid spacing", unit: "mm", scale: 1e-3, step: 0.5 },
91 { key: "fs", label: "Audio sample rate", unit: "Hz", scale: 1, step: 100 },
92 { key: "fps", label: "Movie frame rate", unit: "fps", scale: 1, step: 10 },
93 { key: "settleKE", label: "Settled below KE", unit: "J", scale: 1, step: 1e-9 },
94 ],
95 },
96];
98const inputs = new Map<keyof PhysParams, HTMLInputElement | HTMLSelectElement>();
99let params: PhysParams = { ...defaultParams };
101function buildForm(): void {
102 const root = $("params");
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 103 const exRow = document.createElement("div");
104 exRow.className = "field";
105 const exLabel = document.createElement("label");
106 exLabel.textContent = "Excitation";
107 const exSel = document.createElement("select");
108 for (const [v, t] of [["push", "Push corner and release"], ["strike", "Drumstick strike"]]) {
109 const o = document.createElement("option");
110 o.value = v; o.textContent = t;
111 exSel.appendChild(o);
112 }
113 exSel.value = params.excitation;
114 exSel.addEventListener("change", () => { params.excitation = exSel.value as Excitation; });
115 exRow.append(exLabel, exSel, document.createElement("span"));
116 root.appendChild(exRow);
117 inputs.set("excitation", exSel);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 118 for (const g of groups) {
119 const det = document.createElement("details");
120 det.open = g.open;
121 const sum = document.createElement("summary");
122 sum.textContent = g.title;
123 det.appendChild(sum);
124 for (const f of g.fields) {
125 const row = document.createElement("div");
126 row.className = "field";
127 const label = document.createElement("label");
128 label.textContent = f.label;
129 const inp = document.createElement("input");
130 inp.type = "number";
131 inp.step = String(f.step ?? 1);
132 inp.value = fmt((params[f.key] as number) / f.scale);
133 inp.addEventListener("change", () => onFieldChange(f, inp));
134 const unit = document.createElement("span");
135 unit.className = "unit";
136 unit.textContent = f.unit;
137 row.append(label, inp, unit);
138 det.appendChild(row);
139 inputs.set(f.key, inp);
140 if (f.key === "listenerElevation") {
141 const r2 = document.createElement("div");
142 r2.className = "field";
143 const l2 = document.createElement("label");
144 l2.textContent = "Radiation model";
145 const sel = document.createElement("select");
146 for (const [v, t] of [["rayleigh", "Rayleigh (baffled)"], ["dipole", "Dipole (unbaffled, approx.)"]]) {
147 const o = document.createElement("option");
148 o.value = v; o.textContent = t;
149 sel.appendChild(o);
150 }
151 sel.value = params.radiation;
152 sel.addEventListener("change", () => {
153 params.radiation = sel.value as PhysParams["radiation"];
154 applyListener();
155 });
156 r2.append(l2, sel, document.createElement("span"));
157 det.appendChild(r2);
158 inputs.set("radiation", sel);
159 }
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 160 if (f.key === "bowAmplitude") {
161 const r2 = document.createElement("div");
162 r2.className = "field";
163 const l2 = document.createElement("label");
164 l2.textContent = "Bow shape";
165 const sel = document.createElement("select");
166 for (const [v, t] of [["width", "Curved across the width"], ["height", "Curved across the height"], ["dish", "Dish (doubly curved)"], ["none", "Flat"]]) {
167 const o = document.createElement("option");
168 o.value = v; o.textContent = t;
169 sel.appendChild(o);
170 }
171 sel.value = params.bowShape;
172 sel.addEventListener("change", () => { params.bowShape = sel.value as BowShape; });
173 r2.append(l2, sel, document.createElement("span"));
174 det.appendChild(r2);
175 inputs.set("bowShape", sel);
176 const note = document.createElement("p");
177 note.className = "sub";
178 note.textContent = "Real sheet metal is never flat. A bow of a few mm makes the sheet a shallow shell with an asymmetric stiffness; push with a negative amount to push against the bow.";
179 det.appendChild(note);
180 }
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 182 const note = document.createElement("p");
183 note.className = "sub";
184 note.id = "dampNote";
185 det.appendChild(note);
186 }
187 }
188 root.appendChild(det);
189 }
190 updateDampingNote();
193function fmt(v: number): string {
194 if (v === 0) return "0";
195 const a = Math.abs(v);
196 if (a >= 1e5 || a < 1e-3) return v.toExponential(3);
197 return String(+v.toPrecision(6));
200function onFieldChange(f: FieldSpec, inp: HTMLInputElement): void {
201 const v = parseFloat(inp.value);
202 if (!isFinite(v)) return;
203 (params as unknown as Record<string, number>)[f.key] = v * f.scale;
bfde5e4High-frequency ringing: in-plane loss, band-limited listener sum, damping defaultsJeremy Magland 204 if (f.key === "sigma0" || f.key === "sigma1" || f.key === "sigmaIn") {
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 205 updateDampingNote();
bfde5e4High-frequency ringing: in-plane loss, band-limited listener sum, damping defaultsJeremy Magland 206 sim?.setDamping(params.sigma0, params.sigma1, params.sigmaIn);
208 if (f.key.startsWith("listener")) applyListener();
211function applyListener(): void {
212 sim?.setListener(params.listenerDist, params.listenerAzimuth, params.listenerElevation, params.radiation);
215function updateDampingNote(): void {
216 const m = makeMaterial(params);
217 const f = (hz: number) => t60(m, params, 2 * Math.PI * hz).toFixed(2);
218 $("dampNote").textContent = `T60: ${f(100)} s at 100 Hz, ${f(1000)} s at 1 kHz, ${f(5000)} s at 5 kHz, ${f(10000)} s at 10 kHz`;
221function setFormEnabled(enabled: boolean): void {
222 for (const g of groups) for (const f of g.fields) if (!f.live) inputs.get(f.key)!.disabled = !enabled;
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 223 inputs.get("bowShape")!.disabled = !enabled;
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 224 inputs.get("excitation")!.disabled = !enabled;
227// ---------- State ----------
229let device: GPUDevice | null = null;
230let sim: Simulation | null = null;
231let renderer: Renderer | null = null;
232let running = false;
233let paused = false;
234let live = true;
235let scrubFrame = 0;
236let movieBuf: GPUBuffer | null = null;
237let movieBufFrame = -1;
6f03b39Spectrogram default range 5 kHzJeremy Magland 238let spec = new Spectrogram({ windowSize: 2048, hop: 512, fmax: 5000, dbFloor: 80, logFrequency: false });
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 239const player = new Player();
240let lastStatsTime = 0, lastStatsSteps = 0, stepsPerSec = 0;
241let duration = params.duration;
243// ---------- Controls ----------
245const btnStart = mkButton("Start", "primary");
246const btnPause = mkButton("Pause");
176c8fbStop button: end a run and unlock the parameter fieldsJeremy Magland 247const btnStop = mkButton("Stop");
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 248const btnContinue = mkButton("Continue");
249const durInput = document.createElement("input");
251function mkButton(text: string, cls = ""): HTMLButtonElement {
252 const b = document.createElement("button");
253 b.textContent = text;
254 b.className = cls;
255 return b;
258function buildControls(): void {
259 const c = $("controls");
260 const durRow = document.createElement("div");
261 durRow.className = "field";
262 durRow.style.width = "100%";
263 const l = document.createElement("label");
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 264 l.textContent = "Recorded duration";
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 265 durInput.type = "number";
266 durInput.step = "0.5";
267 durInput.min = "0.1";
268 durInput.value = String(duration);
269 durInput.addEventListener("change", () => {
270 const v = parseFloat(durInput.value);
271 if (isFinite(v) && v > 0) {
272 duration = v;
273 params.duration = v;
274 sim?.setDuration(v);
275 updateButtons();
276 }
277 });
278 const u = document.createElement("span");
279 u.className = "unit";
280 u.textContent = "s";
281 durRow.append(l, durInput, u);
176c8fbStop button: end a run and unlock the parameter fieldsJeremy Magland 282 c.append(durRow, btnStart, btnPause, btnStop, btnContinue);
283 btnStop.addEventListener("click", () => {
284 if (!sim) return;
285 sim.stop();
286 paused = false;
287 btnPause.textContent = "Pause";
288 if (!running) {
289 setFormEnabled(true);
290 updateButtons();
291 }
292 });
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 293 btnStart.addEventListener("click", () => void start());
294 btnPause.addEventListener("click", () => {
295 paused = !paused;
296 btnPause.textContent = paused ? "Resume" : "Pause";
297 if (!paused) void runLoop();
298 });
299 btnContinue.addEventListener("click", () => {
300 if (!sim) return;
301 sim.setDuration(duration);
302 if (sim.phase !== "done") void runLoop();
303 updateButtons();
304 });
305 updateButtons();
308function updateButtons(): void {
309 const s = sim?.status();
6c4aa55Fix Resume button being disabled after PauseJeremy Magland 310 btnPause.disabled = !sim || s?.phase === "done" || (!running && !paused);
176c8fbStop button: end a run and unlock the parameter fieldsJeremy Magland 311 btnStop.disabled = !sim || s?.phase === "done";
312 btnContinue.disabled = !sim || running || !sim.canContinue();
315// ---------- View toolbars ----------
317const viewMode = { value: "2d" as ViewMode };
318const scrub = document.createElement("input");
319const timeLabel = document.createElement("span");
320const btnLive = mkButton("Live");
321const btnPlay = mkButton("Play");
322const btnWav = mkButton("Download .wav");
b9a5a7eSelf-equilibrated release force and loudness normalizationJeremy Magland 323const levelSel = document.createElement("select");
de24345Absolute playback level with gain slider and peak readoutJeremy Magland 324const gainSlider = document.createElement("input");
325const gainLabel = document.createElement("span");
326const peakLabel = document.createElement("span");
328function gainDb(): number {
329 return parseFloat(gainSlider.value) || 0;
332function updateLevelReadout(): void {
333 gainLabel.textContent = `${gainDb() >= 0 ? "+" : ""}${gainDb()} dB`;
334 gainSlider.disabled = levelSel.value !== "absolute";
335 if (!sim || sim.samples === 0) { peakLabel.textContent = ""; return; }
336 const audio = sim.processedAudio();
337 const db = peakDbfs(audio, levelGain(audio, sim.fs, levelSel.value as LevelMode, gainDb()));
338 peakLabel.textContent = isFinite(db) ? `peak ${db.toFixed(1)} dBFS` : "";
339 peakLabel.className = db > 0 ? "warn" : "sub";
340 peakLabel.style.margin = "0";
341 if (db > 0) peakLabel.textContent += " (clipped)";
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 343let exagInput: HTMLInputElement;
344let rangeInput: HTMLInputElement;
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 345let shapeCheck: HTMLInputElement;
347function buildViewToolbar(): void {
348 const tb = $("viewToolbar");
349 const seg = document.createElement("span");
350 seg.className = "seg";
351 const b2 = mkButton("2D", "on"), b3 = mkButton("3D");
352 b2.addEventListener("click", () => { viewMode.value = "2d"; b2.classList.add("on"); b3.classList.remove("on"); });
353 b3.addEventListener("click", () => { viewMode.value = "3d"; b3.classList.add("on"); b2.classList.remove("on"); });
354 seg.append(b2, b3);
355 exagInput = numInput(4, 0.5);
356 rangeInput = numInput(0, 0.5);
357 const hint = document.createElement("span");
358 hint.className = "sub";
359 hint.style.margin = "0";
360 hint.textContent = "3D: drag to orbit, wheel to zoom";
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 361 shapeCheck = document.createElement("input");
362 shapeCheck.type = "checkbox";
363 tb.append(seg, labeled("Exaggeration ×", exagInput), labeled("Color range (mm, 0 = auto)", rangeInput), labeled("3D: add initial shape", shapeCheck), hint);
366function buildMovieToolbar(): void {
367 const tb = $("movieToolbar");
368 scrub.type = "range";
369 scrub.min = "0"; scrub.max = "0"; scrub.value = "0";
370 scrub.addEventListener("input", () => {
371 live = false;
372 scrubFrame = parseInt(scrub.value);
373 if (player.playing) player.stop();
374 updateLiveButton();
375 });
376 timeLabel.className = "time";
377 btnLive.addEventListener("click", () => { live = true; updateLiveButton(); });
38f6b3eReturn to live view when playback endsJeremy Magland 378 // Playback drives the movie; afterwards the view returns to where it was (live or scrubbed).
379 let liveBeforePlay = true;
380 const endPlayback = () => {
381 btnPlay.textContent = "Play";
382 if (liveBeforePlay) {
383 live = true;
384 updateLiveButton();
385 }
386 };
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 387 btnPlay.addEventListener("click", () => {
38f6b3eReturn to live view when playback endsJeremy Magland 388 if (player.playing) { player.stop(); endPlayback(); return; }
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 389 if (!sim || sim.samples === 0) return;
38f6b3eReturn to live view when playback endsJeremy Magland 390 liveBeforePlay = live;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 391 const offset = live ? 0 : scrubFrame / sim.fps;
392 live = false;
de24345Absolute playback level with gain slider and peak readoutJeremy Magland 393 player.play(sim.processedAudio(), sim.fs, offset, levelSel.value as LevelMode, gainDb());
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 394 btnPlay.textContent = "Stop";
395 updateLiveButton();
396 });
38f6b3eReturn to live view when playback endsJeremy Magland 397 player.onEnded = endPlayback;
398 scrub.addEventListener("input", () => { liveBeforePlay = false; });
399 btnLive.addEventListener("click", () => { liveBeforePlay = true; });
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 400 btnWav.addEventListener("click", () => {
401 if (!sim || sim.samples === 0) return;
de24345Absolute playback level with gain slider and peak readoutJeremy Magland 402 const blob = encodeWav(sim.processedAudio(), sim.fs, levelSel.value as LevelMode, gainDb());
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 403 const a = document.createElement("a");
404 a.href = URL.createObjectURL(blob);
405 a.download = `sheet_${sim.samples}samples_${sim.fs}Hz.wav`;
406 a.click();
407 setTimeout(() => URL.revokeObjectURL(a.href), 5000);
408 });
de24345Absolute playback level with gain slider and peak readoutJeremy Magland 409 for (const [v, t] of [["absolute", "Absolute (0 dBFS = 1 Pa at 0 dB)"], ["loudness", "Loudness (RMS, soft clip)"], ["peak", "Peak"]]) {
b9a5a7eSelf-equilibrated release force and loudness normalizationJeremy Magland 410 const o = document.createElement("option");
411 o.value = v; o.textContent = t;
412 levelSel.appendChild(o);
413 }
de24345Absolute playback level with gain slider and peak readoutJeremy Magland 414 gainSlider.type = "range";
415 gainSlider.min = "-40"; gainSlider.max = "60"; gainSlider.step = "1"; gainSlider.value = "20";
416 gainSlider.style.width = "120px";
417 gainSlider.style.flex = "none";
418 const restart = () => {
419 updateLevelReadout();
420 const pos = player.position();
421 if (pos !== null && sim) player.play(sim.processedAudio(), sim.fs, pos, levelSel.value as LevelMode, gainDb());
422 };
423 gainSlider.addEventListener("input", restart);
424 levelSel.addEventListener("change", restart);
425 tb.append(btnPlay, btnLive, scrub, timeLabel, labeled("Level", levelSel), labeled("Gain", gainSlider), gainLabel, peakLabel, btnWav);
426 updateLevelReadout();
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 427 updateLiveButton();
430function updateLiveButton(): void {
431 btnLive.classList.toggle("on", live);
432 btnLive.disabled = live;
435function buildSpecToolbar(): void {
436 const tb = $("specToolbar");
437 const win = document.createElement("select");
438 for (const n of [512, 1024, 2048, 4096, 8192]) {
439 const o = document.createElement("option");
440 o.value = String(n); o.textContent = String(n);
441 win.appendChild(o);
442 }
443 win.value = "2048";
444 const hop = numInput(512, 64);
6f03b39Spectrogram default range 5 kHzJeremy Magland 445 const fmax = numInput(5000, 500);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 446 const floor = numInput(80, 5);
447 const logf = document.createElement("input");
448 logf.type = "checkbox";
449 const apply = () => {
450 if (!sim) return;
451 spec.configure(
452 { windowSize: parseInt(win.value), hop: Math.max(16, parseInt(hop.value)), fmax: Math.min(sim.fs / 2, parseFloat(fmax.value)), dbFloor: parseFloat(floor.value), logFrequency: logf.checked },
453 sim.processedAudio(), sim.samples,
454 );
455 };
456 for (const el of [win, hop, fmax, floor, logf]) el.addEventListener("change", apply);
457 tb.append(
458 document.createTextNode("Spectrogram"),
459 labeled("Window", win), labeled("Hop", hop), labeled("Max Hz", fmax), labeled("dB range", floor), labeled("Log freq.", logf),
460 );
463function numInput(v: number, step: number): HTMLInputElement {
464 const i = document.createElement("input");
465 i.type = "number"; i.value = String(v); i.step = String(step);
466 return i;
468function labeled(text: string, el: HTMLElement): HTMLLabelElement {
469 const l = document.createElement("label");
470 l.append(text, el);
471 return l;
474// ---------- Simulation control ----------
476async function start(): Promise<void> {
477 if (!device) return;
478 player.stop();
479 running = false;
480 await new Promise((r) => setTimeout(r, 0));
481 sim?.destroy();
482 spec.reset();
483 live = true;
484 paused = false;
485 btnPause.textContent = "Pause";
486 params.duration = duration;
487 sim = new Simulation(device, params);
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 488 renderer = new Renderer(device, $("view"), sim.grid, params, sim.w0);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 489 movieBuf?.destroy();
490 movieBuf = device.createBuffer({ size: Math.max(16, sim.grid.n * 4), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
491 movieBufFrame = -1;
492 scrub.max = "0"; scrub.value = "0";
493 lastStatsTime = performance.now(); lastStatsSteps = 0; stepsPerSec = 0;
494 setFormEnabled(false);
495 updateLiveButton();
496 void runLoop();
499async function runLoop(): Promise<void> {
500 if (!sim || running) return;
501 running = true;
502 updateButtons();
503 try {
504 while (sim.phase !== "done" && !paused) {
505 await sim.runBatch();
506 const audio = sim.processedAudio();
507 spec.update(audio, sim.samples);
508 scrub.max = String(Math.max(0, sim.frames.length - 1));
509 if (live) scrub.value = scrub.max;
de24345Absolute playback level with gain slider and peak readoutJeremy Magland 510 updateLevelReadout();
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 511 const now = performance.now();
512 if (now - lastStatsTime > 500) {
513 stepsPerSec = ((sim.totalSteps - lastStatsSteps) * 1000) / (now - lastStatsTime);
514 lastStatsTime = now; lastStatsSteps = sim.totalSteps;
515 }
516 }
517 } catch (e) {
518 console.error(e);
519 $("info").innerHTML = `<div class="err">Simulation error: ${String(e)}</div>`;
520 }
521 running = false;
522 if (sim.phase === "done") setFormEnabled(true);
523 updateButtons();
526// ---------- Render loop ----------
528let frameErrorShown = false;
529function frame(): void {
530 requestAnimationFrame(frame);
531 try {
532 frameBody();
533 } catch (e) {
534 if (!frameErrorShown) { frameErrorShown = true; console.error("frame exception:", e); }
535 }
e6ed3adRender lazily: no GPU or spectrogram work when nothing changedJeremy Magland 538let lastRenderKey = "";
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 539function frameBody(): void {
540 if (!device || !sim || !renderer) return;
541 const dev = device;
542 renderer.mode = viewMode.value;
543 renderer.exaggeration = parseFloat(exagInput.value) || 1;
544 renderer.colorRange = (parseFloat(rangeInput.value) || 0) * 1e-3;
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 545 renderer.showShape = shapeCheck.checked;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 546 const pos = player.position();
547 if (pos !== null) {
548 scrubFrame = Math.min(sim.frames.length - 1, Math.floor(pos * sim.fps));
549 scrub.value = String(scrubFrame);
550 }
551 const st = sim.status();
e6ed3adRender lazily: no GPU or spectrogram work when nothing changedJeremy Magland 552 // Render only when something visible changed, so an idle or paused page does no work.
553 const canvas = $<HTMLCanvasElement>("view");
554 const cam = renderer.camera;
555 const renderKey = [
556 renderer.mode, renderer.exaggeration, renderer.colorRange, renderer.showShape,
557 cam.yaw.toFixed(4), cam.pitch.toFixed(4), cam.dist.toFixed(4),
558 live, scrubFrame, sim.frames.length, st.totalSteps, st.phase,
559 canvas.clientWidth, canvas.clientHeight, window.devicePixelRatio,
560 ].join("|");
561 if (renderKey !== lastRenderKey) {
562 lastRenderKey = renderKey;
563 renderView(dev, st);
564 }
565 spec.draw($("spec"), sim.fs, Math.max(duration, sim.samples / sim.fs), pos ?? (live ? null : scrubFrame / sim.fps));
566 updateInfo(st);
569function renderView(dev: GPUDevice, st: ReturnType<Simulation["status"]>): void {
570 if (!sim || !renderer) return;
571 const enc = dev.createCommandEncoder();
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 572 if (live || sim.frames.length === 0) {
573 sim.encodeDisplay(enc);
574 renderer.render(enc, sim.displayW, st.wmax);
575 timeLabel.textContent = `${st.t >= 0 ? "" : "prep "}${st.t.toFixed(3)} s`;
576 } else {
577 const f = Math.max(0, Math.min(sim.frames.length - 1, scrubFrame));
578 if (movieBufFrame !== f) {
579 dev.queue.writeBuffer(movieBuf!, 0, sim.frames[f]);
580 movieBufFrame = f;
581 }
582 let wmax = 0;
583 const fr = sim.frames[f];
584 for (let k = 0; k < fr.length; k += 7) wmax = Math.max(wmax, Math.abs(fr[k]));
585 renderer.render(enc, movieBuf!, wmax);
586 timeLabel.textContent = `${(f / sim.fps).toFixed(3)} s`;
587 }
588 dev.pushErrorScope("validation");
589 dev.queue.submit([enc.finish()]);
590 void dev.popErrorScope().then((e) => { if (e && !frameErrorShown) { frameErrorShown = true; console.error("frame validation error:", e.message); } });
593function updateInfo(st: ReturnType<Simulation["status"]>): void {
594 if (!sim) return;
595 const g = sim.grid;
596 const spl = st.peakPressure > 0 ? 20 * Math.log10(st.peakPressure / 2e-5) : -Infinity;
597 const phase = { push: "pushing", hold: "settling (held)", recording: "ringing (recording)", done: "done" }[st.phase];
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 598 const stickHook = (window as unknown as { steelsim?: { stick?: unknown } }).steelsim;
599 if (stickHook) stickHook.stick = st.stick;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 600 const rows: [string, string][] = [
601 ["Phase", phase],
602 ["Time", `${st.t.toFixed(3)} s`],
603 ["Grid", `${g.nx} × ${g.ny} nodes, ${(g.hx * 1e3).toFixed(2)} × ${(g.hy * 1e3).toFixed(2)} mm`],
604 ["Time step", `${(sim.dt * 1e6).toFixed(3)} µs (${sim.stepsPerSample} per sample)`],
605 ["Speed", `${(stepsPerSec / 1e3).toFixed(0)} k steps/s (${(stepsPerSec * sim.dt).toFixed(3)}× real time)`],
606 ["Kinetic energy", `${st.ke.toExponential(2)} J`],
607 ["Max |w|", `${(st.wmax * 1e3).toFixed(3)} mm`],
608 ["Audio", `${(st.samples / sim.fs).toFixed(2)} s, ${st.frames} frames`],
609 ["Peak pressure", st.peakPressure > 0 ? `${st.peakPressure.toFixed(3)} Pa (${spl.toFixed(1)} dB SPL)` : "–"],
610 ];
612 rows.push(["Stick", `${(st.stick.x * 1e3).toFixed(2)} mm, ${st.stick.v.toFixed(2)} m/s`]);
613 rows.push(["Contact force", `${st.stick.force.toFixed(1)} N (max ${st.stick.maxForce.toFixed(1)} N)`]);
614 }
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 615 let html = rows.map(([a, b]) => `<div class="row"><span>${a}</span><span>${b}</span></div>`).join("");
616 if (st.delayClamped) html += `<div class="warn">Listener is so close that some propagation delays were clamped.</div>`;
617 if (!isFinite(st.wmax) || st.wmax > 1) html += `<div class="err">The solution has diverged. Reduce the time step by increasing the grid spacing, or reduce the push.</div>`;
e6ed3adRender lazily: no GPU or spectrogram work when nothing changedJeremy Magland 618 if (html !== lastInfoHtml) {
619 lastInfoHtml = html;
620 $("info").innerHTML = html;
621 }
e6ed3adRender lazily: no GPU or spectrogram work when nothing changedJeremy Magland 623let lastInfoHtml = "";
625// ---------- Init ----------
627async function init(): Promise<void> {
628 buildForm();
629 buildControls();
630 buildViewToolbar();
631 buildMovieToolbar();
632 buildSpecToolbar();
633 if (!("gpu" in navigator)) {
634 showNoGpu("WebGPU is not available in this browser. Use a recent Chrome or Edge (or Firefox / Safari with WebGPU enabled).");
635 return;
636 }
637 const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
638 if (!adapter) {
639 showNoGpu("No WebGPU adapter was found.");
640 return;
641 }
642 device = await adapter.requestDevice();
643 device.lost.then((info) => showNoGpu(`WebGPU device lost: ${info.message}`));
644 device.addEventListener("uncapturederror", (ev) => console.error("WebGPU error:", (ev as GPUUncapturedErrorEvent).error.message));
645 const g = makeGrid(params);
646 $("info").innerHTML = `<div class="row"><span>Grid (default)</span><span>${g.nx} × ${g.ny} nodes</span></div><p class="sub">Press Start to run.</p>`;
647 requestAnimationFrame(frame);
648 applyUrlParams();
651/** URL parameters: any PhysParams key in SI units, plus autostart=1. Exposes the simulation on window for tests. */
652function applyUrlParams(): void {
653 const q = new URLSearchParams(location.search);
654 for (const [k, v] of q) {
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 655 if (k in params && k !== "radiation" && k !== "bowShape" && k !== "excitation") {
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 656 const num = parseFloat(v);
657 if (isFinite(num)) {
658 (params as unknown as Record<string, number>)[k] = num;
659 const inp = inputs.get(k as keyof PhysParams);
660 const spec = groups.flatMap((g) => g.fields).find((f) => f.key === k);
661 if (inp && spec) (inp as HTMLInputElement).value = fmt(num / spec.scale);
662 }
663 }
664 if (k === "radiation" && (v === "rayleigh" || v === "dipole")) params.radiation = v;
10998acDrumstick strike excitation (Hertz contact with a free mass)Jeremy Magland 665 if (k === "excitation" && (v === "push" || v === "strike")) {
666 params.excitation = v;
667 (inputs.get("excitation") as HTMLSelectElement).value = v;
668 }
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 669 if (k === "bowShape" && ["none", "width", "height", "dish"].includes(v)) {
670 params.bowShape = v as BowShape;
671 (inputs.get("bowShape") as HTMLSelectElement).value = v;
672 }
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 673 if (k === "duration") {
674 duration = params.duration;
675 durInput.value = String(duration);
676 }
677 }
678 updateDampingNote();
679 (window as unknown as { steelsim: unknown }).steelsim = {
680 status: () => (sim ? { ...sim.status(), dt: sim.dt, stepsPerSample: sim.stepsPerSample, nx: sim.grid.nx, ny: sim.grid.ny, stepsPerSec } : null),
681 audio: () => (sim ? Array.from(sim.processedAudio()) : null),
682 frame: (k: number) => (sim ? Array.from(sim.frames[k] ?? []) : null),
683 frames: () => sim?.frames.length ?? 0,
684 state: async () => { if (!sim) return null; const st = await sim.readState(); return { pos: Array.from(st.pos), vel: Array.from(st.vel) }; },
685 pause: () => { paused = true; },
686 canvasInfo: () => { const c = $<HTMLCanvasElement>("view"); return { cw: c.clientWidth, ch: c.clientHeight, w: c.width, h: c.height, mode: viewMode.value }; },
687 setView: (m: ViewMode) => { viewMode.value = m; },
688 scrub: (k: number) => { live = false; scrubFrame = k; scrub.value = String(k); updateLiveButton(); },
689 };
690 if (q.get("autostart") === "1") void start();
693function showNoGpu(msg: string): void {
694 const el = $("nogpu");
695 el.hidden = false;
696 el.textContent = msg;
697 btnStart.disabled = true;
700void init();
↑↓ move↵openescclose