1// The double pendulum as an instrument: simulated at audio rate inside the AudioWorklet, its
2// motion is the waveform. Time is scaled so the pendulum's lower small-swing mode lands at
3// `pitch` Hz. Modes: strike (start at an energy, ring down through damping, re-strike),
4// sustain (an energy controller holds the energy, like bowing), swell (energy rises, then rings
5// down). Any state quantity can be the left/right output.
7import { DoublePendulum } from "../physics/doublePendulum.ts";
8import { mulberry32 } from "../core/rng.ts";
9import type { LabMsg, LabSettings, LabSnap, Signal } from "./protocol.ts";
11declare const sampleRate: number;
12declare const currentTime: number;
13declare class AudioWorkletProcessor {
14 readonly port: MessagePort;
15 constructor();
16}
17declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void;
19const TRAIL = 384; // samples of bob path sent per snapshot (decimated)
20const DECIM = 2;
22class PendulumVoice extends AudioWorkletProcessor {
23 private s: LabSettings | null = null;
24 private p = new DoublePendulum({ m1: 1, m2: 1, l1: 1, l2: 1, g: 1 });
25 private rand = mulberry32(12345);
26 private t = 0; // audio seconds since the last strike/swell
27 private swellFrom = 0; // energy (normalized) when the current swell began
28 private phase = "silent";
29 private dcL = { x: 0, y: 0 };
30 private dcR = { x: 0, y: 0 };
31 private trail = new Float32Array(4 * TRAIL);
32 private trailW = 0;
33 private sinceSnap = 0;
34 private sampleCount = 0;
36 constructor() {
37 super();
38 this.p.controlled = false;
39 this.port.onmessage = (e: MessageEvent<LabMsg>) => {
40 if (e.data.type === "settings") {
41 const first = !this.s;
42 this.s = e.data.s;
43 this.p.cfg.m2 = this.s.massRatio;
44 this.p.cfg.l2 = this.s.lengthRatio;
45 if (first) {
46 // start hanging at rest; the first strike sets it going
47 this.p.y.fill(0);
48 this.strike();
49 }
50 } else if (e.data.type === "strike") this.strike();
51 };
52 }
54 /** ω of the lower small-swing mode (sim units), for the time scaling. */
55 private lowMode(): number {
56 const { m1, m2, l1, l2, g } = this.p.cfg;
57 // small oscillations: eigenvalues of M⁻¹K for the linearized double pendulum
58 const a = (m1 + m2) * l1 * l1, b = m2 * l1 * l2, c = m2 * l2 * l2;
59 const ka = (m1 + m2) * g * l1, kc = m2 * g * l2;
60 const det = a * c - b * b;
61 const tr = (ka * c + kc * a) / det, dt = (ka * kc) / det;
62 const lam = (tr - Math.sqrt(Math.max(0, tr * tr - 4 * dt))) / 2;
63 return Math.sqrt(Math.max(lam, 1e-9));
64 }
66 /**
67 * A strike adds energy to the current motion (it never restarts): a momentum kick along the
68 * current momentum (like pushing a swing in time, so it always adds), or in a random direction
69 * if the pendulum is still, sized so the energy rises by exactly `strikeEnergy`.
70 */
71 private strike() {
72 const s = this.s;
73 if (!s) return;
74 this.t = 0;
75 if (s.mode === "swell") {
76 this.swellFrom = this.p.energyNorm();
77 this.phase = "swelling";
78 if (this.swellFrom < 1e-6) this.kick(1e-4 * this.p.vTop); // something to swell from
79 return;
80 }
81 this.kick(s.strikeEnergy * this.p.vTop);
82 }
84 private kick(add: number) {
85 const p = this.p, y = p.y;
86 if (!(add > 0)) return;
87 let u0 = y[2], u1 = y[3];
88 const pn = Math.hypot(u0, u1);
89 if (pn > 1e-9) {
90 u0 /= pn;
91 u1 /= pn;
92 } else {
93 const a = this.rand() * 2 * Math.PI;
94 u0 = Math.cos(a);
95 u1 = Math.sin(a);
96 }
97 // energy after p → p + a·u is E + a·(u·ω) + ½a²·(u·M⁻¹u); solve for the positive a
98 const now = p.derived();
99 const b = u0 * now.w1 + u1 * now.w2;
100 const wu = p.derived([y[0], y[1], u0, u1]);
101 const c = u0 * wu.w1 + u1 * wu.w2;
102 const a = (-b + Math.sqrt(Math.max(0, b * b + 2 * c * add))) / c;
103 y[2] += a * u0;
104 y[3] += a * u1;
105 }
107 private signal(sig: Signal, w1: number, w2: number): number {
108 const { l1, l2, m2 } = this.p.cfg;
109 const y = this.p.y;
110 const L = l1 + l2;
111 const vmax = Math.sqrt((2 * this.p.vTop) / m2) + 1e-9;
112 const s1 = Math.sin(y[0]), c1 = Math.cos(y[0]), s2 = Math.sin(y[1]), c2 = Math.cos(y[1]);
113 switch (sig) {
114 case "x2": return (l1 * s1 + l2 * s2) / L;
115 case "y2": return -(l1 * c1 + l2 * c2) / L;
116 case "vx2": return (l1 * c1 * w1 + l2 * c2 * w2) / vmax;
117 case "vy2": return (l1 * s1 * w1 + l2 * s2 * w2) / vmax;
118 case "x1": return s1;
119 case "vx1": return (l1 * c1 * w1) / vmax;
120 case "θ1": return Math.atan2(s1, c1) / Math.PI;
121 case "θ2": return Math.atan2(s2, c2) / Math.PI;
122 case "θ2−θ1": return Math.atan2(Math.sin(y[1] - y[0]), Math.cos(y[1] - y[0])) / Math.PI;
123 case "ω1": return (w1 * l1) / vmax;
124 case "ω2": return (w2 * l2) / vmax;
125 case "p1": return y[2] / (vmax * (1 + m2) * l1 * l1 + 1e-9);
126 case "p2": return y[3] / (vmax * m2 * l2 * l2 + 1e-9);
127 case "speed2": return Math.hypot(l1 * c1 * w1 + l2 * c2 * w2, l1 * s1 * w1 + l2 * s2 * w2) / vmax;
128 }
129 }
131 process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
132 const out = outputs[0];
133 const Lo = out[0], Ro = out[1] ?? out[0];
134 const s = this.s;
135 if (!s) return true;
136 const n = Lo.length;
137 const p = this.p;
138 const w0 = this.lowMode();
139 const k = (2 * Math.PI * s.pitch) / w0; // sim seconds per audio second
140 const dtSample = k / sampleRate;
141 const sub = Math.max(1, Math.ceil(dtSample / 0.004));
142 const h = dtSample / sub;
143 // ring time (amplitude −60 dB in s audio) → viscous damping rate (energy ∝ e^{−γ t_sim})
144 const gamma = s.ringTime > 0 ? (2 * 6.9078) / (s.ringTime * k) : 0;
145 const dcR = 1 - (2 * Math.PI * s.dcCut) / sampleRate;
146 const period = (2 * Math.PI) / w0; // sim seconds
147 p.tau = Math.max(0.05, s.follow * period);
148 for (let i = 0; i < n; i++) {
149 // mode logic (audio time since the last strike)
150 if (s.mode === "sustain") {
151 this.phase = "sustaining";
152 p.controlled = true;
153 p.eTarget = s.energy * p.vTop;
154 p.damping = 0;
155 } else if (s.mode === "swell") {
156 if (this.t < s.swellTime) {
157 p.controlled = true;
158 const u = this.t / Math.max(0.01, s.swellTime);
159 p.eTarget = (this.swellFrom + (s.energy - this.swellFrom) * u * u) * p.vTop;
160 p.damping = 0;
161 this.phase = "swelling";
162 } else {
163 p.controlled = false;
164 p.damping = gamma;
165 this.phase = "ringing";
166 }
167 } else {
168 p.controlled = false;
169 p.damping = gamma;
170 this.phase = "ringing";
171 }
172 for (let j = 0; j < sub; j++) p.step(h);
173 this.t += 1 / sampleRate;
174 if (s.restrike > 0 && this.t >= s.restrike) this.strike();
176 const d = p.derived();
177 let l = this.signal(s.left, d.w1, d.w2), r = s.right === s.left ? l : this.signal(s.right, d.w1, d.w2);
178 // remove constant offsets (angles and positions sit off zero), then gain and a soft limit
179 const yl = l - this.dcL.x + dcR * this.dcL.y;
180 this.dcL.x = l;
181 this.dcL.y = yl;
182 const yr = r - this.dcR.x + dcR * this.dcR.y;
183 this.dcR.x = r;
184 this.dcR.y = yr;
185 l = Math.tanh(s.gain * yl);
186 r = Math.tanh(s.gain * yr);
187 Lo[i] = Number.isFinite(l) ? l : 0;
188 Ro[i] = Number.isFinite(r) ? r : 0;
189 if (!Number.isFinite(p.y[0])) this.strike(); // never let a blow-up stick
191 // bob path for the display
192 if (++this.sampleCount % DECIM === 0) {
193 const y = p.y, cfg = p.cfg, o = 4 * this.trailW;
194 const x1 = cfg.l1 * Math.sin(y[0]), y1 = cfg.l1 * Math.cos(y[0]);
195 this.trail[o] = x1;
196 this.trail[o + 1] = y1;
197 this.trail[o + 2] = x1 + cfg.l2 * Math.sin(y[1]);
198 this.trail[o + 3] = y1 + cfg.l2 * Math.cos(y[1]);
199 this.trailW = (this.trailW + 1) % TRAIL;
200 }
201 }
202 this.sinceSnap += n;
203 if (this.sinceSnap >= sampleRate / 60) {
204 this.sinceSnap = 0;
205 // oldest → newest
206 const tr = new Float32Array(4 * TRAIL);
207 tr.set(this.trail.subarray(4 * this.trailW));
208 tr.set(this.trail.subarray(0, 4 * this.trailW), 4 * (TRAIL - this.trailW));
209 const snap: LabSnap = { type: "snap", energy: p.energyNorm(), phase: this.phase, trail: tr, k };
210 this.port.postMessage(snap, [tr.buffer]);
211 }
212 void currentTime;
213 return true;
214 }
215}
217registerProcessor("pendulum-voice", PendulumVoice);