/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c04-descent / piece.ts
622 lines · 23.5 KBCodeBlameHistory
e8001dcRename composition 4: crash → descentJeremy Magland 1// Composition 4: descent.
f7d91baAdd composition 4: crashJeremy Magland 2//
3// One double pendulum, balanced straight up and nudged by a calibrated amount so it tips at about
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 4// `fallAfter` seconds. Short piano notes mark the outer bob's height as it passes a ladder of
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 5// levels (higher level, higher note), so you hear it come down. Whenever the pendulum is fully
6// extended (the arms pass through a straight line, at any angle) there is an extension note: a
7// short violin note at a fixed pitch, its strength from the bob's speed, the first one accented.
8// The outer bob sweeping past the pivot (a folded pendulum) is a click. Slight friction
9// throughout, growing toward the end until it comes to rest; the last extension note rings out
10// and the piece ends with the fade.
f7d91baAdd composition 4: crashJeremy Magland 11
12import type { AudioEngine } from "../../core/audio.ts";
13import { dbToGain } from "../../core/audio.ts";
14import type { Piece } from "../../core/composition.ts";
15import type { Params } from "../../core/params.ts";
16import { mulberry32, randomSeed } from "../../core/rng.ts";
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 17import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
f7d91baAdd composition 4: crashJeremy Magland 18import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts";
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 19import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
20import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts";
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 21import { type DoublePendulum, type PendulumConfig, wrapAngle } from "../../physics/doublePendulum.ts";
f7d91baAdd composition 4: crashJeremy Magland 22import { cssColor, fitCanvas } from "../shared/section.ts";
5d7ea1acrash: fixed-pitch 'bottom notes' (no longer called crashes)Jeremy Magland 23import { OVERLAP_BUDGET, overlapCapacity, type VoiceCapacity } from "./capacity.ts";
f7d91baAdd composition 4: crashJeremy Magland 24import { DT, bob, inverted, nudgeForTip } from "./fall.ts";
26const STREAMED = streamedModalInstruments();
27const LOOKAHEAD = 0.15;
28const STREAM_PREBUFFER = 0.4;
29const TICK_MS = 25;
30const MAX_SETTLE = 15; // s after the damping: count the pendulum as at rest regardless
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 31const HISTORY_DT = 1 / 480; // piece-time spacing of stored states (drawing, blur, trail)
f7d91baAdd composition 4: crashJeremy Magland 32const BLUR_MAX_SAMPLES = 48;
33const BLUR_SPACING_PX = 2;
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 34const RING_S = 0.9; // extension-note ring lifetime
35const EXT_ARM = 0.05; // rad: the arms must bend this far from straight before the next extension note
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 36const HEIGHT_HYST = 0.3; // a level sounds once the position is this fraction of a level gap past it
1b2ce79crash: click (modal-synth Marimba, high and short) when the bob sweeps past the pivotJeremy Magland 37const CLICK_RING_S = 0.35; // click ring lifetime
f7d91baAdd composition 4: crashJeremy Magland 38
39interface Snap {
40 t: number;
41 th1: number;
42 th2: number;
f7d91baAdd composition 4: crashJeremy Magland 46 t: number;
47 x: number; // bob position (pendulum units)
48 y: number;
49 strength: number;
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 50 click?: boolean; // a pass by the pivot, not an extension note
f7d91baAdd composition 4: crashJeremy Magland 51}
e8001dcRename composition 4: crash → descentJeremy Magland 53export function createDescentPiece(view: HTMLElement, params: () => Params): Piece {
f7d91baAdd composition 4: crashJeremy Magland 54 view.classList.add("c04");
55 const canvas = document.createElement("canvas");
56 view.append(canvas);
58 let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 };
59 let pend: DoublePendulum | null = null;
60 let prevX = 0;
61 let E0 = 1;
62 let vmax = 1;
63 let history: Snap[] = [];
64 let lastHistT = -Infinity;
5d7ea1acrash: fixed-pitch 'bottom notes' (no longer called crashes)Jeremy Magland 65 let marks: Mark[] = [];
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 66 let extCount = 0; // extension notes so far
67 let prevPhi = 0; // relative arm angle at the previous step
68 let extArmed = false;
f7d91baAdd composition 4: crashJeremy Magland 70 let lastNote: { handle: NoteHandle; when: number } | null = null;
71 let restAt: number | null = null;
72 let audio: AudioEngine | null = null;
73 let out: GainNode | null = null;
74 let noteBus: GainNode | null = null;
75 let inst: NoteInstrument | null = null;
76 let instKey = "";
1b2ce79crash: click (modal-synth Marimba, high and short) when the bob sweeps past the pivotJeremy Magland 77 let clickBus: GainNode | null = null;
78 let clickInst: NoteInstrument | null = null;
79 let clickKey = "";
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 80 // height notes: levels (MIDI pitches, ascending) and where the bob is among them
81 let heightBus: GainNode | null = null;
82 let heightInst: NoteInstrument | null = null;
83 let heightKey = "";
84 let levels: number[] = [];
85 let levelIdx = 0; // number of levels below the bob's current pitch position
86 let heightCount = 0;
f7d91baAdd composition 4: crashJeremy Magland 87 let timer: number | undefined;
88 let playing = false;
89 let startToken = 0;
90 let pieceStart = 0;
91 let simPieceT = 0;
92 let seedUsed = 0;
93 let stoppedAt = 0;
94 let stream = false;
95 let simAhead = LOOKAHEAD;
96 let nudge = { d: 0, ratio: 1, side: 1, tipsAt: 0 };
97 let capacity: VoiceCapacity | null = null;
98 let checking = false;
99 let voicesAllowed = 4;
101 const piece: Piece = {
102 get playing() {
103 return playing;
104 },
105 start,
106 stop,
107 draw,
108 now,
109 length: () => endTime(params()),
110 readouts,
111 notice,
112 dispose() {
113 stop();
114 view.classList.remove("c04");
115 view.replaceChildren();
116 },
117 };
119 function now(): number {
120 if (!audio || !playing) return stoppedAt;
121 return audio.ctx.currentTime - pieceStart;
122 }
124 // ── setup ──
126 function makePendulum(P: Params, rand: (() => number) | null) {
127 cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
128 const side = rand ? (rand() < 0.5 ? -1 : 1) : 1;
129 const ratio = rand ? 0.6 + 0.8 * rand() : 1;
130 const speed = P.speed as number;
131 const cal = nudgeForTip(cfg, ratio, (P.fallAfter as number) * speed, (P.tipThreshold as number) * (cfg.l1 + cfg.l2));
132 nudge = { d: cal.nudge, ratio, side, tipsAt: cal.tipsAt / speed };
133 pend = inverted(cfg, cal.nudge, ratio, side);
134 prevX = bob(cfg, pend.y)[0];
135 E0 = pend.energy();
136 vmax = Math.sqrt((2 * E0) / cfg.m2);
137 history = [];
140 prevPhi = wrapAngle(pend.y[1] - pend.y[0]);
141 extArmed = false;
f7d91baAdd composition 4: crashJeremy Magland 143 lastNote = null;
144 restAt = null;
145 pushHistory(0);
146 }
148 function ensureInstrument() {
149 if (!audio || !out) return;
150 const P = params();
151 const ctx = audio.ctx;
152 if (!noteBus) {
153 noteBus = ctx.createGain();
154 noteBus.connect(out);
155 }
156 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05);
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 157 const name = P.extInstrument as string;
f7d91baAdd composition 4: crashJeremy Magland 158 const key = `${name}\n${name === "modal: custom" ? P.modalCustom : ""}\n${voicesAllowed}`;
159 if (inst && instKey === key) return;
160 inst?.dispose();
161 instKey = key;
162 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
163 inst = factory(ctx, noteBus, { custom: P.modalCustom as string, overrides: { voices: voicesAllowed } });
164 }
1b2ce79crash: click (modal-synth Marimba, high and short) when the bob sweeps past the pivotJeremy Magland 166 /** The click for passes by the pivot: its own (cheap) instrument and level. */
167 function ensureClick() {
168 if (!audio || !out) return;
169 const P = params();
170 const ctx = audio.ctx;
171 if (!clickBus) {
172 clickBus = ctx.createGain();
173 clickBus.connect(out);
174 }
175 clickBus.gain.setTargetAtTime(dbToGain(P.clickLevel as number), ctx.currentTime, 0.05);
176 const name = P.clickInstrument as string;
177 const key = P.click ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : "";
178 if (clickKey === key && (clickInst || !key)) return;
179 clickInst?.dispose();
180 clickInst = null;
181 clickKey = key;
182 if (!key) return;
183 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
184 clickInst = factory(ctx, clickBus, { custom: P.modalCustom as string });
185 }
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 187 /** Short notes at height levels: their own instrument and level. */
188 function ensureHeight() {
189 if (!audio || !out) return;
190 const P = params();
191 const ctx = audio.ctx;
192 if (!heightBus) {
193 heightBus = ctx.createGain();
194 heightBus.connect(out);
195 }
196 heightBus.gain.setTargetAtTime(dbToGain(P.heightLevel as number), ctx.currentTime, 0.05);
197 const name = P.heightInstrument as string;
198 const key = P.heightNotes ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : "";
199 if (heightKey === key && (heightInst || !key)) return;
200 heightInst?.dispose();
201 heightInst = null;
202 heightKey = key;
203 if (!key) return;
204 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
205 heightInst = factory(ctx, heightBus, { custom: P.modalCustom as string });
206 }
208 /** The ladder: scale notes between the low and high pitch, every `step`-th. */
209 function makeLevels(P: Params): number[] {
210 const lo = P.heightLow as number, hi = P.heightHigh as number;
211 const root = NOTE_NAMES.indexOf(P.root as string);
212 const all: number[] = [];
213 if (P.scale === "continuous") for (let m = Math.ceil(lo); m <= hi; m++) all.push(m);
214 else for (let m = Math.ceil(lo); m <= hi; m++) if (Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) all.push(m);
215 const step = Math.max(1, Math.round(P.heightStep as number));
216 return all.filter((_, i) => i % step === 0);
217 }
219 /** The bob's height as a pitch position on the ladder (bottom → heightLow, top → heightHigh). */
220 function pitchPos(P: Params, y: number): number {
221 const L = cfg.l1 + cfg.l2;
222 const hn = (L - y) / (2 * L); // 0 at the bottom, 1 at the top
223 return (P.heightLow as number) + ((P.heightHigh as number) - (P.heightLow as number)) * hn;
224 }
226 function countBelow(p: number): number {
227 let i = 0;
228 while (i < levels.length && levels[i] < p) i++;
229 return i;
230 }
f7d91baAdd composition 4: crashJeremy Magland 232 // ── transport ──
234 async function start(a: AudioEngine, offset: number) {
235 stop();
236 const token = ++startToken;
237 audio = a;
238 const P = params();
239 const ctx = a.ctx;
240 stream = !!P.streamAudio;
241 simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
5d7ea1acrash: fixed-pitch 'bottom notes' (no longer called crashes)Jeremy Magland 242 const wanted = Math.round(P.maxOverlap as number);
f7d91baAdd composition 4: crashJeremy Magland 243 voicesAllowed = wanted;
244 if (P.deviceLimit) {
245 checking = true;
246 try {
5d7ea1acrash: fixed-pitch 'bottom notes' (no longer called crashes)Jeremy Magland 247 capacity = await overlapCapacity(P, ctx.sampleRate, wanted);
f7d91baAdd composition 4: crashJeremy Magland 248 voicesAllowed = capacity.cap;
249 } finally {
250 checking = false;
251 }
252 if (token !== startToken) return;
253 }
254 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
255 const rng = mulberry32(seedUsed);
256 makePendulum(P, () => rng());
258 levelIdx = countBelow(pitchPos(P, bob(cfg, pend!.y)[1]));
259 heightCount = 0;
f7d91baAdd composition 4: crashJeremy Magland 260 simPieceT = 0;
261 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
263 out = ctx.createGain();
264 out.connect(a.input);
265 ensureInstrument();
268 await Promise.all([inst?.ready, clickInst?.ready, heightInst?.ready]);
f7d91baAdd composition 4: crashJeremy Magland 269 if (token !== startToken) return;
270 pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
271 playing = true;
272 tick();
273 timer = window.setInterval(tick, TICK_MS);
274 }
276 function stop() {
277 startToken++;
278 if (timer !== undefined) window.clearInterval(timer);
279 timer = undefined;
280 if (playing) {
281 stoppedAt = now();
282 playing = false;
283 }
284 if (!audio) return;
285 const t = audio.ctx.currentTime;
286 const o = out;
287 if (o) {
288 o.gain.setTargetAtTime(0, t, 0.05);
289 window.setTimeout(() => o.disconnect(), 600);
290 }
291 inst?.dispose();
292 inst = null;
293 instKey = "";
295 clickInst = null;
296 clickKey = "";
297 clickBus = null;
299 heightInst = null;
300 heightKey = "";
301 heightBus = null;
f7d91baAdd composition 4: crashJeremy Magland 302 noteBus = null;
303 out = null;
304 }
306 // ── simulation ──
308 function pushHistory(t: number) {
309 if (!pend) return;
310 history.push({ t, th1: pend.y[0], th2: pend.y[1] });
311 lastHistT = t;
312 }
314 /** Friction now (per sim second): slight throughout, growing smoothly over the damping section. */
315 function damping(P: Params, t: number): number {
316 const u = Math.max(0, Math.min(1, (t - (P.freeTime as number)) / (P.dampTime as number)));
317 const s = u * u * (3 - 2 * u);
318 return (P.dampBase as number) + ((P.dampEnd as number) - (P.dampBase as number)) * s;
319 }
321 function advanceTo(target: number, sound: boolean) {
322 if (!pend) return;
323 const P = params();
324 const speed = P.speed as number;
325 const end = (P.freeTime as number) + (P.dampTime as number);
326 const restE = P.restEnergy as number;
e2bd125crash: no crash when the bob sweeps past the pivotJeremy Magland 327 const minY = (P.minDepth as number) * (cfg.l1 + cfg.l2);
f7d91baAdd composition 4: crashJeremy Magland 328 const p = pend;
329 while (simPieceT < target) {
330 const t0 = simPieceT;
331 simPieceT += DT / speed;
332 p.damping = damping(P, t0);
333 p.step(DT);
334 const [x, y] = bob(cfg, p.y);
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 335 if (restAt === null && levels.length) heightLevels(t0, pitchPos(P, y), P, sound);
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 336 // the outer bob sweeping past the pivot (crossing the vertical close to it): a click
1b2ce79crash: click (modal-synth Marimba, high and short) when the bob sweeps past the pivotJeremy Magland 337 if (restAt === null && Math.abs(y) <= minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
338 const f = prevX / (prevX - x);
339 const tc = t0 + f * (simPieceT - t0);
340 clickCount++;
341 if (sound) click(tc, y, P);
f7d91baAdd composition 4: crashJeremy Magland 342 }
343 prevX = x;
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 344 // full extension: the arms pass through a straight line (relative angle crosses 0, not ±π),
345 // at any orientation. It re-arms once the arms bend at least EXT_ARM away from straight.
346 const phi = wrapAngle(p.y[1] - p.y[0]);
347 if (Math.abs(phi) > EXT_ARM) extArmed = true;
348 if (restAt === null && extArmed && ((prevPhi < 0 && phi >= 0) || (prevPhi > 0 && phi <= 0)) && Math.abs(phi - prevPhi) < Math.PI) {
349 const f = prevPhi / (prevPhi - phi);
350 const tc = t0 + f * (simPieceT - t0);
351 extArmed = false;
352 extCount++;
353 if (sound) extensionNote(tc, P);
354 else marks.push({ t: tc, x, y, strength: 0.5 });
355 }
356 prevPhi = phi;
f7d91baAdd composition 4: crashJeremy Magland 357 if (restAt === null && simPieceT >= end && (p.energyNorm() < restE || simPieceT >= end + MAX_SETTLE)) {
358 restAt = simPieceT;
359 if (sound && lastNote) lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
360 }
361 if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT);
362 }
363 }
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 365 /** Notes for every level the bob's pitch position has passed since the last step (with hysteresis). */
366 function heightLevels(t0: number, pos: number, P: Params, sound: boolean) {
367 const h = HEIGHT_HYST * (levels.length > 1 ? (levels[levels.length - 1] - levels[0]) / (levels.length - 1) : 1);
368 // moving up past levels[levelIdx]
369 while (levelIdx < levels.length && pos > levels[levelIdx] + h) {
370 if (sound) heightNote(t0, levels[levelIdx], P);
371 levelIdx++;
372 }
373 // moving down past levels[levelIdx − 1]
374 while (levelIdx > 0 && pos < levels[levelIdx - 1] - h) {
375 levelIdx--;
376 if (sound) heightNote(t0, levels[levelIdx], P);
377 }
378 }
380 function heightNote(t0: number, midi: number, P: Params) {
381 if (!audio || !heightInst || !pend) return;
382 const tc = t0 + DT / (P.speed as number);
383 const when = pieceStart + tc;
384 if (when < audio.ctx.currentTime - 0.02) return;
385 // strength: ramps in over the opening, fades with the energy at the end
386 const ru = (P.heightRamp as number) > 0 ? Math.max(0, Math.min(1, tc / (P.heightRamp as number))) : 1;
387 const from = P.heightRampFrom as number;
388 const ramp = from + (1 - from) * ru * ru * (3 - 2 * ru);
389 const e = Math.min(1, Math.max(0, pend.energy()) / E0);
390 const velocity = (P.heightVel as number) * ramp * Math.pow(e, P.heightFollow as number);
391 heightInst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.heightLength as number });
392 heightCount++;
393 }
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 395 function extensionNote(tc: number, P: Params) {
f7d91baAdd composition 4: crashJeremy Magland 396 if (!audio || !inst || !pend) return;
397 const when = pieceStart + tc;
398 if (when < audio.ctx.currentTime - 0.02) return;
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 399 const midi = P.extPitch as number;
400 // strength: the first extension note is the accent; later ones follow the bob's speed
401 const velocity = extCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength(P);
402 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.extLength as number });
f7d91baAdd composition 4: crashJeremy Magland 403 if (handle) lastNote = { handle, when };
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 404 const [bx, by] = bob(cfg, pend.y);
405 marks.push({ t: tc, x: bx, y: by, strength: velocity });
f7d91baAdd composition 4: crashJeremy Magland 406 }
1b2ce79crash: click (modal-synth Marimba, high and short) when the bob sweeps past the pivotJeremy Magland 408 /** 0..1 from the outer bob's speed now (loudness floor and curve applied). */
409 function speedStrength(P: Params): number {
410 if (!pend) return 0;
411 const w = pend.derived();
412 const yv = pend.y;
413 const vx = cfg.l1 * Math.cos(yv[0]) * w.w1 + cfg.l2 * Math.cos(yv[1]) * w.w2;
414 const vy = cfg.l1 * Math.sin(yv[0]) * w.w1 + cfg.l2 * Math.sin(yv[1]) * w.w2;
415 const xs = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax));
416 const floor = P.loudFloor as number;
417 return floor + (1 - floor) * Math.pow(xs, P.loudCurve as number);
418 }
420 function click(tc: number, y: number, P: Params) {
421 if (!audio || !clickInst) return;
422 const when = pieceStart + tc;
423 if (when < audio.ctx.currentTime - 0.02) return;
424 const velocity = (P.clickMaxVel as number) * speedStrength(P);
425 clickInst.play({ when, freq: midiToFreq(P.clickPitch as number), velocity, pan: 0, duration: P.clickLength as number });
5d7ea1acrash: fixed-pitch 'bottom notes' (no longer called crashes)Jeremy Magland 426 marks.push({ t: tc, x: 0, y, strength: velocity, click: true });
f7d91baAdd composition 4: crashJeremy Magland 429 function endTime(P: Params): number {
430 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
431 return (restAt ?? (P.freeTime as number) + (P.dampTime as number) + 3) + ring;
432 }
434 function tick() {
435 if (!audio || !playing || !pend) return;
436 const P = params();
437 ensureInstrument();
438 const ctx = audio.ctx;
439 const t = ctx.currentTime - pieceStart;
440 const total = endTime(P);
441 if (restAt !== null && t >= total) {
442 stop();
443 stoppedAt = total;
444 piece.onEnded?.();
445 return;
446 }
f7d91baAdd composition 4: crashJeremy Magland 449 advanceTo(t + simAhead, true);
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 450 for (const i of [inst, clickInst, heightInst]) i?.horizon?.(pieceStart + simPieceT);
f7d91baAdd composition 4: crashJeremy Magland 451
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 452 // keep the states drawing, blur and trail still need
f7d91baAdd composition 4: crashJeremy Magland 453 const keep = t - (P.trailLength as number) - 0.5;
454 let i = 0;
455 while (i < history.length - 2 && history[i + 1].t < keep) i++;
456 if (i > 0) history.splice(0, i);
5d7ea1acrash: fixed-pitch 'bottom notes' (no longer called crashes)Jeremy Magland 457 while (marks.length && marks[0].t < t - RING_S - 1) marks.shift();
f7d91baAdd composition 4: crashJeremy Magland 458 }
460 // ── drawing ──
462 function stateAt(t: number): Snap {
463 const n = history.length;
464 if (!n) return { t, th1: pend?.y[0] ?? Math.PI, th2: pend?.y[1] ?? Math.PI };
465 if (t <= history[0].t) return history[0];
466 if (t >= history[n - 1].t) return history[n - 1];
467 let lo = 0, hi = n - 1;
468 while (hi - lo > 1) {
469 const mid = (lo + hi) >> 1;
470 if (history[mid].t <= t) lo = mid;
471 else hi = mid;
472 }
473 const a = history[lo], b = history[hi];
474 const f = (t - a.t) / (b.t - a.t);
475 return { t, th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
476 }
478 let lastWall = 0;
479 let frameDt = 1 / 60;
481 function draw() {
482 const P = params();
483 if (!pend) makePendulum(P, null); // preview: balanced straight up
484 const t = now();
485 const wall = performance.now() / 1000;
486 const dtw = wall - lastWall;
487 lastWall = wall;
488 if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
489 const g = fitCanvas(canvas);
490 const w = canvas.clientWidth, h = canvas.clientHeight;
491 g.clearRect(0, 0, w, h);
492 const fg = cssColor(view, "--fg");
493 const l1 = cfg.l1, l2 = cfg.l2;
494 const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
495 const x0 = w / 2, y0 = h / 2;
496 const pos = (s: { th1: number; th2: number }) => {
497 const x1 = x0 + scale * l1 * Math.sin(s.th1), y1 = y0 + scale * l1 * Math.cos(s.th1);
498 return [x1, y1, x1 + scale * l2 * Math.sin(s.th2), y1 + scale * l2 * Math.cos(s.th2)];
499 };
501 // trail of the outer bob, fading with age
502 if (P.trails && history.length > 1) {
503 const len = P.trailLength as number;
504 const BANDS = 6;
505 g.strokeStyle = fg;
506 g.lineWidth = 1;
507 g.lineJoin = g.lineCap = "round";
508 for (let band = 0; band < BANDS; band++) {
509 const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
510 g.globalAlpha = 0.45 * (1 - (band + 0.5) / BANDS);
511 g.beginPath();
512 let started = false;
513 for (let i = 0; i < history.length; i += 2) {
514 const hs = history[i];
515 if (hs.t < aOld - 0.01 || hs.t > aNew + 0.01) continue;
516 if (hs.t > t) break;
517 const [, , bx, by] = pos(hs);
518 if (started) g.lineTo(bx, by);
519 else g.moveTo(bx, by), (started = true);
520 }
521 g.stroke();
522 }
523 g.globalAlpha = 1;
524 }
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 526 // rings, where each extension note (and click) happened
528 for (const c of marks) {
f7d91baAdd composition 4: crashJeremy Magland 529 const age = t - c.t;
1b2ce79crash: click (modal-synth Marimba, high and short) when the bob sweeps past the pivotJeremy Magland 530 const life = c.click ? CLICK_RING_S : RING_S;
531 if (age < 0 || age > life) continue;
f7d91baAdd composition 4: crashJeremy Magland 532 const s = stateAt(c.t);
533 const [, , bx, by] = pos(s);
534 g.strokeStyle = fg;
1b2ce79crash: click (modal-synth Marimba, high and short) when the bob sweeps past the pivotJeremy Magland 535 g.globalAlpha = (1 - age / life) * (0.4 + 0.6 * c.strength);
536 g.lineWidth = c.click ? 1 : 1.2;
f7d91baAdd composition 4: crashJeremy Magland 537 g.beginPath();
1b2ce79crash: click (modal-synth Marimba, high and short) when the bob sweeps past the pivotJeremy Magland 538 const grow = c.click ? 14 : 60 * (0.5 + c.strength);
539 g.arc(bx, by, (c.click ? 3 : 6) + grow * Math.sqrt(age / life), 0, 2 * Math.PI);
f7d91baAdd composition 4: crashJeremy Magland 540 g.stroke();
541 }
542 g.globalAlpha = 1;
543 }
545 // the pendulum, with motion blur
546 const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
547 let k = 1;
548 if (shutter > 0) {
549 let path = 0;
550 let a = stateAt(t);
551 for (let j = 1; j <= 8; j++) {
552 const b = stateAt(t - (shutter * j) / 8);
553 path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
554 a = b;
555 }
556 k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
557 }
558 const alpha = k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k);
559 const r1 = 4, r2 = 4 * Math.cbrt(cfg.m2);
560 g.strokeStyle = fg;
561 g.fillStyle = fg;
562 g.lineWidth = 1.5;
563 g.lineCap = "round";
564 g.globalAlpha = alpha;
565 for (let i = 0; i < k; i++) {
566 const [x1, y1, x2, y2] = pos(stateAt(t - (shutter * i) / Math.max(1, k - 1)));
567 g.beginPath();
568 g.moveTo(x0, y0);
569 g.lineTo(x1, y1);
570 g.lineTo(x2, y2);
571 g.stroke();
572 g.beginPath();
573 g.arc(x1, y1, r1, 0, 2 * Math.PI);
574 g.moveTo(x2 + r2, y2);
575 g.arc(x2, y2, r2, 0, 2 * Math.PI);
576 g.fill();
577 }
578 g.globalAlpha = 1;
579 g.beginPath();
580 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
581 g.fill();
582 }
584 function notice(): string | null {
585 if (checking) return "checking what this device can play…";
586 const P = params();
587 if (!P.deviceLimit || !capacity || capacity.perVoice === 0) return null;
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 588 if (capacity.perVoice > OVERLAP_BUDGET) return "this device can't render the extension notes in real time; expect glitches";
5d7ea1acrash: fixed-pitch 'bottom notes' (no longer called crashes)Jeremy Magland 589 const want = Math.round(P.maxOverlap as number);
590 return voicesAllowed < want ? `${voicesAllowed} overlapping note${voicesAllowed > 1 ? "s" : ""} (of ${want}): reduced to what this device can play` : null;
f7d91baAdd composition 4: crashJeremy Magland 591 }
593 function readouts(): Record<string, string> {
594 const P = params();
595 const t = now();
596 const free = P.freeTime as number, damp = P.dampTime as number;
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 597 const phase = restAt !== null && simPieceT >= restAt ? "at rest" : extCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
f7d91baAdd composition 4: crashJeremy Magland 598 return {
599 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
600 phase,
601 energy: pend ? `${(pend.energy() / E0).toFixed(3)} of start` : "–",
89519c1crash: extension notes when the arms are fully extendedJeremy Magland 602 "extension notes": String(extCount),
1995755crash: piano notes at height levels instead of the gliding voiceJeremy Magland 604 "height notes": String(heightCount),
f7d91baAdd composition 4: crashJeremy Magland 605 nudge: `${nudge.d.toExponential(2)} rad ${nudge.side > 0 ? "→" : "←"} (shape ${nudge.ratio.toFixed(2)}), tips at ${nudge.tipsAt.toFixed(1)} s`,
606 friction: `${damping(P, t).toFixed(4)} /sim s`,
607 "seed used": seedUsed ? String(seedUsed) : "–",
5d7ea1acrash: fixed-pitch 'bottom notes' (no longer called crashes)Jeremy Magland 608 "overlapping notes": capacity ? `${voicesAllowed} (one ringing note: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed),
97bd308Make streamed audio robust: voice caps, 2 s buffer, soft underrunsJeremy Magland 609 "audio load": [["extension", inst], ["click", clickInst], ["height", heightInst]]
610 .filter(([, i]) => i)
611 .map(([n, i]) => {
612 const x = i as NoteInstrument;
613 const v = x.voices?.();
614 const cap = v && v.allowed < v.wanted ? `, ${v.allowed} of ${v.wanted} voices` : "";
615 return `${n} ${Math.round(100 * (x.load?.() ?? 0))}%${stream ? `, ${x.underruns?.() ?? 0} underruns` : ""}${cap}`;
616 })
617 .join(" · "),
f7d91baAdd composition 4: crashJeremy Magland 618 };
619 }
621 return piece;
↑↓ move↵openescclose