087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 1// The time-domain engine: strings (two polarisations each) coupled at the bridge to the body modes,
2// plucked by a finger, stopped by a finger, heard through the body's radiation.
3//
4// String, modal form. A string of vibrating length L (stop/nut at x = 0, bridge at x = L) whose
5// bridge end moves with the bridge notch, w(t), in each polarisation:
6// u(x,t) = w(t) x/L + sum_n q_n(t) sin(n pi x / L)
7// From the Lagrangian (kinetic energy of string and body, tension + bending + body potential):
8// q_n'' + 2 s_n q_n' + w_n^2 q_n = (2 / mu L) G_n - g_n w'' g_n = 2 (-1)^(n+1) / (n pi)
9// eta_m'' + 2 z_m W_m eta_m' + W_m^2 eta_m = - sum_c B_cm [ T w_c/L + (mu L/2) sum_n g_n q_n'' + (mu L/3) w_c'' - F_dir,c ]
10// with w_c = sum_m B_cm eta_m (c = string x polarisation, B = the body's notch mode shapes by/bz).
11// The w'' mass coupling is solved exactly each step: everything is linear in the unknown notch
12// displacements w+ (one per string-polarisation, at most 8), and the matrix of that small system is
13// constant, so it is inverted once. Each oscillator uses a central-difference update with its
14// stiffness replaced by (2/k sin(w k/2))^2, which makes the discrete frequency exact and the scheme
15// stable for every mode below Nyquist. Per-mode damping s_n is Valette's (air + viscoelastic + floor).
16//
17// Geometric nonlinearity (Kirchhoff-Carrier): the tension rises by EA/(2L) int u_x^2 dx, summed
18// over both polarisations, explicit in time.
19//
20// Plucking finger: during the stick phase a pad (spring padK + dashpot padR, spread over padWidth)
21// is dragged at pullSpeed in the pull direction; when the contact force reaches the release force
22// for the velocity, the string slides off the pad and the force falls to zero as cos^2 over the
23// slip time. Stopping finger: a dashpot near the stop, implicit (it is very stiff in modal terms).
24//
25// String, FD form (engine.stringModel = "fd"): the same string as a finite-difference stiff string
26// with Bilbao's frequency-dependent loss (sigma0 + sigma1 beta^2, fitted to the Valette damping at
27// the fundamental and at 2 kHz), the bridge end node moving with the notch; its force on the bridge
28// (tension and bending shear at the end, plus half a cell of mass) enters the same notch solve.
29//
30// Output: p(t) = sum_m radRe_m eta_m'' - radIm_m W_m eta_m' (complex radiation at each mode's
31// frequency), computed at the internal rate and decimated.
33import type { Params } from "./params.ts";
34import type { BodyMode, BodyModel } from "./types.ts";
35import { N_STRINGS, STRING_OPEN_MIDI } from "./types.ts";
36import { fingering, midiToHz, pluckForVelocity, stringConst, stringModes, valetteQinv, type Fingering, type StringConst } from "./strings.ts";
37import { bandFrequency, decimate } from "./dsp.ts";
39export interface RenderOpts {
40 note: number;
41 velocity: number;
42 /** seconds of sound after the release (default p.engine.duration) */
43 duration?: number;
44 /** seconds kept before the release (default 0.004) */
45 preRoll?: number;
46 onProgress?: (frac: number) => void;
47 /** explicit tuning (open-string tension factors, stopped-length factor); default: tuneByEar */
48 tuning?: Tuning;
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 49 /** record the state for visualisation (see Recording) */
50 record?: RecordSpec;
51}
53/**
54 * What to record for the physics visualisation. Time t is simulation time from the start of the
55 * pull (t = 0), not the audio time. "Dense" frames are taken every internal step inside
56 * [denseFrom, denseTo] (denseTo = Infinity: until denseAfterRelease after the release), "sparse"
57 * frames every sparseDt elsewhere. Scalar channels are recorded at every step.
58 */
59export interface RecordSpec {
60 denseFrom: number;
61 denseTo: number;
62 denseAfterRelease: number;
63 maxDense: number;
64 sparseDt: number;
65 /** points along the played string and along each sympathetic string */
66 stringPoints: number;
67 sympPoints: number;
68 /** body modes with index < shapeModes have mesh shapes: their coordinates go into the frames */
69 shapeModes: number;
70 /** per body mode: share of the energy in the air (cavity + f-hole plugs); default 0 (A0: 1) */
71 airFrac?: ArrayLike<number>;
72}
74export const CHANNELS = ["fingerFy", "fingerFz", "bridgeFy", "bridgeFz", "eString", "eSymp", "eBody", "eAir", "mic", "pickup"] as const;
75export type Channel = (typeof CHANNELS)[number];
77export interface Recording {
78 /** internal time step, s; channel sample j is at t = j dt */
79 dt: number;
80 nSteps: number;
81 channels: Record<Channel, Float32Array>;
82 /** frames: nFrames x frameSize, at frameTimes (s, ascending) */
83 frameTimes: Float64Array;
84 frames: Float32Array;
85 frameSize: number;
86 /** per recorded string: which string, vibrating length, points, offset of its y block (z block follows) */
87 strings: { string: number; length: number; points: number; offset: number; played: boolean }[];
88 /** offset of the 8 notch displacements (y of strings 0..3, then z of strings 0..3), m */
89 notchOffset: number;
90 /** offset and body-mode indices of the recorded body coordinates (already scaled by any mode thinning) */
91 etaOffset: number;
92 etaModes: Int32Array;
93 /** the dense window actually recorded, s */
94 dense: [number, number];
95 tRelease: number;
96 slipTime: number;
97 releaseForce: number;
98 /** pull direction (y = away from the fingerboard, z = across) and speed m/s, pluck point (m from the stop) */
99 pull: { dirY: number; dirZ: number; speed: number; x: number; padWidth: number };
100 /** audio sample 0 is at this simulation time */
101 audioT0: number;
104export interface Tuning { tensionScale: number[]; lengthScale: number }
106export interface RenderResult {
107 /** the output mix (mixOutput of mic and pickup), at p.engine.sampleRate */
108 audio: Float32Array;
109 /** radiated pressure at the listener, Pa */
110 mic: Float32Array;
111 /** bridge pickup, Pa-equivalent (pickupPaPerN per N of string force on the bridge) */
112 pickup: Float32Array;
113 sampleRate: number;
114 fingering: Fingering;
115 releaseForce: number;
116 slipTime: number;
117 /** time from the start of the pull to the release, s */
118 stickTime: number;
119 /** cpu time, s */
120 elapsed: number;
121 modeCounts: { strings: number[]; body: number };
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 122 recording?: Recording;
125/** One string-polarisation's contribution to the notch solve, common to modal and FD strings. */
126interface StringPol {
127 /** before the solve: given the finger force on this polarisation and the tension increase, compute P (k^2-scaled bracket, known part) */
128 pre(fingerF: number, dT: number): number;
129 /** residual mass at the notch (constant), kg */
130 readonly m: number;
131 /** after the solve: advance to n+1 given w+ */
132 post(wNext: number): void;
133 /** displacement at the finger (weighted over the pad), current step and previous step */
134 uFinger(): number;
135 uFingerPrev(): number;
136 /** int u_x^2 dx (for the tension modulation) */
137 e2(): number;
138 /** the notch displacement now and one step ago */
139 w: number;
140 wPrev: number;
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 141 /** displacement at n evenly spaced points, x_j = j L / (n - 1) (stop to bridge), into out[off..] */
142 sample(n: number, out: Float32Array, off: number): void;
143 /** vibrational energy (kinetic + potential of the string's own motion), J */
144 energy(): number;
147const HANN_PTS = 9;
149/** Pad weights: raised cosine over the pad width, normalised to sum 1. */
150function padPoints(center: number, width: number, L: number): { x: number[]; wt: number[] } {
151 const x: number[] = [], wt: number[] = [];
152 let s = 0;
153 for (let j = 0; j < HANN_PTS; j++) {
154 const t = (j + 0.5) / HANN_PTS - 0.5; // -0.5..0.5
155 const v = 0.5 + 0.5 * Math.cos(2 * Math.PI * t);
156 const xx = Math.min(L * 0.999, Math.max(L * 0.001, center + t * width));
157 x.push(xx); wt.push(v); s += v;
158 }
159 return { x, wt: wt.map((v) => v / s) };
160}
162class ModalPol implements StringPol {
163 N: number;
164 q: Float64Array; qp: Float64Array; qn: Float64Array;
165 a: Float64Array; om: Float64Array; inv: Float64Array; g: Float64Array; G2: Float64Array;
166 fw: Float64Array; e: Float64Array; kn2: Float64Array; Ap: Float64Array;
167 m: number;
168 w = 0; wPrev = 0;
169 private kappa: number; private k2: number; private muL2: number; private muL3: number;
170 private L: number; private mu: number; private T: number;
171 private xfOverL: number; private rho: number; private damp: boolean;
172 private aD = 0; private bD = 0; private sEE: number;
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 173 private sinTab: Float32Array | null = null; private sinN = 0;
175 constructor(sc: StringConst, L: number, modes: { w: Float64Array; sigma: Float64Array }, k: number, finger: { x: number[]; wt: number[] } | null, stop: { x: number; r: number } | null) {
176 const N = modes.w.length;
177 this.N = N; this.L = L; this.mu = sc.mu; this.T = sc.T;
178 this.q = new Float64Array(N); this.qp = new Float64Array(N); this.qn = new Float64Array(N);
179 this.a = new Float64Array(N); this.om = new Float64Array(N); this.inv = new Float64Array(N);
180 this.g = new Float64Array(N); this.G2 = new Float64Array(N); this.fw = new Float64Array(N);
181 this.e = new Float64Array(N); this.kn2 = new Float64Array(N); this.Ap = new Float64Array(N);
182 this.k2 = k * k;
183 this.kappa = (k * k * 2) / (sc.mu * L);
184 this.muL2 = (sc.mu * L) / 2; this.muL3 = (sc.mu * L) / 3;
185 this.xfOverL = finger ? finger.x.reduce((s, x, j) => s + x * finger.wt[j], 0) / L : 0;
186 this.damp = !!stop && stop.r > 0;
187 this.rho = stop ? stop.r / (2 * k) : 0;
188 for (let n = 0; n < N; n++) {
189 const nn = n + 1;
190 const s = Math.sin((modes.w[n] * k) / 2);
191 this.a[n] = 4 * s * s; // k^2 * wtilde^2
192 this.om[n] = 1 - modes.sigma[n] * k;
193 this.inv[n] = 1 / (1 + modes.sigma[n] * k);
194 this.g[n] = (2 * (nn % 2 === 1 ? 1 : -1)) / (nn * Math.PI);
195 this.kn2[n] = (nn * Math.PI / L) ** 2;
196 if (finger) {
197 let v = 0;
198 for (let j = 0; j < finger.x.length; j++) v += finger.wt[j] * Math.sin((nn * Math.PI * finger.x[j]) / L);
199 this.fw[n] = v;
200 }
201 if (stop) this.e[n] = Math.sin((nn * Math.PI * stop.x) / L);
202 }
203 // stop damper elimination constants: F_d = aD + bD w+
204 let sEE = 0, sEG = 0;
205 for (let n = 0; n < N; n++) { sEE += this.e[n] * this.e[n] * this.inv[n]; sEG += this.e[n] * this.g[n] * this.inv[n]; }
206 this.sEE = sEE;
207 const den = 1 + this.rho * this.kappa * sEE;
208 this.bD = this.damp ? (this.rho * sEG) / den : 0;
209 // Gamma_n = g_n - kappa e_n bD; beta = sum g inv Gamma
210 let beta = 0;
211 for (let n = 0; n < N; n++) { this.G2[n] = this.g[n] - this.kappa * this.e[n] * this.bD; beta += this.g[n] * this.inv[n] * this.G2[n]; }
212 this.m = sc.mu * L * (1 / 3 - beta / 2);
213 }
215 pre(fingerF: number, dT: number): number {
216 const { N, q, qp, a, om, g, kn2, fw, Ap, inv } = this;
217 const k2 = this.k2, kap = this.kappa;
218 const wTerm = -2 * this.w + this.wPrev;
219 const nl = (k2 * dT) / this.mu;
220 let alpha = 0, sGq = 0, sEA = 0, usPrev = 0;
221 for (let n = 0; n < N; n++) {
222 const qn = q[n];
223 const A = 2 * qn - om[n] * qp[n] - a[n] * qn - g[n] * wTerm + kap * fingerF * fw[n] - nl * kn2[n] * qn;
224 Ap[n] = A;
225 sGq += g[n] * (2 * qn - qp[n]);
226 }
227 if (this.damp) {
228 const e = this.e;
229 for (let n = 0; n < N; n++) { sEA += e[n] * Ap[n] * inv[n]; usPrev += e[n] * qp[n]; }
230 this.aD = (-this.rho * (sEA - usPrev)) / (1 + this.rho * kap * this.sEE);
231 const ka = kap * this.aD;
232 for (let n = 0; n < N; n++) Ap[n] += ka * e[n];
233 }
234 for (let n = 0; n < N; n++) alpha += g[n] * inv[n] * Ap[n];
235 const fDir = fingerF * this.xfOverL;
236 return this.muL2 * (alpha - sGq) + this.muL3 * wTerm + k2 * (((this.T + dT) * this.w) / this.L - fDir);
237 }
239 post(wNext: number): void {
240 const { N, Ap, G2, inv, qn } = this;
241 for (let n = 0; n < N; n++) qn[n] = (Ap[n] - G2[n] * wNext) * inv[n];
242 const t = this.qp; this.qp = this.q; this.q = this.qn; this.qn = t;
243 this.wPrev = this.w; this.w = wNext;
244 }
246 uFinger(): number {
247 let s = 0;
248 for (let n = 0; n < this.N; n++) s += this.fw[n] * this.q[n];
249 return s + this.w * this.xfOverL;
250 }
251 uFingerPrev(): number {
252 let s = 0;
253 for (let n = 0; n < this.N; n++) s += this.fw[n] * this.qp[n];
254 return s + this.wPrev * this.xfOverL;
255 }
256 e2(): number {
257 let s = 0;
258 for (let n = 0; n < this.N; n++) s += this.kn2[n] * this.q[n] * this.q[n];
259 return (s * this.L) / 2 + (this.w * this.w) / this.L;
260 }
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 261 sample(np: number, out: Float32Array, off: number): void {
262 const N = this.N;
263 if (!this.sinTab || this.sinN !== np) {
264 this.sinN = np;
265 this.sinTab = new Float32Array(N * np);
266 for (let n = 0; n < N; n++) for (let j = 0; j < np; j++) this.sinTab[n * np + j] = Math.sin(((n + 1) * Math.PI * j) / (np - 1));
267 }
268 const tab = this.sinTab, q = this.q;
269 for (let j = 0; j < np; j++) out[off + j] = (this.w * j) / (np - 1);
270 for (let n = 0; n < N; n++) {
271 const qn = q[n];
272 if (qn === 0) continue;
273 const o = n * np;
274 for (let j = 1; j < np - 1; j++) out[off + j] += qn * tab[o + j];
275 }
276 }
277 energy(): number {
278 const { N, q, qp, a } = this;
279 let s = 0;
280 for (let n = 0; n < N; n++) { const v = q[n] - qp[n]; s += v * v + a[n] * q[n] * q[n]; }
281 return ((this.mu * this.L) / 4) * s / this.k2;
282 }
285class FDPol implements StringPol {
286 N: number; h: number;
287 u: Float64Array; up: Float64Array; un: Float64Array;
288 m: number;
289 w = 0; wPrev = 0;
290 private c2: number; private kap2: number; private s1: number;
291 private k: number; private mu: number; private T: number; private EI: number;
292 private den: Float64Array; private pc: Float64Array; private fwt: Float64Array; private fIdx: Int32Array;
293 private fIdxN: number;
295 constructor(sc: StringConst, L: number, k: number, courant: number, sig: { s0: number; s1: number }, finger: { x: number[]; wt: number[] } | null, stop: { x: number; r: number } | null) {
296 this.k = k; this.mu = sc.mu; this.T = sc.T; this.EI = sc.EI;
297 const c2 = sc.T / sc.mu, kap2 = sc.EI / sc.mu;
298 const a = c2 * k * k + 4 * sig.s1 * k;
299 const hmin = Math.sqrt((a + Math.sqrt(a * a + 16 * kap2 * k * k)) / 2);
300 const N = Math.max(8, Math.floor((L * courant) / hmin));
301 const h = L / N;
302 this.N = N; this.h = h; this.c2 = c2; this.kap2 = kap2; this.s1 = sig.s1;
303 this.u = new Float64Array(N + 1); this.up = new Float64Array(N + 1); this.un = new Float64Array(N + 1);
304 this.den = new Float64Array(N + 1); this.pc = new Float64Array(N + 1);
305 for (let l = 0; l <= N; l++) { this.den[l] = 1 + sig.s0 * k; this.pc[l] = 1 - sig.s0 * k; }
306 if (stop && stop.r > 0) {
307 const l = Math.max(1, Math.min(N - 1, Math.round(stop.x / h)));
308 const extra = (stop.r * k) / (2 * sc.mu * h);
309 this.den[l] += extra; this.pc[l] -= extra;
310 }
311 // finger weights onto nodes (linear interpolation of each pad point)
312 const wt = new Float64Array(N + 1);
313 if (finger) {
314 for (let j = 0; j < finger.x.length; j++) {
315 const xl = finger.x[j] / h, l0 = Math.floor(xl), fr = xl - l0;
316 if (l0 >= 1 && l0 <= N - 1) wt[l0] += finger.wt[j] * (1 - fr);
317 if (l0 + 1 >= 1 && l0 + 1 <= N - 1) wt[l0 + 1] += finger.wt[j] * fr;
318 }
319 }
320 const idx: number[] = [];
321 for (let l = 0; l <= N; l++) if (wt[l] !== 0) idx.push(l);
322 this.fIdx = Int32Array.from(idx); this.fIdxN = idx.length;
323 this.fwt = wt;
324 this.m = (sc.mu * h) / 2;
325 }
327 private fF = 0; private dT = 0;
328 pre(fingerF: number, dT: number): number {
329 this.fF = fingerF; this.dT = dT;
330 const { u, h, N } = this;
331 const k2 = this.k * this.k;
332 const uxxx = (-u[N - 2] + 2 * u[N - 1] - this.w) / (h * h * h);
333 return k2 * (((this.T + dT) * (this.w - u[N - 1])) / h - this.EI * uxxx) + this.m * (-2 * this.w + this.wPrev);
334 }
336 post(wNext: number): void {
337 const { u, up, un, N, h, den, pc } = this;
338 const k = this.k, k2 = k * k;
339 const lam2 = ((this.c2 + this.dT / this.mu) * k2) / (h * h);
340 const mu2 = (this.kap2 * k2) / (h * h * h * h);
341 const sx = (2 * this.s1 * k) / (h * h);
342 const fsc = (k2 * this.fF) / (this.mu * h);
343 const w = this.w;
344 // ghost values: u[-1] = -u[1], u[N+1] = 2 w - u[N-1]; same for the previous step
345 const at = (arr: Float64Array, l: number, wv: number) => (l < 0 ? -arr[-l] : l > N ? 2 * wv - arr[2 * N - l] : arr[l]);
346 for (let l = 1; l < N; l++) {
347 const ul = u[l];
348 const dxx = u[l + 1] - 2 * ul + u[l - 1];
349 const dxxp = up[l + 1] - 2 * up[l] + up[l - 1];
350 let d4: number;
351 if (l >= 2 && l <= N - 2) d4 = u[l + 2] - 4 * u[l + 1] + 6 * ul - 4 * u[l - 1] + u[l - 2];
352 else d4 = at(u, l + 2, w) - 4 * u[l + 1] + 6 * ul - 4 * u[l - 1] + at(u, l - 2, w);
353 un[l] = (2 * ul - pc[l] * up[l] + lam2 * dxx - mu2 * d4 + sx * (dxx - dxxp) + fsc * this.fwt[l]) / den[l];
354 }
355 un[0] = 0; un[N] = wNext;
356 this.up = u; this.u = un; this.un = up;
357 this.wPrev = this.w; this.w = wNext;
358 }
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 360 sample(np: number, out: Float32Array, off: number): void {
361 const { u, N } = this;
362 for (let j = 0; j < np; j++) {
363 const xl = (j * N) / (np - 1), l0 = Math.min(N - 1, Math.floor(xl)), fr = xl - l0;
364 out[off + j] = u[l0] * (1 - fr) + u[l0 + 1] * fr;
365 }
366 }
367 energy(): number {
368 const { u, up, N, h, k } = this;
369 let ke = 0, pe = 0;
370 for (let l = 0; l <= N; l++) { const v = u[l] - up[l]; ke += v * v; }
371 for (let l = 0; l < N; l++) { const d = u[l + 1] - u[l]; pe += d * d; }
372 return (0.5 * this.mu * h * ke) / (k * k) + (0.5 * this.T * pe) / h;
373 }
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 374 uFinger(): number { let s = 0; for (let j = 0; j < this.fIdxN; j++) { const l = this.fIdx[j]; s += this.fwt[l] * this.u[l]; } return s; }
375 uFingerPrev(): number { let s = 0; for (let j = 0; j < this.fIdxN; j++) { const l = this.fIdx[j]; s += this.fwt[l] * this.up[l]; } return s; }
376 e2(): number {
377 let s = 0;
378 for (let l = 0; l < this.N; l++) { const d = this.u[l + 1] - this.u[l]; s += d * d; }
379 return s / this.h;
380 }
381}
383/**
384 * Bilbao loss parameters sigma0, sigma1 (decay sigma0 + sigma1 beta^2) fitted to the Valette
385 * damping of the string's partials from f1 up to fTop, minimising the relative error. The FD loss
386 * grows as f^2 at high frequency while Valette's floor makes it ~ f, so this is a compromise; the
387 * modal string reproduces Valette exactly.
388 */
389function fitFDLoss(p: Params, sc: StringConst, f1: number, fTop: number): { s0: number; s1: number } {
390 const c2 = sc.T / sc.mu, kap2 = sc.EI / sc.mu;
391 const beta2 = (f: number) => { const w = 2 * Math.PI * f; return (-c2 + Math.sqrt(c2 * c2 + 4 * kap2 * w * w)) / (2 * kap2); };
392 // minimise sum_n w_n ((s0 + s1 b_n) / sig_n - 1)^2, b_n = beta^2, w_n = 1/n (the low partials carry the sustain)
393 let a11 = 0, a12 = 0, a22 = 0, r1 = 0, r2 = 0;
394 for (let n = 1; n * f1 <= fTop; n++) {
395 const f = n * f1, sg = Math.PI * f * valetteQinv(p, sc, f), b = beta2(f), wn = 1 / n;
396 const u = 1 / sg, v = b / sg;
397 a11 += wn * u * u; a12 += wn * u * v; a22 += wn * v * v; r1 += wn * u; r2 += wn * v;
398 }
399 const det = a11 * a22 - a12 * a12;
400 let s0 = (r1 * a22 - r2 * a12) / det, s1 = (a11 * r2 - a12 * r1) / det;
401 if (s1 < 0) { s1 = 0; s0 = r1 / a11; }
402 if (s0 < 0) { s0 = 0; s1 = r2 / a22; }
403 return { s0, s1 };
404}
406export function renderNote(p: Params, body: BodyModel, o: RenderOpts): RenderResult {
407 const t0 = performance.now();
408 const fs = p.engine.sampleRate;
409 const os = Math.max(1, Math.round(p.engine.oversample));
410 const fsi = fs * os, k = 1 / fsi;
411 const fmaxStr = Math.min(p.engine.stringFmax, 0.3 * fsi);
412 const fing = fingering(p, o.note);
413 const { force: fRel, slip } = pluckForVelocity(p, o.velocity);
414 const duration = o.duration ?? p.engine.duration;
415 const preRoll = o.preRoll ?? 0.004;
417 // ---- body
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 418 const srcModes: TaggedMode[] = o.record ? body.modes.map((m, i) => ({ ...m, src: i })) : body.modes;
419 const bm = thinModes(srcModes.filter((m) => m.f > 0 && m.f < 0.45 * fsi), p.engine.bodyOverlap);
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 420 const M = bm.length;
421 const bA = new Float64Array(M), bOm = new Float64Array(M), bInv = new Float64Array(M);
422 const rr = new Float64Array(M), ri = new Float64Array(M);
423 for (let m = 0; m < M; m++) {
424 const wm = 2 * Math.PI * bm[m].f;
425 const s = Math.sin((wm * k) / 2);
426 const sk = bm[m].zeta * wm * k;
427 bA[m] = 4 * s * s; bOm[m] = 1 - sk; bInv[m] = 1 / (1 + sk);
428 rr[m] = bm[m].radRe / (k * k);
429 ri[m] = (bm[m].radIm * wm) / (2 * k);
430 }
432 // ---- tuning by ear (see tuneByEar): tension of the open strings, length of the stopped note
433 const L0 = p.strings.scaleLength;
434 const tuning = o.tuning ?? (p.engine.intonate ? tuneByEar(p, body, fing) : null);
435 const tensionScale = tuning ? tuning.tensionScale : [1, 1, 1, 1];
436 if (tuning && fing.stopped) fing.length *= tuning.lengthScale;
438 // ---- strings: the played one, and the other open strings if sympathetic
439 const finger = padPoints(fing.length - p.pluck.position, p.pluck.padWidth, fing.length);
440 // keep the pluck point on the string for short (high) notes: at most 40 % of the length from the bridge
441 if (p.pluck.position > 0.4 * fing.length) {
442 const pp = padPoints(0.6 * fing.length, Math.min(p.pluck.padWidth, 0.1 * fing.length), fing.length);
443 finger.x = pp.x; finger.wt = pp.wt;
444 }
445 const pols: StringPol[] = [];
446 const polString: number[] = [];
447 const polDir: number[] = []; // 0 = y (vertical), 1 = z (lateral)
448 const active: number[] = [fing.string];
449 if (p.engine.sympathetic) for (let i = 0; i < N_STRINGS; i++) if (i !== fing.string) active.push(i);
450 const strModeCounts: number[] = [];
451 const muteSigma = 25 * p.engine.sympatheticMute;
452 const scs: StringConst[] = [];
453 const Ls: number[] = [];
454 for (const si of active) {
455 const sc0 = stringConst(p, si);
456 const sc: StringConst = { ...sc0, T: sc0.T * tensionScale[si] };
457 const played = si === fing.string;
458 const L = played ? fing.length : L0;
459 const stop = played && fing.stopped && p.stop.damping > 0 ? { x: p.stop.offset, r: p.stop.damping } : null;
460 const extra = played ? 0 : muteSigma;
461 scs[si] = sc; Ls[si] = L;
462 for (let dir = 0; dir < 2; dir++) {
463 if (p.engine.stringModel === "fd") {
464 const f1 = Math.sqrt(sc.T / sc.mu) / (2 * L);
465 const sig = fitFDLoss(p, sc, f1, 1500);
466 sig.s0 += extra;
467 pols.push(new FDPol(sc, L, k, p.engine.fdCourant, sig, played ? finger : null, stop));
468 if (dir === 0) strModeCounts.push((pols[pols.length - 1] as FDPol).N);
469 } else {
470 const modes = stringModes(p, sc, L, played ? fmaxStr : Math.min(fmaxStr, 5000), extra);
471 pols.push(new ModalPol(sc, L, modes, k, played ? finger : null, stop));
472 if (dir === 0) strModeCounts.push(modes.w.length);
473 }
474 polString.push(si); polDir.push(dir);
475 }
476 }
477 const C = pols.length;
478 // notch mode shapes per string-polarisation, stored mode-major: BT[m*C + c]
479 const BT = new Float64Array(C * M);
480 for (let c = 0; c < C; c++) for (let m = 0; m < M; m++) BT[m * C + c] = polDir[c] === 0 ? bm[m].by[polString[c]] : bm[m].bz[polString[c]];
481 // Phi_dc = sum_m B_dm B_cm inv_m ; system (I + Phi diag(m)) w+ = SB - Phi P
482 const Phi = new Float64Array(C * C);
483 for (let m = 0; m < M; m++) for (let d = 0; d < C; d++) for (let c = 0; c < C; c++) Phi[d * C + c] += BT[m * C + d] * BT[m * C + c] * bInv[m];
484 const Ms = new Float64Array(C * C);
485 for (let d = 0; d < C; d++) for (let c = 0; c < C; c++) Ms[d * C + c] = (d === c ? 1 : 0) + Phi[d * C + c] * pols[c].m;
486 const Minv = invert(Ms, C);
488 // ---- finger
489 const ang = (p.pluck.angleDeg * Math.PI) / 180;
490 const dirY = -Math.sin(ang), dirZ = Math.cos(ang); // pull: sideways, slightly into the board (-y)
491 const iy = 0, iz = 1; // the played string is first in `active`, so its pols are 0 (y) and 1 (z)
492 let phase: 0 | 1 | 2 = 0; // 0 stick, 1 slip, 2 free
493 let tRel = -1, relFy = 0, relFz = 0;
494 const maxStick = 0.25;
496 const eta = new Float64Array(M), etaP = new Float64Array(M), etaN = new Float64Array(M);
497 const Bm = new Float64Array(M);
498 const P = new Float64Array(C), SB = new Float64Array(C), rhs = new Float64Array(C), wN = new Float64Array(C), fc = new Float64Array(C);
499 // pickup: a bridge piezo reading the strings' force on the bridge (vertical + a share of lateral),
500 // in Pa-equivalent (pickupPaPerN per newton) so it mixes with the microphone at comparable level
501 const pickY = 1, pickZ = p.output.pickupLateral;
502 const pickScale = p.output.pickupPaPerN / (k * k);
503 const preSteps = Math.round(preRoll * fsi);
504 const postSteps = Math.round(duration * fsi);
505 const maxSteps = Math.round(maxStick * fsi) + postSteps + 1;
506 const ring = new Float64Array(preSteps + 1), ring2 = new Float64Array(preSteps + 1);
507 let ringPos = 0;
508 const out = new Float64Array(preSteps + postSteps), out2 = new Float64Array(preSteps + postSteps);
509 let outN = 0;
510 let relStep = -1;
511 const nonlinear = p.engine.nonlinear;
512 const dTs = new Float64Array(N_STRINGS);
513 let cur = eta, prev = etaP, next = etaN;
514 let lastProg = 0;
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 515 const rec = o.record
516 ? new Recorder(o.record, { k, maxSteps, bm, bA, pols, polDir, active, Ls, played: fing.string })
517 : null;
519 for (let step = 0; step < maxSteps; step++) {
520 const t = step * k;
521 // tension modulation per active string
522 if (nonlinear) {
523 for (let c = 0; c < C; c += 2) {
524 const si = polString[c];
525 dTs[si] = (scs[si].EA / (2 * Ls[si])) * (pols[c].e2() + pols[c + 1].e2());
526 }
527 }
528 // finger force
529 let Fy = 0, Fz = 0;
530 if (phase === 0) {
531 const X = p.pluck.pullSpeed * t;
532 const uy = pols[iy].uFinger(), uz = pols[iz].uFinger();
533 const vy = (uy - pols[iy].uFingerPrev()) / k, vz = (uz - pols[iz].uFingerPrev()) / k;
534 Fy = p.pluck.padK * (X * dirY - uy) + p.pluck.padR * (p.pluck.pullSpeed * dirY - vy);
535 Fz = p.pluck.padK * (X * dirZ - uz) + p.pluck.padR * (p.pluck.pullSpeed * dirZ - vz);
536 const F = Math.hypot(Fy, Fz);
537 if (F >= fRel || t >= maxStick) {
538 phase = 1; tRel = t; relStep = step;
539 const s = fRel / Math.max(F, 1e-12);
540 relFy = Fy * s; relFz = Fz * s; Fy = relFy; Fz = relFz;
541 }
542 } else if (phase === 1) {
543 const x = (t - tRel) / slip;
544 if (x >= 1) { phase = 2; } else { const cc = Math.cos((Math.PI / 2) * x); Fy = relFy * cc * cc; Fz = relFz * cc * cc; }
545 }
546 // strings: known parts
547 for (let c = 0; c < C; c++) {
548 const ff = c === iy ? Fy : c === iz ? Fz : 0;
549 P[c] = pols[c].pre(ff, nonlinear ? dTs[polString[c]] : 0);
550 }
551 // body: known parts, and SB_d = sum_m B_dm Bm_m inv_m
552 SB.fill(0);
553 for (let m = 0; m < M; m++) {
554 const b = 2 * cur[m] - bOm[m] * prev[m] - bA[m] * cur[m];
555 Bm[m] = b;
556 const bi = b * bInv[m], o = m * C;
557 for (let d = 0; d < C; d++) SB[d] += BT[o + d] * bi;
558 }
559 for (let d = 0; d < C; d++) {
560 let s = SB[d];
561 for (let c = 0; c < C; c++) s -= Phi[d * C + c] * P[c];
562 rhs[d] = s;
563 }
564 for (let d = 0; d < C; d++) {
565 let s = 0;
566 for (let c = 0; c < C; c++) s += Minv[d * C + c] * rhs[c];
567 wN[d] = s;
568 }
569 // string forces on the bridge (k^2-scaled, sign: bracket = -k^2 F), body update, output
570 let pick = 0;
571 for (let c = 0; c < C; c++) {
572 fc[c] = P[c] + pols[c].m * wN[c];
573 pick += fc[c] * (polDir[c] === 0 ? pickY : pickZ);
574 }
575 let pr = 0;
576 for (let m = 0; m < M; m++) {
577 let v = Bm[m];
578 const o = m * C;
579 for (let c = 0; c < C; c++) v -= BT[o + c] * fc[c];
580 const en = v * bInv[m];
581 next[m] = en;
582 pr += rr[m] * (en - 2 * cur[m] + prev[m]) - ri[m] * (en - prev[m]);
583 }
584 const pk = -pick * pickScale;
585 for (let c = 0; c < C; c++) pols[c].post(wN[c]);
586 const tmp = prev; prev = cur; cur = next; next = tmp;
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 587 if (rec) rec.step(step, Fy, Fz, fc, pr, pk, cur, prev, relStep >= 0 ? tRel : -1);
589 // output: keep a ring of the last preSteps samples until the release, then record
590 if (relStep < 0) { ring[ringPos] = pr; ring2[ringPos] = pk; ringPos = (ringPos + 1) % (preSteps + 1); }
591 else {
592 if (outN === 0) {
593 // flush the pre-roll (oldest first)
594 for (let j = 0; j < preSteps; j++) { const q = (ringPos + 1 + j) % (preSteps + 1); out[outN] = ring[q]; out2[outN++] = ring2[q]; }
595 }
596 out[outN] = pr; out2[outN++] = pk;
597 if (outN >= out.length) break;
598 }
599 if (o.onProgress && relStep >= 0) {
600 const fr = outN / out.length;
601 if (fr - lastProg > 0.02) { lastProg = fr; o.onProgress(fr); }
602 }
603 }
604 const mic = Float32Array.from(decimate(out.subarray(0, outN), os));
605 const pickup = Float32Array.from(decimate(out2.subarray(0, outN), os));
606 return {
607 audio: mixOutput(p, mic, pickup),
608 mic,
609 pickup,
610 sampleRate: fs,
611 fingering: fing,
612 releaseForce: fRel,
613 slipTime: slip,
614 stickTime: tRel,
615 elapsed: (performance.now() - t0) / 1000,
616 modeCounts: { strings: strModeCounts, body: M },
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 617 recording: rec?.finish({
618 tRelease: tRel, slipTime: slip, releaseForce: fRel, audioT0: relStep >= 0 ? (relStep - preSteps) * k : 0,
619 pull: { dirY, dirZ, speed: p.pluck.pullSpeed, x: finger.x.reduce((s, x, j) => s + x * finger.wt[j], 0), padWidth: p.pluck.padWidth },
620 }),
622}
624/**
625 * Tuning by ear. The bridge gives under the string (spring-like below the body resonances, so the
626 * pitch goes flat; strongly near them), so a player tunes the open strings and places the stopping
627 * finger by ear. Here: short quiet calibration renders (linear, otherwise as the real render,
628 * including the sympathetic strings, which load the bridge too) measure the first partial; the open
629 * strings' tensions (all four, two passes) and then the stopped length are corrected. Cached per body
630 * and string set-up.
631 */
632const tuneCache = new Map<string, number | number[]>();
633export function tuneByEar(p: Params, body: BodyModel, fing: Fingering): Tuning {
634 const bodyKey = `${body.modes.length}:${body.modes.slice(0, 40).reduce((s, m) => s + m.f * 1.7 + m.by[0] * 3.1 + m.bz[3] * 0.7, 0)}`;
635 const q = cloneForTuning(p);
636 const base = JSON.stringify([bodyKey, q.engine, q.strings, q.pluck.angleDeg, q.pluck.position, q.stop, q.fe.stringSpacing]);
637 const measure = (note: number, tuning: Tuning) => {
638 const r = renderNote(q, body, { note, velocity: 40, duration: 1.1, tuning });
639 return bandFrequency(r.audio, r.sampleRate, midiToHz(note), 0.25, 0.85);
640 };
641 // open strings: all four together (they load the bridge for each other), two passes
642 const openKey = `${base}|open`;
643 let tensionScale = tuneCache.get(openKey) as number[] | undefined;
644 if (!tensionScale) {
645 tensionScale = [1, 1, 1, 1];
646 for (let it = 0; it < 2; it++) {
647 for (let si = 0; si < N_STRINGS; si++) {
648 const note = STRING_OPEN_MIDI[si];
649 const f = measure(note, { tensionScale: [...tensionScale], lengthScale: 1 });
650 if (f > 0) tensionScale[si] *= Math.pow(midiToHz(note) / f, 2);
651 }
652 }
653 tuneCache.set(openKey, tensionScale);
654 }
655 let lengthScale = 1;
656 if (fing.stopped) {
657 const note = STRING_OPEN_MIDI[fing.string] + fing.shift;
658 const key = `${base}|note${note}`;
659 const cached = tuneCache.get(key) as number | undefined;
660 if (cached !== undefined) lengthScale = cached;
661 else {
662 for (let it = 0; it < 2; it++) {
663 const f = measure(note, { tensionScale, lengthScale });
664 if (!(f > 0)) break;
665 lengthScale *= f / midiToHz(note);
666 }
667 tuneCache.set(key, lengthScale);
668 }
669 }
670 return { tensionScale, lengthScale };
671}
673function cloneForTuning(p: Params): Params {
674 const q = JSON.parse(JSON.stringify(p)) as Params;
675 q.engine.nonlinear = false; q.engine.oversample = 1; q.engine.intonate = false;
676 // only the first partial matters here: fewer string modes and body modes
677 q.engine.stringFmax = 2500; q.engine.bodyOverlap = Math.max(1, q.engine.bodyOverlap / 2);
678 return q;
679}
681/**
682 * Where the body's modal overlap (half-power bandwidth x modal density) is high, individual modes
683 * cannot be told apart, so the engine can use fewer of them: in 1/6-octave bands, keep every k-th
684 * mode with k = floor(overlap / target), and scale its notch coupling by sqrt(k). That keeps the
685 * band's mean bridge admittance (sum of b^2) and radiated power (sum of b^2 rad^2), and leaves the
686 * overlap at about `target`, so the response stays smooth. target <= 0 keeps every mode.
687 */
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 688export function thinModes<T extends TaggedMode>(modes: T[], target: number): T[] {
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 689 if (!(target > 0)) return modes;
690 const sorted = [...modes].sort((a, b) => a.f - b.f);
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 691 const out: T[] = [];
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 692 let i = 0;
693 while (i < sorted.length) {
694 const f0 = sorted[i].f, f1 = f0 * Math.pow(2, 1 / 6);
695 let j = i;
696 while (j < sorted.length && sorted[j].f < f1) j++;
697 const band = sorted.slice(i, j);
698 const fc = Math.sqrt(f0 * f1), dens = band.length / (f1 - f0);
699 const meanZeta = band.reduce((s, m) => s + m.zeta, 0) / band.length;
700 const overlap = dens * 2 * meanZeta * fc;
701 const k = Math.max(1, Math.floor(overlap / target));
702 if (k === 1 || band.length < 2 * k) out.push(...band);
703 else {
704 const g = Math.sqrt(k);
705 for (let q = Math.floor(k / 2); q < band.length; q += k) {
706 const m = band[q];
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 707 out.push({ ...m, by: m.by.map((v) => v * g), bz: m.bz.map((v) => v * g), thin: g });
709 }
710 i = j;
711 }
712 return out;
713}
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 715/** A body mode as the engine uses it: its index in the body model, and the thinning gain. */
716type TaggedMode = BodyMode & { src?: number; thin?: number };
718interface RecorderEnv { k: number; maxSteps: number; bm: TaggedMode[]; bA: Float64Array; pols: StringPol[]; polDir: number[]; active: number[]; Ls: number[]; played: number }
720/** Collects the frames and channels of a Recording during renderNote. */
721class Recorder {
722 private ch: Record<Channel, Float32Array>;
723 private frames: Float32Array[] = [];
724 private times: number[] = [];
725 private nSteps = 0;
726 private nDense = 0;
727 private denseStart = -1;
728 private denseLast = -1;
729 private nextSparse = 0;
730 private readonly F: number;
731 private readonly strings: Recording["strings"] = [];
732 private readonly notchOffset: number;
733 private readonly etaOffset: number;
734 private readonly etaIdx: Int32Array; // engine mode index of each recorded coordinate
735 private readonly etaModes: Int32Array;
736 private readonly etaGain: Float32Array;
737 private readonly BY: Float64Array; private readonly BZ: Float64Array; // M x 4
738 private readonly air: Float64Array; // per engine mode
739 private readonly spec: RecordSpec;
740 private readonly e: RecorderEnv;
741 constructor(spec: RecordSpec, e: RecorderEnv) {
742 this.spec = spec; this.e = e;
743 this.ch = Object.fromEntries(CHANNELS.map((c) => [c, new Float32Array(e.maxSteps)])) as Record<Channel, Float32Array>;
744 let off = 0;
745 for (const si of e.active) {
746 const played = si === e.played;
747 const points = played ? spec.stringPoints : spec.sympPoints;
748 this.strings.push({ string: si, length: e.Ls[si], points, offset: off, played });
749 off += 2 * points;
750 }
751 this.notchOffset = off; off += 8;
752 this.etaOffset = off;
753 const idx: number[] = [];
754 e.bm.forEach((m, j) => { if (m.src !== undefined && m.src < spec.shapeModes) idx.push(j); });
755 this.etaIdx = Int32Array.from(idx);
756 this.etaModes = Int32Array.from(idx, (j) => e.bm[j].src!);
757 this.etaGain = Float32Array.from(idx, (j) => e.bm[j].thin ?? 1);
758 this.F = off + idx.length;
759 const M = e.bm.length;
760 this.BY = new Float64Array(M * 4); this.BZ = new Float64Array(M * 4); this.air = new Float64Array(M);
761 e.bm.forEach((m, j) => {
762 for (let i = 0; i < 4; i++) { this.BY[j * 4 + i] = m.by[i]; this.BZ[j * 4 + i] = m.bz[i]; }
763 const src = m.src ?? -1;
764 this.air[j] = spec.airFrac && src >= 0 && src < spec.airFrac.length ? spec.airFrac[src] : m.label === "A0" ? 1 : 0;
765 });
766 }
768 step(n: number, Fy: number, Fz: number, fc: Float64Array, pr: number, pk: number, cur: Float64Array, prev: Float64Array, tRel: number): void {
769 const { k, pols, polDir, bA } = this.e;
770 const ch = this.ch, k2 = k * k;
771 ch.fingerFy[n] = Fy; ch.fingerFz[n] = Fz;
772 let by = 0, bz = 0;
773 for (let c = 0; c < fc.length; c++) { if (polDir[c] === 0) by -= fc[c]; else bz -= fc[c]; }
774 ch.bridgeFy[n] = by / k2; ch.bridgeFz[n] = bz / k2;
775 let eS = 0, eY = 0;
776 for (let c = 0; c < pols.length; c++) { const en = pols[c].energy(); if (c < 2) eS += en; else eY += en; }
777 ch.eString[n] = eS; ch.eSymp[n] = eY;
778 let eB = 0, eA = 0;
779 for (let m = 0; m < cur.length; m++) {
780 const v = cur[m] - prev[m];
781 const en = (0.5 * (v * v + bA[m] * cur[m] * cur[m])) / k2;
782 const a = this.air[m];
783 eA += a * en; eB += (1 - a) * en;
784 }
785 ch.eBody[n] = eB; ch.eAir[n] = eA;
786 ch.mic[n] = pr; ch.pickup[n] = pk;
787 this.nSteps = n + 1;
788 // frames: the state after this step, at t = (n + 1) k
789 const t = (n + 1) * k, sp = this.spec;
790 const denseTo = Number.isFinite(sp.denseTo) ? sp.denseTo : tRel >= 0 ? tRel + sp.denseAfterRelease : Infinity;
791 const dense = t >= sp.denseFrom && t <= denseTo && this.nDense < sp.maxDense;
792 if (dense || t >= this.nextSparse) {
793 if (dense) { this.nDense++; if (this.denseStart < 0) this.denseStart = t; this.denseLast = t; }
794 while (this.nextSparse <= t) this.nextSparse += sp.sparseDt;
795 this.capture(t, cur);
796 }
797 }
799 private capture(t: number, eta: Float64Array): void {
800 const f = new Float32Array(this.F);
801 const { pols } = this.e;
802 this.strings.forEach((s, a) => {
803 pols[2 * a].sample(s.points, f, s.offset);
804 pols[2 * a + 1].sample(s.points, f, s.offset + s.points);
805 });
806 const M = eta.length, o = this.notchOffset;
807 for (let m = 0; m < M; m++) {
808 const v = eta[m];
809 if (v === 0) continue;
810 for (let i = 0; i < 4; i++) { f[o + i] += this.BY[m * 4 + i] * v; f[o + 4 + i] += this.BZ[m * 4 + i] * v; }
811 }
812 for (let q = 0; q < this.etaIdx.length; q++) f[this.etaOffset + q] = eta[this.etaIdx[q]] * this.etaGain[q];
813 this.frames.push(f);
814 this.times.push(t);
815 }
817 finish(x: Pick<Recording, "tRelease" | "slipTime" | "releaseForce" | "audioT0" | "pull">): Recording {
818 const n = this.nSteps;
819 const channels = Object.fromEntries(CHANNELS.map((c) => [c, this.ch[c].slice(0, n)])) as Record<Channel, Float32Array>;
820 const frames = new Float32Array(this.frames.length * this.F);
821 this.frames.forEach((f, i) => frames.set(f, i * this.F));
822 return {
823 dt: this.e.k, nSteps: n, channels,
824 frameTimes: Float64Array.from(this.times), frames, frameSize: this.F,
825 strings: this.strings, notchOffset: this.notchOffset, etaOffset: this.etaOffset, etaModes: this.etaModes,
826 dense: [this.denseStart, this.denseLast],
827 ...x,
828 };
829 }
830}
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 832/** The output: micMix * mic + pickupMix * pickup (with its trim), times the output gain. */
833export function mixOutput(p: Params, mic: Float32Array, pickup: Float32Array): Float32Array {
834 const g = Math.pow(10, p.output.gainDb / 20);
835 const a = p.output.micMix * g, b = p.output.pickupMix * Math.pow(10, p.output.pickupGainDb / 20) * g;
836 const y = new Float32Array(mic.length);
837 for (let i = 0; i < y.length; i++) y[i] = a * mic[i] + b * pickup[i];
838 return y;
839}
841/** Small dense matrix inverse (Gauss-Jordan with partial pivoting). */
842function invert(A: Float64Array, n: number): Float64Array {
843 const a = Float64Array.from(A);
844 const inv = new Float64Array(n * n);
845 for (let i = 0; i < n; i++) inv[i * n + i] = 1;
846 for (let col = 0; col < n; col++) {
847 let piv = col;
848 for (let r = col + 1; r < n; r++) if (Math.abs(a[r * n + col]) > Math.abs(a[piv * n + col])) piv = r;
849 if (piv !== col) for (let j = 0; j < n; j++) {
850 [a[col * n + j], a[piv * n + j]] = [a[piv * n + j], a[col * n + j]];
851 [inv[col * n + j], inv[piv * n + j]] = [inv[piv * n + j], inv[col * n + j]];
852 }
853 const d = a[col * n + col];
854 for (let j = 0; j < n; j++) { a[col * n + j] /= d; inv[col * n + j] /= d; }
855 for (let r = 0; r < n; r++) if (r !== col) {
856 const f = a[r * n + col];
857 if (f === 0) continue;
858 for (let j = 0; j < n; j++) { a[r * n + j] -= f * a[col * n + j]; inv[r * n + j] -= f * inv[col * n + j]; }
859 }
860 }
861 return inv;
862}