// The "Physics" tab: records one note with the engine's state (strings, bridge, body modes, // forces, energies) and replays it in 3D at any speed, with synced time traces and a mode // explorer for the body modes and the string partials. Loaded on demand (three.js is large). import type { Params } from "../../core/params.ts"; import type { BodyModel } from "../../core/types.ts"; import { STRING_NAMES } from "../../core/types.ts"; import type { Recording, RecordSpec } from "../../core/engine.ts"; import { fingering, stringConst, stringModes } from "../../core/strings.ts"; import { noteName } from "../../core/sf2.ts"; import { decodeShapes, type FEShapes } from "../../fe/shapes.ts"; import { BassScene, type Frame, type Scales, type StringSetup } from "./scene.ts"; import { tracePlot, traceTimeAt } from "./traces.ts"; export interface VizHost { params(): Params; note(): number; velocity(): number; useFE(): boolean; feKey(): string; /** the body in use (loads / computes the FE body if needed) */ body(): Promise; record(params: Params, body: BodyModel, note: number, velocity: number, duration: number, spec: RecordSpec, progress: (f: number) => void): Promise<{ recording: Recording; mic: Float32Array; pickup: Float32Array; sampleRate: number }>; computeShapes(params: Params, progress: (f: number, msg?: string) => void): Promise; defaultShapesUrl: string; status(s: string, err?: boolean): void; progress(f: number): void; playAudio(x: Float32Array, fs: number): void; stopAudio(): void; mix(mic: Float32Array, pickup: Float32Array): Float32Array; } interface Rec { R: Recording; mic: Float32Array; pickup: Float32Array; fs: number; note: number; velocity: number; duration: number; params: Params; body: BodyModel; shapes: FEShapes | null; key: string; /** maxima for automatic scaling */ maxString: number; maxBody: number; maxPlate: number; maxAir: number; eMax: number; } type Mode = { kind: "replay" } | { kind: "body"; idx: number } | { kind: "partial"; n: number }; const SPEEDS: [number, string][] = [[1e-4, "1/10000"], [3e-4, "1/3000"], [1e-3, "1/1000"], [3e-3, "1/300"], [1e-2, "1/100"], [3e-2, "1/30"], [0.1, "1/10"], [0.3, "1/3"], [1, "real time"]]; const WINDOWS: [string, string][] = [["all", "whole note"], ["dense", "pluck (detail window)"], ["50", "±50 ms"], ["5", "±5 ms"], ["0.5", "±0.5 ms"]]; const MODE_HZ = 0.6; // display rate of a mode animation const css = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || "#888"; export class PhysicsView { private host: VizHost; private root: HTMLElement; private scene: BassScene | null = null; private sceneKey = ""; private rec: Rec | null = null; private recording: Promise | null = null; private shapesCache = new Map(); private t = 0; private playing = false; private speed = 1e-3; private win = "dense"; private mode: Mode = { kind: "replay" }; private modeT0 = performance.now(); private gain = { string: 1, body: 1, color: 1 }; private lastWall = 0; private lastPlot = 0; private dirty = true; private visible = false; private work: Float32Array = new Float32Array(0); private fields = { top: new Float32Array(0), back: new Float32Array(0), air: new Float32Array(0), plug: new Float32Array(0) }; private duration = 1; private modeTab: "body" | "partials" = "body"; constructor(root: HTMLElement, host: VizHost) { this.root = root; this.host = host; root.innerHTML = `
${["overview", "top", "side", "bridge", "string", "below"].map((v) => ``).join("")}
click or drag on a plot to move the playhead · shaded: every time step recorded
`; const $ = (id: string) => root.querySelector(`#${id}`) as T; ($("phSpeed") as HTMLSelectElement).value = String(this.speed); ($("phWin") as HTMLSelectElement).value = this.win; ($("phDur") as HTMLSelectElement).value = String(this.duration); $("phRec").addEventListener("click", () => void this.record()); $("phDur").addEventListener("change", () => { this.duration = Number(($("phDur") as HTMLSelectElement).value); void this.record(); }); $("phPlay").addEventListener("click", () => this.togglePlay()); $("phStart").addEventListener("click", () => this.seek(0)); $("phBack").addEventListener("click", () => this.stepFrame(-1)); $("phFwd").addEventListener("click", () => this.stepFrame(1)); $("phRel").addEventListener("click", () => { if (this.rec) this.seek(Math.max(0, this.rec.R.tRelease - 0.001)); }); $("phSpeed").addEventListener("change", () => { this.speed = Number(($("phSpeed") as HTMLSelectElement).value); }); $("phWin").addEventListener("change", () => { this.win = ($("phWin") as HTMLSelectElement).value; this.dirty = true; }); $("phT").addEventListener("input", () => { const R = this.rec?.R; if (R) this.seek((Number(($("phT") as HTMLInputElement).value) / 100000) * this.tEnd()); }); $("phSound").addEventListener("click", () => this.soundFromHere()); $("phDetail").addEventListener("click", () => void this.record(this.t)); $("mtBody").addEventListener("click", () => { this.modeTab = "body"; this.drawModeList(); }); $("mtPart").addEventListener("click", () => { this.modeTab = "partials"; this.drawModeList(); }); root.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => this.scene?.view(b.dataset.view as never))); const layer = () => { this.scene?.setLayers({ top: ($("lyTop") as HTMLInputElement).checked, topOpacity: Number(($("lyTopOp") as HTMLInputElement).value), back: ($("lyBack") as HTMLInputElement).checked, air: ($("lyAir") as HTMLInputElement).checked, plugs: ($("lyPlugs") as HTMLInputElement).checked, ribs: ($("lyRibs") as HTMLInputElement).checked, symp: ($("lySymp") as HTMLInputElement).checked, }); this.dirty = true; }; for (const id of ["lyTop", "lyTopOp", "lyBack", "lyAir", "lyPlugs", "lyRibs", "lySymp"]) $(id).addEventListener("input", layer); $("lyAir").addEventListener("change", () => { if (($("lyAir") as HTMLInputElement).checked) { ($("lyTopOp") as HTMLInputElement).value = "0.25"; layer(); } }); for (const [id, k] of [["gStr", "string"], ["gBody", "body"], ["gCol", "color"]] as const) $(id).addEventListener("input", () => { this.gain[k] = Math.pow(10, Number(($(id) as HTMLInputElement).value)); this.dirty = true; }); for (let q = 0; q < 4; q++) { const c = $(`pc${q}`) as HTMLCanvasElement; const go = (e: PointerEvent) => { const [t0, t1] = this.window(); this.seek(traceTimeAt(c, e.clientX, t0, t1)); }; c.addEventListener("pointerdown", (e) => { c.setPointerCapture(e.pointerId); this.playing = false; go(e); }); c.addEventListener("pointermove", (e) => { if (c.hasPointerCapture(e.pointerId)) go(e); }); } window.addEventListener("keydown", (e) => { if (!this.visible || (e.target as HTMLElement).closest("input, select, textarea")) return; if (e.key === " ") { e.preventDefault(); this.togglePlay(); } else if (e.key === "ArrowRight") { e.preventDefault(); this.stepFrame(1); } else if (e.key === "ArrowLeft") { e.preventDefault(); this.stepFrame(-1); } else if (e.key === "Home") { e.preventDefault(); this.seek(0); } }); this.updateRecButton(); this.drawModeList(); const loop = (now: number) => { this.tick(now); requestAnimationFrame(loop); }; requestAnimationFrame(loop); } /** The tab became visible (or the note changed while it is). */ async show(): Promise { this.visible = true; this.updateRecButton(); const key = this.recKey(); if (!this.rec || this.rec.key !== key) await this.record(); else this.dirty = true; } hide(): void { this.visible = false; this.playing = false; } /** A note was played on the keyboard / the parameters changed. */ noteChanged(): void { this.updateRecButton(); if (this.visible && (!this.rec || this.rec.key !== this.recKey())) void this.record(); } private recKey(): string { const p = this.host.params(); return JSON.stringify([p.engine, p.strings, p.pluck, p.stop, this.host.useFE() ? this.host.feKey() : p.body, p.fe.stringSpacing, p.fe.bridgeHeight, p.output, this.host.note(), this.host.velocity(), this.duration]); } private updateRecButton(): void { const b = this.root.querySelector("#phRec") as HTMLButtonElement; b.textContent = `● Record ${noteName(this.host.note())} v${this.host.velocity()}`; } // ------------------------------------------------------------ data private async shapesFor(p: Params): Promise { if (!this.host.useFE()) return null; const key = this.host.feKey(); const hit = this.shapesCache.get(key); if (hit) return hit; let s: FEShapes | null = null; try { const r = await fetch(this.host.defaultShapesUrl); if (r.ok) { const d = decodeShapes(await r.arrayBuffer()); if (d.feKey === key) s = d; } } catch { /* not served */ } if (!s) { this.host.status("Computing the FE mode shapes for the 3D view…"); s = await this.host.computeShapes(p, (f, msg) => { this.host.progress(f); if (msg) this.host.status(`FE shapes: ${msg}`); }); } this.shapesCache.set(key, s); return s; } private async record(detailFrom?: number): Promise { if (this.recording) return this.recording; this.recording = (async () => { const p = JSON.parse(JSON.stringify(this.host.params())) as Params; const note = this.host.note(), vel = this.host.velocity(), duration = this.duration; try { const body = await this.host.body(); const shapes = await this.shapesFor(p); const diag = (body.meta?.diag as { ke: number[] }[] | undefined) ?? null; const spec: RecordSpec = { denseFrom: detailFrom !== undefined ? Math.max(0, detailFrom - 0.001) : 0, denseTo: detailFrom !== undefined ? detailFrom + 0.05 : Infinity, denseAfterRelease: 0.05, maxDense: 9000, sparseDt: 0.0005, stringPoints: 128, sympPoints: 48, shapeModes: shapes ? shapes.nModes : 0, airFrac: diag ? diag.map((d) => (d.ke[3] ?? 0) + (d.ke[4] ?? 0)) : undefined, }; this.host.status(`Recording ${noteName(note)} v${vel} for the physics view…`); this.host.progress(0); const r = await this.host.record(p, body, note, vel, duration, spec, (f) => this.host.progress(f)); const rec: Rec = { R: r.recording, mic: r.mic, pickup: r.pickup, fs: r.sampleRate, note, velocity: vel, duration, params: p, body, shapes, key: this.recKey(), maxString: 0, maxBody: 0, maxPlate: 0, maxAir: 0, eMax: 0 }; this.analyse(rec); const keepT = detailFrom !== undefined ? detailFrom : this.rec && this.rec.note === note ? this.t : 0; this.rec = rec; this.mode = { kind: "replay" }; this.ensureScene(); this.t = Math.min(keepT, this.tEnd()); if (detailFrom === undefined && keepT === 0) this.t = 0; this.host.progress(1); this.host.status(`Recorded ${noteName(note)} v${vel}: ${r.recording.frameTimes.length} frames (${(r.recording.frames.byteLength / 1e6).toFixed(0)} MB). Play it, or scrub the time bar.`); this.drawModeList(); this.dirty = true; } catch (e) { this.host.status(`Recording failed: ${(e as Error).message.split("\n")[0]}`, true); } })().finally(() => { this.recording = null; // the note or the parameters changed while recording: record again if (this.visible && this.rec && this.rec.key !== this.recKey()) void this.record(); }); return this.recording; } /** Maxima for automatic display scaling. */ private analyse(rec: Rec): void { const R = rec.R, F = R.frameSize, n = R.frameTimes.length; let ms = 0, mb = 0; for (let f = 0; f < n; f++) { const o = f * F; for (const s of R.strings) { const P = s.points; for (let j = 0; j < P; j++) { const xi = j / (P - 1); ms = Math.max(ms, Math.abs(R.frames[o + s.offset + j] - xi * R.frames[o + s.offset + P - 1]), Math.abs(R.frames[o + s.offset + P + j] - xi * R.frames[o + s.offset + 2 * P - 1])); } } for (let i = 0; i < 8; i++) mb = Math.max(mb, Math.abs(R.frames[o + R.notchOffset + i])); } rec.maxString = ms; let mp = 0, ma = 0; if (rec.shapes) { const step = Math.max(1, Math.floor(n / 150)); this.allocFields(rec); for (let f = 0; f < n; f += step) { this.bodyFields(rec, R.frames.subarray(f * F, (f + 1) * F)); for (const v of this.fields.top) mp = Math.max(mp, Math.abs(v)); for (const v of this.fields.back) mp = Math.max(mp, Math.abs(v)); for (const v of this.fields.air) ma = Math.max(ma, Math.abs(v)); } } rec.maxPlate = mp; rec.maxAir = ma; rec.maxBody = Math.max(mb, mp); let e = 0; for (const c of ["eString", "eSymp", "eBody", "eAir"] as const) for (const v of R.channels[c]) e = Math.max(e, v); rec.eMax = e; } private allocFields(rec: Rec): void { const s = rec.shapes; if (!s) return; if (this.fields.top.length !== s.topNodes.length) this.fields.top = new Float32Array(s.topNodes.length); if (this.fields.back.length !== s.backNodes.length) this.fields.back = new Float32Array(s.backNodes.length); if (this.fields.air.length !== s.cav.colH.length) this.fields.air = new Float32Array(s.cav.colH.length); if (this.fields.plug.length !== s.plugs.length) this.fields.plug = new Float32Array(s.plugs.length); } /** Plate, air and plug fields from the recorded body coordinates of one frame. */ private bodyFields(rec: Rec, frame: Float32Array): void { const s = rec.shapes!, R = rec.R; const { top, back, air, plug } = this.fields; top.fill(0); back.fill(0); air.fill(0); plug.fill(0); const nT = top.length, nB = back.length, nA = air.length, nP = plug.length; for (let q = 0; q < R.etaModes.length; q++) { const e = frame[R.etaOffset + q]; if (e === 0) continue; const m = R.etaModes[q]; let o = m * nT; for (let a = 0; a < nT; a++) top[a] += e * s.top[o + a]; o = m * nB; for (let a = 0; a < nB; a++) back[a] += e * s.back[o + a]; o = m * nA; for (let a = 0; a < nA; a++) air[a] += e * s.air[o + a]; o = m * nP; for (let a = 0; a < nP; a++) plug[a] += e * s.plug[o + a]; } } private ensureScene(): void { const rec = this.rec!; const key = JSON.stringify([rec.params.fe, rec.params.strings.scaleLength, !!rec.shapes]); const box = this.root.querySelector("#phCanvas") as HTMLElement; if (!this.scene || this.sceneKey !== key) { this.scene?.dispose(); this.scene = new BassScene(box, rec.params, rec.shapes); this.sceneKey = key; if (!rec.shapes) (this.root.querySelector("#lyAir") as HTMLInputElement).disabled = true; } const fg = fingering(rec.params, rec.note); const played = rec.R.strings.find((s) => s.played)!; const setups: StringSetup[] = rec.R.strings.map((s) => ({ string: s.string, length: s.length, points: s.points, played: s.played })); this.scene.setupStrings(setups, { string: played.string, length: played.length, stopped: fg.stopped, pluckX: rec.R.pull.x, dirY: rec.R.pull.dirY, dirZ: rec.R.pull.dirZ }); this.work = new Float32Array(rec.R.frameSize); } private tEnd(): number { const R = this.rec?.R; return R ? R.nSteps * R.dt : 1; } // ------------------------------------------------------------ transport private togglePlay(): void { if (!this.rec) return; if (this.mode.kind !== "replay") { this.mode = { kind: "replay" }; this.drawModeList(); } if (!this.playing && this.t >= this.tEnd() - 1e-9) this.t = 0; this.playing = !this.playing; this.lastWall = performance.now(); if (!this.playing) this.host.stopAudio(); } private seek(t: number): void { this.t = Math.max(0, Math.min(this.tEnd(), t)); if (this.mode.kind !== "replay") { this.mode = { kind: "replay" }; this.drawModeList(); } this.dirty = true; } private stepFrame(d: number): void { const R = this.rec?.R; if (!R) return; this.playing = false; const ft = R.frameTimes; let i = this.frameIndex(this.t); if (d > 0) { if (ft[i] <= this.t + 1e-12) i++; } else if (ft[i] >= this.t - 1e-12) i--; i = Math.max(0, Math.min(ft.length - 1, i)); this.seek(ft[i]); } /** Index of the last frame at or before t. */ private frameIndex(t: number): number { const ft = this.rec!.R.frameTimes; let lo = 0, hi = ft.length - 1; if (t <= ft[0]) return 0; while (hi - lo > 1) { const m = (lo + hi) >> 1; if (ft[m] <= t) lo = m; else hi = m; } return ft[hi] <= t ? hi : lo; } private soundFromHere(): void { const rec = this.rec; if (!rec) return; if (this.mode.kind !== "replay") { this.mode = { kind: "replay" }; this.drawModeList(); } const x = this.host.mix(rec.mic, rec.pickup); const i0 = Math.max(0, Math.round((this.t - rec.R.audioT0) * rec.fs)); if (i0 >= x.length) return; this.speed = 1; (this.root.querySelector("#phSpeed") as HTMLSelectElement).value = "1"; this.playing = true; this.lastWall = performance.now(); this.host.playAudio(x.subarray(i0), rec.fs); } private window(): [number, number] { const R = this.rec?.R, T = this.tEnd(); if (!R) return [0, 1]; if (this.win === "all") return [0, T]; if (this.win === "dense") return R.dense[0] >= 0 ? [Math.max(0, R.dense[0] - 0.001), Math.min(T, R.dense[1] + 0.001)] : [0, T]; const half = Number(this.win) / 1000; let a = this.t - half, b = this.t + half; if (a < 0) { b -= a; a = 0; } if (b > T) { a -= b - T; b = T; } return [Math.max(0, a), b]; } // ------------------------------------------------------------ per frame private tick(now: number): void { if (!this.visible || !this.rec || !this.scene) { this.lastWall = now; return; } if (this.playing) { const dt = Math.min(0.1, (now - this.lastWall) / 1000); this.t += this.speed * dt; if (this.t >= this.tEnd()) { this.t = this.tEnd(); this.playing = false; } this.dirty = true; } this.lastWall = now; if (this.mode.kind !== "replay") this.dirty = true; if (!this.dirty) return; this.dirty = false; this.drawFrame(now); if (now - this.lastPlot > 45 || !this.playing) { this.lastPlot = now; this.drawPlots(); } this.updateTransport(); } private drawFrame(now: number): void { const rec = this.rec!, R = rec.R, F = R.frameSize; const sc: Scales = { string: Math.min(400, Math.max(1, 0.03 / Math.max(rec.maxString, 1e-9))) * this.gain.string, body: (0.02 / Math.max(rec.maxBody, 1e-12)) * this.gain.body, plate: (0.6 * Math.max(rec.maxPlate, 1e-15)) / this.gain.color, air: (0.6 * Math.max(rec.maxAir, 1e-15)) / this.gain.color, }; let frame: Frame; const legend: string[] = []; if (this.mode.kind === "replay") { // interpolate between the frames around t const ft = R.frameTimes, i = this.frameIndex(this.t), j = Math.min(ft.length - 1, i + 1); const a = j > i && ft[j] > ft[i] ? Math.max(0, Math.min(1, (this.t - ft[i]) / (ft[j] - ft[i]))) : 0; const w = this.work, A = R.frames; for (let k = 0; k < F; k++) w[k] = A[i * F + k] * (1 - a) + A[j * F + k] * a; if (rec.shapes) this.bodyFields(rec, w); const pullEnd = R.tRelease + R.slipTime; const alpha = this.t <= pullEnd ? 1 : Math.max(0, 1 - (this.t - pullEnd) / 0.03); frame = { top: rec.shapes ? this.fields.top : null, back: rec.shapes ? this.fields.back : null, air: rec.shapes ? this.fields.air : null, plug: rec.shapes ? this.fields.plug : null, notch: w.subarray(R.notchOffset, R.notchOffset + 8), strings: R.strings.map((s) => ({ string: s.string, length: s.length, y: w.subarray(s.offset, s.offset + s.points), z: w.subarray(s.offset + s.points, s.offset + 2 * s.points) })), finger: { travel: R.pull.speed * this.t, alpha }, }; legend.push(`strings ×${fmtX(sc.string)} · body ×${fmtX(sc.body)}`); if (rec.shapes) legend.push(`plate colour ±${fmtLen(sc.plate)}${(this.root.querySelector("#lyAir") as HTMLInputElement).checked ? ` · air ±${fmtP(sc.air)}` : ""}`); else legend.push("parametric body: plates not modelled in space (bridge motion only)"); } else if (this.mode.kind === "body") { const m = rec.body.modes[this.mode.idx]; const c = Math.cos(2 * Math.PI * MODE_HZ * ((now - this.modeT0) / 1000)); const sh = rec.shapes && this.mode.idx < rec.shapes.nModes ? rec.shapes : null; this.allocFields(rec); let mx = 0, mA = 0; for (let i = 0; i < 4; i++) mx = Math.max(mx, Math.abs(m.by[i]), Math.abs(m.bz[i])); if (sh) { const k = this.mode.idx, f = this.fields; const fill = (dst: Float32Array, src: Float32Array) => { const n = dst.length; for (let a = 0; a < n; a++) dst[a] = src[k * n + a] * c; }; fill(f.top, sh.top); fill(f.back, sh.back); fill(f.air, sh.air); fill(f.plug, sh.plug); for (let a = 0; a < f.top.length; a++) mx = Math.max(mx, Math.abs(sh.top[k * f.top.length + a])); for (let a = 0; a < f.back.length; a++) mx = Math.max(mx, Math.abs(sh.back[k * f.back.length + a])); for (let a = 0; a < f.air.length; a++) mA = Math.max(mA, Math.abs(sh.air[k * f.air.length + a])); } const notch = [...m.by.map((v) => v * c), ...m.bz.map((v) => v * c)]; frame = { top: sh ? this.fields.top : null, back: sh ? this.fields.back : null, air: sh ? this.fields.air : null, plug: sh ? this.fields.plug : null, notch, strings: R.strings.map((s) => { const y = new Float32Array(s.points), z = new Float32Array(s.points); for (let j = 0; j < s.points; j++) { const xi = j / (s.points - 1); y[j] = notch[s.string] * xi; z[j] = notch[4 + s.string] * xi; } return { string: s.string, length: s.length, y, z }; }), finger: null, }; sc.body = (0.03 / Math.max(mx, 1e-12)) * this.gain.body; sc.plate = (0.7 * mx) / this.gain.color; sc.air = (0.7 * Math.max(mA, 1e-12)) / this.gain.color; legend.push(`body mode ${m.label ?? ""} ${m.f.toFixed(1)} Hz, Q ${(1 / (2 * m.zeta)).toFixed(0)} — shown at ${MODE_HZ} Hz${sh ? "" : " (no mesh shape: bridge only)"}`); } else { const n = this.mode.n; const played = R.strings.find((s) => s.played)!; const c = Math.cos(2 * Math.PI * MODE_HZ * ((now - this.modeT0) / 1000)); const amp = 0.001; frame = { top: null, back: null, air: null, plug: null, notch: new Float32Array(8), strings: R.strings.map((s) => { const y = new Float32Array(s.points), z = new Float32Array(s.points); if (s === played) for (let j = 0; j < s.points; j++) z[j] = amp * c * Math.sin((n * Math.PI * j) / (s.points - 1)); return { string: s.string, length: s.length, y, z }; }), finger: null, }; sc.string = (0.03 / amp) * this.gain.string; const pi = this.partials()[n - 1]; legend.push(`string partial ${n} of ${STRING_NAMES[played.string]}: ${pi ? `${pi.f.toFixed(1)} Hz, ${pi.cents >= 0 ? "+" : ""}${pi.cents.toFixed(1)} cents, T60 ${pi.t60.toFixed(2)} s` : ""} — shown at ${MODE_HZ} Hz`); } if (this.mode.kind !== "replay") legend.push(``); this.scene!.update(frame, sc); const lg = this.root.querySelector("#phLegend") as HTMLElement; const htmlL = legend.join("
"); if (lg.dataset.h !== htmlL) { lg.innerHTML = htmlL; lg.dataset.h = htmlL; lg.querySelector("#phBackRec")?.addEventListener("click", () => { this.mode = { kind: "replay" }; this.drawModeList(); this.dirty = true; }); } } private updateTransport(): void { const R = this.rec!.R, t = this.t; (this.root.querySelector("#phPlay") as HTMLElement).textContent = this.playing ? "⏸" : "▶︎"; (this.root.querySelector("#phT") as HTMLInputElement).value = String(Math.round((t / this.tEnd()) * 100000)); const phase = t < R.tRelease ? "finger sticks, pulling the string" : t < R.tRelease + R.slipTime ? "string slips off the finger" : "free vibration"; const dense = R.dense[0] >= 0 && t >= R.dense[0] - 1e-12 && t <= R.dense[1] + 1e-12; (this.root.querySelector("#phTime") as HTMLElement).innerHTML = `t = ${(t * 1000).toFixed(t < 0.1 ? 3 : 1)} ms · ${phase} · ${dense ? "every step" : `coarse frames (0.5 ms)`}`; const det = this.root.querySelector("#phDetail") as HTMLButtonElement; det.disabled = dense || !!this.recording; } private drawPlots(): void { const rec = this.rec!, R = rec.R, ch = R.channels; const [t0, t1] = this.window(); const shade = R.dense[0] >= 0 ? ([R.dense[0], R.dense[1]] as [number, number]) : null; const marks = [{ t: R.tRelease, label: "release" }, { t: R.tRelease + R.slipTime, label: "" }]; const ax = { t0, t1, playhead: this.t, shade, marks }; const c = (q: number) => this.root.querySelector(`#pc${q}`) as HTMLCanvasElement; const dt = R.dt; tracePlot(c(0), [ { data: ch.fingerFz, dt, color: css("--sim"), label: "across" }, { data: ch.fingerFy, dt, color: css("--ref"), label: "vertical" }, ], { ...ax, ylabel: "finger force on the string, N" }); tracePlot(c(1), [ { data: ch.bridgeFy, dt, color: css("--sim"), label: "vertical" }, { data: ch.bridgeFz, dt, color: css("--alt"), label: "lateral" }, ], { ...ax, ylabel: "string force on the bridge, N" }); const e0 = Math.max(rec.eMax, 1e-30); const db = (v: number) => (v > 0 ? 10 * Math.log10(v / e0) : -200); tracePlot(c(2), [ { data: ch.eString, dt, color: css("--sim"), label: "played string", map: db }, { data: ch.eSymp, dt, color: css("--mark"), label: "other strings", map: db }, { data: ch.eBody, dt, color: css("--alt"), label: "body structure", map: db }, { data: ch.eAir, dt, color: css("--ref"), label: "air", map: db }, ], { ...ax, ylabel: "energy, dB re max", ymin: -90, ymax: 3 }); tracePlot(c(3), [ { data: ch.mic, dt, color: css("--ref"), label: "mic (Pa)" }, { data: ch.pickup, dt, color: css("--alt"), label: "pickup (Pa equiv.)" }, ], { ...ax, ylabel: "sound" }); } // ------------------------------------------------------------ mode explorer private partials(): { n: number; f: number; cents: number; t60: number }[] { const rec = this.rec; const p = rec?.params ?? this.host.params(); const fg = fingering(p, rec?.note ?? this.host.note()); const L = rec ? rec.R.strings.find((s) => s.played)!.length : fg.length; const sc = stringConst(p, fg.string); const m = stringModes(p, sc, L, Math.min(p.engine.stringFmax, 5000)); const f1 = m.w[0] / (2 * Math.PI); return Array.from(m.w, (w, i) => { const f = w / (2 * Math.PI); return { n: i + 1, f, cents: 1200 * Math.log2(f / ((i + 1) * f1)), t60: Math.log(1000) / m.sigma[i] }; }); } private drawModeList(): void { const box = this.root.querySelector("#phModes") as HTMLElement; (this.root.querySelector("#mtBody") as HTMLElement).classList.toggle("on", this.modeTab === "body"); (this.root.querySelector("#mtPart") as HTMLElement).classList.toggle("on", this.modeTab === "partials"); const rec = this.rec; if (!rec) { box.innerHTML = `

Record a note first.

`; return; } const sel = this.mode; if (this.modeTab === "body") { const b = rec.body, si = rec.R.strings.find((s) => s.played)!.string; const nSh = rec.shapes?.nModes ?? 0; const diag = (b.meta?.diag as { ke: number[] }[] | undefined) ?? null; let radMax = 0; for (const m of b.modes) radMax = Math.max(radMax, Math.hypot(m.radRe, m.radIm) * (2 * Math.PI * m.f) ** 2); const rows: string[] = []; const limit = nSh > 0 ? nSh : Math.min(b.modes.length, 200); for (let k = 0; k < limit; k++) { const m = b.modes[k]; const air = diag?.[k] ? (diag[k].ke[3] + diag[k].ke[4]) * 100 : m.label === "A0" ? 100 : NaN; const rad = 20 * Math.log10((Math.hypot(m.radRe, m.radIm) * (2 * Math.PI * m.f) ** 2) / radMax + 1e-12); rows.push(`${m.label ?? ""}${m.f.toFixed(1)}${(1 / (2 * m.zeta)).toFixed(0)}${(Math.log(1000) / (m.zeta * 2 * Math.PI * m.f)).toFixed(2)}${(Math.abs(m.by[si]) * 1000).toFixed(0)}${isFinite(air) ? air.toFixed(0) : ""}${rad.toFixed(0)}`); } const more = b.modes.length - limit; box.innerHTML = `${rows.join("")}
f HzQT60 sbridgeair %rad dB
${more > 0 ? `

+ ${more} ${nSh > 0 ? "statistical modes above the FE range (no mesh shape)" : "more modes"}.

` : ""}

Click a mode to see it move (slowed to ${MODE_HZ} Hz).

`; box.querySelectorAll("tr[data-k]").forEach((tr) => tr.addEventListener("click", () => { this.mode = { kind: "body", idx: Number(tr.dataset.k) }; this.playing = false; this.modeT0 = performance.now(); this.drawModeList(); this.dirty = true; })); } else { const ps = this.partials().slice(0, 60); const rows = ps.map((q) => `${q.n}${q.f.toFixed(1)}${q.cents >= 0 ? "+" : ""}${q.cents.toFixed(1)}${q.t60.toFixed(2)}`).join(""); box.innerHTML = `${rows}
nf HzcentsT60 s

Partials of the played string (stiff string, Valette damping, rigid ends). Click one to see its shape.

`; box.querySelectorAll("tr[data-n]").forEach((tr) => tr.addEventListener("click", () => { this.mode = { kind: "partial", n: Number(tr.dataset.n) }; this.playing = false; this.modeT0 = performance.now(); this.drawModeList(); this.dirty = true; })); } } } function fmtX(v: number): string { return v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toPrecision(2); } function fmtLen(m: number): string { return m >= 1e-3 ? `${(m * 1e3).toPrecision(2)} mm` : m >= 1e-6 ? `${(m * 1e6).toPrecision(2)} µm` : `${(m * 1e9).toPrecision(2)} nm`; } function fmtP(p: number): string { return p >= 1 ? `${p.toPrecision(2)} Pa` : `${(p * 1e3).toPrecision(2)} mPa`; }