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