/ music / marimba
Sign in
music / marimba
marimba / js / synth.js
352 lines · 16.5 KBBlameHistoryRaw
1// Sound of a mallet strike: bar modes coupled to the resonator tube, radiated to the mic.
2//
3// Bar: mass-normalized modes φₙ (vertical displacement on the top face), so a downward force
4// F at P drives q̈ₙ + 2σₙq̇ₙ + ωₙ²qₙ = φₙ(P)·F (+ the gap pressure, below).
5// Tube: closed at the bottom; seen from its mouth it has input impedance
6// Z_t = Z₀ coth(Γ L_t), Γ = s/c + β√s (wall losses ∝ √f).
7// The bar's underside pushes volume flow U = -s Σ aₙ q̇ₙ... into the gap over the mouth
8// (aₙ = ∫ φₙ over the mouth). That flow either enters the tube (Z_t) or escapes around the
9// rim (Z_e = s M + radiation resistance), so the gap pressure is p_m = Z_t‖Z_e · U and it
10// pushes back on the bar with generalized force aₙ p_m. The coupling is rank one, so the
11// coupled response is solved in closed form at each frequency (Sherman–Morrison).
12// Mic: each top-face cell is a vertical dipole of moment v·V (bar volume + added mass), and
13// the flow swallowed by the tube removes a monopole at the mouth.
14// Time signal: contact force from a Hertz-type mallet simulation against the bar modes,
15// then multiplication by the transfer function and an inverse FFT, with an exponential
16// window (evaluate at s = γ + iω) so long ringing does not wrap around.
17// The FFT window is TAIL seconds longer than the output and the force spectrum is sampled
18// every 2 Hz: interpolating it makes faint copies of the strike every 1/df seconds, and the
19// copy at negative time would otherwise wrap to the end of the output, where the
20// exponential window amplifies it enormously (heard as a rattle at the end of some notes).
22import { AIR, tubeGeom, tubeLength, micPos, noteFreq } from './bar.js';
23import { cellGeom, dipoleDepth } from './fe.js';
24import { internalDecay, malletForce, contactTimeGuess } from './physics.js';
25import { fft, nextPow2 } from './fft.js';
27/**
28 * opts: { note, eta, slope, res: { on, diam, gap, detune, loss } }
29 */
30export function prepare(model, opts) {
31 const b = model.design;
32 const { nx, ny } = model;
33 const { dx, dy, dA } = cellGeom(model);
34 const mic = micPos(b).map((v) => v * 1e-3);
35 const zTop = b.h0 * 1e-3;
36 const r0 = Math.hypot(mic[0] - (b.L / 2) * 1e-3, mic[1] - (b.W / 2) * 1e-3, mic[2] - zTop);
37 const tg = tubeGeom(b, opts.res);
38 const at = tg.a * 1e-3;
40 // fraction of each cell over the tube mouth (3 x 3 subsamples)
41 const cover = new Float32Array(nx * ny);
42 for (let j = 0; j < ny; j++) {
43 for (let i = 0; i < nx; i++) {
44 let c = 0;
45 for (let u = 0; u < 3; u++) for (let v = 0; v < 3; v++) {
46 const x = (i + (u + 0.5) / 3) * dx - tg.x * 1e-3, y = (j + (v + 0.5) / 3) * dy - tg.y * 1e-3;
47 if (x * x + y * y < at * at) c++;
48 }
49 cover[j * nx + i] = c / 9;
50 }
51 }
52 // per-cell geometry toward the mic
53 const geo = [];
54 for (let j = 0; j < ny; j++) {
55 for (let i = 0; i < nx; i++) {
56 const ex = mic[0] - (i + 0.5) * dx, ey = mic[1] - (j + 0.5) * dy, ez = mic[2] - zTop;
57 const r = Math.hypot(ex, ey, ez);
58 geo.push({ r, cos: ez / r });
59 }
60 }
61 const V = dipoleDepth(b) * dA;
62 const c = AIR.c, rho = AIR.rho;
63 const modes = model.modes.map((m) => {
64 const w = 2 * Math.PI * m.f;
65 const sig = m.sigRad + internalDecay(m.f, opts.eta, opts.slope);
66 let a = 0, Br = 0, Bi = 0;
67 for (let q = 0; q < nx * ny; q++) {
68 const ph = m.phi[q];
69 a += ph * cover[q] * dA;
70 // ρ s cosθ (1/r² + s/(c r)) e^{-s (r - r0)/c} / 4π at s = iω, per unit q̇
71 const { r, cos } = geo[q];
72 const k = (ph * V * rho * cos) / (4 * Math.PI);
73 const tr = -(w * w) / (c * r), ti = w / (r * r);
74 const ang = (-w * (r - r0)) / c, cr = Math.cos(ang), ci = Math.sin(ang);
75 Br += k * (tr * cr - ti * ci);
76 Bi += k * (tr * ci + ti * cr);
77 }
78 // Causal form for synthesis: |B| e^{-sτ}, with 0 ≤ τ < one period chosen so it matches B at
79 // s = iω. (A constant complex B at all frequencies is non-causal and leaks before t = 0.)
80 const Bmag = Math.hypot(Br, Bi);
81 let ph = -Math.atan2(Bi, Br);
82 if (ph < 0) ph += 2 * Math.PI;
83 return { f: m.f, w, sig, a, Br, Bi, Bmag, Btau: ph / w, phi: m.phi, label: m.label };
84 });
86 let tube = null;
87 if (opts.res.on) {
88 const fT = noteFreq(opts.note) * 2 ** ((opts.res.detune || 0) / 1200);
89 const Lt = tubeLength(fT, tg.delta) * 1e-3;
90 const S = Math.PI * at * at;
91 const mouth = [tg.x * 1e-3, tg.y * 1e-3, tg.zTop * 1e-3];
92 tube = {
93 L: Lt, S, a: at, fT, delta: tg.delta * 1e-3,
94 Z0: (rho * c) / S,
95 // escape path: inertance of the end correction, minus the part the radiation
96 // impedance below already carries (ρ/4πa)
97 M: (rho * (tg.delta * 1e-3 - at / 4)) / S,
98 // passive radiation impedance of a small monopole of radius a:
99 // (ρc/4πa²)·(sa/c)/(1 + sa/c) ≈ sρ/4πa + ρω²/4πc at low ka
100 Rr: (rho * c) / (4 * Math.PI * at * at), ta: at / c,
101 beta: ((opts.res.loss ?? 1) * 3e-5) / (Math.sqrt(Math.PI) * at),
102 rt: Math.hypot(mic[0] - mouth[0], mic[1] - mouth[1], mic[2] - mouth[2]),
103 };
104 }
105 return { model, modes, tube, r0, nx, ny, dx, dy };
108// Bilinear interpolation of every mode's φ at a top-face point (mm).
109export function phiAt(prep, sx, sy) {
110 const { nx, ny, dx, dy } = prep;
111 const u = Math.min(nx - 1.0001, Math.max(0, (sx * 1e-3) / dx - 0.5));
112 const v = Math.min(ny - 1.0001, Math.max(0, (sy * 1e-3) / dy - 0.5));
113 const i0 = Math.floor(u), j0 = Math.floor(v), fu = u - i0, fv = v - j0;
114 const i1 = Math.min(nx - 1, i0 + 1), j1 = Math.min(ny - 1, j0 + 1);
115 return prep.modes.map((m) =>
116 m.phi[j0 * nx + i0] * (1 - fu) * (1 - fv) + m.phi[j0 * nx + i1] * fu * (1 - fv) +
117 m.phi[j1 * nx + i0] * (1 - fu) * fv + m.phi[j1 * nx + i1] * fu * fv);
120/**
121 * Mallet against the bar modes (tube ignored over the few ms of contact).
122 * Returns { F (N, downward on the bar), h (s) }.
123 */
124export function simulateContact(modes, phiP, ml, hStep = 0) {
125 const T0 = contactTimeGuess(ml);
126 const h = hStep || T0 / 300;
127 const nMax = Math.ceil(Math.max(0.02, 10 * T0) / h);
128 const M = modes.length;
129 const Er = new Float64Array(M), Ei = new Float64Array(M), Gr = new Float64Array(M), Gi = new Float64Array(M);
130 const Pr = new Float64Array(M), Pi = new Float64Array(M), ph = new Float64Array(M);
131 const zr = new Float64Array(M), zi = new Float64Array(M);
132 for (let n = 0; n < M; n++) {
133 const { w, sig } = modes[n];
134 const wd = Math.sqrt(Math.max(1e-6, w * w - sig * sig));
135 const pr = -sig, pi = wd; // pole
136 const e = Math.exp(pr * h);
137 Er[n] = e * Math.cos(pi * h); Ei[n] = e * Math.sin(pi * h);
138 // G = r (E - 1)/p, r = 1 + iσ/ω_d
139 const nr = Er[n] - 1, ni = Ei[n], d = pr * pr + pi * pi;
140 const qr = (nr * pr + ni * pi) / d, qi = (ni * pr - nr * pi) / d;
141 const rr = 1, ri = sig / wd;
142 Gr[n] = qr * rr - qi * ri; Gi[n] = qr * ri + qi * rr;
143 Pr[n] = pr / d; Pi[n] = -pi / d; // 1/p
144 ph[n] = phiP[n];
145 }
146 const m = ml.mass * 1e-3;
147 let xm = 0, vm = ml.v0, wb = 0, vb = 0, apart = 0;
148 const F = [];
149 for (let k = 0; k < nMax; k++) {
150 const f = malletForce(ml, xm - wb, vm - vb);
151 F.push(f);
152 wb = 0; vb = 0;
153 for (let n = 0; n < M; n++) {
154 const g = ph[n] * f;
155 const a = Er[n] * zr[n] - Ei[n] * zi[n] + Gr[n] * g;
156 zi[n] = Er[n] * zi[n] + Ei[n] * zr[n] + Gi[n] * g;
157 zr[n] = a;
158 vb += ph[n] * zr[n];
159 wb += ph[n] * (zr[n] * Pr[n] - zi[n] * Pi[n]);
160 }
161 vm -= (f * h) / m;
162 xm += vm * h;
163 apart = f > 0 ? 0 : apart + 1;
164 if (k > 20 && apart * h > 3e-4 && vm < vb) break;
165 }
166 return { F: Float64Array.from(F), h };
169/**
170 * X_k = Σ_n F_n h e^{-s_k t_n}, s_k = γ + i k Δω, t_n = (n + ½) h, for k = 0..K-1 (Δω = 2π/(Mh·h)), by the
171 * chirp-z transform (Bluestein): nk = (n² + k² - (k-n)²)/2 turns the sum into a convolution.
172 * Exact, unlike interpolating a coarse spectrum, whose errors become ghost strikes that the
173 * exponential window amplifies.
174 */
175function forceSpectrum(F, h, gam, Mh, K) {
176 // Δω = 2π/T and h = T/Mh, so α = Δω·h = 2π/Mh and α m²/2 = π (m² mod 2Mh)/Mh exactly
177 const nF = F.length, dw = (2 * Math.PI) / (Mh * h);
178 const L = nextPow2(nF + K);
179 const ar = new Float64Array(L), ai = new Float64Array(L), br = new Float64Array(L), bi = new Float64Array(L);
180 const chirp = (m) => (Math.PI * ((m * m) % (2 * Mh))) / Mh;
181 for (let n = 0; n < nF; n++) {
182 const x = F[n] * h * Math.exp(-gam * (n + 0.5) * h), c = chirp(n);
183 ar[n] = x * Math.cos(c); ai[n] = -x * Math.sin(c);
184 }
185 for (let m = 0; m < K; m++) { const c = chirp(m); br[m] = Math.cos(c); bi[m] = Math.sin(c); }
186 for (let m = 1; m < nF; m++) { const c = chirp(m); br[L - m] = Math.cos(c); bi[L - m] = Math.sin(c); }
187 fft(ar, ai); fft(br, bi);
188 // product, then inverse FFT via conjugation
189 for (let j = 0; j < L; j++) {
190 const r = ar[j] * br[j] - ai[j] * bi[j], i = ar[j] * bi[j] + ai[j] * br[j];
191 ar[j] = r; ai[j] = -i;
192 }
193 fft(ar, ai);
194 const Xr = new Float64Array(K), Xi = new Float64Array(K);
195 for (let k = 0; k < K; k++) {
196 const cr = ar[k] / L, ci = -ai[k] / L;
197 const ph = -chirp(k) - (k * dw * h) / 2; // e^{-iα k²/2} and the half-step offset
198 const er = Math.cos(ph), ei = Math.sin(ph);
199 Xr[k] = cr * er - ci * ei; Xi[k] = cr * ei + ci * er;
200 }
201 return [Xr, Xi];
204// complex helpers on [re, im] pairs (kept inline in the hot loop below)
205function cdiv(ar, ai, br, bi) { const d = br * br + bi * bi; return [(ar * br + ai * bi) / d, (ai * br - ar * bi) / d]; }
206function csqrt(r, i) {
207 const m = Math.hypot(r, i);
208 const sr = Math.sqrt((m + r) / 2), si = Math.sign(i || 1) * Math.sqrt(Math.max(0, (m - r) / 2));
209 return [sr, si];
211function ccoth(r, i) {
212 // coth(z) = (sinh 2x - i sin 2y) / (cosh 2x - cos 2y)
213 const den = Math.cosh(2 * r) - Math.cos(2 * i);
214 return [Math.sinh(2 * r) / den, -Math.sin(2 * i) / den];
217/**
218 * Mic pressure (Pa) for a strike at (sx, sy) mm.
219 * ml: mallet (see physics.js) with v0; returns { y: Float32Array, sr, F, h, T, Fm, dur }.
220 */
221export function strike(prep, sx, sy, ml, sr, maxDur = 4) {
222 const phiAll = phiAt(prep, sx, sy);
224 // modes below Nyquist take part in the sound
225 const idx = [];
226 prep.modes.forEach((m, n) => { if (m.f < 0.48 * sr) idx.push(n); });
227 const M = idx.length;
228 const w2 = new Float64Array(M), s2 = new Float64Array(M), aC = new Float64Array(M), phi = new Float64Array(M);
229 const Bm = new Float64Array(M), Bt = new Float64Array(M);
230 let sigMin = Infinity;
231 idx.forEach((n, q) => {
232 const m = prep.modes[n];
233 w2[q] = m.w * m.w; s2[q] = 2 * m.sig; aC[q] = m.a; phi[q] = phiAll[n]; Bm[q] = m.Bmag; Bt[q] = m.Btau;
234 if (Math.abs(phi[q]) > 1e-9 || (prep.tube && Math.abs(m.a) > 1e-12)) sigMin = Math.min(sigMin, m.sig);
235 });
236 if (prep.tube) {
237 // the tube's own (wall-loss) decay can be slower than the bar's
238 const t = prep.tube, w = 2 * Math.PI * t.fT;
239 sigMin = Math.min(sigMin, t.beta * Math.sqrt(w / 2) * AIR.c);
240 }
241 const dur = Math.min(maxDur, Math.max(0.4, 7 / (Number.isFinite(sigMin) ? sigMin : 10)));
242 // Exponential window: the part of the ring beyond T wraps to the start, scaled by
243 // e^{-σT}·e^{-γ(T - t)}. Keep that 120 dB down at the end of the output even when the
244 // output is cut while the note still rings (the maxDur cap, light damping). γ is capped
245 // so e^{γ·dur} cannot blow up rounding errors; if the cap binds, the window grows instead.
246 // The window is also at least TAIL longer than the output, so nothing from just before
247 // t = 0 can wrap into it.
248 const TAIL = 0.6, GMAX = 16 / dur, NEED = Math.log(1e6);
249 const sMin = Number.isFinite(sigMin) ? sigMin : 10;
250 let N = nextPow2(Math.ceil((dur + TAIL) * sr));
251 while (N < 1 << 22 && sMin * (N / sr) + GMAX * (N / sr - dur) < NEED) N *= 2;
252 const T = N / sr;
253 const gam = Math.min(GMAX, Math.max(Math.log(1e4) / T, (NEED - sMin * T) / (T - dur)));
254 // per-mode delay phasors e^{-sτ}: e^{-γτ} fixed, e^{-iωτ} rotated bin by bin
255 const bpR = new Float64Array(M), bpI = new Float64Array(M), brR = new Float64Array(M), brI = new Float64Array(M);
256 for (let q = 0; q < M; q++) {
257 bpR[q] = Bm[q] * Math.exp(-gam * Bt[q]); bpI[q] = 0;
258 const a = (-2 * Math.PI * Bt[q]) / T;
259 brR[q] = Math.cos(a); brI[q] = Math.sin(a);
260 }
262 // force spectrum at s = γ + iω_k on every bin, exactly (chirp-z / Bluestein)
263 // contact step h = T / Mh with Mh an integer, so the chirp phases reduce exactly
264 const Mh = Math.max(1, Math.round(T / (contactTimeGuess(ml) / 300)));
265 const { F, h } = simulateContact(prep.modes, phiAll, ml, T / Mh);
266 let Fm = 0, nC = 0;
267 for (const f of F) { Fm = Math.max(Fm, f); if (f > 0) nC++; }
268 const [Fcr, Fci] = forceSpectrum(F, h, gam, Mh, N / 2 + 1);
270 const tube = prep.tube;
271 const c = AIR.c, rho = AIR.rho;
272 const re = new Float64Array(N), im = new Float64Array(N);
273 const Dr = new Float64Array(M), Di = new Float64Array(M);
274 for (let k = 0; k <= N / 2; k++) {
275 const w = (2 * Math.PI * k) / T;
276 const sR = gam, sI = w;
277 const ssR = sR * sR - sI * sI, ssI = 2 * sR * sI;
278 // bar modes
279 let gR = 0, gI = 0, hR = 0, hI = 0;
280 for (let q = 0; q < M; q++) {
281 const dR = ssR + s2[q] * sR + w2[q], dI = ssI + s2[q] * sI;
282 const dd = dR * dR + dI * dI;
283 const r = dR / dd, i = -dI / dd;
284 Dr[q] = r; Di[q] = i;
285 const ta = aC[q];
286 gR += ta * phi[q] * r; gI += ta * phi[q] * i;
287 hR += ta * ta * r; hI += ta * ta * i;
288 }
289 // gap pressure per unit force, and the tube's swallowed flow
290 let PmR = 0, PmI = 0, UtR = 0, UtI = 0;
291 if (tube) {
292 const [qR, qI] = csqrt(sR, sI);
293 const GR = sR / c + tube.beta * qR, GI = sI / c + tube.beta * qI;
294 const [cR, cI] = ccoth(GR * tube.L, GI * tube.L);
295 const ZtR = tube.Z0 * cR, ZtI = tube.Z0 * cI;
296 const [radR, radI] = cdiv(tube.Rr * tube.ta * sR, tube.Rr * tube.ta * sI, 1 + tube.ta * sR, tube.ta * sI);
297 const ZeR = tube.M * sR + radR, ZeI = tube.M * sI + radI;
298 const nR = ZtR * ZeR - ZtI * ZeI, nI = ZtR * ZeI + ZtI * ZeR;
299 const [ZpR, ZpI] = cdiv(nR, nI, ZtR + ZeR, ZtI + ZeI);
300 const sZR = sR * ZpR - sI * ZpI, sZI = sR * ZpI + sI * ZpR; // s Z_par
301 const numR = -(sZR * gR - sZI * gI), numI = -(sZR * gI + sZI * gR);
302 const denR = 1 + sZR * hR - sZI * hI, denI = sZR * hI + sZI * hR;
303 [PmR, PmI] = cdiv(numR, numI, denR, denI);
304 [UtR, UtI] = cdiv(PmR, PmI, ZtR, ZtI); // into the tube
305 }
306 // bar dipole radiation: Σ s qₙ Bₙ
307 let aR = 0, aI = 0;
308 for (let q = 0; q < M; q++) {
309 const fR = phi[q] + aC[q] * PmR, fI = aC[q] * PmI;
310 const qR = Dr[q] * fR - Di[q] * fI, qI = Dr[q] * fI + Di[q] * fR;
311 aR += qR * bpR[q] - qI * bpI[q];
312 aI += qR * bpI[q] + qI * bpR[q];
313 const t = bpR[q] * brR[q] - bpI[q] * brI[q];
314 bpI[q] = bpR[q] * brI[q] + bpI[q] * brR[q];
315 bpR[q] = t;
316 }
317 // times s, times e^{-s r0/c}
318 let pR = sR * aR - sI * aI, pI = sR * aI + sI * aR;
319 {
320 const e = Math.exp((-sR * prep.r0) / c), ang = (-sI * prep.r0) / c;
321 const cR = e * Math.cos(ang), cI = e * Math.sin(ang);
322 [pR, pI] = [pR * cR - pI * cI, pR * cI + pI * cR];
323 }
324 if (tube) {
325 // monopole -U_t at the mouth: ρ s (-U_t) e^{-s r/c} / (4π r)
326 const e = Math.exp((-sR * tube.rt) / c) / (4 * Math.PI * tube.rt), ang = (-sI * tube.rt) / c;
327 const cR = e * Math.cos(ang), cI = e * Math.sin(ang);
328 const uR = -rho * (sR * UtR - sI * UtI), uI = -rho * (sR * UtI + sI * UtR);
329 pR += uR * cR - uI * cI;
330 pI += uR * cI + uI * cR;
331 }
332 // force on the bar is downward, φ is up
333 const FR = -Fcr[k], FI = -Fci[k];
334 // smooth roll-off to zero at Nyquist: a hard cut there smears in time and the
335 // exponential window would amplify the smear near the end of the output
336 const fr = k / N, tap = fr < 0.44 ? 1 : Math.cos(((fr - 0.44) / 0.06) * (Math.PI / 2)) ** 2;
337 const YR = tap * (FR * pR - FI * pI), YI = tap * (FR * pI + FI * pR);
338 // inverse transform via a forward FFT of the conjugate
339 re[k] = YR; im[k] = -YI;
340 if (k > 0 && k < N / 2) { re[N - k] = YR; im[N - k] = YI; }
341 if (k === N / 2) im[k] = 0;
342 }
343 fft(re, im);
344 const nOut = Math.min(N, Math.ceil(dur * sr));
345 const y = new Float32Array(nOut);
346 for (let n = 0; n < nOut; n++) y[n] = (re[n] / T) * Math.exp((gam * n) / sr);
347 // fade out: short if the note has died away, longer if maxDur cut it while still ringing
348 const cut = 7 / (Number.isFinite(sigMin) ? sigMin : 10) > dur + 1e-9;
349 const fade = Math.min(nOut, Math.round((cut ? 0.5 : 0.02) * sr));
350 for (let n = 0; n < fade; n++) y[nOut - 1 - n] *= 0.5 - 0.5 * Math.cos((Math.PI * n) / fade);
351 return { y, sr, F, h, T: nC * h, Fm, dur };
↑↓ move↵openescclose