// Float64 reference time loop with exactly the structure of the GPU kernels: an element pass // (forces, sigma1 term), a hit pass (contact forces, release), a node pass (gather, contact, // lagged rigid-mode projection, leapfrog update, partial sums for the next projection, normal // acceleration and its decimation accumulators), the exciter update, and once per audio sample // the gather of the listener pressure from the element history. See THEORY.md. import { elementForces, strainEnergies } from "../model/forces.ts"; import { HOLD_HEIGHT } from "../model/exciter.ts"; import { DECIMATION_SPAN, DELAY_TAPS, delayedValue } from "../model/radiation.ts"; import type { Setup } from "../model/setup.ts"; import type { BackendOptions, BackendState, ChunkResult, Diagnostics, SimulatorBackend } from "../model/simulator.ts"; export class CpuSimulator implements SimulatorBackend { readonly kind = "cpu" as const; private n = 0; // sub-step counter private readonly q: Float64Array; private readonly v: Float64Array; private readonly vPrev: Float64Array; // projected (u, v, w) velocities of the previous step (for the radiated acceleration) private readonly ef: Float64Array; private readonly fc: Float64Array; private readonly zs: Float64Array; private readonly vs: Float64Array; private readonly Fk: Float64Array; private readonly F: Float64Array; private readonly Fmax: Float64Array; private readonly ncont: Uint32Array; private partialsPrev = new Float64Array(12); private partialsNew = new Float64Array(12); // [0,6): Rm.(M v), [6,12): Rm.(M q) private readonly accRing: Float64Array; // (DECIMATION_SPAN, N) partial audio samples of the normal acceleration private readonly elemHist: Float64Array; // (ringLength, E) finished element-mean samples private readonly emitted: Float64Array; // (N,) the node sample finished at the current step private pending: { j: number; front: number; back: number; acc: Float32Array | null }[] = []; samplesDone = 0; readonly maxChunk = 8192; readonly setup: Setup; readonly movieEvery: number; readonly dispEvery: number; readonly recordAcceleration: boolean; constructor(setup: Setup, opts: BackendOptions | number = {}) { if (typeof opts === "number") opts = { movieEvery: opts }; this.setup = setup; this.movieEvery = opts.movieEvery ?? 0; this.dispEvery = opts.dispEvery ?? 0; this.recordAcceleration = opts.recordAcceleration ?? false; const N = setup.mesh.n, E = setup.mesh.e, K = setup.schedule.K, P = setup.schedule.P; this.q = new Float64Array(5 * N); this.v = new Float64Array(5 * N); this.vPrev = new Float64Array(3 * N); this.ef = new Float64Array(15 * E); this.fc = new Float64Array(N); this.zs = new Float64Array(K).fill(HOLD_HEIGHT); this.vs = new Float64Array(K); this.Fk = new Float64Array(K * P); this.F = new Float64Array(K); this.Fmax = new Float64Array(K); this.ncont = new Uint32Array(K); this.accRing = new Float64Array(DECIMATION_SPAN * N); this.elemHist = new Float64Array(E * setup.radiation.ringLength); this.emitted = new Float64Array(N); } private step() { const { shell: sh, mesh, schedule: sc, radiation: rad, dt, substeps: m } = this.setup; const N = mesh.n, n = this.n; const sigma0 = this.setup.config.material.sigma0; // ---- element pass elementForces(sh, this.q, this.v, this.ef); // ---- hit pass this.fc.fill(0); for (let k = 0; k < sc.K; k++) { let wmax = -Infinity; const wp = new Float64Array(sc.P); for (let p = 0; p < sc.P; p++) { const b = (k * sc.P + p) * 3; let w = sc.offsets[k * sc.P + p]; for (let i = 0; i < 3; i++) w += sc.weights[b + i] * this.q[5 * sc.nodes[b + i] + 2]; wp[p] = w; wmax = Math.max(wmax, w); } if (n === sc.releaseStep[k]) { this.zs[k] = wmax + sc.gap[k]; this.vs[k] = -sc.velocity[k]; } const active = n >= sc.releaseStep[k]; let Ftot = 0; for (let p = 0; p < sc.P; p++) { const delta = Math.max(wp[p] - this.zs[k], 0); const f = active ? sc.kPoint[k] * Math.pow(delta, sc.alpha[k]) : 0; this.Fk[k * sc.P + p] = f; Ftot += f; if (f > 0) { const b = (k * sc.P + p) * 3; for (let i = 0; i < 3; i++) this.fc[sc.nodes[b + i]] -= f * sc.weights[b + i]; } } this.F[k] = Ftot; } // ---- node pass const { M, Minv, Rm, adjOffsets, adjEntries, normalNode } = sh, L = 5 * N, c = this.partialsPrev; this.partialsNew.fill(0); const f = new Float64Array(5); // decimation bookkeeping for the acceleration of the previous step, s = n - 1 const s = n - 1, W = DECIMATION_SPAN, taps = rad.taps; const j0 = s >= 0 ? Math.floor(s / m) : 0, kk = s >= 0 ? s - j0 * m : -1; const emit = s >= 0 && kk === 0, jE = j0 - W / 2, slotE = ((jE % W) + W) % W, r = (((j0 + 1 - W / 2) % W) + W) % W; for (let nd = 0; nd < N; nd++) { f.fill(0); for (let a = adjOffsets[nd]; a < adjOffsets[nd + 1]; a++) { const ent = adjEntries[a], e = (ent / 3) | 0, i = ent % 3; for (let d = 0; d < 5; d++) f[d] += this.ef[15 * e + 5 * i + d]; } f[2] += this.fc[nd]; let acc = 0; for (let d = 0; d < 5; d++) { const idx = 5 * nd + d; // lagged projection: remove the rigid content that the previous step's update introduced let vd = this.v[idx], qd = this.q[idx]; for (let k = 0; k < 6; k++) { const r = Rm[k * L + idx]; vd -= c[k] * r; qd -= c[6 + k] * r; } const v1 = (vd + dt * f[d] * Minv[idx]) / (1 + 2 * sigma0 * dt); // radiated acceleration from consecutive projected velocities, so that the rigid increment // that the lagged projection removes one step later never radiates; normal component if (d < 3) { acc += normalNode[3 * nd + d] * (vd - this.vPrev[3 * nd + d]) / dt; this.vPrev[3 * nd + d] = vd; } const q1 = qd + dt * v1; this.q[idx] = q1; this.v[idx] = v1; for (let k = 0; k < 6; k++) { const r = Rm[k * L + idx] * M[idx]; this.partialsNew[k] += r * v1; this.partialsNew[6 + k] += r * q1; } } if (s >= 0) { if (emit) { this.emitted[nd] = this.accRing[slotE * N + nd]; this.accRing[slotE * N + nd] = 0; } for (let w = 0; w < W; w++) this.accRing[((r + w) % W) * N + nd] += acc * taps[w * m + kk]; } } [this.partialsPrev, this.partialsNew] = [this.partialsNew, this.partialsPrev]; // ---- exciters for (let k = 0; k < sc.K; k++) { this.vs[k] += (dt * this.F[k]) / sc.mass[k]; this.zs[k] += dt * this.vs[k]; this.Fmax[k] = Math.max(this.Fmax[k], this.F[k]); if (this.F[k] > 0) this.ncont[k]++; } this.n++; if (emit && jE >= 0) this.finalizeSample(jE); } /** Audio sample j of the node accelerations is complete: element means into the history, then the listener pressure. */ private finalizeSample(j: number) { const { radiation: rad, mesh } = this.setup, E = mesh.e, D = rad.ringLength, { tri } = mesh; const row = (j % D) * E; for (let e = 0; e < E; e++) this.elemHist[row + e] = (this.emitted[tri[3 * e]] + this.emitted[tri[3 * e + 1]] + this.emitted[tri[3 * e + 2]]) / 3; let front = 0, back = 0; for (let e = 0; e < E; e++) { front += rad.coefF[e] * delayedValue(this.elemHist, E, e, D, j, rad.i0F[e], rad.tapsF, e * DELAY_TAPS); back += rad.coefB[e] * delayedValue(this.elemHist, E, e, D, j, rad.i0B[e], rad.tapsB, e * DELAY_TAPS); } this.pending.push({ j, front, back, acc: this.recordAcceleration ? Float32Array.from(this.emitted) : null }); } async runChunk(nSamples: number): Promise { const m = this.setup.substeps, N = this.setup.mesh.n, frames: Float32Array[] = [], frameSamples: number[] = []; const dispFrames: Float32Array[] = [], dispSamples: number[] = []; const capture = () => { const w = new Float32Array(N); for (let nd = 0; nd < N; nd++) w[nd] = this.q[5 * nd + 2]; return w; }; for (let s = 0; s < nSamples * m; s++) { if (this.movieEvery > 0 && this.n % (m * this.movieEvery) === 0) { frames.push(capture()); frameSamples.push(this.n / m); } if (this.dispEvery > 0 && this.n % (m * this.dispEvery) === 0) { dispFrames.push(capture()); dispSamples.push(this.n / m); } this.step(); } this.samplesDone += nSamples; const out = this.pending; this.pending = []; const firstSample = out.length ? out[0].j : this.samplesDone; let acceleration: Float32Array | null = null; if (this.recordAcceleration) { acceleration = new Float32Array(out.length * N); out.forEach((o, i) => acceleration!.set(o.acc!, i * N)); } return { firstSample, pressureFront: Float32Array.from(out, (o) => o.front), pressureBack: Float32Array.from(out, (o) => o.back), frames, frameSamples, acceleration, dispFrames, dispSamples }; } async diagnostics(): Promise { const { shell: sh, schedule: sc, dt } = this.setup, N = sh.mesh.n; let ke = 0, woh = 0; for (let i = 0; i < 5 * N; i++) ke += 0.5 * sh.M[i] * this.v[i] * this.v[i]; for (let nd = 0; nd < N; nd++) woh = Math.max(woh, Math.abs(this.q[5 * nd + 2] / sh.hNode[nd])); const { membrane, bending } = strainEnergies(sh, this.q); let ex = 0; for (let k = 0; k < sc.K; k++) ex += 0.5 * sc.mass[k] * this.vs[k] * this.vs[k]; return { time: this.n * dt, kinetic: ke, membrane, bending, exciters: ex, maxWoverH: woh, hits: Array.from({ length: sc.K }, (_, k) => ({ peakForce: this.Fmax[k], contactTime: this.ncont[k] * dt, velocity: this.vs[k], height: this.zs[k] })) }; } /** M-weighted rigid-mode content of the current velocity (the lagged projection leaves one step's increment). */ rigidContent(): number { const { shell: sh } = this.setup, L = 5 * sh.mesh.n; let worst = 0; for (let k = 0; k < 6; k++) { let c = 0; for (let i = 0; i < L; i++) c += sh.Rm[k * L + i] * sh.M[i] * this.v[i]; worst = Math.max(worst, Math.abs(c)); } return worst; } async displacement(): Promise { const N = this.setup.mesh.n, w = new Float32Array(N); for (let nd = 0; nd < N; nd++) w[nd] = this.q[5 * nd + 2]; return w; } async exportState(): Promise { return { kind: "cpu", step: this.n, samplesDone: this.samplesDone, arrays: { q: this.q.slice(), v: this.v.slice(), vPrev: this.vPrev.slice(), partials: this.partialsPrev.slice(), zs: this.zs.slice(), vs: this.vs.slice(), Fmax: this.Fmax.slice(), ncont: this.ncont.slice(), accRing: this.accRing.slice(), elemHist: this.elemHist.slice() } }; } async importState(st: BackendState): Promise { if (st.kind !== "cpu") throw new Error("state was written by another backend"); const a = st.arrays; for (const [name, dst] of [["q", this.q], ["v", this.v], ["vPrev", this.vPrev], ["partials", this.partialsPrev], ["zs", this.zs], ["vs", this.vs], ["Fmax", this.Fmax], ["ncont", this.ncont], ["accRing", this.accRing], ["elemHist", this.elemHist]] as const) { if (!a[name] || a[name].length !== dst.length) throw new Error(`state array ${name} is missing or has the wrong size`); (dst as Float64Array).set(a[name] as any); } this.n = st.step; this.samplesDone = st.samplesDone; this.pending = []; } dispose() {} }