// Lab: the double pendulum as an instrument (audio-rate simulation, its motion is the sound). // Click the plot (or press S) to strike. Not part of the album; reachable at #/lab. import { dbToGain, type AudioEngine } from "../../core/audio.ts"; import type { Piece } from "../../core/composition.ts"; import type { Params } from "../../core/params.ts"; import type { LabMsg, LabSettings, LabSnap, Signal } from "../../lab/protocol.ts"; import workletUrl from "../../lab/pendulumWorklet.ts?worker&url"; import { cssColor, fitCanvas } from "../shared/section.ts"; const loaded = new WeakMap>(); export function createLabPiece(view: HTMLElement, params: () => Params): Piece { const canvas = document.createElement("canvas"); canvas.title = "click (or press S) to strike"; canvas.style.cursor = "pointer"; view.append(canvas); let audio: AudioEngine | null = null; let node: AudioWorkletNode | null = null; let out: GainNode | null = null; let analyser: AnalyserNode | null = null; let timer: number | undefined; let playing = false; let startedAt = 0; let snap: LabSnap | null = null; let lastSent = ""; let token = 0; const settings = (P: Params): LabSettings => ({ mode: P.mode as LabSettings["mode"], pitch: P.pitch as number, energy: P.energy as number, strikeEnergy: P.strikeEnergy as number, ringTime: P.ringTime as number, restrike: P.restrike as number, swellTime: P.swellTime as number, massRatio: P.massRatio as number, lengthRatio: P.lengthRatio as number, left: P.left as Signal, right: P.right as Signal, gain: dbToGain(P.gain as number), dcCut: P.dcCut as number, follow: P.follow as number, }); const send = (m: LabMsg) => node?.port.postMessage(m); const strike = () => send({ type: "strike" }); canvas.onclick = strike; const onKey = (e: KeyboardEvent) => { const el = e.target; if ((e.key === "s" || e.key === "S") && !(el instanceof Element && el.closest("input, select, textarea"))) strike(); }; window.addEventListener("keydown", onKey); function sync() { if (!node || !audio || !out) return; const P = params(); const s = settings(P); const key = JSON.stringify(s); if (key !== lastSent) { lastSent = key; send({ type: "settings", s }); } out.gain.setTargetAtTime(dbToGain(P.level as number), audio.ctx.currentTime, 0.05); } async function start(a: AudioEngine) { stop(); const my = ++token; audio = a; const ctx = a.ctx; let p = loaded.get(ctx); if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(workletUrl))); await p; if (my !== token) return; out = ctx.createGain(); out.gain.value = 0; analyser = ctx.createAnalyser(); analyser.fftSize = 4096; analyser.smoothingTimeConstant = 0.6; node = new AudioWorkletNode(ctx, "pendulum-voice", { numberOfInputs: 0, outputChannelCount: [2] }); node.port.onmessage = (e: MessageEvent) => (snap = e.data); node.connect(out); out.connect(a.input); out.connect(analyser); lastSent = ""; sync(); playing = true; startedAt = ctx.currentTime; timer = window.setInterval(sync, 50); } function stop() { token++; if (timer !== undefined) window.clearInterval(timer); timer = undefined; playing = false; if (!audio) return; const o = out, n = node, an = analyser; if (o) o.gain.setTargetAtTime(0, audio.ctx.currentTime, 0.03); window.setTimeout(() => { n?.disconnect(); o?.disconnect(); an?.disconnect(); }, 300); node = out = analyser = null; } const wave = new Float32Array(2048); let spec: Float32Array | null = null; function draw() { const P = params(); const g = fitCanvas(canvas); const w = canvas.clientWidth, h = canvas.clientHeight; g.clearRect(0, 0, w, h); const fg = cssColor(view, "--fg"), dim = cssColor(view, "--dim"), muted = cssColor(view, "--muted"); const top = h * 0.62; // bob path above, waveform and spectrum below // bob path over the last few ms if (snap) { const tr = snap.trail; const pts = tr.length / 4; const msPer = (2 / 48000) * 1000; // decimation 2 at ~48 kHz const nShow = Math.min(pts, Math.round((P.trailMs as number) / msPer)); const L = 1 + (P.lengthRatio as number); const sc = (0.46 * Math.min(w, top)) / L; const cx = w / 2, cy = top / 2; g.lineWidth = 1; g.strokeStyle = fg; g.beginPath(); for (let i = pts - nShow; i < pts; i++) { const x = cx + sc * tr[4 * i + 2], y = cy + sc * tr[4 * i + 3]; if (i === pts - nShow) g.moveTo(x, y); else g.lineTo(x, y); } g.globalAlpha = 0.8; g.stroke(); // the current pose const i = pts - 1; g.globalAlpha = 1; g.strokeStyle = muted; g.beginPath(); g.moveTo(cx, cy); g.lineTo(cx + sc * tr[4 * i], cy + sc * tr[4 * i + 1]); g.lineTo(cx + sc * tr[4 * i + 2], cy + sc * tr[4 * i + 3]); g.stroke(); } // waveform and spectrum if (analyser) { const wh = (h - top) * 0.45, sy = top + 8; analyser.getFloatTimeDomainData(wave); g.strokeStyle = fg; g.lineWidth = 1; g.beginPath(); const N = 1024; for (let i = 0; i < N; i++) { const x = (i / (N - 1)) * w, y = sy + wh / 2 - (wave[i] * wh) / 2; if (i) g.lineTo(x, y); else g.moveTo(x, y); } g.stroke(); if (!spec || spec.length !== analyser.frequencyBinCount) spec = new Float32Array(analyser.frequencyBinCount); analyser.getFloatFrequencyData(spec); const sh = (h - top) * 0.45, sb = h - 4; const sr = audio!.ctx.sampleRate; const fx = (f: number) => (Math.log(f / 20) / Math.log(20000 / 20)) * w; g.strokeStyle = dim; g.beginPath(); for (const f of [100, 1000, 10000]) { g.moveTo(fx(f), sb - sh); g.lineTo(fx(f), sb); } g.stroke(); g.strokeStyle = fg; g.beginPath(); let started = false; for (let b = 1; b < spec.length; b++) { const f = (b * sr) / (2 * spec.length); if (f < 20 || f > 20000) continue; const v = Math.max(0, Math.min(1, (spec[b] + 110) / 100)); const x = fx(f), y = sb - v * sh; if (started) g.lineTo(x, y); else g.moveTo(x, y), (started = true); } g.stroke(); } if (!playing) { g.fillStyle = muted; g.font = "12px ui-monospace, monospace"; g.fillText("play, then click here (or press S) to strike", 8, 16); } } function readouts(): Record { return { mode: playing && snap ? snap.phase : "–", energy: snap ? snap.energy.toFixed(4) : "–", "time scale": snap ? `${snap.k.toFixed(0)} sim s per s` : "–", strike: "click the plot or press S", }; } return { get playing() { return playing; }, start: (a) => start(a), stop, draw, now: () => (playing && audio ? audio.ctx.currentTime - startedAt : 0), length: () => Infinity, readouts, dispose() { stop(); window.removeEventListener("keydown", onKey); view.replaceChildren(); }, }; }