/ proof-of-concept / steelsim21
Sign in
proof-of-concept / steelsim21
steelsim21 / src / main.ts
606 lines · 23.1 KBCodeBlameHistory
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 1// UI wiring: parameters, run loop, live and movie views, playback, downloads.
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 3import { defaultParams, makeGrid, makeMaterial, t60, type BowShape, 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";
b9a5a7eSelf-equilibrated release force and loudness normalizationJeremy Magland 9import { 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 {
38 title: "Excitation",
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: "Initial shape",
52 open: true,
53 fields: [{ key: "bowAmplitude", label: "Bow (center vs edges)", unit: "mm", scale: 1e-3, step: 0.5 }],
54 },
56 title: "Damping",
57 open: true,
58 fields: [
59 { key: "sigma0", label: "σ₀ (freq. independent)", unit: "1/s", scale: 1, step: 0.1, live: true },
60 { key: "sigma1", label: "σ₁ (freq. dependent)", unit: "m²/s", scale: 1, step: 1e-5, live: true },
61 ],
62 },
63 {
64 title: "Listener",
65 open: true,
66 fields: [
67 { key: "listenerDist", label: "Distance", unit: "m", scale: 1, step: 0.1, live: true },
68 { key: "listenerAzimuth", label: "Azimuth", unit: "deg", scale: 1, step: 5, live: true },
69 { key: "listenerElevation", label: "Elevation", unit: "deg", scale: 1, step: 5, live: true },
70 ],
71 },
72 {
73 title: "Numerics",
74 open: false,
75 fields: [
76 { key: "spacing", label: "Grid spacing", unit: "mm", scale: 1e-3, step: 0.5 },
77 { key: "fs", label: "Audio sample rate", unit: "Hz", scale: 1, step: 100 },
78 { key: "fps", label: "Movie frame rate", unit: "fps", scale: 1, step: 10 },
79 { key: "settleKE", label: "Settled below KE", unit: "J", scale: 1, step: 1e-9 },
80 ],
81 },
82];
84const inputs = new Map<keyof PhysParams, HTMLInputElement | HTMLSelectElement>();
85let params: PhysParams = { ...defaultParams };
87function buildForm(): void {
88 const root = $("params");
89 for (const g of groups) {
90 const det = document.createElement("details");
91 det.open = g.open;
92 const sum = document.createElement("summary");
93 sum.textContent = g.title;
94 det.appendChild(sum);
95 for (const f of g.fields) {
96 const row = document.createElement("div");
97 row.className = "field";
98 const label = document.createElement("label");
99 label.textContent = f.label;
100 const inp = document.createElement("input");
101 inp.type = "number";
102 inp.step = String(f.step ?? 1);
103 inp.value = fmt((params[f.key] as number) / f.scale);
104 inp.addEventListener("change", () => onFieldChange(f, inp));
105 const unit = document.createElement("span");
106 unit.className = "unit";
107 unit.textContent = f.unit;
108 row.append(label, inp, unit);
109 det.appendChild(row);
110 inputs.set(f.key, inp);
111 if (f.key === "listenerElevation") {
112 const r2 = document.createElement("div");
113 r2.className = "field";
114 const l2 = document.createElement("label");
115 l2.textContent = "Radiation model";
116 const sel = document.createElement("select");
117 for (const [v, t] of [["rayleigh", "Rayleigh (baffled)"], ["dipole", "Dipole (unbaffled, approx.)"]]) {
118 const o = document.createElement("option");
119 o.value = v; o.textContent = t;
120 sel.appendChild(o);
121 }
122 sel.value = params.radiation;
123 sel.addEventListener("change", () => {
124 params.radiation = sel.value as PhysParams["radiation"];
125 applyListener();
126 });
127 r2.append(l2, sel, document.createElement("span"));
128 det.appendChild(r2);
129 inputs.set("radiation", sel);
130 }
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 131 if (f.key === "bowAmplitude") {
132 const r2 = document.createElement("div");
133 r2.className = "field";
134 const l2 = document.createElement("label");
135 l2.textContent = "Bow shape";
136 const sel = document.createElement("select");
137 for (const [v, t] of [["width", "Curved across the width"], ["height", "Curved across the height"], ["dish", "Dish (doubly curved)"], ["none", "Flat"]]) {
138 const o = document.createElement("option");
139 o.value = v; o.textContent = t;
140 sel.appendChild(o);
141 }
142 sel.value = params.bowShape;
143 sel.addEventListener("change", () => { params.bowShape = sel.value as BowShape; });
144 r2.append(l2, sel, document.createElement("span"));
145 det.appendChild(r2);
146 inputs.set("bowShape", sel);
147 const note = document.createElement("p");
148 note.className = "sub";
149 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.";
150 det.appendChild(note);
151 }
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 152 if (f.key === "sigma1") {
153 const note = document.createElement("p");
154 note.className = "sub";
155 note.id = "dampNote";
156 det.appendChild(note);
157 }
158 }
159 root.appendChild(det);
160 }
161 updateDampingNote();
164function fmt(v: number): string {
165 if (v === 0) return "0";
166 const a = Math.abs(v);
167 if (a >= 1e5 || a < 1e-3) return v.toExponential(3);
168 return String(+v.toPrecision(6));
171function onFieldChange(f: FieldSpec, inp: HTMLInputElement): void {
172 const v = parseFloat(inp.value);
173 if (!isFinite(v)) return;
174 (params as unknown as Record<string, number>)[f.key] = v * f.scale;
175 if (f.key === "sigma0" || f.key === "sigma1") {
176 updateDampingNote();
177 sim?.setDamping(params.sigma0, params.sigma1);
178 }
179 if (f.key.startsWith("listener")) applyListener();
182function applyListener(): void {
183 sim?.setListener(params.listenerDist, params.listenerAzimuth, params.listenerElevation, params.radiation);
186function updateDampingNote(): void {
187 const m = makeMaterial(params);
188 const f = (hz: number) => t60(m, params, 2 * Math.PI * hz).toFixed(2);
189 $("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`;
192function setFormEnabled(enabled: boolean): void {
193 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 194 inputs.get("bowShape")!.disabled = !enabled;
197// ---------- State ----------
199let device: GPUDevice | null = null;
200let sim: Simulation | null = null;
201let renderer: Renderer | null = null;
202let running = false;
203let paused = false;
204let live = true;
205let scrubFrame = 0;
206let movieBuf: GPUBuffer | null = null;
207let movieBufFrame = -1;
6f03b39Spectrogram default range 5 kHzJeremy Magland 208let spec = new Spectrogram({ windowSize: 2048, hop: 512, fmax: 5000, dbFloor: 80, logFrequency: false });
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 209const player = new Player();
210let lastStatsTime = 0, lastStatsSteps = 0, stepsPerSec = 0;
211let duration = params.duration;
213// ---------- Controls ----------
215const btnStart = mkButton("Start", "primary");
216const btnPause = mkButton("Pause");
217const btnContinue = mkButton("Continue");
218const durInput = document.createElement("input");
220function mkButton(text: string, cls = ""): HTMLButtonElement {
221 const b = document.createElement("button");
222 b.textContent = text;
223 b.className = cls;
224 return b;
227function buildControls(): void {
228 const c = $("controls");
229 const durRow = document.createElement("div");
230 durRow.className = "field";
231 durRow.style.width = "100%";
232 const l = document.createElement("label");
233 l.textContent = "Duration after release";
234 durInput.type = "number";
235 durInput.step = "0.5";
236 durInput.min = "0.1";
237 durInput.value = String(duration);
238 durInput.addEventListener("change", () => {
239 const v = parseFloat(durInput.value);
240 if (isFinite(v) && v > 0) {
241 duration = v;
242 params.duration = v;
243 sim?.setDuration(v);
244 updateButtons();
245 }
246 });
247 const u = document.createElement("span");
248 u.className = "unit";
249 u.textContent = "s";
250 durRow.append(l, durInput, u);
251 c.append(durRow, btnStart, btnPause, btnContinue);
252 btnStart.addEventListener("click", () => void start());
253 btnPause.addEventListener("click", () => {
254 paused = !paused;
255 btnPause.textContent = paused ? "Resume" : "Pause";
256 if (!paused) void runLoop();
257 });
258 btnContinue.addEventListener("click", () => {
259 if (!sim) return;
260 sim.setDuration(duration);
261 if (sim.phase !== "done") void runLoop();
262 updateButtons();
263 });
264 updateButtons();
267function updateButtons(): void {
268 const s = sim?.status();
269 btnPause.disabled = !sim || !running || s?.phase === "done";
270 btnContinue.disabled = !sim || running || !s || s.phase !== "done" || s.samples >= Math.round(duration * params.fs) - 1;
271 if (sim && sim.phase === "done" && sim.samples < sim.targetSamples()) btnContinue.disabled = false;
274// ---------- View toolbars ----------
276const viewMode = { value: "2d" as ViewMode };
277const scrub = document.createElement("input");
278const timeLabel = document.createElement("span");
279const btnLive = mkButton("Live");
280const btnPlay = mkButton("Play");
281const btnWav = mkButton("Download .wav");
b9a5a7eSelf-equilibrated release force and loudness normalizationJeremy Magland 282const levelSel = document.createElement("select");
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 283let exagInput: HTMLInputElement;
284let rangeInput: HTMLInputElement;
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 285let shapeCheck: HTMLInputElement;
287function buildViewToolbar(): void {
288 const tb = $("viewToolbar");
289 const seg = document.createElement("span");
290 seg.className = "seg";
291 const b2 = mkButton("2D", "on"), b3 = mkButton("3D");
292 b2.addEventListener("click", () => { viewMode.value = "2d"; b2.classList.add("on"); b3.classList.remove("on"); });
293 b3.addEventListener("click", () => { viewMode.value = "3d"; b3.classList.add("on"); b2.classList.remove("on"); });
294 seg.append(b2, b3);
295 exagInput = numInput(4, 0.5);
296 rangeInput = numInput(0, 0.5);
297 const hint = document.createElement("span");
298 hint.className = "sub";
299 hint.style.margin = "0";
300 hint.textContent = "3D: drag to orbit, wheel to zoom";
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 301 shapeCheck = document.createElement("input");
302 shapeCheck.type = "checkbox";
303 tb.append(seg, labeled("Exaggeration ×", exagInput), labeled("Color range (mm, 0 = auto)", rangeInput), labeled("3D: add initial shape", shapeCheck), hint);
306function buildMovieToolbar(): void {
307 const tb = $("movieToolbar");
308 scrub.type = "range";
309 scrub.min = "0"; scrub.max = "0"; scrub.value = "0";
310 scrub.addEventListener("input", () => {
311 live = false;
312 scrubFrame = parseInt(scrub.value);
313 if (player.playing) player.stop();
314 updateLiveButton();
315 });
316 timeLabel.className = "time";
317 btnLive.addEventListener("click", () => { live = true; updateLiveButton(); });
318 btnPlay.addEventListener("click", () => {
319 if (player.playing) { player.stop(); btnPlay.textContent = "Play"; return; }
320 if (!sim || sim.samples === 0) return;
321 const offset = live ? 0 : scrubFrame / sim.fps;
322 live = false;
b9a5a7eSelf-equilibrated release force and loudness normalizationJeremy Magland 323 player.play(sim.processedAudio(), sim.fs, offset, levelSel.value as LevelMode);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 324 btnPlay.textContent = "Stop";
325 updateLiveButton();
326 });
327 player.onEnded = () => { btnPlay.textContent = "Play"; };
328 btnWav.addEventListener("click", () => {
329 if (!sim || sim.samples === 0) return;
b9a5a7eSelf-equilibrated release force and loudness normalizationJeremy Magland 330 const blob = encodeWav(sim.processedAudio(), sim.fs, levelSel.value as LevelMode);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 331 const a = document.createElement("a");
332 a.href = URL.createObjectURL(blob);
333 a.download = `sheet_${sim.samples}samples_${sim.fs}Hz.wav`;
334 a.click();
335 setTimeout(() => URL.revokeObjectURL(a.href), 5000);
336 });
b9a5a7eSelf-equilibrated release force and loudness normalizationJeremy Magland 337 for (const [v, t] of [["loudness", "Loudness (RMS, soft clip)"], ["peak", "Peak"]]) {
338 const o = document.createElement("option");
339 o.value = v; o.textContent = t;
340 levelSel.appendChild(o);
341 }
342 tb.append(btnPlay, btnLive, scrub, timeLabel, labeled("Level", levelSel), btnWav);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 343 updateLiveButton();
346function updateLiveButton(): void {
347 btnLive.classList.toggle("on", live);
348 btnLive.disabled = live;
351function buildSpecToolbar(): void {
352 const tb = $("specToolbar");
353 const win = document.createElement("select");
354 for (const n of [512, 1024, 2048, 4096, 8192]) {
355 const o = document.createElement("option");
356 o.value = String(n); o.textContent = String(n);
357 win.appendChild(o);
358 }
359 win.value = "2048";
360 const hop = numInput(512, 64);
6f03b39Spectrogram default range 5 kHzJeremy Magland 361 const fmax = numInput(5000, 500);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 362 const floor = numInput(80, 5);
363 const logf = document.createElement("input");
364 logf.type = "checkbox";
365 const apply = () => {
366 if (!sim) return;
367 spec.configure(
368 { 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 },
369 sim.processedAudio(), sim.samples,
370 );
371 };
372 for (const el of [win, hop, fmax, floor, logf]) el.addEventListener("change", apply);
373 tb.append(
374 document.createTextNode("Spectrogram"),
375 labeled("Window", win), labeled("Hop", hop), labeled("Max Hz", fmax), labeled("dB range", floor), labeled("Log freq.", logf),
376 );
379function numInput(v: number, step: number): HTMLInputElement {
380 const i = document.createElement("input");
381 i.type = "number"; i.value = String(v); i.step = String(step);
382 return i;
384function labeled(text: string, el: HTMLElement): HTMLLabelElement {
385 const l = document.createElement("label");
386 l.append(text, el);
387 return l;
390// ---------- Simulation control ----------
392async function start(): Promise<void> {
393 if (!device) return;
394 player.stop();
395 running = false;
396 await new Promise((r) => setTimeout(r, 0));
397 sim?.destroy();
398 spec.reset();
399 live = true;
400 paused = false;
401 btnPause.textContent = "Pause";
402 params.duration = duration;
403 sim = new Simulation(device, params);
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 404 renderer = new Renderer(device, $("view"), sim.grid, params, sim.w0);
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 405 movieBuf?.destroy();
406 movieBuf = device.createBuffer({ size: Math.max(16, sim.grid.n * 4), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
407 movieBufFrame = -1;
408 scrub.max = "0"; scrub.value = "0";
409 lastStatsTime = performance.now(); lastStatsSteps = 0; stepsPerSec = 0;
410 setFormEnabled(false);
411 updateLiveButton();
412 void runLoop();
415async function runLoop(): Promise<void> {
416 if (!sim || running) return;
417 running = true;
418 updateButtons();
419 try {
420 while (sim.phase !== "done" && !paused) {
421 await sim.runBatch();
422 const audio = sim.processedAudio();
423 spec.update(audio, sim.samples);
424 scrub.max = String(Math.max(0, sim.frames.length - 1));
425 if (live) scrub.value = scrub.max;
426 const now = performance.now();
427 if (now - lastStatsTime > 500) {
428 stepsPerSec = ((sim.totalSteps - lastStatsSteps) * 1000) / (now - lastStatsTime);
429 lastStatsTime = now; lastStatsSteps = sim.totalSteps;
430 }
431 }
432 } catch (e) {
433 console.error(e);
434 $("info").innerHTML = `<div class="err">Simulation error: ${String(e)}</div>`;
435 }
436 running = false;
437 setFormEnabled(sim.phase === "done" && !paused ? true : false);
438 if (sim.phase === "done") setFormEnabled(true);
439 updateButtons();
442// ---------- Render loop ----------
444let frameErrorShown = false;
445function frame(): void {
446 requestAnimationFrame(frame);
447 try {
448 frameBody();
449 } catch (e) {
450 if (!frameErrorShown) { frameErrorShown = true; console.error("frame exception:", e); }
451 }
e6ed3adRender lazily: no GPU or spectrogram work when nothing changedJeremy Magland 454let lastRenderKey = "";
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 455function frameBody(): void {
456 if (!device || !sim || !renderer) return;
457 const dev = device;
458 renderer.mode = viewMode.value;
459 renderer.exaggeration = parseFloat(exagInput.value) || 1;
460 renderer.colorRange = (parseFloat(rangeInput.value) || 0) * 1e-3;
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 461 renderer.showShape = shapeCheck.checked;
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 462 const pos = player.position();
463 if (pos !== null) {
464 scrubFrame = Math.min(sim.frames.length - 1, Math.floor(pos * sim.fps));
465 scrub.value = String(scrubFrame);
466 }
467 const st = sim.status();
e6ed3adRender lazily: no GPU or spectrogram work when nothing changedJeremy Magland 468 // Render only when something visible changed, so an idle or paused page does no work.
469 const canvas = $<HTMLCanvasElement>("view");
470 const cam = renderer.camera;
471 const renderKey = [
472 renderer.mode, renderer.exaggeration, renderer.colorRange, renderer.showShape,
473 cam.yaw.toFixed(4), cam.pitch.toFixed(4), cam.dist.toFixed(4),
474 live, scrubFrame, sim.frames.length, st.totalSteps, st.phase,
475 canvas.clientWidth, canvas.clientHeight, window.devicePixelRatio,
476 ].join("|");
477 if (renderKey !== lastRenderKey) {
478 lastRenderKey = renderKey;
479 renderView(dev, st);
480 }
481 spec.draw($("spec"), sim.fs, Math.max(duration, sim.samples / sim.fs), pos ?? (live ? null : scrubFrame / sim.fps));
482 updateInfo(st);
485function renderView(dev: GPUDevice, st: ReturnType<Simulation["status"]>): void {
486 if (!sim || !renderer) return;
487 const enc = dev.createCommandEncoder();
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 488 if (live || sim.frames.length === 0) {
489 sim.encodeDisplay(enc);
490 renderer.render(enc, sim.displayW, st.wmax);
491 timeLabel.textContent = `${st.t >= 0 ? "" : "prep "}${st.t.toFixed(3)} s`;
492 } else {
493 const f = Math.max(0, Math.min(sim.frames.length - 1, scrubFrame));
494 if (movieBufFrame !== f) {
495 dev.queue.writeBuffer(movieBuf!, 0, sim.frames[f]);
496 movieBufFrame = f;
497 }
498 let wmax = 0;
499 const fr = sim.frames[f];
500 for (let k = 0; k < fr.length; k += 7) wmax = Math.max(wmax, Math.abs(fr[k]));
501 renderer.render(enc, movieBuf!, wmax);
502 timeLabel.textContent = `${(f / sim.fps).toFixed(3)} s`;
503 }
504 dev.pushErrorScope("validation");
505 dev.queue.submit([enc.finish()]);
506 void dev.popErrorScope().then((e) => { if (e && !frameErrorShown) { frameErrorShown = true; console.error("frame validation error:", e.message); } });
509function updateInfo(st: ReturnType<Simulation["status"]>): void {
510 if (!sim) return;
511 const g = sim.grid;
512 const spl = st.peakPressure > 0 ? 20 * Math.log10(st.peakPressure / 2e-5) : -Infinity;
513 const phase = { push: "pushing", hold: "settling (held)", recording: "ringing (recording)", done: "done" }[st.phase];
514 const rows: [string, string][] = [
515 ["Phase", phase],
516 ["Time", `${st.t.toFixed(3)} s`],
517 ["Grid", `${g.nx} × ${g.ny} nodes, ${(g.hx * 1e3).toFixed(2)} × ${(g.hy * 1e3).toFixed(2)} mm`],
518 ["Time step", `${(sim.dt * 1e6).toFixed(3)} µs (${sim.stepsPerSample} per sample)`],
519 ["Speed", `${(stepsPerSec / 1e3).toFixed(0)} k steps/s (${(stepsPerSec * sim.dt).toFixed(3)}× real time)`],
520 ["Kinetic energy", `${st.ke.toExponential(2)} J`],
521 ["Max |w|", `${(st.wmax * 1e3).toFixed(3)} mm`],
522 ["Audio", `${(st.samples / sim.fs).toFixed(2)} s, ${st.frames} frames`],
523 ["Peak pressure", st.peakPressure > 0 ? `${st.peakPressure.toFixed(3)} Pa (${spl.toFixed(1)} dB SPL)` : "–"],
524 ];
525 let html = rows.map(([a, b]) => `<div class="row"><span>${a}</span><span>${b}</span></div>`).join("");
526 if (st.delayClamped) html += `<div class="warn">Listener is so close that some propagation delays were clamped.</div>`;
527 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 528 if (html !== lastInfoHtml) {
529 lastInfoHtml = html;
530 $("info").innerHTML = html;
531 }
e6ed3adRender lazily: no GPU or spectrogram work when nothing changedJeremy Magland 533let lastInfoHtml = "";
535// ---------- Init ----------
537async function init(): Promise<void> {
538 buildForm();
539 buildControls();
540 buildViewToolbar();
541 buildMovieToolbar();
542 buildSpecToolbar();
543 if (!("gpu" in navigator)) {
544 showNoGpu("WebGPU is not available in this browser. Use a recent Chrome or Edge (or Firefox / Safari with WebGPU enabled).");
545 return;
546 }
547 const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
548 if (!adapter) {
549 showNoGpu("No WebGPU adapter was found.");
550 return;
551 }
552 device = await adapter.requestDevice();
553 device.lost.then((info) => showNoGpu(`WebGPU device lost: ${info.message}`));
554 device.addEventListener("uncapturederror", (ev) => console.error("WebGPU error:", (ev as GPUUncapturedErrorEvent).error.message));
555 const g = makeGrid(params);
556 $("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>`;
557 requestAnimationFrame(frame);
558 applyUrlParams();
561/** URL parameters: any PhysParams key in SI units, plus autostart=1. Exposes the simulation on window for tests. */
562function applyUrlParams(): void {
563 const q = new URLSearchParams(location.search);
564 for (const [k, v] of q) {
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 565 if (k in params && k !== "radiation" && k !== "bowShape") {
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 566 const num = parseFloat(v);
567 if (isFinite(num)) {
568 (params as unknown as Record<string, number>)[k] = num;
569 const inp = inputs.get(k as keyof PhysParams);
570 const spec = groups.flatMap((g) => g.fields).find((f) => f.key === k);
571 if (inp && spec) (inp as HTMLInputElement).value = fmt(num / spec.scale);
572 }
573 }
574 if (k === "radiation" && (v === "rayleigh" || v === "dipole")) params.radiation = v;
8dcc11fInitial-shape imperfection (Marguerre shallow-shell strains)Jeremy Magland 575 if (k === "bowShape" && ["none", "width", "height", "dish"].includes(v)) {
576 params.bowShape = v as BowShape;
577 (inputs.get("bowShape") as HTMLSelectElement).value = v;
578 }
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 579 if (k === "duration") {
580 duration = params.duration;
581 durInput.value = String(duration);
582 }
583 }
584 updateDampingNote();
585 (window as unknown as { steelsim: unknown }).steelsim = {
586 status: () => (sim ? { ...sim.status(), dt: sim.dt, stepsPerSample: sim.stepsPerSample, nx: sim.grid.nx, ny: sim.grid.ny, stepsPerSec } : null),
587 audio: () => (sim ? Array.from(sim.processedAudio()) : null),
588 frame: (k: number) => (sim ? Array.from(sim.frames[k] ?? []) : null),
589 frames: () => sim?.frames.length ?? 0,
590 state: async () => { if (!sim) return null; const st = await sim.readState(); return { pos: Array.from(st.pos), vel: Array.from(st.vel) }; },
591 pause: () => { paused = true; },
592 canvasInfo: () => { const c = $<HTMLCanvasElement>("view"); return { cw: c.clientWidth, ch: c.clientHeight, w: c.width, h: c.height, mode: viewMode.value }; },
593 setView: (m: ViewMode) => { viewMode.value = m; },
594 scrub: (k: number) => { live = false; scrubFrame = k; scrub.value = String(k); updateLiveButton(); },
595 };
596 if (q.get("autostart") === "1") void start();
599function showNoGpu(msg: string): void {
600 const el = $("nogpu");
601 el.hidden = false;
602 el.textContent = msg;
603 btnStart.disabled = true;
606void init();
↑↓ move↵openescclose