/ music / marimba
Sign in
music / marimba
marimba / main.js
480 lines · 20.7 KBBlameHistoryRaw
1import { MATERIALS, LOW_NOTE, HIGH_NOTE, noteName, noteFreq, isBlack, nominalDesign, maxDepth, validateDesign, micPos } from './js/bar.js';
2import { feBarModel } from './js/fe.js';
3import { tuneDesign, partialErrors, DEFAULT_TARGETS } from './js/tune.js';
4import { prepare, strike } from './js/synth.js';
5import { MALLETS, graduatedMallet } from './js/physics.js';
6import { analyzeBar, analysisCost, matchModes } from './js/analysis.js';
7import { exportSF2, sampledKeys, LAYERS, VARIANTS } from './js/export.js';
8import { spectrumDb } from './js/fft.js';
9import { BarView } from './js/view3d.js';
10import { drawSpectrum, drawWave } from './js/plots.js';
12const $ = (id) => document.getElementById(id);
14// ---------- parameters ----------
15const MALLET = [
16 { key: 'v0', label: 'Strike velocity', min: 0.2, max: 4, step: 0.05, value: 1.5, unit: 'm/s' },
17 { key: 'yarn', label: 'Yarn thickness', min: 0.3, max: 6, step: 0.1, value: MALLETS.medium.yarn, unit: 'mm' },
18 { key: 'Ky', label: 'Yarn stiffness log₁₀K', min: 8.5, max: 12.5, step: 0.05, value: MALLETS.medium.Ky, unit: '' },
19 { key: 'Kc', label: 'Core hardness log₁₀K', min: 6.5, max: 10, step: 0.05, value: MALLETS.medium.Kc, unit: '' },
20 { key: 'mass', label: 'Mallet mass', min: 10, max: 80, step: 1, value: MALLETS.medium.mass, unit: 'g' },
21 { key: 'lam', label: 'Yarn hysteresis', min: 0, max: 0.6, step: 0.01, value: MALLETS.medium.lam, unit: 's/m' },
22];
23const RES = [
24 { key: 'diam', label: 'Tube diameter', min: 0.5, max: 1.3, step: 0.01, value: 0.9, unit: '× W' },
25 { key: 'gap', label: 'Gap below bar', min: 3, max: 60, step: 1, value: 20, unit: 'mm' },
26 { key: 'detune', label: 'Tube tuning', min: -100, max: 100, step: 1, value: 0, unit: 'cents' },
27 { key: 'loss', label: 'Tube wall loss', min: 0.25, max: 4, step: 0.05, value: 1, unit: '×' },
28];
29const DAMP = [
30 { key: 'eta', label: 'Loss factor η (1 kHz)', min: 0.001, max: 0.03, step: 0.0005, value: MATERIALS.rosewood.eta, unit: '' },
31 { key: 'slope', label: 'η frequency slope', min: -0.5, max: 1, step: 0.05, value: 0, unit: '' },
32];
33const DESIGN = [
34 { key: 'L', label: 'Length', min: 60, max: 1200, step: 0.5, unit: 'mm' },
35 { key: 'W', label: 'Width', min: 25, max: 100, step: 0.5, unit: 'mm' },
36 { key: 'h0', label: 'Thickness', min: 10, max: 32, step: 0.1, unit: 'mm' },
37 { key: 'd', label: 'Undercut depth', min: 0, max: 29, step: 0.05, unit: 'mm' },
38 { key: 'a', label: 'Undercut length', min: 0.2, max: 0.95, step: 0.005, unit: '× L' },
39 { key: 'p', label: 'Arch flatness', min: 1, max: 10, step: 0.1, unit: '' },
40].map((d) => ({ ...d, value: 0 }));
41const TARGET = [
42 { key: 'r2', label: 'Partial 2 ratio', min: 2, max: 6, step: 0.01, value: DEFAULT_TARGETS.r2, unit: '× f1' },
43 { key: 'r3', label: 'Partial 3 ratio', min: 5, max: 14, step: 0.01, value: DEFAULT_TARGETS.r3, unit: '× f1' },
44 { key: 'fCut', label: 'Tune partials up to', min: 2000, max: 20000, step: 100, value: DEFAULT_TARGETS.fCut, unit: 'Hz' },
45];
46const MAT = [
47 { key: 'rho', label: 'Density', min: 500, max: 1300, step: 5, value: MATERIALS.rosewood.rho, unit: 'kg/m³' },
48 { key: 'EL', label: 'Stiffness E_L', min: 6, max: 30, step: 0.1, value: MATERIALS.rosewood.EL, unit: 'GPa' },
49];
51const P = {};
52const sliders = {};
53function addSliders(container, defs, onChange) {
54 for (const d of defs) {
55 P[d.key] = d.value;
56 const row = document.createElement('label');
57 row.className = 'row';
58 row.innerHTML = `<span class="lab">${d.label}</span><input type="range" min="${d.min}" max="${d.max}" step="${d.step}" value="${d.value}"><span class="val"></span>`;
59 container.appendChild(row);
60 const inp = row.querySelector('input'), val = row.querySelector('.val');
61 const show = () => (val.textContent = fmt(d, P[d.key]));
62 inp.addEventListener('input', () => { P[d.key] = parseFloat(inp.value); show(); onChange(d.key); });
63 sliders[d.key] = { set: (v) => { P[d.key] = v; inp.value = v; show(); }, setMax: (m) => { inp.max = m; } };
64 show();
65 }
67function fmt(d, v) {
68 if (d.key === 'Ky' || d.key === 'Kc') return v.toFixed(2);
69 if (d.key === 'detune') return (v > 0 ? '+' : '') + v.toFixed(0) + ' ¢';
70 if (d.key === 'eta') return v.toFixed(4);
71 if (d.key === 'slope') return (v > 0 ? '+' : '') + v.toFixed(2);
72 if (d.key === 'fCut') return (v / 1000).toFixed(1) + ' kHz';
73 if (d.key === 'a' || d.key === 'diam') return v.toFixed(2) + ' ' + d.unit;
74 const dec = d.step < 0.1 ? 2 : d.step < 1 ? 1 : 0;
75 return v.toFixed(dec) + (d.unit ? ' ' + d.unit : '');
78// ---------- state ----------
79let note = 60;
80const designs = new Map(); // note -> { b, manual }
81let feModel = null; // FE bar model of the selected bar
82let fdModel = null; // FDTD bar model (with .key = design it was made for)
83let compareRows = [];
84let prep = null;
85let strikeF = [0.5, 0.4]; // strike point as fractions of L and W
86let busy = false, cancel = false;
87let actx = null, gain = 1;
88let lastStrike = null;
89let throughput = 0; // FDTD cell-steps per second, measured
91const mat = () => ({ rho: P.rho, EL: P.EL });
92const targets = () => ({ r2: P.r2, r3: P.r3, fCut: P.fCut });
93const res = () => ({ on: $('reson').checked, diam: P.diam, gap: P.gap, detune: P.detune, loss: P.loss });
94const mallet = () => ({ v0: P.v0, yarn: P.yarn, Ky: P.Ky, Kc: P.Kc, mass: P.mass, lam: P.lam });
95// the mallet actually used on a key (softer toward the bass when graduated)
96const malletFor = (n) => ($('grad').checked ? graduatedMallet(mallet(), n) : mallet());
97function showGrad() {
98 const m = malletFor(note), base = mallet();
99 const same = ['yarn', 'Ky', 'Kc', 'mass'].every((k) => Math.abs(m[k] - base[k]) < 1e-9);
100 $('gradinfo').textContent = !$('grad').checked
101 ? 'Same mallet on every key.'
102 : same ? 'Below C4 the mallet gets softer and heavier, reaching a bass mallet at C2.'
103 : `On ${noteName(note)}: yarn ${m.yarn.toFixed(1)} mm, log₁₀K ${m.Ky.toFixed(2)} / ${m.Kc.toFixed(2)}, ${m.mass.toFixed(0)} g.`;
105const sound = () => ({ note, eta: P.eta, slope: P.slope, res: res() });
106const bar = () => designs.get(note).b;
107const keyOf = (b) => JSON.stringify([b, mat()]);
109function designFor(n) {
110 if (!designs.has(n)) designs.set(n, { b: tuneDesign(n, mat(), targets()), manual: false });
111 return designs.get(n).b;
114// ---------- UI construction ----------
115const view = new BarView($('view'), (x, y) => {
116 const b = bar();
117 strikeF = [x / b.L, y / b.W];
118 view.setStrike(x, y);
119 showStrike();
120 playStrike();
121});
123addSliders($('mallet'), MALLET, (k) => { if (k !== 'v0') $('mpreset').value = 'custom'; showGrad(); });
124$('grad').addEventListener('change', showGrad);
125addSliders($('res'), RES, () => soundChanged());
126addSliders($('damp'), DAMP, () => soundChanged());
127addSliders($('design'), DESIGN, (k) => designEdited(k));
128addSliders($('targets'), TARGET, () => retuneAll());
129addSliders($('mat'), MAT, () => { $('matpreset').value = 'custom'; retuneAll(); });
130$('reson').addEventListener('change', () => soundChanged());
132$('mpreset').addEventListener('change', () => {
133 const m = MALLETS[$('mpreset').value];
134 if (m) for (const k of ['yarn', 'Ky', 'Kc', 'mass', 'lam']) sliders[k].set(m[k]);
135 showGrad();
136});
137$('matpreset').addEventListener('change', () => {
138 const m = MATERIALS[$('matpreset').value];
139 if (!m) return;
140 sliders.rho.set(m.rho); sliders.EL.set(m.EL); sliders.eta.set(m.eta);
141 retuneAll();
142});
144// keyboard strip: naturals along the bottom, accidentals above, as on a marimba
145const keyEls = new Map();
146(function buildKeys() {
147 const box = $('keys');
148 const naturals = [];
149 for (let n = LOW_NOTE; n <= HIGH_NOTE; n++) if (!isBlack(n)) naturals.push(n);
150 const w = 100 / naturals.length;
151 for (let n = LOW_NOTE; n <= HIGH_NOTE; n++) {
152 const el = document.createElement('button');
153 el.className = 'key ' + (isBlack(n) ? 'acc' : 'nat');
154 const pos = naturals.filter((m) => m < n).length;
155 el.style.left = (isBlack(n) ? pos * w - w * 0.42 : pos * w) + '%';
156 el.style.width = (isBlack(n) ? w * 0.84 : w) + '%';
157 el.title = `${noteName(n)} · ${noteFreq(n).toFixed(1)} Hz`;
158 if (n % 12 === 0) el.textContent = noteName(n);
159 el.addEventListener('click', () => { selectNote(n); playStrike(); });
160 box.appendChild(el);
161 keyEls.set(n, el);
162 }
163})();
165function markKeys() {
166 for (const [n, el] of keyEls) {
167 el.classList.toggle('sel', n === note);
168 el.classList.toggle('edited', !!designs.get(n)?.manual);
169 }
172// ---------- bar selection and editing ----------
173function selectNote(n) {
174 note = Math.max(LOW_NOTE, Math.min(HIGH_NOTE, n));
175 designFor(note);
176 showDesign();
177 rebuild();
180function showDesign() {
181 const b = bar();
182 for (const d of DESIGN) sliders[d.key].set(b[d.key]);
183 sliders.d.setMax(maxDepth(b).toFixed(2));
184 $('notename').textContent = `· ${noteName(note)} ${noteFreq(note).toFixed(1)} Hz`;
185 $('barnote').textContent = noteName(note);
186 $('barstate').textContent = designs.get(note).manual ? 'edited' : 'auto-tuned';
187 showGrad();
190let pending = 0;
191function designEdited(k) {
192 const b = { ...bar(), [k]: P[k] };
193 b.d = Math.min(b.d, maxDepth(b));
194 if (k !== 'd') sliders.d.set(b.d);
195 sliders.d.setMax(maxDepth(b).toFixed(2));
196 designs.set(note, { b, manual: true });
197 $('barstate').textContent = 'edited';
198 if (!pending) pending = requestAnimationFrame(() => { pending = 0; rebuild(); });
201function retuneAll() {
202 for (const [n, v] of [...designs]) if (!v.manual) designs.delete(n);
203 selectNote(note);
206$('autotune').onclick = () => {
207 const b0 = bar();
208 const b = tuneDesign(note, mat(), targets(), b0);
209 const nom = nominalDesign(note, mat());
210 const manual = Math.abs(b.W - nom.W) > 1e-6 || Math.abs(b.h0 - nom.h0) > 1e-6 || Math.abs(b.p - nom.p) > 1e-6;
211 designs.set(note, { b, manual });
212 showDesign();
213 rebuild();
214 playStrike();
215};
216$('reset').onclick = () => { designs.delete(note); selectNote(note); playStrike(); };
218// FE model of the selected bar, then the sound model
219function rebuild() {
220 const b = bar();
221 const errs = validateDesign(b);
222 $('warn').textContent = errs.join('; ');
223 feModel = feBarModel(b, mat());
224 const fdOk = fdModel && fdModel.key === keyOf(b);
225 $('source').querySelector('[value=FDTD]').disabled = !fdOk;
226 if (!fdOk && $('source').value === 'FDTD') $('source').value = 'FE';
227 showCompare(fdOk);
228 showPartials();
229 markKeys();
230 soundChanged();
231 updateInfo();
232 updateSfInfo();
235function soundModel() {
236 const fdOk = fdModel && fdModel.key === keyOf(bar());
237 return $('source').value === 'FDTD' && fdOk ? fdModel : feModel;
240function soundChanged() {
241 prep = prepare(soundModel(), sound());
242 const b = bar();
243 const t = prep.tube;
244 view.setScene(b, t ? { a: t.a * 1e3, L: t.L * 1e3, gap: P.gap } : null, micPos(b), feModel.nodes);
245 view.setStrike(strikeF[0] * b.L, strikeF[1] * b.W);
246 showStrike();
247 $('tubeinfo').textContent = t
248 ? `Tube ${(t.L * 1000).toFixed(0)} mm long, ${(t.a * 2000).toFixed(0)} mm across, tuned to ${t.fT.toFixed(1)} Hz (end correction ${(t.delta * 1000).toFixed(1)} mm).`
249 : 'No resonator: the bar radiates on its own.';
250 fillModeList();
251 drawPlots();
253$('source').addEventListener('change', () => soundChanged());
255function showStrike() {
256 const b = bar();
257 $('strikepos').textContent = `${(strikeF[0] * b.L).toFixed(0)}, ${(strikeF[1] * b.W).toFixed(0)} mm`;
260function showPartials() {
261 const f = ['B1', 'B2', 'B3'].map((l) => feModel.modes.find((m) => m.label === l)?.f ?? NaN);
262 const e = partialErrors(f, note, targets());
263 const rows = e.map((x, i) => {
264 const cls = !x.on ? 'muted' : Math.abs(x.cents) < 3 ? 'ok' : 'bad';
265 const err = x.on ? `${x.cents > 0 ? '+' : ''}${x.cents.toFixed(1)} ¢` : 'not tuned';
266 return `<tr><td>f${i + 1}</td><td>${x.f.toFixed(1)} Hz</td><td class="muted">${(x.f / f[0]).toFixed(2)}×</td><td class="${cls}">${err}</td></tr>`;
267 });
268 $('partials').innerHTML = `<tr><th>partial</th><th>FE</th><th>ratio</th><th>vs target</th></tr>${rows.join('')}`;
271function fillModeList() {
272 const sel = $('overlay');
273 const prev = sel.value;
274 sel.innerHTML = '<option value="-1">none</option>' +
275 prep.modes.map((m, i) => `<option value="${i}">${m.label || i + 1}: ${m.f.toFixed(0)} Hz</option>`).join('');
276 sel.value = prep.modes[prev] ? prev : '-1';
277 showOverlay();
279function showOverlay() {
280 const i = parseInt($('overlay').value, 10);
281 if (!prep || i < 0) { view.setOverlay(0, 0, null); return; }
282 const m = prep.modes[i];
283 let mx = 0;
284 for (const v of m.phi) mx = Math.max(mx, Math.abs(v));
285 view.setOverlay(prep.nx, prep.ny, Float32Array.from(m.phi, (v) => v / (mx || 1)));
287$('overlay').addEventListener('change', showOverlay);
289// ---------- audio ----------
290function audio() {
291 if (!actx) actx = new AudioContext();
292 if (actx.state === 'suspended') actx.resume();
293 return actx;
295function play(y, sr) {
296 const ctx = audio();
297 const buf = ctx.createBuffer(1, y.length, sr);
298 const ch = buf.getChannelData(0);
299 for (let i = 0; i < y.length; i++) ch[i] = Math.max(-1, Math.min(1, y[i] * gain));
300 const src = ctx.createBufferSource();
301 src.buffer = buf;
302 src.connect(ctx.destination);
303 src.start();
306function playStrike() {
307 if (!prep) return;
308 const sr = audio().sampleRate;
309 const b = bar();
310 const r = strike(prep, strikeF[0] * b.L, strikeF[1] * b.W, malletFor(note), sr);
311 lastStrike = r;
312 view.hit();
313 play(r.y, sr);
314 $('contact').textContent = `contact ${(r.T * 1000).toFixed(2)} ms, peak force ${r.Fm.toFixed(0)} N`;
315 drawPlots();
318function drawPlots() {
319 const series = [], waves = [];
320 if (lastStrike) {
321 series.push({ name: 'modal', ...spectrumDb(lastStrike.y, lastStrike.sr) });
322 waves.push({ name: 'modal', y: lastStrike.y, sr: lastStrike.sr });
323 }
324 const marks = prep ? prep.modes.map((m) => m.f) : [];
325 drawSpectrum($('spec'), series, marks, prep?.tube ? [prep.tube.fT, 3 * prep.tube.fT] : []);
326 const full = $('wavespan').value === 'full';
327 drawWave($('wave'), waves, full ? null : 0.2);
328 $('ringlen').textContent = lastStrike ? `${(lastStrike.y.length / lastStrike.sr).toFixed(2)} s rendered` : '';
330$('wavespan').addEventListener('change', () => {
331 try { localStorage.setItem('mb-wavespan', $('wavespan').value); } catch {}
332 drawPlots();
333});
334try { const v = localStorage.getItem('mb-wavespan'); if (v) $('wavespan').value = v; } catch {}
336// ---------- FDTD check ----------
337function setBusy(b, label = '') {
338 busy = b;
339 for (const id of ['analyze', 'export', 'autotune']) $(id).disabled = b;
340 $('cancel').hidden = !b;
341 $('status').textContent = label;
342 if (!b) $('bar').style.width = '0%';
345function updateInfo() {
346 if (!navigator.gpu) return;
347 const b = bar();
348 const dx = parseFloat($('dx').value);
349 const f1 = feModel.modes.find((m) => m.label === 'B1')?.f ?? noteFreq(note);
350 const { cells, steps } = analysisCost(b, mat(), dx, f1);
351 const est = throughput ? `est. ${Math.round((cells * steps) / throughput)} s` : `roughly ${Math.max(1, Math.round((cells * steps) / 3e9))} s on a fast GPU`;
352 const cen = b.h0 - b.d;
353 $('info').textContent = `${(cells / 1e6).toFixed(2)} M cells · ${steps.toLocaleString()} steps · ${est}. ` +
354 `Thinnest point ${cen.toFixed(1)} mm = ${(cen / dx).toFixed(1)} cells.`;
356$('dx').addEventListener('change', updateInfo);
358function showCompare(ok) {
359 if (!ok || !compareRows.length) {
360 $('compare').innerHTML = fdModel && !ok ? '<tr><td class="muted">Bar changed since the last FDTD analysis.</td></tr>' : '';
361 return;
362 }
363 const rows = compareRows.filter((r) => r.fe.f < 12000).map((r) =>
364 `<tr><td>${r.fe.label}</td><td>${r.fe.f.toFixed(1)}</td><td>${r.fd.f.toFixed(1)}</td><td class="${Math.abs(r.cents) < 20 ? 'ok' : 'bad'}">${r.cents > 0 ? '+' : ''}${r.cents.toFixed(0)} ¢</td><td class="muted">${r.fe.sigRad.toFixed(1)} / ${r.fd.sigRad.toFixed(1)}</td></tr>`);
365 $('compare').innerHTML = `<tr><th>mode</th><th>FE Hz</th><th>FDTD Hz</th><th>Δ</th><th>σ_rad FE/FDTD</th></tr>${rows.join('')}`;
368async function analyze() {
369 if (busy) return;
370 const b = { ...bar() };
371 const dx = parseFloat($('dx').value);
372 const f1 = feModel.modes.find((m) => m.label === 'B1')?.f ?? noteFreq(note);
373 setBusy(true, 'Analyzing…');
374 cancel = false;
375 try {
376 const { cells, steps } = analysisCost(b, mat(), dx, f1);
377 const t0 = performance.now();
378 const model = await analyzeBar(b, mat(), dx, f1, {
379 isCancelled: () => cancel,
380 onProgress: (label, frac, sec, fRun) => {
381 $('bar').style.width = (frac * 100).toFixed(1) + '%';
382 const left = frac > 0.01 && frac < 1 ? ` · ${Math.round((sec / frac) * (1 - frac))} s left` : '';
383 $('status').textContent = `${label} ${frac < 1 ? (fRun * 100).toFixed(0) + '%' : ''}${left}`;
384 },
385 });
386 if (!model) { setBusy(false, 'Cancelled.'); return; }
387 throughput = (cells * steps) / model.seconds;
388 model.key = keyOf(b);
389 fdModel = model;
390 compareRows = matchModes(feBarModel(b, mat()), model);
391 const sec = ((performance.now() - t0) / 1000).toFixed(1);
392 setBusy(false, `FDTD found ${model.modes.length} modes in ${sec} s. "Sound from" can now use them.`);
393 rebuild();
394 } catch (e) {
395 console.error(e);
396 setBusy(false, 'Error: ' + e.message);
397 }
399$('analyze').onclick = analyze;
400$('cancel').onclick = () => (cancel = true);
402// ---------- SoundFont export ----------
403function sfRange() {
404 let lo = parseInt($('sflo').value, 10), hi = parseInt($('sfhi').value, 10);
405 if (hi < lo) [lo, hi] = [hi, lo];
406 return { lo, hi, step: parseInt($('sfstep').value, 10) };
408function updateSfInfo() {
409 const { lo, hi, step } = sfRange();
410 $('sflo_v').textContent = noteName(parseInt($('sflo').value, 10));
411 $('sfhi_v').textContent = noteName(parseInt($('sfhi').value, 10));
412 const nKeys = sampledKeys(lo, hi, step).length;
413 const edited = [...designs].filter(([n, v]) => v.manual && n >= lo && n <= hi).length;
414 $('sfinfo').textContent = `${nKeys * LAYERS * VARIANTS} samples: ${nKeys} keys × ${LAYERS} velocity layers × ${VARIANTS} strike-point variations. ` +
415 `Each sampled key is its own auto-tuned bar and tube${edited ? ` (${edited} edited bar${edited > 1 ? 's' : ''} in range are used as edited)` : ''}; ` +
416 'uses the current mallet (graduated if ticked), damping, resonator and strike point (as a fraction of the bar). FE modes.';
418for (const id of ['sflo', 'sfhi', 'sfstep']) $(id).addEventListener('input', updateSfInfo);
420async function doExport() {
421 if (busy) return;
422 setBusy(true, 'Rendering samples…');
423 try {
424 const { lo, hi, step } = sfRange();
425 const name = $('sfname').value.trim() || 'Marimba';
426 const t0 = performance.now();
427 const r = await exportSF2({
428 lo, hi, step, name, sampleRate: 44100, mat: mat(), designFor,
429 sound: { eta: P.eta, slope: P.slope, res: res() }, malletFor, strike: strikeF,
430 onProgress: (f, k) => { $('bar').style.width = (f * 100).toFixed(1) + '%'; $('status').textContent = `Rendering ${noteName(k)} · ${(f * 100).toFixed(0)}%`; },
431 });
432 lastExport = r.bytes;
433 const blob = new Blob([r.bytes], { type: 'audio/x-soundfont' });
434 const a = document.createElement('a');
435 a.href = URL.createObjectURL(blob);
436 a.download = name.replace(/[^\w\- ]+/g, '_') + '.sf2';
437 a.click();
438 setTimeout(() => URL.revokeObjectURL(a.href), 10000);
439 markKeys();
440 setBusy(false, `Exported ${a.download}: ${r.nSamples} samples, ${(r.bytes.length / 1e6).toFixed(1)} MB, ${noteName(lo)}–${noteName(hi)} (${((performance.now() - t0) / 1000).toFixed(1)} s).`);
441 } catch (e) {
442 console.error(e);
443 setBusy(false, 'Export error: ' + e.message);
444 }
446let lastExport = null;
447$('export').onclick = doExport;
449$('strike').onclick = playStrike;
450window.addEventListener('keydown', (e) => {
451 if (['INPUT', 'SELECT', 'TEXTAREA'].includes(e.target.tagName) && e.target.type !== 'range' && e.target.type !== 'checkbox') return;
452 if (e.code === 'Space') { e.preventDefault(); playStrike(); }
453 if (e.code === 'ArrowLeft' || e.code === 'ArrowRight') {
454 if (e.target.type === 'range') return;
455 e.preventDefault();
456 selectNote(note + (e.code === 'ArrowLeft' ? -1 : 1));
457 playStrike();
458 }
459});
460window.addEventListener('resize', drawPlots);
462// for debugging in the console
463window.mb = { get prep() { return prep; }, get feModel() { return feModel; }, get fdModel() { return fdModel; }, get lastStrike() { return lastStrike; }, get lastExport() { return lastExport; }, designs, P };
465// ---------- start ----------
466// One fixed loudness scale (Pa -> full scale) so keys keep their relative loudness.
468 const b = designFor(60);
469 const p0 = prepare(feBarModel(b, mat()), { note: 60, eta: P.eta, slope: P.slope, res: res() });
470 const r = strike(p0, b.L / 2, b.W / 2, { ...MALLETS.medium, v0: 1.5 }, 48000);
471 let pk = 0;
472 for (const v of r.y) pk = Math.max(pk, Math.abs(v));
473 gain = 0.3 / (pk || 1);
475selectNote(60);
476if (!navigator.gpu) {
477 $('analyze').disabled = true;
478 $('info').textContent = 'WebGPU is not available in this browser (try Chrome or Safari 26+); the FE model still works.';
480$('status').textContent = 'Click the bar or a key to play. Each key is its own auto-tuned bar.';
↑↓ move↵openescclose