// Composition 2: orbits. // // Several double pendulums at once, all steered along the same energy envelope from random // starting states. Only the Poincaré section is shown: each orbit traces its crossings in its own // color, and plays its own instrument (orbit n uses instrument slot n, cycling) in its own register. // A hum follows the energy. Each orbit plays until it comes to rest; its last note rings out, // and the piece ends when every orbit has rested and faded. import type { AudioEngine } from "../../core/audio.ts"; import { dbToGain } from "../../core/audio.ts"; import type { Piece } from "../../core/composition.ts"; import type { Params } from "../../core/params.ts"; import { mulberry32, randomSeed } from "../../core/rng.ts"; import { NOTE_INSTRUMENTS } from "../../instruments/index.ts"; import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts"; import { midiToFreq } from "../../music/scales.ts"; import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts"; import { energyTarget } from "../shared/form.ts"; import { Hum } from "../shared/hum.ts"; import { noteFor } from "../shared/noteMap.ts"; import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts"; import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts"; import { orbitCapacity, type CapacityResult } from "./capacity.ts"; import { SLOTS } from "./schema.ts"; import { SharedReverb } from "../../instruments/reverb.ts"; import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts"; import type { NoteInstrumentFactory } from "../../instruments/types.ts"; // rendered-ahead (worker) versions of the modal instruments const STREAMED = streamedModalInstruments(); const STREAM_PREBUFFER = 0.4; // extra delay before the piece starts, so the renderers fill up const DT = 0.003; // simulation step (sim seconds) const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s) const TICK_MS = 25; const MAX_SETTLE = 10; // s after duration: count every orbit as at rest regardless interface Crossing { t: number; // piece time th2: number; // wrapped p2: number; // normalized } interface Orbit { index: number; pend: DoublePendulum; prev: number; // wrapped θ1 at the previous step prevTh2: number; prevP2: number; points: Crossing[]; lastNote: { handle: NoteHandle; when: number } | null; restAt: number | null; } export function createOrbitsPiece(view: HTMLElement, params: () => Params): Piece { view.classList.add("c02"); const canvas = document.createElement("canvas"); view.append(canvas); const plot = new SectionPlot(canvas); const hum = new Hum(); const portrait = new PortraitLayer(() => now(), () => playing); const portraitSettings = (P: Params): PortraitSettings => ({ show: P.portrait as boolean, count: P.portraitCount as number, cpu: P.portraitCpu as number, life: P.portraitLife as number, band: P.portraitBand as number, minHold: P.portraitMinHold as number, maxPoints: P.portraitMaxPoints as number, xfade: P.portraitXfade as number, alpha: P.portraitAlpha as number, size: P.portraitSize as number, tracks: P.traces as boolean, trackMax: P.traceMax as number, trackAlpha: P.traceAlpha as number, trackSize: P.traceSize as number, }); const postPortrait = (running: boolean) => { const P = params(); // each pendulum's current state, so the worker can trace the orbit it is on const tracks = orbits.filter((o) => o.restAt === null).map((o) => ({ id: o.index, y: Array.from(o.pend.y) })); portrait.post(running, portraitSettings(P), meanEnergy(), P.massRatio as number, P.lengthRatio as number, tracks); }; let orbits: Orbit[] = []; let audio: AudioEngine | null = null; let out: GainNode | null = null; let noteBus: GainNode | null = null; let instruments = new Map(); // by instrument name (+ custom settings) let reverb: SharedReverb | null = null; // one reverb for all the orbit instruments let timer: number | undefined; let playing = false; let startToken = 0; let pieceStart = 0; let simPieceT = 0; let seedUsed = 0; let noteCount = 0; let stoppedAt = 0; let restAll: number | null = null; // piece time every orbit had come to rest let stream = false; // instruments rendered ahead in workers (fixed per play) let simAhead = LOOKAHEAD; // how far the simulation (and note scheduling) runs ahead // device limit (measured on the first play, then cached) let capacity: CapacityResult | null = null; let checking = false; const piece: Piece = { get playing() { return playing; }, start, stop, draw, now, length: () => endTime(params()), readouts, notice, dispose() { stop(); portrait.dispose(); view.classList.remove("c02"); view.replaceChildren(); }, }; function now(): number { if (!audio || !playing) return stoppedAt; return audio.ctx.currentTime - pieceStart; } // ── orbits ── function makeOrbit(P: Params, index: number, e: number): Orbit { const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number }); pend.randomize(e, mulberry32(seedUsed * 1009 + index * 7919 + 1)); pend.tau = P.tau as number; return { index, pend, prev: wrapAngle(pend.y[0]), prevTh2: pend.y[1], prevP2: pend.y[3], points: [], lastNote: null, restAt: null }; } function wantedOrbits(P: Params): number { return Math.max(1, Math.min(20, Math.round(P.orbitCount as number))); } /** Orbits actually played: the setting, limited to what this device can handle. */ function playableOrbits(P: Params): number { const want = wantedOrbits(P); return P.deviceLimit && capacity ? Math.min(want, capacity.cap) : want; } /** Match the number of orbits to the setting (new ones start at the current target energy). */ function syncOrbitCount(P: Params) { const n = playableOrbits(P); if (restAll !== null) return; while (orbits.length < n) orbits.push(makeOrbit(P, orbits.length, Math.max(1e-4, energyTarget(P, simPieceT)))); if (orbits.length > n) orbits.length = n; } // ── instruments ── function slotOf(o: Orbit): number { return o.index % SLOTS; } function instrumentKey(P: Params, slot: number): { name: string; key: string } { const name = P[`slot${slot + 1}Instrument`] as string; return { name, key: name === "modal: custom" ? `${name}\n${P.modalCustom}` : name }; } function factory(name: string): NoteInstrumentFactory { return (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name]; } /** One instance per distinct instrument; orbits on the same instrument share it (it's polyphonic). */ function ensureInstruments() { if (!audio || !out) return; const P = params(); if (!noteBus) { noteBus = audio.ctx.createGain(); noteBus.connect(out); reverb = new SharedReverb(audio.ctx, noteBus, P.reverbTime as number); } noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05); const wanted = new Map(); for (const o of orbits) { const { name, key } = instrumentKey(P, slotOf(o)); wanted.set(key, name); } for (const [key, inst] of instruments) { if (!wanted.has(key)) { inst.dispose(); instruments.delete(key); } } for (const [key, name] of wanted) { if (!instruments.has(key)) instruments.set(key, factory(name)(audio.ctx, noteBus, { custom: P.modalCustom as string, effects: { send: reverb!.input } })); } hum.ensure(audio.ctx, out, P, playing); } // ── transport ── async function start(a: AudioEngine, offset: number) { stop(); const token = ++startToken; audio = a; const P = params(); const ctx = a.ctx; stream = !!P.streamAudio; simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD; if (P.deviceLimit) { checking = true; try { capacity = await orbitCapacity(ctx, P, wantedOrbits(P), SLOTS, stream); } finally { checking = false; } if (token !== startToken) return; // stopped or restarted meanwhile } seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed(); simPieceT = 0; restAll = null; noteCount = 0; orbits = []; portrait.reset(); // the worker starts a fresh portrait syncOrbitCount(P); // random starts at the starting energy, from the seed if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at") out = ctx.createGain(); out.connect(a.input); ensureInstruments(); await Promise.all([...[...instruments.values()].map((i) => i.ready), hum.ready]); if (token !== startToken) return; pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset; hum.start(ctx, P); playing = true; tick(); timer = window.setInterval(tick, TICK_MS); } function stop() { startToken++; if (timer !== undefined) window.clearInterval(timer); timer = undefined; const wasPlaying = playing; if (playing) { stoppedAt = now(); playing = false; postPortrait(false); } if (!audio) return; const t = audio.ctx.currentTime; hum.release(audio.ctx, wasPlaying); const o = out; if (o) { o.gain.setTargetAtTime(0, t, 0.05); window.setTimeout(() => o.disconnect(), 600); } for (const inst of instruments.values()) inst.dispose(); instruments = new Map(); reverb?.dispose(); reverb = null; noteBus = null; out = null; } // ── simulation ── function advanceTo(target: number, sound: boolean) { const P = params(); const speed = P.speed as number; const duration = P.duration as number; const restE = P.restEnergy as number; for (const o of orbits) { o.pend.cfg.m2 = P.massRatio as number; o.pend.cfg.l2 = P.lengthRatio as number; o.pend.tau = P.tau as number; } while (simPieceT < target) { const eT = energyTarget(P, simPieceT); const t0 = simPieceT; simPieceT += DT / speed; for (const o of orbits) { const pend = o.pend, y = pend.y; pend.eTarget = eT * pend.vTop; pend.step(DT); const cur = wrapAngle(y[0]); if (o.restAt === null && o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) { const f = -o.prev / (cur - o.prev); const c: Crossing = { t: t0 + f * (simPieceT - t0), th2: wrapAngle(o.prevTh2 + f * (y[1] - o.prevTh2)), p2: (o.prevP2 + f * (y[3] - o.prevP2)) / pend.p2Scale, }; o.points.push(c); if (sound) playNote(o, c, P); } if (o.restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) { o.restAt = simPieceT; // let this orbit's last real note ring: sustain, then fade if (sound && o.lastNote) o.lastNote.handle.hold(o.lastNote.when, P.finalHold as number, P.finalFade as number); } o.prev = cur; o.prevTh2 = y[1]; o.prevP2 = y[3]; } if (restAll === null && orbits.length && orbits.every((o) => o.restAt !== null)) restAll = simPieceT; } } function playNote(o: Orbit, c: Crossing, P: Params) { if (!audio) return; const when = pieceStart + c.t; if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background) const slot = slotOf(o); const inst = instruments.get(instrumentKey(P, slot).key); if (!inst) return; const { midi, velocity, pan } = noteFor(P, c.th2, c.p2, P[`slot${slot + 1}Octave`] as number); const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan, duration: P.noteLength as number }); if (handle) o.lastNote = { handle, when }; noteCount++; } /** Piece time at which everything has faded: known once every orbit is at rest, estimated before. */ function endTime(P: Params): number { const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3; return (restAll ?? (P.duration as number) + 0.5) + ring; } function meanEnergy(): number { if (!orbits.length) return 0; return orbits.reduce((s, o) => s + o.pend.energyNorm(), 0) / orbits.length; } function tick() { if (!audio || !playing) return; const P = params(); syncOrbitCount(P); ensureInstruments(); const ctx = audio.ctx; const t = ctx.currentTime - pieceStart; const total = endTime(P); if (restAll !== null && t >= total) { stop(); stoppedAt = total; piece.onEnded?.(); return; } advanceTo(t + simAhead, true); // tell the renderers every note up to here has been sent for (const inst of instruments.values()) inst.horizon?.(pieceStart + simPieceT); postPortrait(true); hum.update(ctx, P, meanEnergy(), t, restAll !== null ? total : null); } // ── drawing ── function colors(P: Params): string[] { const list = String(P.colors) .split(",") .map((s) => s.trim()) .filter(Boolean); return list.length ? list : [cssColor(view, "--fg")]; } function draw() { const P = params(); const t = now(); const ref = orbits[0]?.pend ?? null; const eMax = orbits.length ? Math.max(...orbits.map((o) => o.pend.energyNorm())) : null; const f = plot.begin(P, eMax, ref?.cfg ?? null, ref?.vTop ?? 1, cssColor(view, "--dim")); const fade = P.fade as number; const size = P.pointSize as number; const cols = colors(P); portrait.draw(f, t, portraitSettings(P), cssColor(view, "--fg"), (id) => cols[id % cols.length]); for (const o of orbits) { let drop = 0; while (drop < o.points.length && t - o.points[drop].t > 4.6 * fade) drop++; if (drop > 0) o.points.splice(0, drop); const col = cols[o.index % cols.length]; for (const c of o.points) { const age = t - c.t; if (age < 0) break; // not sounded yet drawCrossing(f, c.th2, c.p2, age, fade, size, col); } } } function notice(): string | null { if (checking) return "checking what this device can play…"; const P = params(); const want = wantedOrbits(P); const n = playableOrbits(P); return n < want ? `${n} of ${want} orbits: reduced to what this device can play live` : null; } function readouts(): Record { const P = params(); const t = now(); return { time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`, "energy target": energyTarget(P, t).toFixed(4), "energy (mean)": orbits.length ? meanEnergy().toFixed(4) : "–", notes: String(noteCount), "at rest": `${orbits.filter((o) => o.restAt !== null).length} / ${orbits.length}`, "device limit": capacity ? `${capacity.cap} orbits (synth load ${(100 * capacity.load).toFixed(0)}% with ${capacity.at})` : "–", instruments: String(instruments.size), "audio load": stream ? `renderers ${Math.round(100 * Math.max(0, ...[...instruments.values()].map((i) => i.load?.() ?? 0)))}% (busiest), ` + `${[...instruments.values()].reduce((s, i) => s + (i.underruns?.() ?? 0), 0)} underruns; hum ${Math.round(100 * (hum.inst?.load?.() ?? 0))}%` : `${Math.round(100 * ([...instruments.values()].reduce((s, i) => s + (i.load?.() ?? 0), 0) + (hum.inst?.load?.() ?? 0)))}%`, "seed used": seedUsed ? String(seedUsed) : "–", hum: hum.describe(), portrait: portrait.describe(), }; } return piece; }