import { CELL_FLUID, CELL_MOUTH, CELL_WALL, CS, Sim } from "./sim.ts"; import { Renderer, VIEW_MODES, type ViewMode } from "./render.ts"; import { Geometry, PRESETS, type Preset } from "./geometry.ts"; import { AUDIO_RATE, encodeWav, highPass, peakAbs, resample, rms, spectrum } from "./audio.ts"; import "./style.css"; // Physical scaling. A lattice step of dx meters moves sound c_s cells per step, // so dt = c_s * dx / c, and a speed U maps to U * c_s / c cells per step. const C_AIR = 343; // m/s const RHO_AIR = 1.2; // kg/m^3 const P_SCALE = RHO_AIR * C_AIR * C_AIR; // Pa per unit relative density change const SPONGE = 16; // cells; absorbs a pulse as well as 40 cells did (see README) type Tool = "pulse" | "wall" | "erase" | "mouth" | "listener"; const REC_CAPACITY = 1 << 22; // samples (one per step): ~7 s of sound at dx = 1 mm const P_MEAN_TIME = 2e-3; // s, time constant of the running-mean pressure (acoustic view) const MOUTH_DIRS = ["→", "←", "↑", "↓"]; const $ = (id: string) => document.getElementById(id) as T; async function main() { const status = $("status"); status.textContent = ""; if (!navigator.gpu) { status.textContent = "WebGPU is not available in this browser."; return; } const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" }); if (!adapter) { status.textContent = "No WebGPU adapter."; return; } const device = await adapter.requestDevice(); device.addEventListener("uncapturederror", (e) => { status.textContent = `WebGPU error: ${(e as GPUUncapturedErrorEvent).error.message}`; }); const canvas = $("view"); const context = canvas.getContext("webgpu")!; const format = navigator.gpu.getPreferredCanvasFormat(); context.configure({ device, format, alphaMode: "opaque" }); const ui = { run: $("run"), reset: $("reset"), blow: $("blow"), speed: $("speed"), attack: $("attack"), preset: $("preset"), tools: $("tools"), brush: $("brush"), mouthDir: $("mouthDir"), viewMode: $("viewMode"), spf: $("spf"), spfOut: $("spfOut"), tau: $("tau"), smag: $("smag"), dx: $("dx"), pRange: $("pRange"), aRange: $("aRange"), rec: $("rec"), play: $("play"), download: $("download"), recInfo: $("recInfo"), wave: $("wave"), spec: $("spec"), wRange: $("wRange"), amp: $("amp"), info: $("info"), }; for (const p of PRESETS) ui.preset.add(new Option(p.label, p.id)); for (const [k, d] of MOUTH_DIRS.entries()) ui.mouthDir.add(new Option(d, String(k))); for (const m of VIEW_MODES) ui.viewMode.add(new Option(m[0].toUpperCase() + m.slice(1), m)); // The grid (simulation, renderer, geometry) is rebuilt when a preset needs a different size. let sim!: Sim; let renderer!: Renderer; let geom!: Geometry; const setGrid = (nx: number, ny: number) => { if (sim && sim.nx === nx && sim.ny === ny) return; const old = sim; sim = new Sim(device, { nx, ny, tau: Math.max(0.5001, Number(ui.tau.value)), spongeWidth: SPONGE, spongeMax: 0.3, meanRate: 2e-4, pMeanRate: 1e-3, recCapacity: REC_CAPACITY, smagorinsky: Math.max(0, Number(ui.smag.value)), }); renderer = new Renderer(device, context, format, sim.moments, sim.cells, nx, ny, SPONGE); geom = new Geometry(nx, ny); canvas.width = nx * 2; canvas.height = ny * 2; canvas.style.aspectRatio = `${nx} / ${ny}`; canvas.style.maxWidth = `${nx * 2}px`; old?.destroy(); }; const dxMeters = () => Number(ui.dx.value) / 1000; const dtSeconds = () => (CS * dxMeters()) / C_AIR; const toLatticeSpeed = (U: number) => (U * CS) / C_AIR; let running = true; ui.run.onclick = () => { running = !running; ui.run.textContent = running ? "Pause" : "Run"; }; // Blowing: the mouth velocity follows a smooth (raised-cosine) ramp, computed every step on the // GPU, lasting the attack time in simulated time. Starting or stopping abruptly makes the mouth // act like a suddenly moved piston, which radiates a click far louder than the tone. let blowing = false; const attackSteps = () => (Math.max(0, Number(ui.attack.value)) / 1000) / dtSeconds(); const updateBlow = () => sim.setBlow(blowing ? toLatticeSpeed(Number(ui.speed.value)) : 0, attackSteps()); const setBlowing = (on: boolean) => { blowing = on; ui.blow.textContent = on ? "Stop blowing" : "Blow"; ui.blow.classList.toggle("on", on); updateBlow(); }; ui.blow.onclick = () => setBlowing(!blowing); ui.speed.onchange = updateBlow; const loadPreset = async (id: Preset) => { const p = PRESETS.find((q) => q.id === id)!; if (sim?.isRecording) await stopRecording(); setGrid(p.nx, p.ny); geom.load(id); sim.setCells(geom.cells); sim.reset(); placeListener({ x: p.listener[0], y: p.listener[1] }); updateBlow(); }; ui.preset.onchange = () => void loadPreset(ui.preset.value as Preset); ui.reset.onclick = () => sim.reset(); ui.tau.onchange = () => (sim.tau = Math.max(0.5001, Number(ui.tau.value))); ui.smag.onchange = () => (sim.smagorinsky = Math.max(0, Number(ui.smag.value))); let tool: Tool = "pulse"; ui.tools.addEventListener("click", (e) => { const b = (e.target as HTMLElement).closest("button"); if (!b?.dataset.tool) return; tool = b.dataset.tool as Tool; for (const el of ui.tools.querySelectorAll("button")) el.classList.toggle("on", el === b); }); // Pointer: pulse tool clicks; paint tools drag. const cellAt = (e: PointerEvent) => { const r = canvas.getBoundingClientRect(); return { x: ((e.clientX - r.left) / r.width) * sim.nx, y: (1 - (e.clientY - r.top) / r.height) * sim.ny }; }; const paintType = () => (tool === "wall" ? CELL_WALL : tool === "mouth" ? CELL_MOUTH + Number(ui.mouthDir.value) : CELL_FLUID); let last: { x: number; y: number } | null = null; const listener = { x: 110, y: 200 }; const placeListener = (p: { x: number; y: number }) => { listener.x = Math.min(sim.nx - 1, Math.max(0, Math.floor(p.x))); listener.y = Math.min(sim.ny - 1, Math.max(0, Math.floor(p.y))); sim.setListener(listener.x, listener.y); }; let dragListener = false; canvas.addEventListener("pointerdown", (e) => { const p = cellAt(e); if (tool === "listener") { canvas.setPointerCapture(e.pointerId); placeListener(p); dragListener = true; return; } if (tool === "pulse") { sim.addPulse(p.x, p.y, Number(ui.amp.value) / P_SCALE, 3); return; } canvas.setPointerCapture(e.pointerId); geom.paint(p.x, p.y, Number(ui.brush.value), paintType()); sim.setCells(geom.cells); last = p; }); canvas.addEventListener("pointermove", (e) => { if (dragListener) placeListener(cellAt(e)); if (!last) return; const p = cellAt(e); geom.paintLine(last.x, last.y, p.x, p.y, Number(ui.brush.value), paintType()); sim.setCells(geom.cells); last = p; }); const endPaint = () => { last = null; dragListener = false; }; canvas.addEventListener("pointerup", endPaint); canvas.addEventListener("pointercancel", endPaint); // Throughput and slow-motion factor, averaged over ~1 s. let tWin = performance.now(); let stepsWin = 0; let mlups = 0; let slow = 0; const render = () => { const enc = device.createCommandEncoder(); const dt = dtSeconds(); renderer.encode(enc, ui.viewMode.value as ViewMode, { pressure: Number(ui.pRange.value) / P_SCALE / 3, acoustic: Number(ui.aRange.value) / P_SCALE / 3, vorticity: Number(ui.wRange.value) * dt, speed: Math.max(toLatticeSpeed(Number(ui.speed.value)) * 1.2, 1e-4), }, listener); device.queue.submit([enc.finish()]); }; // Recording at the listener: one sample per step on the GPU, read back when stopped, // resampled to 48 kHz, high-passed at 20 Hz, and normalized for playback. let recDt = dtSeconds(); let recSteps = 0; // steps simulated since recording started (CPU-side count) let lastRaw: Float32Array = new Float32Array(0); // for re-processing from the console let take: { audio: Float32Array; norm: Float32Array } | null = null; const startRecording = () => { recDt = dtSeconds(); recSteps = 0; sim.startRecording(); ui.rec.textContent = "Stop recording"; ui.rec.classList.add("on"); }; const stopRecording = async () => { sim.stopRecording(); ui.rec.textContent = "Record"; ui.rec.classList.remove("on"); await processRecording(); }; ui.rec.onclick = () => (sim.isRecording ? stopRecording() : startRecording()); const processRecording = async () => { const raw = await sim.readRecording(); if (raw.length < 2) { ui.recInfo.textContent = "Nothing recorded (is the listener on a wall, or the simulation paused?)"; take = null; return; } const pa = raw.map((v) => v * P_SCALE); const audio = highPass(resample(pa, 1 / recDt, AUDIO_RATE), AUDIO_RATE, 20); const pk = peakAbs(audio); const norm = new Float32Array(audio.length); for (let k = 0; k < audio.length; k++) norm[k] = pk > 0 ? (0.9 * audio[k]) / pk : 0; take = { audio, norm }; lastRaw = raw; const sp = spectrum(audio, AUDIO_RATE); let kPeak = -1; for (let k = 0; k < sp.freq.length; k++) if (sp.freq[k] >= 40 && sp.freq[k] <= 15000 && (kPeak < 0 || sp.db[k] > sp.db[kPeak])) kPeak = k; const f0 = kPeak >= 0 ? sp.freq[kPeak] : 0; const r = rms(audio); ui.recInfo.textContent = `${(audio.length / AUDIO_RATE).toFixed(3)} s (${raw.length} steps) · ` + `rms ${r.toFixed(2)} Pa (${(20 * Math.log10(r / 2e-5)).toFixed(0)} dB SPL in 2D) · ` + `peak ${pk.toFixed(1)} Pa · spectral peak ${f0.toFixed(0)} Hz (${noteName(f0)}) · ` + `playback gain ${(20 * Math.log10(0.9 / Math.max(pk, 1e-12))).toFixed(0)} dB re 1 Pa`; drawWave(ui.wave, audio); drawSpectrum(ui.spec, sp, f0); }; let audioCtx: AudioContext | null = null; let playing: AudioBufferSourceNode | null = null; ui.play.onclick = () => { if (!take) return; if (playing) { playing.stop(); return; } audioCtx ??= new AudioContext(); void audioCtx.resume(); const buf = audioCtx.createBuffer(1, take.norm.length, AUDIO_RATE); buf.copyToChannel(take.norm, 0); const src = audioCtx.createBufferSource(); src.buffer = buf; src.connect(audioCtx.destination); src.onended = () => { playing = null; ui.play.textContent = "Play"; }; src.start(); playing = src; ui.play.textContent = "Stop"; }; ui.download.onclick = () => { if (!take) return; const a = document.createElement("a"); a.href = URL.createObjectURL(encodeWav(take.norm, AUDIO_RATE)); a.download = `aerophone-${ui.preset.value}.wav`; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); }; // Benchmark from the console: aerophone.bench(). Runs `steps` steps without drawing (pause first // for a clean number) and reports throughput and the slow-motion factor at the current dx. const bench = async (steps = 30000) => { await device.queue.onSubmittedWorkDone(); const t0 = performance.now(); for (let done = 0; done < steps; done += 1000) { const enc = device.createCommandEncoder(); sim.encodeSteps(enc, 1000); device.queue.submit([enc.finish()]); if (done % 10000 === 0) await device.queue.onSubmittedWorkDone(); } await device.queue.onSubmittedWorkDone(); const wall = (performance.now() - t0) / 1000; const steps1000 = Math.ceil(steps / 1000) * 1000; return { grid: `${sim.nx} x ${sim.ny}`, mlups: Math.round((steps1000 * sim.N) / wall / 1e6), slowerThanRealTime: +(wall / (steps1000 * dtSeconds())).toFixed(1), }; }; // For inspection from the console. const debug = { bench, get sim() { return sim; }, get geom() { return geom; }, listener, P_SCALE, dtSeconds, toLatticeSpeed, setBlowing, loadPreset, render, placeListener, startRecording, stopRecording, processRecording, get lastRaw() { return lastRaw; }, get take() { return take; }, get blowing() { return blowing; }, }; (window as unknown as { aerophone: typeof debug }).aerophone = debug; await loadPreset(PRESETS[0].id); ui.preset.value = PRESETS[0].id; // Each frame submits one batch of steps, unless two are already queued on the GPU. Keeping a // second batch queued means the GPU never waits for the next animation frame. let inFlight = 0; const frame = () => { const spf = Number(ui.spf.value); ui.spfOut.textContent = String(spf); const U = Number(ui.speed.value); if (running && inFlight < 2) { const enc = device.createCommandEncoder(); sim.pMeanRate = dtSeconds() / P_MEAN_TIME; sim.encodeSteps(enc, spf); device.queue.submit([enc.finish()]); inFlight++; void device.queue.onSubmittedWorkDone().then(() => inFlight--); stepsWin += spf; if (sim.isRecording) { recSteps += spf; ui.recInfo.textContent = `recording… ${(recSteps * recDt).toFixed(3)} s of sound`; if (recSteps >= sim.recCapacity) void stopRecording(); } } render(); const dt = dtSeconds(); const now = performance.now(); if (now - tWin > 1000) { const wall = (now - tWin) / 1000; mlups = (stepsWin * sim.N) / wall / 1e6; slow = stepsWin > 0 ? wall / (stepsWin * dt) : 0; tWin = now; stepsWin = 0; } const nu = ((sim.tau - 0.5) / 3) * (dxMeters() * dxMeters()) / dt; const re = (U * 10 * dxMeters()) / nu; ui.info.textContent = `t = ${(sim.stepCount * dt * 1000).toFixed(2)} ms · ${mlups.toFixed(0)} MLUPS · ` + `${slow > 0 ? slow.toFixed(0) + "× slower than real time" : "paused"} · ` + `domain ${(sim.nx * dxMeters() * 100).toFixed(1)} × ${(sim.ny * dxMeters() * 100).toFixed(1)} cm (${sim.nx} × ${sim.ny}) · ` + `ν = ${nu.toExponential(1)} m²/s (air 1.5e-5) · Re (10-cell windway) ≈ ${re.toFixed(0)} · ` + `blowing ${(sim.blowVelocityAt() / toLatticeSpeed(1)).toFixed(1)} m/s (Mach ${(sim.blowVelocityAt() / toLatticeSpeed(C_AIR)).toFixed(3)})`; requestAnimationFrame(frame); }; requestAnimationFrame(frame); } const NOTES = ["C", "C♯", "D", "E♭", "E", "F", "F♯", "G", "A♭", "A", "B♭", "B"]; function noteName(f: number) { if (!(f > 0)) return "–"; const m = 69 + 12 * Math.log2(f / 440); const r = Math.round(m); const cents = Math.round(100 * (m - r)); return `${NOTES[((r % 12) + 12) % 12]}${Math.floor(r / 12) - 1} ${cents >= 0 ? "+" : ""}${cents}¢`; } function plotContext(c: HTMLCanvasElement) { const dpr = window.devicePixelRatio || 1; const w = c.clientWidth; const h = c.clientHeight; c.width = Math.round(w * dpr); c.height = Math.round(h * dpr); const g = c.getContext("2d")!; g.setTransform(dpr, 0, 0, dpr, 0, 0); g.fillStyle = "#16181d"; g.fillRect(0, 0, w, h); g.font = "11px system-ui, sans-serif"; return { g, w, h }; } // Waveform: min/max per pixel column, in Pa. function drawWave(c: HTMLCanvasElement, x: Float32Array) { const { g, w, h } = plotContext(c); const pk = Math.max(peakAbs(x), 1e-12); g.strokeStyle = "#e0884a"; g.beginPath(); for (let px = 0; px < w; px++) { const k0 = Math.floor((px * x.length) / w); const k1 = Math.max(k0 + 1, Math.floor(((px + 1) * x.length) / w)); let lo = Infinity; let hi = -Infinity; for (let k = k0; k < k1 && k < x.length; k++) { lo = Math.min(lo, x[k]); hi = Math.max(hi, x[k]); } g.moveTo(px + 0.5, h / 2 - (hi / pk) * (h / 2 - 4)); g.lineTo(px + 0.5, h / 2 - (lo / pk) * (h / 2 - 4) + 1); } g.stroke(); g.fillStyle = "#8a909a"; g.fillText(`±${pk.toFixed(1)} Pa`, 6, 13); g.fillText(`${(x.length / AUDIO_RATE).toFixed(3)} s`, w - 50, h - 6); } // Spectrum on a log frequency axis (40 Hz to 20 kHz), 80 dB range. function drawSpectrum(c: HTMLCanvasElement, sp: { freq: Float64Array; db: Float64Array }, f0: number) { const { g, w, h } = plotContext(c); const fmin = 40; const fmax = 20000; const X = (f: number) => (Math.log(f / fmin) / Math.log(fmax / fmin)) * w; let top = -Infinity; for (let k = 0; k < sp.db.length; k++) if (sp.freq[k] >= fmin) top = Math.max(top, sp.db[k]); const Y = (d: number) => ((top - d) / 80) * (h - 16) + 4; g.strokeStyle = "#2a2e36"; g.fillStyle = "#8a909a"; for (const f of [100, 1000, 10000]) { g.beginPath(); g.moveTo(X(f), 0); g.lineTo(X(f), h); g.stroke(); g.fillText(f >= 1000 ? `${f / 1000} kHz` : `${f} Hz`, X(f) + 3, h - 4); } g.strokeStyle = "#6fb3e8"; g.beginPath(); let started = false; for (let k = 0; k < sp.freq.length; k++) { const f = sp.freq[k]; if (f < fmin || f > fmax) continue; const y = Math.min(h, Y(sp.db[k])); if (started) g.lineTo(X(f), y); else g.moveTo(X(f), y); started = true; } g.stroke(); if (f0 > 0) { g.strokeStyle = "#e0884a"; g.beginPath(); g.moveTo(X(f0), 0); g.lineTo(X(f0), h); g.stroke(); g.fillStyle = "#e0884a"; g.fillText(`${f0.toFixed(0)} Hz`, X(f0) + 4, 13); } } main();