/ proof-of-concept / steelsim21
Sign in
proof-of-concept / steelsim21
steelsim21 / src / sim / simulation.ts
538 lines · 20.4 KBBlameHistoryRaw
1// WebGPU time-stepping driver for the von Karman plate.
2//
3// The simulation advances in batches of one movie frame (1/fps seconds). A batch
4// encodes one compute dispatch per time step (with a per-step uniform addressed
5// by dynamic offset), a rigid-body projection every RB_INTERVAL steps, one
6// retarded-time audio sum per audio sample, and one movie-frame extraction at
7// the end. Audio, frame, and statistics are read back after every batch.
9import {
10 type PhysParams,
11 type Grid,
12 type Material,
13 makeGrid,
14 makeMaterial,
15 nodeX,
16 nodeY,
17 trapWeight,
18 HIST_LEN,
19 RB_INTERVAL,
20 RB_INTERVAL_HELD,
21 RHO_AIR,
22 SPEED_OF_SOUND,
23} from "../params.ts";
24import { maxAngularFrequency } from "./cpuRef.ts";
25import commonWgsl from "./shaders/common.wgsl?raw";
26import stepWgsl from "./shaders/step.wgsl?raw";
27import rigidWgsl from "./shaders/rigid.wgsl?raw";
28import audioWgsl from "./shaders/audio.wgsl?raw";
29import extractWgsl from "./shaders/extract.wgsl?raw";
31export type Phase = "push" | "hold" | "recording" | "done";
33export interface SimStatus {
34 phase: Phase;
35 /** Simulation time relative to the release [s]. */
36 t: number;
37 totalSteps: number;
38 ke: number;
39 wmax: number;
40 samples: number;
41 frames: number;
42 peakPressure: number;
43 delayClamped: boolean;
46const STATS_LEN = 16;
48export class Simulation {
49 readonly grid: Grid;
50 readonly mat: Material;
51 readonly dt: number;
52 /** Time steps per audio sample. */
53 readonly stepsPerSample: number;
54 readonly samplesPerBatch: number;
55 readonly stepsPerBatch: number;
56 readonly omegaMax: number;
58 /** Raw listener pressure [Pa] at fs, from the release. */
59 audio: Float32Array = new Float32Array(0);
60 samples = 0;
61 /** Movie frames of w [m]; frame k is at t = k / fps. */
62 frames: Float32Array<ArrayBuffer>[] = [];
64 phase: Phase = "push";
65 /** Steps since the start of the current phase clock (prep or recording). */
66 private stepCount = 0;
67 private prepTime = 0;
68 totalSteps = 0;
69 ke = 0;
70 wmax = 0;
71 peakPressure = 0;
72 delayClamped = false;
73 private hpState = { y: 0, x: 0 };
75 private device: GPUDevice;
76 private params: PhysParams;
77 private paramsBuf: GPUBuffer;
78 private stepBuf: GPUBuffer;
79 private stepStride: number;
80 private stepData: ArrayBuffer;
81 private pos: GPUBuffer[];
82 private vel: GPUBuffer[];
83 private hist: GPUBuffer;
84 private lw: GPUBuffer;
85 private audioOut: GPUBuffer;
86 private frameBuf: GPUBuffer;
87 private statsBuf: GPUBuffer;
88 private staging: GPUBuffer[];
89 private stagingIdx = 0;
90 /** Index of the buffer pair holding the current state. */
91 private cur = 0;
92 /** The `displayW` buffer is a plain f32 array of w for the renderer. */
93 readonly displayW: GPUBuffer;
95 private stepPipe: GPUComputePipeline;
96 private sumsPipe: GPUComputePipeline;
97 private applyPipe: GPUComputePipeline;
98 private audioPipe: GPUComputePipeline;
99 private extractPipe: GPUComputePipeline;
100 private stepBG: GPUBindGroup[];
101 private rbBG: GPUBindGroup[];
102 private audioBG: GPUBindGroup;
103 private extractBG: GPUBindGroup[];
104 private displayBG: GPUBindGroup[];
105 private stagingSize: number;
107 constructor(device: GPUDevice, params: PhysParams) {
108 this.device = device;
109 this.params = { ...params };
110 const g = makeGrid(params);
111 const m = makeMaterial(params);
112 this.grid = g;
113 this.mat = m;
115 // Stable time step, aligned so that an integer number of steps make one audio sample.
116 this.omegaMax = maxAngularFrequency(g, m);
117 const dtMax = (0.85 * 2) / this.omegaMax;
118 this.stepsPerSample = Math.ceil(1 / (params.fs * dtMax));
119 this.dt = 1 / (params.fs * this.stepsPerSample);
120 this.samplesPerBatch = Math.max(1, Math.round(params.fs / params.fps));
121 this.stepsPerBatch = this.samplesPerBatch * this.stepsPerSample;
123 const n = g.n;
124 const f32 = (size: number, usage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) =>
125 device.createBuffer({ size: Math.max(16, size * 4), usage });
127 this.pos = [f32(4 * n), f32(4 * n)]; // [u | v | w | wLo]
128 this.vel = [f32(3 * n), f32(3 * n)]; // [du | dv | dw]
129 this.hist = f32(HIST_LEN * n);
130 this.lw = f32(2 * n);
131 this.audioOut = f32(this.samplesPerBatch);
132 this.frameBuf = f32(n);
133 this.displayW = f32(n);
134 this.statsBuf = f32(STATS_LEN);
135 this.stagingSize = (this.samplesPerBatch + n + STATS_LEN) * 4;
136 this.staging = [0, 1].map(() =>
137 device.createBuffer({ size: this.stagingSize, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }),
138 );
140 // Constant parameters.
141 let mass = 0, Ix = 0, Iy = 0;
142 for (let j = 0; j < g.ny; j++) {
143 for (let i = 0; i < g.nx; i++) {
144 const mk = m.rhoh * g.hx * g.hy * trapWeight(g, i, j);
145 mass += mk;
146 Ix += mk * nodeY(g, j) ** 2;
147 Iy += mk * nodeX(g, i) ** 2;
148 }
149 }
150 const pf = new Float32Array(20);
151 const pu = new Uint32Array(pf.buffer);
152 pu[0] = g.nx; pu[1] = g.ny; pu[2] = n; pu[3] = HIST_LEN;
153 pf[4] = g.hx; pf[5] = g.hy; pf[6] = this.dt; pf[7] = m.nu;
154 pf[8] = m.D; pf[9] = m.C; pf[10] = m.G; pf[11] = m.rhoh;
155 pf[12] = params.Lx / 2; pf[13] = -params.Ly / 2; pf[14] = params.fingerRadius ** 2; pf[15] = mass;
156 pf[16] = Ix; pf[17] = Iy; pf[18] = Ix + Iy; pf[19] = 0;
157 this.paramsBuf = device.createBuffer({ size: pf.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
158 device.queue.writeBuffer(this.paramsBuf, 0, pf);
160 // Per-step parameters, one 32-byte struct per step at a dynamic offset.
161 this.stepStride = Math.max(32, device.limits.minUniformBufferOffsetAlignment);
162 this.stepData = new ArrayBuffer(this.stepStride * this.stepsPerBatch);
163 this.stepBuf = device.createBuffer({ size: this.stepData.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
165 const mk = (code: string, entry: string, layout: GPUPipelineLayout | "auto" = "auto") =>
166 device.createComputePipeline({
167 layout,
168 compute: { module: device.createShaderModule({ code: commonWgsl + code }), entryPoint: entry },
169 });
170 const entry = (binding: number, type: GPUBufferBindingType, hasDynamicOffset = false): GPUBindGroupLayoutEntry => ({
171 binding,
172 visibility: GPUShaderStage.COMPUTE,
173 buffer: { type, hasDynamicOffset },
174 });
175 const stepLayout = device.createBindGroupLayout({
176 entries: [
177 entry(0, "uniform"),
178 entry(1, "uniform", true),
179 entry(2, "read-only-storage"),
180 entry(3, "read-only-storage"),
181 entry(4, "storage"),
182 entry(5, "storage"),
183 entry(6, "storage"),
184 ],
185 });
186 this.stepPipe = mk(stepWgsl, "main", device.createPipelineLayout({ bindGroupLayouts: [stepLayout] }));
187 const audioLayout = device.createBindGroupLayout({
188 entries: [entry(0, "uniform"), entry(1, "uniform", true), entry(2, "read-only-storage"), entry(3, "read-only-storage"), entry(4, "storage")],
189 });
190 const rigidModule = device.createShaderModule({ code: commonWgsl + rigidWgsl });
191 const rbLayout = device.createBindGroupLayout({
192 entries: [
193 { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "uniform" } },
194 { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
195 { binding: 2, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
196 { binding: 3, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
197 ],
198 });
199 const rbPipeLayout = device.createPipelineLayout({ bindGroupLayouts: [rbLayout] });
200 this.sumsPipe = device.createComputePipeline({ layout: rbPipeLayout, compute: { module: rigidModule, entryPoint: "sums" } });
201 this.applyPipe = device.createComputePipeline({ layout: rbPipeLayout, compute: { module: rigidModule, entryPoint: "apply" } });
202 this.audioPipe = mk(audioWgsl, "main", device.createPipelineLayout({ bindGroupLayouts: [audioLayout] }));
203 this.extractPipe = mk(extractWgsl, "main");
205 const sp = { buffer: this.stepBuf, size: 32 };
206 this.stepBG = [0, 1].map((p) =>
207 device.createBindGroup({
208 layout: stepLayout,
209 entries: [
210 { binding: 0, resource: { buffer: this.paramsBuf } },
211 { binding: 1, resource: sp },
212 { binding: 2, resource: { buffer: this.pos[p] } },
213 { binding: 3, resource: { buffer: this.vel[p] } },
214 { binding: 4, resource: { buffer: this.pos[1 - p] } },
215 { binding: 5, resource: { buffer: this.vel[1 - p] } },
216 { binding: 6, resource: { buffer: this.hist } },
217 ],
218 }),
219 );
220 this.rbBG = [0, 1].map((p) =>
221 device.createBindGroup({
222 layout: rbLayout,
223 entries: [
224 { binding: 0, resource: { buffer: this.paramsBuf } },
225 { binding: 1, resource: { buffer: this.pos[p] } },
226 { binding: 2, resource: { buffer: this.vel[p] } },
227 { binding: 3, resource: { buffer: this.statsBuf } },
228 ],
229 }),
230 );
231 this.audioBG = device.createBindGroup({
232 layout: audioLayout,
233 entries: [
234 { binding: 0, resource: { buffer: this.paramsBuf } },
235 { binding: 1, resource: sp },
236 { binding: 2, resource: { buffer: this.hist } },
237 { binding: 3, resource: { buffer: this.lw } },
238 { binding: 4, resource: { buffer: this.audioOut } },
239 ],
240 });
241 const extractBG = (p: number, out: GPUBuffer) =>
242 device.createBindGroup({
243 layout: this.extractPipe.getBindGroupLayout(0),
244 entries: [
245 { binding: 0, resource: { buffer: this.paramsBuf } },
246 { binding: 1, resource: { buffer: this.pos[p] } },
247 { binding: 2, resource: { buffer: out } },
248 ],
249 });
250 this.extractBG = [0, 1].map((p) => extractBG(p, this.frameBuf));
251 this.displayBG = [0, 1].map((p) => extractBG(p, this.displayW));
253 this.setListener(params.listenerDist, params.listenerAzimuth, params.listenerElevation, params.radiation);
254 }
256 /** Recomputes the per-node weights and delays of the listener sum. Takes effect on later samples. */
257 setListener(dist: number, azimuthDeg: number, elevationDeg: number, radiation: "rayleigh" | "dipole"): void {
258 const g = this.grid;
259 const az = (azimuthDeg * Math.PI) / 180;
260 const el = (elevationDeg * Math.PI) / 180;
261 const L = [dist * Math.sin(az) * Math.cos(el), dist * Math.sin(el), dist * Math.cos(az) * Math.cos(el)];
262 const data = new Float32Array(2 * g.n);
263 let dmin = Infinity;
264 for (let j = 0; j < g.ny; j++) {
265 for (let i = 0; i < g.nx; i++) {
266 const k = j * g.nx + i;
267 const rx = L[0] - nodeX(g, i), ry = L[1] - nodeY(g, j), rz = L[2];
268 const r = Math.sqrt(rx * rx + ry * ry + rz * rz);
269 const dA = g.hx * g.hy * trapWeight(g, i, j);
270 let wgt = (RHO_AIR * dA) / (2 * Math.PI * r);
271 if (radiation === "dipole") wgt *= Math.abs(rz) / r;
272 data[2 * k] = wgt;
273 data[2 * k + 1] = (r / SPEED_OF_SOUND) * this.params.fs;
274 dmin = Math.min(dmin, data[2 * k + 1]);
275 }
276 }
277 this.delayClamped = false;
278 for (let k = 0; k < g.n; k++) {
279 let d = data[2 * k + 1] - dmin;
280 if (d > HIST_LEN - 2) {
281 d = HIST_LEN - 2;
282 this.delayClamped = true;
283 }
284 data[2 * k + 1] = d;
285 }
286 this.device.queue.writeBuffer(this.lw, 0, data);
287 this.params.listenerDist = dist;
288 this.params.listenerAzimuth = azimuthDeg;
289 this.params.listenerElevation = elevationDeg;
290 this.params.radiation = radiation;
291 }
293 setDamping(sigma0: number, sigma1: number): void {
294 this.params.sigma0 = sigma0;
295 this.params.sigma1 = sigma1;
296 }
298 setDuration(duration: number): void {
299 this.params.duration = duration;
300 if (this.phase === "done" && this.samples < this.targetSamples()) this.phase = "recording";
301 }
303 targetSamples(): number {
304 return Math.round(this.params.duration * this.params.fs);
305 }
307 status(): SimStatus {
308 const t = this.phase === "push" || this.phase === "hold" ? this.prepTime - this.prepDuration() : this.stepCount * this.dt;
309 return {
310 phase: this.phase,
311 t,
312 totalSteps: this.totalSteps,
313 ke: this.ke,
314 wmax: this.wmax,
315 samples: this.samples,
316 frames: this.frames.length,
317 peakPressure: this.peakPressure,
318 delayClamped: this.delayClamped,
319 };
320 }
322 private prepDuration(): number {
323 return this.params.rampTime + this.params.holdMax;
324 }
326 /** Enqueues an extraction of the current w field into `displayW` (for the live view). */
327 encodeDisplay(encoder: GPUCommandEncoder): void {
328 const pass = encoder.beginComputePass();
329 pass.setPipeline(this.extractPipe);
330 pass.setBindGroup(0, this.displayBG[this.cur]);
331 pass.dispatchWorkgroups(Math.ceil(this.grid.n / 256));
332 pass.end();
333 }
335 /** Listener audio with the radiation post-processing applied [Pa]. */
336 processedAudio(): Float32Array {
337 return this.processed.subarray(0, this.samples);
338 }
339 private processed: Float32Array = new Float32Array(0);
341 private appendAudio(raw: Float32Array): void {
342 const need = this.samples + raw.length;
343 if (this.audio.length < need) {
344 const grow = Math.max(need, 2 * this.audio.length, this.params.fs);
345 const a = new Float32Array(grow);
346 a.set(this.audio.subarray(0, this.samples));
347 this.audio = a;
348 const b = new Float32Array(grow);
349 b.set(this.processed.subarray(0, this.samples));
350 this.processed = b;
351 }
352 this.audio.set(raw, this.samples);
353 // Dipole option: first-order high-pass at the baffle cutoff c / (2 sqrt(Lx Ly)).
354 const dipole = this.params.radiation === "dipole";
355 const fc = SPEED_OF_SOUND / (2 * Math.sqrt(this.params.Lx * this.params.Ly));
356 const alpha = 1 / (1 + (2 * Math.PI * fc) / this.params.fs);
357 for (let k = 0; k < raw.length; k++) {
358 const x = raw[k];
359 let y = x;
360 if (dipole) {
361 y = alpha * (this.hpState.y + x - this.hpState.x);
362 }
363 this.hpState = { y, x };
364 this.processed[this.samples + k] = y;
365 this.peakPressure = Math.max(this.peakPressure, Math.abs(y));
366 }
367 this.samples = need;
368 }
370 /** Runs one batch (one movie frame of time). Resolves when its results have been read back. */
371 async runBatch(): Promise<void> {
372 if (this.phase === "done") return;
373 const p = this.params;
374 const recording = this.phase === "recording";
375 const nSteps = this.stepsPerBatch;
376 const stepsLeft = recording ? (this.targetSamples() - this.samples) * this.stepsPerSample : nSteps;
377 const steps = Math.min(nSteps, Math.max(0, stepsLeft));
378 if (steps === 0) {
379 this.phase = "done";
380 return;
381 }
383 // Fill the per-step parameters.
384 const u32 = new Uint32Array(this.stepData);
385 const i32 = new Int32Array(this.stepData);
386 const f32 = new Float32Array(this.stepData);
387 const stride = this.stepStride / 4;
388 const audioStepsInBatch: number[] = [];
389 for (let s = 0; s < steps; s++) {
390 const o = s * stride;
391 const local = this.stepCount + s;
392 u32[o] = this.totalSteps + s;
393 let flags = 0, pushW = 0, pushV = 0, sigma0 = p.sigma0, slot = -1, outIdx = -1;
394 if (!recording) {
395 const t = this.prepTime + (s + 1) * this.dt; // state after this step
396 const tau = Math.min(1, t / p.rampTime);
397 const smooth = tau * tau * (3 - 2 * tau);
398 const dsmooth = tau < 1 ? (6 * tau * (1 - tau)) / p.rampTime : 0;
399 flags = 1;
400 pushW = p.pushAmount * smooth;
401 pushV = p.pushAmount * dsmooth;
402 sigma0 = p.settleSigma0;
403 } else if (local % this.stepsPerSample === 0) {
404 const sampleIdx = local / this.stepsPerSample;
405 slot = sampleIdx % HIST_LEN;
406 outIdx = audioStepsInBatch.length;
407 audioStepsInBatch.push(s);
408 }
409 u32[o + 1] = flags;
410 i32[o + 2] = slot;
411 i32[o + 3] = outIdx;
412 f32[o + 4] = pushW;
413 f32[o + 5] = pushV;
414 f32[o + 6] = sigma0;
415 f32[o + 7] = p.sigma1;
416 }
417 this.device.queue.writeBuffer(this.stepBuf, 0, this.stepData, 0, steps * this.stepStride);
419 // Encode the batch in chunks so that the GPU starts while JS is still encoding.
420 const CHUNK = 1024;
421 let enc = this.device.createCommandEncoder();
422 let pass = enc.beginComputePass();
423 const wgX = Math.ceil(this.grid.nx / 16), wgY = Math.ceil(this.grid.ny / 16);
424 const wgN = Math.ceil(this.grid.n / 256);
425 let cur = this.cur;
426 let audioPtr = 0;
427 const rbInterval = recording ? RB_INTERVAL : RB_INTERVAL_HELD;
428 let stepBound = false;
429 for (let s = 0; s < steps; s++) {
430 if (s > 0 && s % CHUNK === 0) {
431 pass.end();
432 this.device.queue.submit([enc.finish()]);
433 enc = this.device.createCommandEncoder();
434 pass = enc.beginComputePass();
435 stepBound = false;
436 }
437 if (!stepBound) {
438 pass.setPipeline(this.stepPipe);
439 stepBound = true;
440 }
441 pass.setBindGroup(0, this.stepBG[cur], [s * this.stepStride]);
442 pass.dispatchWorkgroups(wgX, wgY);
443 cur = 1 - cur;
444 const global = this.totalSteps + s + 1;
445 if (global % rbInterval === 0 || s === steps - 1) {
446 pass.setPipeline(this.sumsPipe);
447 pass.setBindGroup(0, this.rbBG[cur]);
448 pass.dispatchWorkgroups(1);
449 pass.setPipeline(this.applyPipe);
450 pass.setBindGroup(0, this.rbBG[cur]);
451 pass.dispatchWorkgroups(wgN);
452 stepBound = false;
453 }
454 if (audioPtr < audioStepsInBatch.length && audioStepsInBatch[audioPtr] === s) {
455 pass.setPipeline(this.audioPipe);
456 pass.setBindGroup(0, this.audioBG, [s * this.stepStride]);
457 pass.dispatchWorkgroups(1);
458 audioPtr++;
459 stepBound = false;
460 }
461 }
462 pass.setPipeline(this.extractPipe);
463 pass.setBindGroup(0, this.extractBG[cur]);
464 pass.dispatchWorkgroups(wgN);
465 pass.end();
466 const staging = this.staging[this.stagingIdx];
467 this.stagingIdx = 1 - this.stagingIdx;
468 const nAudio = audioStepsInBatch.length;
469 enc.copyBufferToBuffer(this.audioOut, 0, staging, 0, Math.max(4, nAudio * 4));
470 enc.copyBufferToBuffer(this.frameBuf, 0, staging, this.samplesPerBatch * 4, this.grid.n * 4);
471 enc.copyBufferToBuffer(this.statsBuf, 0, staging, (this.samplesPerBatch + this.grid.n) * 4, STATS_LEN * 4);
472 this.device.queue.submit([enc.finish()]);
473 this.cur = cur;
474 this.totalSteps += steps;
475 this.stepCount += steps;
476 if (!recording) this.prepTime += steps * this.dt;
478 await staging.mapAsync(GPUMapMode.READ);
479 const view = new Float32Array(staging.getMappedRange());
480 const stats = view.subarray(this.samplesPerBatch + this.grid.n, this.samplesPerBatch + this.grid.n + STATS_LEN);
481 this.ke = stats[12];
482 this.wmax = stats[13];
483 if (recording) {
484 this.appendAudio(view.slice(0, nAudio));
485 this.frames.push(view.slice(this.samplesPerBatch, this.samplesPerBatch + this.grid.n));
486 } else {
487 this.lastPrepFrame = view.slice(this.samplesPerBatch, this.samplesPerBatch + this.grid.n);
488 }
489 staging.unmap();
491 if (!recording) {
492 if (this.phase === "push" && this.prepTime >= p.rampTime) this.phase = "hold";
493 const settled = this.phase === "hold" && this.ke < p.settleKE;
494 if (settled || this.prepTime >= this.prepDuration()) this.release();
495 } else if (this.samples >= this.targetSamples()) {
496 this.phase = "done";
497 }
498 }
499 private lastPrepFrame: Float32Array<ArrayBuffer> | null = null;
501 private release(): void {
502 this.phase = "recording";
503 this.stepCount = 0;
504 this.totalSteps = 0;
505 // Frame 0 is the held, settled shape.
506 if (this.lastPrepFrame) this.frames.push(this.lastPrepFrame);
507 }
509 /** Reads back the full state (debugging and tests). */
510 async readState(): Promise<{ pos: Float32Array; vel: Float32Array }> {
511 const n = this.grid.n;
512 const stg = this.device.createBuffer({ size: 7 * n * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
513 const enc = this.device.createCommandEncoder();
514 enc.copyBufferToBuffer(this.pos[this.cur], 0, stg, 0, 4 * n * 4);
515 enc.copyBufferToBuffer(this.vel[this.cur], 0, stg, 4 * n * 4, 3 * n * 4);
516 this.device.queue.submit([enc.finish()]);
517 await stg.mapAsync(GPUMapMode.READ);
518 const all = new Float32Array(stg.getMappedRange()).slice();
519 stg.unmap();
520 stg.destroy();
521 // Returned as [u | v | w | wLo] and [du | dv | dw].
522 return { pos: all.subarray(0, 4 * n), vel: all.subarray(4 * n) };
523 }
525 destroy(): void {
526 for (const b of [...this.pos, ...this.vel, this.hist, this.lw, this.audioOut, this.frameBuf, this.displayW, this.statsBuf, this.paramsBuf, this.stepBuf, ...this.staging]) b.destroy();
527 }
529 get fs(): number {
530 return this.params.fs;
531 }
532 get fps(): number {
533 return this.params.fps;
534 }
535 get physParams(): PhysParams {
536 return this.params;
537 }
↑↓ move↵openescclose