1ee087eCymbal designer: scripted design, thickness field, mount, single strikeJeremy Magland 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
4// batch encodes one compute dispatch per time step (with a per-step uniform
5// addressed by dynamic offset), an optional rigid-body projection every
6// RB_INTERVAL steps, one retarded-time listener sum over the batch's audio
7// samples, and one movie-frame extraction at the end. Audio, frame, and
8// statistics are read back after every batch. One batch is kept encoded
9// ahead of the one being read back, so the GPU does not wait for the
10// readback or for the encoding. The recording starts at the impact, with the
11// plate at rest in its stress-free shape.
13import {
14 type SimParams,
15 type Plate,
16 type Grid,
17 strikePoint,
18 contactPatch,
19 mountPatch,
20 massProperties,
21 thicknessRange,
22 nodeX,
23 nodeY,
24 nodeWeight,
25 nodeWeights,
26 CFL,
27 HIST_MARGIN,
28 RB_INTERVAL,
29 RHO_AIR,
30 SPEED_OF_SOUND,
31} from "../params.ts";
32import { maxAngularFrequency } from "./cpuRef.ts";
33import commonWgsl from "./shaders/common.wgsl?raw";
34import stepWgsl from "./shaders/step.wgsl?raw";
35import rigidWgsl from "./shaders/rigid.wgsl?raw";
36import audioWgsl from "./shaders/audio.wgsl?raw";
37import extractWgsl from "./shaders/extract.wgsl?raw";
39export type Phase = "recording" | "done";
41export interface StickState {
42 x: number;
43 v: number;
44 force: number;
45 maxForce: number;
46}
48export interface SimStatus {
49 phase: Phase;
50 /** Simulation time since the impact [s]. */
51 t: number;
52 totalSteps: number;
53 ke: number;
54 wmax: number;
55 samples: number;
56 frames: number;
57 peakPressure: number;
58 delayClamped: boolean;
59 stick: StickState;
60}
62const PARAMS_LEN = 40; // floats in the Params uniform
63const STEP_LEN = 12; // floats in the StepParams uniform
64const STATS_LEN = 16;
65const STICK_LEN = 8;
66/** Nodes per workgroup along each axis in step.wgsl. */
67const TILE = 12;
69/** A batch that has been encoded and submitted but not read back. */
70interface Pending {
71 staging: GPUBuffer;
72 steps: number;
73 nAudio: number;
74 /** Which of the two stick-state slots the batch's last step wrote. */
75 stickParity: number;
76}
78export class Simulation {
79 readonly plate: Plate;
80 readonly grid: Grid;
81 readonly dt: number;
82 /** Time steps per audio sample. */
83 readonly stepsPerSample: number;
84 readonly samplesPerBatch: number;
85 readonly stepsPerBatch: number;
86 readonly omegaMax: number;
87 /** Ring buffer length of the listener sum [samples]. */
88 readonly histLen: number;
89 /** Total mass of the plate [kg]. */
90 readonly mass: number;
92 /** Listener pressure [Pa] at fs, from the impact. */
93 audio: Float32Array = new Float32Array(0);
94 samples = 0;
95 /** Movie frames of w [m]; frame k is at t = k / fps. */
96 frames: Float32Array<ArrayBuffer>[] = [];
98 phase: Phase = "recording";
99 totalSteps = 0;
100 ke = 0;
101 wmax = 0;
102 peakPressure = 0;
103 delayClamped = false;
105 private stick: StickState;
106 private inFlight: Pending | null = null;
108 private device: GPUDevice;
109 private params: SimParams;
110 private paramsBuf: GPUBuffer;
111 private stepBuf: GPUBuffer;
112 private stepStride: number;
113 private stepData: ArrayBuffer;
114 private pos: GPUBuffer[];
115 private vel: GPUBuffer[];
116 private hist: GPUBuffer;
117 private stickBuf: GPUBuffer;
118 /** Static per-node data for the kernels, packed as (w0, weight, thickness, 0) per node. */
119 private nd: GPUBuffer;
120 /** Stress-free initial shape (f32 per node), for the renderer. */
121 readonly w0: GPUBuffer;
122 /** Largest magnitude of the initial shape [m]. */
123 readonly w0Max: number;
124 /** Node weights (f32 per node, 0 outside the plate), for the renderer. */
125 readonly nw: GPUBuffer;
126 /** Thickness (f32 per node, 0 outside the plate), for the renderer. */
127 readonly hn: GPUBuffer;
128 private lw: GPUBuffer;
129 private audioOut: GPUBuffer;
130 private frameBuf: GPUBuffer;
131 private statsBuf: GPUBuffer;
132 private staging: GPUBuffer[];
133 private stagingIdx = 0;
134 private stagingSize: number;
135 /** Index of the buffer pair holding the current state. */
136 private cur = 0;
137 /** Plain f32 array of w for the live view. */
138 readonly displayW: GPUBuffer;
140 private stepPipe: GPUComputePipeline;
141 private sumsPipe: GPUComputePipeline;
142 private applyPipe: GPUComputePipeline;
143 private audioPipe: GPUComputePipeline;
144 private extractPipe: GPUComputePipeline;
145 private stepBG: GPUBindGroup[];
146 private rbBG: GPUBindGroup[];
147 private audioBG: GPUBindGroup;
148 private extractBG: GPUBindGroup[];
149 private displayBG: GPUBindGroup[];
151 constructor(device: GPUDevice, plate: Plate, params: SimParams) {
152 this.device = device;
153 this.plate = plate;
154 this.params = { ...params };
155 const g = plate.grid;
156 const m = plate.mat;
157 this.grid = g;
159 // Stable time step, rounded so that an integer number of steps make one audio sample.
160 const hr = thicknessRange(plate);
161 this.omegaMax = maxAngularFrequency(g, m, hr.max, params.inPlaneMass);
162 const dtMax = (CFL * 2) / this.omegaMax;
163 this.stepsPerSample = Math.ceil(1 / (params.fs * dtMax));
164 this.dt = 1 / (params.fs * this.stepsPerSample);
165 this.samplesPerBatch = Math.max(1, Math.round(params.fs / params.fps));
166 this.stepsPerBatch = this.samplesPerBatch * this.stepsPerSample;
167 this.histLen = this.samplesPerBatch + HIST_MARGIN;
169 const n = g.n;
170 const f32 = (size: number, usage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) =>
171 device.createBuffer({ size: Math.max(16, size * 4), usage });
173 this.pos = [f32(4 * n), f32(4 * n)]; // [u | v | w | wLo]
174 this.vel = [f32(3 * n), f32(3 * n)]; // [du | dv | dw]
175 this.hist = f32(this.histLen * n);
176 this.stickBuf = f32(STICK_LEN);
177 this.w0 = f32(n);
178 const shape = Float32Array.from(plate.w0);
179 device.queue.writeBuffer(this.w0, 0, shape);
180 this.w0Max = shape.reduce((mx, v) => Math.max(mx, Math.abs(v)), 0);
181 const weights = nodeWeights(g);
182 this.nw = f32(n);
183 device.queue.writeBuffer(this.nw, 0, weights);
184 const thick = Float32Array.from(plate.h);
185 this.hn = f32(n);
186 device.queue.writeBuffer(this.hn, 0, thick);
187 const packed = new Float32Array(4 * n);
188 for (let k = 0; k < n; k++) { packed[4 * k] = shape[k]; packed[4 * k + 1] = weights[k]; packed[4 * k + 2] = thick[k]; }
189 this.nd = f32(4 * n);
190 device.queue.writeBuffer(this.nd, 0, packed);
191 this.lw = f32(2 * n);
192 this.audioOut = f32(this.samplesPerBatch);
193 this.frameBuf = f32(n);
194 this.displayW = f32(n);
195 this.statsBuf = f32(STATS_LEN);
196 this.stagingSize = (this.samplesPerBatch + n + STATS_LEN + STICK_LEN) * 4;
197 this.staging = [0, 1].map(() =>
198 device.createBuffer({ size: this.stagingSize, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }),
199 );
201 // Mass and moments of inertia of the plate, the contact patch, the mount patch,
202 // and the initial stick state (position 0, moving toward the plate).
203 const { mass, Ix, Iy } = massProperties(plate);
204 this.mass = mass;
205 const cp = contactPatch(params, plate);
206 const mp = mountPatch(plate);
207 const stick = new Float32Array(STICK_LEN);
208 stick[1] = -params.strikeVelocity; stick[5] = -params.strikeVelocity;
209 device.queue.writeBuffer(this.stickBuf, 0, stick);
210 this.stick = { x: 0, v: -params.strikeVelocity, force: 0, maxForce: 0 };
212 const [sx, sy] = strikePoint(params, plate);
213 const pf = new Float32Array(PARAMS_LEN);
214 const pu = new Uint32Array(pf.buffer);
215 pu[0] = g.nx; pu[1] = g.ny; pu[2] = n; pu[3] = this.histLen;
216 pf[4] = g.hx; pf[5] = g.hy; pf[6] = this.dt; pf[7] = m.nu;
217 pf[8] = m.E / (12 * (1 - m.nu * m.nu)); pf[9] = m.E / (1 - m.nu * m.nu); pf[10] = m.E / (2 * (1 + m.nu)); pf[11] = m.rho;
218 pf[12] = mass; pf[13] = Ix; pf[14] = Iy; pf[15] = Ix + Iy;
219 pf[16] = params.fs; pf[17] = sx; pf[18] = sy; pf[19] = params.contactRadius ** 2;
220 pf[20] = cp.mass; pu[21] = cp.nearest; pf[22] = params.contactStiffness; pf[23] = params.contactExponent;
221 pf[24] = params.stickMass; pu[25] = cp.box[0]; pu[26] = cp.box[1]; pu[27] = cp.box[2];
222 pu[28] = cp.box[3]; pf[29] = cp.center[0]; pf[30] = cp.center[1]; pf[31] = params.inPlaneMass;
223 pf[32] = 1 / params.inPlaneMass;
224 if (mp && plate.mount) {
225 pf[33] = plate.mount.x; pf[34] = plate.mount.y; pf[35] = plate.mount.radius ** 2;
226 pf[36] = plate.mount.stiffness / mp.weight; pf[37] = plate.mount.damping / mp.weight;
227 pu[38] = mp.nearest; pu[39] = 1;
228 }
229 this.paramsBuf = device.createBuffer({ size: pf.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
230 device.queue.writeBuffer(this.paramsBuf, 0, pf);
232 // Per-step parameters, one struct per step at a dynamic offset.
233 this.stepStride = Math.max(STEP_LEN * 4, device.limits.minUniformBufferOffsetAlignment);
234 this.stepData = new ArrayBuffer(this.stepStride * this.stepsPerBatch);
235 this.stepBuf = device.createBuffer({ size: this.stepData.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
237 // Pipelines.
238 const shader = (code: string) => device.createShaderModule({ code: commonWgsl + code });
239 const entry = (binding: number, type: GPUBufferBindingType, hasDynamicOffset = false): GPUBindGroupLayoutEntry => ({
240 binding,
241 visibility: GPUShaderStage.COMPUTE,
242 buffer: { type, hasDynamicOffset },
243 });
244 const pipeline = (module: GPUShaderModule, entryPoint: string, layout: GPUBindGroupLayout) =>
245 device.createComputePipeline({ layout: device.createPipelineLayout({ bindGroupLayouts: [layout] }), compute: { module, entryPoint } });
247 const stepLayout = device.createBindGroupLayout({
248 entries: [
249 entry(0, "uniform"),
250 entry(1, "uniform", true),
251 entry(2, "read-only-storage"),
252 entry(3, "read-only-storage"),
253 entry(4, "storage"),
254 entry(5, "storage"),
255 entry(6, "storage"),
256 entry(7, "storage"),
257 entry(8, "read-only-storage"),
258 ],
259 });
260 this.stepPipe = pipeline(shader(stepWgsl), "main", stepLayout);
262 const rigidModule = shader(rigidWgsl);
263 const rbLayout = device.createBindGroupLayout({
264 entries: [entry(0, "uniform"), entry(1, "storage"), entry(2, "storage"), entry(3, "storage"), entry(8, "read-only-storage")],
265 });
266 this.sumsPipe = pipeline(rigidModule, "sums", rbLayout);
267 this.applyPipe = pipeline(rigidModule, "apply", rbLayout);
269 const audioLayout = device.createBindGroupLayout({
270 entries: [entry(0, "uniform"), entry(1, "uniform", true), entry(2, "read-only-storage"), entry(3, "read-only-storage"), entry(4, "storage")],
271 });
272 this.audioPipe = pipeline(shader(audioWgsl), "main", audioLayout);
274 const extractLayout = device.createBindGroupLayout({
275 entries: [entry(0, "uniform"), entry(1, "read-only-storage"), entry(2, "storage")],
276 });
277 this.extractPipe = pipeline(shader(extractWgsl), "main", extractLayout);
279 // Bind groups. The state is double-buffered: bind group p reads pair p and writes pair 1 - p.
280 const sp = { buffer: this.stepBuf, size: STEP_LEN * 4 };
281 this.stepBG = [0, 1].map((p) =>
282 device.createBindGroup({
283 layout: stepLayout,
284 entries: [
285 { binding: 0, resource: { buffer: this.paramsBuf } },
286 { binding: 1, resource: sp },
287 { binding: 2, resource: { buffer: this.pos[p] } },
288 { binding: 3, resource: { buffer: this.vel[p] } },
289 { binding: 4, resource: { buffer: this.pos[1 - p] } },
290 { binding: 5, resource: { buffer: this.vel[1 - p] } },
291 { binding: 6, resource: { buffer: this.hist } },
292 { binding: 7, resource: { buffer: this.stickBuf } },
293 { binding: 8, resource: { buffer: this.nd } },
294 ],
295 }),
296 );
297 this.rbBG = [0, 1].map((p) =>
298 device.createBindGroup({
299 layout: rbLayout,
300 entries: [
301 { binding: 0, resource: { buffer: this.paramsBuf } },
302 { binding: 1, resource: { buffer: this.pos[p] } },
303 { binding: 2, resource: { buffer: this.vel[p] } },
304 { binding: 3, resource: { buffer: this.statsBuf } },
305 { binding: 8, resource: { buffer: this.nd } },
306 ],
307 }),
308 );
309 this.audioBG = device.createBindGroup({
310 layout: audioLayout,
311 entries: [
312 { binding: 0, resource: { buffer: this.paramsBuf } },
313 { binding: 1, resource: sp },
314 { binding: 2, resource: { buffer: this.hist } },
315 { binding: 3, resource: { buffer: this.lw } },
316 { binding: 4, resource: { buffer: this.audioOut } },
317 ],
318 });
319 const extractBG = (p: number, out: GPUBuffer) =>
320 device.createBindGroup({
321 layout: extractLayout,
322 entries: [
323 { binding: 0, resource: { buffer: this.paramsBuf } },
324 { binding: 1, resource: { buffer: this.pos[p] } },
325 { binding: 2, resource: { buffer: out } },
326 ],
327 });
328 this.extractBG = [0, 1].map((p) => extractBG(p, this.frameBuf));
329 this.displayBG = [0, 1].map((p) => extractBG(p, this.displayW));
331 this.setListener(params.listenerDist, params.listenerAzimuth, params.listenerElevation);
332 // Frame 0: the plate at rest when the stick arrives.
333 this.frames.push(new Float32Array(n));
334 }
336 /** Recomputes the per-node weights and delays of the listener sum. Takes effect on later samples. */
337 setListener(dist: number, azimuthDeg: number, elevationDeg: number): void {
338 const g = this.grid;
339 const az = (azimuthDeg * Math.PI) / 180;
340 const el = (elevationDeg * Math.PI) / 180;
341 const L = [dist * Math.sin(az) * Math.cos(el), dist * Math.sin(el), dist * Math.cos(az) * Math.cos(el)];
342 const data = new Float32Array(2 * g.n);
343 let dmin = Infinity;
344 for (let j = 0; j < g.ny; j++) {
345 for (let i = 0; i < g.nx; i++) {
346 const k = j * g.nx + i;
347 const rx = L[0] - nodeX(g, i), ry = L[1] - nodeY(g, j), rz = L[2];
348 const r = Math.sqrt(rx * rx + ry * ry + rz * rz);
349 const dA = g.hx * g.hy * nodeWeight(g, i, j);
350 data[2 * k] = (RHO_AIR * dA) / (2 * Math.PI * r);
351 data[2 * k + 1] = (r / SPEED_OF_SOUND) * this.params.fs;
352 dmin = Math.min(dmin, data[2 * k + 1]);
353 }
354 }
355 // Only the spread of delays across the plate is kept; the common delay is dropped.
356 this.delayClamped = false;
357 for (let k = 0; k < g.n; k++) {
358 let d = data[2 * k + 1] - dmin;
359 if (d > HIST_MARGIN - 3) {
360 d = HIST_MARGIN - 3;
361 this.delayClamped = true;
362 }
363 data[2 * k + 1] = d;
364 }
365 this.device.queue.writeBuffer(this.lw, 0, data);
366 this.params.listenerDist = dist;
367 this.params.listenerAzimuth = azimuthDeg;
368 this.params.listenerElevation = elevationDeg;
369 }
371 setDuration(duration: number): void {
372 this.params.duration = duration;
373 if (this.canContinue()) this.phase = "recording";
374 }
376 /** True when a finished or stopped run can be extended. */
377 canContinue(): boolean {
378 return this.phase === "done" && this.samples < this.targetSamples();
379 }
381 /** Ends the run; the state, audio, and movie are kept. */
382 stop(): void {
383 this.phase = "done";
384 }
386 targetSamples(): number {
387 return Math.round(this.params.duration * this.params.fs);
388 }
390 status(): SimStatus {
391 // Report the time of the state that has been read back, not the one enqueued.
392 const ahead = this.inFlight ? this.inFlight.steps * this.dt : 0;
393 return {
394 phase: this.phase,
395 t: this.totalSteps * this.dt - ahead,
396 totalSteps: this.totalSteps,
397 ke: this.ke,
398 wmax: this.wmax,
399 samples: this.samples,
400 frames: this.frames.length,
401 peakPressure: this.peakPressure,
402 delayClamped: this.delayClamped,
403 stick: this.stick,
404 };
405 }
407 /** Enqueues an extraction of the current w field into `displayW` (for the live view). */
408 encodeDisplay(encoder: GPUCommandEncoder): void {
409 const pass = encoder.beginComputePass();
410 pass.setPipeline(this.extractPipe);
411 pass.setBindGroup(0, this.displayBG[this.cur]);
412 pass.dispatchWorkgroups(Math.ceil(this.grid.n / 256));
413 pass.end();
414 }
416 private stepWorkgroups(): [number, number] {
417 return [Math.ceil(this.grid.nx / TILE), Math.ceil(this.grid.ny / TILE)];
418 }
420 /** The recorded listener pressure so far [Pa]. */
421 recordedAudio(): Float32Array {
422 return this.audio.subarray(0, this.samples);
423 }
425 private appendAudio(raw: Float32Array): void {
426 const need = this.samples + raw.length;
427 if (this.audio.length < need) {
428 const a = new Float32Array(Math.max(need, 2 * this.audio.length, this.params.fs));
429 a.set(this.audio.subarray(0, this.samples));
430 this.audio = a;
431 }
432 this.audio.set(raw, this.samples);
433 for (let k = 0; k < raw.length; k++) this.peakPressure = Math.max(this.peakPressure, Math.abs(raw[k]));
434 this.samples = need;
435 }
437 /** Writes the per-step uniform for step s of a batch. */
438 private writeStepParams(s: number, fields: { flags: number; slot: number; outIdx: number }): void {
439 const o = (s * this.stepStride) / 4;
440 const u32 = new Uint32Array(this.stepData);
441 const i32 = new Int32Array(this.stepData);
442 const f32 = new Float32Array(this.stepData);
443 const { sigma0, sigma1, sigmaIn } = this.plate.loss;
444 u32[o] = this.totalSteps + s;
445 u32[o + 1] = fields.flags;
446 i32[o + 2] = fields.slot;
447 i32[o + 3] = fields.outIdx;
448 f32[o + 4] = sigma0;
449 f32[o + 5] = sigma1;
450 f32[o + 6] = sigmaIn;
451 u32[o + 7] = (this.totalSteps + s) & 1;
452 }
454 /**
455 * Runs one batch (one movie frame of time). Resolves when its results have
456 * been read back. The following batch is encoded before this one is awaited.
457 */
458 async runBatch(): Promise<void> {
459 if (this.phase === "done") return;
460 const cur = this.inFlight ?? this.encodeBatch();
461 this.inFlight = null;
462 if (!cur) {
463 this.phase = "done";
464 return;
465 }
466 if (this.stepsLeft() > 0) this.inFlight = this.encodeBatch();
467 await this.collect(cur);
468 }
470 private stepsLeft(): number {
471 return this.targetSamples() * this.stepsPerSample - this.totalSteps;
472 }
474 /** Encodes and submits one batch; null when no steps remain. */
475 private encodeBatch(): Pending | null {
476 const p = this.params;
477 const steps = Math.min(this.stepsPerBatch, Math.max(0, this.stepsLeft()));
478 if (steps === 0) return null;
480 // Per-step parameters: the drumstick and the audio bookkeeping.
481 const audioSteps: number[] = [];
482 for (let s = 0; s < steps; s++) {
483 const local = this.totalSteps + s;
484 let slot = -1, outIdx = -1;
485 if (local % this.stepsPerSample === 0) {
486 slot = (local / this.stepsPerSample) % this.histLen;
487 outIdx = audioSteps.length;
488 audioSteps.push(s);
489 }
490 this.writeStepParams(s, { flags: 1, slot, outIdx });
491 }
492 this.device.queue.writeBuffer(this.stepBuf, 0, this.stepData, 0, steps * this.stepStride);
494 // Encode the batch in chunks so that the GPU starts while JS is still encoding.
495 const CHUNK = 1024;
496 let enc = this.device.createCommandEncoder();
497 let pass = enc.beginComputePass();
498 const [wgX, wgY] = this.stepWorkgroups();
499 const wgN = Math.ceil(this.grid.n / 256);
500 let cur = this.cur;
501 // The projection is optional and only meaningful for a free plate; the
502 // sums still run once per batch for the statistics.
503 const project = p.rigidProjection && !this.plate.mount;
504 let stepBound = false;
505 for (let s = 0; s < steps; s++) {
506 if (s > 0 && s % CHUNK === 0) {
507 pass.end();
508 this.device.queue.submit([enc.finish()]);
509 enc = this.device.createCommandEncoder();
510 pass = enc.beginComputePass();
511 stepBound = false;
512 }
513 if (!stepBound) {
514 pass.setPipeline(this.stepPipe);
515 stepBound = true;
516 }
517 pass.setBindGroup(0, this.stepBG[cur], [s * this.stepStride]);
518 pass.dispatchWorkgroups(wgX, wgY);
519 cur = 1 - cur;
520 const global = this.totalSteps + s + 1;
521 if ((project && global % RB_INTERVAL === 0) || s === steps - 1) {
522 pass.setPipeline(this.sumsPipe);
523 pass.setBindGroup(0, this.rbBG[cur]);
524 pass.dispatchWorkgroups(1);
525 if (project) {
526 pass.setPipeline(this.applyPipe);
527 pass.setBindGroup(0, this.rbBG[cur]);
528 pass.dispatchWorkgroups(wgN);
529 }
530 stepBound = false;
531 }
532 }
533 // The listener sum for every audio sample of the batch, one workgroup each;
534 // the ring buffer is long enough that no slot of the batch has been reused.
535 const nAudio = audioSteps.length;
536 if (nAudio > 0) {
537 pass.setPipeline(this.audioPipe);
538 pass.setBindGroup(0, this.audioBG, [audioSteps[0] * this.stepStride]);
539 pass.dispatchWorkgroups(nAudio);
540 }
541 pass.setPipeline(this.extractPipe);
542 pass.setBindGroup(0, this.extractBG[cur]);
543 pass.dispatchWorkgroups(wgN);
544 pass.end();
545 const staging = this.staging[this.stagingIdx];
546 this.stagingIdx = 1 - this.stagingIdx;
547 const n = this.grid.n;
548 enc.copyBufferToBuffer(this.audioOut, 0, staging, 0, Math.max(4, nAudio * 4));
549 enc.copyBufferToBuffer(this.frameBuf, 0, staging, this.samplesPerBatch * 4, n * 4);
550 enc.copyBufferToBuffer(this.statsBuf, 0, staging, (this.samplesPerBatch + n) * 4, STATS_LEN * 4);
551 enc.copyBufferToBuffer(this.stickBuf, 0, staging, (this.samplesPerBatch + n + STATS_LEN) * 4, STICK_LEN * 4);
552 this.device.queue.submit([enc.finish()]);
553 this.cur = cur;
554 this.totalSteps += steps;
555 return { staging, steps, nAudio, stickParity: this.totalSteps & 1 };
556 }
558 /** Reads back a batch and applies its results. */
559 private async collect(b: Pending): Promise<void> {
560 const n = this.grid.n;
561 await b.staging.mapAsync(GPUMapMode.READ);
562 const view = new Float32Array(b.staging.getMappedRange());
563 const stats = view.subarray(this.samplesPerBatch + n, this.samplesPerBatch + n + STATS_LEN);
564 this.ke = stats[12];
565 this.wmax = stats[13];
566 // The slot written by the last step is the one the next step reads.
567 const base = this.samplesPerBatch + n + STATS_LEN + 4 * b.stickParity;
568 this.stick = { x: view[base], v: view[base + 1], force: view[base + 2], maxForce: view[base + 3] };
569 this.appendAudio(view.slice(0, b.nAudio));
570 this.frames.push(view.slice(this.samplesPerBatch, this.samplesPerBatch + n));
571 b.staging.unmap();
572 if (this.samples >= this.targetSamples()) this.phase = "done";
573 }
575 // ---------- Testing support ----------
577 /**
578 * Advances the state by exactly one free step (no drumstick, no rigid-body
579 * projection, no audio) with the plate's loss parameters and its mount.
580 */
581 async stepOnce(): Promise<void> {
582 this.writeStepParams(0, { flags: 0, slot: -1, outIdx: -1 });
583 this.device.queue.writeBuffer(this.stepBuf, 0, this.stepData, 0, this.stepStride);
584 const enc = this.device.createCommandEncoder();
585 const pass = enc.beginComputePass();
586 pass.setPipeline(this.stepPipe);
587 pass.setBindGroup(0, this.stepBG[this.cur], [0]);
588 pass.dispatchWorkgroups(...this.stepWorkgroups());
589 pass.end();
590 this.device.queue.submit([enc.finish()]);
591 this.cur = 1 - this.cur;
592 this.totalSteps++;
593 await this.device.queue.onSubmittedWorkDone();
594 }
596 /** Overwrites the state: pos as [u | v | w | wLo], vel as [du | dv | dw]. */
597 writeState(pos: Float32Array<ArrayBuffer>, vel: Float32Array<ArrayBuffer>): void {
598 const n = this.grid.n;
599 if (pos.length !== 4 * n || vel.length !== 3 * n) throw new Error("state arrays have the wrong length");
600 this.device.queue.writeBuffer(this.pos[this.cur], 0, pos);
601 this.device.queue.writeBuffer(this.vel[this.cur], 0, vel);
602 }
604 /** Reads back the full state as [u | v | w | wLo] and [du | dv | dw]. */
605 async readState(): Promise<{ pos: Float32Array; vel: Float32Array }> {
606 const n = this.grid.n;
607 const stg = this.device.createBuffer({ size: 7 * n * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
608 const enc = this.device.createCommandEncoder();
609 enc.copyBufferToBuffer(this.pos[this.cur], 0, stg, 0, 4 * n * 4);
610 enc.copyBufferToBuffer(this.vel[this.cur], 0, stg, 4 * n * 4, 3 * n * 4);
611 this.device.queue.submit([enc.finish()]);
612 await stg.mapAsync(GPUMapMode.READ);
613 const all = new Float32Array(stg.getMappedRange()).slice();
614 stg.unmap();
615 stg.destroy();
616 return { pos: all.subarray(0, 4 * n), vel: all.subarray(4 * n) };
617 }
619 destroy(): void {
620 this.inFlight = null;
621 for (const b of [...this.pos, ...this.vel, this.hist, this.stickBuf, this.nd, this.w0, this.nw, this.hn, this.lw, this.audioOut, this.frameBuf, this.displayW, this.statsBuf, this.paramsBuf, this.stepBuf, ...this.staging]) b.destroy();
622 }
624 get fs(): number {
625 return this.params.fs;
626 }
627 get fps(): number {
628 return this.params.fps;
629 }
630 get simParams(): SimParams {
631 return this.params;
632 }
633}