// The time-domain engine: strings (two polarisations each) coupled at the bridge to the body modes, // plucked by a finger, stopped by a finger, heard through the body's radiation. // // String, modal form. A string of vibrating length L (stop/nut at x = 0, bridge at x = L) whose // bridge end moves with the bridge notch, w(t), in each polarisation: // u(x,t) = w(t) x/L + sum_n q_n(t) sin(n pi x / L) // From the Lagrangian (kinetic energy of string and body, tension + bending + body potential): // 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) // 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 ] // with w_c = sum_m B_cm eta_m (c = string x polarisation, B = the body's notch mode shapes by/bz). // The w'' mass coupling is solved exactly each step: everything is linear in the unknown notch // displacements w+ (one per string-polarisation, at most 8), and the matrix of that small system is // constant, so it is inverted once. Each oscillator uses a central-difference update with its // stiffness replaced by (2/k sin(w k/2))^2, which makes the discrete frequency exact and the scheme // stable for every mode below Nyquist. Per-mode damping s_n is Valette's (air + viscoelastic + floor). // // Geometric nonlinearity (Kirchhoff-Carrier): the tension rises by EA/(2L) int u_x^2 dx, summed // over both polarisations, explicit in time. // // Plucking finger: during the stick phase a pad (spring padK + dashpot padR, spread over padWidth) // is dragged at pullSpeed in the pull direction; when the contact force reaches the release force // for the velocity, the string slides off the pad and the force falls to zero as cos^2 over the // slip time. Stopping finger: a dashpot near the stop, implicit (it is very stiff in modal terms). // // String, FD form (engine.stringModel = "fd"): the same string as a finite-difference stiff string // with Bilbao's frequency-dependent loss (sigma0 + sigma1 beta^2, fitted to the Valette damping at // the fundamental and at 2 kHz), the bridge end node moving with the notch; its force on the bridge // (tension and bending shear at the end, plus half a cell of mass) enters the same notch solve. // // Output: p(t) = sum_m radRe_m eta_m'' - radIm_m W_m eta_m' (complex radiation at each mode's // frequency), computed at the internal rate and decimated. import type { Params } from "./params.ts"; import type { BodyMode, BodyModel } from "./types.ts"; import { N_STRINGS, STRING_OPEN_MIDI } from "./types.ts"; import { fingering, midiToHz, pluckForVelocity, stringConst, stringModes, valetteQinv, type Fingering, type StringConst } from "./strings.ts"; import { bandFrequency, decimate } from "./dsp.ts"; export interface RenderOpts { note: number; velocity: number; /** seconds of sound after the release (default p.engine.duration) */ duration?: number; /** seconds kept before the release (default 0.004) */ preRoll?: number; onProgress?: (frac: number) => void; /** explicit tuning (open-string tension factors, stopped-length factor); default: tuneByEar */ tuning?: Tuning; /** record the state for visualisation (see Recording) */ record?: RecordSpec; } /** * What to record for the physics visualisation. Time t is simulation time from the start of the * pull (t = 0), not the audio time. "Dense" frames are taken every internal step inside * [denseFrom, denseTo] (denseTo = Infinity: until denseAfterRelease after the release), "sparse" * frames every sparseDt elsewhere. Scalar channels are recorded at every step. */ export interface RecordSpec { denseFrom: number; denseTo: number; denseAfterRelease: number; maxDense: number; sparseDt: number; /** points along the played string and along each sympathetic string */ stringPoints: number; sympPoints: number; /** body modes with index < shapeModes have mesh shapes: their coordinates go into the frames */ shapeModes: number; /** per body mode: share of the energy in the air (cavity + f-hole plugs); default 0 (A0: 1) */ airFrac?: ArrayLike; } export const CHANNELS = ["fingerFy", "fingerFz", "bridgeFy", "bridgeFz", "eString", "eSymp", "eBody", "eAir", "mic", "pickup"] as const; export type Channel = (typeof CHANNELS)[number]; export interface Recording { /** internal time step, s; channel sample j is at t = j dt */ dt: number; nSteps: number; channels: Record; /** frames: nFrames x frameSize, at frameTimes (s, ascending) */ frameTimes: Float64Array; frames: Float32Array; frameSize: number; /** per recorded string: which string, vibrating length, points, offset of its y block (z block follows) */ strings: { string: number; length: number; points: number; offset: number; played: boolean }[]; /** offset of the 8 notch displacements (y of strings 0..3, then z of strings 0..3), m */ notchOffset: number; /** offset and body-mode indices of the recorded body coordinates (already scaled by any mode thinning) */ etaOffset: number; etaModes: Int32Array; /** the dense window actually recorded, s */ dense: [number, number]; tRelease: number; slipTime: number; releaseForce: number; /** pull direction (y = away from the fingerboard, z = across) and speed m/s, pluck point (m from the stop) */ pull: { dirY: number; dirZ: number; speed: number; x: number; padWidth: number }; /** audio sample 0 is at this simulation time */ audioT0: number; } export interface Tuning { tensionScale: number[]; lengthScale: number } export interface RenderResult { /** the output mix (mixOutput of mic and pickup), at p.engine.sampleRate */ audio: Float32Array; /** radiated pressure at the listener, Pa */ mic: Float32Array; /** bridge pickup, Pa-equivalent (pickupPaPerN per N of string force on the bridge) */ pickup: Float32Array; sampleRate: number; fingering: Fingering; releaseForce: number; slipTime: number; /** time from the start of the pull to the release, s */ stickTime: number; /** cpu time, s */ elapsed: number; modeCounts: { strings: number[]; body: number }; recording?: Recording; } /** One string-polarisation's contribution to the notch solve, common to modal and FD strings. */ interface StringPol { /** before the solve: given the finger force on this polarisation and the tension increase, compute P (k^2-scaled bracket, known part) */ pre(fingerF: number, dT: number): number; /** residual mass at the notch (constant), kg */ readonly m: number; /** after the solve: advance to n+1 given w+ */ post(wNext: number): void; /** displacement at the finger (weighted over the pad), current step and previous step */ uFinger(): number; uFingerPrev(): number; /** int u_x^2 dx (for the tension modulation) */ e2(): number; /** the notch displacement now and one step ago */ w: number; wPrev: number; /** displacement at n evenly spaced points, x_j = j L / (n - 1) (stop to bridge), into out[off..] */ sample(n: number, out: Float32Array, off: number): void; /** vibrational energy (kinetic + potential of the string's own motion), J */ energy(): number; } const HANN_PTS = 9; /** Pad weights: raised cosine over the pad width, normalised to sum 1. */ function padPoints(center: number, width: number, L: number): { x: number[]; wt: number[] } { const x: number[] = [], wt: number[] = []; let s = 0; for (let j = 0; j < HANN_PTS; j++) { const t = (j + 0.5) / HANN_PTS - 0.5; // -0.5..0.5 const v = 0.5 + 0.5 * Math.cos(2 * Math.PI * t); const xx = Math.min(L * 0.999, Math.max(L * 0.001, center + t * width)); x.push(xx); wt.push(v); s += v; } return { x, wt: wt.map((v) => v / s) }; } class ModalPol implements StringPol { N: number; q: Float64Array; qp: Float64Array; qn: Float64Array; a: Float64Array; om: Float64Array; inv: Float64Array; g: Float64Array; G2: Float64Array; fw: Float64Array; e: Float64Array; kn2: Float64Array; Ap: Float64Array; m: number; w = 0; wPrev = 0; private kappa: number; private k2: number; private muL2: number; private muL3: number; private L: number; private mu: number; private T: number; private xfOverL: number; private rho: number; private damp: boolean; private aD = 0; private bD = 0; private sEE: number; private sinTab: Float32Array | null = null; private sinN = 0; constructor(sc: StringConst, L: number, modes: { w: Float64Array; sigma: Float64Array }, k: number, finger: { x: number[]; wt: number[] } | null, stop: { x: number; r: number } | null) { const N = modes.w.length; this.N = N; this.L = L; this.mu = sc.mu; this.T = sc.T; this.q = new Float64Array(N); this.qp = new Float64Array(N); this.qn = new Float64Array(N); this.a = new Float64Array(N); this.om = new Float64Array(N); this.inv = new Float64Array(N); this.g = new Float64Array(N); this.G2 = new Float64Array(N); this.fw = new Float64Array(N); this.e = new Float64Array(N); this.kn2 = new Float64Array(N); this.Ap = new Float64Array(N); this.k2 = k * k; this.kappa = (k * k * 2) / (sc.mu * L); this.muL2 = (sc.mu * L) / 2; this.muL3 = (sc.mu * L) / 3; this.xfOverL = finger ? finger.x.reduce((s, x, j) => s + x * finger.wt[j], 0) / L : 0; this.damp = !!stop && stop.r > 0; this.rho = stop ? stop.r / (2 * k) : 0; for (let n = 0; n < N; n++) { const nn = n + 1; const s = Math.sin((modes.w[n] * k) / 2); this.a[n] = 4 * s * s; // k^2 * wtilde^2 this.om[n] = 1 - modes.sigma[n] * k; this.inv[n] = 1 / (1 + modes.sigma[n] * k); this.g[n] = (2 * (nn % 2 === 1 ? 1 : -1)) / (nn * Math.PI); this.kn2[n] = (nn * Math.PI / L) ** 2; if (finger) { let v = 0; for (let j = 0; j < finger.x.length; j++) v += finger.wt[j] * Math.sin((nn * Math.PI * finger.x[j]) / L); this.fw[n] = v; } if (stop) this.e[n] = Math.sin((nn * Math.PI * stop.x) / L); } // stop damper elimination constants: F_d = aD + bD w+ let sEE = 0, sEG = 0; 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]; } this.sEE = sEE; const den = 1 + this.rho * this.kappa * sEE; this.bD = this.damp ? (this.rho * sEG) / den : 0; // Gamma_n = g_n - kappa e_n bD; beta = sum g inv Gamma let beta = 0; 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]; } this.m = sc.mu * L * (1 / 3 - beta / 2); } pre(fingerF: number, dT: number): number { const { N, q, qp, a, om, g, kn2, fw, Ap, inv } = this; const k2 = this.k2, kap = this.kappa; const wTerm = -2 * this.w + this.wPrev; const nl = (k2 * dT) / this.mu; let alpha = 0, sGq = 0, sEA = 0, usPrev = 0; for (let n = 0; n < N; n++) { const qn = q[n]; const A = 2 * qn - om[n] * qp[n] - a[n] * qn - g[n] * wTerm + kap * fingerF * fw[n] - nl * kn2[n] * qn; Ap[n] = A; sGq += g[n] * (2 * qn - qp[n]); } if (this.damp) { const e = this.e; for (let n = 0; n < N; n++) { sEA += e[n] * Ap[n] * inv[n]; usPrev += e[n] * qp[n]; } this.aD = (-this.rho * (sEA - usPrev)) / (1 + this.rho * kap * this.sEE); const ka = kap * this.aD; for (let n = 0; n < N; n++) Ap[n] += ka * e[n]; } for (let n = 0; n < N; n++) alpha += g[n] * inv[n] * Ap[n]; const fDir = fingerF * this.xfOverL; return this.muL2 * (alpha - sGq) + this.muL3 * wTerm + k2 * (((this.T + dT) * this.w) / this.L - fDir); } post(wNext: number): void { const { N, Ap, G2, inv, qn } = this; for (let n = 0; n < N; n++) qn[n] = (Ap[n] - G2[n] * wNext) * inv[n]; const t = this.qp; this.qp = this.q; this.q = this.qn; this.qn = t; this.wPrev = this.w; this.w = wNext; } uFinger(): number { let s = 0; for (let n = 0; n < this.N; n++) s += this.fw[n] * this.q[n]; return s + this.w * this.xfOverL; } uFingerPrev(): number { let s = 0; for (let n = 0; n < this.N; n++) s += this.fw[n] * this.qp[n]; return s + this.wPrev * this.xfOverL; } e2(): number { let s = 0; for (let n = 0; n < this.N; n++) s += this.kn2[n] * this.q[n] * this.q[n]; return (s * this.L) / 2 + (this.w * this.w) / this.L; } sample(np: number, out: Float32Array, off: number): void { const N = this.N; if (!this.sinTab || this.sinN !== np) { this.sinN = np; this.sinTab = new Float32Array(N * np); 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)); } const tab = this.sinTab, q = this.q; for (let j = 0; j < np; j++) out[off + j] = (this.w * j) / (np - 1); for (let n = 0; n < N; n++) { const qn = q[n]; if (qn === 0) continue; const o = n * np; for (let j = 1; j < np - 1; j++) out[off + j] += qn * tab[o + j]; } } energy(): number { const { N, q, qp, a } = this; let s = 0; for (let n = 0; n < N; n++) { const v = q[n] - qp[n]; s += v * v + a[n] * q[n] * q[n]; } return ((this.mu * this.L) / 4) * s / this.k2; } } class FDPol implements StringPol { N: number; h: number; u: Float64Array; up: Float64Array; un: Float64Array; m: number; w = 0; wPrev = 0; private c2: number; private kap2: number; private s1: number; private k: number; private mu: number; private T: number; private EI: number; private den: Float64Array; private pc: Float64Array; private fwt: Float64Array; private fIdx: Int32Array; private fIdxN: number; 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) { this.k = k; this.mu = sc.mu; this.T = sc.T; this.EI = sc.EI; const c2 = sc.T / sc.mu, kap2 = sc.EI / sc.mu; const a = c2 * k * k + 4 * sig.s1 * k; const hmin = Math.sqrt((a + Math.sqrt(a * a + 16 * kap2 * k * k)) / 2); const N = Math.max(8, Math.floor((L * courant) / hmin)); const h = L / N; this.N = N; this.h = h; this.c2 = c2; this.kap2 = kap2; this.s1 = sig.s1; this.u = new Float64Array(N + 1); this.up = new Float64Array(N + 1); this.un = new Float64Array(N + 1); this.den = new Float64Array(N + 1); this.pc = new Float64Array(N + 1); for (let l = 0; l <= N; l++) { this.den[l] = 1 + sig.s0 * k; this.pc[l] = 1 - sig.s0 * k; } if (stop && stop.r > 0) { const l = Math.max(1, Math.min(N - 1, Math.round(stop.x / h))); const extra = (stop.r * k) / (2 * sc.mu * h); this.den[l] += extra; this.pc[l] -= extra; } // finger weights onto nodes (linear interpolation of each pad point) const wt = new Float64Array(N + 1); if (finger) { for (let j = 0; j < finger.x.length; j++) { const xl = finger.x[j] / h, l0 = Math.floor(xl), fr = xl - l0; if (l0 >= 1 && l0 <= N - 1) wt[l0] += finger.wt[j] * (1 - fr); if (l0 + 1 >= 1 && l0 + 1 <= N - 1) wt[l0 + 1] += finger.wt[j] * fr; } } const idx: number[] = []; for (let l = 0; l <= N; l++) if (wt[l] !== 0) idx.push(l); this.fIdx = Int32Array.from(idx); this.fIdxN = idx.length; this.fwt = wt; this.m = (sc.mu * h) / 2; } private fF = 0; private dT = 0; pre(fingerF: number, dT: number): number { this.fF = fingerF; this.dT = dT; const { u, h, N } = this; const k2 = this.k * this.k; const uxxx = (-u[N - 2] + 2 * u[N - 1] - this.w) / (h * h * h); return k2 * (((this.T + dT) * (this.w - u[N - 1])) / h - this.EI * uxxx) + this.m * (-2 * this.w + this.wPrev); } post(wNext: number): void { const { u, up, un, N, h, den, pc } = this; const k = this.k, k2 = k * k; const lam2 = ((this.c2 + this.dT / this.mu) * k2) / (h * h); const mu2 = (this.kap2 * k2) / (h * h * h * h); const sx = (2 * this.s1 * k) / (h * h); const fsc = (k2 * this.fF) / (this.mu * h); const w = this.w; // ghost values: u[-1] = -u[1], u[N+1] = 2 w - u[N-1]; same for the previous step const at = (arr: Float64Array, l: number, wv: number) => (l < 0 ? -arr[-l] : l > N ? 2 * wv - arr[2 * N - l] : arr[l]); for (let l = 1; l < N; l++) { const ul = u[l]; const dxx = u[l + 1] - 2 * ul + u[l - 1]; const dxxp = up[l + 1] - 2 * up[l] + up[l - 1]; let d4: number; if (l >= 2 && l <= N - 2) d4 = u[l + 2] - 4 * u[l + 1] + 6 * ul - 4 * u[l - 1] + u[l - 2]; else d4 = at(u, l + 2, w) - 4 * u[l + 1] + 6 * ul - 4 * u[l - 1] + at(u, l - 2, w); un[l] = (2 * ul - pc[l] * up[l] + lam2 * dxx - mu2 * d4 + sx * (dxx - dxxp) + fsc * this.fwt[l]) / den[l]; } un[0] = 0; un[N] = wNext; this.up = u; this.u = un; this.un = up; this.wPrev = this.w; this.w = wNext; } sample(np: number, out: Float32Array, off: number): void { const { u, N } = this; for (let j = 0; j < np; j++) { const xl = (j * N) / (np - 1), l0 = Math.min(N - 1, Math.floor(xl)), fr = xl - l0; out[off + j] = u[l0] * (1 - fr) + u[l0 + 1] * fr; } } energy(): number { const { u, up, N, h, k } = this; let ke = 0, pe = 0; for (let l = 0; l <= N; l++) { const v = u[l] - up[l]; ke += v * v; } for (let l = 0; l < N; l++) { const d = u[l + 1] - u[l]; pe += d * d; } return (0.5 * this.mu * h * ke) / (k * k) + (0.5 * this.T * pe) / h; } 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; } 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; } e2(): number { let s = 0; for (let l = 0; l < this.N; l++) { const d = this.u[l + 1] - this.u[l]; s += d * d; } return s / this.h; } } /** * Bilbao loss parameters sigma0, sigma1 (decay sigma0 + sigma1 beta^2) fitted to the Valette * damping of the string's partials from f1 up to fTop, minimising the relative error. The FD loss * grows as f^2 at high frequency while Valette's floor makes it ~ f, so this is a compromise; the * modal string reproduces Valette exactly. */ function fitFDLoss(p: Params, sc: StringConst, f1: number, fTop: number): { s0: number; s1: number } { const c2 = sc.T / sc.mu, kap2 = sc.EI / sc.mu; const beta2 = (f: number) => { const w = 2 * Math.PI * f; return (-c2 + Math.sqrt(c2 * c2 + 4 * kap2 * w * w)) / (2 * kap2); }; // 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) let a11 = 0, a12 = 0, a22 = 0, r1 = 0, r2 = 0; for (let n = 1; n * f1 <= fTop; n++) { const f = n * f1, sg = Math.PI * f * valetteQinv(p, sc, f), b = beta2(f), wn = 1 / n; const u = 1 / sg, v = b / sg; a11 += wn * u * u; a12 += wn * u * v; a22 += wn * v * v; r1 += wn * u; r2 += wn * v; } const det = a11 * a22 - a12 * a12; let s0 = (r1 * a22 - r2 * a12) / det, s1 = (a11 * r2 - a12 * r1) / det; if (s1 < 0) { s1 = 0; s0 = r1 / a11; } if (s0 < 0) { s0 = 0; s1 = r2 / a22; } return { s0, s1 }; } export function renderNote(p: Params, body: BodyModel, o: RenderOpts): RenderResult { const t0 = performance.now(); const fs = p.engine.sampleRate; const os = Math.max(1, Math.round(p.engine.oversample)); const fsi = fs * os, k = 1 / fsi; const fmaxStr = Math.min(p.engine.stringFmax, 0.3 * fsi); const fing = fingering(p, o.note); const { force: fRel, slip } = pluckForVelocity(p, o.velocity); const duration = o.duration ?? p.engine.duration; const preRoll = o.preRoll ?? 0.004; // ---- body const srcModes: TaggedMode[] = o.record ? body.modes.map((m, i) => ({ ...m, src: i })) : body.modes; const bm = thinModes(srcModes.filter((m) => m.f > 0 && m.f < 0.45 * fsi), p.engine.bodyOverlap); const M = bm.length; const bA = new Float64Array(M), bOm = new Float64Array(M), bInv = new Float64Array(M); const rr = new Float64Array(M), ri = new Float64Array(M); for (let m = 0; m < M; m++) { const wm = 2 * Math.PI * bm[m].f; const s = Math.sin((wm * k) / 2); const sk = bm[m].zeta * wm * k; bA[m] = 4 * s * s; bOm[m] = 1 - sk; bInv[m] = 1 / (1 + sk); rr[m] = bm[m].radRe / (k * k); ri[m] = (bm[m].radIm * wm) / (2 * k); } // ---- tuning by ear (see tuneByEar): tension of the open strings, length of the stopped note const L0 = p.strings.scaleLength; const tuning = o.tuning ?? (p.engine.intonate ? tuneByEar(p, body, fing) : null); const tensionScale = tuning ? tuning.tensionScale : [1, 1, 1, 1]; if (tuning && fing.stopped) fing.length *= tuning.lengthScale; // ---- strings: the played one, and the other open strings if sympathetic const finger = padPoints(fing.length - p.pluck.position, p.pluck.padWidth, fing.length); // keep the pluck point on the string for short (high) notes: at most 40 % of the length from the bridge if (p.pluck.position > 0.4 * fing.length) { const pp = padPoints(0.6 * fing.length, Math.min(p.pluck.padWidth, 0.1 * fing.length), fing.length); finger.x = pp.x; finger.wt = pp.wt; } const pols: StringPol[] = []; const polString: number[] = []; const polDir: number[] = []; // 0 = y (vertical), 1 = z (lateral) const active: number[] = [fing.string]; if (p.engine.sympathetic) for (let i = 0; i < N_STRINGS; i++) if (i !== fing.string) active.push(i); const strModeCounts: number[] = []; const muteSigma = 25 * p.engine.sympatheticMute; const scs: StringConst[] = []; const Ls: number[] = []; for (const si of active) { const sc0 = stringConst(p, si); const sc: StringConst = { ...sc0, T: sc0.T * tensionScale[si] }; const played = si === fing.string; const L = played ? fing.length : L0; const stop = played && fing.stopped && p.stop.damping > 0 ? { x: p.stop.offset, r: p.stop.damping } : null; const extra = played ? 0 : muteSigma; scs[si] = sc; Ls[si] = L; for (let dir = 0; dir < 2; dir++) { if (p.engine.stringModel === "fd") { const f1 = Math.sqrt(sc.T / sc.mu) / (2 * L); const sig = fitFDLoss(p, sc, f1, 1500); sig.s0 += extra; pols.push(new FDPol(sc, L, k, p.engine.fdCourant, sig, played ? finger : null, stop)); if (dir === 0) strModeCounts.push((pols[pols.length - 1] as FDPol).N); } else { const modes = stringModes(p, sc, L, played ? fmaxStr : Math.min(fmaxStr, 5000), extra); pols.push(new ModalPol(sc, L, modes, k, played ? finger : null, stop)); if (dir === 0) strModeCounts.push(modes.w.length); } polString.push(si); polDir.push(dir); } } const C = pols.length; // notch mode shapes per string-polarisation, stored mode-major: BT[m*C + c] const BT = new Float64Array(C * M); 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]]; // Phi_dc = sum_m B_dm B_cm inv_m ; system (I + Phi diag(m)) w+ = SB - Phi P const Phi = new Float64Array(C * C); 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]; const Ms = new Float64Array(C * C); 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; const Minv = invert(Ms, C); // ---- finger const ang = (p.pluck.angleDeg * Math.PI) / 180; const dirY = -Math.sin(ang), dirZ = Math.cos(ang); // pull: sideways, slightly into the board (-y) const iy = 0, iz = 1; // the played string is first in `active`, so its pols are 0 (y) and 1 (z) let phase: 0 | 1 | 2 = 0; // 0 stick, 1 slip, 2 free let tRel = -1, relFy = 0, relFz = 0; const maxStick = 0.25; const eta = new Float64Array(M), etaP = new Float64Array(M), etaN = new Float64Array(M); const Bm = new Float64Array(M); const P = new Float64Array(C), SB = new Float64Array(C), rhs = new Float64Array(C), wN = new Float64Array(C), fc = new Float64Array(C); // pickup: a bridge piezo reading the strings' force on the bridge (vertical + a share of lateral), // in Pa-equivalent (pickupPaPerN per newton) so it mixes with the microphone at comparable level const pickY = 1, pickZ = p.output.pickupLateral; const pickScale = p.output.pickupPaPerN / (k * k); const preSteps = Math.round(preRoll * fsi); const postSteps = Math.round(duration * fsi); const maxSteps = Math.round(maxStick * fsi) + postSteps + 1; const ring = new Float64Array(preSteps + 1), ring2 = new Float64Array(preSteps + 1); let ringPos = 0; const out = new Float64Array(preSteps + postSteps), out2 = new Float64Array(preSteps + postSteps); let outN = 0; let relStep = -1; const nonlinear = p.engine.nonlinear; const dTs = new Float64Array(N_STRINGS); let cur = eta, prev = etaP, next = etaN; let lastProg = 0; const rec = o.record ? new Recorder(o.record, { k, maxSteps, bm, bA, pols, polDir, active, Ls, played: fing.string }) : null; for (let step = 0; step < maxSteps; step++) { const t = step * k; // tension modulation per active string if (nonlinear) { for (let c = 0; c < C; c += 2) { const si = polString[c]; dTs[si] = (scs[si].EA / (2 * Ls[si])) * (pols[c].e2() + pols[c + 1].e2()); } } // finger force let Fy = 0, Fz = 0; if (phase === 0) { const X = p.pluck.pullSpeed * t; const uy = pols[iy].uFinger(), uz = pols[iz].uFinger(); const vy = (uy - pols[iy].uFingerPrev()) / k, vz = (uz - pols[iz].uFingerPrev()) / k; Fy = p.pluck.padK * (X * dirY - uy) + p.pluck.padR * (p.pluck.pullSpeed * dirY - vy); Fz = p.pluck.padK * (X * dirZ - uz) + p.pluck.padR * (p.pluck.pullSpeed * dirZ - vz); const F = Math.hypot(Fy, Fz); if (F >= fRel || t >= maxStick) { phase = 1; tRel = t; relStep = step; const s = fRel / Math.max(F, 1e-12); relFy = Fy * s; relFz = Fz * s; Fy = relFy; Fz = relFz; } } else if (phase === 1) { const x = (t - tRel) / slip; if (x >= 1) { phase = 2; } else { const cc = Math.cos((Math.PI / 2) * x); Fy = relFy * cc * cc; Fz = relFz * cc * cc; } } // strings: known parts for (let c = 0; c < C; c++) { const ff = c === iy ? Fy : c === iz ? Fz : 0; P[c] = pols[c].pre(ff, nonlinear ? dTs[polString[c]] : 0); } // body: known parts, and SB_d = sum_m B_dm Bm_m inv_m SB.fill(0); for (let m = 0; m < M; m++) { const b = 2 * cur[m] - bOm[m] * prev[m] - bA[m] * cur[m]; Bm[m] = b; const bi = b * bInv[m], o = m * C; for (let d = 0; d < C; d++) SB[d] += BT[o + d] * bi; } for (let d = 0; d < C; d++) { let s = SB[d]; for (let c = 0; c < C; c++) s -= Phi[d * C + c] * P[c]; rhs[d] = s; } for (let d = 0; d < C; d++) { let s = 0; for (let c = 0; c < C; c++) s += Minv[d * C + c] * rhs[c]; wN[d] = s; } // string forces on the bridge (k^2-scaled, sign: bracket = -k^2 F), body update, output let pick = 0; for (let c = 0; c < C; c++) { fc[c] = P[c] + pols[c].m * wN[c]; pick += fc[c] * (polDir[c] === 0 ? pickY : pickZ); } let pr = 0; for (let m = 0; m < M; m++) { let v = Bm[m]; const o = m * C; for (let c = 0; c < C; c++) v -= BT[o + c] * fc[c]; const en = v * bInv[m]; next[m] = en; pr += rr[m] * (en - 2 * cur[m] + prev[m]) - ri[m] * (en - prev[m]); } const pk = -pick * pickScale; for (let c = 0; c < C; c++) pols[c].post(wN[c]); const tmp = prev; prev = cur; cur = next; next = tmp; if (rec) rec.step(step, Fy, Fz, fc, pr, pk, cur, prev, relStep >= 0 ? tRel : -1); // output: keep a ring of the last preSteps samples until the release, then record if (relStep < 0) { ring[ringPos] = pr; ring2[ringPos] = pk; ringPos = (ringPos + 1) % (preSteps + 1); } else { if (outN === 0) { // flush the pre-roll (oldest first) for (let j = 0; j < preSteps; j++) { const q = (ringPos + 1 + j) % (preSteps + 1); out[outN] = ring[q]; out2[outN++] = ring2[q]; } } out[outN] = pr; out2[outN++] = pk; if (outN >= out.length) break; } if (o.onProgress && relStep >= 0) { const fr = outN / out.length; if (fr - lastProg > 0.02) { lastProg = fr; o.onProgress(fr); } } } const mic = Float32Array.from(decimate(out.subarray(0, outN), os)); const pickup = Float32Array.from(decimate(out2.subarray(0, outN), os)); return { audio: mixOutput(p, mic, pickup), mic, pickup, sampleRate: fs, fingering: fing, releaseForce: fRel, slipTime: slip, stickTime: tRel, elapsed: (performance.now() - t0) / 1000, modeCounts: { strings: strModeCounts, body: M }, recording: rec?.finish({ tRelease: tRel, slipTime: slip, releaseForce: fRel, audioT0: relStep >= 0 ? (relStep - preSteps) * k : 0, pull: { dirY, dirZ, speed: p.pluck.pullSpeed, x: finger.x.reduce((s, x, j) => s + x * finger.wt[j], 0), padWidth: p.pluck.padWidth }, }), }; } /** * Tuning by ear. The bridge gives under the string (spring-like below the body resonances, so the * pitch goes flat; strongly near them), so a player tunes the open strings and places the stopping * finger by ear. Here: short quiet calibration renders (linear, otherwise as the real render, * including the sympathetic strings, which load the bridge too) measure the first partial; the open * strings' tensions (all four, two passes) and then the stopped length are corrected. Cached per body * and string set-up. */ const tuneCache = new Map(); export function tuneByEar(p: Params, body: BodyModel, fing: Fingering): Tuning { 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)}`; const q = cloneForTuning(p); const base = JSON.stringify([bodyKey, q.engine, q.strings, q.pluck.angleDeg, q.pluck.position, q.stop, q.fe.stringSpacing]); const measure = (note: number, tuning: Tuning) => { const r = renderNote(q, body, { note, velocity: 40, duration: 1.1, tuning }); return bandFrequency(r.audio, r.sampleRate, midiToHz(note), 0.25, 0.85); }; // open strings: all four together (they load the bridge for each other), two passes const openKey = `${base}|open`; let tensionScale = tuneCache.get(openKey) as number[] | undefined; if (!tensionScale) { tensionScale = [1, 1, 1, 1]; for (let it = 0; it < 2; it++) { for (let si = 0; si < N_STRINGS; si++) { const note = STRING_OPEN_MIDI[si]; const f = measure(note, { tensionScale: [...tensionScale], lengthScale: 1 }); if (f > 0) tensionScale[si] *= Math.pow(midiToHz(note) / f, 2); } } tuneCache.set(openKey, tensionScale); } let lengthScale = 1; if (fing.stopped) { const note = STRING_OPEN_MIDI[fing.string] + fing.shift; const key = `${base}|note${note}`; const cached = tuneCache.get(key) as number | undefined; if (cached !== undefined) lengthScale = cached; else { for (let it = 0; it < 2; it++) { const f = measure(note, { tensionScale, lengthScale }); if (!(f > 0)) break; lengthScale *= f / midiToHz(note); } tuneCache.set(key, lengthScale); } } return { tensionScale, lengthScale }; } function cloneForTuning(p: Params): Params { const q = JSON.parse(JSON.stringify(p)) as Params; q.engine.nonlinear = false; q.engine.oversample = 1; q.engine.intonate = false; // only the first partial matters here: fewer string modes and body modes q.engine.stringFmax = 2500; q.engine.bodyOverlap = Math.max(1, q.engine.bodyOverlap / 2); return q; } /** * Where the body's modal overlap (half-power bandwidth x modal density) is high, individual modes * cannot be told apart, so the engine can use fewer of them: in 1/6-octave bands, keep every k-th * mode with k = floor(overlap / target), and scale its notch coupling by sqrt(k). That keeps the * band's mean bridge admittance (sum of b^2) and radiated power (sum of b^2 rad^2), and leaves the * overlap at about `target`, so the response stays smooth. target <= 0 keeps every mode. */ export function thinModes(modes: T[], target: number): T[] { if (!(target > 0)) return modes; const sorted = [...modes].sort((a, b) => a.f - b.f); const out: T[] = []; let i = 0; while (i < sorted.length) { const f0 = sorted[i].f, f1 = f0 * Math.pow(2, 1 / 6); let j = i; while (j < sorted.length && sorted[j].f < f1) j++; const band = sorted.slice(i, j); const fc = Math.sqrt(f0 * f1), dens = band.length / (f1 - f0); const meanZeta = band.reduce((s, m) => s + m.zeta, 0) / band.length; const overlap = dens * 2 * meanZeta * fc; const k = Math.max(1, Math.floor(overlap / target)); if (k === 1 || band.length < 2 * k) out.push(...band); else { const g = Math.sqrt(k); for (let q = Math.floor(k / 2); q < band.length; q += k) { const m = band[q]; out.push({ ...m, by: m.by.map((v) => v * g), bz: m.bz.map((v) => v * g), thin: g }); } } i = j; } return out; } /** A body mode as the engine uses it: its index in the body model, and the thinning gain. */ type TaggedMode = BodyMode & { src?: number; thin?: number }; interface RecorderEnv { k: number; maxSteps: number; bm: TaggedMode[]; bA: Float64Array; pols: StringPol[]; polDir: number[]; active: number[]; Ls: number[]; played: number } /** Collects the frames and channels of a Recording during renderNote. */ class Recorder { private ch: Record; private frames: Float32Array[] = []; private times: number[] = []; private nSteps = 0; private nDense = 0; private denseStart = -1; private denseLast = -1; private nextSparse = 0; private readonly F: number; private readonly strings: Recording["strings"] = []; private readonly notchOffset: number; private readonly etaOffset: number; private readonly etaIdx: Int32Array; // engine mode index of each recorded coordinate private readonly etaModes: Int32Array; private readonly etaGain: Float32Array; private readonly BY: Float64Array; private readonly BZ: Float64Array; // M x 4 private readonly air: Float64Array; // per engine mode private readonly spec: RecordSpec; private readonly e: RecorderEnv; constructor(spec: RecordSpec, e: RecorderEnv) { this.spec = spec; this.e = e; this.ch = Object.fromEntries(CHANNELS.map((c) => [c, new Float32Array(e.maxSteps)])) as Record; let off = 0; for (const si of e.active) { const played = si === e.played; const points = played ? spec.stringPoints : spec.sympPoints; this.strings.push({ string: si, length: e.Ls[si], points, offset: off, played }); off += 2 * points; } this.notchOffset = off; off += 8; this.etaOffset = off; const idx: number[] = []; e.bm.forEach((m, j) => { if (m.src !== undefined && m.src < spec.shapeModes) idx.push(j); }); this.etaIdx = Int32Array.from(idx); this.etaModes = Int32Array.from(idx, (j) => e.bm[j].src!); this.etaGain = Float32Array.from(idx, (j) => e.bm[j].thin ?? 1); this.F = off + idx.length; const M = e.bm.length; this.BY = new Float64Array(M * 4); this.BZ = new Float64Array(M * 4); this.air = new Float64Array(M); e.bm.forEach((m, j) => { for (let i = 0; i < 4; i++) { this.BY[j * 4 + i] = m.by[i]; this.BZ[j * 4 + i] = m.bz[i]; } const src = m.src ?? -1; this.air[j] = spec.airFrac && src >= 0 && src < spec.airFrac.length ? spec.airFrac[src] : m.label === "A0" ? 1 : 0; }); } step(n: number, Fy: number, Fz: number, fc: Float64Array, pr: number, pk: number, cur: Float64Array, prev: Float64Array, tRel: number): void { const { k, pols, polDir, bA } = this.e; const ch = this.ch, k2 = k * k; ch.fingerFy[n] = Fy; ch.fingerFz[n] = Fz; let by = 0, bz = 0; for (let c = 0; c < fc.length; c++) { if (polDir[c] === 0) by -= fc[c]; else bz -= fc[c]; } ch.bridgeFy[n] = by / k2; ch.bridgeFz[n] = bz / k2; let eS = 0, eY = 0; for (let c = 0; c < pols.length; c++) { const en = pols[c].energy(); if (c < 2) eS += en; else eY += en; } ch.eString[n] = eS; ch.eSymp[n] = eY; let eB = 0, eA = 0; for (let m = 0; m < cur.length; m++) { const v = cur[m] - prev[m]; const en = (0.5 * (v * v + bA[m] * cur[m] * cur[m])) / k2; const a = this.air[m]; eA += a * en; eB += (1 - a) * en; } ch.eBody[n] = eB; ch.eAir[n] = eA; ch.mic[n] = pr; ch.pickup[n] = pk; this.nSteps = n + 1; // frames: the state after this step, at t = (n + 1) k const t = (n + 1) * k, sp = this.spec; const denseTo = Number.isFinite(sp.denseTo) ? sp.denseTo : tRel >= 0 ? tRel + sp.denseAfterRelease : Infinity; const dense = t >= sp.denseFrom && t <= denseTo && this.nDense < sp.maxDense; if (dense || t >= this.nextSparse) { if (dense) { this.nDense++; if (this.denseStart < 0) this.denseStart = t; this.denseLast = t; } while (this.nextSparse <= t) this.nextSparse += sp.sparseDt; this.capture(t, cur); } } private capture(t: number, eta: Float64Array): void { const f = new Float32Array(this.F); const { pols } = this.e; this.strings.forEach((s, a) => { pols[2 * a].sample(s.points, f, s.offset); pols[2 * a + 1].sample(s.points, f, s.offset + s.points); }); const M = eta.length, o = this.notchOffset; for (let m = 0; m < M; m++) { const v = eta[m]; if (v === 0) continue; 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; } } for (let q = 0; q < this.etaIdx.length; q++) f[this.etaOffset + q] = eta[this.etaIdx[q]] * this.etaGain[q]; this.frames.push(f); this.times.push(t); } finish(x: Pick): Recording { const n = this.nSteps; const channels = Object.fromEntries(CHANNELS.map((c) => [c, this.ch[c].slice(0, n)])) as Record; const frames = new Float32Array(this.frames.length * this.F); this.frames.forEach((f, i) => frames.set(f, i * this.F)); return { dt: this.e.k, nSteps: n, channels, frameTimes: Float64Array.from(this.times), frames, frameSize: this.F, strings: this.strings, notchOffset: this.notchOffset, etaOffset: this.etaOffset, etaModes: this.etaModes, dense: [this.denseStart, this.denseLast], ...x, }; } } /** The output: micMix * mic + pickupMix * pickup (with its trim), times the output gain. */ export function mixOutput(p: Params, mic: Float32Array, pickup: Float32Array): Float32Array { const g = Math.pow(10, p.output.gainDb / 20); const a = p.output.micMix * g, b = p.output.pickupMix * Math.pow(10, p.output.pickupGainDb / 20) * g; const y = new Float32Array(mic.length); for (let i = 0; i < y.length; i++) y[i] = a * mic[i] + b * pickup[i]; return y; } /** Small dense matrix inverse (Gauss-Jordan with partial pivoting). */ function invert(A: Float64Array, n: number): Float64Array { const a = Float64Array.from(A); const inv = new Float64Array(n * n); for (let i = 0; i < n; i++) inv[i * n + i] = 1; for (let col = 0; col < n; col++) { let piv = col; for (let r = col + 1; r < n; r++) if (Math.abs(a[r * n + col]) > Math.abs(a[piv * n + col])) piv = r; if (piv !== col) for (let j = 0; j < n; j++) { [a[col * n + j], a[piv * n + j]] = [a[piv * n + j], a[col * n + j]]; [inv[col * n + j], inv[piv * n + j]] = [inv[piv * n + j], inv[col * n + j]]; } const d = a[col * n + col]; for (let j = 0; j < n; j++) { a[col * n + j] /= d; inv[col * n + j] /= d; } for (let r = 0; r < n; r++) if (r !== col) { const f = a[r * n + col]; if (f === 0) continue; 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]; } } } return inv; }