/ music / acoustic-base
Sign in
music / acoustic-base
acoustic-base / src / core / engine.ts
641 lines · 29.3 KBBlameHistoryRaw
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;
51export interface Tuning { tensionScale: number[]; lengthScale: number }
53export interface RenderResult {
54 /** the output mix (mixOutput of mic and pickup), at p.engine.sampleRate */
55 audio: Float32Array;
56 /** radiated pressure at the listener, Pa */
57 mic: Float32Array;
58 /** bridge pickup, Pa-equivalent (pickupPaPerN per N of string force on the bridge) */
59 pickup: Float32Array;
60 sampleRate: number;
61 fingering: Fingering;
62 releaseForce: number;
63 slipTime: number;
64 /** time from the start of the pull to the release, s */
65 stickTime: number;
66 /** cpu time, s */
67 elapsed: number;
68 modeCounts: { strings: number[]; body: number };
71/** One string-polarisation's contribution to the notch solve, common to modal and FD strings. */
72interface StringPol {
73 /** before the solve: given the finger force on this polarisation and the tension increase, compute P (k^2-scaled bracket, known part) */
74 pre(fingerF: number, dT: number): number;
75 /** residual mass at the notch (constant), kg */
76 readonly m: number;
77 /** after the solve: advance to n+1 given w+ */
78 post(wNext: number): void;
79 /** displacement at the finger (weighted over the pad), current step and previous step */
80 uFinger(): number;
81 uFingerPrev(): number;
82 /** int u_x^2 dx (for the tension modulation) */
83 e2(): number;
84 /** the notch displacement now and one step ago */
85 w: number;
86 wPrev: number;
89const HANN_PTS = 9;
91/** Pad weights: raised cosine over the pad width, normalised to sum 1. */
92function padPoints(center: number, width: number, L: number): { x: number[]; wt: number[] } {
93 const x: number[] = [], wt: number[] = [];
94 let s = 0;
95 for (let j = 0; j < HANN_PTS; j++) {
96 const t = (j + 0.5) / HANN_PTS - 0.5; // -0.5..0.5
97 const v = 0.5 + 0.5 * Math.cos(2 * Math.PI * t);
98 const xx = Math.min(L * 0.999, Math.max(L * 0.001, center + t * width));
99 x.push(xx); wt.push(v); s += v;
100 }
101 return { x, wt: wt.map((v) => v / s) };
104class ModalPol implements StringPol {
105 N: number;
106 q: Float64Array; qp: Float64Array; qn: Float64Array;
107 a: Float64Array; om: Float64Array; inv: Float64Array; g: Float64Array; G2: Float64Array;
108 fw: Float64Array; e: Float64Array; kn2: Float64Array; Ap: Float64Array;
109 m: number;
110 w = 0; wPrev = 0;
111 private kappa: number; private k2: number; private muL2: number; private muL3: number;
112 private L: number; private mu: number; private T: number;
113 private xfOverL: number; private rho: number; private damp: boolean;
114 private aD = 0; private bD = 0; private sEE: number;
116 constructor(sc: StringConst, L: number, modes: { w: Float64Array; sigma: Float64Array }, k: number, finger: { x: number[]; wt: number[] } | null, stop: { x: number; r: number } | null) {
117 const N = modes.w.length;
118 this.N = N; this.L = L; this.mu = sc.mu; this.T = sc.T;
119 this.q = new Float64Array(N); this.qp = new Float64Array(N); this.qn = new Float64Array(N);
120 this.a = new Float64Array(N); this.om = new Float64Array(N); this.inv = new Float64Array(N);
121 this.g = new Float64Array(N); this.G2 = new Float64Array(N); this.fw = new Float64Array(N);
122 this.e = new Float64Array(N); this.kn2 = new Float64Array(N); this.Ap = new Float64Array(N);
123 this.k2 = k * k;
124 this.kappa = (k * k * 2) / (sc.mu * L);
125 this.muL2 = (sc.mu * L) / 2; this.muL3 = (sc.mu * L) / 3;
126 this.xfOverL = finger ? finger.x.reduce((s, x, j) => s + x * finger.wt[j], 0) / L : 0;
127 this.damp = !!stop && stop.r > 0;
128 this.rho = stop ? stop.r / (2 * k) : 0;
129 for (let n = 0; n < N; n++) {
130 const nn = n + 1;
131 const s = Math.sin((modes.w[n] * k) / 2);
132 this.a[n] = 4 * s * s; // k^2 * wtilde^2
133 this.om[n] = 1 - modes.sigma[n] * k;
134 this.inv[n] = 1 / (1 + modes.sigma[n] * k);
135 this.g[n] = (2 * (nn % 2 === 1 ? 1 : -1)) / (nn * Math.PI);
136 this.kn2[n] = (nn * Math.PI / L) ** 2;
137 if (finger) {
138 let v = 0;
139 for (let j = 0; j < finger.x.length; j++) v += finger.wt[j] * Math.sin((nn * Math.PI * finger.x[j]) / L);
140 this.fw[n] = v;
141 }
142 if (stop) this.e[n] = Math.sin((nn * Math.PI * stop.x) / L);
143 }
144 // stop damper elimination constants: F_d = aD + bD w+
145 let sEE = 0, sEG = 0;
146 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]; }
147 this.sEE = sEE;
148 const den = 1 + this.rho * this.kappa * sEE;
149 this.bD = this.damp ? (this.rho * sEG) / den : 0;
150 // Gamma_n = g_n - kappa e_n bD; beta = sum g inv Gamma
151 let beta = 0;
152 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]; }
153 this.m = sc.mu * L * (1 / 3 - beta / 2);
154 }
156 pre(fingerF: number, dT: number): number {
157 const { N, q, qp, a, om, g, kn2, fw, Ap, inv } = this;
158 const k2 = this.k2, kap = this.kappa;
159 const wTerm = -2 * this.w + this.wPrev;
160 const nl = (k2 * dT) / this.mu;
161 let alpha = 0, sGq = 0, sEA = 0, usPrev = 0;
162 for (let n = 0; n < N; n++) {
163 const qn = q[n];
164 const A = 2 * qn - om[n] * qp[n] - a[n] * qn - g[n] * wTerm + kap * fingerF * fw[n] - nl * kn2[n] * qn;
165 Ap[n] = A;
166 sGq += g[n] * (2 * qn - qp[n]);
167 }
168 if (this.damp) {
169 const e = this.e;
170 for (let n = 0; n < N; n++) { sEA += e[n] * Ap[n] * inv[n]; usPrev += e[n] * qp[n]; }
171 this.aD = (-this.rho * (sEA - usPrev)) / (1 + this.rho * kap * this.sEE);
172 const ka = kap * this.aD;
173 for (let n = 0; n < N; n++) Ap[n] += ka * e[n];
174 }
175 for (let n = 0; n < N; n++) alpha += g[n] * inv[n] * Ap[n];
176 const fDir = fingerF * this.xfOverL;
177 return this.muL2 * (alpha - sGq) + this.muL3 * wTerm + k2 * (((this.T + dT) * this.w) / this.L - fDir);
178 }
180 post(wNext: number): void {
181 const { N, Ap, G2, inv, qn } = this;
182 for (let n = 0; n < N; n++) qn[n] = (Ap[n] - G2[n] * wNext) * inv[n];
183 const t = this.qp; this.qp = this.q; this.q = this.qn; this.qn = t;
184 this.wPrev = this.w; this.w = wNext;
185 }
187 uFinger(): number {
188 let s = 0;
189 for (let n = 0; n < this.N; n++) s += this.fw[n] * this.q[n];
190 return s + this.w * this.xfOverL;
191 }
192 uFingerPrev(): number {
193 let s = 0;
194 for (let n = 0; n < this.N; n++) s += this.fw[n] * this.qp[n];
195 return s + this.wPrev * this.xfOverL;
196 }
197 e2(): number {
198 let s = 0;
199 for (let n = 0; n < this.N; n++) s += this.kn2[n] * this.q[n] * this.q[n];
200 return (s * this.L) / 2 + (this.w * this.w) / this.L;
201 }
204class FDPol implements StringPol {
205 N: number; h: number;
206 u: Float64Array; up: Float64Array; un: Float64Array;
207 m: number;
208 w = 0; wPrev = 0;
209 private c2: number; private kap2: number; private s1: number;
210 private k: number; private mu: number; private T: number; private EI: number;
211 private den: Float64Array; private pc: Float64Array; private fwt: Float64Array; private fIdx: Int32Array;
212 private fIdxN: number;
214 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) {
215 this.k = k; this.mu = sc.mu; this.T = sc.T; this.EI = sc.EI;
216 const c2 = sc.T / sc.mu, kap2 = sc.EI / sc.mu;
217 const a = c2 * k * k + 4 * sig.s1 * k;
218 const hmin = Math.sqrt((a + Math.sqrt(a * a + 16 * kap2 * k * k)) / 2);
219 const N = Math.max(8, Math.floor((L * courant) / hmin));
220 const h = L / N;
221 this.N = N; this.h = h; this.c2 = c2; this.kap2 = kap2; this.s1 = sig.s1;
222 this.u = new Float64Array(N + 1); this.up = new Float64Array(N + 1); this.un = new Float64Array(N + 1);
223 this.den = new Float64Array(N + 1); this.pc = new Float64Array(N + 1);
224 for (let l = 0; l <= N; l++) { this.den[l] = 1 + sig.s0 * k; this.pc[l] = 1 - sig.s0 * k; }
225 if (stop && stop.r > 0) {
226 const l = Math.max(1, Math.min(N - 1, Math.round(stop.x / h)));
227 const extra = (stop.r * k) / (2 * sc.mu * h);
228 this.den[l] += extra; this.pc[l] -= extra;
229 }
230 // finger weights onto nodes (linear interpolation of each pad point)
231 const wt = new Float64Array(N + 1);
232 if (finger) {
233 for (let j = 0; j < finger.x.length; j++) {
234 const xl = finger.x[j] / h, l0 = Math.floor(xl), fr = xl - l0;
235 if (l0 >= 1 && l0 <= N - 1) wt[l0] += finger.wt[j] * (1 - fr);
236 if (l0 + 1 >= 1 && l0 + 1 <= N - 1) wt[l0 + 1] += finger.wt[j] * fr;
237 }
238 }
239 const idx: number[] = [];
240 for (let l = 0; l <= N; l++) if (wt[l] !== 0) idx.push(l);
241 this.fIdx = Int32Array.from(idx); this.fIdxN = idx.length;
242 this.fwt = wt;
243 this.m = (sc.mu * h) / 2;
244 }
246 private fF = 0; private dT = 0;
247 pre(fingerF: number, dT: number): number {
248 this.fF = fingerF; this.dT = dT;
249 const { u, h, N } = this;
250 const k2 = this.k * this.k;
251 const uxxx = (-u[N - 2] + 2 * u[N - 1] - this.w) / (h * h * h);
252 return k2 * (((this.T + dT) * (this.w - u[N - 1])) / h - this.EI * uxxx) + this.m * (-2 * this.w + this.wPrev);
253 }
255 post(wNext: number): void {
256 const { u, up, un, N, h, den, pc } = this;
257 const k = this.k, k2 = k * k;
258 const lam2 = ((this.c2 + this.dT / this.mu) * k2) / (h * h);
259 const mu2 = (this.kap2 * k2) / (h * h * h * h);
260 const sx = (2 * this.s1 * k) / (h * h);
261 const fsc = (k2 * this.fF) / (this.mu * h);
262 const w = this.w;
263 // ghost values: u[-1] = -u[1], u[N+1] = 2 w - u[N-1]; same for the previous step
264 const at = (arr: Float64Array, l: number, wv: number) => (l < 0 ? -arr[-l] : l > N ? 2 * wv - arr[2 * N - l] : arr[l]);
265 for (let l = 1; l < N; l++) {
266 const ul = u[l];
267 const dxx = u[l + 1] - 2 * ul + u[l - 1];
268 const dxxp = up[l + 1] - 2 * up[l] + up[l - 1];
269 let d4: number;
270 if (l >= 2 && l <= N - 2) d4 = u[l + 2] - 4 * u[l + 1] + 6 * ul - 4 * u[l - 1] + u[l - 2];
271 else d4 = at(u, l + 2, w) - 4 * u[l + 1] + 6 * ul - 4 * u[l - 1] + at(u, l - 2, w);
272 un[l] = (2 * ul - pc[l] * up[l] + lam2 * dxx - mu2 * d4 + sx * (dxx - dxxp) + fsc * this.fwt[l]) / den[l];
273 }
274 un[0] = 0; un[N] = wNext;
275 this.up = u; this.u = un; this.un = up;
276 this.wPrev = this.w; this.w = wNext;
277 }
279 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; }
280 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; }
281 e2(): number {
282 let s = 0;
283 for (let l = 0; l < this.N; l++) { const d = this.u[l + 1] - this.u[l]; s += d * d; }
284 return s / this.h;
285 }
288/**
289 * Bilbao loss parameters sigma0, sigma1 (decay sigma0 + sigma1 beta^2) fitted to the Valette
290 * damping of the string's partials from f1 up to fTop, minimising the relative error. The FD loss
291 * grows as f^2 at high frequency while Valette's floor makes it ~ f, so this is a compromise; the
292 * modal string reproduces Valette exactly.
293 */
294function fitFDLoss(p: Params, sc: StringConst, f1: number, fTop: number): { s0: number; s1: number } {
295 const c2 = sc.T / sc.mu, kap2 = sc.EI / sc.mu;
296 const beta2 = (f: number) => { const w = 2 * Math.PI * f; return (-c2 + Math.sqrt(c2 * c2 + 4 * kap2 * w * w)) / (2 * kap2); };
297 // 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)
298 let a11 = 0, a12 = 0, a22 = 0, r1 = 0, r2 = 0;
299 for (let n = 1; n * f1 <= fTop; n++) {
300 const f = n * f1, sg = Math.PI * f * valetteQinv(p, sc, f), b = beta2(f), wn = 1 / n;
301 const u = 1 / sg, v = b / sg;
302 a11 += wn * u * u; a12 += wn * u * v; a22 += wn * v * v; r1 += wn * u; r2 += wn * v;
303 }
304 const det = a11 * a22 - a12 * a12;
305 let s0 = (r1 * a22 - r2 * a12) / det, s1 = (a11 * r2 - a12 * r1) / det;
306 if (s1 < 0) { s1 = 0; s0 = r1 / a11; }
307 if (s0 < 0) { s0 = 0; s1 = r2 / a22; }
308 return { s0, s1 };
311export function renderNote(p: Params, body: BodyModel, o: RenderOpts): RenderResult {
312 const t0 = performance.now();
313 const fs = p.engine.sampleRate;
314 const os = Math.max(1, Math.round(p.engine.oversample));
315 const fsi = fs * os, k = 1 / fsi;
316 const fmaxStr = Math.min(p.engine.stringFmax, 0.3 * fsi);
317 const fing = fingering(p, o.note);
318 const { force: fRel, slip } = pluckForVelocity(p, o.velocity);
319 const duration = o.duration ?? p.engine.duration;
320 const preRoll = o.preRoll ?? 0.004;
322 // ---- body
323 const bm = thinModes(body.modes.filter((m) => m.f > 0 && m.f < 0.45 * fsi), p.engine.bodyOverlap);
324 const M = bm.length;
325 const bA = new Float64Array(M), bOm = new Float64Array(M), bInv = new Float64Array(M);
326 const rr = new Float64Array(M), ri = new Float64Array(M);
327 for (let m = 0; m < M; m++) {
328 const wm = 2 * Math.PI * bm[m].f;
329 const s = Math.sin((wm * k) / 2);
330 const sk = bm[m].zeta * wm * k;
331 bA[m] = 4 * s * s; bOm[m] = 1 - sk; bInv[m] = 1 / (1 + sk);
332 rr[m] = bm[m].radRe / (k * k);
333 ri[m] = (bm[m].radIm * wm) / (2 * k);
334 }
336 // ---- tuning by ear (see tuneByEar): tension of the open strings, length of the stopped note
337 const L0 = p.strings.scaleLength;
338 const tuning = o.tuning ?? (p.engine.intonate ? tuneByEar(p, body, fing) : null);
339 const tensionScale = tuning ? tuning.tensionScale : [1, 1, 1, 1];
340 if (tuning && fing.stopped) fing.length *= tuning.lengthScale;
342 // ---- strings: the played one, and the other open strings if sympathetic
343 const finger = padPoints(fing.length - p.pluck.position, p.pluck.padWidth, fing.length);
344 // keep the pluck point on the string for short (high) notes: at most 40 % of the length from the bridge
345 if (p.pluck.position > 0.4 * fing.length) {
346 const pp = padPoints(0.6 * fing.length, Math.min(p.pluck.padWidth, 0.1 * fing.length), fing.length);
347 finger.x = pp.x; finger.wt = pp.wt;
348 }
349 const pols: StringPol[] = [];
350 const polString: number[] = [];
351 const polDir: number[] = []; // 0 = y (vertical), 1 = z (lateral)
352 const active: number[] = [fing.string];
353 if (p.engine.sympathetic) for (let i = 0; i < N_STRINGS; i++) if (i !== fing.string) active.push(i);
354 const strModeCounts: number[] = [];
355 const muteSigma = 25 * p.engine.sympatheticMute;
356 const scs: StringConst[] = [];
357 const Ls: number[] = [];
358 for (const si of active) {
359 const sc0 = stringConst(p, si);
360 const sc: StringConst = { ...sc0, T: sc0.T * tensionScale[si] };
361 const played = si === fing.string;
362 const L = played ? fing.length : L0;
363 const stop = played && fing.stopped && p.stop.damping > 0 ? { x: p.stop.offset, r: p.stop.damping } : null;
364 const extra = played ? 0 : muteSigma;
365 scs[si] = sc; Ls[si] = L;
366 for (let dir = 0; dir < 2; dir++) {
367 if (p.engine.stringModel === "fd") {
368 const f1 = Math.sqrt(sc.T / sc.mu) / (2 * L);
369 const sig = fitFDLoss(p, sc, f1, 1500);
370 sig.s0 += extra;
371 pols.push(new FDPol(sc, L, k, p.engine.fdCourant, sig, played ? finger : null, stop));
372 if (dir === 0) strModeCounts.push((pols[pols.length - 1] as FDPol).N);
373 } else {
374 const modes = stringModes(p, sc, L, played ? fmaxStr : Math.min(fmaxStr, 5000), extra);
375 pols.push(new ModalPol(sc, L, modes, k, played ? finger : null, stop));
376 if (dir === 0) strModeCounts.push(modes.w.length);
377 }
378 polString.push(si); polDir.push(dir);
379 }
380 }
381 const C = pols.length;
382 // notch mode shapes per string-polarisation, stored mode-major: BT[m*C + c]
383 const BT = new Float64Array(C * M);
384 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]];
385 // Phi_dc = sum_m B_dm B_cm inv_m ; system (I + Phi diag(m)) w+ = SB - Phi P
386 const Phi = new Float64Array(C * C);
387 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];
388 const Ms = new Float64Array(C * C);
389 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;
390 const Minv = invert(Ms, C);
392 // ---- finger
393 const ang = (p.pluck.angleDeg * Math.PI) / 180;
394 const dirY = -Math.sin(ang), dirZ = Math.cos(ang); // pull: sideways, slightly into the board (-y)
395 const iy = 0, iz = 1; // the played string is first in `active`, so its pols are 0 (y) and 1 (z)
396 let phase: 0 | 1 | 2 = 0; // 0 stick, 1 slip, 2 free
397 let tRel = -1, relFy = 0, relFz = 0;
398 const maxStick = 0.25;
400 const eta = new Float64Array(M), etaP = new Float64Array(M), etaN = new Float64Array(M);
401 const Bm = new Float64Array(M);
402 const P = new Float64Array(C), SB = new Float64Array(C), rhs = new Float64Array(C), wN = new Float64Array(C), fc = new Float64Array(C);
403 // pickup: a bridge piezo reading the strings' force on the bridge (vertical + a share of lateral),
404 // in Pa-equivalent (pickupPaPerN per newton) so it mixes with the microphone at comparable level
405 const pickY = 1, pickZ = p.output.pickupLateral;
406 const pickScale = p.output.pickupPaPerN / (k * k);
407 const preSteps = Math.round(preRoll * fsi);
408 const postSteps = Math.round(duration * fsi);
409 const maxSteps = Math.round(maxStick * fsi) + postSteps + 1;
410 const ring = new Float64Array(preSteps + 1), ring2 = new Float64Array(preSteps + 1);
411 let ringPos = 0;
412 const out = new Float64Array(preSteps + postSteps), out2 = new Float64Array(preSteps + postSteps);
413 let outN = 0;
414 let relStep = -1;
415 const nonlinear = p.engine.nonlinear;
416 const dTs = new Float64Array(N_STRINGS);
417 let cur = eta, prev = etaP, next = etaN;
418 let lastProg = 0;
420 for (let step = 0; step < maxSteps; step++) {
421 const t = step * k;
422 // tension modulation per active string
423 if (nonlinear) {
424 for (let c = 0; c < C; c += 2) {
425 const si = polString[c];
426 dTs[si] = (scs[si].EA / (2 * Ls[si])) * (pols[c].e2() + pols[c + 1].e2());
427 }
428 }
429 // finger force
430 let Fy = 0, Fz = 0;
431 if (phase === 0) {
432 const X = p.pluck.pullSpeed * t;
433 const uy = pols[iy].uFinger(), uz = pols[iz].uFinger();
434 const vy = (uy - pols[iy].uFingerPrev()) / k, vz = (uz - pols[iz].uFingerPrev()) / k;
435 Fy = p.pluck.padK * (X * dirY - uy) + p.pluck.padR * (p.pluck.pullSpeed * dirY - vy);
436 Fz = p.pluck.padK * (X * dirZ - uz) + p.pluck.padR * (p.pluck.pullSpeed * dirZ - vz);
437 const F = Math.hypot(Fy, Fz);
438 if (F >= fRel || t >= maxStick) {
439 phase = 1; tRel = t; relStep = step;
440 const s = fRel / Math.max(F, 1e-12);
441 relFy = Fy * s; relFz = Fz * s; Fy = relFy; Fz = relFz;
442 }
443 } else if (phase === 1) {
444 const x = (t - tRel) / slip;
445 if (x >= 1) { phase = 2; } else { const cc = Math.cos((Math.PI / 2) * x); Fy = relFy * cc * cc; Fz = relFz * cc * cc; }
446 }
447 // strings: known parts
448 for (let c = 0; c < C; c++) {
449 const ff = c === iy ? Fy : c === iz ? Fz : 0;
450 P[c] = pols[c].pre(ff, nonlinear ? dTs[polString[c]] : 0);
451 }
452 // body: known parts, and SB_d = sum_m B_dm Bm_m inv_m
453 SB.fill(0);
454 for (let m = 0; m < M; m++) {
455 const b = 2 * cur[m] - bOm[m] * prev[m] - bA[m] * cur[m];
456 Bm[m] = b;
457 const bi = b * bInv[m], o = m * C;
458 for (let d = 0; d < C; d++) SB[d] += BT[o + d] * bi;
459 }
460 for (let d = 0; d < C; d++) {
461 let s = SB[d];
462 for (let c = 0; c < C; c++) s -= Phi[d * C + c] * P[c];
463 rhs[d] = s;
464 }
465 for (let d = 0; d < C; d++) {
466 let s = 0;
467 for (let c = 0; c < C; c++) s += Minv[d * C + c] * rhs[c];
468 wN[d] = s;
469 }
470 // string forces on the bridge (k^2-scaled, sign: bracket = -k^2 F), body update, output
471 let pick = 0;
472 for (let c = 0; c < C; c++) {
473 fc[c] = P[c] + pols[c].m * wN[c];
474 pick += fc[c] * (polDir[c] === 0 ? pickY : pickZ);
475 }
476 let pr = 0;
477 for (let m = 0; m < M; m++) {
478 let v = Bm[m];
479 const o = m * C;
480 for (let c = 0; c < C; c++) v -= BT[o + c] * fc[c];
481 const en = v * bInv[m];
482 next[m] = en;
483 pr += rr[m] * (en - 2 * cur[m] + prev[m]) - ri[m] * (en - prev[m]);
484 }
485 const pk = -pick * pickScale;
486 for (let c = 0; c < C; c++) pols[c].post(wN[c]);
487 const tmp = prev; prev = cur; cur = next; next = tmp;
489 // output: keep a ring of the last preSteps samples until the release, then record
490 if (relStep < 0) { ring[ringPos] = pr; ring2[ringPos] = pk; ringPos = (ringPos + 1) % (preSteps + 1); }
491 else {
492 if (outN === 0) {
493 // flush the pre-roll (oldest first)
494 for (let j = 0; j < preSteps; j++) { const q = (ringPos + 1 + j) % (preSteps + 1); out[outN] = ring[q]; out2[outN++] = ring2[q]; }
495 }
496 out[outN] = pr; out2[outN++] = pk;
497 if (outN >= out.length) break;
498 }
499 if (o.onProgress && relStep >= 0) {
500 const fr = outN / out.length;
501 if (fr - lastProg > 0.02) { lastProg = fr; o.onProgress(fr); }
502 }
503 }
504 const mic = Float32Array.from(decimate(out.subarray(0, outN), os));
505 const pickup = Float32Array.from(decimate(out2.subarray(0, outN), os));
506 return {
507 audio: mixOutput(p, mic, pickup),
508 mic,
509 pickup,
510 sampleRate: fs,
511 fingering: fing,
512 releaseForce: fRel,
513 slipTime: slip,
514 stickTime: tRel,
515 elapsed: (performance.now() - t0) / 1000,
516 modeCounts: { strings: strModeCounts, body: M },
517 };
520/**
521 * Tuning by ear. The bridge gives under the string (spring-like below the body resonances, so the
522 * pitch goes flat; strongly near them), so a player tunes the open strings and places the stopping
523 * finger by ear. Here: short quiet calibration renders (linear, otherwise as the real render,
524 * including the sympathetic strings, which load the bridge too) measure the first partial; the open
525 * strings' tensions (all four, two passes) and then the stopped length are corrected. Cached per body
526 * and string set-up.
527 */
528const tuneCache = new Map<string, number | number[]>();
529export function tuneByEar(p: Params, body: BodyModel, fing: Fingering): Tuning {
530 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)}`;
531 const q = cloneForTuning(p);
532 const base = JSON.stringify([bodyKey, q.engine, q.strings, q.pluck.angleDeg, q.pluck.position, q.stop, q.fe.stringSpacing]);
533 const measure = (note: number, tuning: Tuning) => {
534 const r = renderNote(q, body, { note, velocity: 40, duration: 1.1, tuning });
535 return bandFrequency(r.audio, r.sampleRate, midiToHz(note), 0.25, 0.85);
536 };
537 // open strings: all four together (they load the bridge for each other), two passes
538 const openKey = `${base}|open`;
539 let tensionScale = tuneCache.get(openKey) as number[] | undefined;
540 if (!tensionScale) {
541 tensionScale = [1, 1, 1, 1];
542 for (let it = 0; it < 2; it++) {
543 for (let si = 0; si < N_STRINGS; si++) {
544 const note = STRING_OPEN_MIDI[si];
545 const f = measure(note, { tensionScale: [...tensionScale], lengthScale: 1 });
546 if (f > 0) tensionScale[si] *= Math.pow(midiToHz(note) / f, 2);
547 }
548 }
549 tuneCache.set(openKey, tensionScale);
550 }
551 let lengthScale = 1;
552 if (fing.stopped) {
553 const note = STRING_OPEN_MIDI[fing.string] + fing.shift;
554 const key = `${base}|note${note}`;
555 const cached = tuneCache.get(key) as number | undefined;
556 if (cached !== undefined) lengthScale = cached;
557 else {
558 for (let it = 0; it < 2; it++) {
559 const f = measure(note, { tensionScale, lengthScale });
560 if (!(f > 0)) break;
561 lengthScale *= f / midiToHz(note);
562 }
563 tuneCache.set(key, lengthScale);
564 }
565 }
566 return { tensionScale, lengthScale };
569function cloneForTuning(p: Params): Params {
570 const q = JSON.parse(JSON.stringify(p)) as Params;
571 q.engine.nonlinear = false; q.engine.oversample = 1; q.engine.intonate = false;
572 // only the first partial matters here: fewer string modes and body modes
573 q.engine.stringFmax = 2500; q.engine.bodyOverlap = Math.max(1, q.engine.bodyOverlap / 2);
574 return q;
577/**
578 * Where the body's modal overlap (half-power bandwidth x modal density) is high, individual modes
579 * cannot be told apart, so the engine can use fewer of them: in 1/6-octave bands, keep every k-th
580 * mode with k = floor(overlap / target), and scale its notch coupling by sqrt(k). That keeps the
581 * band's mean bridge admittance (sum of b^2) and radiated power (sum of b^2 rad^2), and leaves the
582 * overlap at about `target`, so the response stays smooth. target <= 0 keeps every mode.
583 */
584export function thinModes(modes: BodyMode[], target: number): BodyMode[] {
585 if (!(target > 0)) return modes;
586 const sorted = [...modes].sort((a, b) => a.f - b.f);
587 const out: BodyMode[] = [];
588 let i = 0;
589 while (i < sorted.length) {
590 const f0 = sorted[i].f, f1 = f0 * Math.pow(2, 1 / 6);
591 let j = i;
592 while (j < sorted.length && sorted[j].f < f1) j++;
593 const band = sorted.slice(i, j);
594 const fc = Math.sqrt(f0 * f1), dens = band.length / (f1 - f0);
595 const meanZeta = band.reduce((s, m) => s + m.zeta, 0) / band.length;
596 const overlap = dens * 2 * meanZeta * fc;
597 const k = Math.max(1, Math.floor(overlap / target));
598 if (k === 1 || band.length < 2 * k) out.push(...band);
599 else {
600 const g = Math.sqrt(k);
601 for (let q = Math.floor(k / 2); q < band.length; q += k) {
602 const m = band[q];
603 out.push({ ...m, by: m.by.map((v) => v * g), bz: m.bz.map((v) => v * g) });
604 }
605 }
606 i = j;
607 }
608 return out;
611/** The output: micMix * mic + pickupMix * pickup (with its trim), times the output gain. */
612export function mixOutput(p: Params, mic: Float32Array, pickup: Float32Array): Float32Array {
613 const g = Math.pow(10, p.output.gainDb / 20);
614 const a = p.output.micMix * g, b = p.output.pickupMix * Math.pow(10, p.output.pickupGainDb / 20) * g;
615 const y = new Float32Array(mic.length);
616 for (let i = 0; i < y.length; i++) y[i] = a * mic[i] + b * pickup[i];
617 return y;
620/** Small dense matrix inverse (Gauss-Jordan with partial pivoting). */
621function invert(A: Float64Array, n: number): Float64Array {
622 const a = Float64Array.from(A);
623 const inv = new Float64Array(n * n);
624 for (let i = 0; i < n; i++) inv[i * n + i] = 1;
625 for (let col = 0; col < n; col++) {
626 let piv = col;
627 for (let r = col + 1; r < n; r++) if (Math.abs(a[r * n + col]) > Math.abs(a[piv * n + col])) piv = r;
628 if (piv !== col) for (let j = 0; j < n; j++) {
629 [a[col * n + j], a[piv * n + j]] = [a[piv * n + j], a[col * n + j]];
630 [inv[col * n + j], inv[piv * n + j]] = [inv[piv * n + j], inv[col * n + j]];
631 }
632 const d = a[col * n + col];
633 for (let j = 0; j < n; j++) { a[col * n + j] /= d; inv[col * n + j] /= d; }
634 for (let r = 0; r < n; r++) if (r !== col) {
635 const f = a[r * n + col];
636 if (f === 0) continue;
637 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]; }
638 }
639 }
640 return inv;
↑↓ move↵openescclose