// Islands in a sea of chaos: the Poincaré section of the driven Duffing // oscillator (js/duffing.js), filled in live, with tracks that sonify orbits // (js/voices.js). // // - Seed orbits, started on the axes of the view at drive phase 0, fill the // section in the background, a few thousand points per frame. // - A track is an orbit (a start (x, x') picked on the plot, at drive phase // 0) and how it plays: rhythm, scale, key, tempo multiple, sustain, // volume, instrument and velocity. Its dots fill in fast and larger; while // it plays, a playhead walks it one drive period per tick, with a // live trail of the motion through the period, plucking notes whose pitch // is set by x (left to right over three octaves of its scale and key). // Tracks start paused; each can be played, paused and restarted from its // start. // - One global tempo (bpm) sets the beat; each track ticks at a multiple of // it (x1, x2, x3, ..., x1/2, x1/3, ..., or any value), on a grid aligned to // the beat, so x2 and x3 meet on every beat and x1/2 ticks on every other. // - Each setting but the instrument can be linked: the linked tracks share // one value (by default scale and key). // - Rhythm 'steady' plucks at the section point, once per beat; 'natural' // plays the motion in slowed time and plucks wherever x' crosses 0 upward // (the left turning point of each swing), at that x; 'both' at either // turning point. // - Changing a parameter or preset doesn't restart anything: the tracks // carry on from where they are under the new equation, their dots now // computed from there, and the old dots fade out as the new ones fill in. // Restart takes a track back to its start. // - Coupling (optional; off by default) joins the playing tracks with the // same tempo multiple into one system (one per multiple): a spring and // damper on each one's difference from their mean (duffing.js, stepMany), // so they pull together and, strong enough, fall into step. When such a // set of tracks or the coupling changes, they carry on from where they are // (their dots are recomputed from there, coupled as the playheads will // move). import { createStepper, physicsOf, X_MAX } from './js/duffing.js'; import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js'; import { midiSupported, openMidi } from './js/midi.js'; import { forgetSoundFont, loadSaved, makeInstrument, parseSF2, saveSoundFont } from './js/soundfont.js'; import { PRESETS } from './js/presets.js'; import { download, downloadBlob, FORMAT, forgetLocal, fromBase64, loadKnobs, loadLocal, saveKnobs, saveLocal, toBase64 } from './js/session.js'; const SEEDS_X = 24; // seed orbits along x' = 0 const SEEDS_V = 8; // and along x = 0 const SEED_POINTS = 1500; const TRACK_POINTS = 4000; const TRACK_PER_FRAME = 40; // so a track's orbit visibly grows const MAX_TRACKS = 8; const HIT_RADIUS = 9; // px: a press this close to a start ring picks its track const DRAG_START = 4; // px a press on a start ring moves before it drags const FRAME_BUDGET = 7; // ms of integration per frame const TAIL = 2; // trail length, in beats const LOOKAHEAD = 0.12; // s of notes scheduled ahead const FADE = 0.7; // s for replaced dots to fade out const RING = 0.35; // s a pluck's ring takes to fade (at most 3 beats) const MARGIN = { left: 56, right: 12, top: 12, bottom: 34 }; const SLIDERS = [ { name: 'freq', label: 'f0', unit: 'Hz', min: -1000, max: 1000, step: 5, fmt: (v) => `${v < 0 ? '−' : ''}${Math.abs(v)} Hz` }, { name: 'alpha', label: 'α', min: -5, max: 10, step: 0.1, scale: 1e7, fmt: (v) => `${v.toFixed(1)}·10⁷` }, { name: 'delta', label: 'δ', min: 0, max: 50, step: 0.5, fmt: (v) => `${v.toFixed(1)} s⁻¹` }, { name: 'F', label: 'F', min: 0, max: 30, step: 0.1, scale: 1e4, fmt: (v) => `${v.toFixed(1)}·10⁴` }, { name: 'drive', label: 'Ω / 2π', min: 20, max: 2000, step: 5, fmt: (v) => `${v} Hz` }, { name: 'view', label: 'View ±x', min: 0.1, max: X_MAX, step: 0.05, fmt: (v) => v.toFixed(2) }, ]; // ---- track settings ------------------------------------------------------------ const RHYTHMS = [ { value: 'steady', name: 'Steady: each drive period', short: 'steady' }, { value: 'both', name: 'Natural: ẋ = 0 both ways', short: 'both ways' }, { value: 'natural', name: 'Natural: ẋ = 0 upward', short: 'upward' }, ]; const SCALE_SHORT = { 'Major pentatonic': 'maj. pent.', 'Minor pentatonic': 'min. pent.', Major: 'major', 'Natural minor': 'minor', 'Harmonic minor': 'harm. minor', 'Whole tone': 'whole tone', Chromatic: 'chromatic', Continuous: 'continuous', }; // the settings that can be linked (shared by the linked tracks), and their defaults const SETTINGS = ['rhythm', 'scale', 'key', 'rate', 'sustain', 'volume', 'velocity']; const DEFAULTS = { rhythm: 'steady', scale: SCALES.findIndex((s) => s.name === DEFAULT_SCALE), key: DEFAULT_KEY, rate: '1', sustain: SUSTAIN.default, volume: 1, velocity: 100, }; const LINKED_BY_DEFAULT = ['scale', 'key']; // The 'Custom notes' scale (the scale setting's value CUSTOM): its notes are // in the setting 'notes', which is linked along with the scale: MIDI note // numbers (sorted), as entered in key `ref`, so a change of key transposes // them (the nearer way); every: their pitch classes in every octave (a scale // across the usual three octaves), rather than just those notes. const CUSTOM = 'custom'; DEFAULTS.notes = { notes: [], ref: DEFAULT_KEY, every: true }; const VALUES = [...SETTINGS, 'notes']; // a track's values (the settings, and the custom notes) const linkOf = (p) => (p === 'notes' ? 'scale' : p); // the global tempo (bpm) const TEMPO = { min: 40, max: 240, default: 120 }; // a track's tempo multiple: ticks (drive periods) per beat, as text ('3', // '1/2', '1.5'); the menu's choices, and the range of custom ones const RATES = ['16', '12', '8', '6', '4', '3', '2', '1', '1/2', '1/3', '1/4', '1/6', '1/8']; const RATE_RANGE = { min: 1 / 16, max: 32 }; const RANGES = { sustain: { label: 'Sustain', min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, fmt: (v) => `${v.toFixed(1)} s`, title: 'How long each note rings (built-in instruments)' }, volume: { label: 'Volume', min: 0, max: 1, step: 0.01, fmt: (v) => `${Math.round(100 * v)}%` }, velocity: { label: 'Velocity', min: 1, max: 127, step: 1, fmt: (v) => `${v}`, title: 'MIDI velocity (SoundFont instruments)' }, }; const $ = (id) => document.getElementById(id); const canvas = $('plot'); const ctx = canvas.getContext('2d'); // the section points, accumulated: seed orbits, and the tracks' on top const dots = document.createElement('canvas'); const top = document.createElement('canvas'); const layers = [dots, top]; // replaced dots, fading out (and a spare canvas to composite into) let ghost = document.createElement('canvas'); let spare = document.createElement('canvas'); let ghostStart = -Infinity; let params = { ...PRESETS[0].params }; let stepper; let view; // { xr, vr }: half-ranges of x and x' let seeds = []; // the seed orbits let tracks = []; // see newTrack let selected = null; // the track whose controls are open, and whose start a click moves let shared = { ...DEFAULTS }; // the linked tracks' settings let tempo = TEMPO.default; // bpm let anchor = { time: 0, beat: 0 }; // the beat at a clock time (moved when the tempo changes) let synth = null; let soundOn = false; let nextId = 1; let hueCounter = 0; let coupling = 0; // r (s^-1) of the coupling; 0: off let groups = []; // the sets of coupled tracks, as last restarted let groupKey = ''; let dirty = false; // the equation changed: reset at the next frame let theme; let soundfonts = []; // the loaded .sf2 files: { id, fileName, bytes, sf (parsed), insts: Map(preset -> instrument) } let nextFontId = 1; let recording = null; // { recorder, chunks, mime, started } while recording let recorded = null; // { blob, mime, seconds, saved } once stopped let restored = false; // the saved state has been restored (until then, nothing is saved) // ---- tracks -------------------------------------------------------------------- // a track's setting: its own, or the shared one if linked const val = (t, p) => (t.linked[linkOf(p)] ? shared : t.own)[p]; // a tempo multiple's value from its text ('3', '1/2', '1.5'), or NaN function parseRate(text) { const m = String(text).trim().match(/^(\d*\.?\d+)\s*(?:\/\s*(\d*\.?\d+))?$/); const v = m ? Number(m[1]) / (m[2] ? Number(m[2]) : 1) : NaN; return v >= RATE_RANGE.min && v <= RATE_RANGE.max ? v : NaN; } const rateOf = (t) => parseRate(val(t, 'rate')) || 1; const rateLabel = (t) => `×${val(t, 'rate')}`; // a track's tick: its length in beats, and in seconds (one drive period) const tickBeats = (t) => 1 / rateOf(t); const tickDt = (t) => 60 / (tempo * rateOf(t)); // the beat at clock time `time`, and the clock time of beat b const beatAt = (time) => anchor.beat + ((time - anchor.time) * tempo) / 60; const timeAt = (b) => anchor.time + ((b - anchor.beat) * 60) / tempo; // the coupled set a track is in, if any const groupOf = (t) => groups.find((g) => g.includes(t)); // a new track, paused, with the settings of `like` (a track) or the defaults function newTrack(like) { const own = like ? Object.fromEntries(VALUES.map((p) => [p, val(like, p)])) : { ...DEFAULTS }; return { id: nextId++, hue: (0.08 + hueCounter++ * 0.382) % 1, instrument: freeInstrument(), start: null, // { x, v } orbit: null, // its dots ph: null, // its playhead playing: false, tick: null, // its next tick, as a number of ticks from beat 0 (null: from the next one due) own, linked: Object.fromEntries(SETTINGS.map((p) => [p, LINKED_BY_DEFAULT.includes(p)])), escaped: false, }; } function addTrack() { if (tracks.length >= MAX_TRACKS) return null; const t = newTrack(selected); tracks.push(t); selected = t; applyVolumes(); renderTracks(); return t; } function removeTrack(t) { tracks = tracks.filter((q) => q !== t); if (selected === t) selected = tracks[tracks.length - 1] ?? null; synth?.removeTrack(t.id); redrawTop(); renderTracks(); } function setValue(t, p, v) { (t.linked[linkOf(p)] ? shared : t.own)[p] = v; if (p === 'volume') applyVolumes(); if (p === 'rate') for (const q of tracks) q.tick = null; // onto the new grid } // link or unlink a track's setting: linking adopts the shared value (or, if // no other track is linked, shares the track's own); unlinking keeps it function setLinked(t, p, on) { if (on === t.linked[p]) return; const ps = VALUES.filter((q) => linkOf(q) === p); if (on) { if (!tracks.some((q) => q !== t && q.linked[p])) for (const q of ps) shared[q] = t.own[q]; } else { for (const q of ps) t.own[q] = shared[q]; } t.linked[p] = on; if (p === 'volume') applyVolumes(); if (p === 'rate') t.tick = null; } const applyVolumes = () => { for (const t of tracks) synth?.setTrackVolume(t.id, val(t, 'volume')); }; const trackName = (t) => `${tracks.indexOf(t) + 1}`; // the sets of coupled tracks: the playing ones with the same tempo multiple, // two or more to a set function coupledGroups() { if (!coupling) return []; const by = new Map(); for (const t of tracks) { if (!t.start || !t.playing) continue; const k = rateOf(t).toPrecision(9); if (!by.has(k)) by.set(k, []); by.get(k).push(t); } return [...by.values()].filter((g) => g.length > 1); } // ---- physics --------------------------------------------------------------- // x' half-range: the speed at the bottom of the well of a free orbit that // just reaches x = +/-xr, so the view frames the motions of that size function speedRange(p, xr) { const V = (x) => 0.5 * p.omega2 * x * x + 0.25 * p.alpha * x ** 4; const vMin = p.omega2 < 0 && p.alpha > 0 ? -(p.omega2 ** 2) / (4 * p.alpha) : 0; const v = Math.sqrt(Math.max(0, 2 * (V(xr) - vMin))); return Math.max(v, 0.3 * xr * p.Omega, 1); } // skip: drive periods to run before recording (a seed's transient) function newOrbit(x, v, cap, hue, isTrack, skip = 0) { return { x0: x, v0: v, s: { x, v, escaped: false }, pts: new Float32Array(2 * cap), n: 0, cap, hue, isTrack, skip }; } // a playhead: the orbit's state; its scheduled beats ({ time, dt, path, // last, notes }) still needed for the trail, notes: [{ t, x, v }]; and the // time its last scheduled beat ends const newPlayhead = (x, v) => ({ s: { x, v, escaped: false }, queue: [], until: 0 }); function reset() { const p = physicsOf(params); stepper = createStepper(p); view = { xr: params.view, vr: speedRange(p, params.view) }; // damped: the seeds settle onto the attractors before they are drawn, // for about 5 / delta (the tracks show the way in) const skip = p.delta > 0 ? Math.min(5000, Math.ceil((5 / p.delta) / stepper.T)) : 0; seeds = []; for (let i = 0; i < SEEDS_X; i++) { const x = view.xr * (-1 + (2 * (i + 0.5)) / SEEDS_X); seeds.push(newOrbit(x, 0, SEED_POINTS, (i * 0.618) % 1, false, skip)); } for (let i = 0; i < SEEDS_V; i++) { const v = 0.9 * view.vr * (-1 + (2 * (i + 0.5)) / SEEDS_V); seeds.push(newOrbit(0, v, SEED_POINTS, ((i + SEEDS_X) * 0.618) % 1, false, skip)); } fadeOut(layers); clearDots([dots]); reseed(tracks, false); } // recompute tracks' dots from where their playheads are (coupled as they // will move), the old ones fading out function reseed(ts, fade = true) { if (fade) fadeOut([top]); for (const t of ts) { if (!t.ph) continue; const { x, v, escaped } = t.ph.s; t.orbit = newOrbit(x, v, TRACK_POINTS, t.hue, true); t.orbit.s.escaped = escaped; } redrawTop(); } // restart tracks' playheads from their starts, and their dots too if they // weren't computed from there function restart(ts) { let changed = false; for (const t of ts) { if (!t.start) continue; t.ph = newPlayhead(t.start.x, t.start.v); t.tick = null; if (!t.orbit || t.orbit.x0 !== t.start.x || t.orbit.v0 !== t.start.v) { t.orbit = newOrbit(t.start.x, t.start.v, TRACK_POINTS, t.hue, true); changed = true; } } if (changed) redrawTop(); } // restart a track; if it is coupled, the others carry on, with it function restartTrack(t) { restart([t]); const g = groupOf(t); if (g) reseed(g); } // When the coupled sets change (a track played, paused, added or removed, // its tempo multiple changed, or the coupling changed), the old and new // members carry on from where they are, their dots recomputed. function syncCoupling() { const gs = coupledGroups(); const key = gs.length ? `${coupling}:${gs.map((g) => g.map((t) => t.id).join(',')).join(';')}` : ''; if (key === groupKey) return; const was = groups.flat().filter((t) => tracks.includes(t)); groups = gs; groupKey = key; reseed([...new Set([...was, ...gs.flat()])]); } function setStart(t, x, v) { const first = !t.start; t.start = { x, v }; t.escaped = false; restartTrack(t); if (first) renderTracks(); else updateTrack(t); renderHint(); } // ---- playhead and sound ----------------------------------------------------- const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000); const ringTime = (dt) => Math.min(RING, 3 * dt); // The crossings of x' = 0 along a drive period's path (N + 1 points, evenly // spaced in time over dt from time t0), interpolated linearly: upward only // (from x' < 0 to x' >= 0), or both ways (also from x' > 0 to x' <= 0). function crossings(path, t0, dt, both) { const N = path.length / 2 - 1; const notes = []; for (let j = 1; j <= N; j++) { const v0 = path[2 * j - 1]; const v1 = path[2 * j + 1]; if ((v0 < 0 && v1 >= 0) || (both && v0 > 0 && v1 <= 0)) { const f = v0 / (v0 - v1); notes.push({ t: t0 + ((j - 1 + f) / N) * dt, x: path[2 * j - 2] + f * (path[2 * j] - path[2 * j - 2]), v: 0 }); } } return notes; } // ---- pitch --------------------------------------------------------------------- const midiHz = (m) => 440 * 2 ** ((m - 69) / 12); const noteName = (m) => `${KEYS[m % 12]}${Math.floor(m / 12) - 1}`; const pc = (n) => ((n % 12) + 12) % 12; // the shift (semitones) of custom notes c in key `key`: the nearer way from c.ref const shiftOf = (c, key) => { const d = pc(key - c.ref); return d > 6 ? d - 12 : d; }; // a track's custom notes as they sound (in its key) const soundingNotes = (t) => { const c = val(t, 'notes'); const d = shiftOf(c, val(t, 'key')); return c.notes.map((n) => n + d); }; const isCustom = (t) => val(t, 'scale') === CUSTOM; // the pitch (Hz) a track plays at u in [0, 1] (the left to right edge of the // view), or null (custom notes, but none yet): custom notes spread evenly // over the view (or as a scale), or the scale's notes function pitchFor(t, u) { const key = val(t, 'key'); if (!isCustom(t)) return pitchOf(u, SCALES[val(t, 'scale')], key); const c = val(t, 'notes'); if (!c.notes.length) return null; if (c.every) return pitchOf(u, { steps: [...new Set(c.notes.map((n) => pc(n - c.ref)))] }, key); const ns = soundingNotes(t); return midiHz(ns[Math.round(Math.min(1, Math.max(0, u)) * (ns.length - 1))]); } // MIDI velocity for SoundFont notes: the track's, jittered a little so // neighbouring velocity layers (or variations) alternate function velocity(t) { const v = val(t, 'velocity') + Math.round((Math.random() * 2 - 1) * 6); return Math.max(1, Math.min(127, v)); } // One tick at time `time` (lasting dt) for tracks ts: each playhead advances // one drive period (together if coupled), keeping the path for the trail, // and plucks its notes (steady: one at the section point; natural: at each // upward x' = 0; both: at each x' = 0), at level gain. function beat(ts, time, dt, together, gain) { const before = ts.map((t) => ({ ...t.ph.s })); const paths = ts.map(() => new Float32Array(2 * (stepper.N + 1))); if (together) stepper.stepMany(ts.map((t) => t.ph.s), coupling, paths); else ts.forEach((t, k) => stepper.step(t.ph.s, paths[k])); for (const [k, t] of ts.entries()) { t.ph.until = time + dt; if (before[k].escaped) continue; const { x, v } = before[k]; const rhythm = val(t, 'rhythm'); // (at crossings: none in the period it escapes, whose path ends at rest) const notes = rhythm === 'steady' ? [{ t: time, x, v }] : t.ph.s.escaped ? [] : crossings(paths[k], time, dt, rhythm === 'both'); t.ph.queue.push({ time, dt, path: paths[k], last: t.ph.s.escaped, notes }); if (soundOn && synth) { const voice = voiceOf(t); for (const n of notes) { const u = (n.x / view.xr + 1) / 2; const freq = pitchFor(t, u); if (freq == null) continue; synth.play(t.id, voice, freq, n.t, { pan: Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain, sustain: val(t, 'sustain'), vel: velocity(t), }); } } } } // Run tracks ts (one, or a coupled set, sharing the tempo multiple) over // their ticks due within LOOKAHEAD. Ticks fall on a grid aligned to beat 0, // tickBeats apart; a track starting (or fallen behind: a stalled frame, a // hidden tab, a pause) picks up at the next tick after now, rather than // playing the missed ones in a burst. function runTicks(ts, now, gain) { const lead = ts[0]; const step = tickBeats(lead); const dt = tickDt(lead); const until = Math.max(...ts.map((t) => t.ph.until)); if (lead.tick == null || timeAt(lead.tick * step) < now) { lead.tick = Math.ceil(beatAt(Math.max(now + 0.02, until)) / step - 1e-6); } let k = lead.tick; for (let time = timeAt(k * step); time < now + LOOKAHEAD; time = timeAt(++k * step)) { // (after a tempo change, the ticks already played wait out) if (time < until - 1e-6) continue; beat(ts, time, dt, ts.length > 1, gain); } for (const t of ts) t.tick = k; } // schedule the ticks due within LOOKAHEAD, softer the more tracks play function schedule() { const now = clock(); const playing = tracks.filter((t) => t.playing && t.ph); const gain = 1 / Math.sqrt(Math.max(1, playing.length)); for (const g of groups) runTicks(g, now, gain); for (const t of playing) if (!groupOf(t)) runTicks([t], now, gain); for (const t of tracks) { if (!t.ph) continue; const dt = tickDt(t); const keep = Math.max((TAIL + 1) * dt, ringTime(dt) + dt); const q = t.ph.queue; while (q.length > 1 && q[1].time < now - keep) q.shift(); } } // a new global tempo: the beat carries on from now function setTempo(bpm) { const now = clock(); anchor = { time: now, beat: beatAt(now) }; tempo = bpm; } function setSound(on) { soundOn = on; renderSoundButton(); if (on && !synth) { // the clock switches to the audio context's synth = createSynth(); applyVolumes(); anchor = { time: clock(), beat: 0 }; for (const t of tracks) { t.tick = null; if (t.ph) { t.ph.queue = []; t.ph.until = 0; } } } if (synth) { synth.ctx.resume(); synth.setVolume(on ? Number($('volume').value) : 0); } } // ---- drawing ----------------------------------------------------------------- function readTheme() { const cs = getComputedStyle(document.documentElement); theme = { bg: cs.getPropertyValue('--bg').trim(), fg: cs.getPropertyValue('--fg').trim(), muted: cs.getPropertyValue('--muted').trim(), line: cs.getPropertyValue('--line').trim(), accent: cs.getPropertyValue('--accent').trim(), light: cs.getPropertyValue('--dot-light').trim(), }; } const orbitColor = (hue, isTrack, alpha = 1) => `hsla(${Math.round(hue * 360)}, ${isTrack ? 85 : 50}%, ${theme.light}, ${alpha})`; function plotRect() { const dpr = devicePixelRatio || 1; const w = canvas.width / dpr; const h = canvas.height / dpr; return { x: MARGIN.left, y: MARGIN.top, w: Math.max(10, w - MARGIN.left - MARGIN.right), h: Math.max(10, h - MARGIN.top - MARGIN.bottom) }; } const toPx = (r, x, v) => [r.x + ((x / view.xr + 1) / 2) * r.w, r.y + ((1 - v / view.vr) / 2) * r.h]; function drawPoints(o, from) { const r = plotRect(); const dctx = (o.isTrack ? top : dots).getContext('2d'); dctx.fillStyle = orbitColor(o.hue, o.isTrack, o.isTrack ? 0.95 : 0.7); const size = o.isTrack ? 2.2 : 1.4; for (let i = from; i < o.n; i++) { const [px, py] = toPx(r, o.pts[2 * i], o.pts[2 * i + 1]); dctx.fillRect(px - size / 2, py - size / 2, size, size); } } function clearDots(which = layers) { const dpr = devicePixelRatio || 1; for (const layer of which) { const c = layer.getContext('2d'); c.setTransform(1, 0, 0, 1, 0, 0); c.clearRect(0, 0, layer.width, layer.height); c.setTransform(dpr, 0, 0, dpr, 0, 0); } } // redraw the tracks' dots function redrawTop() { clearDots([top]); for (const t of tracks) if (t.orbit) drawPoints(t.orbit, 0); } // the opacity of the fading dots const ghostAlpha = () => Math.max(0, 1 - (performance.now() / 1000 - ghostStart) / FADE); // start fading out what the given layers show (on top of what is fading already) function fadeOut(which) { if (!canvas.width || !canvas.height) return; const c = spare.getContext('2d'); c.setTransform(1, 0, 0, 1, 0, 0); c.clearRect(0, 0, spare.width, spare.height); const a = ghostAlpha(); if (a > 0) { c.globalAlpha = a; c.drawImage(ghost, 0, 0); c.globalAlpha = 1; } for (const layer of which) c.drawImage(layer, 0, 0); [ghost, spare] = [spare, ghost]; ghostStart = performance.now() / 1000; } function resize() { const dpr = devicePixelRatio || 1; const { width, height } = canvas.getBoundingClientRect(); canvas.width = dots.width = top.width = ghost.width = spare.width = Math.round(width * dpr); canvas.height = dots.height = top.height = ghost.height = spare.height = Math.round(height * dpr); ghostStart = -Infinity; clearDots(); for (const o of seeds) drawPoints(o, 0); redrawTop(); } // advance the orbits within the frame's budget, drawing their new points function fill() { const deadline = performance.now() + FRAME_BUDGET; const advance = (o, count) => { const from = o.n; for (let k = 0; k < count && o.n < o.cap && !o.s.escaped; k++) { stepper.step(o.s); if (o.s.escaped) break; if (o.skip > 0) { o.skip--; continue; } o.pts[2 * o.n] = o.s.x; o.pts[2 * o.n + 1] = o.s.v; o.n++; } drawPoints(o, from); }; for (const g of groups) { // the coupled tracks together, as their playheads will move const os = g.map((t) => t.orbit); const from = os.map((o) => o.n); for (let k = 0; k < TRACK_PER_FRAME && os.some((o) => o.n < o.cap && !o.s.escaped); k++) { stepper.stepMany(os.map((o) => o.s), coupling); for (const o of os) { if (o.s.escaped || o.n >= o.cap) continue; o.pts[2 * o.n] = o.s.x; o.pts[2 * o.n + 1] = o.s.v; o.n++; } } os.forEach((o, k) => drawPoints(o, from[k])); } for (const t of tracks) if (t.orbit && !groupOf(t)) advance(t.orbit, TRACK_PER_FRAME); let busy = true; while (busy && performance.now() < deadline) { busy = false; for (const o of seeds) { if (o.n >= o.cap || o.s.escaped) continue; advance(o, 10); busy = true; } } } function drawAxes(r) { ctx.strokeStyle = theme.line; ctx.lineWidth = 1; ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1); ctx.beginPath(); ctx.moveTo(r.x + r.w / 2, r.y); ctx.lineTo(r.x + r.w / 2, r.y + r.h); ctx.moveTo(r.x, r.y + r.h / 2); ctx.lineTo(r.x + r.w, r.y + r.h / 2); ctx.stroke(); ctx.fillStyle = theme.muted; ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif'; ctx.textBaseline = 'top'; ctx.textAlign = 'left'; ctx.fillText(`−${view.xr.toFixed(2)}`, r.x, r.y + r.h + 6); ctx.textAlign = 'right'; ctx.fillText(view.xr.toFixed(2), r.x + r.w, r.y + r.h + 6); ctx.textAlign = 'center'; ctx.fillText('displacement x', r.x + r.w / 2, r.y + r.h + 6); ctx.save(); ctx.translate(r.x - 8, r.y + r.h / 2); ctx.rotate(-Math.PI / 2); ctx.textBaseline = 'bottom'; ctx.fillText('velocity ẋ (s⁻¹)', 0, 0); ctx.textAlign = 'right'; ctx.fillText(`${Math.round(view.vr)}`, r.h / 2, 0); ctx.textAlign = 'left'; ctx.fillText(`−${Math.round(view.vr)}`, -r.h / 2, 0); ctx.restore(); } function drawPlayhead(c, r, t) { const { ph, hue } = t; if (!ph?.queue.length) return; const now = clock(); const dt = tickDt(t); const q = ph.queue; let cur = -1; for (let k = 0; k < q.length; k++) if (q[k].time <= now) cur = k; if (cur < 0) return; c.save(); c.beginPath(); c.rect(r.x, r.y, r.w, r.h); c.clip(); c.lineWidth = 1.6; c.lineCap = 'round'; c.lineJoin = 'round'; let head = null; for (let k = 0; k <= cur; k++) { const e = q[k]; // (N, the steps per period, as when the path was computed) const N = e.path.length / 2 - 1; const CHUNK = Math.max(4, Math.ceil(N / 24)); const span = e.dt; const f = Math.min(1, (now - e.time) / span); const end = Math.floor(f * N); for (let j0 = 0; j0 < end; j0 += CHUNK) { const age = (now - (e.time + (j0 / N) * span)) / dt; const alpha = 1 - age / TAIL; if (alpha <= 0) continue; c.strokeStyle = orbitColor(hue, true, 0.85 * alpha); c.beginPath(); for (let j = j0; j <= Math.min(end, j0 + CHUNK); j++) { const [px, py] = toPx(r, e.path[2 * j], e.path[2 * j + 1]); if (j === j0) c.moveTo(px, py); else c.lineTo(px, py); } c.stroke(); } if (k === cur) { const j = Math.min(N, f * N); const i0 = Math.floor(j); const i1 = Math.min(N, i0 + 1); const w = j - i0; head = toPx(r, (1 - w) * e.path[2 * i0] + w * e.path[2 * i1], (1 - w) * e.path[2 * i0 + 1] + w * e.path[2 * i1 + 1]); if (e.last) head = null; } // each pluck: a ring growing and fading where it was played for (const n of e.notes) { const g = (now - n.t) / ringTime(e.dt); if (g < 0 || g >= 1) continue; const [sx, sy] = toPx(r, n.x, n.v); c.strokeStyle = orbitColor(hue, true); c.globalAlpha = 1 - g; c.lineWidth = 2; c.beginPath(); c.arc(sx, sy, 4 + 14 * g, 0, 2 * Math.PI); c.stroke(); c.globalAlpha = 1; } } if (head) { c.beginPath(); c.arc(head[0], head[1], 4.5, 0, 2 * Math.PI); if (t.playing) { c.fillStyle = orbitColor(hue, true); c.fill(); } else { // paused: a hollow head c.strokeStyle = orbitColor(hue, true); c.lineWidth = 2; c.stroke(); } } c.restore(); } // the tracks' start rings (a cross if escaped), and their numbers if `labels` function drawStarts(c, r, labels) { for (const t of tracks) { if (!t.start) continue; const [px, py] = toPx(r, t.start.x, t.start.v); const sel = t === selected; c.strokeStyle = orbitColor(t.hue, true); c.lineWidth = sel ? 2.5 : 1.5; c.beginPath(); if (t.orbit?.s.escaped) { // escaped: a cross at its start c.moveTo(px - 5, py - 5); c.lineTo(px + 5, py + 5); c.moveTo(px + 5, py - 5); c.lineTo(px - 5, py + 5); } else { c.arc(px, py, sel ? 7 : 5, 0, 2 * Math.PI); } c.stroke(); if (!labels) continue; // its number, beside the ring c.fillStyle = orbitColor(t.hue, true); c.font = `${sel ? 600 : 400} 12px "Hanken Grotesk", system-ui, sans-serif`; c.textAlign = 'left'; c.textBaseline = 'bottom'; c.fillText(trackName(t), px + 7, py - 5); } } // The phase space within plot rect r, on context c (set up so r is in CSS // px): the dots (and those fading out), then `under` (the axes, on screen), // the start rings (numbered if `labels`) and the playheads. function drawScene(c, r, { labels, under }) { const dpr = devicePixelRatio || 1; c.save(); c.beginPath(); c.rect(r.x, r.y, r.w, r.h); c.clip(); c.fillStyle = theme.bg; c.fillRect(r.x, r.y, r.w, r.h); const w = canvas.width / dpr; const h = canvas.height / dpr; const a = ghostAlpha(); if (a > 0) { c.globalAlpha = a; c.drawImage(ghost, 0, 0, w, h); c.globalAlpha = 1; } c.drawImage(dots, 0, 0, w, h); c.drawImage(top, 0, 0, w, h); c.restore(); under?.(); drawStarts(c, r, labels); for (const t of tracks) drawPlayhead(c, r, t); } function frame() { requestAnimationFrame(frame); if (!canvas.width || !canvas.height) return; if (dirty) { dirty = false; reset(); } syncCoupling(); fill(); schedule(); for (const t of tracks) { const esc = !!t.orbit?.s.escaped; if (esc !== t.escaped) { t.escaped = esc; updateTrack(t); } } const dpr = devicePixelRatio || 1; const r = plotRect(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = theme.bg; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); drawScene(ctx, r, { labels: true, under: () => drawAxes(r) }); if (recording) drawRecordingFrame(r); } // ---- instruments --------------------------------------------------------------- // a track's instrument: 'b' (VOICES[i]) or 's:' (preset i of the // loaded SoundFont with that id) const isSoundFont = (t) => t.instrument[0] === 's'; const sfId = (font, preset) => `s${font.id}:${preset}`; // a SoundFont instrument's { font, preset }, or null function fontPreset(id) { const m = /^s(\d+):(\d+)$/.exec(id); const font = m && soundfonts.find((f) => f.id === Number(m[1])); return font && Number(m[2]) < font.sf.presets.length ? { font, preset: Number(m[2]) } : null; } function voiceOf(t) { if (!isSoundFont(t)) return Number(t.instrument.slice(1)); const { font, preset } = fontPreset(t.instrument); if (!font.insts.has(preset)) font.insts.set(preset, makeInstrument(font.sf, preset)); return font.insts.get(preset); } function instrumentName(t) { if (!isSoundFont(t)) return VOICES[Number(t.instrument.slice(1))].name; const { font, preset } = fontPreset(t.instrument); return font.sf.presets[preset].name; } // the first built-in voice no track is playing function freeInstrument() { const i = VOICES.findIndex((_, k) => !tracks.some((t) => t.instrument === `b${k}`)); return `b${i < 0 ? 0 : i}`; } // ---- the tracks panel ------------------------------------------------------------ const escapeHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]); const svg = (body, attrs = '') => ``; const STROKE = 'fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"'; const ICONS = { play: svg(''), pause: svg(''), restart: svg('', STROKE), remove: svg('', STROKE), link: svg('', STROKE), unlink: svg('', STROKE), soundOn: svg('', 'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"'), keyboard: svg('', STROKE), soundOff: svg('', 'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"'), }; function scaleText(t) { if (isCustom(t)) { const c = val(t, 'notes'); if (!c.notes.length) return 'no notes yet'; const n = c.every ? new Set(c.notes.map(pc)).size : c.notes.length; return c.every ? `custom, ${n} per octave` : `${n} custom note${n === 1 ? '' : 's'}`; } const s = SCALES[val(t, 'scale')]; return `${KEYS[val(t, 'key')]} ${SCALE_SHORT[s.name] ?? s.name}`; } function summary(t) { if (!t.start) return 'No start yet: click the plot'; const r = RHYTHMS.find((q) => q.value === val(t, 'rhythm')); const parts = [scaleText(t), rateLabel(t), r.short]; if (t.escaped) parts.push('escaped'); return parts.join(' · '); } const fmtNum = (v) => (v < 0 ? '−' : '') + Math.abs(v); const coordsText = (t) => (t.start ? `x = ${fmtNum(+t.start.x.toFixed(3))}, ẋ = ${fmtNum(Math.round(t.start.v))} s⁻¹` : 'click the plot to place it'); function linkButton(t, p) { const on = t.linked[p]; const title = on ? 'Linked: shared with the other linked tracks. Click to unlink.' : 'This track\'s own. Click to link it with the other tracks.'; return ``; } function rangeRow(t, p, disabled = false) { const R = RANGES[p]; const v = val(t, p); return `
${linkButton(t, p)}${R.label} ${R.fmt(v)}
`; } // the tempo multiple: a menu of the usual ones, or a custom value typed in function rateRow(t) { const v = String(val(t, 'rate')); const custom = !RATES.includes(v) || t.customRate; const opts = RATES.map((r) => ``).join(''); return `
${linkButton(t, 'rate')}Tempo ${custom ? `` : ''}
`; } function instrumentOptions(t) { const opt = (value, name) => ``; let html = `${VOICES.map((v, i) => opt(`b${i}`, v.name)).join('')}`; for (const f of soundfonts) { const ps = f.sf.presets; html += `${ps.map((p, i) => opt(sfId(f, i), ps.length > 1 ? `${p.bank}:${p.program} ${p.name}` : p.name)).join('')}`; } return html; } // the custom notes' editor: a piano (the notes as they sound, in the track's // key; click a key, or press it on a MIDI keyboard, to add or remove it) const BLACK = [1, 3, 6, 8, 10]; function notesEditor(t) { const c = val(t, 'notes'); const sounding = soundingNotes(t); const on = new Set(sounding); const pcs = c.every ? new Set(sounding.map(pc)) : null; // C3 to B5 (or to C6, the top of the scale's range, in every octave), // widened by octaves to take in every note let lo = 48; let hi = c.every ? 84 : 83; if (sounding.length) { lo = Math.min(lo, 12 * Math.floor(sounding[0] / 12)); hi = Math.max(hi, 12 * Math.ceil((sounding[sounding.length - 1] + 1) / 12) - 1); } const whites = []; const blacks = []; for (let m = lo; m <= hi; m++) (BLACK.includes(m % 12) ? blacks : whites).push({ m, at: whites.length }); const w = whites.length; const key = ({ m, at }, black) => { const lit = on.has(m); const echo = !lit && pcs?.has(m % 12); const cls = `${black ? 'bk' : 'wk'}${lit ? ' on' : ''}${echo ? ' echo' : ''}${midi.down.has(m) ? ' down' : ''}`; return ``; }; const listening = midi.listening && t === selected; const names = c.every ? [...new Set(sounding.map(pc))].sort((a, b) => a - b).map((k) => KEYS[k]).join(' ') : sounding.map(noteName).join(' '); let status; if (midi.error) status = `${midi.error}`; else if (listening) { status = midi.inputs.length ? `Listening to ${escapeHtml(midi.inputs.join(', '))}: hold down the notes you want, together or one after another without letting go (or with the sustain pedal down). Once you let go of everything, the next key starts a new set.` : 'No MIDI keyboard found: plug one in (it is picked up when you do).'; } else status = 'Click keys to add or remove notes, or use a MIDI keyboard.'; return `
${whites.map((k) => key(k, false)).join('')}${blacks.map((k) => key(k, true)).join('')}

${names ? `${names}` : 'No notes yet: the track is silent.'}
${status}

`; } // redraw the selected track's notes editor (if it is open) function refreshNotesEditor() { const el = selected && trackEl(selected)?.querySelector('.notes-editor'); if (el) el.outerHTML = notesEditor(selected); } // add or remove sounding note m from a track's custom notes (every octave: // its pitch class); true if added function toggleNote(t, m) { let c = val(t, 'notes'); if (!c.notes.length) c = { ...c, ref: val(t, 'key') }; const n = m - shiftOf(c, val(t, 'key')); const has = c.every ? c.notes.some((q) => pc(q) === pc(n)) : c.notes.includes(n); const notes = has ? c.notes.filter((q) => (c.every ? pc(q) !== pc(n) : q !== n)) : [...c.notes, n].sort((a, b) => a - b); setValue(t, 'notes', { ...c, notes }); tracks.forEach(updateTrack); return !has; } // sound a note on a track's instrument now (to hear a key clicked) function previewNote(t, m, vel = 100) { if (!soundOn || !synth) return; synth.play(t.id, voiceOf(t), midiHz(m), synth.ctx.currentTime + 0.01, { pan: 0, gain: 0.8, sustain: Math.min(1.5, val(t, 'sustain')), vel }); } // ---- the MIDI keyboard ------------------------------------------------------------- // access: once granted; listening: its keys go to the selected track's // custom notes; inputs: the devices' names; down: the keys held // (held: a set of notes is being played: a key has gone down since all were // up, and some key, or the sustain pedal, is still down) const midi = { access: null, listening: false, inputs: [], error: '', down: new Set(), pedal: false, held: false }; // open MIDI (once): '' if open, or why not async function openMidiOnce() { if (midi.access) return ''; if (!midiSupported()) return 'This browser has no Web MIDI (Chrome, Edge and Firefox do).'; try { midi.access = await openMidi({ onNote: midiNote, onPedal: (down) => { midi.pedal = down; if (!down && !midi.down.size) midi.held = false; }, onControl: midiControl, onInputs: (names) => { midi.inputs = names; refreshNotesEditor(); renderKnobs(); }, }); return ''; } catch { return 'MIDI access was blocked: allow it for this page in the browser\'s site settings.'; } } async function setListening(on) { midi.error = ''; midi.listening = false; if (on) { const err = await openMidiOnce(); if (err) midi.error = midiSupported() ? err : `${err} You can still click the keys.`; else midi.listening = true; } refreshNotesEditor(); } // ---- MIDI knobs ------------------------------------------------------------------ // The sliders a knob (a MIDI controller's control change) can be assigned // to: the equation's and the coupling. knobs: { [slider id]: { ch, cc, // mode } }; learning: the slider waiting for a knob to be turned. // // mode: how the knob sends its turns. 'abs': its position, 0 to 127 (only // when it changes); or relative, as endless encoders (the MiniLab's // clickable browse knobs, say) send them: each message a step left or right, // as 64 ± n ('rel64'), 16 ± n ('rel16') or n in two's complement ('rel2c'). // Told apart by repeats: a relative knob turned steadily sends the same // value again and again, which an absolute one never does. const KNOB_TARGETS = () => [...SLIDERS.map((sl) => `s-${sl.name}`), 'coupling']; let knobs = {}; let knobsShown = false; let learning = null; let knobError = ''; let candidate = null; // while learning: { ch, cc, values, timer }, the knob being turned const lastValue = new Map(); // the last value of each control ('ch:cc') const flashTimers = new Map(); const MODES = ['abs', 'rel64', 'rel16', 'rel2c']; const isRelative = (k) => k.mode !== 'abs' && k.mode !== 'auto'; // the relative mode values (repeats seen) suggest function relativeMode(values) { if (values.every((v) => v >= 48 && v <= 80)) return 'rel64'; if (values.every((v) => v >= 8 && v <= 24)) return 'rel16'; return 'rel2c'; } // a relative knob's message: the steps it turned (negative: to the left) function relativeSteps(mode, v) { if (mode === 'rel64') return v - 64; if (mode === 'rel16') return v - 16; return v < 64 ? v : v - 128; } function readKnobs(o) { const r = {}; for (const id of KNOB_TARGETS()) { const k = o?.[id]; if (k && Number.isInteger(k.ch) && k.ch >= 0 && k.ch < 16 && Number.isInteger(k.cc) && k.cc >= 0 && k.cc < 128) { // (assigned before modes: 'auto', told by its next two values) r[id] = { ch: k.ch, cc: k.cc, mode: MODES.includes(k.mode) ? k.mode : 'auto' }; } } return r; } const knobLabel = (k) => `CC${k.cc}${k.ch ? `/${k.ch + 1}` : ''}${isRelative(k) ? ' ↻' : ''}`; function renderKnobs() { $('knobs').setAttribute('aria-pressed', knobsShown); document.querySelector('.eqn-panel').classList.toggle('knobs-on', knobsShown); for (const id of KNOB_TARGETS()) { const row = $(id).closest('.row'); let chip = row.querySelector('.knob'); if (!chip) { chip = document.createElement('button'); chip.className = 'knob'; chip.dataset.knob = id; chip.type = 'button'; row.append(chip); } const k = knobs[id]; const name = row.querySelector('span').textContent; chip.classList.toggle('learning', learning === id); chip.classList.toggle('set', !!k); chip.textContent = learning === id ? 'turn…' : k ? knobLabel(k) : '+'; chip.title = learning === id ? 'Turn a knob to assign it (click to cancel)' : k ? `${knobLabel(k)} (${isRelative(k) ? 'relative' : 'absolute'}) controls ${name}: click to change or unassign it` : `Assign a knob to ${name}`; } const msg = $('knob-msg'); msg.hidden = !knobsShown; msg.classList.toggle('error', !!knobError); const none = midi.access && !midi.inputs.length ? ' No MIDI device found: plug one in.' : ''; if (knobError) msg.textContent = knobError; else if (learning) { const k = knobs[learning]; const kind = k ? ` Its ${knobLabel(k)} is ${isRelative(k) ? 'relative (endless)' : 'absolute (0 to 127)'}: · ` : ''; msg.innerHTML = `Turn a knob on your controller to assign it.${none}${kind}`; } else msg.textContent = `Click a slider's + (or its knob's label), then turn a knob to assign it.${none}`; } async function learnKnob(id) { knobError = ''; if (candidate) clearTimeout(candidate.timer); candidate = null; learning = learning === id ? null : id; if (learning) knobError = await openMidiOnce(); if (knobError) learning = null; renderKnobs(); } // the knob turned while learning: assigned once it has sent a few values // (or paused), as relative if any repeated function assignCandidate() { const { ch, cc, values, timer } = candidate; clearTimeout(timer); candidate = null; if (!learning) return; for (const [id, k] of Object.entries(knobs)) if (k.ch === ch && k.cc === cc) delete knobs[id]; const repeats = values.some((v, i) => i && v === values[i - 1]); knobs[learning] = { ch, cc, mode: repeats ? relativeMode(values) : 'abs' }; learning = null; saveKnobs(knobs); renderKnobs(); } // a knob turned (or another control change) function midiControl(ch, cc, value) { const key = `${ch}:${cc}`; const seen = lastValue.has(key); const repeat = lastValue.get(key) === value; lastValue.set(key, value); if (learning) { if (candidate && (candidate.ch !== ch || candidate.cc !== cc)) return; candidate ??= { ch, cc, values: [], timer: setTimeout(assignCandidate, 400) }; candidate.values.push(value); if (candidate.values.length >= 5) assignCandidate(); return; } for (const [id, k] of Object.entries(knobs)) { if (k.ch !== ch || k.cc !== cc) continue; // an absolute knob repeating itself is a relative one after all if (repeat && !isRelative(k)) { k.mode = relativeMode([value]); saveKnobs(knobs); renderKnobs(); } else if (k.mode === 'auto') { // (not known yet: wait for a second value) if (!seen) continue; k.mode = 'abs'; saveKnobs(knobs); } const input = $(id); const lo = Number(input.min); const hi = Number(input.max); // absolute: the slider's range, 0 to 127; relative: steps of a 256th of // it (at least the slider's step), more as the knob turns faster; // snapped to the slider's step by the input const v = isRelative(k) ? Number(input.value) + relativeSteps(k.mode, value) * Math.max(Number(input.step) || 0, (hi - lo) / 256) : lo + ((hi - lo) * value) / 127; const before = input.value; input.value = v; if (input.value === before) continue; input.dispatchEvent(new Event('input', { bubbles: true })); // (the row lights up a moment) const row = input.closest('.row'); row.classList.add('turned'); clearTimeout(flashTimers.get(id)); flashTimers.set(id, setTimeout(() => row.classList.remove('turned'), 250)); } } function buildKnobControls() { knobs = readKnobs(loadKnobs()); $('knobs').addEventListener('click', () => { knobsShown = !knobsShown; if (!knobsShown) learning = null; knobError = ''; renderKnobs(); }); document.querySelector('.eqn-panel').addEventListener('click', (e) => { if (e.target.closest('[data-mode]') && learning && knobs[learning]) { const k = knobs[learning]; k.mode = isRelative(k) ? 'abs' : relativeMode([lastValue.get(`${k.ch}:${k.cc}`) ?? 64]); saveKnobs(knobs); renderKnobs(); return; } if (e.target.closest('[data-unassign]') && learning) { delete knobs[learning]; learning = null; saveKnobs(knobs); renderKnobs(); return; } const chip = e.target.closest('.knob'); if (!chip) return; e.preventDefault(); learnKnob(chip.dataset.knob); }); renderKnobs(); // knobs assigned before: listen for them (MIDI access, if granted before, // is given without asking) if (Object.keys(knobs).length && midiSupported()) openMidiOnce(); } // A key pressed on the MIDI keyboard: the keys pressed together (from the // first one down until all are up, and the sustain pedal too) become the // notes; the next press after that starts afresh. function midiNote(m, on) { const fresh = on && !midi.held; if (on) { midi.down.add(m); midi.held = true; } else { midi.down.delete(m); if (!midi.down.size && !midi.pedal) midi.held = false; } const t = selected; // (not sounded: the keyboard makes its own sound, if any) if (midi.listening && t && isCustom(t) && on) addNote(t, m, fresh); refreshNotesEditor(); } // add sounding note m to a track's custom notes, or (fresh) make it the only one function addNote(t, m, fresh) { let c = val(t, 'notes'); if (fresh || !c.notes.length) c = { ...c, notes: [], ref: val(t, 'key') }; const n = m - shiftOf(c, val(t, 'key')); if (!c.notes.includes(n)) setValue(t, 'notes', { ...c, notes: [...c.notes, n].sort((a, b) => a - b) }); else setValue(t, 'notes', c); tracks.forEach(updateTrack); } function trackBody(t) { const sf = isSoundFont(t); const lk = (p) => (t.linked[p] ? ' linked' : ''); return `
Start ${coordsText(t)}
Instrument
${linkButton(t, 'rhythm')}Rhythm
${linkButton(t, 'scale')}Scale
${isCustom(t) ? notesEditor(t) : ''}
${linkButton(t, 'key')}Key
${KEYS.map((k, i) => ``).join('')}
${rateRow(t)} ${rangeRow(t, 'sustain', sf)} ${rangeRow(t, 'volume')} ${rangeRow(t, 'velocity', !sf)}
`; } function trackItem(t) { const sel = t === selected; return `
  • ${trackName(t)}${escapeHtml(instrumentName(t))} ${summary(t)}
    ${sel ? trackBody(t) : ''}
  • `; } function renderTracks() { $('track-list').innerHTML = tracks.map(trackItem).join(''); renderSoundFonts(); $('add-track').disabled = tracks.length >= MAX_TRACKS; $('add-track').textContent = tracks.length >= MAX_TRACKS ? `${MAX_TRACKS} tracks at most` : '+ Add track'; renderTransport(); renderHint(); } const trackEl = (t) => $('track-list').querySelector(`.track[data-id="${t.id}"]`); // update a track's head (and its body's start) in place function updateTrack(t) { const el = trackEl(t); if (!el) return; el.querySelector('.summary').textContent = summary(t); const play = el.querySelector('[data-act="play"]'); play.setAttribute('aria-pressed', t.playing); play.title = t.playing ? 'Pause' : 'Play'; play.setAttribute('aria-label', `${t.playing ? 'Pause' : 'Play'} track ${trackName(t)}`); play.innerHTML = t.playing ? ICONS.pause : ICONS.play; const coords = el.querySelector('.coords'); if (coords) coords.innerHTML = coordsText(t); } function renderTransport() { const placed = tracks.filter((t) => t.start); $('play-all').disabled = !placed.some((t) => !t.playing); $('pause-all').disabled = !placed.some((t) => t.playing); $('restart-all').disabled = !placed.length; } function renderHint() { const t = selected; let s; if (!tracks.length) s = 'Click the plot to add a track'; else if (!t) s = 'Click to add a track · click a start ring to pick its track'; else if (!t.start) s = `Click to place track ${trackName(t)}'s start`; else s = `Click or drag to move track ${trackName(t)}'s start${tracks.length < MAX_TRACKS && !matchMedia('(pointer: coarse)').matches ? ' · shift-click for a new track' : ''}`; $('hint').textContent = s; } function renderSoundButton() { const btn = $('sound'); btn.setAttribute('aria-pressed', soundOn); btn.innerHTML = `${soundOn ? ICONS.soundOn : ICONS.soundOff}${soundOn ? 'Sound on' : 'Sound off'}`; btn.title = soundOn ? 'Mute' : 'Turn the sound on'; if (soundOn) btn.classList.remove('nudge'); } function setPlaying(t, on) { if (!t.start || t.playing === on) return; t.playing = on; if (on && !t.ph) restart([t]); updateTrack(t); renderTransport(); // playing, but muted: point at the sound button if (on && !soundOn) { const btn = $('sound'); btn.classList.remove('nudge'); void btn.offsetWidth; btn.classList.add('nudge'); } } function buildTrackControls() { const list = $('track-list'); const trackOf = (el) => { const li = el.closest('.track'); return li && tracks.find((t) => String(t.id) === li.dataset.id); }; list.addEventListener('click', (e) => { const t = trackOf(e.target); if (!t) return; const act = e.target.closest('[data-act]'); const noteBtn = e.target.closest('button[data-note]'); if (noteBtn) { const m = Number(noteBtn.dataset.note); if (toggleNote(t, m)) previewNote(t, m); refreshNotesEditor(); return; } const keyBtn = e.target.closest('button[data-key]'); if (keyBtn) { setValue(t, 'key', Number(keyBtn.dataset.key)); for (const b of keyBtn.parentElement.children) b.setAttribute('aria-pressed', b === keyBtn); tracks.forEach(updateTrack); refreshNotesEditor(); return; } if (!act) return; switch (act.dataset.act) { case 'play': setPlaying(t, !t.playing); break; case 'restart': restartTrack(t); break; case 'remove': removeTrack(t); break; case 'midi': setListening(!midi.listening); break; case 'clear-notes': setValue(t, 'notes', { ...val(t, 'notes'), notes: [] }); tracks.forEach(updateTrack); refreshNotesEditor(); break; case 'link': setLinked(t, act.dataset.p, !t.linked[act.dataset.p]); renderTracks(); break; case 'select': selected = selected === t ? null : t; renderTracks(); break; default: } }); list.addEventListener('input', (e) => { if (e.target.matches('input[data-rate-custom]')) { e.target.classList.toggle('invalid', Number.isNaN(parseRate(e.target.value.replace(/\s+/g, '')))); return; } const t = trackOf(e.target); const p = e.target.dataset?.p; if (!t || !RANGES[p]) return; const v = Number(e.target.value); setValue(t, p, v); e.target.closest('.trow').querySelector('output').textContent = RANGES[p].fmt(v); tracks.forEach(updateTrack); }); list.addEventListener('change', (e) => { const t = trackOf(e.target); if (!t) return; if (e.target.matches('select[data-instrument]')) { t.instrument = e.target.value; renderTracks(); } else if (e.target.matches('select[data-rate]')) { if (e.target.value === 'custom') { t.customRate = true; renderTracks(); const input = trackEl(t)?.querySelector('[data-rate-custom]'); input?.focus(); input?.select(); } else { t.customRate = false; setValue(t, 'rate', e.target.value); renderTracks(); } } else if (e.target.matches('input[data-rate-custom]')) { const text = e.target.value.replace(/\s+/g, ''); const ok = !Number.isNaN(parseRate(text)); e.target.classList.toggle('invalid', !ok); if (ok) { setValue(t, 'rate', text); tracks.forEach(updateTrack); } } else if (e.target.matches('select[data-p="rhythm"]')) { setValue(t, 'rhythm', e.target.value); tracks.forEach(updateTrack); } else if (e.target.matches('select[data-p="scale"]')) { const custom = e.target.value === CUSTOM; setValue(t, 'scale', custom ? CUSTOM : Number(e.target.value)); renderTracks(); // (the keyboard's keys go to the notes from the start) if (custom && midiSupported() && !midi.listening) setListening(true); } else if (e.target.matches('input[data-every]')) { setValue(t, 'notes', { ...val(t, 'notes'), every: e.target.checked }); tracks.forEach(updateTrack); refreshNotesEditor(); } }); $('add-track').addEventListener('click', addTrack); $('play-all').addEventListener('click', () => tracks.forEach((t) => setPlaying(t, true))); $('pause-all').addEventListener('click', () => tracks.forEach((t) => setPlaying(t, false))); $('restart-all').addEventListener('click', () => { restart(tracks); for (const g of groups) reseed(g); }); } // ---- the plot: picking and dragging starts ------------------------------------ function buildPlotControls() { let drag = null; // { t, px, py, moved } const at = (e) => { const rect = canvas.getBoundingClientRect(); const r = plotRect(); const px = e.clientX - rect.left; const py = e.clientY - rect.top; const inside = px >= r.x && px <= r.x + r.w && py >= r.y && py <= r.y + r.h; const cx = Math.min(r.x + r.w, Math.max(r.x, px)); const cy = Math.min(r.y + r.h, Math.max(r.y, py)); return { r, px, py, inside, x: ((cx - r.x) / r.w * 2 - 1) * view.xr, v: (1 - (cy - r.y) / r.h * 2) * view.vr }; }; canvas.addEventListener('pointerdown', (e) => { const p = at(e); if (!p.inside) return; // on a start ring: pick that track (and drag it, past a few px) const hit = !e.shiftKey && tracks.find((t) => { if (!t.start) return false; const [cx, cy] = toPx(p.r, t.start.x, t.start.v); return Math.hypot(cx - p.px, cy - p.py) <= HIT_RADIUS; }); canvas.setPointerCapture(e.pointerId); if (hit) { if (selected !== hit) { selected = hit; renderTracks(); } drag = { t: hit, px: p.px, py: p.py, moved: false }; return; } // elsewhere: move the selected track's start (shift, or none selected: // a new track's) let t = selected; if (e.shiftKey || !t) t = addTrack(); if (!t) return; setStart(t, p.x, p.v); drag = { t, moved: true }; }); canvas.addEventListener('pointermove', (e) => { if (!drag) return; const p = at(e); if (!drag.moved && Math.hypot(p.px - drag.px, p.py - drag.py) < DRAG_START) return; drag.moved = true; setStart(drag.t, p.x, p.v); }); const end = () => { drag = null; }; canvas.addEventListener('pointerup', end); canvas.addEventListener('pointercancel', end); } // ---- the equation panel ---------------------------------------------------------- function buildEquationControls() { const presetSel = $('preset'); presetSel.innerHTML = PRESETS.map((pr, i) => ``).join('') + ''; $('sliders').innerHTML = SLIDERS.map((s) => ` `).join(''); for (const s of SLIDERS) { $(`s-${s.name}`).addEventListener('input', (e) => { params[s.name] = Number(e.target.value) * (s.scale ?? 1); $(`o-${s.name}`).textContent = s.fmt(Number(e.target.value)); presetSel.value = 'custom'; dirty = true; }); } presetSel.addEventListener('change', () => { if (presetSel.value === 'custom') return; // the tracks carry on from where they are under the new parameters params = { ...PRESETS[presetSel.value].params }; showParams(); dirty = true; }); showParams(); // coupling: off, then 1 to about 3000 s^-1 on a log scale (the coupled // tracks' dots are recomputed, in syncCoupling) const cpl = $('coupling'); cpl.addEventListener('input', () => setCoupling(Number(cpl.value))); setCoupling(Number(cpl.value)); } function showParams() { for (const s of SLIDERS) { const v = params[s.name] / (s.scale ?? 1); $(`s-${s.name}`).value = v; $(`o-${s.name}`).textContent = s.fmt(Number($(`s-${s.name}`).value)); } } // u: the coupling slider, 0 (off), then 1 to about 3000 s^-1 on a log scale function setCoupling(u) { $('coupling').value = u; coupling = u ? 10 ** (u / 20) : 0; $('coupling').nextElementSibling.textContent = coupling ? `${Math.round(coupling)} s⁻¹` : 'off'; } function buildMasterControls() { const vol = $('volume'); vol.addEventListener('input', () => setMasterVolume(Number(vol.value))); setMasterVolume(Number(vol.value)); $('sound').addEventListener('click', () => setSound(!soundOn)); const tem = $('tempo'); Object.assign(tem, { min: TEMPO.min, max: TEMPO.max, step: 1, value: tempo }); tem.addEventListener('input', () => { setTempo(Number(tem.value)); showTempo(); }); showTempo(); renderSoundButton(); } const showTempo = () => { $('tempo').value = tempo; $('tempo').nextElementSibling.textContent = `${tempo} bpm`; }; function setMasterVolume(v) { const vol = $('volume'); vol.value = v; vol.nextElementSibling.textContent = `${Math.round(100 * v)}%`; if (synth && soundOn) synth.setVolume(v); } // ---- uploaded SoundFont ------------------------------------------------------- // add a .sf2 file's bytes (ArrayBuffer): its presets join the instruments. // A file of the same name as one loaded replaces it (its tracks keep their // presets, found by name). save: remember it in this browser; assign: the // open track takes its first preset. Returns the font, or null if unreadable. function addSoundFont(fileName, bytes, { save = true, assign = save } = {}) { let sf; try { sf = parseSF2(bytes); } catch (err) { sfMessage(`Can't read ${fileName}: ${err.message}`, true); return null; } const old = soundfonts.find((f) => f.fileName === fileName); const font = { id: old?.id ?? nextFontId++, fileName, bytes, sf, insts: new Map() }; if (old) { // the tracks on it: their presets by name in the new file const names = new Map(tracks.filter((t) => fontPreset(t.instrument)?.font === old) .map((t) => [t, old.sf.presets[fontPreset(t.instrument).preset].name])); soundfonts[soundfonts.indexOf(old)] = font; for (const [t, name] of names) { const k = sf.presets.findIndex((p) => p.name === name); t.instrument = k >= 0 ? sfId(font, k) : freeInstrument(); } } else { soundfonts.push(font); } if (save) saveSoundFont({ fileName, bytes }); if (assign && selected) selected.instrument = sfId(font, 0); sfMessage(''); renderSoundFonts(); renderTracks(); return font; } function removeSoundFont(font) { soundfonts = soundfonts.filter((f) => f !== font); forgetSoundFont(font.fileName); for (const t of tracks) if (isSoundFont(t) && !fontPreset(t.instrument)) t.instrument = freeInstrument(); renderSoundFonts(); renderTracks(); } const sfMessage = (text, error = false) => { $('sf-msg').textContent = text; $('sf-msg').classList.toggle('error', error); }; function renderSoundFonts() { $('sf-list').innerHTML = soundfonts.map((f) => { const n = f.sf.presets.length; const used = tracks.filter((t) => fontPreset(t.instrument)?.font === f).map(trackName); return `
  • ${escapeHtml(f.fileName)} ${n} preset${n === 1 ? '' : 's'}${used.length ? ` · track${used.length > 1 ? 's' : ''} ${used.join(', ')}` : ''}
  • `; }).join(''); $('sf-empty').hidden = soundfonts.length > 0; } function buildSoundFontControls() { $('sf-load').addEventListener('click', () => $('sf-file').click()); $('sf-file').addEventListener('change', async () => { const files = [...$('sf-file').files]; $('sf-file').value = ''; // (the open track takes the first one's first preset) let assign = true; for (const file of files) { if (addSoundFont(file.name, await file.arrayBuffer(), { assign })) assign = false; } }); $('sf-list').addEventListener('click', (e) => { const btn = e.target.closest('button[data-font]'); const font = btn && soundfonts.find((f) => String(f.id) === btn.dataset.font); if (font) removeSoundFont(font); }); renderSoundFonts(); } // ---- saving the state ------------------------------------------------------------ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)); const finite = (v) => typeof v === 'number' && Number.isFinite(v); // everything to save: the equation, the global settings and the tracks (each // with where its playhead is), but not whether the sound is on function captureState() { return { format: FORMAT, version: 1, preset: $('preset').value, params: { ...params }, coupling: Number($('coupling').value), tempo, volume: Number($('volume').value), shared: { ...shared }, hueCounter, selected: tracks.indexOf(selected), tracks: tracks.map((t) => ({ hue: t.hue, instrument: isSoundFont(t) ? 's' : t.instrument, ...(isSoundFont(t) ? { soundfont: fontPreset(t.instrument).font.fileName, preset: fontPreset(t.instrument).preset } : {}), instrumentName: instrumentName(t), start: t.start, at: t.ph ? { x: t.ph.s.x, v: t.ph.s.v, escaped: t.ph.s.escaped } : null, playing: t.playing, own: { ...t.own }, linked: { ...t.linked }, customRate: !!t.customRate, })), }; } // a track's settings from saved ones, each checked (or the default's) function readSettings(o, base) { const r = { ...base }; if (!o || typeof o !== 'object') return r; if (RHYTHMS.some((q) => q.value === o.rhythm)) r.rhythm = o.rhythm; if ((Number.isInteger(o.scale) && SCALES[o.scale]) || o.scale === CUSTOM) r.scale = o.scale; const c = o.notes; if (c && typeof c === 'object' && Array.isArray(c.notes)) { r.notes = { notes: [...new Set(c.notes.filter((n) => Number.isInteger(n) && n >= 0 && n <= 127))].sort((a, b) => a - b), ref: Number.isInteger(c.ref) && c.ref >= 0 && c.ref < 12 ? c.ref : DEFAULT_KEY, every: !!c.every, }; } if (Number.isInteger(o.key) && o.key >= 0 && o.key < KEYS.length) r.key = o.key; if (o.rate != null && !Number.isNaN(parseRate(o.rate))) r.rate = String(o.rate); for (const p of ['sustain', 'volume', 'velocity']) if (finite(o[p])) r[p] = clamp(o[p], RANGES[p].min, RANGES[p].max); return r; } // a saved track's instrument, if there is such a one: a built-in voice, or a // SoundFont preset, in the file of that name by its number if the name // matches, or else by name (in that file, then in any loaded) function readInstrument(s) { const b = /^b(\d+)$/.exec(String(s.instrument)); if (b) return Number(b[1]) < VOICES.length ? s.instrument : null; // (saved when only one SoundFont could be loaded: 's') const old = /^s(\d+)$/.exec(String(s.instrument)); const font = soundfonts.find((f) => f.fileName === s.soundfont) ?? (old ? soundfonts[0] : null); const i = old ? Number(old[1]) : s.preset; const name = s.instrumentName; if (font) { const ps = font.sf.presets; if (Number.isInteger(i) && i >= 0 && i < ps.length && (name == null || ps[i].name === name)) return sfId(font, i); const k = ps.findIndex((p) => p.name === name); if (k >= 0) return sfId(font, k); } for (const f of soundfonts) { const k = f.sf.presets.findIndex((p) => p.name === name); if (k >= 0) return sfId(f, k); } return null; } const readPoint = (p) => (p && finite(p.x) && finite(p.v) ? { x: p.x, v: p.v } : null); // replace everything with a saved state ({} for the defaults); the tracks // carry on from where their playheads were function applyState(st) { st = st && typeof st === 'object' ? st : {}; params = { ...PRESETS[0].params }; for (const sl of SLIDERS) if (finite(st.params?.[sl.name])) params[sl.name] = clamp(st.params[sl.name], sl.min * (sl.scale ?? 1), sl.max * (sl.scale ?? 1)); const presets = [...$('preset').options].map((o) => o.value); $('preset').value = presets.includes(String(st.preset)) ? String(st.preset) : st.params ? 'custom' : '0'; showParams(); setCoupling(finite(st.coupling) ? Math.round(clamp(st.coupling, 0, 70)) : 0); setTempo(finite(st.tempo) ? Math.round(clamp(st.tempo, TEMPO.min, TEMPO.max)) : TEMPO.default); showTempo(); setMasterVolume(finite(st.volume) ? clamp(st.volume, 0, 1) : 0.6); shared = readSettings(st.shared, DEFAULTS); for (const t of tracks) synth?.removeTrack(t.id); tracks = []; hueCounter = 0; for (const s of (Array.isArray(st.tracks) ? st.tracks : []).slice(0, MAX_TRACKS)) { if (!s || typeof s !== 'object') continue; const t = newTrack(); if (finite(s.hue)) t.hue = s.hue; t.instrument = readInstrument(s) ?? t.instrument; t.own = readSettings(s.own, DEFAULTS); for (const p of SETTINGS) if (typeof s.linked?.[p] === 'boolean') t.linked[p] = s.linked[p]; t.customRate = !!s.customRate; t.start = readPoint(s.start); if (t.start) { const at = readPoint(s.at) ?? t.start; t.ph = newPlayhead(at.x, at.v); t.ph.s.escaped = !!s.at?.escaped; t.orbit = newOrbit(t.start.x, t.start.v, TRACK_POINTS, t.hue, true); t.playing = !!s.playing; } tracks.push(t); } hueCounter = Math.max(tracks.length, finite(st.hueCounter) ? st.hueCounter : 0); selected = st.selected === -1 ? null : tracks[st.selected] ?? tracks[0] ?? null; groups = []; groupKey = ''; dirty = true; // (reset at the next frame: the dots from where the playheads are) if (!tracks.length) addTrack(); applyVolumes(); renderTracks(); } const sessionMessage = (text, error = false) => { $('session-msg').textContent = text; $('session-msg').classList.toggle('error', error); }; function autosave() { if (restored && !saveLocal(captureState())) sessionMessage('Couldn\'t save in this browser (storage is blocked or full).', true); } function exportFile() { const st = captureState(); st.soundfonts = soundfonts.map((f) => ({ fileName: f.fileName, data: toBase64(f.bytes) })); const d = new Date(); const pad = (n) => String(n).padStart(2, '0'); const name = `duffing-islands-${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.json`; download(JSON.stringify(st, null, 1), name); const n = soundfonts.length; sessionMessage(`Saved ${name}${n ? `, with ${n === 1 ? soundfonts[0].fileName : `${n} SoundFonts`}` : ''}.`); } async function importFile(file) { let st; try { st = JSON.parse(await file.text()); } catch { sessionMessage(`Can't read ${file.name}: not a JSON file.`, true); return; } if (st?.format !== FORMAT) { sessionMessage(`${file.name} isn't a Duffing Islands file.`, true); return; } // its SoundFonts first, so the tracks can find their instruments for (const sf of Array.isArray(st.soundfonts) ? st.soundfonts : []) { if (!sf?.data) continue; const fileName = String(sf.fileName ?? 'SoundFont.sf2'); let bytes; try { bytes = fromBase64(sf.data); } catch { sfMessage(`Can't read ${fileName} in ${file.name}.`, true); continue; } addSoundFont(fileName, bytes, { save: true, assign: false }); } applyState(st); autosave(); sessionMessage(`Opened ${file.name}.`); } function buildSessionControls() { $('export').addEventListener('click', exportFile); $('import').addEventListener('click', () => $('import-file').click()); $('import-file').addEventListener('change', () => { const file = $('import-file').files[0]; $('import-file').value = ''; if (file) importFile(file); }); $('start-over').addEventListener('click', () => { if (!confirm('Start over with the default settings and one empty track? (Save to a file first to keep this session.)')) return; forgetLocal(); applyState({}); sessionMessage('Started over.'); }); // save as you go, and on leaving setInterval(autosave, 2000); addEventListener('pagehide', autosave); document.addEventListener('visibilitychange', () => { if (document.hidden) autosave(); }); } // ---- recording a video ------------------------------------------------------------ // The video is the phase space alone (no axes or labels), drawn each frame // onto a canvas of its own at the plot's size when the recording started // (its longer side at most REC_MAX px); the audio is the sound as heard. const REC_MAX = 1920; const REC_FPS = 60; const recCanvas = document.createElement('canvas'); const REC_TYPES = [ 'video/mp4;codecs=avc1.640028,mp4a.40.2', 'video/mp4;codecs=avc1.4d002a,mp4a.40.2', 'video/mp4', 'video/webm;codecs=vp9,opus', 'video/webm;codecs=vp8,opus', 'video/webm', ]; const canRecord = () => typeof MediaRecorder !== 'undefined' && !!recCanvas.captureStream; // a frame of the video: the plot rect r of the screen, scaled to the canvas function drawRecordingFrame(r) { const c = recCanvas.getContext('2d'); const sx = recCanvas.width / r.w; const sy = recCanvas.height / r.h; c.setTransform(sx, 0, 0, sy, -r.x * sx, -r.y * sy); drawScene(c, r, { labels: false }); } const fmtTime = (sec) => { const s = Math.floor(sec); const h = Math.floor(s / 3600); const mm = String(Math.floor((s % 3600) / 60)).padStart(h ? 2 : 1, '0'); return `${h ? `${h}:` : ''}${mm}:${String(s % 60).padStart(2, '0')}`; }; const fmtSize = (bytes) => (bytes < 1e9 ? `${(bytes / 1e6).toFixed(bytes < 1e7 ? 1 : 0)} MB` : `${(bytes / 1e9).toFixed(2)} GB`); function startRecording() { if (!canRecord()) return; // the audio is the sound as heard, so the sound goes on if (!soundOn) setSound(true); discardRecording(); const r = plotRect(); const dpr = devicePixelRatio || 1; const k = Math.min(1, REC_MAX / (Math.max(r.w, r.h) * dpr)); recCanvas.width = 2 * Math.round((r.w * dpr * k) / 2); recCanvas.height = 2 * Math.round((r.h * dpr * k) / 2); drawRecordingFrame(r); const stream = recCanvas.captureStream(REC_FPS); for (const track of synth.stream().getAudioTracks()) stream.addTrack(track); const mime = REC_TYPES.find((t) => MediaRecorder.isTypeSupported(t)) ?? ''; let recorder; try { recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 8e6, audioBitsPerSecond: 192e3 }); } catch (err) { recMessage(`Can't record here: ${err.message}`); return; } const chunks = []; recorder.ondataavailable = (e) => { if (e.data.size) chunks.push(e.data); }; recorder.onstop = () => { const rec = recording; recording = null; for (const track of stream.getVideoTracks()) track.stop(); const type = rec.recorder.mimeType || rec.mime || 'video/webm'; recorded = { blob: new Blob(rec.chunks, { type }), mime: type, seconds: (performance.now() - rec.started) / 1000, saved: false }; renderRecording(); }; recorder.onerror = (e) => recMessage(`Recording failed: ${e.error?.message ?? 'unknown error'}`); // (in slices, so a long recording is collected as it goes) recorder.start(1000); recording = { recorder, chunks, mime, started: performance.now() }; renderRecording(); } function stopRecording() { if (recording?.recorder.state !== 'inactive') recording?.recorder.stop(); } function discardRecording() { recorded = null; renderRecording(); } function saveRecording() { if (!recorded) return; const d = new Date(); const pad = (n) => String(n).padStart(2, '0'); const ext = recorded.mime.includes('mp4') ? 'mp4' : 'webm'; downloadBlob(recorded.blob, `duffing-islands-${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.${ext}`); recorded.saved = true; } const recMessage = (text) => { $('rec-status').textContent = text; $('rec-status').hidden = !text; }; function renderRecording() { const btn = $('record'); const on = !!recording; btn.setAttribute('aria-pressed', on); btn.querySelector('.rec-label').textContent = on ? 'Stop' : 'Record'; btn.title = on ? 'Stop recording' : 'Record a video of the phase space with the sound (the sound goes on)'; $('rec-download').hidden = !recorded; $('rec-discard').hidden = !recorded; if (recorded) { $('rec-download').textContent = `Download video (${fmtTime(recorded.seconds)}, ${fmtSize(recorded.blob.size)})`; } updateRecordingTime(); } function updateRecordingTime() { if (!recording) { recMessage(''); return; } const bytes = recording.chunks.reduce((n, c) => n + c.size, 0); recMessage(`${fmtTime((performance.now() - recording.started) / 1000)} · ${fmtSize(bytes)}`); } function buildRecordingControls() { const btn = $('record'); if (!canRecord()) { btn.disabled = true; btn.title = 'Recording isn\'t supported in this browser'; return; } btn.addEventListener('click', () => (recording ? stopRecording() : startRecording())); $('rec-download').addEventListener('click', saveRecording); $('rec-discard').addEventListener('click', () => { if (recorded && !recorded.saved && !confirm('Discard the recording without downloading it?')) return; discardRecording(); }); setInterval(() => { if (recording) updateRecordingTime(); }, 500); // a recording in progress, or not yet downloaded: ask before leaving addEventListener('beforeunload', (e) => { if (recording || (recorded && !recorded.saved)) e.preventDefault(); }); renderRecording(); } readTheme(); matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { readTheme(); resize(); }); buildEquationControls(); buildMasterControls(); buildTrackControls(); buildPlotControls(); buildSoundFontControls(); buildSessionControls(); buildRecordingControls(); buildKnobControls(); reset(); new ResizeObserver(resize).observe(canvas); resize(); requestAnimationFrame(frame); // the SoundFont and the state saved in this browser (or the defaults: one // track, waiting for its start) loadSaved() .then((recs) => { for (const rec of Array.isArray(recs) ? recs : []) addSoundFont(rec.fileName, rec.bytes, { save: false }); }) .finally(() => { applyState(loadLocal() ?? {}); restored = true; });