/ proof-of-concept / steelsim21
Sign in
proof-of-concept / steelsim21
steelsim21 / src / main.ts
688 lines · 26.8 KBBlameHistoryRaw
1// UI wiring: parameters, run loop, live and movie views, playback, downloads.
3import { defaultParams, makeGrid, makeMaterial, t60, type BowShape, type Excitation, 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";
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 {
38 title: "Excitation: push and release",
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 },
45 { key: "releaseTime", label: "Release time", unit: "ms", scale: 1e-3, step: 1 },
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 },
50 {
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 },
63 {
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 },
68 {
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 },
74 { key: "sigmaIn", label: "In-plane loss", unit: "1/s", scale: 1, step: 5, live: true },
75 ],
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");
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);
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 }
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 }
181 if (f.key === "sigmaIn") {
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;
204 if (f.key === "sigma0" || f.key === "sigma1" || f.key === "sigmaIn") {
205 updateDampingNote();
206 sim?.setDamping(params.sigma0, params.sigma1, params.sigmaIn);
207 }
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;
223 inputs.get("bowShape")!.disabled = !enabled;
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;
238let spec = new Spectrogram({ windowSize: 2048, hop: 512, fmax: 5000, dbFloor: 80, logFrequency: false });
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");
247const btnStop = mkButton("Stop");
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");
264 l.textContent = "Recorded duration";
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);
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 });
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();
310 btnPause.disabled = !sim || s?.phase === "done" || (!running && !paused);
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");
323const levelSel = document.createElement("select");
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)";
343let exagInput: HTMLInputElement;
344let rangeInput: HTMLInputElement;
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";
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(); });
378 btnPlay.addEventListener("click", () => {
379 if (player.playing) { player.stop(); btnPlay.textContent = "Play"; return; }
380 if (!sim || sim.samples === 0) return;
381 const offset = live ? 0 : scrubFrame / sim.fps;
382 live = false;
383 player.play(sim.processedAudio(), sim.fs, offset, levelSel.value as LevelMode, gainDb());
384 btnPlay.textContent = "Stop";
385 updateLiveButton();
386 });
387 player.onEnded = () => { btnPlay.textContent = "Play"; };
388 btnWav.addEventListener("click", () => {
389 if (!sim || sim.samples === 0) return;
390 const blob = encodeWav(sim.processedAudio(), sim.fs, levelSel.value as LevelMode, gainDb());
391 const a = document.createElement("a");
392 a.href = URL.createObjectURL(blob);
393 a.download = `sheet_${sim.samples}samples_${sim.fs}Hz.wav`;
394 a.click();
395 setTimeout(() => URL.revokeObjectURL(a.href), 5000);
396 });
397 for (const [v, t] of [["absolute", "Absolute (0 dBFS = 1 Pa at 0 dB)"], ["loudness", "Loudness (RMS, soft clip)"], ["peak", "Peak"]]) {
398 const o = document.createElement("option");
399 o.value = v; o.textContent = t;
400 levelSel.appendChild(o);
401 }
402 gainSlider.type = "range";
403 gainSlider.min = "-40"; gainSlider.max = "60"; gainSlider.step = "1"; gainSlider.value = "20";
404 gainSlider.style.width = "120px";
405 gainSlider.style.flex = "none";
406 const restart = () => {
407 updateLevelReadout();
408 const pos = player.position();
409 if (pos !== null && sim) player.play(sim.processedAudio(), sim.fs, pos, levelSel.value as LevelMode, gainDb());
410 };
411 gainSlider.addEventListener("input", restart);
412 levelSel.addEventListener("change", restart);
413 tb.append(btnPlay, btnLive, scrub, timeLabel, labeled("Level", levelSel), labeled("Gain", gainSlider), gainLabel, peakLabel, btnWav);
414 updateLevelReadout();
415 updateLiveButton();
418function updateLiveButton(): void {
419 btnLive.classList.toggle("on", live);
420 btnLive.disabled = live;
423function buildSpecToolbar(): void {
424 const tb = $("specToolbar");
425 const win = document.createElement("select");
426 for (const n of [512, 1024, 2048, 4096, 8192]) {
427 const o = document.createElement("option");
428 o.value = String(n); o.textContent = String(n);
429 win.appendChild(o);
430 }
431 win.value = "2048";
432 const hop = numInput(512, 64);
433 const fmax = numInput(5000, 500);
434 const floor = numInput(80, 5);
435 const logf = document.createElement("input");
436 logf.type = "checkbox";
437 const apply = () => {
438 if (!sim) return;
439 spec.configure(
440 { 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 },
441 sim.processedAudio(), sim.samples,
442 );
443 };
444 for (const el of [win, hop, fmax, floor, logf]) el.addEventListener("change", apply);
445 tb.append(
446 document.createTextNode("Spectrogram"),
447 labeled("Window", win), labeled("Hop", hop), labeled("Max Hz", fmax), labeled("dB range", floor), labeled("Log freq.", logf),
448 );
451function numInput(v: number, step: number): HTMLInputElement {
452 const i = document.createElement("input");
453 i.type = "number"; i.value = String(v); i.step = String(step);
454 return i;
456function labeled(text: string, el: HTMLElement): HTMLLabelElement {
457 const l = document.createElement("label");
458 l.append(text, el);
459 return l;
462// ---------- Simulation control ----------
464async function start(): Promise<void> {
465 if (!device) return;
466 player.stop();
467 running = false;
468 await new Promise((r) => setTimeout(r, 0));
469 sim?.destroy();
470 spec.reset();
471 live = true;
472 paused = false;
473 btnPause.textContent = "Pause";
474 params.duration = duration;
475 sim = new Simulation(device, params);
476 renderer = new Renderer(device, $("view"), sim.grid, params, sim.w0);
477 movieBuf?.destroy();
478 movieBuf = device.createBuffer({ size: Math.max(16, sim.grid.n * 4), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
479 movieBufFrame = -1;
480 scrub.max = "0"; scrub.value = "0";
481 lastStatsTime = performance.now(); lastStatsSteps = 0; stepsPerSec = 0;
482 setFormEnabled(false);
483 updateLiveButton();
484 void runLoop();
487async function runLoop(): Promise<void> {
488 if (!sim || running) return;
489 running = true;
490 updateButtons();
491 try {
492 while (sim.phase !== "done" && !paused) {
493 await sim.runBatch();
494 const audio = sim.processedAudio();
495 spec.update(audio, sim.samples);
496 scrub.max = String(Math.max(0, sim.frames.length - 1));
497 if (live) scrub.value = scrub.max;
498 updateLevelReadout();
499 const now = performance.now();
500 if (now - lastStatsTime > 500) {
501 stepsPerSec = ((sim.totalSteps - lastStatsSteps) * 1000) / (now - lastStatsTime);
502 lastStatsTime = now; lastStatsSteps = sim.totalSteps;
503 }
504 }
505 } catch (e) {
506 console.error(e);
507 $("info").innerHTML = `<div class="err">Simulation error: ${String(e)}</div>`;
508 }
509 running = false;
510 if (sim.phase === "done") setFormEnabled(true);
511 updateButtons();
514// ---------- Render loop ----------
516let frameErrorShown = false;
517function frame(): void {
518 requestAnimationFrame(frame);
519 try {
520 frameBody();
521 } catch (e) {
522 if (!frameErrorShown) { frameErrorShown = true; console.error("frame exception:", e); }
523 }
526let lastRenderKey = "";
527function frameBody(): void {
528 if (!device || !sim || !renderer) return;
529 const dev = device;
530 renderer.mode = viewMode.value;
531 renderer.exaggeration = parseFloat(exagInput.value) || 1;
532 renderer.colorRange = (parseFloat(rangeInput.value) || 0) * 1e-3;
533 renderer.showShape = shapeCheck.checked;
534 const pos = player.position();
535 if (pos !== null) {
536 scrubFrame = Math.min(sim.frames.length - 1, Math.floor(pos * sim.fps));
537 scrub.value = String(scrubFrame);
538 }
539 const st = sim.status();
540 // Render only when something visible changed, so an idle or paused page does no work.
541 const canvas = $<HTMLCanvasElement>("view");
542 const cam = renderer.camera;
543 const renderKey = [
544 renderer.mode, renderer.exaggeration, renderer.colorRange, renderer.showShape,
545 cam.yaw.toFixed(4), cam.pitch.toFixed(4), cam.dist.toFixed(4),
546 live, scrubFrame, sim.frames.length, st.totalSteps, st.phase,
547 canvas.clientWidth, canvas.clientHeight, window.devicePixelRatio,
548 ].join("|");
549 if (renderKey !== lastRenderKey) {
550 lastRenderKey = renderKey;
551 renderView(dev, st);
552 }
553 spec.draw($("spec"), sim.fs, Math.max(duration, sim.samples / sim.fs), pos ?? (live ? null : scrubFrame / sim.fps));
554 updateInfo(st);
557function renderView(dev: GPUDevice, st: ReturnType<Simulation["status"]>): void {
558 if (!sim || !renderer) return;
559 const enc = dev.createCommandEncoder();
560 if (live || sim.frames.length === 0) {
561 sim.encodeDisplay(enc);
562 renderer.render(enc, sim.displayW, st.wmax);
563 timeLabel.textContent = `${st.t >= 0 ? "" : "prep "}${st.t.toFixed(3)} s`;
564 } else {
565 const f = Math.max(0, Math.min(sim.frames.length - 1, scrubFrame));
566 if (movieBufFrame !== f) {
567 dev.queue.writeBuffer(movieBuf!, 0, sim.frames[f]);
568 movieBufFrame = f;
569 }
570 let wmax = 0;
571 const fr = sim.frames[f];
572 for (let k = 0; k < fr.length; k += 7) wmax = Math.max(wmax, Math.abs(fr[k]));
573 renderer.render(enc, movieBuf!, wmax);
574 timeLabel.textContent = `${(f / sim.fps).toFixed(3)} s`;
575 }
576 dev.pushErrorScope("validation");
577 dev.queue.submit([enc.finish()]);
578 void dev.popErrorScope().then((e) => { if (e && !frameErrorShown) { frameErrorShown = true; console.error("frame validation error:", e.message); } });
581function updateInfo(st: ReturnType<Simulation["status"]>): void {
582 if (!sim) return;
583 const g = sim.grid;
584 const spl = st.peakPressure > 0 ? 20 * Math.log10(st.peakPressure / 2e-5) : -Infinity;
585 const phase = { push: "pushing", hold: "settling (held)", recording: "ringing (recording)", done: "done" }[st.phase];
586 const stickHook = (window as unknown as { steelsim?: { stick?: unknown } }).steelsim;
587 if (stickHook) stickHook.stick = st.stick;
588 const rows: [string, string][] = [
589 ["Phase", phase],
590 ["Time", `${st.t.toFixed(3)} s`],
591 ["Grid", `${g.nx} × ${g.ny} nodes, ${(g.hx * 1e3).toFixed(2)} × ${(g.hy * 1e3).toFixed(2)} mm`],
592 ["Time step", `${(sim.dt * 1e6).toFixed(3)} µs (${sim.stepsPerSample} per sample)`],
593 ["Speed", `${(stepsPerSec / 1e3).toFixed(0)} k steps/s (${(stepsPerSec * sim.dt).toFixed(3)}× real time)`],
594 ["Kinetic energy", `${st.ke.toExponential(2)} J`],
595 ["Max |w|", `${(st.wmax * 1e3).toFixed(3)} mm`],
596 ["Audio", `${(st.samples / sim.fs).toFixed(2)} s, ${st.frames} frames`],
597 ["Peak pressure", st.peakPressure > 0 ? `${st.peakPressure.toFixed(3)} Pa (${spl.toFixed(1)} dB SPL)` : "–"],
598 ];
599 if (st.stick) {
600 rows.push(["Stick", `${(st.stick.x * 1e3).toFixed(2)} mm, ${st.stick.v.toFixed(2)} m/s`]);
601 rows.push(["Contact force", `${st.stick.force.toFixed(1)} N (max ${st.stick.maxForce.toFixed(1)} N)`]);
602 }
603 let html = rows.map(([a, b]) => `<div class="row"><span>${a}</span><span>${b}</span></div>`).join("");
604 if (st.delayClamped) html += `<div class="warn">Listener is so close that some propagation delays were clamped.</div>`;
605 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>`;
606 if (html !== lastInfoHtml) {
607 lastInfoHtml = html;
608 $("info").innerHTML = html;
609 }
611let lastInfoHtml = "";
613// ---------- Init ----------
615async function init(): Promise<void> {
616 buildForm();
617 buildControls();
618 buildViewToolbar();
619 buildMovieToolbar();
620 buildSpecToolbar();
621 if (!("gpu" in navigator)) {
622 showNoGpu("WebGPU is not available in this browser. Use a recent Chrome or Edge (or Firefox / Safari with WebGPU enabled).");
623 return;
624 }
625 const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
626 if (!adapter) {
627 showNoGpu("No WebGPU adapter was found.");
628 return;
629 }
630 device = await adapter.requestDevice();
631 device.lost.then((info) => showNoGpu(`WebGPU device lost: ${info.message}`));
632 device.addEventListener("uncapturederror", (ev) => console.error("WebGPU error:", (ev as GPUUncapturedErrorEvent).error.message));
633 const g = makeGrid(params);
634 $("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>`;
635 requestAnimationFrame(frame);
636 applyUrlParams();
639/** URL parameters: any PhysParams key in SI units, plus autostart=1. Exposes the simulation on window for tests. */
640function applyUrlParams(): void {
641 const q = new URLSearchParams(location.search);
642 for (const [k, v] of q) {
643 if (k in params && k !== "radiation" && k !== "bowShape" && k !== "excitation") {
644 const num = parseFloat(v);
645 if (isFinite(num)) {
646 (params as unknown as Record<string, number>)[k] = num;
647 const inp = inputs.get(k as keyof PhysParams);
648 const spec = groups.flatMap((g) => g.fields).find((f) => f.key === k);
649 if (inp && spec) (inp as HTMLInputElement).value = fmt(num / spec.scale);
650 }
651 }
652 if (k === "radiation" && (v === "rayleigh" || v === "dipole")) params.radiation = v;
653 if (k === "excitation" && (v === "push" || v === "strike")) {
654 params.excitation = v;
655 (inputs.get("excitation") as HTMLSelectElement).value = v;
656 }
657 if (k === "bowShape" && ["none", "width", "height", "dish"].includes(v)) {
658 params.bowShape = v as BowShape;
659 (inputs.get("bowShape") as HTMLSelectElement).value = v;
660 }
661 if (k === "duration") {
662 duration = params.duration;
663 durInput.value = String(duration);
664 }
665 }
666 updateDampingNote();
667 (window as unknown as { steelsim: unknown }).steelsim = {
668 status: () => (sim ? { ...sim.status(), dt: sim.dt, stepsPerSample: sim.stepsPerSample, nx: sim.grid.nx, ny: sim.grid.ny, stepsPerSec } : null),
669 audio: () => (sim ? Array.from(sim.processedAudio()) : null),
670 frame: (k: number) => (sim ? Array.from(sim.frames[k] ?? []) : null),
671 frames: () => sim?.frames.length ?? 0,
672 state: async () => { if (!sim) return null; const st = await sim.readState(); return { pos: Array.from(st.pos), vel: Array.from(st.vel) }; },
673 pause: () => { paused = true; },
674 canvasInfo: () => { const c = $<HTMLCanvasElement>("view"); return { cw: c.clientWidth, ch: c.clientHeight, w: c.width, h: c.height, mode: viewMode.value }; },
675 setView: (m: ViewMode) => { viewMode.value = m; },
676 scrub: (k: number) => { live = false; scrubFrame = k; scrub.value = String(k); updateLiveButton(); },
677 };
678 if (q.get("autostart") === "1") void start();
681function showNoGpu(msg: string): void {
682 const el = $("nogpu");
683 el.hidden = false;
684 el.textContent = msg;
685 btnStart.disabled = true;
688void init();
↑↓ move↵openescclose