/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c05-ensemble / score.ts
129 lines · 5.5 KBBlameHistoryRaw
1// Composition 5: ensemble — the score (score worker). The sound is the pendulums themselves:
2// six double pendulums simulated at audio rate on one shared time scale (so each one's pitch comes
3// from its size; proportions solved from musical ratios in harmony.ts), each contributing a state
4// quantity (by default its outer bob's horizontal position) as its waveform. The score pushes them
5// in chords ("36 25 … 1!4"); after the last step they ring out and fade.
6//
7// Drawing data: track 0 = per pendulum [x1, y1, x2, y2] (120 per piece second); track 1 = per
8// pendulum [x2, y2] (8000 per piece second, for the bobs' short paths); events "push" (i).
10import type { Params } from "../../core/params.ts";
11import { mulberry32 } from "../../core/rng.ts";
12import { DcBlock, kick, signal } from "../../lab/voice.ts";
13import type { Signal } from "../../lab/protocol.ts";
14import { cos, exp, sin, tanh } from "../../physics/dmath.ts";
15import { DoublePendulum } from "../../physics/doublePendulum.ts";
16import { SAMPLE_RATE } from "../../stream/protocol.ts";
17import type { ScoreFactory } from "../../stream/score.ts";
18import { build, parseRatio, timeScale, type Built } from "./harmony.ts";
19import { START_DELAY, parseScore, scoreEnd, stepSec } from "./layout.ts";
21export const N = 6;
22const STEPS_PER_CYCLE = 40; // RK4 steps per cycle of a pendulum's faster mode, at least
23const JOINTS_EVERY = SAMPLE_RATE / 120;
24const BOBS_EVERY = 6; // samples between rows of the bobs' paths (8 kHz)
26/** Physics for every pendulum from the musical ratios: one time scale, sizes and masses solved. */
27export function physics(P: Params): { k: number; built: Built[] } {
28 const base = P.basePitch as number;
29 const v = Array.from({ length: N }, (_, i) => ({
30 ratio: parseRatio(P[`ratio${i + 1}`] as string),
31 partial: parseRatio(P[`partial${i + 1}`] as string),
32 shape: P[`shape${i + 1}`] as number,
33 }));
34 // the lowest-pitched pendulum is the biggest: give it l1 = 1
35 const low = v.reduce((a, b) => (b.ratio < a.ratio ? b : a));
36 const k = timeScale(base, low.ratio, low.partial, low.shape);
37 return { k, built: v.map((x) => build(base, x.ratio, x.partial, x.shape, k)) };
40export const ensembleScore: ScoreFactory = (P: Params, seed: number, sink) => {
41 const { k, built } = physics(P);
42 const rand = mulberry32(seed);
43 const sig = P.signal as Signal;
44 const gain = exp((P.gain as number) * 0.11512925464970229); // dB → linear
45 const dcR = 1 - (2 * Math.PI * (P.dcCut as number)) / SAMPLE_RATE;
46 const steps = parseScore(P.score as string, P.pulseAdds as number, P.accent as number);
47 const stepS = stepSec(P);
48 const end = scoreEnd(P) + (P.tail as number);
49 const fadeLen = Math.min(P.fade as number, P.tail as number);
50 const dtS = k / SAMPLE_RATE;
51 const voices = built.map((b, i) => {
52 const p = new DoublePendulum({ m1: 1, m2: b.m2, l1: b.l1, l2: b.l2, g: 1 });
53 p.controlled = false;
54 const ring = P[`ring${i + 1}`] as number;
55 p.damping = ring > 0 ? (2 * 6.9078) / (ring * k) : 0;
56 const sub = Math.max(1, Math.ceil((STEPS_PER_CYCLE * b.upper) / SAMPLE_RATE));
57 const pan = P.spread as number * ((2 * i) / (N - 1) - 1);
58 const a = ((pan + 1) * Math.PI) / 4; // equal-power
59 const level = exp((P[`level${i + 1}`] as number) * 0.11512925464970229);
60 return { p, dc: new DcBlock(), sub, h: dtS / sub, gl: cos(a) * level, gr: sin(a) * level };
61 });
63 let sample = 0; // samples simulated
64 let step = 0; // score steps played
65 let ended = false;
66 const joints = new Float64Array(4 * N), bobs = new Float64Array(2 * N);
68 function advance(t: number) {
69 if (!ended) {
70 ended = true;
71 sink.end(end);
72 }
73 const target = Math.round(t * SAMPLE_RATE);
74 const n = target - sample;
75 if (n <= 0) return;
76 const L = new Float32Array(n), R = new Float32Array(n);
77 for (let j = 0; j < n; j++, sample++) {
78 const time = sample / SAMPLE_RATE;
79 // the score: step k falls at START_DELAY + k·step
80 if (step < steps.length && time >= START_DELAY + step * stepS) {
81 for (const push of steps[step]) {
82 const v = voices[push.i];
83 if (!v) continue;
84 kick(v.p, push.add * v.p.vTop, rand);
85 sink.event({ t: time, kind: "push", i: push.i });
86 }
87 step++;
88 }
89 let l = 0, r = 0;
90 for (const v of voices) {
91 for (let s = 0; s < v.sub; s++) v.p.step(v.h);
92 if (!Number.isFinite(v.p.y[0])) v.p.y.fill(0);
93 const d = v.p.derived();
94 const x = tanh(gain * v.dc.run(signal(v.p, sig, d.w1, d.w2), dcR));
95 l += v.gl * x;
96 r += v.gr * x;
97 }
98 // the end: fade over the last `fadeLen` s
99 const u = Math.max(0, Math.min(1, (end - time) / fadeLen));
100 L[j] = l * u * u;
101 R[j] = r * u * u;
102 if (sample % BOBS_EVERY === 0) {
103 voices.forEach((v, i) => {
104 const y = v.p.y, c = v.p.cfg;
105 bobs[2 * i] = c.l1 * sin(y[0]) + c.l2 * sin(y[1]);
106 bobs[2 * i + 1] = c.l1 * cos(y[0]) + c.l2 * cos(y[1]);
107 });
108 sink.frame(1, time, bobs);
109 }
110 if (sample % JOINTS_EVERY === 0) {
111 voices.forEach((v, i) => {
112 const y = v.p.y, c = v.p.cfg;
113 const x1 = c.l1 * sin(y[0]), y1 = c.l1 * cos(y[0]);
114 joints.set([x1, y1, x1 + c.l2 * sin(y[1]), y1 + c.l2 * cos(y[1])], 4 * i);
115 });
116 sink.frame(0, time, joints);
117 sink.info(time, { score: `step ${step} of ${steps.length}`, energies: voices.map((v) => v.p.energyNorm().toFixed(2)).join(" ") });
118 }
119 }
120 sink.audio(0, L, R);
121 }
123 return {
124 get time() {
125 return sample / SAMPLE_RATE;
126 },
127 advance,
128 };
129};
↑↓ move↵openescclose