7b06bdfWoodblock strike simulator: modal model, FDTD mode analysis, SoundFont exportJeremy Magland 1import { DEFAULT_BLOCK, buildGrid, strikePatch, validateBlock } from './js/block.js';
2import { runFDTD, timeStep } from './js/fdtd.js';
3import { extractModes, modalStrike, residuesAt, spectrumDb, dominantFreq } from './js/modal.js';
4import { exportSF2, noteName, freqToMidi, LAYERS, VARIANTS } from './js/export.js';
5import { pitchScale } from './js/physics.js';
6import { BlockView } from './js/view3d.js';
7import { drawSpectrum, drawWave } from './js/plots.js';
9const $ = (id) => document.getElementById(id);
11// ---------- parameters ----------
12const LIVE = [
13 { key: 'pitch', label: 'Pitch', min: -12, max: 12, step: 0.1, value: 0, unit: 'st' },
14 { key: 'eta', label: 'Damping (loss factor)', min: 0.002, max: 0.05, step: 0.001, value: 0.012, unit: '' },
15 { key: 'hard', label: 'Mallet hardness log₁₀K', min: 6, max: 9.5, step: 0.05, value: 8, unit: '' },
16 { key: 'mass', label: 'Mallet mass', min: 5, max: 100, step: 1, value: 20, unit: 'g' },
17 { key: 'v0', label: 'Strike velocity', min: 0.2, max: 5, step: 0.1, value: 2, unit: 'm/s' },
18];
19const BLOCK = [
20 { key: 'L', label: 'Length', min: 100, max: 300, step: 1, unit: 'mm' },
21 { key: 'W', label: 'Depth', min: 40, max: 120, step: 1, unit: 'mm' },
22 { key: 'H', label: 'Height', min: 35, max: 100, step: 1, unit: 'mm' },
23 { key: 'wall', label: 'Wall thickness', min: 4, max: 15, step: 0.5, unit: 'mm' },
24 { key: 'top', label: 'Top plate', min: 3, max: 15, step: 0.5, unit: 'mm' },
25 { key: 'slotH', label: 'Slot height', min: 3, max: 15, step: 0.5, unit: 'mm' },
26 { key: 'inset', label: 'Slot end inset', min: 8, max: 60, step: 1, unit: 'mm' },
27 { key: 'rho', label: 'Density', min: 400, max: 1200, step: 5, unit: 'kg/m³' },
28 { key: 'EL', label: 'Stiffness E_L', min: 6, max: 20, step: 0.1, unit: 'GPa' },
29].map((p) => ({ ...p, value: DEFAULT_BLOCK[p.key] }));
31const P = {};
32function addSliders(container, defs, onChange) {
33 for (const d of defs) {
34 P[d.key] = d.value;
35 const row = document.createElement('label');
36 row.className = 'row';
37 row.innerHTML = `<span class="lab">${d.label}</span><input type="range" min="${d.min}" max="${d.max}" step="${d.step}" value="${d.value}" id="s_${d.key}"><span class="val" id="v_${d.key}"></span>`;
38 container.appendChild(row);
39 const inp = row.querySelector('input');
40 const show = () => ($(`v_${d.key}`).textContent = fmt(d, P[d.key]));
41 inp.addEventListener('input', () => { P[d.key] = parseFloat(inp.value); show(); onChange(d.key); });
42 show();
43 }
44}
45function fmt(d, v) {
46 if (d.key === 'hard') return v.toFixed(2);
47 if (d.key === 'pitch') return (v > 0 ? '+' : '') + v.toFixed(1) + ' st';
48 if (d.key === 'eta') return v.toFixed(3);
49 const dec = d.step < 0.1 ? 2 : d.step < 1 ? 1 : 0;
50 return v.toFixed(dec) + (d.unit ? ' ' + d.unit : '');
51}
52const block = () => Object.fromEntries(BLOCK.map((d) => [d.key, P[d.key]]));
53const liveParams = () => ({ pitch: pitchScale(P.pitch), eta: P.eta, K: 10 ** P.hard, m: P.mass / 1000, v0: P.v0 });
55// ---------- state ----------
56let model = null; // modal model
57let modelKey = ''; // block+dx the model was built for
58let strike = [DEFAULT_BLOCK.L / 2, DEFAULT_BLOCK.W / 2];
59let busy = false, cancel = false;
60let actx = null, gain = 1;
61let lastModal = null;
62let throughput = 0; // cell-steps per second, measured
63const ANALYSIS_DUR = 0.06; // s per analysis run
64let lastRes = null; // last analysis run (for debugging)
66const view = new BlockView($('view'), (x, y) => { strike = [x, y]; view.setStrike(x, y); updateInfo(); updateSfInfo(); playModal(); });
67const keyOf = () => JSON.stringify([block(), $('dx').value]);
69addSliders($('live'), LIVE, () => { updateInfo(); updateSfInfo(); });
70addSliders($('blockp'), BLOCK, () => onBlockChange());
71$('dx').addEventListener('change', () => { updateInfo(); });
73function onBlockChange() {
74 const b = block();
75 const errs = validateBlock(b);
76 $('warn').textContent = errs.join('; ');
77 if (errs.length) return;
78 strike = [Math.min(strike[0], b.L), Math.min(strike[1], b.W)];
79 view.setBlock(b);
80 view.setStrike(...strike);
81 updateInfo();
82}
84function updateInfo() {
85 const b = block();
86 const dx = parseFloat($('dx').value);
87 const stale = model && modelKey !== keyOf();
88 $('stale').hidden = !stale;
89 $('strikepos').textContent = `${strike[0].toFixed(0)}, ${strike[1].toFixed(0)} mm`;
90 if (validateBlock(b).length) return;
91 const nx = Math.ceil(b.L / dx) + 2 * (10 + Math.ceil(20 / dx));
92 const ny = Math.ceil(b.W / dx) + 2 * (10 + Math.ceil(20 / dx));
93 const nz = Math.ceil(b.H / dx) + 2 * (10 + Math.ceil(20 / dx));
94 const dt = timeStep(b, dx);
95 const steps = 3 * Math.ceil(ANALYSIS_DUR / dt);
96 const cells = nx * ny * nz;
97 const est = throughput ? ` · est. ${Math.round((cells * steps) / throughput)} s` : '';
98 $('info').textContent = `analysis grid ${nx}×${ny}×${nz} = ${(cells / 1e6).toFixed(2)} M cells · ${steps.toLocaleString()} steps${est}`;
99}
101// ---------- audio ----------
102function audio() {
103 if (!actx) actx = new AudioContext();
104 if (actx.state === 'suspended') actx.resume();
105 return actx;
106}
107function play(y, sr) {
108 const ctx = audio();
109 const buf = ctx.createBuffer(1, y.length, sr);
110 const ch = buf.getChannelData(0);
111 for (let i = 0; i < y.length; i++) ch[i] = Math.max(-1, Math.min(1, y[i] * gain));
112 const src = ctx.createBufferSource();
113 src.buffer = buf;
114 src.connect(ctx.destination);
115 src.start();
116}
118function playModal() {
119 if (!model) return;
120 const sr = audio().sampleRate;
121 const r = modalStrike(model, strike[0], strike[1], liveParams(), sr);
122 lastModal = { y: r.y, sr };
123 view.hit();
124 play(r.y, sr);
125 $('contact').textContent = `contact ${(r.T * 1000).toFixed(2)} ms, peak force ${r.Fm.toFixed(0)} N`;
126 drawPlots();
127}
129function drawPlots() {
130 const series = [], waves = [];
131 if (lastModal) {
132 series.push({ name: 'modal', ...spectrumDb(lastModal.y, lastModal.sr) });
133 waves.push({ name: 'modal', ...lastModal });
134 }
135 const marks = model ? model.modes.map((m) => m.f * pitchScale(P.pitch)) : [];
136 drawSpectrum($('spec'), series, marks);
137 drawWave($('wave'), waves, 0.2);
138}
140// ---------- simulations ----------
141function setBusy(b, label = '') {
142 busy = b;
143 for (const id of ['analyze', 'export']) $(id).disabled = b;
144 $('cancel').hidden = !b;
145 $('status').textContent = label;
146 if (!b) $('bar').style.width = '0%';
147}
148const progress = (label) => (f, sec) => {
149 $('bar').style.width = (f * 100).toFixed(1) + '%';
150 const eta = f > 0.01 ? Math.round((sec / f) * (1 - f)) : '…';
151 $('status').textContent = `${label} ${(f * 100).toFixed(0)}% · ${eta} s left`;
152};
154async function analyze() {
155 if (busy) return;
156 const b = block();
157 if (validateBlock(b).length) return;
158 const dx = parseFloat($('dx').value);
159 setBusy(true, 'Analyzing…');
160 cancel = false;
161 try {
162 const grid = buildGrid(b, dx);
163 // run 1: source at the mic (sound); runs 2-3: force at two reference points (contact)
164 const refs = [[0.27, 0.38], [0.61, 0.77]].map(([fx, fy]) => {
165 const x = fx * b.L, y = fy * b.W;
166 const ib = Math.round(x / dx - 0.5), jb = Math.round(y / dx - 0.5);
167 return { x, y, surf: grid.surfIndex[ib + grid.nbx * jb], patch: strikePatch(grid, x, y) };
168 });
169 const jobs = [{ mode: 'analysis' }, ...refs.map((r) => ({ mode: 'impulse', patch: r.patch }))];
170 const runs = [];
171 let secs = 0;
172 for (let k = 0; k < jobs.length; k++) {
173 const res = await runFDTD({
174 block: b, grid, ...jobs[k], duration: ANALYSIS_DUR, stiffScale: 1, eta: 0, recRate: 48000,
175 onProgress: progress(`Analysis ${k + 1}/${jobs.length} (FDTD)`), isCancelled: () => cancel,
176 });
177 if (!res) { setBusy(false, 'Cancelled.'); return; }
178 throughput = (grid.N * res.nSteps) / res.seconds;
179 secs += res.seconds;
180 runs.push(res);
181 }
182 const res = { seconds: secs, nSteps: runs.reduce((a, r) => a + r.nSteps, 0) };
183 $('status').textContent = 'Extracting modes…';
184 await new Promise((r) => setTimeout(r, 20));
185 lastRes = { runs, grid, refs };
186 model = extractModes(runs, grid, refs);
187 modelKey = keyOf();
188 // loudness normalization from a reference modal strike
189 const ref = modalStrike(model, b.L / 2, b.W / 2, { pitch: 1, eta: 0.012, K: 1e8, m: 0.02, v0: 2 }, 48000);
190 gain = 0.35 / Math.max(1e-12, ...ref.y.map(Math.abs));
191 fillModeList();
192 updateSfInfo();
193 setBusy(false, `Found ${model.modes.length} modes in ${res.seconds.toFixed(1)} s (${res.nSteps.toLocaleString()} steps). Click the top face to strike.`);
194 updateInfo();
195 drawPlots();
196 } catch (e) {
197 console.error(e);
198 setBusy(false, 'Error: ' + e.message);
199 }
200}
202function fillModeList() {
203 const sel = $('overlay');
204 sel.innerHTML = '<option value="-1">none</option>' +
205 model.modes.map((m, i) => `<option value="${i}">${i + 1}: ${m.f.toFixed(0)} Hz</option>`).join('');
206 view.setOverlay(0, 0, null);
207}
209$('overlay').addEventListener('change', () => {
210 const i = parseInt($('overlay').value, 10);
211 if (!model || i < 0) { view.setOverlay(0, 0, null); return; }
212 const m = model.modes[i];
213 // rotate phase so the largest residue is real, then show the real part
214 let best = 0, br = 0, bi = 0;
215 for (let n = 0; n < m.re.length; n++) {
216 const a = m.re[n] ** 2 + m.im[n] ** 2;
217 if (a > best) { best = a; br = m.re[n]; bi = m.im[n]; }
218 }
219 const s = Math.sqrt(best) || 1;
220 const vals = new Float32Array(model.nbx * model.nby);
221 for (let k = 0; k < vals.length; k++) {
222 const n = model.surfIndex[k];
223 if (n >= 0) vals[k] = (m.re[n] * br + m.im[n] * bi) / (s * s);
224 }
225 view.setOverlay(model.nbx, model.nby, vals);
226});
228// ---------- SoundFont export ----------
229function sfRange() {
230 let lo = parseInt($('sflo').value, 10), hi = parseInt($('sfhi').value, 10);
231 if (hi < lo) [lo, hi] = [hi, lo];
232 return { lo, hi, step: parseInt($('sfstep').value, 10) };
233}
234function updateSfInfo() {
235 const { lo, hi, step } = sfRange();
236 $('sflo_v').textContent = noteName(parseInt($('sflo').value, 10));
237 $('sfhi_v').textContent = noteName(parseInt($('sfhi').value, 10));
238 const nKeys = Math.floor((hi - lo) / step) + 1 + ((hi - lo) % step > step / 2 ? 1 : 0);
239 const n = nKeys * LAYERS * VARIANTS;
240 let pitch = '';
241 if (model) {
242 const f = dominantFreq(model, strike[0], strike[1], liveParams());
243 pitch = `Block rings at ${f.toFixed(0)} Hz (≈ ${noteName(Math.round(freqToMidi(f)))}); keys retune it. `;
244 }
245 $('sfinfo').textContent = `${pitch}${n} samples: ${nKeys} keys × ${LAYERS} velocity layers × ${VARIANTS} strike-point variations. ` +
246 'Uses the current damping, mallet and strike point; strike velocity sets the loudest layer.';
247}
248for (const id of ['sflo', 'sfhi', 'sfstep']) $(id).addEventListener('input', updateSfInfo);
250async function doExport() {
251 if (busy || !model) return;
252 if (modelKey !== keyOf()) $('status').textContent = 'Note: block changed since analysis; exporting the analyzed block.';
253 setBusy(true, 'Rendering samples…');
254 try {
255 const { lo, hi, step } = sfRange();
256 const name = $('sfname').value.trim() || 'Woodblock';
257 const lp = liveParams();
258 const t0 = performance.now();
259 const r = await exportSF2({
260 model, block: block(), strike, live: lp, lo, hi, step, name, sampleRate: 44100,
261 onProgress: (f) => { $('bar').style.width = (f * 100).toFixed(1) + '%'; $('status').textContent = `Rendering samples ${(f * 100).toFixed(0)}%`; },
262 });
263 lastExport = r.bytes;
264 const blob = new Blob([r.bytes], { type: 'audio/x-soundfont' });
265 const a = document.createElement('a');
266 a.href = URL.createObjectURL(blob);
267 a.download = name.replace(/[^\w\- ]+/g, '_') + '.sf2';
268 a.click();
269 setTimeout(() => URL.revokeObjectURL(a.href), 10000);
270 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).`);
271 } catch (e) {
272 console.error(e);
273 setBusy(false, 'Export error: ' + e.message);
274 }
275}
276let lastExport = null;
277$('export').onclick = doExport;
279$('analyze').onclick = analyze;
280$('cancel').onclick = () => (cancel = true);
281$('strike').onclick = playModal;
282window.addEventListener('keydown', (e) => {
283 if (e.code === 'Space' && e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT') { e.preventDefault(); playModal(); }
284});
285window.addEventListener('resize', drawPlots);
287// for debugging in the console
288window.wb = { get model() { return model; }, get lastRes() { return lastRes; }, get lastModal() { return lastModal; }, get lastExport() { return lastExport; }, residuesAt, extractModes, P };
290onBlockChange();
291drawPlots();
292updateSfInfo();
293if (!navigator.gpu) {
294 $('status').textContent = 'WebGPU is not available in this browser (try Chrome or Safari 26+).';
295 $('analyze').disabled = $('export').disabled = true;
296} else {
297 analyze();
298}