/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / lab / piece.ts
220 lines · 7.1 KBBlameHistoryRaw
1// Lab: the double pendulum as an instrument (audio-rate simulation, its motion is the sound).
2// Click the plot (or press S) to strike. Not part of the album; reachable at #/lab.
4import { dbToGain, type AudioEngine } from "../../core/audio.ts";
5import type { Piece } from "../../core/composition.ts";
6import type { Params } from "../../core/params.ts";
7import type { LabMsg, LabSettings, LabSnap, Signal } from "../../lab/protocol.ts";
8import workletUrl from "../../lab/pendulumWorklet.ts?worker&url";
9import { cssColor, fitCanvas } from "../shared/section.ts";
11const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
13export function createLabPiece(view: HTMLElement, params: () => Params): Piece {
14 const canvas = document.createElement("canvas");
15 canvas.title = "click (or press S) to strike";
16 canvas.style.cursor = "pointer";
17 view.append(canvas);
19 let audio: AudioEngine | null = null;
20 let node: AudioWorkletNode | null = null;
21 let out: GainNode | null = null;
22 let analyser: AnalyserNode | null = null;
23 let timer: number | undefined;
24 let playing = false;
25 let startedAt = 0;
26 let snap: LabSnap | null = null;
27 let lastSent = "";
28 let token = 0;
30 const settings = (P: Params): LabSettings => ({
31 mode: P.mode as LabSettings["mode"],
32 pitch: P.pitch as number,
33 energy: P.energy as number,
34 strikeEnergy: P.strikeEnergy as number,
35 ringTime: P.ringTime as number,
36 restrike: P.restrike as number,
37 swellTime: P.swellTime as number,
38 massRatio: P.massRatio as number,
39 lengthRatio: P.lengthRatio as number,
40 left: P.left as Signal,
41 right: P.right as Signal,
42 gain: dbToGain(P.gain as number),
43 dcCut: P.dcCut as number,
44 follow: P.follow as number,
45 });
47 const send = (m: LabMsg) => node?.port.postMessage(m);
48 const strike = () => send({ type: "strike" });
49 canvas.onclick = strike;
50 const onKey = (e: KeyboardEvent) => {
51 const el = e.target;
52 if ((e.key === "s" || e.key === "S") && !(el instanceof Element && el.closest("input, select, textarea"))) strike();
53 };
54 window.addEventListener("keydown", onKey);
56 function sync() {
57 if (!node || !audio || !out) return;
58 const P = params();
59 const s = settings(P);
60 const key = JSON.stringify(s);
61 if (key !== lastSent) {
62 lastSent = key;
63 send({ type: "settings", s });
64 }
65 out.gain.setTargetAtTime(dbToGain(P.level as number), audio.ctx.currentTime, 0.05);
66 }
68 async function start(a: AudioEngine) {
69 stop();
70 const my = ++token;
71 audio = a;
72 const ctx = a.ctx;
73 let p = loaded.get(ctx);
74 if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(workletUrl)));
75 await p;
76 if (my !== token) return;
77 out = ctx.createGain();
78 out.gain.value = 0;
79 analyser = ctx.createAnalyser();
80 analyser.fftSize = 4096;
81 analyser.smoothingTimeConstant = 0.6;
82 node = new AudioWorkletNode(ctx, "pendulum-voice", { numberOfInputs: 0, outputChannelCount: [2] });
83 node.port.onmessage = (e: MessageEvent<LabSnap>) => (snap = e.data);
84 node.connect(out);
85 out.connect(a.input);
86 out.connect(analyser);
87 lastSent = "";
88 sync();
89 playing = true;
90 startedAt = ctx.currentTime;
91 timer = window.setInterval(sync, 50);
92 }
94 function stop() {
95 token++;
96 if (timer !== undefined) window.clearInterval(timer);
97 timer = undefined;
98 playing = false;
99 if (!audio) return;
100 const o = out, n = node, an = analyser;
101 if (o) o.gain.setTargetAtTime(0, audio.ctx.currentTime, 0.03);
102 window.setTimeout(() => {
103 n?.disconnect();
104 o?.disconnect();
105 an?.disconnect();
106 }, 300);
107 node = out = analyser = null;
108 }
110 const wave = new Float32Array(2048);
111 let spec: Float32Array<ArrayBuffer> | null = null;
113 function draw() {
114 const P = params();
115 const g = fitCanvas(canvas);
116 const w = canvas.clientWidth, h = canvas.clientHeight;
117 g.clearRect(0, 0, w, h);
118 const fg = cssColor(view, "--fg"), dim = cssColor(view, "--dim"), muted = cssColor(view, "--muted");
119 const top = h * 0.62; // bob path above, waveform and spectrum below
120 // bob path over the last few ms
121 if (snap) {
122 const tr = snap.trail;
123 const pts = tr.length / 4;
124 const msPer = (2 / 48000) * 1000; // decimation 2 at ~48 kHz
125 const nShow = Math.min(pts, Math.round((P.trailMs as number) / msPer));
126 const L = 1 + (P.lengthRatio as number);
127 const sc = (0.46 * Math.min(w, top)) / L;
128 const cx = w / 2, cy = top / 2;
129 g.lineWidth = 1;
130 g.strokeStyle = fg;
131 g.beginPath();
132 for (let i = pts - nShow; i < pts; i++) {
133 const x = cx + sc * tr[4 * i + 2], y = cy + sc * tr[4 * i + 3];
134 if (i === pts - nShow) g.moveTo(x, y);
135 else g.lineTo(x, y);
136 }
137 g.globalAlpha = 0.8;
138 g.stroke();
139 // the current pose
140 const i = pts - 1;
141 g.globalAlpha = 1;
142 g.strokeStyle = muted;
143 g.beginPath();
144 g.moveTo(cx, cy);
145 g.lineTo(cx + sc * tr[4 * i], cy + sc * tr[4 * i + 1]);
146 g.lineTo(cx + sc * tr[4 * i + 2], cy + sc * tr[4 * i + 3]);
147 g.stroke();
148 }
149 // waveform and spectrum
150 if (analyser) {
151 const wh = (h - top) * 0.45, sy = top + 8;
152 analyser.getFloatTimeDomainData(wave);
153 g.strokeStyle = fg;
154 g.lineWidth = 1;
155 g.beginPath();
156 const N = 1024;
157 for (let i = 0; i < N; i++) {
158 const x = (i / (N - 1)) * w, y = sy + wh / 2 - (wave[i] * wh) / 2;
159 if (i) g.lineTo(x, y);
160 else g.moveTo(x, y);
161 }
162 g.stroke();
163 if (!spec || spec.length !== analyser.frequencyBinCount) spec = new Float32Array(analyser.frequencyBinCount);
164 analyser.getFloatFrequencyData(spec);
165 const sh = (h - top) * 0.45, sb = h - 4;
166 const sr = audio!.ctx.sampleRate;
167 const fx = (f: number) => (Math.log(f / 20) / Math.log(20000 / 20)) * w;
168 g.strokeStyle = dim;
169 g.beginPath();
170 for (const f of [100, 1000, 10000]) {
171 g.moveTo(fx(f), sb - sh);
172 g.lineTo(fx(f), sb);
173 }
174 g.stroke();
175 g.strokeStyle = fg;
176 g.beginPath();
177 let started = false;
178 for (let b = 1; b < spec.length; b++) {
179 const f = (b * sr) / (2 * spec.length);
180 if (f < 20 || f > 20000) continue;
181 const v = Math.max(0, Math.min(1, (spec[b] + 110) / 100));
182 const x = fx(f), y = sb - v * sh;
183 if (started) g.lineTo(x, y);
184 else g.moveTo(x, y), (started = true);
185 }
186 g.stroke();
187 }
188 if (!playing) {
189 g.fillStyle = muted;
190 g.font = "12px ui-monospace, monospace";
191 g.fillText("play, then click here (or press S) to strike", 8, 16);
192 }
193 }
195 function readouts(): Record<string, string> {
196 return {
197 mode: playing && snap ? snap.phase : "–",
198 energy: snap ? snap.energy.toFixed(4) : "–",
199 "time scale": snap ? `${snap.k.toFixed(0)} sim s per s` : "–",
200 strike: "click the plot or press S",
201 };
202 }
204 return {
205 get playing() {
206 return playing;
207 },
208 start: (a) => start(a),
209 stop,
210 draw,
211 now: () => (playing && audio ? audio.ctx.currentTime - startedAt : 0),
212 length: () => Infinity,
213 readouts,
214 dispose() {
215 stop();
216 window.removeEventListener("keydown", onKey);
217 view.replaceChildren();
218 },
219 };
↑↓ move↵openescclose