// D2Q9 lattice Boltzmann solver on WebGPU (weakly compressible air). // // Storage is shifted: we keep h_q = f_q - w_q (deviation from the rest state rho = 1, u = 0), // which keeps small acoustic fluctuations well resolved in float32. // Layout is structure-of-arrays: h[q * N + y * nx + x]. // Streaming is "pull": each cell gathers h_q from its upstream neighbor, then collides. // Collision: regularized BGK (non-equilibrium part projected onto the stress tensor), // with an optional Smagorinsky eddy viscosity. // Cell types: fluid, wall (halfway bounce-back), mouth (a wall moving at the blowing velocity, // pointing in one of four directions, which injects air). The blowing velocity follows a // raised-cosine ramp evaluated every step on the GPU, so starting and stopping are smooth // (a sudden change of piston speed radiates a loud click). // Edges: a sponge layer relaxes toward rest density and the running-mean velocity, so outgoing // sound is absorbed and a steady jet can leave; beyond the edge, populations are copied from the edge cell. // Lattice units: dx = dt = 1, speed of sound c_s = 1/sqrt(3). export const CS = 1 / Math.sqrt(3); // The display moments and the running-mean pressure are updated every MEAN_EVERY steps // (and on the last step of each batch). const MEAN_EVERY = 16; export const CELL_FLUID = 0; export const CELL_WALL = 1; // Mouth cells: 2 + direction index (0: +x, 1: -x, 2: +y, 3: -y). export const CELL_MOUTH = 2; const common = /* wgsl */ ` var CX: array = array(0, 1, 0, -1, 0, 1, -1, -1, 1); var CY: array = array(0, 0, 1, 0, -1, 1, 1, -1, -1); var OPP: array = array(0u, 3u, 4u, 1u, 2u, 7u, 8u, 5u, 6u); var W: array = array( 4.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 9.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0, 1.0 / 36.0); var MOUTH_DIR: array = array(vec2f(1.0, 0.0), vec2f(-1.0, 0.0), vec2f(0.0, 1.0), vec2f(0.0, -1.0)); `; const stepWGSL = (wx: number, wy: number) => /* wgsl */ ` struct Params { nx: u32, ny: u32, omega: f32, spongeWidth: f32, spongeMax: f32, u0: f32, smag: f32, meanRate: f32, listener: u32, recording: u32, recCap: u32, pMeanRate: f32, u1: f32, rampStart: u32, rampLen: f32, parity: u32, momentsStep: u32, p0: u32, p1: u32, p2: u32, }; @group(0) @binding(0) var P: Params; @group(0) @binding(1) var hin: array; @group(0) @binding(2) var hout: array; @group(0) @binding(3) var moments: array; @group(0) @binding(4) var cells: array; @group(0) @binding(5) var meanU: array; @group(0) @binding(6) var rec: array; @group(0) @binding(7) var recCount: array; ${common} fn spongeSigma(x: i32, y: i32) -> f32 { let d = f32(min(min(x, i32(P.nx) - 1 - x), min(y, i32(P.ny) - 1 - y))); let s = clamp((P.spongeWidth - d) / P.spongeWidth, 0.0, 1.0); return P.spongeMax * s * s; } @compute @workgroup_size(${wx}, ${wy}) fn main(@builtin(global_invocation_id) gid: vec3u) { if (gid.x >= P.nx || gid.y >= P.ny) { return; } let x = i32(gid.x); let y = i32(gid.y); let nx = i32(P.nx); let ny = i32(P.ny); let N = P.nx * P.ny; let i = gid.y * P.nx + gid.x; let t = cells[i]; // Step counter, ping-ponged between recCount[1] and recCount[2] (the two bind groups // differ in parity), so reading and writing it in one dispatch does not race. let n = recCount[1u + P.parity]; if (i == 0u) { recCount[2u - P.parity] = n + 1u; } // Blowing speed: raised-cosine ramp from u0 (at step rampStart) to u1 over rampLen steps. let dn = select(0u, n - P.rampStart, n >= P.rampStart); let s = clamp(f32(dn) / P.rampLen, 0.0, 1.0); let uin = mix(P.u0, P.u1, 0.5 - 0.5 * cos(3.14159265 * s)); // Moments (for display) are written only every MEAN_EVERY steps, when the running mean is // updated, and on the last step of each batch, which is the one drawn. This saves memory traffic. let meanStep = (n % ${MEAN_EVERY}u) == 0u; let writeMoments = meanStep || n == P.momentsStep; if (t >= 1u) { // Wall or mouth: no fluid state. Mouth cells report their wall velocity for display. for (var q = 0u; q < 9u; q++) { hout[q * N + i] = 0.0; } var uw = vec2f(0.0); if (t >= 2u) { uw = uin * MOUTH_DIR[t - 2u]; } if (writeMoments) { moments[i] = vec4f(0.0, uw.x, uw.y, 0.0); } return; } // Stream (pull), with halfway bounce-back from wall and mouth neighbors. // A mouth is a wall moving at the blowing velocity u_w (Ladd): the reflected population // gains 6 w_q rho0 (c_q . u_w), which pushes air into the fluid like a piston. var h: array; var drho = 0.0; var jx = 0.0; var jy = 0.0; for (var q = 0u; q < 9u; q++) { let xs = x - CX[q]; let ys = y - CY[q]; // Outside the domain: zero-gradient (copy the nearest edge cell), so flow can leave. let j = u32(clamp(ys, 0, ny - 1)) * P.nx + u32(clamp(xs, 0, nx - 1)); var v = 0.0; { let tj = cells[j]; if (tj == 1u) { v = hin[OPP[q] * N + i]; } else if (tj >= 2u) { let uw = uin * MOUTH_DIR[tj - 2u]; v = hin[OPP[q] * N + i] + 6.0 * W[q] * (f32(CX[q]) * uw.x + f32(CY[q]) * uw.y); } else { v = hin[q * N + j]; } } h[q] = v; drho += v; jx += v * f32(CX[q]); jy += v * f32(CY[q]); } // Listener: one sample (the density fluctuation) per step. Only the listener's own thread // touches recCount, and dispatches run in order, so no atomics are needed. if (P.recording != 0u && i == P.listener) { let k = recCount[0]; if (k < P.recCap) { rec[k] = drho; recCount[0] = k + 1u; } } let rho = 1.0 + drho; let ux = jx / rho; let uy = jy / rho; // Regularized collision. let usq = ux * ux + uy * uy; var heq: array; var pxx = 0.0; var pyy = 0.0; var pxy = 0.0; for (var q = 0u; q < 9u; q++) { let cx = f32(CX[q]); let cy = f32(CY[q]); let cu = cx * ux + cy * uy; heq[q] = W[q] * (drho + rho * (3.0 * cu + 4.5 * cu * cu - 1.5 * usq)); let fneq = h[q] - heq[q]; pxx += cx * cx * fneq; pyy += cy * cy * fneq; pxy += cx * cy * fneq; } var omega = P.omega; if (P.smag > 0.0) { let qn = sqrt(pxx * pxx + pyy * pyy + 2.0 * pxy * pxy); let tau0 = 1.0 / P.omega; let tau = 0.5 * (tau0 + sqrt(tau0 * tau0 + 18.0 * 1.41421356 * P.smag * P.smag * qn / rho)); omega = 1.0 / tau; } // Sponge: relax toward equilibrium at rest density and the local running-mean velocity, so // fluctuations (sound) are absorbed while a steady outflow (a jet) passes out of the domain. let sig = spongeSigma(x, y); var v = vec2f(0.0); if (sig > 0.0) { v = meanU[i] + P.meanRate * (vec2f(ux, uy) - meanU[i]); meanU[i] = v; } let vx = v.x; let vy = v.y; let vsq = vx * vx + vy * vy; for (var q = 0u; q < 9u; q++) { let cx = f32(CX[q]); let cy = f32(CY[q]); let qp = (cx * cx - 1.0 / 3.0) * pxx + (cy * cy - 1.0 / 3.0) * pyy + 2.0 * cx * cy * pxy; let post = heq[q] + (1.0 - omega) * 4.5 * W[q] * qp; let cv = cx * vx + cy * vy; let rest = W[q] * (3.0 * cv + 4.5 * cv * cv - 1.5 * vsq); hout[q * N + i] = post - sig * (post - rest); } // w: running mean of drho, used by the acoustic view, updated every MEAN_EVERY steps // (pMeanRate is the rate per update). if (writeMoments) { var pm = moments[i].w; if (meanStep) { pm += P.pMeanRate * (drho - pm); } moments[i] = vec4f(drho, ux, uy, pm); } } `; const pulseWGSL = /* wgsl */ ` struct Pulse { nx: u32, ny: u32, x0: f32, y0: f32, amp: f32, width: f32, p0: f32, p1: f32 }; @group(0) @binding(0) var U: Pulse; @group(0) @binding(1) var h: array; ${common} @compute @workgroup_size(16, 16) fn main(@builtin(global_invocation_id) gid: vec3u) { if (gid.x >= U.nx || gid.y >= U.ny) { return; } let dx = f32(gid.x) - U.x0; let dy = f32(gid.y) - U.y0; let d = U.amp * exp(-(dx * dx + dy * dy) / (2.0 * U.width * U.width)); let N = U.nx * U.ny; let i = gid.y * U.nx + gid.x; for (var q = 0u; q < 9u; q++) { h[q * N + i] += W[q] * d; } } `; export type SimOptions = { nx: number; ny: number; tau: number; spongeWidth: number; spongeMax: number; meanRate: number; // per-step rate of the running-mean velocity used as the sponge target pMeanRate: number; // per-step rate of the running-mean density (acoustic view) recCapacity: number; // max recorded samples (one per step) smagorinsky: number; workgroup?: [number, number]; // step kernel workgroup size (default 16 x 16) }; export class Sim { readonly nx: number; readonly ny: number; readonly N: number; readonly moments: GPUBuffer; // vec4 per cell: (drho, ux, uy, running mean of drho) readonly cells: GPUBuffer; // u32 per cell: cell type private meanU: GPUBuffer; // vec2 per cell: running-mean velocity (sponge cells only) stepCount = 0; private h: [GPUBuffer, GPUBuffer]; private cur = 0; // index of the buffer holding the current state private params: [GPUBuffer, GPUBuffer]; // identical except for the counter parity private pulseParams: GPUBuffer; private stepPipeline: GPUComputePipeline; private pulsePipeline: GPUComputePipeline; private stepGroups: [GPUBindGroup, GPUBindGroup]; private pulseGroups: [GPUBindGroup, GPUBindGroup]; private opts: SimOptions; // Blowing velocity (lattice units): a raised-cosine ramp from u0 to u1 over rampLen steps // starting at step rampStart. private u0 = 0; private u1 = 0; private rampStart = 0; private rampLen = 1; private rec: GPUBuffer; private recCount: GPUBuffer; private listenerIndex = 0; private recording = false; private momentsStep = 0; // step index (from 0) whose moments are written: the last of the batch private wg: [number, number]; constructor(private device: GPUDevice, opts: SimOptions) { this.opts = { ...opts }; this.wg = opts.workgroup ?? [16, 16]; this.nx = opts.nx; this.ny = opts.ny; this.N = opts.nx * opts.ny; const hBytes = 9 * this.N * 4; const mk = (size: number, usage: number) => device.createBuffer({ size, usage }); const S = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC; this.h = [mk(hBytes, S), mk(hBytes, S)]; this.moments = mk(this.N * 16, S); this.cells = mk(this.N * 4, S); this.meanU = mk(this.N * 8, S); this.rec = mk(opts.recCapacity * 4, S); this.recCount = mk(16, S); this.params = [0, 1].map(() => mk(80, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST)) as [GPUBuffer, GPUBuffer]; this.pulseParams = mk(32, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST); this.stepPipeline = device.createComputePipeline({ layout: "auto", compute: { module: device.createShaderModule({ code: stepWGSL(...this.wg) }), entryPoint: "main" }, }); this.pulsePipeline = device.createComputePipeline({ layout: "auto", compute: { module: device.createShaderModule({ code: pulseWGSL }), entryPoint: "main" }, }); const stepGroup = (src: GPUBuffer, dst: GPUBuffer, params: GPUBuffer) => device.createBindGroup({ layout: this.stepPipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: params } }, { binding: 1, resource: { buffer: src } }, { binding: 2, resource: { buffer: dst } }, { binding: 3, resource: { buffer: this.moments } }, { binding: 4, resource: { buffer: this.cells } }, { binding: 5, resource: { buffer: this.meanU } }, { binding: 6, resource: { buffer: this.rec } }, { binding: 7, resource: { buffer: this.recCount } }, ], }); this.stepGroups = [stepGroup(this.h[0], this.h[1], this.params[0]), stepGroup(this.h[1], this.h[0], this.params[1])]; const pulseGroup = (buf: GPUBuffer) => device.createBindGroup({ layout: this.pulsePipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: this.pulseParams } }, { binding: 1, resource: { buffer: buf } }, ], }); this.pulseGroups = [pulseGroup(this.h[0]), pulseGroup(this.h[1])]; this.writeParams(); } get tau() { return this.opts.tau; } set tau(t: number) { this.opts.tau = t; this.writeParams(); } set smagorinsky(c: number) { this.opts.smagorinsky = c; this.writeParams(); } // Blowing velocity at mouth cells after step n (default: now), in lattice units (U * c_s / c). blowVelocityAt(n = this.stepCount) { const s = Math.min(1, Math.max(0, (n - this.rampStart) / this.rampLen)); return this.u0 + (this.u1 - this.u0) * (0.5 - 0.5 * Math.cos(Math.PI * s)); } get blowTarget() { return this.u1; } // Ramp the blowing velocity from its current value to u (lattice units) over rampSteps steps, // starting with the next step. setBlow(u: number, rampSteps: number) { this.u0 = this.blowVelocityAt(); this.u1 = u; this.rampStart = this.stepCount; this.rampLen = Math.max(1, Math.round(rampSteps)); this.writeParams(); } get spongeWidth() { return this.opts.spongeWidth; } set pMeanRate(r: number) { if (r === this.opts.pMeanRate) return; this.opts.pMeanRate = r; this.writeParams(); } get recCapacity() { return this.opts.recCapacity; } // Listener cell. It records only while it sits on a fluid cell. setListener(x: number, y: number) { const xi = Math.min(this.nx - 1, Math.max(0, Math.round(x))); const yi = Math.min(this.ny - 1, Math.max(0, Math.round(y))); this.listenerIndex = yi * this.nx + xi; this.writeParams(); } get isRecording() { return this.recording; } // Start a new recording (clears the previous one). startRecording() { this.device.queue.writeBuffer(this.recCount, 0, new Uint32Array(1)); this.recording = true; this.writeParams(); } stopRecording() { this.recording = false; this.writeParams(); } // The recorded density fluctuation at the listener, one sample per step. async readRecording(): Promise { const cnt = this.device.createBuffer({ size: 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); let enc = this.device.createCommandEncoder(); enc.copyBufferToBuffer(this.recCount, 0, cnt, 0, 16); this.device.queue.submit([enc.finish()]); await cnt.mapAsync(GPUMapMode.READ); const n = new Uint32Array(cnt.getMappedRange())[0]; cnt.unmap(); cnt.destroy(); if (n === 0) return new Float32Array(0); const staging = this.device.createBuffer({ size: n * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); enc = this.device.createCommandEncoder(); enc.copyBufferToBuffer(this.rec, 0, staging, 0, n * 4); this.device.queue.submit([enc.finish()]); await staging.mapAsync(GPUMapMode.READ); const out = new Float32Array(staging.getMappedRange().slice(0)); staging.unmap(); staging.destroy(); return out; } private writeParams() { for (const parity of [0, 1]) { const b = new ArrayBuffer(80); new Uint32Array(b, 0, 2).set([this.nx, this.ny]); new Float32Array(b, 8, 6).set([ 1 / this.opts.tau, this.opts.spongeWidth, this.opts.spongeMax, this.u0, this.opts.smagorinsky, this.opts.meanRate, ]); new Uint32Array(b, 32, 3).set([this.listenerIndex, this.recording ? 1 : 0, this.opts.recCapacity]); new Float32Array(b, 44, 2).set([1 - Math.pow(1 - this.opts.pMeanRate, MEAN_EVERY), this.u1]); new Uint32Array(b, 52, 1).set([this.rampStart]); new Float32Array(b, 56, 1).set([this.rampLen]); new Uint32Array(b, 60, 2).set([parity, this.momentsStep]); this.device.queue.writeBuffer(this.params[parity], 0, b); } } setCells(cells: Uint32Array) { this.device.queue.writeBuffer(this.cells, 0, cells); } reset() { const enc = this.device.createCommandEncoder(); enc.clearBuffer(this.h[0]); enc.clearBuffer(this.h[1]); enc.clearBuffer(this.moments); enc.clearBuffer(this.meanU); this.device.queue.submit([enc.finish()]); this.device.queue.writeBuffer(this.recCount, 4, new Uint32Array(2)); // step counters this.stepCount = 0; // Start again from rest, ramping to the current target. this.u0 = 0; this.rampStart = 0; this.writeParams(); } // Add a Gaussian density bump (at rest) centered at cell (x0, y0). addPulse(x0: number, y0: number, amp: number, width: number) { const b = new ArrayBuffer(32); new Uint32Array(b, 0, 2).set([this.nx, this.ny]); new Float32Array(b, 8, 4).set([x0, y0, amp, width]); this.device.queue.writeBuffer(this.pulseParams, 0, b); const enc = this.device.createCommandEncoder(); const pass = enc.beginComputePass(); pass.setPipeline(this.pulsePipeline); pass.setBindGroup(0, this.pulseGroups[this.cur]); pass.dispatchWorkgroups(Math.ceil(this.nx / 16), Math.ceil(this.ny / 16)); pass.end(); this.device.queue.submit([enc.finish()]); } // Encode n time steps. After the last one, `moments` holds the moments of the final input state. // Only the last batch encoded before a submit is guaranteed fresh moments on its last step; // otherwise they are at most MEAN_EVERY - 1 steps old. encodeSteps(enc: GPUCommandEncoder, n: number) { if (n <= 0) return; this.momentsStep = this.stepCount + n - 1; this.writeParams(); const pass = enc.beginComputePass(); pass.setPipeline(this.stepPipeline); for (let k = 0; k < n; k++) { pass.setBindGroup(0, this.stepGroups[this.cur]); pass.dispatchWorkgroups(Math.ceil(this.nx / this.wg[0]), Math.ceil(this.ny / this.wg[1])); this.cur = 1 - this.cur; } pass.end(); this.stepCount += n; } // Free the GPU buffers (when switching to a different grid size). destroy() { for (const b of [...this.h, this.moments, this.cells, this.meanU, this.rec, this.recCount, ...this.params, this.pulseParams]) b.destroy(); } // Copy the moments buffer to the CPU (for debugging and tests). async readMoments(): Promise { const staging = this.device.createBuffer({ size: this.N * 16, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }); const enc = this.device.createCommandEncoder(); enc.copyBufferToBuffer(this.moments, 0, staging, 0, this.N * 16); this.device.queue.submit([enc.finish()]); await staging.mapAsync(GPUMapMode.READ); const out = new Float32Array(staging.getMappedRange().slice(0)); staging.unmap(); staging.destroy(); return out; } }