/ proof-of-concept / cymsimweb
Sign in
proof-of-concept / cymsimweb
cymsimweb / src / gpu / simulator.ts
192 lines · 11.7 KBBlameHistoryRaw
1// WebGPU time loop: packs the set-up into storage buffers, compiles the three kernels and runs
2// the sub-steps of a chunk of audio samples as one command buffer. Works in a browser and under
3// Node with the `webgpu` (Dawn) package, which the tests use.
4import { HOLD_HEIGHT } from "../model/exciter.ts";
5import { strainEnergies } from "../model/forces.ts";
6import { DECIMATION_SPAN } from "../model/radiation.ts";
7import type { Setup } from "../model/setup.ts";
8import type { ChunkResult, Diagnostics, SimulatorBackend } from "../model/simulator.ts";
9import { ELEM_STRIDE, HIT_HEADER, HITU_HEADER, NODE_STRIDE, SYNC_HEADER, WORKGROUP_NODES, shaderSource } from "./shaders.ts";
11// evaluated lazily: under Node the WebGPU globals are installed after this module is imported
12const storageUsage = () => GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC;
14export class GpuSimulator implements SimulatorBackend {
15 readonly kind = "gpu" as const;
16 readonly setup: Setup; readonly device: GPUDevice;
17 samplesDone = 0;
18 private step = 0;
19 private readonly G: number; private readonly HF: number; private readonly HU: number;
20 private readonly buffers: Record<string, GPUBuffer> = {};
21 private readonly pipelines: Record<string, GPUComputePipeline> = {};
22 private readonly bindGroups: Record<string, GPUBindGroup> = {};
23 private readonly chunkCapacity: number;
24 private readonly stagingPressure: GPUBuffer; private readonly stagingState: GPUBuffer; private readonly stagingHits: GPUBuffer; private readonly stagingHitsU: GPUBuffer;
26 constructor(device: GPUDevice, setup: Setup, chunkCapacity = 8192) {
27 this.device = device; this.setup = setup; this.chunkCapacity = chunkCapacity;
28 const { mesh, shell: sh, schedule: sc, radiation: rad, substeps: M, dt } = setup;
29 const N = mesh.n, E = mesh.e, K = sc.K, P = sc.P, W = DECIMATION_SPAN, D = rad.ringLength;
30 this.G = Math.ceil(N / WORKGROUP_NODES);
31 this.HF = HIT_HEADER + 5 * P; this.HU = HITU_HEADER + 3 * P;
32 const G = this.G, HF = this.HF, HU = this.HU;
34 // ---- pack the set-up
35 const elemF = new Float32Array(ELEM_STRIDE * E + W * M);
36 for (let e = 0; e < E; e++) {
37 const b = ELEM_STRIDE * e;
38 for (let i = 0; i < 3; i++) { elemF[b + i] = mesh.Gx[3 * e + i]; elemF[b + 3 + i] = mesh.Gy[3 * e + i]; }
39 elemF[b + 6] = mesh.area[e]; elemF[b + 7] = sh.z0x[e]; elemF[b + 8] = sh.z0y[e];
40 elemF[b + 9] = sh.Cm[3 * e]; elemF[b + 10] = sh.Cm[3 * e + 1]; elemF[b + 11] = sh.Cm[3 * e + 2];
41 elemF[b + 12] = 2 * setup.config.material.sigma1 * sh.rhoHA[e];
42 for (let i = 0; i < 81; i++) elemF[b + 13 + i] = sh.Ke[81 * e + i];
43 }
44 elemF.set(rad.taps, ELEM_STRIDE * E);
45 const elemU = new Uint32Array(3 * E); elemU.set(mesh.tri);
46 const nodeF = new Float32Array(NODE_STRIDE * N);
47 for (let n = 0; n < N; n++) {
48 const b = NODE_STRIDE * n;
49 for (let d = 0; d < 5; d++) { nodeF[b + d] = sh.Minv[5 * n + d]; nodeF[b + 5 + d] = sh.M[5 * n + d]; }
50 for (let k = 0; k < 6; k++) for (let d = 0; d < 5; d++) nodeF[b + 10 + 5 * k + d] = sh.Rm[(k * N + n) * 5 + d];
51 }
52 const adj = new Uint32Array(N + 1 + sh.adjEntries.length); adj.set(sh.adjOffsets); adj.set(sh.adjEntries, N + 1);
53 const hitsF = new Float32Array(HF * K), hitsU = new Uint32Array(HU * K);
54 for (let k = 0; k < K; k++) {
55 const hf = HF * k, hu = HU * k;
56 hitsF[hf] = sc.kPoint[k]; hitsF[hf + 1] = sc.alpha[k]; hitsF[hf + 2] = sc.mass[k]; hitsF[hf + 3] = sc.gap[k];
57 hitsF[hf + 4] = sc.velocity[k]; hitsF[hf + 5] = HOLD_HEIGHT; hitsF[hf + 6] = 0; hitsF[hf + 7] = 0; hitsF[hf + 8] = 0;
58 for (let p = 0; p < P; p++) {
59 for (let i = 0; i < 3; i++) { hitsF[hf + HIT_HEADER + 3 * p + i] = sc.weights[(k * P + p) * 3 + i]; hitsU[hu + HITU_HEADER + 3 * p + i] = sc.nodes[(k * P + p) * 3 + i]; }
60 hitsF[hf + HIT_HEADER + 3 * P + p] = sc.offsets[k * P + p];
61 }
62 hitsU[hu] = sc.releaseStep[k]; hitsU[hu + 1] = 0;
63 }
64 const radCoef = new Float32Array(6 * E);
65 for (let e = 0; e < E; e++) {
66 radCoef[6 * e] = rad.coefF[e]; radCoef[6 * e + 1] = rad.coefB[e]; radCoef[6 * e + 2] = rad.i0F[e];
67 radCoef[6 * e + 3] = rad.frF[e]; radCoef[6 * e + 4] = rad.i0B[e]; radCoef[6 * e + 5] = rad.frB[e];
68 }
69 const mk = (name: string, data: Float32Array | Uint32Array, usage = storageUsage()) => {
70 const buf = device.createBuffer({ label: name, size: Math.max(16, data.byteLength), usage });
71 device.queue.writeBuffer(buf, 0, data.buffer, data.byteOffset, data.byteLength);
72 this.buffers[name] = buf;
73 return buf;
74 };
75 mk("elemF", elemF); mk("elemU", elemU); mk("nodeF", nodeF); mk("adj", adj); mk("radCoef", radCoef);
76 mk("hitsF", hitsF); mk("hitsU", hitsU);
77 mk("state", new Float32Array(12 * N)); mk("elemForce", new Float32Array(15 * E));
78 mk("sync", new Float32Array(SYNC_HEADER + 2 * G * 12)); mk("rad", new Float32Array(E * W + E * D));
79 mk("pressure", new Float32Array(2 * chunkCapacity));
80 const chunkBuf = device.createBuffer({ label: "chunk", size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
81 this.buffers.chunk = chunkBuf;
82 const staging = (size: number) => device.createBuffer({ size, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
83 this.stagingPressure = staging(8 * chunkCapacity); this.stagingState = staging(12 * N * 4);
84 this.stagingHits = staging(Math.max(16, HF * K * 4)); this.stagingHitsU = staging(Math.max(16, HU * K * 4));
86 // ---- pipelines
87 const module = device.createShaderModule({ code: shaderSource({ N, E, K, P, M, W, D, G, dt, sigma0: setup.config.material.sigma0, nl: sh.nl }) });
88 const bgl = (entries: [number, "read-only-storage" | "storage" | "uniform"][]) => device.createBindGroupLayout({
89 entries: entries.map(([binding, type]) => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type } })),
90 });
91 const L0 = bgl([[0, "read-only-storage"], [1, "read-only-storage"], [2, "read-only-storage"], [3, "storage"], [4, "storage"], [5, "read-only-storage"], [6, "storage"], [7, "storage"]]);
92 const L1 = bgl([[0, "storage"], [1, "read-only-storage"], [2, "read-only-storage"], [3, "read-only-storage"], [4, "storage"], [5, "storage"], [6, "storage"]]);
93 const L2 = bgl([[0, "read-only-storage"], [1, "read-only-storage"], [2, "read-only-storage"], [3, "storage"], [4, "uniform"]]);
94 const empty = device.createBindGroupLayout({ entries: [] });
95 const mkPipe = (entryPoint: string, layouts: GPUBindGroupLayout[]) => device.createComputePipeline({
96 label: entryPoint, layout: device.createPipelineLayout({ bindGroupLayouts: layouts }), compute: { module, entryPoint },
97 });
98 this.pipelines.element = mkPipe("elementPass", [L0]);
99 this.pipelines.node = mkPipe("nodePass", [empty, L1]);
100 this.pipelines.gather = mkPipe("gatherPass", [empty, empty, L2]);
101 const B = this.buffers;
102 const bg = (layout: GPUBindGroupLayout, bufs: GPUBuffer[]) => device.createBindGroup({ layout, entries: bufs.map((buffer, binding) => ({ binding, resource: { buffer } })) });
103 this.bindGroups.element = bg(L0, [B.elemF, B.elemU, B.state, B.elemForce, B.hitsF, B.hitsU, B.sync, B.rad]);
104 this.bindGroups.node = bg(L1, [B.state, B.elemForce, B.nodeF, B.adj, B.hitsF, B.hitsU, B.sync]);
105 this.bindGroups.gather = bg(L2, [B.sync, B.rad, B.radCoef, B.pressure, B.chunk]);
106 this.bindGroups.empty = device.createBindGroup({ layout: empty, entries: [] });
107 }
109 /** Audio sample completed by the gather pass at sub-step n, or -1 when none is due. */
110 private sampleDueAt(n: number): number {
111 const M = this.setup.substeps, W = DECIMATION_SPAN;
112 if (n < 1 || (n - 1) % M !== 0) return -1;
113 const j0 = (n - 1) / M;
114 if (j0 === 0) return -1;
115 const j = j0 - W / 2;
116 return j >= 0 ? j : -1;
117 }
119 async runChunk(nSamples: number): Promise<ChunkResult> {
120 if (nSamples > this.chunkCapacity) throw new Error("chunk larger than the pressure buffer");
121 const { device, setup } = this, M = setup.substeps, E = setup.mesh.e, K = setup.schedule.K;
122 const n0 = this.step, n1 = n0 + nSamples * M;
123 let base = -1, count = 0;
124 for (let n = n0; n < n1; n++) { const j = this.sampleDueAt(n); if (j >= 0) { if (base < 0) base = j; count++; } }
125 device.queue.writeBuffer(this.buffers.chunk, 0, new Int32Array([base < 0 ? 0 : base, Math.max(count, 1), 0, 0]));
126 const enc = device.createCommandEncoder();
127 enc.clearBuffer(this.buffers.pressure);
128 const pass = enc.beginComputePass();
129 const wgE = Math.ceil((E + K) / 64), wgN = this.G;
130 for (let n = n0; n < n1; n++) {
131 pass.setPipeline(this.pipelines.element); pass.setBindGroup(0, this.bindGroups.element); pass.dispatchWorkgroups(wgE);
132 if (this.sampleDueAt(n) >= 0) {
133 pass.setPipeline(this.pipelines.gather); pass.setBindGroup(0, this.bindGroups.empty); pass.setBindGroup(1, this.bindGroups.empty);
134 pass.setBindGroup(2, this.bindGroups.gather); pass.dispatchWorkgroups(1);
135 }
136 pass.setPipeline(this.pipelines.node); pass.setBindGroup(0, this.bindGroups.empty); pass.setBindGroup(1, this.bindGroups.node); pass.dispatchWorkgroups(wgN);
137 }
138 pass.end();
139 enc.copyBufferToBuffer(this.buffers.pressure, 0, this.stagingPressure, 0, 8 * this.chunkCapacity);
140 device.queue.submit([enc.finish()]);
141 this.step = n1; this.samplesDone += nSamples;
142 await this.stagingPressure.mapAsync(GPUMapMode.READ);
143 const all = new Float32Array(this.stagingPressure.getMappedRange().slice(0));
144 this.stagingPressure.unmap();
145 const size = Math.max(count, 1);
146 return { firstSample: base < 0 ? this.samplesDone : base, pressureFront: all.slice(0, count), pressureBack: all.slice(size, size + count) };
147 }
149 private async read(buffer: GPUBuffer, staging: GPUBuffer, bytes: number): Promise<ArrayBuffer> {
150 const enc = this.device.createCommandEncoder();
151 enc.copyBufferToBuffer(buffer, 0, staging, 0, bytes);
152 this.device.queue.submit([enc.finish()]);
153 await staging.mapAsync(GPUMapMode.READ);
154 const out = staging.getMappedRange().slice(0);
155 staging.unmap();
156 return out;
157 }
159 async diagnostics(): Promise<Diagnostics> {
160 const { setup } = this, sh = setup.shell, N = setup.mesh.n, sc = setup.schedule, HF = this.HF, HU = this.HU;
161 const st = new Float32Array(await this.read(this.buffers.state, this.stagingState, 12 * N * 4));
162 const hf = new Float32Array(await this.read(this.buffers.hitsF, this.stagingHits, Math.max(16, HF * sc.K * 4)));
163 const hu = new Uint32Array(await this.read(this.buffers.hitsU, this.stagingHitsU, Math.max(16, HU * sc.K * 4)));
164 let ke = 0, woh = 0;
165 for (let i = 0; i < 5 * N; i++) ke += 0.5 * sh.M[i] * st[5 * N + i] * st[5 * N + i];
166 for (let n = 0; n < N; n++) woh = Math.max(woh, Math.abs(st[5 * n + 2] / sh.hNode[n]));
167 const { membrane, bending } = strainEnergies(sh, st.subarray(0, 5 * N));
168 let ex = 0;
169 const hits = [];
170 for (let k = 0; k < sc.K; k++) {
171 ex += 0.5 * hf[HF * k + 2] * hf[HF * k + 6] ** 2;
172 hits.push({ peakForce: hf[HF * k + 8], contactTime: hu[HU * k + 1] * setup.dt, velocity: hf[HF * k + 6], height: hf[HF * k + 5] });
173 }
174 return { time: this.step * setup.dt, kinetic: ke, membrane, bending, exciters: ex, maxWoverH: woh, hits };
175 }
177 async displacement(): Promise<Float32Array> {
178 const N = this.setup.mesh.n;
179 const st = new Float32Array(await this.read(this.buffers.state, this.stagingState, 12 * N * 4));
180 const w = new Float32Array(N);
181 for (let n = 0; n < N; n++) w[n] = st[5 * n + 2];
182 return w;
183 }
185 /** The state buffer (q at offset 0, 5 floats per node), for a renderer that reads w directly. */
186 get stateBuffer(): GPUBuffer { return this.buffers.state; }
188 dispose() {
189 for (const b of Object.values(this.buffers)) b.destroy();
190 this.stagingPressure.destroy(); this.stagingState.destroy(); this.stagingHits.destroy(); this.stagingHitsU.destroy();
191 }
↑↓ move↵openescclose