/ simulated_instruments / aerophone
Sign in
simulated_instruments / aerophone
aerophone / src / main.ts
486 lines · 17.5 KBCodeBlameHistory
b8aa175aerophone: 2D wind instruments with lattice Boltzmann on WebGPUJeremy Magland 1import { CELL_FLUID, CELL_MOUTH, CELL_WALL, CS, Sim } from "./sim.ts";
2import { Renderer, VIEW_MODES, type ViewMode } from "./render.ts";
3import { Geometry, PRESETS, type Preset } from "./geometry.ts";
4import { AUDIO_RATE, encodeWav, highPass, peakAbs, resample, rms, spectrum } from "./audio.ts";
5import "./style.css";
7// Physical scaling. A lattice step of dx meters moves sound c_s cells per step,
8// so dt = c_s * dx / c, and a speed U maps to U * c_s / c cells per step.
9const C_AIR = 343; // m/s
10const RHO_AIR = 1.2; // kg/m^3
11const P_SCALE = RHO_AIR * C_AIR * C_AIR; // Pa per unit relative density change
13const SPONGE = 16; // cells; absorbs a pulse as well as 40 cells did (see README)
15type Tool = "pulse" | "wall" | "erase" | "mouth" | "listener";
16const REC_CAPACITY = 1 << 22; // samples (one per step): ~7 s of sound at dx = 1 mm
17const P_MEAN_TIME = 2e-3; // s, time constant of the running-mean pressure (acoustic view)
18const MOUTH_DIRS = ["→", "←", "↑", "↓"];
20const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
22async function main() {
23 const status = $("status");
24 status.textContent = "";
25 if (!navigator.gpu) {
26 status.textContent = "WebGPU is not available in this browser.";
27 return;
28 }
29 const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
30 if (!adapter) {
31 status.textContent = "No WebGPU adapter.";
32 return;
33 }
34 const device = await adapter.requestDevice();
35 device.addEventListener("uncapturederror", (e) => {
36 status.textContent = `WebGPU error: ${(e as GPUUncapturedErrorEvent).error.message}`;
37 });
38 const canvas = $<HTMLCanvasElement>("view");
39 const context = canvas.getContext("webgpu")!;
40 const format = navigator.gpu.getPreferredCanvasFormat();
41 context.configure({ device, format, alphaMode: "opaque" });
43 const ui = {
44 run: $<HTMLButtonElement>("run"),
45 reset: $<HTMLButtonElement>("reset"),
46 blow: $<HTMLButtonElement>("blow"),
47 speed: $<HTMLInputElement>("speed"),
48 attack: $<HTMLInputElement>("attack"),
49 preset: $<HTMLSelectElement>("preset"),
50 tools: $("tools"),
51 brush: $<HTMLInputElement>("brush"),
52 mouthDir: $<HTMLSelectElement>("mouthDir"),
53 viewMode: $<HTMLSelectElement>("viewMode"),
54 spf: $<HTMLInputElement>("spf"),
55 spfOut: $("spfOut"),
56 tau: $<HTMLInputElement>("tau"),
57 smag: $<HTMLInputElement>("smag"),
58 dx: $<HTMLInputElement>("dx"),
59 pRange: $<HTMLInputElement>("pRange"),
60 aRange: $<HTMLInputElement>("aRange"),
61 rec: $<HTMLButtonElement>("rec"),
62 play: $<HTMLButtonElement>("play"),
63 download: $<HTMLButtonElement>("download"),
64 recInfo: $("recInfo"),
65 wave: $<HTMLCanvasElement>("wave"),
66 spec: $<HTMLCanvasElement>("spec"),
67 wRange: $<HTMLInputElement>("wRange"),
68 amp: $<HTMLInputElement>("amp"),
69 info: $("info"),
70 };
72 for (const p of PRESETS) ui.preset.add(new Option(p.label, p.id));
73 for (const [k, d] of MOUTH_DIRS.entries()) ui.mouthDir.add(new Option(d, String(k)));
74 for (const m of VIEW_MODES) ui.viewMode.add(new Option(m[0].toUpperCase() + m.slice(1), m));
76 // The grid (simulation, renderer, geometry) is rebuilt when a preset needs a different size.
77 let sim!: Sim;
78 let renderer!: Renderer;
79 let geom!: Geometry;
80 const setGrid = (nx: number, ny: number) => {
81 if (sim && sim.nx === nx && sim.ny === ny) return;
82 const old = sim;
83 sim = new Sim(device, {
84 nx,
85 ny,
86 tau: Math.max(0.5001, Number(ui.tau.value)),
87 spongeWidth: SPONGE,
88 spongeMax: 0.3,
89 meanRate: 2e-4,
90 pMeanRate: 1e-3,
91 recCapacity: REC_CAPACITY,
92 smagorinsky: Math.max(0, Number(ui.smag.value)),
93 });
94 renderer = new Renderer(device, context, format, sim.moments, sim.cells, nx, ny, SPONGE);
95 geom = new Geometry(nx, ny);
96 canvas.width = nx * 2;
97 canvas.height = ny * 2;
98 canvas.style.aspectRatio = `${nx} / ${ny}`;
99 canvas.style.maxWidth = `${nx * 2}px`;
100 old?.destroy();
101 };
103 const dxMeters = () => Number(ui.dx.value) / 1000;
104 const dtSeconds = () => (CS * dxMeters()) / C_AIR;
105 const toLatticeSpeed = (U: number) => (U * CS) / C_AIR;
107 let running = true;
108 ui.run.onclick = () => {
109 running = !running;
110 ui.run.textContent = running ? "Pause" : "Run";
111 };
113 // Blowing: the mouth velocity follows a smooth (raised-cosine) ramp, computed every step on the
114 // GPU, lasting the attack time in simulated time. Starting or stopping abruptly makes the mouth
115 // act like a suddenly moved piston, which radiates a click far louder than the tone.
116 let blowing = false;
117 const attackSteps = () => (Math.max(0, Number(ui.attack.value)) / 1000) / dtSeconds();
118 const updateBlow = () => sim.setBlow(blowing ? toLatticeSpeed(Number(ui.speed.value)) : 0, attackSteps());
119 const setBlowing = (on: boolean) => {
120 blowing = on;
121 ui.blow.textContent = on ? "Stop blowing" : "Blow";
122 ui.blow.classList.toggle("on", on);
123 updateBlow();
124 };
125 ui.blow.onclick = () => setBlowing(!blowing);
126 ui.speed.onchange = updateBlow;
128 const loadPreset = async (id: Preset) => {
129 const p = PRESETS.find((q) => q.id === id)!;
130 if (sim?.isRecording) await stopRecording();
131 setGrid(p.nx, p.ny);
132 geom.load(id);
133 sim.setCells(geom.cells);
134 sim.reset();
135 placeListener({ x: p.listener[0], y: p.listener[1] });
136 updateBlow();
137 };
138 ui.preset.onchange = () => void loadPreset(ui.preset.value as Preset);
139 ui.reset.onclick = () => sim.reset();
140 ui.tau.onchange = () => (sim.tau = Math.max(0.5001, Number(ui.tau.value)));
141 ui.smag.onchange = () => (sim.smagorinsky = Math.max(0, Number(ui.smag.value)));
143 let tool: Tool = "pulse";
144 ui.tools.addEventListener("click", (e) => {
145 const b = (e.target as HTMLElement).closest("button");
146 if (!b?.dataset.tool) return;
147 tool = b.dataset.tool as Tool;
148 for (const el of ui.tools.querySelectorAll("button")) el.classList.toggle("on", el === b);
149 });
151 // Pointer: pulse tool clicks; paint tools drag.
152 const cellAt = (e: PointerEvent) => {
153 const r = canvas.getBoundingClientRect();
154 return { x: ((e.clientX - r.left) / r.width) * sim.nx, y: (1 - (e.clientY - r.top) / r.height) * sim.ny };
155 };
156 const paintType = () => (tool === "wall" ? CELL_WALL : tool === "mouth" ? CELL_MOUTH + Number(ui.mouthDir.value) : CELL_FLUID);
157 let last: { x: number; y: number } | null = null;
158 const listener = { x: 110, y: 200 };
159 const placeListener = (p: { x: number; y: number }) => {
160 listener.x = Math.min(sim.nx - 1, Math.max(0, Math.floor(p.x)));
161 listener.y = Math.min(sim.ny - 1, Math.max(0, Math.floor(p.y)));
162 sim.setListener(listener.x, listener.y);
163 };
164 let dragListener = false;
165 canvas.addEventListener("pointerdown", (e) => {
166 const p = cellAt(e);
167 if (tool === "listener") {
168 canvas.setPointerCapture(e.pointerId);
169 placeListener(p);
170 dragListener = true;
171 return;
172 }
173 if (tool === "pulse") {
174 sim.addPulse(p.x, p.y, Number(ui.amp.value) / P_SCALE, 3);
175 return;
176 }
177 canvas.setPointerCapture(e.pointerId);
178 geom.paint(p.x, p.y, Number(ui.brush.value), paintType());
179 sim.setCells(geom.cells);
180 last = p;
181 });
182 canvas.addEventListener("pointermove", (e) => {
183 if (dragListener) placeListener(cellAt(e));
184 if (!last) return;
185 const p = cellAt(e);
186 geom.paintLine(last.x, last.y, p.x, p.y, Number(ui.brush.value), paintType());
187 sim.setCells(geom.cells);
188 last = p;
189 });
190 const endPaint = () => {
191 last = null;
192 dragListener = false;
193 };
194 canvas.addEventListener("pointerup", endPaint);
195 canvas.addEventListener("pointercancel", endPaint);
197 // Throughput and slow-motion factor, averaged over ~1 s.
198 let tWin = performance.now();
199 let stepsWin = 0;
200 let mlups = 0;
201 let slow = 0;
203 const render = () => {
204 const enc = device.createCommandEncoder();
205 const dt = dtSeconds();
206 renderer.encode(enc, ui.viewMode.value as ViewMode, {
207 pressure: Number(ui.pRange.value) / P_SCALE / 3,
208 acoustic: Number(ui.aRange.value) / P_SCALE / 3,
209 vorticity: Number(ui.wRange.value) * dt,
210 speed: Math.max(toLatticeSpeed(Number(ui.speed.value)) * 1.2, 1e-4),
211 }, listener);
212 device.queue.submit([enc.finish()]);
213 };
215 // Recording at the listener: one sample per step on the GPU, read back when stopped,
216 // resampled to 48 kHz, high-passed at 20 Hz, and normalized for playback.
217 let recDt = dtSeconds();
218 let recSteps = 0; // steps simulated since recording started (CPU-side count)
219 let lastRaw: Float32Array = new Float32Array(0); // for re-processing from the console
220 let take: { audio: Float32Array; norm: Float32Array<ArrayBuffer> } | null = null;
221 const startRecording = () => {
222 recDt = dtSeconds();
223 recSteps = 0;
224 sim.startRecording();
225 ui.rec.textContent = "Stop recording";
226 ui.rec.classList.add("on");
227 };
228 const stopRecording = async () => {
229 sim.stopRecording();
230 ui.rec.textContent = "Record";
231 ui.rec.classList.remove("on");
232 await processRecording();
233 };
234 ui.rec.onclick = () => (sim.isRecording ? stopRecording() : startRecording());
236 const processRecording = async () => {
237 const raw = await sim.readRecording();
238 if (raw.length < 2) {
239 ui.recInfo.textContent = "Nothing recorded (is the listener on a wall, or the simulation paused?)";
240 take = null;
241 return;
242 }
243 const pa = raw.map((v) => v * P_SCALE);
244 const audio = highPass(resample(pa, 1 / recDt, AUDIO_RATE), AUDIO_RATE, 20);
245 const pk = peakAbs(audio);
246 const norm = new Float32Array(audio.length);
247 for (let k = 0; k < audio.length; k++) norm[k] = pk > 0 ? (0.9 * audio[k]) / pk : 0;
248 take = { audio, norm };
249 lastRaw = raw;
250 const sp = spectrum(audio, AUDIO_RATE);
251 let kPeak = -1;
252 for (let k = 0; k < sp.freq.length; k++)
253 if (sp.freq[k] >= 40 && sp.freq[k] <= 15000 && (kPeak < 0 || sp.db[k] > sp.db[kPeak])) kPeak = k;
254 const f0 = kPeak >= 0 ? sp.freq[kPeak] : 0;
255 const r = rms(audio);
256 ui.recInfo.textContent =
257 `${(audio.length / AUDIO_RATE).toFixed(3)} s (${raw.length} steps) · ` +
258 `rms ${r.toFixed(2)} Pa (${(20 * Math.log10(r / 2e-5)).toFixed(0)} dB SPL in 2D) · ` +
259 `peak ${pk.toFixed(1)} Pa · spectral peak ${f0.toFixed(0)} Hz (${noteName(f0)}) · ` +
260 `playback gain ${(20 * Math.log10(0.9 / Math.max(pk, 1e-12))).toFixed(0)} dB re 1 Pa`;
261 drawWave(ui.wave, audio);
262 drawSpectrum(ui.spec, sp, f0);
263 };
265 let audioCtx: AudioContext | null = null;
266 let playing: AudioBufferSourceNode | null = null;
267 ui.play.onclick = () => {
268 if (!take) return;
269 if (playing) {
270 playing.stop();
271 return;
272 }
273 audioCtx ??= new AudioContext();
274 void audioCtx.resume();
275 const buf = audioCtx.createBuffer(1, take.norm.length, AUDIO_RATE);
276 buf.copyToChannel(take.norm, 0);
277 const src = audioCtx.createBufferSource();
278 src.buffer = buf;
279 src.connect(audioCtx.destination);
280 src.onended = () => {
281 playing = null;
282 ui.play.textContent = "Play";
283 };
284 src.start();
285 playing = src;
286 ui.play.textContent = "Stop";
287 };
288 ui.download.onclick = () => {
289 if (!take) return;
290 const a = document.createElement("a");
291 a.href = URL.createObjectURL(encodeWav(take.norm, AUDIO_RATE));
292 a.download = `aerophone-${ui.preset.value}.wav`;
293 a.click();
294 setTimeout(() => URL.revokeObjectURL(a.href), 1000);
295 };
297 // Benchmark from the console: aerophone.bench(). Runs `steps` steps without drawing (pause first
298 // for a clean number) and reports throughput and the slow-motion factor at the current dx.
299 const bench = async (steps = 30000) => {
300 await device.queue.onSubmittedWorkDone();
301 const t0 = performance.now();
302 for (let done = 0; done < steps; done += 1000) {
303 const enc = device.createCommandEncoder();
304 sim.encodeSteps(enc, 1000);
305 device.queue.submit([enc.finish()]);
306 if (done % 10000 === 0) await device.queue.onSubmittedWorkDone();
307 }
308 await device.queue.onSubmittedWorkDone();
309 const wall = (performance.now() - t0) / 1000;
310 const steps1000 = Math.ceil(steps / 1000) * 1000;
311 return {
312 grid: `${sim.nx} x ${sim.ny}`,
313 mlups: Math.round((steps1000 * sim.N) / wall / 1e6),
314 slowerThanRealTime: +(wall / (steps1000 * dtSeconds())).toFixed(1),
315 };
316 };
318 // For inspection from the console.
319 const debug = {
320 bench,
321 get sim() {
322 return sim;
323 },
324 get geom() {
325 return geom;
326 },
327 listener,
328 P_SCALE,
329 dtSeconds,
330 toLatticeSpeed,
331 setBlowing,
332 loadPreset,
333 render,
334 placeListener,
335 startRecording,
336 stopRecording,
337 processRecording,
338 get lastRaw() {
339 return lastRaw;
340 },
341 get take() {
342 return take;
343 },
344 get blowing() {
345 return blowing;
346 },
347 };
348 (window as unknown as { aerophone: typeof debug }).aerophone = debug;
350 await loadPreset(PRESETS[0].id);
351 ui.preset.value = PRESETS[0].id;
353 // Each frame submits one batch of steps, unless two are already queued on the GPU. Keeping a
354 // second batch queued means the GPU never waits for the next animation frame.
355 let inFlight = 0;
356 const frame = () => {
357 const spf = Number(ui.spf.value);
358 ui.spfOut.textContent = String(spf);
359 const U = Number(ui.speed.value);
360 if (running && inFlight < 2) {
361 const enc = device.createCommandEncoder();
362 sim.pMeanRate = dtSeconds() / P_MEAN_TIME;
363 sim.encodeSteps(enc, spf);
364 device.queue.submit([enc.finish()]);
365 inFlight++;
366 void device.queue.onSubmittedWorkDone().then(() => inFlight--);
367 stepsWin += spf;
368 if (sim.isRecording) {
369 recSteps += spf;
370 ui.recInfo.textContent = `recording… ${(recSteps * recDt).toFixed(3)} s of sound`;
371 if (recSteps >= sim.recCapacity) void stopRecording();
372 }
373 }
374 render();
375 const dt = dtSeconds();
377 const now = performance.now();
378 if (now - tWin > 1000) {
379 const wall = (now - tWin) / 1000;
380 mlups = (stepsWin * sim.N) / wall / 1e6;
381 slow = stepsWin > 0 ? wall / (stepsWin * dt) : 0;
382 tWin = now;
383 stepsWin = 0;
384 }
385 const nu = ((sim.tau - 0.5) / 3) * (dxMeters() * dxMeters()) / dt;
386 const re = (U * 10 * dxMeters()) / nu;
387 ui.info.textContent =
388 `t = ${(sim.stepCount * dt * 1000).toFixed(2)} ms · ${mlups.toFixed(0)} MLUPS · ` +
389 `${slow > 0 ? slow.toFixed(0) + "× slower than real time" : "paused"} · ` +
390 `domain ${(sim.nx * dxMeters() * 100).toFixed(1)} × ${(sim.ny * dxMeters() * 100).toFixed(1)} cm (${sim.nx} × ${sim.ny}) · ` +
391 `ν = ${nu.toExponential(1)} m²/s (air 1.5e-5) · Re (10-cell windway) ≈ ${re.toFixed(0)} · ` +
392 `blowing ${(sim.blowVelocityAt() / toLatticeSpeed(1)).toFixed(1)} m/s (Mach ${(sim.blowVelocityAt() / toLatticeSpeed(C_AIR)).toFixed(3)})`;
393 requestAnimationFrame(frame);
394 };
395 requestAnimationFrame(frame);
398const NOTES = ["C", "C♯", "D", "E♭", "E", "F", "F♯", "G", "A♭", "A", "B♭", "B"];
399function noteName(f: number) {
400 if (!(f > 0)) return "–";
401 const m = 69 + 12 * Math.log2(f / 440);
402 const r = Math.round(m);
403 const cents = Math.round(100 * (m - r));
404 return `${NOTES[((r % 12) + 12) % 12]}${Math.floor(r / 12) - 1} ${cents >= 0 ? "+" : ""}${cents}¢`;
407function plotContext(c: HTMLCanvasElement) {
408 const dpr = window.devicePixelRatio || 1;
409 const w = c.clientWidth;
410 const h = c.clientHeight;
411 c.width = Math.round(w * dpr);
412 c.height = Math.round(h * dpr);
413 const g = c.getContext("2d")!;
414 g.setTransform(dpr, 0, 0, dpr, 0, 0);
415 g.fillStyle = "#16181d";
416 g.fillRect(0, 0, w, h);
417 g.font = "11px system-ui, sans-serif";
418 return { g, w, h };
421// Waveform: min/max per pixel column, in Pa.
422function drawWave(c: HTMLCanvasElement, x: Float32Array) {
423 const { g, w, h } = plotContext(c);
424 const pk = Math.max(peakAbs(x), 1e-12);
425 g.strokeStyle = "#e0884a";
426 g.beginPath();
427 for (let px = 0; px < w; px++) {
428 const k0 = Math.floor((px * x.length) / w);
429 const k1 = Math.max(k0 + 1, Math.floor(((px + 1) * x.length) / w));
430 let lo = Infinity;
431 let hi = -Infinity;
432 for (let k = k0; k < k1 && k < x.length; k++) {
433 lo = Math.min(lo, x[k]);
434 hi = Math.max(hi, x[k]);
435 }
436 g.moveTo(px + 0.5, h / 2 - (hi / pk) * (h / 2 - 4));
437 g.lineTo(px + 0.5, h / 2 - (lo / pk) * (h / 2 - 4) + 1);
438 }
439 g.stroke();
440 g.fillStyle = "#8a909a";
441 g.fillText(`±${pk.toFixed(1)} Pa`, 6, 13);
442 g.fillText(`${(x.length / AUDIO_RATE).toFixed(3)} s`, w - 50, h - 6);
445// Spectrum on a log frequency axis (40 Hz to 20 kHz), 80 dB range.
446function drawSpectrum(c: HTMLCanvasElement, sp: { freq: Float64Array; db: Float64Array }, f0: number) {
447 const { g, w, h } = plotContext(c);
448 const fmin = 40;
449 const fmax = 20000;
450 const X = (f: number) => (Math.log(f / fmin) / Math.log(fmax / fmin)) * w;
451 let top = -Infinity;
452 for (let k = 0; k < sp.db.length; k++) if (sp.freq[k] >= fmin) top = Math.max(top, sp.db[k]);
453 const Y = (d: number) => ((top - d) / 80) * (h - 16) + 4;
454 g.strokeStyle = "#2a2e36";
455 g.fillStyle = "#8a909a";
456 for (const f of [100, 1000, 10000]) {
457 g.beginPath();
458 g.moveTo(X(f), 0);
459 g.lineTo(X(f), h);
460 g.stroke();
461 g.fillText(f >= 1000 ? `${f / 1000} kHz` : `${f} Hz`, X(f) + 3, h - 4);
462 }
463 g.strokeStyle = "#6fb3e8";
464 g.beginPath();
465 let started = false;
466 for (let k = 0; k < sp.freq.length; k++) {
467 const f = sp.freq[k];
468 if (f < fmin || f > fmax) continue;
469 const y = Math.min(h, Y(sp.db[k]));
470 if (started) g.lineTo(X(f), y);
471 else g.moveTo(X(f), y);
472 started = true;
473 }
474 g.stroke();
475 if (f0 > 0) {
476 g.strokeStyle = "#e0884a";
477 g.beginPath();
478 g.moveTo(X(f0), 0);
479 g.lineTo(X(f0), h);
480 g.stroke();
481 g.fillStyle = "#e0884a";
482 g.fillText(`${f0.toFixed(0)} Hz`, X(f0) + 4, 13);
483 }
486main();
↑↓ move↵openescclose