1// Composition 3: divergence — the score (score worker).
2//
3// N double pendulums released together from rest at a wide angle, each outer arm offset by a tiny,
4// calibrated amount, so they swing as one and then visibly separate at about `separateAt` seconds,
5// and chaos takes over. A note sounds whenever a bottom bob crosses the vertical through the pivot
6// (either direction): in "chord" mode each pendulum has its own note of a chord (two interleaved
7// chords by direction); in "motion" mode the pitch follows the bob's speed. Notes go to the side
8// the bob is heading. After `freeTime` the pendulums are damped to rest over `dampTime`; each one's
9// last note rings out and the piece ends with the fade.
10//
11// Drawing data: track 0 = [θ1, θ2] per pendulum (120 per piece second).
13import type { Params } from "../../core/params.ts";
14import { mulberry32 } from "../../core/rng.ts";
15import { NOTE_NAMES, quantize } from "../../music/scales.ts";
16import { cos, hypot, pow, sin } from "../../physics/dmath.ts";
17import type { DoublePendulum } from "../../physics/doublePendulum.ts";
18import type { NoteRef, ScoreFactory } from "../../stream/score.ts";
19import { LEFT, RIGHT } from "./layout.ts";
20import { DT, bob, offsetForSeparation, released } from "./release.ts";
22const MAX_SETTLE = 10; // s after the damping: count every pendulum as at rest regardless
23const FRAME_DT = 1 / 120;
24const INFO_DT = 0.1;
26interface Pend {
27 p: DoublePendulum;
28 prevX: number;
29 E0: number;
30 lastNote: NoteRef | null;
31 restAt: number | null;
32}
34/** Release angles: the nominal angle, varied per play by up to `jitter` (null rand: nominal). */
35export function releaseAngles(P: Params, rand: (() => number) | null): [number, number] {
36 const deg = Math.PI / 180;
37 const base = (P.releaseAngle as number) * deg, j = (P.jitter as number) * deg;
38 return rand ? [base + (2 * rand() - 1) * j, base + (2 * rand() - 1) * j] : [base, base];
39}
41/**
42 * The chord pitches per pendulum, low to high, from the scale's notes in range (an even spread
43 * if continuous). With two chords, 2n notes are spread over the range and alternate between
44 * them: left-to-right crossings play one, right-to-left the other (its neighbour above).
45 */
46function chords(P: Params, n: number): { right: number[]; left: number[] } {
47 const low = P.pitchLow as number, high = P.pitchHigh as number;
48 const root = NOTE_NAMES.indexOf(P.root as string);
49 const two = !!P.directionChords;
50 const k = two ? 2 * n : n;
51 let notes: number[] = [];
52 if (P.scale === "continuous") notes = Array.from({ length: Math.max(k, 2) }, (_, i) => low + ((high - low) * i) / Math.max(1, Math.max(k, 2) - 1));
53 else for (let m = Math.ceil(low); m <= high; m++) if (Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) notes.push(m);
54 if (!notes.length) notes = [quantize((low + high) / 2, P.scale as string, root)];
55 const spread = Array.from({ length: k }, (_, i) => notes[k > 1 ? Math.round((i * (notes.length - 1)) / (k - 1)) : Math.floor(notes.length / 2)]);
56 if (!two) return { right: spread, left: spread };
57 return { right: spread.filter((_, i) => i % 2 === 0), left: spread.filter((_, i) => i % 2 === 1) };
58}
60export const divergenceScore: ScoreFactory = (P: Params, seed: number, sink) => {
61 const cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
62 const speed = P.speed as number;
63 const [th1, th2] = releaseAngles(P, mulberry32(seed));
64 const cal = offsetForSeparation(cfg, th1, th2, (P.separateAt as number) * speed, (P.sepThreshold as number) * (cfg.l1 + cfg.l2));
65 const n = Math.max(1, Math.round(P.count as number));
66 const pends: Pend[] = Array.from({ length: n }, (_, i) => {
67 const p = released(cfg, th1, th2, n > 1 ? (i / (n - 1) - 0.5) * cal.offset : 0);
68 return { p, prevX: bob(cfg, p.y)[0], E0: 0, lastNote: null, restAt: null };
69 });
70 const vmax0 = Math.sqrt((2 * pends[0].p.energy()) / cfg.m2);
71 const free = P.freeTime as number, damp = P.dampTime as number;
72 const curve = P.dampCurve as number, tau = P.tau as number, restE = P.restEnergy as number;
73 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
74 const chord = chords(P, n);
75 const deg = 180 / Math.PI;
76 const releaseInfo = `${(th1 * deg).toFixed(2)}°, ${(th2 * deg).toFixed(2)}°`;
77 const offsetInfo = `${cal.offset.toExponential(2)} rad → separate at ${(cal.separatesAt / speed).toFixed(1)} s`;
79 let time = 0;
80 let restAll: number | null = null;
81 let notes = 0;
82 let nextFrame = 0, nextInfo = 0;
83 const row = new Float64Array(2 * n);
85 function note(i: number, tc: number, dir: number) {
86 const d = pends[i], y = d.p.y, w = d.p.derived();
87 // bottom bob's speed at the crossing
88 const vx = cfg.l1 * cos(y[0]) * w.w1 + cfg.l2 * cos(y[1]) * w.w2;
89 const vy = cfg.l1 * sin(y[0]) * w.w1 + cfg.l2 * sin(y[1]) * w.w2;
90 const x = Math.min(1, hypot(vx, vy) / ((P.loudRef as number) * vmax0));
91 const floor = P.loudFloor as number;
92 const velocity = floor + (1 - floor) * pow(x, P.loudCurve as number);
93 const midi =
94 P.pitchMode === "motion"
95 ? quantize((P.pitchLow as number) + ((P.pitchHigh as number) - (P.pitchLow as number)) * x, P.scale as string, NOTE_NAMES.indexOf(P.root as string))
96 : chord[dir > 0 ? "right" : "left"][i];
97 d.lastNote = sink.note(dir > 0 ? RIGHT : LEFT, tc, midi, velocity, P.noteLength as number) ?? d.lastNote;
98 notes++;
99 }
101 function step() {
102 const t0 = time;
103 time += DT / speed;
104 const u = (t0 - free) / damp; // damping progress (< 0: free swinging)
105 pends.forEach((d, i) => {
106 const p = d.p;
107 if (u >= 0) {
108 if (!p.controlled) {
109 p.controlled = true;
110 d.E0 = p.energy();
111 }
112 p.tau = tau;
113 p.eTarget = u < 1 ? d.E0 * pow(1 - u, curve) : 0;
114 // the energy controller fades out near zero energy; real friction settles the last of it
115 p.damping = u >= 1 ? 1 / tau : 0;
116 }
117 p.step(DT);
118 const x = bob(cfg, p.y)[0];
119 if (d.restAt === null && ((d.prevX < 0 && x >= 0) || (d.prevX > 0 && x <= 0))) note(i, t0 + (d.prevX / (d.prevX - x)) * (time - t0), x > d.prevX ? 1 : -1);
120 d.prevX = x;
121 if (d.restAt === null && u >= 1 && (p.energyNorm() < restE || time >= free + damp + MAX_SETTLE)) {
122 d.restAt = time;
123 if (d.lastNote) sink.hold(d.lastNote, d.lastNote.t, P.finalHold as number, P.finalFade as number);
124 }
125 });
126 if (restAll === null && pends.every((d) => d.restAt !== null)) {
127 restAll = time;
128 sink.end(time + ring);
129 }
130 if (time >= nextFrame) {
131 nextFrame = time + FRAME_DT;
132 pends.forEach((d, i) => {
133 row[2 * i] = d.p.y[0];
134 row[2 * i + 1] = d.p.y[1];
135 });
136 sink.frame(0, time, row);
137 }
138 if (time >= nextInfo) {
139 nextInfo = time + INFO_DT;
140 const phase = restAll !== null ? "at rest" : time < free ? "swinging" : time < free + damp ? "damping" : "settling";
141 sink.info(time, {
142 phase,
143 "energy (mean)": (pends.reduce((s, d) => s + d.p.energyNorm(), 0) / n).toFixed(4),
144 notes: String(notes),
145 release: releaseInfo,
146 "offset (outermost)": offsetInfo,
147 "at rest": `${pends.filter((d) => d.restAt !== null).length} / ${n}`,
148 });
149 }
150 }
152 return {
153 get time() {
154 return time;
155 },
156 advance(t: number) {
157 while (time < t) step();
158 },
159 };
160};