/ proof-of-concept / cymsimweb
Sign in
proof-of-concept / cymsimweb
cymsimweb / src / gpu / simulator.ts
225 lines · 14.1 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; readonly movieEvery: number; private readonly framesCapacity: number;
24 private readonly stagingPressure: GPUBuffer; private readonly stagingState: GPUBuffer; private readonly stagingHits: GPUBuffer; private readonly stagingHitsU: GPUBuffer;
25 private readonly stagingMovie: GPUBuffer | null;
27 /** ``movieEvery`` > 0 captures w every that many audio samples; the chunk size is reduced so a chunk's frames stay under 64 MB. */
28 constructor(device: GPUDevice, setup: Setup, chunkCapacity = 8192, movieEvery = 0) {
29 this.device = device; this.setup = setup; this.movieEvery = movieEvery;
30 const Nn = setup.mesh.n;
31 if (movieEvery > 0) chunkCapacity = Math.max(128, Math.min(chunkCapacity, Math.floor((64e6 / (4 * Nn)) * movieEvery)));
32 this.chunkCapacity = chunkCapacity;
33 this.framesCapacity = movieEvery > 0 ? Math.ceil(chunkCapacity / movieEvery) + 2 : 0;
34 const { mesh, shell: sh, schedule: sc, radiation: rad, substeps: M, dt } = setup;
35 const N = mesh.n, E = mesh.e, K = sc.K, P = sc.P, W = DECIMATION_SPAN, D = rad.ringLength;
36 this.G = Math.ceil(N / WORKGROUP_NODES);
37 this.HF = HIT_HEADER + 5 * P; this.HU = HITU_HEADER + 3 * P;
38 const G = this.G, HF = this.HF, HU = this.HU;
40 // ---- pack the set-up
41 const elemF = new Float32Array(ELEM_STRIDE * E + W * M);
42 for (let e = 0; e < E; e++) {
43 const b = ELEM_STRIDE * e;
44 for (let i = 0; i < 3; i++) { elemF[b + i] = mesh.Gx[3 * e + i]; elemF[b + 3 + i] = mesh.Gy[3 * e + i]; }
45 elemF[b + 6] = mesh.area[e]; elemF[b + 7] = sh.z0x[e]; elemF[b + 8] = sh.z0y[e];
46 elemF[b + 9] = sh.Cm[3 * e]; elemF[b + 10] = sh.Cm[3 * e + 1]; elemF[b + 11] = sh.Cm[3 * e + 2];
47 elemF[b + 12] = 2 * setup.config.material.sigma1 * sh.rhoHA[e];
48 for (let i = 0; i < 81; i++) elemF[b + 13 + i] = sh.Ke[81 * e + i];
49 }
50 elemF.set(rad.taps, ELEM_STRIDE * E);
51 const elemU = new Uint32Array(3 * E); elemU.set(mesh.tri);
52 const nodeF = new Float32Array(NODE_STRIDE * N);
53 for (let n = 0; n < N; n++) {
54 const b = NODE_STRIDE * n;
55 for (let d = 0; d < 5; d++) { nodeF[b + d] = sh.Minv[5 * n + d]; nodeF[b + 5 + d] = sh.M[5 * n + d]; }
56 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];
57 }
58 const adj = new Uint32Array(N + 1 + sh.adjEntries.length); adj.set(sh.adjOffsets); adj.set(sh.adjEntries, N + 1);
59 const hitsF = new Float32Array(HF * K), hitsU = new Uint32Array(HU * K);
60 for (let k = 0; k < K; k++) {
61 const hf = HF * k, hu = HU * k;
62 hitsF[hf] = sc.kPoint[k]; hitsF[hf + 1] = sc.alpha[k]; hitsF[hf + 2] = sc.mass[k]; hitsF[hf + 3] = sc.gap[k];
63 hitsF[hf + 4] = sc.velocity[k]; hitsF[hf + 5] = HOLD_HEIGHT; hitsF[hf + 6] = 0; hitsF[hf + 7] = 0; hitsF[hf + 8] = 0;
64 for (let p = 0; p < P; p++) {
65 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]; }
66 hitsF[hf + HIT_HEADER + 3 * P + p] = sc.offsets[k * P + p];
67 }
68 hitsU[hu] = sc.releaseStep[k]; hitsU[hu + 1] = 0;
69 }
70 const radCoef = new Float32Array(6 * E);
71 for (let e = 0; e < E; e++) {
72 radCoef[6 * e] = rad.coefF[e]; radCoef[6 * e + 1] = rad.coefB[e]; radCoef[6 * e + 2] = rad.i0F[e];
73 radCoef[6 * e + 3] = rad.frF[e]; radCoef[6 * e + 4] = rad.i0B[e]; radCoef[6 * e + 5] = rad.frB[e];
74 }
75 const mk = (name: string, data: Float32Array | Uint32Array, usage = storageUsage()) => {
76 const buf = device.createBuffer({ label: name, size: Math.max(16, data.byteLength), usage });
77 device.queue.writeBuffer(buf, 0, data.buffer, data.byteOffset, data.byteLength);
78 this.buffers[name] = buf;
79 return buf;
80 };
81 mk("elemF", elemF); mk("elemU", elemU); mk("nodeF", nodeF); mk("adj", adj); mk("radCoef", radCoef);
82 mk("hitsF", hitsF); mk("hitsU", hitsU);
83 mk("state", new Float32Array(12 * N)); mk("elemForce", new Float32Array(15 * E));
84 mk("sync", new Float32Array(SYNC_HEADER + 2 * G * 12)); mk("rad", new Float32Array(E * W + E * D));
85 mk("pressure", new Float32Array(2 * chunkCapacity));
86 const chunkBuf = device.createBuffer({ label: "chunk", size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
87 this.buffers.chunk = chunkBuf;
88 const staging = (size: number) => device.createBuffer({ size, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
89 this.stagingPressure = staging(8 * chunkCapacity); this.stagingState = staging(12 * N * 4);
90 this.stagingHits = staging(Math.max(16, HF * K * 4)); this.stagingHitsU = staging(Math.max(16, HU * K * 4));
91 if (this.framesCapacity > 0) {
92 mk("movie", new Float32Array(this.framesCapacity * N));
93 this.stagingMovie = staging(this.framesCapacity * N * 4);
94 } else this.stagingMovie = null;
96 // ---- pipelines
97 const module = device.createShaderModule({ code: shaderSource({ N, E, K, P, M, W, D, G, dt, sigma0: setup.config.material.sigma0, nl: sh.nl }) });
98 const bgl = (entries: [number, "read-only-storage" | "storage" | "uniform"][]) => device.createBindGroupLayout({
99 entries: entries.map(([binding, type]) => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type } })),
100 });
101 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"]]);
102 const L1 = bgl([[0, "storage"], [1, "read-only-storage"], [2, "read-only-storage"], [3, "read-only-storage"], [4, "storage"], [5, "storage"], [6, "storage"]]);
103 const L2 = bgl([[0, "read-only-storage"], [1, "read-only-storage"], [2, "read-only-storage"], [3, "storage"], [4, "uniform"]]);
104 const L3 = bgl([[0, "read-only-storage"], [1, "storage"], [2, "uniform"], [3, "read-only-storage"]]);
105 const empty = device.createBindGroupLayout({ entries: [] });
106 const mkPipe = (entryPoint: string, layouts: GPUBindGroupLayout[]) => device.createComputePipeline({
107 label: entryPoint, layout: device.createPipelineLayout({ bindGroupLayouts: layouts }), compute: { module, entryPoint },
108 });
109 this.pipelines.element = mkPipe("elementPass", [L0]);
110 this.pipelines.node = mkPipe("nodePass", [empty, L1]);
111 this.pipelines.gather = mkPipe("gatherPass", [empty, empty, L2]);
112 if (this.framesCapacity > 0) this.pipelines.capture = mkPipe("capturePass", [empty, empty, empty, L3]);
113 const B = this.buffers;
114 const bg = (layout: GPUBindGroupLayout, bufs: GPUBuffer[]) => device.createBindGroup({ layout, entries: bufs.map((buffer, binding) => ({ binding, resource: { buffer } })) });
115 this.bindGroups.element = bg(L0, [B.elemF, B.elemU, B.state, B.elemForce, B.hitsF, B.hitsU, B.sync, B.rad]);
116 this.bindGroups.node = bg(L1, [B.state, B.elemForce, B.nodeF, B.adj, B.hitsF, B.hitsU, B.sync]);
117 this.bindGroups.gather = bg(L2, [B.sync, B.rad, B.radCoef, B.pressure, B.chunk]);
118 if (this.framesCapacity > 0) this.bindGroups.capture = bg(L3, [B.state, B.movie, B.chunk, B.sync]);
119 this.bindGroups.empty = device.createBindGroup({ layout: empty, entries: [] });
120 }
122 /** Audio sample completed by the gather pass at sub-step n, or -1 when none is due. */
123 private sampleDueAt(n: number): number {
124 const M = this.setup.substeps, W = DECIMATION_SPAN;
125 if (n < 1 || (n - 1) % M !== 0) return -1;
126 const j0 = (n - 1) / M;
127 if (j0 === 0) return -1;
128 const j = j0 - W / 2;
129 return j >= 0 ? j : -1;
130 }
132 get maxChunk() { return this.chunkCapacity; }
134 async runChunk(nSamples: number): Promise<ChunkResult> {
135 if (nSamples > this.chunkCapacity) throw new Error("chunk larger than the pressure buffer");
136 const { device, setup } = this, M = setup.substeps, E = setup.mesh.e, K = setup.schedule.K, N = setup.mesh.n;
137 const n0 = this.step, n1 = n0 + nSamples * M;
138 let base = -1, count = 0;
139 for (let n = n0; n < n1; n++) { const j = this.sampleDueAt(n); if (j >= 0) { if (base < 0) base = j; count++; } }
140 // frames captured in this chunk: the state at the start of sub-step n where n / M is a multiple of movieEvery
141 const frameSamples: number[] = [];
142 const every = this.movieEvery;
143 if (every > 0) for (let n = n0; n < n1; n++) if (n % (M * every) === 0) frameSamples.push(n / M);
144 const frameBase = frameSamples.length ? frameSamples[0] / every : 0;
145 device.queue.writeBuffer(this.buffers.chunk, 0, new Int32Array([base < 0 ? 0 : base, Math.max(count, 1), frameBase, Math.max(every, 1)]));
146 const enc = device.createCommandEncoder();
147 enc.clearBuffer(this.buffers.pressure);
148 const pass = enc.beginComputePass();
149 const wgE = Math.ceil((E + K) / 64), wgN = this.G;
150 for (let n = n0; n < n1; n++) {
151 if (every > 0 && n % (M * every) === 0) {
152 pass.setPipeline(this.pipelines.capture); pass.setBindGroup(0, this.bindGroups.empty); pass.setBindGroup(1, this.bindGroups.empty);
153 pass.setBindGroup(2, this.bindGroups.empty); pass.setBindGroup(3, this.bindGroups.capture); pass.dispatchWorkgroups(wgN);
154 }
155 pass.setPipeline(this.pipelines.element); pass.setBindGroup(0, this.bindGroups.element); pass.dispatchWorkgroups(wgE);
156 if (this.sampleDueAt(n) >= 0) {
157 pass.setPipeline(this.pipelines.gather); pass.setBindGroup(0, this.bindGroups.empty); pass.setBindGroup(1, this.bindGroups.empty);
158 pass.setBindGroup(2, this.bindGroups.gather); pass.dispatchWorkgroups(1);
159 }
160 pass.setPipeline(this.pipelines.node); pass.setBindGroup(0, this.bindGroups.empty); pass.setBindGroup(1, this.bindGroups.node); pass.dispatchWorkgroups(wgN);
161 }
162 pass.end();
163 enc.copyBufferToBuffer(this.buffers.pressure, 0, this.stagingPressure, 0, 8 * this.chunkCapacity);
164 const nFrames = frameSamples.length;
165 if (nFrames > 0) enc.copyBufferToBuffer(this.buffers.movie, 0, this.stagingMovie!, 0, nFrames * N * 4);
166 device.queue.submit([enc.finish()]);
167 this.step = n1; this.samplesDone += nSamples;
168 await this.stagingPressure.mapAsync(GPUMapMode.READ);
169 const all = new Float32Array(this.stagingPressure.getMappedRange().slice(0));
170 this.stagingPressure.unmap();
171 const frames: Float32Array[] = [];
172 if (nFrames > 0) {
173 await this.stagingMovie!.mapAsync(GPUMapMode.READ, 0, nFrames * N * 4);
174 const data = new Float32Array(this.stagingMovie!.getMappedRange(0, nFrames * N * 4).slice(0));
175 this.stagingMovie!.unmap();
176 for (let f = 0; f < nFrames; f++) frames.push(data.slice(f * N, (f + 1) * N));
177 }
178 const size = Math.max(count, 1);
179 return { firstSample: base < 0 ? this.samplesDone : base, pressureFront: all.slice(0, count), pressureBack: all.slice(size, size + count), frames, frameSamples };
180 }
182 private async read(buffer: GPUBuffer, staging: GPUBuffer, bytes: number): Promise<ArrayBuffer> {
183 const enc = this.device.createCommandEncoder();
184 enc.copyBufferToBuffer(buffer, 0, staging, 0, bytes);
185 this.device.queue.submit([enc.finish()]);
186 await staging.mapAsync(GPUMapMode.READ);
187 const out = staging.getMappedRange().slice(0);
188 staging.unmap();
189 return out;
190 }
192 async diagnostics(): Promise<Diagnostics> {
193 const { setup } = this, sh = setup.shell, N = setup.mesh.n, sc = setup.schedule, HF = this.HF, HU = this.HU;
194 const st = new Float32Array(await this.read(this.buffers.state, this.stagingState, 12 * N * 4));
195 const hf = new Float32Array(await this.read(this.buffers.hitsF, this.stagingHits, Math.max(16, HF * sc.K * 4)));
196 const hu = new Uint32Array(await this.read(this.buffers.hitsU, this.stagingHitsU, Math.max(16, HU * sc.K * 4)));
197 let ke = 0, woh = 0;
198 for (let i = 0; i < 5 * N; i++) ke += 0.5 * sh.M[i] * st[5 * N + i] * st[5 * N + i];
199 for (let n = 0; n < N; n++) woh = Math.max(woh, Math.abs(st[5 * n + 2] / sh.hNode[n]));
200 const { membrane, bending } = strainEnergies(sh, st.subarray(0, 5 * N));
201 let ex = 0;
202 const hits = [];
203 for (let k = 0; k < sc.K; k++) {
204 ex += 0.5 * hf[HF * k + 2] * hf[HF * k + 6] ** 2;
205 hits.push({ peakForce: hf[HF * k + 8], contactTime: hu[HU * k + 1] * setup.dt, velocity: hf[HF * k + 6], height: hf[HF * k + 5] });
206 }
207 return { time: this.step * setup.dt, kinetic: ke, membrane, bending, exciters: ex, maxWoverH: woh, hits };
208 }
210 async displacement(): Promise<Float32Array> {
211 const N = this.setup.mesh.n;
212 const st = new Float32Array(await this.read(this.buffers.state, this.stagingState, 12 * N * 4));
213 const w = new Float32Array(N);
214 for (let n = 0; n < N; n++) w[n] = st[5 * n + 2];
215 return w;
216 }
218 /** The state buffer (q at offset 0, 5 floats per node), for a renderer that reads w directly. */
219 get stateBuffer(): GPUBuffer { return this.buffers.state; }
221 dispose() {
222 for (const b of Object.values(this.buffers)) b.destroy();
223 this.stagingPressure.destroy(); this.stagingState.destroy(); this.stagingHits.destroy(); this.stagingHitsU.destroy(); this.stagingMovie?.destroy();
224 }
↑↓ move↵openescclose