Woodblock strike simulator: modal model, FDTD mode analysis, SoundFont export
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 changed files+1827−0
.gitignoreadded+3−0View file
@@ -0,0 +1,3 @@
1+.claude/
2+node_modules/
3+.DS_Store
README.mdadded+29−0View file
@@ -0,0 +1,29 @@
1+# Woodblock
2+
3+Interactive woodblock played by real-time modal synthesis. The modes come from a 3D FDTD analysis of the block (WebGPU).
4+
5+```bash
6+npm run dev # http://127.0.0.1:8020
7+```
8+
9+Needs a browser with WebGPU (Chrome, Safari 26+). three.js loads from jsDelivr (pinned 0.169.0).
10+
11+## Model
12+
13+- **Mode analysis** (`js/fdtd.js`): undamped staggered-grid velocity–stress solver, orthotropic wood (grain along length) and air on one grid (air = μ 0, λ = ρc²), sponge boundary. Three short runs record vertical velocity at every top-face node: one with a volume-velocity pulse at the mic, 12 mm in front of the slot (by reciprocity, mic pressure per unit force at every strike point), and two with a force pulse at reference points on the top (surface mobility, for the mallet contact).
14+- **Modes** (`js/modal.js`): peaks from the combined spectra, radiation decay from two half windows, complex residues by a least-squares fit with those poles.
15+- **Strike**: Hertz mallet (F = K δ^1.5) simulated against the modal surface at the strike point; the contact force drives the modes. Damping: Rayleigh law fitted to the loss factor at 400 Hz and 4 kHz (`js/physics.js`), plus each mode's radiation decay.
16+
17+## Controls
18+
19+- Live: pitch (scales every mode frequency), loss factor, mallet hardness, mass, velocity, strike point (click the top face).
20+- Block geometry, density and E_L need **Analyze modes** again (about 40–60 s at 3 mm on an Apple GPU; 4 mm is faster).
21+
22+## SoundFont export
23+
24+**Export .sf2** renders a chromatic instrument from the modal model (`js/export.js`, `js/sf2.js`):
25+
26+- Keys: each sampled key is the block retuned so its loudest ringing mode lands exactly on that note. Samples every 1–6 semitones; the player pitch-shifts in between.
27+- Velocity: 4 layers; harder layers use a faster strike and a harder mallet (K down to ~0.25× at the softest layer). The velocity slider sets the loudest layer. The default SoundFont velocity-to-volume curve is turned off so loudness comes from the samples themselves (some players may ignore that).
28+- Variation: SF2 has no round-robin, so each layer is split into 3 narrow velocity bands sampled from strike points a few mm apart.
29+- Preset is GM program 116 (Wood Block), bank 0.
index.htmladded+66−0View file
@@ -0,0 +1,66 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+ <meta charset="utf-8">
5+ <meta name="viewport" content="width=device-width, initial-scale=1">
6+ <title>Woodblock Lab</title>
7+ <link rel="stylesheet" href="style.css">
8+ <script type="importmap">
9+ {
10+ "imports": {
11+ "three": "https://cdn.jsdelivr.net/npm/three@0.169.0/build/three.module.js",
12+ "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.169.0/examples/jsm/"
13+ }
14+ }
15+ </script>
16+</head>
17+<body>
18+ <main>
19+ <section class="stage">
20+ <div id="view"></div>
21+ <div class="hint">Click the top face to strike · Space repeats · drag to orbit</div>
22+ <div class="plots">
23+ <div class="plot"><div class="ptitle">Spectrum</div><canvas id="spec"></canvas></div>
24+ <div class="plot"><div class="ptitle">Waveform (first 200 ms)</div><canvas id="wave"></canvas></div>
25+ </div>
26+ </section>
27+ <aside class="panel">
28+ <h1>Woodblock</h1>
29+ <div class="actions">
30+ <button id="strike">Strike</button>
31+ </div>
32+ <div class="progress"><div id="bar"></div></div>
33+ <div class="status"><span id="status"></span> <button id="cancel" class="small" hidden>Cancel</button></div>
34+
35+ <h2>Strike & sound <small>live</small></h2>
36+ <div class="kv"><span>Strike point</span><span id="strikepos"></span></div>
37+ <div id="live"></div>
38+ <div class="kv muted"><span id="contact"></span></div>
39+
40+ <h2>Block <small>needs re-analysis</small></h2>
41+ <div id="blockp"></div>
42+ <div id="warn" class="warn"></div>
43+ <div id="stale" class="warn" hidden>Block changed since the last analysis. The modal sound uses the old modes.</div>
44+
45+ <h2>Mode analysis <small>FDTD</small></h2>
46+ <label class="row"><span class="lab">Grid spacing</span>
47+ <select id="dx"><option value="4">4 mm (fast)</option><option value="3" selected>3 mm</option><option value="2">2 mm (slow)</option></select><span></span>
48+ </label>
49+ <div class="info" id="info"></div>
50+ <div class="actions"><button id="analyze">Analyze modes</button></div>
51+ <label class="row"><span class="lab">Show mode on top</span><select id="overlay"><option value="-1">none</option></select><span></span></label>
52+
53+ <h2>Export instrument <small>SoundFont .sf2</small></h2>
54+ <label class="row"><span class="lab">Name</span><input id="sfname" type="text" value="Woodblock"><span></span></label>
55+ <label class="row"><span class="lab">Lowest key</span><input id="sflo" type="range" min="24" max="108" step="1" value="48"><span class="val" id="sflo_v"></span></label>
56+ <label class="row"><span class="lab">Highest key</span><input id="sfhi" type="range" min="24" max="108" step="1" value="84"><span class="val" id="sfhi_v"></span></label>
57+ <label class="row"><span class="lab">Sample every</span>
58+ <select id="sfstep"><option value="1">1 semitone</option><option value="2">2 semitones</option><option value="3" selected>3 semitones</option><option value="4">4 semitones</option><option value="6">6 semitones</option></select><span></span>
59+ </label>
60+ <div class="info" id="sfinfo"></div>
61+ <div class="actions"><button id="export">Export .sf2</button></div>
62+ </aside>
63+ </main>
64+ <script type="module" src="main.js"></script>
65+</body>
66+</html>
js/block.jsadded+150−0View file
@@ -0,0 +1,150 @@
1+// Block geometry, wood material and voxel grid.
2+// Axes: x = length (grain, L), y = depth (front face at y=0, T), z = height (up, R).
3+
4+export const DEFAULT_BLOCK = {
5+ L: 200, W: 70, H: 60, // outer size, mm
6+ wall: 8, top: 7, // wall and top-plate thickness, mm
7+ slotH: 6, inset: 15, // slot height and end inset, mm
8+ rho: 705, EL: 12.6, // density kg/m^3, longitudinal modulus GPa
9+};
10+
11+export const AIR = { rho: 1.2, c: 343 };
12+
13+// Hard-maple-like orthotropic ratios (USDA Wood Handbook style), scaled by E_L.
14+export function woodStiffness(EL /* Pa */, scale = 1) {
15+ const E = EL * scale;
16+ const Ex = E, Ey = 0.065 * E, Ez = 0.132 * E; // L, T, R
17+ const nuLT = 0.476, nuLR = 0.424, nuRT = 0.774;
18+ const S = [
19+ [1 / Ex, -nuLT / Ex, -nuLR / Ex],
20+ [-nuLT / Ex, 1 / Ey, -nuRT / Ez],
21+ [-nuLR / Ex, -nuRT / Ez, 1 / Ez],
22+ ];
23+ const C = inv3(S);
24+ return {
25+ c11: C[0][0], c22: C[1][1], c33: C[2][2],
26+ c12: C[0][1], c13: C[0][2], c23: C[1][2],
27+ gxy: 0.063 * E, gxz: 0.111 * E, gyz: 0.02 * E,
28+ };
29+}
30+
31+function inv3(m) {
32+ const [a, b, c] = m[0], [d, e, f] = m[1], [g, h, i] = m[2];
33+ const A = e * i - f * h, B = -(d * i - f * g), Cc = d * h - e * g;
34+ const det = a * A + b * B + c * Cc;
35+ return [
36+ [A / det, -(b * i - c * h) / det, (b * f - c * e) / det],
37+ [B / det, (a * i - c * g) / det, -(a * f - c * d) / det],
38+ [Cc / det, -(a * h - b * g) / det, (a * e - b * d) / det],
39+ ];
40+}
41+
42+// Is the point (mm, block-local) inside wood?
43+export function isWood(b, x, y, z) {
44+ if (x < 0 || x > b.L || y < 0 || y > b.W || z < 0 || z > b.H) return false;
45+ const zTopIn = b.H - b.top;
46+ if (x > b.wall && x < b.L - b.wall && y > b.wall && y < b.W - b.wall && z > b.wall && z < zTopIn) return false;
47+ if (x > b.inset && x < b.L - b.inset && y <= b.wall && z > zTopIn - b.slotH && z < zTopIn) return false;
48+ return true;
49+}
50+
51+// Boxes [x0,x1,y0,y1,z0,z1] (mm) that make up the block, for rendering.
52+export function blockBoxes(b) {
53+ const zt = b.H - b.top, zs = zt - b.slotH;
54+ const boxes = [
55+ [0, b.L, 0, b.W, 0, b.wall],
56+ [0, b.L, 0, b.W, zt, b.H],
57+ [0, b.L, b.W - b.wall, b.W, b.wall, zt],
58+ [0, b.wall, 0, b.W - b.wall, b.wall, zt],
59+ [b.L - b.wall, b.L, 0, b.W - b.wall, b.wall, zt],
60+ [b.wall, b.L - b.wall, 0, b.wall, b.wall, zs],
61+ ];
62+ if (b.inset > b.wall) {
63+ boxes.push([b.wall, b.inset, 0, b.wall, zs, zt]);
64+ boxes.push([b.L - b.inset, b.L - b.wall, 0, b.wall, zs, zt]);
65+ }
66+ return boxes.filter((q) => q[1] > q[0] && q[3] > q[2] && q[5] > q[4]);
67+}
68+
69+export function validateBlock(b) {
70+ const e = [];
71+ if (b.wall * 2 >= Math.min(b.L, b.W)) e.push('walls too thick');
72+ if (b.top + b.slotH + b.wall >= b.H) e.push('top + slot + wall must be < height');
73+ if (b.inset < b.wall) e.push('slot inset must be ≥ wall');
74+ if (2 * b.inset >= b.L) e.push('slot inset too large');
75+ return e;
76+}
77+
78+export const MIC_OFFSET = 12; // mm in front of the slot
79+
80+export function micPos(b) {
81+ return [b.L / 2, -MIC_OFFSET, b.H - b.top - b.slotH / 2];
82+}
83+
84+// Voxelize block + surrounding air. dx in mm.
85+export function buildGrid(b, dx, margin = 20, ns = 10) {
86+ const mc = Math.ceil(margin / dx); // air margin (mm -> cells); ns = sponge cells
87+ const pad = ns + mc;
88+ const nbx = Math.ceil(b.L / dx), nby = Math.ceil(b.W / dx), nbz = Math.ceil(b.H / dx);
89+ const nx = nbx + 2 * pad, ny = nby + 2 * pad, nz = nbz + 2 * pad;
90+ const o = pad * dx; // block origin offset (mm)
91+ const N = nx * ny * nz;
92+ const mat = new Uint32Array(N);
93+ for (let k = 0; k < nz; k++) {
94+ const z = (k + 0.5) * dx - o;
95+ for (let j = 0; j < ny; j++) {
96+ const y = (j + 0.5) * dx - o;
97+ for (let i = 0; i < nx; i++) {
98+ const x = (i + 0.5) * dx - o;
99+ if (isWood(b, x, y, z)) mat[i + nx * (j + ny * k)] = 1;
100+ }
101+ }
102+ }
103+ const id = (i, j, k) => i + nx * (j + ny * k);
104+ // Top-surface vz nodes: one per block column (node above topmost wood cell).
105+ const surf = []; // node indices
106+ const surfIJ = []; // [ib, jb] block-column indices
107+ const kTop = new Int32Array(nbx * nby).fill(-1);
108+ for (let jb = 0; jb < nby; jb++) {
109+ for (let ib = 0; ib < nbx; ib++) {
110+ const i = ib + pad, j = jb + pad;
111+ for (let k = nz - 2; k > 0; k--) {
112+ if (mat[id(i, j, k)] === 1) { kTop[ib + nbx * jb] = k; break; }
113+ }
114+ }
115+ }
116+ const surfIndex = new Int32Array(nbx * nby).fill(-1);
117+ for (let jb = 0; jb < nby; jb++) {
118+ for (let ib = 0; ib < nbx; ib++) {
119+ const k = kTop[ib + nbx * jb];
120+ if (k < 0) continue;
121+ surfIndex[ib + nbx * jb] = surf.length;
122+ surf.push(id(ib + pad, jb + pad, k));
123+ surfIJ.push([ib, jb]);
124+ }
125+ }
126+ const mp = micPos(b);
127+ const mi = Math.floor((mp[0] + o) / dx), mj = Math.floor((mp[1] + o) / dx), mk = Math.floor((mp[2] + o) / dx);
128+ const micIdx = id(mi, mj, mk);
129+ let nWood = 0;
130+ for (let n = 0; n < N; n++) nWood += mat[n];
131+ return { nx, ny, nz, N, dx, ns, pad, o, nbx, nby, mat, surf: Uint32Array.from(surf), surfIJ, surfIndex, kTop, micIdx, nWood, id };
132+}
133+
134+// Gaussian force patch around strike point (mm) on the top surface.
135+export function strikePatch(grid, sx, sy) {
136+ const ib0 = Math.round(sx / grid.dx - 0.5), jb0 = Math.round(sy / grid.dx - 0.5);
137+ const idx = [], w = [];
138+ for (let dj = -2; dj <= 2; dj++) {
139+ for (let di = -2; di <= 2; di++) {
140+ const ib = ib0 + di, jb = jb0 + dj;
141+ if (ib < 0 || jb < 0 || ib >= grid.nbx || jb >= grid.nby) continue;
142+ const s = grid.surfIndex[ib + grid.nbx * jb];
143+ if (s < 0) continue;
144+ idx.push(grid.surf[s]);
145+ w.push(Math.exp(-(di * di + dj * dj) / 2));
146+ }
147+ }
148+ const sum = w.reduce((a, c) => a + c, 0);
149+ return { idx: Uint32Array.from(idx), w: Float32Array.from(w.map((v) => v / sum)) };
150+}
js/export.jsadded+85−0View file
@@ -0,0 +1,85 @@
1+// Render a chromatic, velocity-layered woodblock SoundFont from the modal model.
2+
3+import { modalStrike, dominantFreq } from './modal.js';
4+import { buildSF2 } from './sf2.js';
5+
6+const NOTE = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
7+export const noteName = (k) => NOTE[k % 12] + (Math.floor(k / 12) - 1);
8+export const freqToMidi = (f) => 69 + 12 * Math.log2(f / 440);
9+
10+export const LAYERS = 4; // velocity layers
11+export const VARIANTS = 3; // strike-point variations, interleaved in velocity
12+const RR_OFFSETS = [[0, 0], [5, -3], [-4, 4]]; // mm
13+
14+/**
15+ * opts: { model, block, strike:[x,y], live:{eta,K,m,v0}, lo, hi, step, sampleRate, name,
16+ * onProgress(frac) }
17+ */
18+export async function exportSF2(opts) {
19+ const { model, block, live, lo, hi, step, name } = opts;
20+ const sr = opts.sampleRate ?? 44100;
21+ const fRef = dominantFreq(model, opts.strike[0], opts.strike[1], live);
22+
23+ // sampled keys and the key range each one covers
24+ const keys = [];
25+ for (let k = lo; k <= hi; k += step) keys.push(k);
26+ if (keys[keys.length - 1] !== hi && hi - keys[keys.length - 1] > step / 2) keys.push(hi);
27+ const ranges = keys.map((k, i) => [
28+ i === 0 ? lo : Math.floor((keys[i - 1] + k) / 2) + 1,
29+ i === keys.length - 1 ? hi : Math.floor((k + keys[i + 1]) / 2),
30+ ]);
31+
32+ // velocity bands: LAYERS x VARIANTS equal slices of 1..127
33+ const nBands = LAYERS * VARIANTS;
34+ const band = (b) => [1 + Math.floor((b * 127) / nBands), Math.floor(((b + 1) * 127) / nBands)];
35+
36+ const pts = RR_OFFSETS.map(([dx, dy]) => [
37+ Math.min(block.L - 3, Math.max(3, opts.strike[0] + dx)),
38+ Math.min(block.W - 3, Math.max(3, opts.strike[1] + dy)),
39+ ]);
40+
41+ const raw = [], zones = [];
42+ const total = keys.length * nBands;
43+ let done = 0, peak = 0;
44+ for (let ki = 0; ki < keys.length; ki++) {
45+ const k = keys[ki];
46+ const pitch = (440 * 2 ** ((k - 69) / 12)) / fRef;
47+ for (let b = 0; b < nBands; b++) {
48+ const layer = Math.floor(b / VARIANTS), rr = b % VARIANTS;
49+ const x = (layer + 1) / LAYERS;
50+ const p = { pitch, eta: live.eta, m: live.m, v0: live.v0 * (0.12 + 0.88 * x), K: live.K * 10 ** (0.6 * (x - 1)) };
51+ const { y } = modalStrike(model, pts[rr][0], pts[rr][1], p, sr, 2.5);
52+ for (let i = 0; i < y.length; i++) peak = Math.max(peak, Math.abs(y[i]));
53+ const [vlo, vhi] = band(b);
54+ zones.push({ keyLo: ranges[ki][0], keyHi: ranges[ki][1], velLo: vlo, velHi: vhi, sample: raw.length });
55+ raw.push({ y, root: k, name: `wb${k}v${layer + 1}r${rr + 1}` });
56+ done++;
57+ if (done % 4 === 0) {
58+ opts.onProgress?.(done / total);
59+ await new Promise((r) => setTimeout(r, 0));
60+ }
61+ }
62+ }
63+
64+ // one global gain so velocity layers keep their physical loudness; trim tails at -72 dB
65+ const g = (0.89 * 32767) / (peak || 1);
66+ const floor = peak * 10 ** (-72 / 20);
67+ const fade = Math.round(0.005 * sr);
68+ const samples = raw.map((s) => {
69+ let end = s.y.length - 1;
70+ while (end > 0 && Math.abs(s.y[end]) < floor) end--;
71+ const n = Math.min(s.y.length, end + fade);
72+ const d = new Int16Array(n);
73+ for (let i = 0; i < n; i++) {
74+ const fo = i > n - fade ? (n - i) / fade : 1;
75+ d[i] = Math.max(-32768, Math.min(32767, Math.round(s.y[i] * g * fo)));
76+ }
77+ return { name: s.name, data: d, root: s.root };
78+ });
79+
80+ const bytes = buildSF2({
81+ name, bank: 0, program: 115, sampleRate: sr, samples, zones,
82+ releaseSec: 2.5, disableVelocityAttenuation: true,
83+ });
84+ return { bytes, fRef, keys, nSamples: samples.length };
85+}
js/fdtd.jsadded+308−0View file
@@ -0,0 +1,308 @@
1+// 3D staggered-grid (velocity-stress) FDTD on WebGPU for orthotropic wood + air, used
2+// only to find the block's modes (undamped; the modal model adds damping itself).
3+// Air cells use mu = 0, lambda = rho c^2, so one kernel handles both media.
4+// mode 1 = 'analysis': volume-velocity pulse at the mic, record vz at every top-surface
5+// node (by reciprocity this gives mic pressure per unit force at every strike point).
6+// mode 2 = 'impulse': half-sine force pulse on a patch, record vz at every top-surface node
7+// (surface mobility, used for the modal model's contact dynamics).
8+
9+import { AIR, woodStiffness } from './block.js';
10+
11+const WGSL = /* wgsl */ `
12+struct P {
13+ nx:u32, ny:u32, nz:u32, N:u32,
14+ dx:f32, dt:f32, rhoW:f32, rhoA:f32,
15+ c11:f32, c22:f32, c33:f32, c12:f32,
16+ c13:f32, c23:f32, gxy:f32, gxz:f32,
17+ gyz:f32, lamA:f32, ns:f32, dmax:f32,
18+ mode:u32, pulseT:f32, pulseA:f32, nPatch:u32,
19+ micIdx:u32, nRec:u32, decim:u32, nSurf:u32,
20+};
21+@group(0) @binding(0) var<uniform> p: P;
22+@group(0) @binding(1) var<storage, read_write> fld: array<f32>;
23+@group(0) @binding(2) var<storage, read> mat: array<u32>;
24+@group(0) @binding(3) var<storage, read_write> state: array<f32>;
25+@group(0) @binding(4) var<storage, read> idxs: array<u32>;
26+@group(0) @binding(5) var<storage, read> patchW: array<f32>;
27+@group(0) @binding(6) var<storage, read_write> outb: array<f32>;
28+@group(0) @binding(7) var<storage, read_write> acc: array<f32>;
29+
30+const VX = 0u; const VY = 1u; const VZ = 2u;
31+const SXX = 3u; const SYY = 4u; const SZZ = 5u;
32+const SXY = 6u; const SXZ = 7u; const SYZ = 8u;
33+
34+fn id(i:u32, j:u32, k:u32) -> u32 { return i + p.nx * (j + p.ny * k); }
35+fn fv(c:u32, n:u32) -> f32 { return fld[c * p.N + n]; }
36+fn isW(n:u32) -> bool { return mat[n] == 1u; }
37+fn rho(n:u32) -> f32 { return select(p.rhoA, p.rhoW, isW(n)); }
38+
39+fn sponge(i:u32, j:u32, k:u32) -> f32 {
40+ let x = f32(i); let y = f32(j); let z = f32(k);
41+ let dxs = max(max(p.ns - x, x - (f32(p.nx) - 1.0 - p.ns)), 0.0);
42+ let dys = max(max(p.ns - y, y - (f32(p.ny) - 1.0 - p.ns)), 0.0);
43+ let dzs = max(max(p.ns - z, z - (f32(p.nz) - 1.0 - p.ns)), 0.0);
44+ let r2 = (dxs * dxs + dys * dys + dzs * dzs) / (p.ns * p.ns);
45+ return exp(-p.dmax * r2 * p.dt);
46+}
47+
48+fn inside(g:vec3u) -> bool {
49+ return g.x >= 1u && g.y >= 1u && g.z >= 1u && g.x < p.nx - 1u && g.y < p.ny - 1u && g.z < p.nz - 1u;
50+}
51+
52+@compute @workgroup_size(8, 8, 4)
53+fn vel(@builtin(global_invocation_id) g: vec3u) {
54+ if (!inside(g)) { return; }
55+ let c = id(g.x, g.y, g.z);
56+ let sx = 1u; let sy = p.nx; let sz = p.nx * p.ny;
57+ let h = p.dt / p.dx;
58+ let sp = sponge(g.x, g.y, g.z);
59+ {
60+ let n = c + sx;
61+ let d = fv(SXX, n) - fv(SXX, c) + fv(SXY, c) - fv(SXY, c - sy) + fv(SXZ, c) - fv(SXZ, c - sz);
62+ fld[VX * p.N + c] = sp * (fv(VX, c) + 2.0 * h * d / (rho(c) + rho(n)));
63+ }
64+ {
65+ let n = c + sy;
66+ let d = fv(SXY, c) - fv(SXY, c - sx) + fv(SYY, n) - fv(SYY, c) + fv(SYZ, c) - fv(SYZ, c - sz);
67+ fld[VY * p.N + c] = sp * (fv(VY, c) + 2.0 * h * d / (rho(c) + rho(n)));
68+ }
69+ {
70+ let n = c + sz;
71+ let d = fv(SXZ, c) - fv(SXZ, c - sx) + fv(SYZ, c) - fv(SYZ, c - sy) + fv(SZZ, n) - fv(SZZ, c);
72+ fld[VZ * p.N + c] = sp * (fv(VZ, c) + 2.0 * h * d / (rho(c) + rho(n)));
73+ }
74+}
75+
76+fn upd(comp:u32, n:u32, t:f32, sp:f32) {
77+ let i = comp * p.N + n;
78+ fld[i] = sp * (fld[i] + p.dt * t);
79+}
80+
81+@compute @workgroup_size(8, 8, 4)
82+fn str(@builtin(global_invocation_id) g: vec3u) {
83+ if (!inside(g)) { return; }
84+ let c = id(g.x, g.y, g.z);
85+ let sx = 1u; let sy = p.nx; let sz = p.nx * p.ny;
86+ let sp = sponge(g.x, g.y, g.z);
87+ let idx = 1.0 / p.dx;
88+ let wc = isW(c);
89+ let exx = (fv(VX, c) - fv(VX, c - sx)) * idx;
90+ let eyy = (fv(VY, c) - fv(VY, c - sy)) * idx;
91+ let ezz = (fv(VZ, c) - fv(VZ, c - sz)) * idx;
92+ var c11 = p.lamA; var c22 = p.lamA; var c33 = p.lamA;
93+ var c12 = p.lamA; var c13 = p.lamA; var c23 = p.lamA;
94+ if (wc) { c11 = p.c11; c22 = p.c22; c33 = p.c33; c12 = p.c12; c13 = p.c13; c23 = p.c23; }
95+ upd(SXX, c, c11 * exx + c12 * eyy + c13 * ezz, sp);
96+ upd(SYY, c, c12 * exx + c22 * eyy + c23 * ezz, sp);
97+ upd(SZZ, c, c13 * exx + c23 * eyy + c33 * ezz, sp);
98+ // shear moduli at edges: harmonic mean of the 4 cells, i.e. 0 unless all are wood
99+ {
100+ let all = wc && isW(c + sx) && isW(c + sy) && isW(c + sx + sy);
101+ let e = (fv(VX, c + sy) - fv(VX, c) + fv(VY, c + sx) - fv(VY, c)) * idx;
102+ upd(SXY, c, select(0.0, p.gxy, all) * e, sp);
103+ }
104+ {
105+ let all = wc && isW(c + sx) && isW(c + sz) && isW(c + sx + sz);
106+ let e = (fv(VX, c + sz) - fv(VX, c) + fv(VZ, c + sx) - fv(VZ, c)) * idx;
107+ upd(SXZ, c, select(0.0, p.gxz, all) * e, sp);
108+ }
109+ {
110+ let all = wc && isW(c + sy) && isW(c + sz) && isW(c + sy + sz);
111+ let e = (fv(VY, c + sz) - fv(VY, c) + fv(VZ, c + sy) - fv(VZ, c)) * idx;
112+ upd(SYZ, c, select(0.0, p.gyz, all) * e, sp);
113+ }
114+}
115+
116+// Single-thread step: the source pulse (at the mic, or a force on the patch).
117+@compute @workgroup_size(1)
118+fn aux() {
119+ let s = state[0];
120+ let t = s * p.dt;
121+ let dx3 = p.dx * p.dx * p.dx;
122+ var A = 0.0;
123+ if (t < p.pulseT) { A = p.pulseA * sin(3.14159265 * t / p.pulseT); }
124+ if (p.mode == 2u) {
125+ // downward force A (N) spread over the patch's surface nodes
126+ let rs = 0.5 * (p.rhoW + p.rhoA);
127+ for (var n = 0u; n < p.nPatch; n++) {
128+ let q = VZ * p.N + idxs[n];
129+ fld[q] = fld[q] - p.dt * A * patchW[n] / (rs * dx3);
130+ }
131+ } else {
132+ // volume velocity A (m^3/s) at the mic cell
133+ let m = p.micIdx;
134+ let dS = p.dt * p.lamA * A / dx3;
135+ fld[SXX * p.N + m] -= dS;
136+ fld[SYY * p.N + m] -= dS;
137+ fld[SZZ * p.N + m] -= dS;
138+ }
139+ state[0] = s + 1.0;
140+}
141+
142+// Boxcar-decimated recording of vz at every top-surface node.
143+@compute @workgroup_size(64)
144+fn rec(@builtin(global_invocation_id) g: vec3u) {
145+ let n = g.x;
146+ if (n >= p.nSurf) { return; }
147+ let s = u32(state[0]); // steps completed
148+ var a = acc[n] + fld[VZ * p.N + idxs[p.nPatch + n]];
149+ if (s % p.decim == 0u) {
150+ let r = s / p.decim - 1u;
151+ if (r < p.nRec) { outb[r * p.nSurf + n] = a / f32(p.decim); }
152+ a = 0.0;
153+ }
154+ acc[n] = a;
155+}
156+`;
157+
158+let devicePromise = null;
159+export function getDevice() {
160+ if (!devicePromise) {
161+ devicePromise = (async () => {
162+ if (!navigator.gpu) throw new Error('WebGPU is not available in this browser.');
163+ const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
164+ if (!adapter) throw new Error('No WebGPU adapter found.');
165+ return adapter.requestDevice({
166+ requiredLimits: {
167+ maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
168+ maxBufferSize: adapter.limits.maxBufferSize,
169+ },
170+ });
171+ })();
172+ }
173+ return devicePromise;
174+}
175+
176+// Time step (CFL) for a grid spacing dx (mm) and stiffness scale.
177+export function timeStep(block, dx, stiffScale = 1) {
178+ const C = woodStiffness(block.EL * 1e9, stiffScale);
179+ const cmax = Math.sqrt(Math.max(C.c11, C.c22, C.c33) / block.rho);
180+ return (0.9 * dx * 1e-3) / (cmax * Math.sqrt(3));
181+}
182+
183+/**
184+ * Run one analysis simulation, recording vz at every top-surface node.
185+ * opts: { block, grid, mode: 'analysis'|'impulse', duration (s), stiffScale,
186+ * patch: {idx, w} (impulse), recRate, onProgress(frac, sec), isCancelled() }
187+ * Returns { dt, nSteps, data: Float32Array [nRec x nSurf], recRate, pulseT, pulseA, ... }.
188+ */
189+export async function runFDTD(opts) {
190+ const device = await getDevice();
191+ const { block, grid, mode } = opts;
192+ const modeId = { analysis: 1, impulse: 2 }[mode];
193+ if (!modeId) throw new Error(`unknown FDTD mode ${mode}`);
194+ const dt = timeStep(block, grid.dx, opts.stiffScale ?? 1);
195+ const nSteps = Math.ceil(opts.duration / dt);
196+ const C = woodStiffness(block.EL * 1e9, opts.stiffScale ?? 1);
197+ const lamA = AIR.rho * AIR.c * AIR.c;
198+ const dxm = grid.dx * 1e-3;
199+ const dmax = (3 * AIR.c * Math.log(1e3)) / (2 * grid.ns * dxm);
200+
201+ const decim = Math.max(1, Math.round(1 / (opts.recRate * dt)));
202+ const nRec = Math.floor(nSteps / decim);
203+ const nSurf = grid.surf.length;
204+ const patch = modeId === 2 ? opts.patch : { idx: new Uint32Array(0), w: new Float32Array(0) };
205+ const pulseT = 6e-5, pulseA = modeId === 1 ? 1e-6 : 1; // m^3/s (mic source) or N (force)
206+
207+ // Uniforms (order must match struct P)
208+ const U = new ArrayBuffer(112);
209+ const dv = new DataView(U);
210+ let off = 0;
211+ const u = (v) => { dv.setUint32(off, v, true); off += 4; };
212+ const f = (v) => { dv.setFloat32(off, v, true); off += 4; };
213+ u(grid.nx); u(grid.ny); u(grid.nz); u(grid.N);
214+ f(dxm); f(dt); f(block.rho); f(AIR.rho);
215+ f(C.c11); f(C.c22); f(C.c33); f(C.c12);
216+ f(C.c13); f(C.c23); f(C.gxy); f(C.gxz);
217+ f(C.gyz); f(lamA); f(grid.ns); f(dmax);
218+ u(modeId); f(pulseT); f(pulseA); u(patch.idx.length);
219+ u(grid.micIdx); u(nRec); u(decim); u(nSurf);
220+
221+ const usage = GPUBufferUsage;
222+ const mk = (size, use, data) => {
223+ const b = device.createBuffer({ size: Math.max(16, Math.ceil(size / 4) * 4), usage: use, mappedAtCreation: !!data });
224+ if (data) {
225+ new data.constructor(b.getMappedRange()).set(data);
226+ b.unmap();
227+ }
228+ return b;
229+ };
230+ const S = usage.STORAGE | usage.COPY_DST | usage.COPY_SRC;
231+ const uni = mk(U.byteLength, usage.UNIFORM | usage.COPY_DST);
232+ device.queue.writeBuffer(uni, 0, U);
233+ const fldB = mk(9 * grid.N * 4, S);
234+ const matB = mk(grid.N * 4, S, grid.mat);
235+ const stateB = mk(16, S, new Float32Array(4));
236+ const idxArr = new Uint32Array(Math.max(1, patch.idx.length + nSurf));
237+ idxArr.set(patch.idx, 0);
238+ idxArr.set(grid.surf, patch.idx.length);
239+ const idxB = mk(idxArr.byteLength, S, idxArr);
240+ const pw = new Float32Array(Math.max(1, patch.w.length));
241+ pw.set(patch.w);
242+ const pwB = mk(pw.byteLength, S, pw);
243+ const outLen = nRec * nSurf;
244+ const outB = mk(outLen * 4, S);
245+ const accB = mk(Math.max(1, nSurf) * 4, S);
246+
247+ const layout = device.createBindGroupLayout({
248+ entries: ['uniform', 'storage', 'read-only-storage', 'storage', 'read-only-storage', 'read-only-storage', 'storage', 'storage']
249+ .map((type, binding) => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type } })),
250+ });
251+ const bg = device.createBindGroup({
252+ layout,
253+ entries: [uni, fldB, matB, stateB, idxB, pwB, outB, accB].map((buffer, binding) => ({ binding, resource: { buffer } })),
254+ });
255+ const module = device.createShaderModule({ code: WGSL });
256+ const info = await module.getCompilationInfo();
257+ const errs = info.messages.filter((m) => m.type === 'error');
258+ if (errs.length) throw new Error('WGSL: ' + errs.map((m) => `${m.lineNum}: ${m.message}`).join('\n'));
259+ const plLayout = device.createPipelineLayout({ bindGroupLayouts: [layout] });
260+ const [pVel, pStr, pAux, pRec] = await Promise.all(
261+ ['vel', 'str', 'aux', 'rec'].map((e) =>
262+ device.createComputePipelineAsync({ layout: plLayout, compute: { module, entryPoint: e } })),
263+ );
264+
265+ const wg = [Math.ceil(grid.nx / 8), Math.ceil(grid.ny / 8), Math.ceil(grid.nz / 4)];
266+ const wgRec = Math.ceil(Math.max(1, nSurf) / 64);
267+ const chunk = 200;
268+ const t0 = performance.now();
269+ let cancelled = false;
270+ for (let s = 0; s < nSteps; s += chunk) {
271+ const enc = device.createCommandEncoder();
272+ const pass = enc.beginComputePass();
273+ pass.setBindGroup(0, bg);
274+ const n = Math.min(chunk, nSteps - s);
275+ for (let q = 0; q < n; q++) {
276+ pass.setPipeline(pVel); pass.dispatchWorkgroups(wg[0], wg[1], wg[2]);
277+ pass.setPipeline(pAux); pass.dispatchWorkgroups(1);
278+ pass.setPipeline(pStr); pass.dispatchWorkgroups(wg[0], wg[1], wg[2]);
279+ pass.setPipeline(pRec); pass.dispatchWorkgroups(wgRec);
280+ }
281+ pass.end();
282+ device.queue.submit([enc.finish()]);
283+ if ((s / chunk) % 10 === 9 || s + chunk >= nSteps) {
284+ await device.queue.onSubmittedWorkDone();
285+ const frac = Math.min(1, (s + n) / nSteps);
286+ opts.onProgress?.(frac, (performance.now() - t0) / 1000);
287+ if (opts.isCancelled?.()) { cancelled = true; break; }
288+ }
289+ }
290+
291+ let data = null;
292+ if (!cancelled) {
293+ const read = device.createBuffer({ size: outLen * 4, usage: usage.MAP_READ | usage.COPY_DST });
294+ const enc = device.createCommandEncoder();
295+ enc.copyBufferToBuffer(outB, 0, read, 0, outLen * 4);
296+ device.queue.submit([enc.finish()]);
297+ await read.mapAsync(GPUMapMode.READ);
298+ data = new Float32Array(read.getMappedRange().slice(0));
299+ read.unmap();
300+ read.destroy();
301+ }
302+ for (const b of [uni, fldB, matB, stateB, idxB, pwB, outB, accB]) b.destroy();
303+ if (cancelled) return null;
304+ return {
305+ dt, nSteps, data, decim, nRec, nSurf, pulseT, pulseA,
306+ recRate: 1 / (decim * dt), seconds: (performance.now() - t0) / 1000,
307+ };
308+}
js/modal.jsadded+364−0View file
@@ -0,0 +1,364 @@
1+// Mode extraction from the FDTD analysis run, and real-time modal synthesis.
2+
3+import { decayRate, halfSineFT, hertzPulse } from './physics.js';
4+
5+// ---------- FFT (radix-2, in place) ----------
6+export function fft(re, im) {
7+ const n = re.length;
8+ for (let i = 1, j = 0; i < n; i++) {
9+ let bit = n >> 1;
10+ for (; j & bit; bit >>= 1) j ^= bit;
11+ j ^= bit;
12+ if (i < j) {
13+ [re[i], re[j]] = [re[j], re[i]];
14+ [im[i], im[j]] = [im[j], im[i]];
15+ }
16+ }
17+ for (let len = 2; len <= n; len <<= 1) {
18+ const ang = (-2 * Math.PI) / len;
19+ const wr = Math.cos(ang), wi = Math.sin(ang);
20+ for (let i = 0; i < n; i += len) {
21+ let cr = 1, ci = 0;
22+ for (let k = 0; k < len / 2; k++) {
23+ const a = i + k, b = a + len / 2;
24+ const tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr;
25+ re[b] = re[a] - tr; im[b] = im[a] - ti;
26+ re[a] += tr; im[a] += ti;
27+ const t = cr * wr - ci * wi;
28+ ci = cr * wi + ci * wr;
29+ cr = t;
30+ }
31+ }
32+ }
33+}
34+
35+const nextPow2 = (n) => 1 << Math.ceil(Math.log2(n));
36+const hann = (n) => Float32Array.from({ length: n }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * (i + 0.5)) / n));
37+/**
38+ * Mode extraction from three FDTD runs that all record vz (up) at every top-surface node:
39+ * runs[0]: volume-velocity pulse at the mic. By reciprocity -vz/Qhat = mic pressure per
40+ * unit downward force at each strike point (residue R).
41+ * runs[1..]: downward force pulse at a reference point. vz/Fhat = surface mobility (residue V).
42+ * Poles come from the combined spectrum; residues from a least-squares fit with those poles.
43+ */
44+export function extractModes(runs, grid, refs, { maxModes = 120, fmin = 120, fmax = 12000 } = {}) {
45+ const { nRec, nSurf, recRate } = runs[0];
46+ const t = Float64Array.from({ length: nRec }, (_, r) => (r + 0.5) / recRate);
47+ const win = hann(nRec);
48+
49+ // 1. combined power spectrum (each run normalized)
50+ const nfft = nextPow2(nRec) * 4;
51+ const Ptot = new Float64Array(nfft / 2);
52+ const stride = Math.max(1, Math.floor(nSurf / 400));
53+ const re = new Float64Array(nfft), im = new Float64Array(nfft);
54+ for (const run of runs) {
55+ const P = new Float64Array(nfft / 2);
56+ for (let n = 0; n < nSurf; n += stride) {
57+ re.fill(0); im.fill(0);
58+ for (let r = 0; r < nRec; r++) re[r] = run.data[r * nSurf + n] * win[r];
59+ fft(re, im);
60+ for (let k = 0; k < nfft / 2; k++) P[k] += re[k] * re[k] + im[k] * im[k];
61+ }
62+ let m = 0;
63+ for (let k = 0; k < nfft / 2; k++) m = Math.max(m, P[k]);
64+ for (let k = 0; k < nfft / 2; k++) Ptot[k] += P[k] / m;
65+ }
66+ const df = recRate / nfft;
67+ const k0 = Math.max(2, Math.floor(fmin / df));
68+ const k1 = Math.min(nfft / 2 - 2, Math.floor(Math.min(fmax, 0.45 * recRate) / df));
69+ let pmax = 0;
70+ for (let k = k0; k <= k1; k++) pmax = Math.max(pmax, Ptot[k]);
71+ const span = Math.round(3 * (nfft / nRec));
72+ const peaks = [];
73+ for (let k = k0; k <= k1; k++) {
74+ if (Ptot[k] < pmax * 1e-6) continue;
75+ let ok = true;
76+ for (let q = Math.max(0, k - span); q <= Math.min(nfft / 2 - 1, k + span); q++) {
77+ if (q !== k && Ptot[q] > Ptot[k]) { ok = false; break; }
78+ }
79+ if (!ok) continue;
80+ const a = Math.log(Ptot[k - 1]), b = Math.log(Ptot[k]), c = Math.log(Ptot[k + 1]);
81+ const d = (0.5 * (a - c)) / (a - 2 * b + c);
82+ let lo = k, hi = k;
83+ while (lo > 1 && Ptot[lo - 1] > Ptot[k] / 2 && k - lo < 50 * span) lo--;
84+ while (hi < nfft / 2 - 2 && Ptot[hi + 1] > Ptot[k] / 2 && hi - k < 50 * span) hi++;
85+ peaks.push({ f: (k + (Number.isFinite(d) ? d : 0)) * df, p: Ptot[k] * (hi - lo + 1) });
86+ }
87+ peaks.sort((x, y) => y.p - x.p);
88+ const poles = peaks.slice(0, maxModes).sort((x, y) => x.f - y.f).map((pk) => ({ f: pk.f, w: 2 * Math.PI * pk.f }));
89+
90+ // 2. radiation decay per mode from two half-window DFTs (subset of points, all runs)
91+ const half = Math.floor(nRec / 2);
92+ const w1 = hann(half);
93+ const Dt = half / recRate;
94+ const sstride = Math.max(1, Math.floor(nSurf / 150));
95+ for (const pole of poles) {
96+ let P1 = 0, P2 = 0;
97+ for (const run of runs) {
98+ for (let n = 0; n < nSurf; n += sstride) {
99+ let ar = 0, ai = 0, br = 0, bi = 0;
100+ for (let r = 0; r < 2 * half; r++) {
101+ const c = Math.cos(pole.w * t[r]), s = Math.sin(pole.w * t[r]);
102+ const v = run.data[r * nSurf + n] * (r < half ? w1[r] : w1[r - half]);
103+ if (r < half) { ar += v * c; ai += v * s; } else { br += v * c; bi += v * s; }
104+ }
105+ P1 += ar * ar + ai * ai; P2 += br * br + bi * bi;
106+ }
107+ }
108+ const sig = P2 > 0 ? (0.5 * Math.log(P1 / P2)) / Dt : 0;
109+ pole.sig = Math.min(300, Math.max(0, Number.isFinite(sig) ? sig : 0));
110+ }
111+
112+ // 3. least-squares residues with the known poles
113+ const r0 = Math.ceil(2 * runs[0].pulseT * recRate); // skip the pulse itself
114+ const fits = runs.map((run) => lsFit(run.data, nRec, nSurf, t, r0, poles, recRate));
115+
116+ const modes = poles.map((pole, n) => {
117+ const [qr, qi] = halfSineFT(runs[0].pulseA, runs[0].pulseT, pole.w);
118+ const q2 = qr * qr + qi * qi;
119+ const Rre = new Float32Array(nSurf), Rim = new Float32Array(nSurf);
120+ let peak = 0;
121+ for (let s = 0; s < nSurf; s++) {
122+ const ar = fits[0].re[n * nSurf + s], ai = fits[0].im[n * nSurf + s];
123+ Rre[s] = -(ar * qr + ai * qi) / q2; // R = -A / Qhat
124+ Rim[s] = -(ai * qr - ar * qi) / q2;
125+ peak = Math.max(peak, Math.hypot(Rre[s], Rim[s]));
126+ }
127+ // mobility from the reference whose point moves most in this mode
128+ let best = null;
129+ for (let k = 1; k < runs.length; k++) {
130+ const [fr, fi] = halfSineFT(runs[k].pulseA, runs[k].pulseT, pole.w);
131+ const f2 = fr * fr + fi * fi;
132+ const Vre = new Float32Array(nSurf), Vim = new Float32Array(nSurf);
133+ let vmax = 0;
134+ for (let s = 0; s < nSurf; s++) {
135+ const ar = fits[k].re[n * nSurf + s], ai = fits[k].im[n * nSurf + s];
136+ Vre[s] = (ar * fr + ai * fi) / f2; // V = A / Fhat
137+ Vim[s] = (ai * fr - ar * fi) / f2;
138+ vmax = Math.max(vmax, Math.hypot(Vre[s], Vim[s]));
139+ }
140+ const sr = refs[k - 1].surf;
141+ const ratio = Math.hypot(Vre[sr], Vim[sr]) / (vmax || 1);
142+ if (!best || ratio > best.ratio) best = { ratio, Vre, Vim, vpp: [Vre[sr], Vim[sr]] };
143+ }
144+ return { f: pole.f, sigRad: pole.sig, re: Rre, im: Rim, peak, mob: best && best.ratio > 0.15 ? best : null };
145+ });
146+ return { modes, nbx: grid.nbx, nby: grid.nby, dx: grid.dx, surfIndex: grid.surfIndex };
147+}
148+
149+// Fit h(t) = sum_n Re(A_n e^{(i w_n - sig_n) t}) for every surface point (columns of data).
150+function lsFit(data, nRec, nSurf, t, r0, poles, recRate) {
151+ const M = poles.length, K = 2 * M, nT = nRec - r0;
152+ const B = new Float64Array(nT * K);
153+ for (let r = 0; r < nT; r++) {
154+ const tt = t[r + r0];
155+ for (let n = 0; n < M; n++) {
156+ const e = Math.exp(-poles[n].sig * tt);
157+ // boxcar decimation response
158+ const x = poles[n].w / (2 * recRate), bc = Math.sin(x) / x;
159+ B[r * K + 2 * n] = bc * e * Math.cos(poles[n].w * tt);
160+ B[r * K + 2 * n + 1] = -bc * e * Math.sin(poles[n].w * tt);
161+ }
162+ }
163+ const G = new Float64Array(K * K);
164+ for (let r = 0; r < nT; r++) {
165+ const o = r * K;
166+ for (let i = 0; i < K; i++) {
167+ const bi = B[o + i];
168+ for (let j = i; j < K; j++) G[i * K + j] += bi * B[o + j];
169+ }
170+ }
171+ let tr = 0;
172+ for (let i = 0; i < K; i++) tr += G[i * K + i];
173+ for (let i = 0; i < K; i++) {
174+ G[i * K + i] += (1e-9 * tr) / K;
175+ for (let j = 0; j < i; j++) G[i * K + j] = G[j * K + i];
176+ }
177+ const L = cholesky(G, K);
178+ // C = B^T H (K x nSurf)
179+ const C = new Float64Array(K * nSurf);
180+ for (let r = 0; r < nT; r++) {
181+ const o = (r + r0) * nSurf;
182+ for (let i = 0; i < K; i++) {
183+ const b = B[r * K + i];
184+ const ci = i * nSurf;
185+ for (let s = 0; s < nSurf; s++) C[ci + s] += b * data[o + s];
186+ }
187+ }
188+ // solve L L^T X = C, column by column (in place, row-major over K)
189+ const col = new Float64Array(K);
190+ const out = { re: new Float32Array(M * nSurf), im: new Float32Array(M * nSurf) };
191+ for (let s = 0; s < nSurf; s++) {
192+ for (let i = 0; i < K; i++) col[i] = C[i * nSurf + s];
193+ for (let i = 0; i < K; i++) {
194+ let v = col[i];
195+ for (let j = 0; j < i; j++) v -= L[i * K + j] * col[j];
196+ col[i] = v / L[i * K + i];
197+ }
198+ for (let i = K - 1; i >= 0; i--) {
199+ let v = col[i];
200+ for (let j = i + 1; j < K; j++) v -= L[j * K + i] * col[j];
201+ col[i] = v / L[i * K + i];
202+ }
203+ for (let n = 0; n < M; n++) {
204+ out.re[n * nSurf + s] = col[2 * n];
205+ out.im[n * nSurf + s] = col[2 * n + 1];
206+ }
207+ }
208+ return out;
209+}
210+
211+function cholesky(A, n) {
212+ const L = new Float64Array(n * n);
213+ for (let i = 0; i < n; i++) {
214+ for (let j = 0; j <= i; j++) {
215+ let s = A[i * n + j];
216+ for (let k = 0; k < j; k++) s -= L[i * n + k] * L[j * n + k];
217+ L[i * n + j] = i === j ? Math.sqrt(Math.max(s, 1e-300)) : s / L[j * n + j];
218+ }
219+ }
220+ return L;
221+}
222+
223+// Bilinear interpolation over block columns of a per-surface-point complex field.
224+function interp(model, sx, sy, get) {
225+ const { nbx, nby, dx, surfIndex } = model;
226+ const u = Math.min(nbx - 1.001, Math.max(0, sx / dx - 0.5));
227+ const v = Math.min(nby - 1.001, Math.max(0, sy / dx - 0.5));
228+ const i0 = Math.floor(u), j0 = Math.floor(v), fu = u - i0, fv = v - j0;
229+ const corners = [[i0, j0, (1 - fu) * (1 - fv)], [i0 + 1, j0, fu * (1 - fv)], [i0, j0 + 1, (1 - fu) * fv], [i0 + 1, j0 + 1, fu * fv]];
230+ return model.modes.map((m) => {
231+ const f = get(m);
232+ if (!f) return [0, 0];
233+ let re = 0, im = 0, ws = 0;
234+ for (const [i, j, w] of corners) {
235+ const s = surfIndex[Math.min(nbx - 1, i) + nbx * Math.min(nby - 1, j)];
236+ if (s < 0) continue;
237+ re += w * f[0][s]; im += w * f[1][s]; ws += w;
238+ }
239+ return ws > 0 ? [re / ws, im / ws] : [0, 0];
240+ });
241+}
242+
243+// Mic-pressure residue of every mode at strike point (mm).
244+export const residuesAt = (model, sx, sy) => interp(model, sx, sy, (m) => [m.re, m.im]);
245+
246+// Driving-point mobility residue D = V(ref,P)^2 / V(ref,ref) of every mode at P.
247+export function drivingPointAt(model, sx, sy) {
248+ const V = interp(model, sx, sy, (m) => (m.mob ? [m.mob.Vre, m.mob.Vim] : null));
249+ return model.modes.map((m, n) => {
250+ if (!m.mob) return [0, 0];
251+ const [a, b] = V[n];
252+ const [c, d] = m.mob.vpp;
253+ const nr = a * a - b * b, ni = 2 * a * b; // V^2
254+ const den = c * c + d * d;
255+ return [(nr * c + ni * d) / den, (ni * c - nr * d) / den];
256+ });
257+}
258+
259+/**
260+ * Hertz mallet (F = K d^1.5) against the modal surface at the strike point.
261+ * D: driving-point residues, poles: [{w, sig}]. Returns force samples F[k] at step h.
262+ */
263+export function simulateContact(D, poles, K, m, v0) {
264+ const T0 = hertzPulse(K, m, v0).T;
265+ const h = T0 / 400;
266+ const nMax = Math.ceil(Math.max(4e-3, 8 * T0) / h);
267+ const M = poles.length;
268+ const er = new Float64Array(M), ei = new Float64Array(M), qr = new Float64Array(M), qi = new Float64Array(M);
269+ for (let n = 0; n < M; n++) {
270+ const e = Math.exp(-poles[n].sig * h);
271+ er[n] = e * Math.cos(poles[n].w * h);
272+ ei[n] = e * Math.sin(poles[n].w * h);
273+ }
274+ const F = [];
275+ let w = 0, pm = 0, vm = v0, apart = 0;
276+ for (let k = 0; k < nMax; k++) {
277+ const d = pm + w;
278+ const f = d > 0 ? K * Math.pow(d, 1.5) : 0;
279+ F.push(f);
280+ let vs = 0;
281+ for (let n = 0; n < M; n++) {
282+ const a = qr[n] * er[n] - qi[n] * ei[n] + D[n][0] * f * h;
283+ qi[n] = qr[n] * ei[n] + qi[n] * er[n] + D[n][1] * f * h;
284+ qr[n] = a;
285+ vs += qr[n];
286+ }
287+ w += vs * h;
288+ vm -= (h * f) / m;
289+ pm += vm * h;
290+ apart = f > 0 ? 0 : apart + 1;
291+ if (k > 10 && apart > 0.5e-3 / h && vm < 0) break; // separated and moving away
292+ }
293+ return { F: Float64Array.from(F), h };
294+}
295+
296+/**
297+ * Modal strike: mic pressure (Pa) for a Hertz mallet hit.
298+ * p = { pitch (freq scale), eta, K, m, v0 }
299+ */
300+export function modalStrike(model, sx, sy, p, sr, maxDur = 3) {
301+ const R = residuesAt(model, sx, sy);
302+ const poles = model.modes.map((m) => {
303+ const w = 2 * Math.PI * m.f * p.pitch;
304+ return { w, sig: m.sigRad + decayRate(w, p.eta) };
305+ });
306+ const D = drivingPointAt(model, sx, sy);
307+ const { F, h } = simulateContact(D, poles, p.K, p.m, p.v0);
308+ let Fm = 0, nC = 0;
309+ for (let k = 0; k < F.length; k++) { Fm = Math.max(Fm, F[k]); if (F[k] > 0) nC++; }
310+ const osc = [];
311+ poles.forEach((o, n) => {
312+ if (o.w >= Math.PI * sr * 0.95) return;
313+ // Fhat = sum F_k e^{-i w t_k} h
314+ let fr = 0, fi = 0, cr = 1, ci = 0;
315+ const dr = Math.cos(o.w * h), di = -Math.sin(o.w * h);
316+ for (let k = 0; k < F.length; k++) {
317+ fr += F[k] * cr; fi += F[k] * ci;
318+ const tt = cr * dr - ci * di;
319+ ci = cr * di + ci * dr;
320+ cr = tt;
321+ }
322+ fr *= h; fi *= h;
323+ const [rr, ri] = R[n];
324+ osc.push({ w: o.w, sig: o.sig, ar: rr * fr - ri * fi, ai: rr * fi + ri * fr });
325+ });
326+ const minSig = Math.min(...osc.map((o) => o.sig), 1e9);
327+ const dur = Math.min(maxDur, Math.max(0.3, 8 / Math.max(minSig, 1e-3)));
328+ const N = Math.floor(dur * sr);
329+ const y = new Float32Array(N);
330+ for (const o of osc) {
331+ const dec = Math.exp(-o.sig / sr), c = Math.cos(o.w / sr) * dec, s = Math.sin(o.w / sr) * dec;
332+ let zr = o.ar, zi = o.ai;
333+ for (let i = 0; i < N; i++) {
334+ y[i] += zr;
335+ const t = zr * c - zi * s;
336+ zi = zr * s + zi * c;
337+ zr = t;
338+ }
339+ }
340+ return { y, T: nC * h, Fm, F, h, dur, osc };
341+}
342+
343+// Frequency (Hz, at pitch 1) of the mode that rings loudest: max |amplitude| / decay rate.
344+export function dominantFreq(model, sx, sy, p) {
345+ const { osc } = modalStrike(model, sx, sy, { ...p, pitch: 1 }, 48000, 0.01);
346+ let best = null;
347+ for (const o of osc) {
348+ const score = Math.hypot(o.ar, o.ai) / o.sig;
349+ if (!best || score > best.score) best = { score, f: o.w / (2 * Math.PI) };
350+ }
351+ return best ? best.f : 440;
352+}
353+
354+// Magnitude spectrum in dB (Hann window), returns {f, db}.
355+export function spectrumDb(y, sr, nfft = 32768) {
356+ const n = Math.min(y.length, nfft);
357+ const re = new Float64Array(nfft), im = new Float64Array(nfft);
358+ const w = hann(n);
359+ for (let i = 0; i < n; i++) re[i] = y[i] * w[i];
360+ fft(re, im);
361+ const db = new Float32Array(nfft / 2);
362+ for (let k = 0; k < nfft / 2; k++) db[k] = 10 * Math.log10(re[k] * re[k] + im[k] * im[k] + 1e-30);
363+ return { df: sr / nfft, db };
364+}
js/physics.jsadded+38−0View file
@@ -0,0 +1,38 @@
1+// Physics laws shared by the modal model and the SoundFont export.
2+
3+// Damping law of the modal model: Rayleigh damping matched to loss factor eta at F1 and
4+// F2, with the stiffness term rolled off above F_TAU (a Zener element).
5+export const F1 = 400, F2 = 4000, F_TAU = 40000;
6+export const TAU = 1 / (2 * Math.PI * F_TAU);
7+
8+export function rayleigh(eta) {
9+ const w1 = 2 * Math.PI * F1, w2 = 2 * Math.PI * F2;
10+ return { alpha: (eta * w1 * w2) / (w1 + w2), beta: eta / (w1 + w2) };
11+}
12+
13+// Amplitude decay rate (1/s) of a mode at angular frequency w.
14+export function decayRate(w, eta) {
15+ const { alpha, beta } = rayleigh(eta);
16+ return alpha / 2 + (beta * w * w) / (2 * (1 + (w * TAU) ** 2));
17+}
18+
19+// Hertz contact (F = K d^1.5) of mass m at speed v0 against a rigid surface.
20+export function hertzPulse(K, m, v0) {
21+ const dmax = Math.pow((5 * m * v0 * v0) / (4 * K), 0.4);
22+ return { T: (2.9432 * dmax) / v0, Fm: K * Math.pow(dmax, 1.5) };
23+}
24+
25+// Fourier transform of a half-sine pulse A sin(pi t/T), 0<t<T, at angular frequency w.
26+export function halfSineFT(A, T, w) {
27+ const a = Math.PI / T;
28+ const den = a * a - w * w;
29+ if (Math.abs(den) < 1e-6 * a * a) {
30+ // limit w -> a: integral = T/2 * (-i) * A (approximately)
31+ return [0, -A * T / 2];
32+ }
33+ const re = (A * a * (1 + Math.cos(w * T))) / den;
34+ const im = (-A * a * Math.sin(w * T)) / den;
35+ return [re, im];
36+}
37+
38+export const pitchScale = (semitones) => Math.pow(2, semitones / 12);
js/plots.jsadded+79−0View file
@@ -0,0 +1,79 @@
1+// Small canvas plots: spectrum (log f, dB) and waveform overlay.
2+
3+function setup(canvas) {
4+ const dpr = window.devicePixelRatio || 1;
5+ const w = canvas.clientWidth, h = canvas.clientHeight;
6+ canvas.width = w * dpr; canvas.height = h * dpr;
7+ const g = canvas.getContext('2d');
8+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
9+ const cs = getComputedStyle(document.documentElement);
10+ const col = (n) => cs.getPropertyValue(n).trim();
11+ g.clearRect(0, 0, w, h);
12+ g.font = '11px system-ui, sans-serif';
13+ return { g, w, h, col };
14+}
15+
16+const SERIES = { modal: '--c-modal' };
17+
18+// series: [{name:'modal', df, db}], marks: frequencies (Hz)
19+export function drawSpectrum(canvas, series, marks = []) {
20+ const { g, w, h, col } = setup(canvas);
21+ const L = 34, R = 8, T = 8, B = 20;
22+ const f0 = 100, f1 = 16000;
23+ const X = (f) => L + ((Math.log(f) - Math.log(f0)) / (Math.log(f1) - Math.log(f0))) * (w - L - R);
24+ let top = -Infinity;
25+ for (const s of series) for (let k = 1; k < s.db.length; k++) if (k * s.df > f0 && k * s.df < f1) top = Math.max(top, s.db[k]);
26+ if (!Number.isFinite(top)) top = 0;
27+ top = Math.ceil(top / 10) * 10;
28+ const range = 70;
29+ const Y = (d) => T + ((top - d) / range) * (h - T - B);
30+ g.strokeStyle = col('--grid'); g.fillStyle = col('--muted'); g.lineWidth = 1;
31+ for (const f of [100, 200, 500, 1000, 2000, 5000, 10000]) {
32+ g.beginPath(); g.moveTo(X(f), T); g.lineTo(X(f), h - B); g.stroke();
33+ g.fillText(f >= 1000 ? f / 1000 + 'k' : String(f), X(f) - 8, h - 6);
34+ }
35+ for (let d = 0; d <= range; d += 20) {
36+ g.beginPath(); g.moveTo(L, Y(top - d)); g.lineTo(w - R, Y(top - d)); g.stroke();
37+ g.fillText(String(-d), 4, Y(top - d) + 4);
38+ }
39+ g.strokeStyle = col('--mark');
40+ for (const f of marks) { if (f > f0 && f < f1) { g.beginPath(); g.moveTo(X(f), h - B); g.lineTo(X(f), h - B - 6); g.stroke(); } }
41+ for (const s of series) {
42+ g.strokeStyle = col(SERIES[s.name]); g.lineWidth = 1.4;
43+ g.beginPath();
44+ let first = true;
45+ for (let k = 1; k < s.db.length; k++) {
46+ const f = k * s.df;
47+ if (f < f0 || f > f1) continue;
48+ const x = X(f), y = Math.min(h - B, Math.max(T, Y(s.db[k])));
49+ if (first) { g.moveTo(x, y); first = false; } else g.lineTo(x, y);
50+ }
51+ g.stroke();
52+ }
53+ g.fillStyle = col('--muted');
54+ g.fillText('dB / Hz', w - 60, T + 10);
55+}
56+
57+// series: [{name, y, sr}] shown over first `dur` seconds
58+export function drawWave(canvas, series, dur = 0.25) {
59+ const { g, w, h, col } = setup(canvas);
60+ const L = 8, R = 8, T = 6, B = 18;
61+ let amax = 1e-12;
62+ for (const s of series) for (let i = 0; i < Math.min(s.y.length, dur * s.sr); i++) amax = Math.max(amax, Math.abs(s.y[i]));
63+ g.strokeStyle = col('--grid');
64+ g.beginPath(); g.moveTo(L, (T + h - B) / 2); g.lineTo(w - R, (T + h - B) / 2); g.stroke();
65+ g.fillStyle = col('--muted');
66+ for (let t = 0; t <= dur + 1e-9; t += 0.05) g.fillText((t * 1000).toFixed(0), L + (t / dur) * (w - L - R) - 6, h - 5);
67+ g.fillText('ms', w - 22, h - 5);
68+ for (const s of series) {
69+ g.strokeStyle = col(SERIES[s.name]); g.lineWidth = 1;
70+ g.beginPath();
71+ const n = Math.min(s.y.length, Math.floor(dur * s.sr));
72+ for (let i = 0; i < n; i++) {
73+ const x = L + (i / (dur * s.sr)) * (w - L - R);
74+ const y = (T + h - B) / 2 - (s.y[i] / amax) * ((h - T - B) / 2);
75+ i ? g.lineTo(x, y) : g.moveTo(x, y);
76+ }
77+ g.stroke();
78+ }
79+}
js/sf2.jsadded+150−0View file
@@ -0,0 +1,150 @@
1+// Minimal SoundFont 2.01 writer: one preset -> one instrument -> many sample zones.
2+
3+const enc = new TextEncoder();
4+
5+function str(s, len) { // fixed-length, zero-padded ASCII
6+ const b = new Uint8Array(len);
7+ b.set(enc.encode(s.replace(/[^\x20-\x7e]/g, '_')).slice(0, len - 1));
8+ return b;
9+}
10+function zstr(s) { // zero-terminated, even length
11+ const t = enc.encode(s.replace(/[^\x20-\x7e]/g, '_'));
12+ const b = new Uint8Array(t.length + 1 + ((t.length + 1) % 2));
13+ b.set(t);
14+ return b;
15+}
16+function concat(parts) {
17+ const n = parts.reduce((a, p) => a + p.length, 0);
18+ const out = new Uint8Array(n);
19+ let o = 0;
20+ for (const p of parts) { out.set(p, o); o += p.length; }
21+ return out;
22+}
23+function chunk(id, data) {
24+ const h = new Uint8Array(8);
25+ h.set(enc.encode(id));
26+ new DataView(h.buffer).setUint32(4, data.length, true);
27+ return concat(data.length % 2 ? [h, data, new Uint8Array(1)] : [h, data]);
28+}
29+function list(type, chunks) { return chunk('LIST', concat([enc.encode(type), ...chunks])); }
30+
31+// Fixed-size record builder
32+function records(size, items, fill) {
33+ const b = new Uint8Array(size * items.length);
34+ const dv = new DataView(b.buffer);
35+ items.forEach((it, i) => fill(dv, i * size, it, b));
36+ return b;
37+}
38+
39+export const GEN = { releaseVolEnv: 38, instrument: 41, keyRange: 43, velRange: 44, sampleModes: 54, sampleID: 53, overridingRootKey: 58 };
40+
41+/**
42+ * opts: {
43+ * name, bank, program, sampleRate,
44+ * samples: [{ name, data: Int16Array, root, correction? }],
45+ * zones: [{ keyLo, keyHi, velLo, velHi, sample }],
46+ * releaseSec, disableVelocityAttenuation
47+ * }
48+ */
49+export function buildSF2(opts) {
50+ const { name, samples, zones } = opts;
51+ const PAD = 46;
52+
53+ // ---- sdta ----
54+ const total = samples.reduce((a, s) => a + s.data.length + PAD, 0);
55+ const smpl = new Int16Array(total);
56+ const offsets = [];
57+ let o = 0;
58+ for (const s of samples) {
59+ offsets.push(o);
60+ smpl.set(s.data, o);
61+ o += s.data.length + PAD;
62+ }
63+ const sdta = list('sdta', [chunk('smpl', new Uint8Array(smpl.buffer))]);
64+
65+ // ---- INFO ----
66+ const ifil = new Uint8Array(4);
67+ new DataView(ifil.buffer).setUint16(0, 2, true);
68+ new DataView(ifil.buffer).setUint16(2, 1, true);
69+ const info = list('INFO', [
70+ chunk('ifil', ifil), chunk('isng', zstr('EMU8000')), chunk('INAM', zstr(name)), chunk('ISFT', zstr('Woodblock Lab')),
71+ ]);
72+
73+ // ---- pdta ----
74+ // instrument zones: global zone (release + velocity modulator override), then sample zones
75+ const igen = [], ibag = [], imod = [];
76+ ibag.push([igen.length, imod.length]);
77+ igen.push([GEN.releaseVolEnv, Math.round(1200 * Math.log2(opts.releaseSec ?? 2)), 's']);
78+ if (opts.disableVelocityAttenuation) {
79+ // same source/dest as the default "velocity -> initial attenuation" modulator, amount 0
80+ imod.push([0x0502, 48, 0, 0, 0]);
81+ }
82+ for (const z of zones) {
83+ ibag.push([igen.length, imod.length]);
84+ igen.push([GEN.keyRange, [z.keyLo, z.keyHi], 'r']);
85+ igen.push([GEN.velRange, [z.velLo, z.velHi], 'r']);
86+ igen.push([GEN.sampleModes, 0, 'u']);
87+ igen.push([GEN.sampleID, z.sample, 'u']);
88+ }
89+ const nIbag = ibag.length;
90+ ibag.push([igen.length, imod.length]); // terminal
91+ igen.push([0, 0, 'u']);
92+ imod.push([0, 0, 0, 0, 0]);
93+
94+ const genRec = (dv, off, [op, amt, kind]) => {
95+ dv.setUint16(off, op, true);
96+ if (kind === 'r') { dv.setUint8(off + 2, amt[0]); dv.setUint8(off + 3, amt[1]); }
97+ else if (kind === 's') dv.setInt16(off + 2, amt, true);
98+ else dv.setUint16(off + 2, amt, true);
99+ };
100+ const bagRec = (dv, off, [g, m]) => { dv.setUint16(off, g, true); dv.setUint16(off + 2, m, true); };
101+ const modRec = (dv, off, [src, dst, amt, asrc, tr]) => {
102+ dv.setUint16(off, src, true); dv.setUint16(off + 2, dst, true); dv.setInt16(off + 4, amt, true);
103+ dv.setUint16(off + 6, asrc, true); dv.setUint16(off + 8, tr, true);
104+ };
105+
106+ const inst = records(22, [[name, 0], ['EOI', nIbag]], (dv, off, [n, bag], b) => {
107+ b.set(str(n, 20), off); dv.setUint16(off + 20, bag, true);
108+ });
109+
110+ // preset: one zone pointing at instrument 0
111+ const pgen = [[GEN.instrument, 0, 'u'], [0, 0, 'u']];
112+ const pbag = [[0, 0], [1, 0]];
113+ const pmod = [[0, 0, 0, 0, 0]];
114+ const phdr = records(38, [[name, opts.program ?? 0, opts.bank ?? 0, 0], ['EOP', 0, 0, 1]], (dv, off, [n, prog, bank, bag], b) => {
115+ b.set(str(n, 20), off);
116+ dv.setUint16(off + 20, prog, true); dv.setUint16(off + 22, bank, true); dv.setUint16(off + 24, bag, true);
117+ });
118+
119+ const sr = opts.sampleRate;
120+ const shdrItems = samples.map((s, i) => ({ ...s, start: offsets[i], end: offsets[i] + s.data.length }));
121+ shdrItems.push({ name: 'EOS', start: 0, end: 0, root: 0, terminal: true });
122+ const shdr = records(46, shdrItems, (dv, off, s, b) => {
123+ b.set(str(s.name, 20), off);
124+ dv.setUint32(off + 20, s.start, true);
125+ dv.setUint32(off + 24, s.end, true);
126+ const ls = s.terminal ? 0 : Math.min(s.start + 8, s.end);
127+ const le = s.terminal ? 0 : Math.max(ls, s.end - 8);
128+ dv.setUint32(off + 28, ls, true);
129+ dv.setUint32(off + 32, le, true);
130+ dv.setUint32(off + 36, s.terminal ? 0 : sr, true);
131+ dv.setUint8(off + 40, s.root);
132+ dv.setInt8(off + 41, s.correction ?? 0);
133+ dv.setUint16(off + 42, 0, true);
134+ dv.setUint16(off + 44, s.terminal ? 0 : 1, true); // 1 = mono sample
135+ });
136+
137+ const pdta = list('pdta', [
138+ chunk('phdr', phdr),
139+ chunk('pbag', records(4, pbag, bagRec)),
140+ chunk('pmod', records(10, pmod, modRec)),
141+ chunk('pgen', records(4, pgen, genRec)),
142+ chunk('inst', inst),
143+ chunk('ibag', records(4, ibag, bagRec)),
144+ chunk('imod', records(10, imod, modRec)),
145+ chunk('igen', records(4, igen, genRec)),
146+ chunk('shdr', shdr),
147+ ]);
148+
149+ return chunk('RIFF', concat([enc.encode('sfbk'), info, sdta, pdta]));
150+}
js/view3d.jsadded+197−0View file
@@ -0,0 +1,197 @@
1+// three.js view of the block: click the top face to set the strike point.
2+
3+import * as THREE from 'three';
4+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
5+import { blockBoxes, micPos } from './block.js';
6+
7+const S = 0.01; // scene units per mm
8+
9+function woodTexture() {
10+ const c = document.createElement('canvas');
11+ c.width = 512; c.height = 128;
12+ const g = c.getContext('2d');
13+ g.fillStyle = '#b5743c';
14+ g.fillRect(0, 0, c.width, c.height);
15+ for (let y = 0; y < c.height; y++) {
16+ const v = Math.sin(y * 0.35 + Math.sin(y * 0.05) * 3) * 0.5 + 0.5;
17+ g.fillStyle = `rgba(90,45,15,${0.08 + 0.22 * v * v})`;
18+ g.fillRect(0, y, c.width, 1);
19+ }
20+ for (let i = 0; i < 60; i++) {
21+ g.strokeStyle = `rgba(70,35,10,${0.05 + Math.random() * 0.12})`;
22+ g.beginPath();
23+ const y = Math.random() * c.height;
24+ g.moveTo(0, y);
25+ for (let x = 0; x <= c.width; x += 32) g.lineTo(x, y + Math.sin(x * 0.01 + i) * 3);
26+ g.stroke();
27+ }
28+ const t = new THREE.CanvasTexture(c);
29+ t.colorSpace = THREE.SRGBColorSpace;
30+ t.wrapS = t.wrapT = THREE.RepeatWrapping;
31+ return t;
32+}
33+
34+export class BlockView {
35+ constructor(container, onPick) {
36+ this.container = container;
37+ this.onPick = onPick;
38+ const r = (this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }));
39+ r.setPixelRatio(Math.min(2, window.devicePixelRatio));
40+ container.appendChild(r.domElement);
41+ this.scene = new THREE.Scene();
42+ this.camera = new THREE.PerspectiveCamera(35, 1, 0.01, 100);
43+ this.camera.position.set(1.6, 1.5, 3.0);
44+ this.controls = new OrbitControls(this.camera, r.domElement);
45+ this.controls.enableDamping = true;
46+ this.scene.add(new THREE.HemisphereLight(0xffffff, 0x404050, 1.4));
47+ const sun = new THREE.DirectionalLight(0xffffff, 2.2);
48+ sun.position.set(2, 4, 3);
49+ this.scene.add(sun);
50+ this.tex = woodTexture();
51+ this.group = new THREE.Group();
52+ this.scene.add(this.group);
53+
54+ // mallet
55+ this.mallet = new THREE.Group();
56+ const head = new THREE.Mesh(new THREE.SphereGeometry(0.09, 24, 16), new THREE.MeshStandardMaterial({ color: 0x333a44, roughness: 0.5 }));
57+ head.position.y = 0.09;
58+ const stick = new THREE.Mesh(new THREE.CylinderGeometry(0.018, 0.018, 1.0, 12), new THREE.MeshStandardMaterial({ color: 0xd8c39a }));
59+ stick.position.set(0.0, 0.2, 0.45);
60+ stick.rotation.x = Math.PI / 2.6;
61+ this.mallet.add(head, stick);
62+ this.scene.add(this.mallet);
63+ this.mic = new THREE.Mesh(new THREE.SphereGeometry(0.03, 16, 12), new THREE.MeshStandardMaterial({ color: 0x3d8bfd, emissive: 0x112244 }));
64+ this.scene.add(this.mic);
65+ this.hitT = -1;
66+
67+ const ray = new THREE.Raycaster();
68+ let down = null;
69+ r.domElement.addEventListener('pointerdown', (e) => (down = [e.clientX, e.clientY]));
70+ r.domElement.addEventListener('pointerup', (e) => {
71+ if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4) return;
72+ const rect = r.domElement.getBoundingClientRect();
73+ const ndc = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
74+ ray.setFromCamera(ndc, this.camera);
75+ const hit = ray.intersectObject(this.topPick)[0];
76+ if (hit) {
77+ const p = this.toBlock(hit.point);
78+ this.onPick(p[0], p[1]);
79+ }
80+ });
81+ new ResizeObserver(() => this.resize()).observe(container);
82+ this.resize();
83+ const loop = () => {
84+ requestAnimationFrame(loop);
85+ this.animate();
86+ this.controls.update();
87+ r.render(this.scene, this.camera);
88+ };
89+ loop();
90+ }
91+
92+ // block mm -> scene
93+ toScene(x, y, z) {
94+ const b = this.block;
95+ return new THREE.Vector3((x - b.L / 2) * S, (z - b.H / 2) * S, (b.W / 2 - y) * S);
96+ }
97+ toBlock(v) {
98+ const b = this.block;
99+ return [v.x / S + b.L / 2, b.W / 2 - v.z / S, v.y / S + b.H / 2];
100+ }
101+
102+ setBlock(b) {
103+ this.block = b;
104+ this.group.clear();
105+ const mat = new THREE.MeshStandardMaterial({ map: this.tex, roughness: 0.65 });
106+ for (const [x0, x1, y0, y1, z0, z1] of blockBoxes(b)) {
107+ const geo = new THREE.BoxGeometry((x1 - x0) * S, (z1 - z0) * S, (y1 - y0) * S);
108+ const m = new THREE.Mesh(geo, mat);
109+ m.position.copy(this.toScene((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2));
110+ this.group.add(m);
111+ }
112+ // dark cavity interior (slightly inset so it doesn't z-fight)
113+ const e = 0.3;
114+ const cav = new THREE.Mesh(
115+ new THREE.BoxGeometry((b.L - 2 * b.wall - e) * S, (b.H - b.top - b.wall - e) * S, (b.W - 2 * b.wall - e) * S),
116+ new THREE.MeshBasicMaterial({ color: 0x140a04, side: THREE.BackSide }),
117+ );
118+ cav.position.copy(this.toScene(b.L / 2, b.W / 2, (b.wall + b.H - b.top) / 2));
119+ this.group.add(cav);
120+ // invisible pick plane + mode overlay on top face
121+ this.topPick = new THREE.Mesh(new THREE.PlaneGeometry(b.L * S, b.W * S), new THREE.MeshBasicMaterial({ visible: false }));
122+ this.topPick.rotation.x = -Math.PI / 2;
123+ this.topPick.position.copy(this.toScene(b.L / 2, b.W / 2, b.H + 0.2));
124+ this.group.add(this.topPick);
125+ this.overlay = new THREE.Mesh(
126+ new THREE.PlaneGeometry(b.L * S, b.W * S),
127+ new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.85, depthWrite: false }),
128+ );
129+ this.overlay.rotation.x = -Math.PI / 2;
130+ this.overlay.position.copy(this.toScene(b.L / 2, b.W / 2, b.H + 0.3));
131+ this.overlay.visible = false;
132+ this.group.add(this.overlay);
133+ this.mic.position.copy(this.toScene(...micPos(b)));
134+ if (this.strike) this.setStrike(...this.strike);
135+ }
136+
137+ setStrike(x, y) {
138+ this.strike = [x, y];
139+ this.malletRest = this.toScene(x, y, this.block.H);
140+ this.mallet.position.copy(this.malletRest).add(new THREE.Vector3(0, 0.12, 0));
141+ }
142+
143+ hit() { this.hitT = performance.now(); }
144+
145+ animate() {
146+ if (!this.malletRest) return;
147+ const lift = 0.12;
148+ let h = lift;
149+ if (this.hitT > 0) {
150+ const t = (performance.now() - this.hitT) / 1000;
151+ h = t < 0.03 ? lift * (1 - t / 0.03) : t < 0.25 ? lift * Math.sin(((t - 0.03) / 0.22) * Math.PI / 2) : lift;
152+ }
153+ this.mallet.position.copy(this.malletRest).add(new THREE.Vector3(0, h, 0));
154+ }
155+
156+ // values[nby][nbx] in [0,1] or null to hide
157+ setOverlay(nbx, nby, values) {
158+ if (!values) { this.overlay.visible = false; return; }
159+ const c = document.createElement('canvas');
160+ c.width = nbx; c.height = nby;
161+ const g = c.getContext('2d');
162+ const img = g.createImageData(nbx, nby);
163+ for (let j = 0; j < nby; j++) {
164+ for (let i = 0; i < nbx; i++) {
165+ const v = values[j * nbx + i];
166+ const o = ((nby - 1 - j) * nbx + i) * 4;
167+ const [r, gg, b] = colormap(v);
168+ img.data[o] = r; img.data[o + 1] = gg; img.data[o + 2] = b; img.data[o + 3] = 255;
169+ }
170+ }
171+ g.putImageData(img, 0, 0);
172+ const t = new THREE.CanvasTexture(c);
173+ t.colorSpace = THREE.SRGBColorSpace;
174+ t.magFilter = THREE.LinearFilter;
175+ this.overlay.material.map?.dispose();
176+ this.overlay.material.map = t;
177+ this.overlay.material.needsUpdate = true;
178+ this.overlay.visible = true;
179+ }
180+
181+ resize() {
182+ const w = this.container.clientWidth, h = this.container.clientHeight;
183+ if (!w || !h) return;
184+ this.renderer.setSize(w, h);
185+ this.camera.aspect = w / h;
186+ // back off on narrow screens so the whole block fits
187+ const d = 3.75 * Math.max(1, 1.4 / this.camera.aspect);
188+ this.camera.position.sub(this.controls.target).setLength(d).add(this.controls.target);
189+ this.camera.updateProjectionMatrix();
190+ }
191+}
192+
193+// signed value in [-1,1] -> blue / white / red
194+function colormap(v) {
195+ const a = Math.min(1, Math.abs(v));
196+ return v >= 0 ? [255, 255 * (1 - a), 255 * (1 - a)] : [255 * (1 - a), 255 * (1 - a), 255];
197+}
main.jsadded+298−0View file
@@ -0,0 +1,298 @@
1+import { DEFAULT_BLOCK, buildGrid, strikePatch, validateBlock } from './js/block.js';
2+import { runFDTD, timeStep } from './js/fdtd.js';
3+import { extractModes, modalStrike, residuesAt, spectrumDb, dominantFreq } from './js/modal.js';
4+import { exportSF2, noteName, freqToMidi, LAYERS, VARIANTS } from './js/export.js';
5+import { pitchScale } from './js/physics.js';
6+import { BlockView } from './js/view3d.js';
7+import { drawSpectrum, drawWave } from './js/plots.js';
8+
9+const $ = (id) => document.getElementById(id);
10+
11+// ---------- parameters ----------
12+const 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+];
19+const 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] }));
30+
31+const P = {};
32+function 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+}
45+function 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+}
52+const block = () => Object.fromEntries(BLOCK.map((d) => [d.key, P[d.key]]));
53+const liveParams = () => ({ pitch: pitchScale(P.pitch), eta: P.eta, K: 10 ** P.hard, m: P.mass / 1000, v0: P.v0 });
54+
55+// ---------- state ----------
56+let model = null; // modal model
57+let modelKey = ''; // block+dx the model was built for
58+let strike = [DEFAULT_BLOCK.L / 2, DEFAULT_BLOCK.W / 2];
59+let busy = false, cancel = false;
60+let actx = null, gain = 1;
61+let lastModal = null;
62+let throughput = 0; // cell-steps per second, measured
63+const ANALYSIS_DUR = 0.06; // s per analysis run
64+let lastRes = null; // last analysis run (for debugging)
65+
66+const view = new BlockView($('view'), (x, y) => { strike = [x, y]; view.setStrike(x, y); updateInfo(); updateSfInfo(); playModal(); });
67+const keyOf = () => JSON.stringify([block(), $('dx').value]);
68+
69+addSliders($('live'), LIVE, () => { updateInfo(); updateSfInfo(); });
70+addSliders($('blockp'), BLOCK, () => onBlockChange());
71+$('dx').addEventListener('change', () => { updateInfo(); });
72+
73+function 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+}
83+
84+function 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+}
100+
101+// ---------- audio ----------
102+function audio() {
103+ if (!actx) actx = new AudioContext();
104+ if (actx.state === 'suspended') actx.resume();
105+ return actx;
106+}
107+function 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+}
117+
118+function 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+}
128+
129+function 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+}
139+
140+// ---------- simulations ----------
141+function 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+}
148+const 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+};
153+
154+async 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+}
201+
202+function 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+}
208+
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+});
227+
228+// ---------- SoundFont export ----------
229+function 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+}
234+function 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+}
248+for (const id of ['sflo', 'sfhi', 'sfstep']) $(id).addEventListener('input', updateSfInfo);
249+
250+async 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+}
276+let lastExport = null;
277+$('export').onclick = doExport;
278+
279+$('analyze').onclick = analyze;
280+$('cancel').onclick = () => (cancel = true);
281+$('strike').onclick = playModal;
282+window.addEventListener('keydown', (e) => {
283+ if (e.code === 'Space' && e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT') { e.preventDefault(); playModal(); }
284+});
285+window.addEventListener('resize', drawPlots);
286+
287+// for debugging in the console
288+window.wb = { get model() { return model; }, get lastRes() { return lastRes; }, get lastModal() { return lastModal; }, get lastExport() { return lastExport; }, residuesAt, extractModes, P };
289+
290+onBlockChange();
291+drawPlots();
292+updateSfInfo();
293+if (!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+}
package.jsonadded+8−0View file
@@ -0,0 +1,8 @@
1+{
2+ "name": "woodblock",
3+ "private": true,
4+ "type": "module",
5+ "scripts": {
6+ "dev": "python3 -m http.server 8020 --bind 127.0.0.1"
7+ }
8+}
style.cssadded+52−0View file
@@ -0,0 +1,52 @@
1+:root {
2+ --bg: #f6f4f0; --panel: #ffffff; --fg: #1d1b18; --muted: #6f6a62; --line: #e2ddd4;
3+ --accent: #a0522d; --grid: #ebe6dd; --mark: #b8b0a2;
4+ --c-modal: #c2410c; --warn: #b45309;
5+ color-scheme: light dark;
6+}
7+@media (prefers-color-scheme: dark) {
8+ :root {
9+ --bg: #151412; --panel: #1e1c19; --fg: #ece8e1; --muted: #9a948a; --line: #34302b;
10+ --accent: #e0915c; --grid: #2a2723; --mark: #5c564e;
11+ --c-modal: #fb923c; --warn: #fbbf24;
12+ }
13+}
14+* { box-sizing: border-box; }
15+html, body { margin: 0; height: 100%; background: var(--bg); color: var(--fg); font: 13px/1.4 system-ui, -apple-system, sans-serif; }
16+main { display: grid; grid-template-columns: 1fr 340px; height: 100vh; }
17+.stage { display: grid; grid-template-rows: 1fr auto; grid-template-columns: minmax(0, 1fr); min-width: 0; position: relative; }
18+#view { min-height: 300px; position: relative; overflow: hidden; }
19+#view canvas { position: absolute; inset: 0; }
20+.hint { position: absolute; top: 10px; left: 14px; color: var(--muted); font-size: 12px; pointer-events: none; }
21+.plots { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; padding: 10px; border-top: 1px solid var(--line); }
22+.plot { min-width: 0; }
23+.plot canvas { width: 100%; height: 170px; display: block; }
24+.ptitle { color: var(--muted); font-size: 12px; margin-bottom: 4px; }
25+.panel { background: var(--panel); border-left: 1px solid var(--line); padding: 14px 16px; overflow-y: auto; }
26+h1 { font-size: 17px; margin: 0 0 10px; }
27+h2 { font-size: 13px; margin: 18px 0 6px; padding-top: 10px; border-top: 1px solid var(--line); }
28+h2 small { color: var(--muted); font-weight: 400; margin-left: 6px; }
29+.row { display: grid; grid-template-columns: 130px 1fr 64px; align-items: center; gap: 8px; margin: 3px 0; }
30+.row .lab { color: var(--muted); font-size: 12px; }
31+.row .val { text-align: right; font-variant-numeric: tabular-nums; font-size: 12px; }
32+input[type=range] { width: 100%; accent-color: var(--accent); }
33+input[type=text] { width: 100%; background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 3px 6px; font: inherit; }
34+select { background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 3px 4px; }
35+.actions { display: flex; gap: 6px; flex-wrap: wrap; margin: 6px 0; }
36+button { background: var(--accent); color: #fff; border: 0; border-radius: 7px; padding: 7px 11px; font: inherit; font-weight: 600; cursor: pointer; }
37+button:disabled { opacity: 0.45; cursor: default; }
38+button.small { padding: 2px 8px; font-size: 12px; background: var(--muted); }
39+.progress { height: 4px; background: var(--grid); border-radius: 2px; overflow: hidden; margin-top: 8px; }
40+#bar { height: 100%; width: 0; background: var(--accent); transition: width 0.2s; }
41+.status { min-height: 36px; margin-top: 6px; font-size: 12px; color: var(--muted); }
42+.kv { display: flex; justify-content: space-between; font-size: 12px; margin: 2px 0 4px; }
43+.muted { color: var(--muted); }
44+.info { font-size: 11px; color: var(--muted); margin: 6px 0; font-variant-numeric: tabular-nums; }
45+.warn { color: var(--warn); font-size: 12px; margin: 4px 0; }
46+.warn:empty { display: none; }
47+@media (max-width: 800px) {
48+ main { grid-template-columns: 1fr; height: auto; }
49+ .stage { grid-template-rows: 55vh auto; }
50+ .plots { grid-template-columns: 1fr; padding: 10px 16px; }
51+ .panel { border-left: 0; border-top: 1px solid var(--line); padding: 14px 16px; }
52+}