/ proof-of-concept / steelsim21
Sign in
proof-of-concept / steelsim21
steelsim21 / src / main.ts
542 lines · 20.2 KBCodeBlameHistory
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 1// UI wiring: parameters, run loop, live and movie views, playback, downloads.
3import { defaultParams, makeGrid, makeMaterial, t60, type PhysParams } from "./params.ts";
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";
10const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
12// ---------- Parameter form ----------
14interface FieldSpec {
15 key: keyof PhysParams;
16 label: string;
17 unit: string;
18 scale: number; // UI value = SI value / scale
19 step?: number;
20 live?: boolean; // may be changed while a simulation runs
23const groups: { title: string; open: boolean; fields: FieldSpec[] }[] = [
24 {
25 title: "Plate",
26 open: true,
27 fields: [
28 { key: "Lx", label: "Width", unit: "in", scale: 0.0254, step: 0.5 },
29 { key: "Ly", label: "Height", unit: "in", scale: 0.0254, step: 0.5 },
30 { key: "h", label: "Thickness", unit: "mm", scale: 1e-3, step: 0.01 },
31 { key: "E", label: "Young's modulus", unit: "GPa", scale: 1e9, step: 1 },
32 { key: "nu", label: "Poisson ratio", unit: "", scale: 1, step: 0.01 },
33 { key: "rho", label: "Density", unit: "kg/m³", scale: 1, step: 10 },
34 ],
35 },
36 {
37 title: "Excitation",
38 open: true,
39 fields: [
40 { key: "pushAmount", label: "Push at corner", unit: "mm", scale: 1e-3, step: 0.5 },
41 { key: "fingerRadius", label: "Finger radius", unit: "mm", scale: 1e-3, step: 1 },
42 { key: "rampTime", label: "Push ramp", unit: "s", scale: 1, step: 0.01 },
43 { 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 44 { key: "releaseTime", label: "Release time", unit: "ms", scale: 1e-3, step: 1 },
f8a8a6cNonlinear steel sheet gong simulator with WebGPUJeremy Magland 45 { key: "settleSigma0", label: "Settle damping σ₀", unit: "1/s", scale: 1, step: 10 },
46 { key: "holeInset", label: "Hole inset", unit: "mm", scale: 1e-3, step: 1 },
47 ],
48 },
49 {
50 title: "Damping",
51 open: true,
52 fields: [
53 { key: "sigma0", label: "σ₀ (freq. independent)", unit: "1/s", scale: 1, step: 0.1, live: true },
54 { key: "sigma1", label: "σ₁ (freq. dependent)", unit: "m²/s", scale: 1, step: 1e-5, live: true },
55 ],
56 },
57 {
58 title: "Listener",
59 open: true,
60 fields: [
61 { key: "listenerDist", label: "Distance", unit: "m", scale: 1, step: 0.1, live: true },
62 { key: "listenerAzimuth", label: "Azimuth", unit: "deg", scale: 1, step: 5, live: true },
63 { key: "listenerElevation", label: "Elevation", unit: "deg", scale: 1, step: 5, live: true },
64 ],
65 },
66 {
67 title: "Numerics",
68 open: false,
69 fields: [
70 { key: "spacing", label: "Grid spacing", unit: "mm", scale: 1e-3, step: 0.5 },
71 { key: "fs", label: "Audio sample rate", unit: "Hz", scale: 1, step: 100 },
72 { key: "fps", label: "Movie frame rate", unit: "fps", scale: 1, step: 10 },
73 { key: "settleKE", label: "Settled below KE", unit: "J", scale: 1, step: 1e-9 },
74 ],
75 },
76];
78const inputs = new Map<keyof PhysParams, HTMLInputElement | HTMLSelectElement>();
79let params: PhysParams = { ...defaultParams };
81function buildForm(): void {
82 const root = $("params");
83 for (const g of groups) {
84 const det = document.createElement("details");
85 det.open = g.open;
86 const sum = document.createElement("summary");
87 sum.textContent = g.title;
88 det.appendChild(sum);
89 for (const f of g.fields) {
90 const row = document.createElement("div");
91 row.className = "field";
92 const label = document.createElement("label");
93 label.textContent = f.label;
94 const inp = document.createElement("input");
95 inp.type = "number";
96 inp.step = String(f.step ?? 1);
97 inp.value = fmt((params[f.key] as number) / f.scale);
98 inp.addEventListener("change", () => onFieldChange(f, inp));
99 const unit = document.createElement("span");
100 unit.className = "unit";
101 unit.textContent = f.unit;
102 row.append(label, inp, unit);
103 det.appendChild(row);
104 inputs.set(f.key, inp);
105 if (f.key === "listenerElevation") {
106 const r2 = document.createElement("div");
107 r2.className = "field";
108 const l2 = document.createElement("label");
109 l2.textContent = "Radiation model";
110 const sel = document.createElement("select");
111 for (const [v, t] of [["rayleigh", "Rayleigh (baffled)"], ["dipole", "Dipole (unbaffled, approx.)"]]) {
112 const o = document.createElement("option");
113 o.value = v; o.textContent = t;
114 sel.appendChild(o);
115 }
116 sel.value = params.radiation;
117 sel.addEventListener("change", () => {
118 params.radiation = sel.value as PhysParams["radiation"];
119 applyListener();
120 });
121 r2.append(l2, sel, document.createElement("span"));
122 det.appendChild(r2);
123 inputs.set("radiation", sel);
124 }
125 if (f.key === "sigma1") {
126 const note = document.createElement("p");
127 note.className = "sub";
128 note.id = "dampNote";
129 det.appendChild(note);
130 }
131 }
132 root.appendChild(det);
133 }
134 updateDampingNote();
137function fmt(v: number): string {
138 if (v === 0) return "0";
139 const a = Math.abs(v);
140 if (a >= 1e5 || a < 1e-3) return v.toExponential(3);
141 return String(+v.toPrecision(6));
144function onFieldChange(f: FieldSpec, inp: HTMLInputElement): void {
145 const v = parseFloat(inp.value);
146 if (!isFinite(v)) return;
147 (params as unknown as Record<string, number>)[f.key] = v * f.scale;
148 if (f.key === "sigma0" || f.key === "sigma1") {
149 updateDampingNote();
150 sim?.setDamping(params.sigma0, params.sigma1);
151 }
152 if (f.key.startsWith("listener")) applyListener();
155function applyListener(): void {
156 sim?.setListener(params.listenerDist, params.listenerAzimuth, params.listenerElevation, params.radiation);
159function updateDampingNote(): void {
160 const m = makeMaterial(params);
161 const f = (hz: number) => t60(m, params, 2 * Math.PI * hz).toFixed(2);
162 $("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`;
165function setFormEnabled(enabled: boolean): void {
166 for (const g of groups) for (const f of g.fields) if (!f.live) inputs.get(f.key)!.disabled = !enabled;
169// ---------- State ----------
171let device: GPUDevice | null = null;
172let sim: Simulation | null = null;
173let renderer: Renderer | null = null;
174let running = false;
175let paused = false;
176let live = true;
177let scrubFrame = 0;
178let movieBuf: GPUBuffer | null = null;
179let movieBufFrame = -1;
180let spec = new Spectrogram({ windowSize: 2048, hop: 512, fmax: 10000, dbFloor: 80, logFrequency: false });
181const player = new Player();
182let lastStatsTime = 0, lastStatsSteps = 0, stepsPerSec = 0;
183let duration = params.duration;
185// ---------- Controls ----------
187const btnStart = mkButton("Start", "primary");
188const btnPause = mkButton("Pause");
189const btnContinue = mkButton("Continue");
190const durInput = document.createElement("input");
192function mkButton(text: string, cls = ""): HTMLButtonElement {
193 const b = document.createElement("button");
194 b.textContent = text;
195 b.className = cls;
196 return b;
199function buildControls(): void {
200 const c = $("controls");
201 const durRow = document.createElement("div");
202 durRow.className = "field";
203 durRow.style.width = "100%";
204 const l = document.createElement("label");
205 l.textContent = "Duration after release";
206 durInput.type = "number";
207 durInput.step = "0.5";
208 durInput.min = "0.1";
209 durInput.value = String(duration);
210 durInput.addEventListener("change", () => {
211 const v = parseFloat(durInput.value);
212 if (isFinite(v) && v > 0) {
213 duration = v;
214 params.duration = v;
215 sim?.setDuration(v);
216 updateButtons();
217 }
218 });
219 const u = document.createElement("span");
220 u.className = "unit";
221 u.textContent = "s";
222 durRow.append(l, durInput, u);
223 c.append(durRow, btnStart, btnPause, btnContinue);
224 btnStart.addEventListener("click", () => void start());
225 btnPause.addEventListener("click", () => {
226 paused = !paused;
227 btnPause.textContent = paused ? "Resume" : "Pause";
228 if (!paused) void runLoop();
229 });
230 btnContinue.addEventListener("click", () => {
231 if (!sim) return;
232 sim.setDuration(duration);
233 if (sim.phase !== "done") void runLoop();
234 updateButtons();
235 });
236 updateButtons();
239function updateButtons(): void {
240 const s = sim?.status();
241 btnPause.disabled = !sim || !running || s?.phase === "done";
242 btnContinue.disabled = !sim || running || !s || s.phase !== "done" || s.samples >= Math.round(duration * params.fs) - 1;
243 if (sim && sim.phase === "done" && sim.samples < sim.targetSamples()) btnContinue.disabled = false;
246// ---------- View toolbars ----------
248const viewMode = { value: "2d" as ViewMode };
249const scrub = document.createElement("input");
250const timeLabel = document.createElement("span");
251const btnLive = mkButton("Live");
252const btnPlay = mkButton("Play");
253const btnWav = mkButton("Download .wav");
254let exagInput: HTMLInputElement;
255let rangeInput: HTMLInputElement;
257function buildViewToolbar(): void {
258 const tb = $("viewToolbar");
259 const seg = document.createElement("span");
260 seg.className = "seg";
261 const b2 = mkButton("2D", "on"), b3 = mkButton("3D");
262 b2.addEventListener("click", () => { viewMode.value = "2d"; b2.classList.add("on"); b3.classList.remove("on"); });
263 b3.addEventListener("click", () => { viewMode.value = "3d"; b3.classList.add("on"); b2.classList.remove("on"); });
264 seg.append(b2, b3);
265 exagInput = numInput(4, 0.5);
266 rangeInput = numInput(0, 0.5);
267 const hint = document.createElement("span");
268 hint.className = "sub";
269 hint.style.margin = "0";
270 hint.textContent = "3D: drag to orbit, wheel to zoom";
271 tb.append(seg, labeled("Exaggeration ×", exagInput), labeled("Color range (mm, 0 = auto)", rangeInput), hint);
274function buildMovieToolbar(): void {
275 const tb = $("movieToolbar");
276 scrub.type = "range";
277 scrub.min = "0"; scrub.max = "0"; scrub.value = "0";
278 scrub.addEventListener("input", () => {
279 live = false;
280 scrubFrame = parseInt(scrub.value);
281 if (player.playing) player.stop();
282 updateLiveButton();
283 });
284 timeLabel.className = "time";
285 btnLive.addEventListener("click", () => { live = true; updateLiveButton(); });
286 btnPlay.addEventListener("click", () => {
287 if (player.playing) { player.stop(); btnPlay.textContent = "Play"; return; }
288 if (!sim || sim.samples === 0) return;
289 const offset = live ? 0 : scrubFrame / sim.fps;
290 live = false;
291 player.play(sim.processedAudio(), sim.fs, offset);
292 btnPlay.textContent = "Stop";
293 updateLiveButton();
294 });
295 player.onEnded = () => { btnPlay.textContent = "Play"; };
296 btnWav.addEventListener("click", () => {
297 if (!sim || sim.samples === 0) return;
298 const blob = encodeWav(sim.processedAudio(), sim.fs);
299 const a = document.createElement("a");
300 a.href = URL.createObjectURL(blob);
301 a.download = `sheet_${sim.samples}samples_${sim.fs}Hz.wav`;
302 a.click();
303 setTimeout(() => URL.revokeObjectURL(a.href), 5000);
304 });
305 tb.append(btnPlay, btnLive, scrub, timeLabel, btnWav);
306 updateLiveButton();
309function updateLiveButton(): void {
310 btnLive.classList.toggle("on", live);
311 btnLive.disabled = live;
314function buildSpecToolbar(): void {
315 const tb = $("specToolbar");
316 const win = document.createElement("select");
317 for (const n of [512, 1024, 2048, 4096, 8192]) {
318 const o = document.createElement("option");
319 o.value = String(n); o.textContent = String(n);
320 win.appendChild(o);
321 }
322 win.value = "2048";
323 const hop = numInput(512, 64);
324 const fmax = numInput(10000, 500);
325 const floor = numInput(80, 5);
326 const logf = document.createElement("input");
327 logf.type = "checkbox";
328 const apply = () => {
329 if (!sim) return;
330 spec.configure(
331 { 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 },
332 sim.processedAudio(), sim.samples,
333 );
334 };
335 for (const el of [win, hop, fmax, floor, logf]) el.addEventListener("change", apply);
336 tb.append(
337 document.createTextNode("Spectrogram"),
338 labeled("Window", win), labeled("Hop", hop), labeled("Max Hz", fmax), labeled("dB range", floor), labeled("Log freq.", logf),
339 );
342function numInput(v: number, step: number): HTMLInputElement {
343 const i = document.createElement("input");
344 i.type = "number"; i.value = String(v); i.step = String(step);
345 return i;
347function labeled(text: string, el: HTMLElement): HTMLLabelElement {
348 const l = document.createElement("label");
349 l.append(text, el);
350 return l;
353// ---------- Simulation control ----------
355async function start(): Promise<void> {
356 if (!device) return;
357 player.stop();
358 running = false;
359 await new Promise((r) => setTimeout(r, 0));
360 sim?.destroy();
361 spec.reset();
362 live = true;
363 paused = false;
364 btnPause.textContent = "Pause";
365 params.duration = duration;
366 sim = new Simulation(device, params);
367 renderer = new Renderer(device, $("view"), sim.grid, params);
368 movieBuf?.destroy();
369 movieBuf = device.createBuffer({ size: Math.max(16, sim.grid.n * 4), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
370 movieBufFrame = -1;
371 scrub.max = "0"; scrub.value = "0";
372 lastStatsTime = performance.now(); lastStatsSteps = 0; stepsPerSec = 0;
373 setFormEnabled(false);
374 updateLiveButton();
375 void runLoop();
378async function runLoop(): Promise<void> {
379 if (!sim || running) return;
380 running = true;
381 updateButtons();
382 try {
383 while (sim.phase !== "done" && !paused) {
384 await sim.runBatch();
385 const audio = sim.processedAudio();
386 spec.update(audio, sim.samples);
387 scrub.max = String(Math.max(0, sim.frames.length - 1));
388 if (live) scrub.value = scrub.max;
389 const now = performance.now();
390 if (now - lastStatsTime > 500) {
391 stepsPerSec = ((sim.totalSteps - lastStatsSteps) * 1000) / (now - lastStatsTime);
392 lastStatsTime = now; lastStatsSteps = sim.totalSteps;
393 }
394 }
395 } catch (e) {
396 console.error(e);
397 $("info").innerHTML = `<div class="err">Simulation error: ${String(e)}</div>`;
398 }
399 running = false;
400 setFormEnabled(sim.phase === "done" && !paused ? true : false);
401 if (sim.phase === "done") setFormEnabled(true);
402 updateButtons();
405// ---------- Render loop ----------
407let frameErrorShown = false;
408function frame(): void {
409 requestAnimationFrame(frame);
410 try {
411 frameBody();
412 } catch (e) {
413 if (!frameErrorShown) { frameErrorShown = true; console.error("frame exception:", e); }
414 }
417function frameBody(): void {
418 if (!device || !sim || !renderer) return;
419 const dev = device;
420 renderer.mode = viewMode.value;
421 renderer.exaggeration = parseFloat(exagInput.value) || 1;
422 renderer.colorRange = (parseFloat(rangeInput.value) || 0) * 1e-3;
423 const pos = player.position();
424 if (pos !== null) {
425 scrubFrame = Math.min(sim.frames.length - 1, Math.floor(pos * sim.fps));
426 scrub.value = String(scrubFrame);
427 }
428 const enc = dev.createCommandEncoder();
429 const st = sim.status();
430 if (live || sim.frames.length === 0) {
431 sim.encodeDisplay(enc);
432 renderer.render(enc, sim.displayW, st.wmax);
433 timeLabel.textContent = `${st.t >= 0 ? "" : "prep "}${st.t.toFixed(3)} s`;
434 } else {
435 const f = Math.max(0, Math.min(sim.frames.length - 1, scrubFrame));
436 if (movieBufFrame !== f) {
437 dev.queue.writeBuffer(movieBuf!, 0, sim.frames[f]);
438 movieBufFrame = f;
439 }
440 let wmax = 0;
441 const fr = sim.frames[f];
442 for (let k = 0; k < fr.length; k += 7) wmax = Math.max(wmax, Math.abs(fr[k]));
443 renderer.render(enc, movieBuf!, wmax);
444 timeLabel.textContent = `${(f / sim.fps).toFixed(3)} s`;
445 }
446 dev.pushErrorScope("validation");
447 dev.queue.submit([enc.finish()]);
448 void dev.popErrorScope().then((e) => { if (e && !frameErrorShown) { frameErrorShown = true; console.error("frame validation error:", e.message); } });
449 spec.draw($("spec"), sim.fs, Math.max(duration, sim.samples / sim.fs), pos ?? (live ? null : scrubFrame / sim.fps));
450 updateInfo(st);
453function updateInfo(st: ReturnType<Simulation["status"]>): void {
454 if (!sim) return;
455 const g = sim.grid;
456 const spl = st.peakPressure > 0 ? 20 * Math.log10(st.peakPressure / 2e-5) : -Infinity;
457 const phase = { push: "pushing", hold: "settling (held)", recording: "ringing (recording)", done: "done" }[st.phase];
458 const rows: [string, string][] = [
459 ["Phase", phase],
460 ["Time", `${st.t.toFixed(3)} s`],
461 ["Grid", `${g.nx} × ${g.ny} nodes, ${(g.hx * 1e3).toFixed(2)} × ${(g.hy * 1e3).toFixed(2)} mm`],
462 ["Time step", `${(sim.dt * 1e6).toFixed(3)} µs (${sim.stepsPerSample} per sample)`],
463 ["Speed", `${(stepsPerSec / 1e3).toFixed(0)} k steps/s (${(stepsPerSec * sim.dt).toFixed(3)}× real time)`],
464 ["Kinetic energy", `${st.ke.toExponential(2)} J`],
465 ["Max |w|", `${(st.wmax * 1e3).toFixed(3)} mm`],
466 ["Audio", `${(st.samples / sim.fs).toFixed(2)} s, ${st.frames} frames`],
467 ["Peak pressure", st.peakPressure > 0 ? `${st.peakPressure.toFixed(3)} Pa (${spl.toFixed(1)} dB SPL)` : "–"],
468 ];
469 let html = rows.map(([a, b]) => `<div class="row"><span>${a}</span><span>${b}</span></div>`).join("");
470 if (st.delayClamped) html += `<div class="warn">Listener is so close that some propagation delays were clamped.</div>`;
471 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>`;
472 $("info").innerHTML = html;
475// ---------- Init ----------
477async function init(): Promise<void> {
478 buildForm();
479 buildControls();
480 buildViewToolbar();
481 buildMovieToolbar();
482 buildSpecToolbar();
483 if (!("gpu" in navigator)) {
484 showNoGpu("WebGPU is not available in this browser. Use a recent Chrome or Edge (or Firefox / Safari with WebGPU enabled).");
485 return;
486 }
487 const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
488 if (!adapter) {
489 showNoGpu("No WebGPU adapter was found.");
490 return;
491 }
492 device = await adapter.requestDevice();
493 device.lost.then((info) => showNoGpu(`WebGPU device lost: ${info.message}`));
494 device.addEventListener("uncapturederror", (ev) => console.error("WebGPU error:", (ev as GPUUncapturedErrorEvent).error.message));
495 const g = makeGrid(params);
496 $("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>`;
497 requestAnimationFrame(frame);
498 applyUrlParams();
501/** URL parameters: any PhysParams key in SI units, plus autostart=1. Exposes the simulation on window for tests. */
502function applyUrlParams(): void {
503 const q = new URLSearchParams(location.search);
504 for (const [k, v] of q) {
505 if (k in params && k !== "radiation") {
506 const num = parseFloat(v);
507 if (isFinite(num)) {
508 (params as unknown as Record<string, number>)[k] = num;
509 const inp = inputs.get(k as keyof PhysParams);
510 const spec = groups.flatMap((g) => g.fields).find((f) => f.key === k);
511 if (inp && spec) (inp as HTMLInputElement).value = fmt(num / spec.scale);
512 }
513 }
514 if (k === "radiation" && (v === "rayleigh" || v === "dipole")) params.radiation = v;
515 if (k === "duration") {
516 duration = params.duration;
517 durInput.value = String(duration);
518 }
519 }
520 updateDampingNote();
521 (window as unknown as { steelsim: unknown }).steelsim = {
522 status: () => (sim ? { ...sim.status(), dt: sim.dt, stepsPerSample: sim.stepsPerSample, nx: sim.grid.nx, ny: sim.grid.ny, stepsPerSec } : null),
523 audio: () => (sim ? Array.from(sim.processedAudio()) : null),
524 frame: (k: number) => (sim ? Array.from(sim.frames[k] ?? []) : null),
525 frames: () => sim?.frames.length ?? 0,
526 state: async () => { if (!sim) return null; const st = await sim.readState(); return { pos: Array.from(st.pos), vel: Array.from(st.vel) }; },
527 pause: () => { paused = true; },
528 canvasInfo: () => { const c = $<HTMLCanvasElement>("view"); return { cw: c.clientWidth, ch: c.clientHeight, w: c.width, h: c.height, mode: viewMode.value }; },
529 setView: (m: ViewMode) => { viewMode.value = m; },
530 scrub: (k: number) => { live = false; scrubFrame = k; scrub.value = String(k); updateLiveButton(); },
531 };
532 if (q.get("autostart") === "1") void start();
535function showNoGpu(msg: string): void {
536 const el = $("nogpu");
537 el.hidden = false;
538 el.textContent = msg;
539 btnStart.disabled = true;
542void init();
↑↓ move↵openescclose