/ proof-of-concept / cymsimweb
Sign in
proof-of-concept / cymsimweb
cymsimweb / src / gpu / simulator.ts
320 lines · 22.0 KBBlameHistoryRaw
1// WebGPU time loop: packs the set-up into storage buffers, compiles the four 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 { invertMatrix } from "../model/linalg.ts";
7import { DECIMATION_SPAN, DELAY_TAPS } from "../model/radiation.ts";
8import { rawRigidModes } from "../model/shell.ts";
9import type { Setup } from "../model/setup.ts";
10import type { BackendOptions, BackendState, ChunkResult, Diagnostics, SimulatorBackend } from "../model/simulator.ts";
11import { CHUNK_WORDS, ELEM_STRIDE, GATHER_ELEMS, HIT_HEADER, HITU_HEADER, NODE_STRIDE, RADCOEF_STRIDE, RAW_BASIS, STATE_FLOATS, SYNC_HEADER, WORKGROUP_NODES, shaderSource } from "./shaders.ts";
13// evaluated lazily: under Node the WebGPU globals are installed after this module is imported
14const storageUsage = () => GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC;
16/** Largest per-chunk output buffer (acceleration rows or movie frames) we allocate on the GPU. */
17const OUTPUT_BUDGET = 64e6;
19export class GpuSimulator implements SimulatorBackend {
20 readonly kind = "gpu" as const;
21 readonly setup: Setup; readonly device: GPUDevice;
22 samplesDone = 0;
23 private step = 0;
24 private readonly G: number; private readonly GE: number; private readonly HF: number; private readonly HU: number;
25 private readonly buffers: Record<string, GPUBuffer> = {};
26 private readonly pipelines: Record<string, GPUComputePipeline> = {};
27 private readonly bindGroups: Record<string, GPUBindGroup> = {};
28 private readonly chunkCapacity: number; readonly movieEvery: number; readonly dispEvery: number; readonly recordAcceleration: boolean;
29 private readonly framesCapacity: number; private readonly dispCapacity: number; private readonly accRows: number;
30 private readonly stagingPressure: GPUBuffer; private readonly stagingState: GPUBuffer; private readonly stagingHits: GPUBuffer; private readonly stagingHitsU: GPUBuffer;
31 private readonly stagingMovie: GPUBuffer | null; private readonly stagingDisp: GPUBuffer | null; private readonly stagingAcc: GPUBuffer | null;
32 private readonly rawFromOrtho: Float64Array; // p = L c: raw-mode partial sums from orthonormal-mode ones (6 x 6)
33 private readonly radStateFloats: number; // accumulator slots, node history and the current sample's sub-step accelerations: the part of `rad` that is state
35 constructor(device: GPUDevice, setup: Setup, chunkCapacity = 8192, opts: BackendOptions | number = {}) {
36 if (typeof opts === "number") opts = { movieEvery: opts };
37 this.device = device; this.setup = setup;
38 this.movieEvery = opts.movieEvery ?? 0; this.dispEvery = opts.dispEvery ?? 0; this.recordAcceleration = opts.recordAcceleration ?? false;
39 const Nn = setup.mesh.n;
40 // a chunk's outputs (movie frames, acceleration rows) stay under the budget
41 if (this.movieEvery > 0) chunkCapacity = Math.max(128, Math.min(chunkCapacity, Math.floor((OUTPUT_BUDGET / (4 * Nn)) * this.movieEvery)));
42 if (this.recordAcceleration) chunkCapacity = Math.max(128, Math.min(chunkCapacity, Math.floor(OUTPUT_BUDGET / (4 * Nn)) - 2));
43 this.chunkCapacity = chunkCapacity;
44 this.framesCapacity = this.movieEvery > 0 ? Math.ceil(chunkCapacity / this.movieEvery) + 2 : 0;
45 this.dispCapacity = this.dispEvery > 0 ? Math.ceil(chunkCapacity / this.dispEvery) + 2 : 0;
46 this.accRows = this.recordAcceleration ? chunkCapacity + 2 : 0;
47 const { mesh, shell: sh, schedule: sc, radiation: rad, substeps: M } = setup;
48 const N = mesh.n, E = mesh.e, K = sc.K, P = sc.P, W = DECIMATION_SPAN, D = rad.ringLength, T = DELAY_TAPS;
49 this.G = Math.ceil(N / WORKGROUP_NODES); this.GE = Math.ceil(E / GATHER_ELEMS);
50 this.HF = HIT_HEADER + 5 * P; this.HU = HITU_HEADER + 3 * P;
51 const G = this.G, HF = this.HF, HU = this.HU;
52 this.radStateFloats = (W + D + M) * N;
54 // ---- pack the set-up
55 // field-major: field f of element e at f * E + e, of node n at f * N + n
56 const elemF = new Float32Array(ELEM_STRIDE * E);
57 for (let e = 0; e < E; e++) {
58 const set = (f: number, x: number) => { elemF[f * E + e] = x; };
59 for (let i = 0; i < 3; i++) { set(i, mesh.Gx[3 * e + i]); set(3 + i, mesh.Gy[3 * e + i]); }
60 set(6, mesh.area[e]); set(7, sh.z0x[e]); set(8, sh.z0y[e]);
61 set(9, sh.Cm[3 * e]); set(10, sh.Cm[3 * e + 1]); set(11, sh.Cm[3 * e + 2]);
62 set(12, 2 * setup.config.material.sigma1 * sh.rhoHA[e]);
63 // upper triangle of K_e, symmetrised in float64 (it is symmetric to round-off)
64 const K = sh.Ke.subarray(81 * e, 81 * e + 81);
65 for (let i = 0, f = 13; i < 9; i++) for (let j = i; j < 9; j++) set(f++, 0.5 * (K[9 * i + j] + K[9 * j + i]));
66 }
67 const elemU = new Uint32Array(3 * E); elemU.set(mesh.tri);
68 const nodeF = new Float32Array(NODE_STRIDE * N + W * M);
69 // the shader evaluates the raw rigid modes from (X, Y, z0) and projects with the inverse of their
70 // M-Gram matrix, which is the projection onto the M-orthonormal modes Rm without storing them
71 const [cx, cy] = sh.rigidCentre;
72 const gram = new Float64Array(36), rawFromOrtho = new Float64Array(36);
73 for (let n = 0; n < N; n++) {
74 const set = (f: number, x: number) => { nodeF[f * N + n] = x; };
75 const X = mesh.xy[2 * n] - cx, Y = mesh.xy[2 * n + 1] - cy, z = sh.z0Node[n];
76 for (let d = 0; d < 5; d++) { set(d, sh.Minv[5 * n + d]); set(5 + d, sh.M[5 * n + d]); }
77 set(10, X); set(11, Y); set(12, z);
78 for (let d = 0; d < 3; d++) set(13 + d, sh.normalNode[3 * n + d]);
79 const r = rawRigidModes(X, Y, z);
80 for (let a = 0; a < 6; a++) for (let d = 0; d < 5; d++) {
81 const rm = r[a][d] * sh.M[5 * n + d];
82 if (rm === 0) continue;
83 for (let b = 0; b < 6; b++) { gram[6 * a + b] += rm * r[b][d]; rawFromOrtho[6 * a + b] += rm * sh.Rm[(b * N + n) * 5 + d]; }
84 }
85 }
86 this.rawFromOrtho = rawFromOrtho;
87 nodeF.set(rad.taps, NODE_STRIDE * N);
88 const adj = new Uint32Array(N + 1 + sh.adjEntries.length); adj.set(sh.adjOffsets); adj.set(sh.adjEntries, N + 1);
89 const hitsF = new Float32Array(HF * K), hitsU = new Uint32Array(HU * K);
90 for (let k = 0; k < K; k++) {
91 const hf = HF * k, hu = HU * k;
92 hitsF[hf] = sc.kPoint[k]; hitsF[hf + 1] = sc.alpha[k]; hitsF[hf + 2] = sc.mass[k]; hitsF[hf + 3] = sc.gap[k];
93 hitsF[hf + 4] = sc.velocity[k]; hitsF[hf + 5] = HOLD_HEIGHT; hitsF[hf + 6] = 0; hitsF[hf + 7] = 0; hitsF[hf + 8] = 0;
94 for (let p = 0; p < P; p++) {
95 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]; }
96 hitsF[hf + HIT_HEADER + 3 * P + p] = sc.offsets[k * P + p];
97 }
98 hitsU[hu] = sc.releaseStep[k]; hitsU[hu + 1] = 0;
99 }
100 const radCoef = new Float32Array(RADCOEF_STRIDE * E);
101 for (let e = 0; e < E; e++) {
102 const b = RADCOEF_STRIDE * e;
103 radCoef[b] = rad.coefF[e]; radCoef[b + 1] = rad.coefB[e]; radCoef[b + 2] = rad.i0F[e]; radCoef[b + 3] = rad.i0B[e];
104 for (let t = 0; t < T; t++) { radCoef[b + 4 + t] = rad.tapsF[e * T + t]; radCoef[b + 4 + T + t] = rad.tapsB[e * T + t]; }
105 }
106 const mk = (name: string, data: Float32Array | Uint32Array, usage = storageUsage()) => {
107 const buf = device.createBuffer({ label: name, size: Math.max(16, data.byteLength), usage });
108 device.queue.writeBuffer(buf, 0, data.buffer, data.byteOffset, data.byteLength);
109 this.buffers[name] = buf;
110 return buf;
111 };
112 const mkEmpty = (name: string, floats: number) => {
113 const buf = device.createBuffer({ label: name, size: Math.max(16, 4 * floats), usage: storageUsage() });
114 this.buffers[name] = buf;
115 return buf;
116 };
117 mk("elemF", elemF); mk("elemU", elemU); mk("nodeF", nodeF); mk("adj", adj); mk("radCoef", radCoef);
118 mk("hitsF", hitsF); mk("hitsU", hitsU);
119 mkEmpty("state", STATE_FLOATS * N); mkEmpty("elemForce", 15 * E);
120 mk("sync", Float32Array.from({ length: SYNC_HEADER + 2 * G * 12 }, (_, i) => (i === 2 ? RAW_BASIS : 0))); mkEmpty("rad", this.radStateFloats + this.accRows * N); mkEmpty("elemHist", D * E);
121 mkEmpty("pressure", 2 * chunkCapacity * this.GE); // one partial sum per gather workgroup
122 const uniform = (name: string) => { const b = device.createBuffer({ label: name, size: 4 * CHUNK_WORDS, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); this.buffers[name] = b; return b; };
123 uniform("chunk"); uniform("chunkD");
124 const staging = (size: number) => device.createBuffer({ size: Math.max(16, size), usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
125 this.stagingPressure = staging(8 * chunkCapacity * this.GE); this.stagingState = staging(STATE_FLOATS * N * 4);
126 this.stagingHits = staging(HF * K * 4); this.stagingHitsU = staging(HU * K * 4);
127 this.stagingMovie = this.framesCapacity > 0 ? (mkEmpty("movie", this.framesCapacity * N), staging(this.framesCapacity * N * 4)) : null;
128 this.stagingDisp = this.dispCapacity > 0 ? (mkEmpty("disp", this.dispCapacity * N), staging(this.dispCapacity * N * 4)) : null;
129 this.stagingAcc = this.accRows > 0 ? staging(this.accRows * N * 4) : null;
131 // ---- pipelines
132 const module = device.createShaderModule({ code: shaderSource({ N, E, K, P, M, W, D, G, T, rigidGramInv: invertMatrix(gram, 6), accRows: this.accRows, dt: setup.dt, sigma0: setup.config.material.sigma0, nl: sh.nl }) });
133 type Kind = "read-only-storage" | "storage" | "uniform";
134 const bgl = (entries: [number, Kind][]) => device.createBindGroupLayout({
135 entries: entries.map(([binding, type]) => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type } })),
136 });
137 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"]]);
138 const L1 = bgl([[0, "storage"], [1, "read-only-storage"], [2, "read-only-storage"], [3, "read-only-storage"], [4, "storage"], [5, "storage"], [6, "storage"], [7, "storage"], [8, "uniform"]]);
139 const L2 = bgl([[0, "read-only-storage"], [1, "read-only-storage"], [2, "read-only-storage"], [3, "storage"], [4, "uniform"], [5, "storage"], [6, "read-only-storage"]]);
140 const L3 = bgl([[0, "read-only-storage"], [1, "storage"], [2, "uniform"], [3, "read-only-storage"]]);
141 const empty = device.createBindGroupLayout({ entries: [] });
142 const mkPipe = (entryPoint: string, layouts: GPUBindGroupLayout[]) => device.createComputePipeline({
143 label: entryPoint, layout: device.createPipelineLayout({ bindGroupLayouts: layouts }), compute: { module, entryPoint },
144 });
145 this.pipelines.element = mkPipe("elementPass", [L0]);
146 this.pipelines.node = mkPipe("nodePass", [empty, L1]);
147 this.pipelines.gather = mkPipe("gatherPass", [empty, empty, L2]);
148 if (this.framesCapacity > 0 || this.dispCapacity > 0) this.pipelines.capture = mkPipe("capturePass", [empty, empty, empty, L3]);
149 const B = this.buffers;
150 const bg = (layout: GPUBindGroupLayout, bufs: GPUBuffer[]) => device.createBindGroup({ layout, entries: bufs.map((buffer, binding) => ({ binding, resource: { buffer } })) });
151 this.bindGroups.element = bg(L0, [B.elemF, B.elemU, B.state, B.elemForce, B.hitsF, B.hitsU, B.sync]);
152 this.bindGroups.node = bg(L1, [B.state, B.elemForce, B.nodeF, B.adj, B.hitsF, B.hitsU, B.sync, B.rad, B.chunk]);
153 this.bindGroups.gather = bg(L2, [B.sync, B.rad, B.radCoef, B.pressure, B.chunk, B.elemHist, B.elemU]);
154 if (this.framesCapacity > 0) this.bindGroups.capture = bg(L3, [B.state, B.movie, B.chunk, B.sync]);
155 if (this.dispCapacity > 0) this.bindGroups.captureDisp = bg(L3, [B.state, B.disp, B.chunkD, B.sync]);
156 this.bindGroups.empty = device.createBindGroup({ layout: empty, entries: [] });
157 }
159 /** Audio sample finished by the node pass of sub-step n (the acceleration of s = n - 1), or -1 when none. */
160 private sampleDueAt(n: number): number {
161 const M = this.setup.substeps, W = DECIMATION_SPAN;
162 if (n < 1 || (n - 1) % M !== 0) return -1;
163 const j = (n - 1) / M - W / 2;
164 return j >= 0 ? j : -1;
165 }
167 get maxChunk() { return this.chunkCapacity; }
169 private capture(pass: GPUComputePassEncoder, group: GPUBindGroup) {
170 pass.setPipeline(this.pipelines.capture); pass.setBindGroup(0, this.bindGroups.empty); pass.setBindGroup(1, this.bindGroups.empty);
171 pass.setBindGroup(2, this.bindGroups.empty); pass.setBindGroup(3, group); pass.dispatchWorkgroups(this.G);
172 }
174 private async readStaging(staging: GPUBuffer, bytes: number): Promise<Float32Array> {
175 await staging.mapAsync(GPUMapMode.READ, 0, bytes);
176 const data = new Float32Array(staging.getMappedRange(0, bytes).slice(0));
177 staging.unmap();
178 return data;
179 }
181 async runChunk(nSamples: number): Promise<ChunkResult> {
182 if (nSamples > this.chunkCapacity) throw new Error("chunk larger than the pressure buffer");
183 const { device, setup } = this, M = setup.substeps, E = setup.mesh.e, K = setup.schedule.K, N = setup.mesh.n;
184 const n0 = this.step, n1 = n0 + nSamples * M;
185 let base = -1, count = 0;
186 for (let n = n0; n < n1; n++) { const j = this.sampleDueAt(n); if (j >= 0) { if (base < 0) base = j; count++; } }
187 // frames captured in this chunk: the state at the start of sub-step n where n / M is a multiple of `every`
188 const framesAt = (every: number) => { const out: number[] = []; if (every > 0) for (let n = n0; n < n1; n++) if (n % (M * every) === 0) out.push(n / M); return out; };
189 const frameSamples = framesAt(this.movieEvery), dispSamples = framesAt(this.dispEvery);
190 const frameBase = frameSamples.length ? frameSamples[0] / this.movieEvery : 0, dispBase = dispSamples.length ? dispSamples[0] / this.dispEvery : 0;
191 const accBase = base < 0 ? 0 : base, accRows = this.recordAcceleration ? Math.max(count, 0) : 0;
192 device.queue.writeBuffer(this.buffers.chunk, 0, new Int32Array([accBase, Math.max(count, 1), frameBase, Math.max(this.movieEvery, 1), accBase, accRows, 0, 0]));
193 device.queue.writeBuffer(this.buffers.chunkD, 0, new Int32Array([accBase, Math.max(count, 1), dispBase, Math.max(this.dispEvery, 1), accBase, accRows, 0, 0]));
194 const enc = device.createCommandEncoder();
195 enc.clearBuffer(this.buffers.pressure);
196 const pass = enc.beginComputePass();
197 const wgE = Math.ceil((E + K) / 64), wgN = this.G;
198 for (let n = n0; n < n1; n++) {
199 if (this.movieEvery > 0 && n % (M * this.movieEvery) === 0) this.capture(pass, this.bindGroups.capture);
200 if (this.dispEvery > 0 && n % (M * this.dispEvery) === 0) this.capture(pass, this.bindGroups.captureDisp);
201 pass.setPipeline(this.pipelines.element); pass.setBindGroup(0, this.bindGroups.element); pass.dispatchWorkgroups(wgE);
202 pass.setPipeline(this.pipelines.node); pass.setBindGroup(0, this.bindGroups.empty); pass.setBindGroup(1, this.bindGroups.node); pass.dispatchWorkgroups(wgN);
203 if (this.sampleDueAt(n) >= 0) {
204 pass.setPipeline(this.pipelines.gather); pass.setBindGroup(0, this.bindGroups.empty); pass.setBindGroup(1, this.bindGroups.empty);
205 pass.setBindGroup(2, this.bindGroups.gather); pass.dispatchWorkgroups(this.GE);
206 }
207 }
208 pass.end();
209 const GE = this.GE;
210 enc.copyBufferToBuffer(this.buffers.pressure, 0, this.stagingPressure, 0, 8 * this.chunkCapacity * GE);
211 const nFrames = frameSamples.length, nDisp = dispSamples.length;
212 if (nFrames > 0) enc.copyBufferToBuffer(this.buffers.movie, 0, this.stagingMovie!, 0, nFrames * N * 4);
213 if (nDisp > 0) enc.copyBufferToBuffer(this.buffers.disp, 0, this.stagingDisp!, 0, nDisp * N * 4);
214 if (accRows > 0) enc.copyBufferToBuffer(this.buffers.rad, this.radStateFloats * 4, this.stagingAcc!, 0, accRows * N * 4);
215 device.queue.submit([enc.finish()]);
216 this.step = n1; this.samplesDone += nSamples;
217 const partial = await this.readStaging(this.stagingPressure, 8 * this.chunkCapacity * GE);
218 const all = new Float32Array(2 * this.chunkCapacity);
219 for (let i = 0; i < 2 * Math.max(count, 1); i++) { let s = 0; for (let g = 0; g < GE; g++) s += partial[i * GE + g]; all[i] = s; }
220 const split = (data: Float32Array, k: number) => Array.from({ length: k }, (_, f) => data.slice(f * N, (f + 1) * N));
221 const frames = nFrames > 0 ? split(await this.readStaging(this.stagingMovie!, nFrames * N * 4), nFrames) : [];
222 const dispFrames = nDisp > 0 ? split(await this.readStaging(this.stagingDisp!, nDisp * N * 4), nDisp) : [];
223 const acceleration = this.recordAcceleration ? (accRows > 0 ? await this.readStaging(this.stagingAcc!, accRows * N * 4) : new Float32Array(0)) : null;
224 const size = Math.max(count, 1);
225 return { firstSample: base < 0 ? this.samplesDone : base, pressureFront: all.slice(0, count), pressureBack: all.slice(size, size + count),
226 frames, frameSamples, acceleration, dispFrames, dispSamples };
227 }
229 private async read(buffer: GPUBuffer, staging: GPUBuffer, bytes: number): Promise<ArrayBuffer> {
230 const enc = this.device.createCommandEncoder();
231 enc.copyBufferToBuffer(buffer, 0, staging, 0, bytes);
232 this.device.queue.submit([enc.finish()]);
233 await staging.mapAsync(GPUMapMode.READ, 0, bytes);
234 const out = staging.getMappedRange(0, bytes).slice(0);
235 staging.unmap();
236 return out;
237 }
239 /** Read a whole buffer through a temporary staging buffer. */
240 private async readWhole(buffer: GPUBuffer, bytes: number): Promise<ArrayBuffer> {
241 const staging = this.device.createBuffer({ size: Math.max(16, bytes), usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
242 try { return await this.read(buffer, staging, bytes); } finally { staging.destroy(); }
243 }
245 async diagnostics(): Promise<Diagnostics> {
246 const { setup } = this, sh = setup.shell, N = setup.mesh.n, sc = setup.schedule, HF = this.HF, HU = this.HU;
247 const st = new Float32Array(await this.read(this.buffers.state, this.stagingState, STATE_FLOATS * N * 4));
248 const hf = new Float32Array(await this.read(this.buffers.hitsF, this.stagingHits, Math.max(16, HF * sc.K * 4)));
249 const hu = new Uint32Array(await this.read(this.buffers.hitsU, this.stagingHitsU, Math.max(16, HU * sc.K * 4)));
250 let ke = 0, woh = 0;
251 for (let i = 0; i < 5 * N; i++) ke += 0.5 * sh.M[i] * st[5 * N + i] * st[5 * N + i];
252 for (let n = 0; n < N; n++) woh = Math.max(woh, Math.abs(st[5 * n + 2] / sh.hNode[n]));
253 const { membrane, bending } = strainEnergies(sh, st.subarray(0, 5 * N));
254 let ex = 0;
255 const hits = [];
256 for (let k = 0; k < sc.K; k++) {
257 ex += 0.5 * hf[HF * k + 2] * hf[HF * k + 6] ** 2;
258 hits.push({ peakForce: hf[HF * k + 8], contactTime: hu[HU * k + 1] * setup.dt, velocity: hf[HF * k + 6], height: hf[HF * k + 5] });
259 }
260 return { time: this.step * setup.dt, kinetic: ke, membrane, bending, exciters: ex, maxWoverH: woh, hits };
261 }
263 async displacement(): Promise<Float32Array> {
264 const N = this.setup.mesh.n;
265 const st = new Float32Array(await this.read(this.buffers.state, this.stagingState, STATE_FLOATS * N * 4));
266 const w = new Float32Array(N);
267 for (let n = 0; n < N; n++) w[n] = st[5 * n + 2];
268 return w;
269 }
271 async exportState(): Promise<BackendState> {
272 const { setup } = this, N = setup.mesh.n, E = setup.mesh.e, K = setup.schedule.K, D = setup.radiation.ringLength;
273 const B = this.buffers;
274 return { kind: "gpu", step: this.step, samplesDone: this.samplesDone, arrays: {
275 state: new Float32Array(await this.readWhole(B.state, STATE_FLOATS * N * 4)),
276 sync: new Float32Array(await this.readWhole(B.sync, (SYNC_HEADER + 2 * this.G * 12) * 4)),
277 hitsF: new Float32Array(await this.readWhole(B.hitsF, Math.max(16, this.HF * K * 4))).subarray(0, this.HF * K),
278 hitsU: new Uint32Array(await this.readWhole(B.hitsU, Math.max(16, this.HU * K * 4))).subarray(0, this.HU * K),
279 rad: new Float32Array(await this.readWhole(B.rad, this.radStateFloats * 4)),
280 elemHist: new Float32Array(await this.readWhole(B.elemHist, D * E * 4)),
281 } };
282 }
284 async importState(st: BackendState): Promise<void> {
285 if (st.kind !== "gpu") throw new Error("state was written by another backend");
286 const { setup } = this, N = setup.mesh.n, E = setup.mesh.e, K = setup.schedule.K, D = setup.radiation.ringLength;
287 const expect: Record<string, number> = { state: STATE_FLOATS * N, sync: SYNC_HEADER + 2 * this.G * 12, hitsF: this.HF * K, hitsU: this.HU * K, rad: this.radStateFloats, elemHist: D * E };
288 // states written before the sub-step accelerations were kept per sample lack them; their accumulator
289 // slots already hold the sample's earlier sub-steps, so zero accelerations continue them exactly
290 const legacyRad = this.radStateFloats - setup.substeps * N;
291 for (const [name, len] of Object.entries(expect)) {
292 let a = st.arrays[name];
293 if (name === "rad" && a?.length === legacyRad) { const full = new Float32Array(len); full.set(a); a = full; }
294 if (name === "sync" && a?.length === len && a[2] !== RAW_BASIS) a = this.syncToRawBasis(a as Float32Array);
295 if (!a || a.length !== len) throw new Error(`state array ${name} is missing or has the wrong size`);
296 this.device.queue.writeBuffer(this.buffers[name], 0, a.buffer, a.byteOffset, a.byteLength);
297 }
298 this.step = st.step; this.samplesDone = st.samplesDone;
299 }
301 /** A sync array of a state exported before step 3, whose partials are sums for the orthonormal modes, in the raw basis. */
302 private syncToRawBasis(old: Float32Array): Float32Array {
303 const out = Float32Array.from(old), L = this.rawFromOrtho;
304 out[2] = RAW_BASIS;
305 for (let b = 0; b < 2 * this.G; b++) for (const o of [0, 6]) {
306 const base = SYNC_HEADER + 12 * b + o;
307 for (let a = 0; a < 6; a++) { let s = 0; for (let k = 0; k < 6; k++) s += L[6 * a + k] * old[base + k]; out[base + a] = s; }
308 }
309 return out;
310 }
312 /** The state buffer (q at offset 0, 5 floats per node), for a renderer that reads w directly. */
313 get stateBuffer(): GPUBuffer { return this.buffers.state; }
315 dispose() {
316 for (const b of Object.values(this.buffers)) b.destroy();
317 this.stagingPressure.destroy(); this.stagingState.destroy(); this.stagingHits.destroy(); this.stagingHitsU.destroy();
318 this.stagingMovie?.destroy(); this.stagingDisp?.destroy(); this.stagingAcc?.destroy();
319 }
↑↓ move↵openescclose