/ proof-of-concept / steelsim21
Sign in
proof-of-concept / steelsim21
steelsim21 / src / sim / simulation.ts
630 lines · 24.5 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 initialShape,
16 strikePoint,
17 nodeX,
18 nodeY,
19 trapWeight,
20 HIST_LEN,
21 RB_INTERVAL,
22 RB_INTERVAL_HELD,
23 RHO_AIR,
24 SPEED_OF_SOUND,
25} from "../params.ts";
26import { maxAngularFrequency } from "./cpuRef.ts";
27import commonWgsl from "./shaders/common.wgsl?raw";
28import stepWgsl from "./shaders/step.wgsl?raw";
29import rigidWgsl from "./shaders/rigid.wgsl?raw";
30import audioWgsl from "./shaders/audio.wgsl?raw";
31import extractWgsl from "./shaders/extract.wgsl?raw";
33export type Phase = "push" | "hold" | "recording" | "done";
35export interface SimStatus {
36 phase: Phase;
37 /** Simulation time relative to the release [s]. */
38 t: number;
39 totalSteps: number;
40 ke: number;
41 wmax: number;
42 samples: number;
43 frames: number;
44 peakPressure: number;
45 delayClamped: boolean;
46 /** Drumstick state (strike excitation only). */
47 stick: { x: number; v: number; force: number; maxForce: number } | null;
50const STATS_LEN = 16;
51const STICK_LEN = 8;
53export class Simulation {
54 readonly grid: Grid;
55 readonly mat: Material;
56 readonly dt: number;
57 /** Time steps per audio sample. */
58 readonly stepsPerSample: number;
59 readonly samplesPerBatch: number;
60 readonly stepsPerBatch: number;
61 readonly omegaMax: number;
63 /** Raw listener pressure [Pa] at fs, from the release. */
64 audio: Float32Array = new Float32Array(0);
65 samples = 0;
66 /** Movie frames of w [m]; frame k is at t = k / fps. */
67 frames: Float32Array<ArrayBuffer>[] = [];
69 phase: Phase = "push";
70 /** Steps since the start of the current phase clock (prep or recording). */
71 private stepCount = 0;
72 private prepTime = 0;
73 totalSteps = 0;
74 ke = 0;
75 wmax = 0;
76 peakPressure = 0;
77 delayClamped = false;
78 private hpState = { y: 0, x: 0 };
80 private device: GPUDevice;
81 private params: PhysParams;
82 private paramsBuf: GPUBuffer;
83 private stepBuf: GPUBuffer;
84 private stepStride: number;
85 private stepData: ArrayBuffer;
86 private pos: GPUBuffer[];
87 private vel: GPUBuffer[];
88 private hist: GPUBuffer;
89 private react: GPUBuffer;
90 /** Stress-free initial shape (f32 per node), also used by the renderer. */
91 readonly w0: GPUBuffer;
92 private lw: GPUBuffer;
93 private audioOut: GPUBuffer;
94 private frameBuf: GPUBuffer;
95 private statsBuf: GPUBuffer;
96 private staging: GPUBuffer[];
97 private stagingIdx = 0;
98 /** Index of the buffer pair holding the current state. */
99 private cur = 0;
100 /** The `displayW` buffer is a plain f32 array of w for the renderer. */
101 readonly displayW: GPUBuffer;
103 private stepPipe: GPUComputePipeline;
104 private sumsPipe: GPUComputePipeline;
105 private applyPipe: GPUComputePipeline;
106 private projectPipe: GPUComputePipeline;
107 private projectBG: GPUBindGroup;
108 private audioPipe: GPUComputePipeline;
109 private extractPipe: GPUComputePipeline;
110 private stepBG: GPUBindGroup[];
111 private rbBG: GPUBindGroup[];
112 private audioBG: GPUBindGroup;
113 private extractBG: GPUBindGroup[];
114 private displayBG: GPUBindGroup[];
115 private stagingSize: number;
117 constructor(device: GPUDevice, params: PhysParams) {
118 this.device = device;
119 this.params = { ...params };
120 const g = makeGrid(params);
121 const m = makeMaterial(params);
122 this.grid = g;
123 this.mat = m;
125 // Stable time step, aligned so that an integer number of steps make one audio sample.
126 this.omegaMax = maxAngularFrequency(g, m);
127 const dtMax = (0.85 * 2) / this.omegaMax;
128 this.stepsPerSample = Math.ceil(1 / (params.fs * dtMax));
129 this.dt = 1 / (params.fs * this.stepsPerSample);
130 this.samplesPerBatch = Math.max(1, Math.round(params.fs / params.fps));
131 this.stepsPerBatch = this.samplesPerBatch * this.stepsPerSample;
133 const n = g.n;
134 const f32 = (size: number, usage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) =>
135 device.createBuffer({ size: Math.max(16, size * 4), usage });
137 this.pos = [f32(4 * n), f32(4 * n)]; // [u | v | w | wLo]
138 this.vel = [f32(3 * n), f32(3 * n)]; // [du | dv | dw]
139 this.hist = f32(HIST_LEN * n);
140 this.react = f32(n + STICK_LEN);
141 this.w0 = f32(n);
142 device.queue.writeBuffer(this.w0, 0, initialShape(params, g));
143 this.lw = f32(2 * n);
144 this.audioOut = f32(this.samplesPerBatch);
145 this.frameBuf = f32(n);
146 this.displayW = f32(n);
147 this.statsBuf = f32(STATS_LEN);
148 this.stagingSize = (this.samplesPerBatch + n + STATS_LEN + STICK_LEN) * 4;
149 this.staging = [0, 1].map(() =>
150 device.createBuffer({ size: this.stagingSize, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }),
151 );
153 // Constant parameters.
154 let mass = 0, Ix = 0, Iy = 0;
155 for (let j = 0; j < g.ny; j++) {
156 for (let i = 0; i < g.nx; i++) {
157 const mk = m.rhoh * g.hx * g.hy * trapWeight(g, i, j);
158 mass += mk;
159 Ix += mk * nodeY(g, j) ** 2;
160 Iy += mk * nodeX(g, i) ** 2;
161 }
162 }
163 // Drumstick contact patch.
164 const [sx, sy] = strikePoint(params);
165 let strikeNode = 0, best = Infinity, patchMass = 0;
166 for (let j = 0; j < g.ny; j++) {
167 for (let i = 0; i < g.nx; i++) {
168 const d2 = (nodeX(g, i) - sx) ** 2 + (nodeY(g, j) - sy) ** 2;
169 if (d2 < best) { best = d2; strikeNode = j * g.nx + i; }
170 }
171 }
172 for (let j = 0; j < g.ny; j++) {
173 for (let i = 0; i < g.nx; i++) {
174 const d2 = (nodeX(g, i) - sx) ** 2 + (nodeY(g, j) - sy) ** 2;
175 if (d2 <= params.contactRadius ** 2 || j * g.nx + i === strikeNode) patchMass += m.rhoh * g.hx * g.hy * trapWeight(g, i, j);
176 }
177 }
178 const stick = new Float32Array(STICK_LEN);
179 stick[0] = 0; stick[1] = -params.strikeVelocity; stick[4] = 0; stick[5] = -params.strikeVelocity;
180 device.queue.writeBuffer(this.react, n * 4, stick);
182 const pf = new Float32Array(28);
183 const pu = new Uint32Array(pf.buffer);
184 pu[0] = g.nx; pu[1] = g.ny; pu[2] = n; pu[3] = HIST_LEN;
185 pf[4] = g.hx; pf[5] = g.hy; pf[6] = this.dt; pf[7] = m.nu;
186 pf[8] = m.D; pf[9] = m.C; pf[10] = m.G; pf[11] = m.rhoh;
187 pf[12] = params.Lx / 2; pf[13] = -params.Ly / 2; pf[14] = params.fingerRadius ** 2; pf[15] = mass;
188 pf[16] = Ix; pf[17] = Iy; pf[18] = Ix + Iy; pf[19] = params.fs;
189 pf[20] = sx; pf[21] = sy; pf[22] = params.contactRadius ** 2; pf[23] = patchMass;
190 pu[24] = strikeNode; pf[25] = params.contactStiffness; pf[26] = params.contactExponent; pf[27] = params.stickMass;
191 this.paramsBuf = device.createBuffer({ size: pf.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
192 device.queue.writeBuffer(this.paramsBuf, 0, pf);
194 // Per-step parameters, one 48-byte struct per step at a dynamic offset.
195 this.stepStride = Math.max(48, device.limits.minUniformBufferOffsetAlignment);
196 this.stepData = new ArrayBuffer(this.stepStride * this.stepsPerBatch);
197 this.stepBuf = device.createBuffer({ size: this.stepData.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
199 const mk = (code: string, entry: string, layout: GPUPipelineLayout | "auto" = "auto") =>
200 device.createComputePipeline({
201 layout,
202 compute: { module: device.createShaderModule({ code: commonWgsl + code }), entryPoint: entry },
203 });
204 const entry = (binding: number, type: GPUBufferBindingType, hasDynamicOffset = false): GPUBindGroupLayoutEntry => ({
205 binding,
206 visibility: GPUShaderStage.COMPUTE,
207 buffer: { type, hasDynamicOffset },
208 });
209 const stepLayout = device.createBindGroupLayout({
210 entries: [
211 entry(0, "uniform"),
212 entry(1, "uniform", true),
213 entry(2, "read-only-storage"),
214 entry(3, "read-only-storage"),
215 entry(4, "storage"),
216 entry(5, "storage"),
217 entry(6, "storage"),
218 entry(7, "storage"),
219 entry(8, "read-only-storage"),
220 ],
221 });
222 this.stepPipe = mk(stepWgsl, "main", device.createPipelineLayout({ bindGroupLayouts: [stepLayout] }));
223 const audioLayout = device.createBindGroupLayout({
224 entries: [entry(0, "uniform"), entry(1, "uniform", true), entry(2, "read-only-storage"), entry(3, "read-only-storage"), entry(4, "storage")],
225 });
226 const rigidModule = device.createShaderModule({ code: commonWgsl + rigidWgsl });
227 const rbLayout = device.createBindGroupLayout({
228 entries: [
229 { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "uniform" } },
230 { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
231 { binding: 2, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
232 { binding: 3, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
233 ],
234 });
235 const rbPipeLayout = device.createPipelineLayout({ bindGroupLayouts: [rbLayout] });
236 this.sumsPipe = device.createComputePipeline({ layout: rbPipeLayout, compute: { module: rigidModule, entryPoint: "sums" } });
237 this.applyPipe = device.createComputePipeline({ layout: rbPipeLayout, compute: { module: rigidModule, entryPoint: "apply" } });
238 const projectLayout = device.createBindGroupLayout({
239 entries: [
240 { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "uniform" } },
241 { binding: 4, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } },
242 ],
243 });
244 this.projectPipe = device.createComputePipeline({
245 layout: device.createPipelineLayout({ bindGroupLayouts: [projectLayout] }),
246 compute: { module: rigidModule, entryPoint: "projectField" },
247 });
248 this.audioPipe = mk(audioWgsl, "main", device.createPipelineLayout({ bindGroupLayouts: [audioLayout] }));
249 this.extractPipe = mk(extractWgsl, "main");
251 const sp = { buffer: this.stepBuf, size: 48 };
252 this.stepBG = [0, 1].map((p) =>
253 device.createBindGroup({
254 layout: stepLayout,
255 entries: [
256 { binding: 0, resource: { buffer: this.paramsBuf } },
257 { binding: 1, resource: sp },
258 { binding: 2, resource: { buffer: this.pos[p] } },
259 { binding: 3, resource: { buffer: this.vel[p] } },
260 { binding: 4, resource: { buffer: this.pos[1 - p] } },
261 { binding: 5, resource: { buffer: this.vel[1 - p] } },
262 { binding: 6, resource: { buffer: this.hist } },
263 { binding: 7, resource: { buffer: this.react } },
264 { binding: 8, resource: { buffer: this.w0 } },
265 ],
266 }),
267 );
268 this.rbBG = [0, 1].map((p) =>
269 device.createBindGroup({
270 layout: rbLayout,
271 entries: [
272 { binding: 0, resource: { buffer: this.paramsBuf } },
273 { binding: 1, resource: { buffer: this.pos[p] } },
274 { binding: 2, resource: { buffer: this.vel[p] } },
275 { binding: 3, resource: { buffer: this.statsBuf } },
276 ],
277 }),
278 );
279 this.projectBG = device.createBindGroup({
280 layout: projectLayout,
281 entries: [
282 { binding: 0, resource: { buffer: this.paramsBuf } },
283 { binding: 4, resource: { buffer: this.react } },
284 ],
285 });
286 this.audioBG = device.createBindGroup({
287 layout: audioLayout,
288 entries: [
289 { binding: 0, resource: { buffer: this.paramsBuf } },
290 { binding: 1, resource: sp },
291 { binding: 2, resource: { buffer: this.hist } },
292 { binding: 3, resource: { buffer: this.lw } },
293 { binding: 4, resource: { buffer: this.audioOut } },
294 ],
295 });
296 const extractBG = (p: number, out: GPUBuffer) =>
297 device.createBindGroup({
298 layout: this.extractPipe.getBindGroupLayout(0),
299 entries: [
300 { binding: 0, resource: { buffer: this.paramsBuf } },
301 { binding: 1, resource: { buffer: this.pos[p] } },
302 { binding: 2, resource: { buffer: out } },
303 ],
304 });
305 this.extractBG = [0, 1].map((p) => extractBG(p, this.frameBuf));
306 this.displayBG = [0, 1].map((p) => extractBG(p, this.displayW));
308 this.setListener(params.listenerDist, params.listenerAzimuth, params.listenerElevation, params.radiation);
309 if (params.excitation === "strike") {
310 // No push phase: the sheet is at rest in its natural shape when the stick arrives.
311 this.phase = "recording";
312 this.frames.push(new Float32Array(n));
313 }
314 }
316 /** Recomputes the per-node weights and delays of the listener sum. Takes effect on later samples. */
317 setListener(dist: number, azimuthDeg: number, elevationDeg: number, radiation: "rayleigh" | "dipole"): void {
318 const g = this.grid;
319 const az = (azimuthDeg * Math.PI) / 180;
320 const el = (elevationDeg * Math.PI) / 180;
321 const L = [dist * Math.sin(az) * Math.cos(el), dist * Math.sin(el), dist * Math.cos(az) * Math.cos(el)];
322 const data = new Float32Array(2 * g.n);
323 let dmin = Infinity;
324 for (let j = 0; j < g.ny; j++) {
325 for (let i = 0; i < g.nx; i++) {
326 const k = j * g.nx + i;
327 const rx = L[0] - nodeX(g, i), ry = L[1] - nodeY(g, j), rz = L[2];
328 const r = Math.sqrt(rx * rx + ry * ry + rz * rz);
329 const dA = g.hx * g.hy * trapWeight(g, i, j);
330 let wgt = (RHO_AIR * dA) / (2 * Math.PI * r);
331 if (radiation === "dipole") wgt *= Math.abs(rz) / r;
332 data[2 * k] = wgt;
333 data[2 * k + 1] = (r / SPEED_OF_SOUND) * this.params.fs;
334 dmin = Math.min(dmin, data[2 * k + 1]);
335 }
336 }
337 this.delayClamped = false;
338 for (let k = 0; k < g.n; k++) {
339 let d = data[2 * k + 1] - dmin;
340 if (d > HIST_LEN - 3) {
341 d = HIST_LEN - 3;
342 this.delayClamped = true;
343 }
344 data[2 * k + 1] = d;
345 }
346 this.device.queue.writeBuffer(this.lw, 0, data);
347 this.params.listenerDist = dist;
348 this.params.listenerAzimuth = azimuthDeg;
349 this.params.listenerElevation = elevationDeg;
350 this.params.radiation = radiation;
351 }
353 setDamping(sigma0: number, sigma1: number, sigmaIn: number): void {
354 this.params.sigma0 = sigma0;
355 this.params.sigma1 = sigma1;
356 this.params.sigmaIn = sigmaIn;
357 }
359 setDuration(duration: number): void {
360 this.params.duration = duration;
361 if (this.phase === "done" && this.samples < this.targetSamples()) this.phase = "recording";
362 }
364 targetSamples(): number {
365 return Math.round(this.params.duration * this.params.fs);
366 }
368 status(): SimStatus {
369 const t = this.phase === "push" || this.phase === "hold" ? this.prepTime - this.prepDuration() : this.stepCount * this.dt;
370 return {
371 phase: this.phase,
372 t,
373 totalSteps: this.totalSteps,
374 ke: this.ke,
375 wmax: this.wmax,
376 samples: this.samples,
377 frames: this.frames.length,
378 peakPressure: this.peakPressure,
379 delayClamped: this.delayClamped,
380 stick: this.stick,
381 };
382 }
384 private prepDuration(): number {
385 return this.params.rampTime + this.params.holdMax;
386 }
388 /** Enqueues an extraction of the current w field into `displayW` (for the live view). */
389 encodeDisplay(encoder: GPUCommandEncoder): void {
390 const pass = encoder.beginComputePass();
391 pass.setPipeline(this.extractPipe);
392 pass.setBindGroup(0, this.displayBG[this.cur]);
393 pass.dispatchWorkgroups(Math.ceil(this.grid.n / 256));
394 pass.end();
395 }
397 /** Listener audio with the radiation post-processing applied [Pa]. */
398 processedAudio(): Float32Array {
399 return this.processed.subarray(0, this.samples);
400 }
401 private processed: Float32Array = new Float32Array(0);
403 private appendAudio(raw: Float32Array): void {
404 const need = this.samples + raw.length;
405 if (this.audio.length < need) {
406 const grow = Math.max(need, 2 * this.audio.length, this.params.fs);
407 const a = new Float32Array(grow);
408 a.set(this.audio.subarray(0, this.samples));
409 this.audio = a;
410 const b = new Float32Array(grow);
411 b.set(this.processed.subarray(0, this.samples));
412 this.processed = b;
413 }
414 this.audio.set(raw, this.samples);
415 // Dipole option: first-order high-pass at the baffle cutoff c / (2 sqrt(Lx Ly)).
416 const dipole = this.params.radiation === "dipole";
417 const fc = SPEED_OF_SOUND / (2 * Math.sqrt(this.params.Lx * this.params.Ly));
418 const alpha = 1 / (1 + (2 * Math.PI * fc) / this.params.fs);
419 for (let k = 0; k < raw.length; k++) {
420 const x = raw[k];
421 let y = x;
422 if (dipole) {
423 y = alpha * (this.hpState.y + x - this.hpState.x);
424 }
425 this.hpState = { y, x };
426 this.processed[this.samples + k] = y;
427 this.peakPressure = Math.max(this.peakPressure, Math.abs(y));
428 }
429 this.samples = need;
430 }
432 /** Runs one batch (one movie frame of time). Resolves when its results have been read back. */
433 async runBatch(): Promise<void> {
434 if (this.phase === "done") return;
435 const p = this.params;
436 const recording = this.phase === "recording";
437 const nSteps = this.stepsPerBatch;
438 const stepsLeft = recording ? (this.targetSamples() - this.samples) * this.stepsPerSample : nSteps;
439 const steps = Math.min(nSteps, Math.max(0, stepsLeft));
440 if (steps === 0) {
441 this.phase = "done";
442 return;
443 }
445 // Fill the per-step parameters.
446 const u32 = new Uint32Array(this.stepData);
447 const i32 = new Int32Array(this.stepData);
448 const f32 = new Float32Array(this.stepData);
449 const stride = this.stepStride / 4;
450 const audioStepsInBatch: number[] = [];
451 for (let s = 0; s < steps; s++) {
452 const o = s * stride;
453 const local = this.stepCount + s;
454 u32[o] = this.totalSteps + s;
455 let flags = 0, pushW = 0, pushV = 0, sigma0 = p.sigma0, slot = -1, outIdx = -1, releaseGain = 0;
456 const parity = (this.totalSteps + s) & 1;
457 if (!recording) {
458 const t = this.prepTime + (s + 1) * this.dt; // state after this step
459 const tau = Math.min(1, t / p.rampTime);
460 const smooth = tau * tau * (3 - 2 * tau);
461 const dsmooth = tau < 1 ? (6 * tau * (1 - tau)) / p.rampTime : 0;
462 flags = 1 | (tau >= 1 ? 2 : 0); // record the reaction once the ramp is complete
463 pushW = p.pushAmount * smooth;
464 pushV = p.pushAmount * dsmooth;
465 sigma0 = p.settleSigma0;
466 } else {
467 const t = local * this.dt;
468 if (p.excitation === "strike") {
469 flags = 8;
470 } else if (p.releaseTime > 0 && t < p.releaseTime) {
471 const tau = t / p.releaseTime;
472 releaseGain = 1 - tau * tau * (3 - 2 * tau);
473 flags = 4;
474 }
475 if (local % this.stepsPerSample === 0) {
476 const sampleIdx = local / this.stepsPerSample;
477 slot = sampleIdx % HIST_LEN;
478 outIdx = audioStepsInBatch.length;
479 audioStepsInBatch.push(s);
480 }
481 }
482 u32[o + 1] = flags;
483 i32[o + 2] = slot;
484 i32[o + 3] = outIdx;
485 f32[o + 4] = pushW;
486 f32[o + 5] = pushV;
487 f32[o + 6] = sigma0;
488 f32[o + 7] = p.sigma1;
489 f32[o + 8] = releaseGain;
490 f32[o + 9] = p.sigmaIn;
491 u32[o + 10] = parity;
492 }
493 this.device.queue.writeBuffer(this.stepBuf, 0, this.stepData, 0, steps * this.stepStride);
495 // Encode the batch in chunks so that the GPU starts while JS is still encoding.
496 const CHUNK = 1024;
497 let enc = this.device.createCommandEncoder();
498 let pass = enc.beginComputePass();
499 const wgX = Math.ceil(this.grid.nx / 16), wgY = Math.ceil(this.grid.ny / 16);
500 const wgN = Math.ceil(this.grid.n / 256);
501 let cur = this.cur;
502 let audioPtr = 0;
503 const rbInterval = recording ? RB_INTERVAL : RB_INTERVAL_HELD;
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 (global % rbInterval === 0 || s === steps - 1) {
522 pass.setPipeline(this.sumsPipe);
523 pass.setBindGroup(0, this.rbBG[cur]);
524 pass.dispatchWorkgroups(1);
525 pass.setPipeline(this.applyPipe);
526 pass.setBindGroup(0, this.rbBG[cur]);
527 pass.dispatchWorkgroups(wgN);
528 stepBound = false;
529 }
530 if (audioPtr < audioStepsInBatch.length && audioStepsInBatch[audioPtr] === s) {
531 pass.setPipeline(this.audioPipe);
532 pass.setBindGroup(0, this.audioBG, [s * this.stepStride]);
533 pass.dispatchWorkgroups(1);
534 audioPtr++;
535 stepBound = false;
536 }
537 }
538 pass.setPipeline(this.extractPipe);
539 pass.setBindGroup(0, this.extractBG[cur]);
540 pass.dispatchWorkgroups(wgN);
541 pass.end();
542 const staging = this.staging[this.stagingIdx];
543 this.stagingIdx = 1 - this.stagingIdx;
544 const nAudio = audioStepsInBatch.length;
545 enc.copyBufferToBuffer(this.audioOut, 0, staging, 0, Math.max(4, nAudio * 4));
546 enc.copyBufferToBuffer(this.frameBuf, 0, staging, this.samplesPerBatch * 4, this.grid.n * 4);
547 enc.copyBufferToBuffer(this.statsBuf, 0, staging, (this.samplesPerBatch + this.grid.n) * 4, STATS_LEN * 4);
548 enc.copyBufferToBuffer(this.react, this.grid.n * 4, staging, (this.samplesPerBatch + this.grid.n + STATS_LEN) * 4, STICK_LEN * 4);
549 this.device.queue.submit([enc.finish()]);
550 this.cur = cur;
551 this.totalSteps += steps;
552 this.stepCount += steps;
553 if (!recording) this.prepTime += steps * this.dt;
555 await staging.mapAsync(GPUMapMode.READ);
556 const view = new Float32Array(staging.getMappedRange());
557 const stats = view.subarray(this.samplesPerBatch + this.grid.n, this.samplesPerBatch + this.grid.n + STATS_LEN);
558 this.ke = stats[12];
559 this.wmax = stats[13];
560 if (p.excitation === "strike") {
561 // The slot written by the last step is the one the next step reads.
562 const base = this.samplesPerBatch + this.grid.n + STATS_LEN + 4 * (this.totalSteps & 1);
563 this.stick = { x: view[base], v: view[base + 1], force: view[base + 2], maxForce: view[base + 3] };
564 }
565 if (recording) {
566 this.appendAudio(view.slice(0, nAudio));
567 this.frames.push(view.slice(this.samplesPerBatch, this.samplesPerBatch + this.grid.n));
568 } else {
569 this.lastPrepFrame = view.slice(this.samplesPerBatch, this.samplesPerBatch + this.grid.n);
570 }
571 staging.unmap();
573 if (!recording) {
574 if (this.phase === "push" && this.prepTime >= p.rampTime) this.phase = "hold";
575 const settled = this.phase === "hold" && this.ke < p.settleKE;
576 if (settled || this.prepTime >= this.prepDuration()) this.release();
577 } else if (this.samples >= this.targetSamples()) {
578 this.phase = "done";
579 }
580 }
581 private lastPrepFrame: Float32Array<ArrayBuffer> | null = null;
582 private stick: SimStatus["stick"] = null;
584 private release(): void {
585 this.phase = "recording";
586 this.stepCount = 0;
587 this.totalSteps = 0;
588 // The finger force and the distributed holding reaction relax together:
589 // remove the rigid-body components of the recorded reaction.
590 const enc = this.device.createCommandEncoder();
591 const pass = enc.beginComputePass();
592 pass.setPipeline(this.projectPipe);
593 pass.setBindGroup(0, this.projectBG);
594 pass.dispatchWorkgroups(1);
595 pass.end();
596 this.device.queue.submit([enc.finish()]);
597 // Frame 0 is the held, settled shape.
598 if (this.lastPrepFrame) this.frames.push(this.lastPrepFrame);
599 }
601 /** Reads back the full state (debugging and tests). */
602 async readState(): Promise<{ pos: Float32Array; vel: Float32Array }> {
603 const n = this.grid.n;
604 const stg = this.device.createBuffer({ size: 7 * n * 4, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
605 const enc = this.device.createCommandEncoder();
606 enc.copyBufferToBuffer(this.pos[this.cur], 0, stg, 0, 4 * n * 4);
607 enc.copyBufferToBuffer(this.vel[this.cur], 0, stg, 4 * n * 4, 3 * n * 4);
608 this.device.queue.submit([enc.finish()]);
609 await stg.mapAsync(GPUMapMode.READ);
610 const all = new Float32Array(stg.getMappedRange()).slice();
611 stg.unmap();
612 stg.destroy();
613 // Returned as [u | v | w | wLo] and [du | dv | dw].
614 return { pos: all.subarray(0, 4 * n), vel: all.subarray(4 * n) };
615 }
617 destroy(): void {
618 for (const b of [...this.pos, ...this.vel, this.hist, this.react, this.w0, this.lw, this.audioOut, this.frameBuf, this.displayW, this.statsBuf, this.paramsBuf, this.stepBuf, ...this.staging]) b.destroy();
619 }
621 get fs(): number {
622 return this.params.fs;
623 }
624 get fps(): number {
625 return this.params.fps;
626 }
627 get physParams(): PhysParams {
628 return this.params;
629 }
↑↓ move↵openescclose