@zeeuw/riff 0.0.0-stage → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/data/registry-data.js +3 -0
  4. package/data/signatures.js +3 -0
  5. package/docs/clean-room.md +450 -0
  6. package/package.json +69 -4
  7. package/src/audio/clock.js +383 -0
  8. package/src/audio/engine.js +678 -0
  9. package/src/audio/index.js +394 -0
  10. package/src/audio/offline.js +73 -0
  11. package/src/audio/params.js +397 -0
  12. package/src/audio/samples.js +274 -0
  13. package/src/audio/unlock.js +70 -0
  14. package/src/audio/voices.js +44 -0
  15. package/src/combinators.js +150 -0
  16. package/src/compat.js +16 -0
  17. package/src/constructors.js +236 -0
  18. package/src/controls.js +199 -0
  19. package/src/draw.js +252 -0
  20. package/src/euclid.js +57 -0
  21. package/src/evaluate.js +251 -0
  22. package/src/extras/check.js +678 -0
  23. package/src/extras/describe.js +433 -0
  24. package/src/extras/editor.js +369 -0
  25. package/src/extras/index.js +10 -0
  26. package/src/fraction.js +300 -0
  27. package/src/hap.js +64 -0
  28. package/src/helpers.js +68 -0
  29. package/src/index.js +74 -0
  30. package/src/mini/index.js +36 -0
  31. package/src/mini/parser.js +400 -0
  32. package/src/ops.js +293 -0
  33. package/src/outline.js +175 -0
  34. package/src/pattern.js +365 -0
  35. package/src/random.js +344 -0
  36. package/src/register.js +83 -0
  37. package/src/registry.js +52 -0
  38. package/src/samples.js +14 -0
  39. package/src/sampling.js +123 -0
  40. package/src/scope.js +77 -0
  41. package/src/signals.js +76 -0
  42. package/src/stepwise.js +150 -0
  43. package/src/structure.js +636 -0
  44. package/src/time.js +70 -0
  45. package/src/tonal.js +583 -0
  46. package/src/transforms.js +125 -0
  47. package/src/transpile.js +394 -0
  48. package/src/util.js +80 -0
  49. package/src/visuals.js +216 -0
@@ -0,0 +1,199 @@
1
+ // Controls (plan 2.5, spec/functions/controls-tier1.md): every control name of
2
+ // spec/inventory.csv, as a free function (`s("bd")`) and a Pattern method
3
+ // (`.gain(0.5)`). A control writes one key of the hap value; colon arrays are
4
+ // spread over several keys for the controls the spec lists.
5
+ import { Pattern, reify, assignMap } from './pattern.js';
6
+ import { register } from './register.js';
7
+ import { isRecord } from './util.js';
8
+ import { asMap, isPatLike as isPat, isValueMap } from './util.js';
9
+
10
+ // One entry per value key: 'key|alias|alias'. Every name writes `key`. The
11
+ // key is the longest name of the group (matches every Tier 1 key the spec
12
+ // gives), except `s` (spec: `sound` writes `s`) and `vib` (spec/sound.md 16:
13
+ // `vibrato` writes `vib`). docs/decisions.md.
14
+ const GROUPS = `
15
+ accelerate activeLabel amp analyze anchor attack|att bandf|bp|bpf bandq|bpq
16
+ bank byteBeatExpression|bbexpr byteBeatStartTime|bbst begin binshift
17
+ bpattack|bpa bpdecay|bpd bpenv|bpe bprelease|bpr bpsustain|bps ccn ccv
18
+ channels|ch channel chord chorus legato|clip coarse color comb compressor
19
+ compressorAttack compressorKnee compressorRatio compressorRelease cps crush
20
+ cutoff|ctf|lp|lpf ctlNum ctranspose curve cut decay|dec degree delay
21
+ delayfeedback|delayfb|dfb delayspeed delaysync delaytime|delayt|dt deltaSlide
22
+ detune|det dictionary|dict distort|dist distorttype|disttype distortvol|distvol djf drive dry
23
+ duck duckattack|duckatt duckdepth duckonset|duckons duration|dur end enhance expression
24
+ fadeInTime fadeOutTime|fadeTime fanchor fft fmi|fm fmattack fmdecay fmenv fmh
25
+ fmrelease fmsustain fmvelocity fmwave frameRate frames freeze freq fshift
26
+ fshiftnote fshiftphase ftype gain gate|gat harmonic hbrick hcutoff|hp|hpf hold
27
+ hours hpattack|hpa hpdecay|hpd hpenv|hpe hresonance|hpq hprelease|hpr
28
+ hpsustain|hps imag iresponse|ir irbegin irspeed kcutoff krush label lbrick
29
+ leslie repeatTime|lfo lock loop loopBegin|loopb loopEnd|loope lpattack|lpa
30
+ lpdecay|lpd lpenv|lpe resonance|lpq lprelease|lpr lpsustain|lps lrate lsize
31
+ midibend midichan midicmd midimap midiport miditouch minutes mode mtranspose n
32
+ noise note nrpnn nrpv nudge octave octaveR octaves octer octersub octersubsub
33
+ offset orbit oschost oscport overgain overshape pan panchor panorient panspan
34
+ pansplay panwidth partials pattack|patt pcurve pdecay|pdec penv
35
+ phaserrate|ph|phaser phaserdepth|phasdp|phd phasercenter|phc phasersweep|phs
36
+ pitchJump pitchJumpTime polyTouch postgain prelease|prel progNum psustain|psus
37
+ pw pwrate pwsweep rate roomdim|rdim real release|rel roomfade|rfade ring
38
+ ringdf ringf roomlp|rlp room roomsize|rsize|size|sz s|sound scram seconds
39
+ semitone shape slide smear songPtr source|src speed spread squiz
40
+ stepsPerOctave stretch sustain|sus sustainpedal sysexdata sysexid tremolo|trem
41
+ tremolodepth|tremdepth tremolophase|tremphase tremoloshape|tremshape tremoloskew|tremskew tremolosync triode tsdelay
42
+ uid unison unit vib|v|vibrato val velocity vibmod|vmod voice vowel
43
+ wavetableWarp|warp warpattack|warpatt warpdc warpdecay|warpdec warpdepth
44
+ warpenv wavetableWarpMode|warpmode warprate warprelease|warprel warpshape
45
+ warpskew warpsustain|warpsus warpsync waveloss wavetablePhaseRand|wtphaserand
46
+ wavetablePosition|wt wtattack|wtatt wtdc wtdecay|wtdec wtdepth wtenv wtrate
47
+ wtrelease|wtrel wtshape wtskew wtsustain|wtsus wtsync xsdelay zcrush zdelay
48
+ zmod znoise zrand zzfx
49
+ `.trim().split(/\s+/);
50
+
51
+ // Colon arrays (`"400:8"` -> [400, 8]) spread into these keys, in order; extra
52
+ // elements are dropped. Any other control stores the array as it is.
53
+ // `room` writes `size` (not `roomsize`): fixture functions/controls-colon.
54
+ const SPLITS = {
55
+ s: ['s', 'n', 'gain'],
56
+ note: ['note', 'n'],
57
+ cutoff: ['cutoff', 'resonance'],
58
+ hcutoff: ['hcutoff', 'hresonance'],
59
+ room: ['room', 'size'],
60
+ delay: ['delay', 'delaytime', 'delayfeedback'],
61
+ distort: ['distort', 'distortvol'],
62
+ shape: ['shape', 'shapevol'],
63
+ fmi: ['fmi', 'fmh'],
64
+ fmh: ['fmh', 'fmi'],
65
+ mode: ['mode', 'anchor'],
66
+ // spec/sound.md 16-17: "rate:depth".
67
+ vib: ['vib', 'vibmod'],
68
+ tremolo: ['tremolo', 'tremolodepth'],
69
+ };
70
+
71
+
72
+ // The value map one control writes for the value v.
73
+ export function controlValue(key, v) {
74
+ const split = SPLITS[key];
75
+ if (!split || !Array.isArray(v)) { const o = {}; o[key] = v; return o; } // not `{ [key]: v }`: 4x slower
76
+ const out = {};
77
+ for (let i = 0; i < split.length && i < v.length; i++) out[split[i]] = v[i];
78
+ return out;
79
+ }
80
+
81
+ // name -> value key, and name -> free function.
82
+ export const controlKeys = new Map();
83
+ export const controlFunctions = {};
84
+
85
+ function defineControl(key, aliases) {
86
+ const merge = SPLITS[key]
87
+ ? (v, x) => ({ ...(isRecord(v) ? v : {}), ...controlValue(key, x) })
88
+ : (v, x) => { const o = isRecord(v) ? { ...v } : {}; o[key] = x; return o; };
89
+ // No argument: wrap the current value (`"c e".note()`, even a map).
90
+ // With one: merge into each value of `pat` (a non-map value is replaced).
91
+ // A patterned argument keeps `pat`'s wholes, cuts parts where it changes and
92
+ // is sampled over each whole, so a signal gives its value at whole.begin.
93
+ const impl = (pat, ...args) => {
94
+ if (args.length === 0) return pat.fmap((v) => controlValue(key, v));
95
+ const x = args[0];
96
+ if (x instanceof Pattern || typeof x === 'string') return pat.fmap((v) => (y) => merge(v, y)).appLeft(reify(x));
97
+ return pat.fmap(assignMap(Object.entries(controlValue(key, x)))); // = merge(v, x), fusable
98
+ };
99
+ const fn = register(key, impl, { patternArgs: 0, aliases });
100
+ for (const n of [key, ...aliases]) { controlKeys.set(n, key); controlFunctions[n] = fn; }
101
+ }
102
+
103
+ for (const g of GROUPS) {
104
+ const [key, ...aliases] = g.split('|');
105
+ defineControl(key, aliases);
106
+ }
107
+
108
+ export const {
109
+ accelerate, activeLabel, amp, analyze, anchor, attack, att, bandf, bp, bpf,
110
+ bandq, bpq, bank, byteBeatExpression, bbexpr, byteBeatStartTime, bbst, begin,
111
+ binshift, bpattack, bpa, bpdecay, bpd, bpenv, bpe, bprelease, bpr, bpsustain,
112
+ bps, ccn, ccv, channels, ch, channel, chord, chorus, legato, clip, coarse,
113
+ color, comb, compressor, compressorAttack, compressorKnee, compressorRatio,
114
+ compressorRelease, cps, crush, cutoff, ctf, lp, lpf, ctlNum, ctranspose,
115
+ curve, cut, decay, dec, degree, delay, delayfeedback, delayfb, dfb,
116
+ delayspeed, delaysync, delaytime, delayt, dt, deltaSlide, detune, det,
117
+ dictionary, dict, distort, dist, distorttype, disttype, distortvol, distvol, djf, drive, dry,
118
+ duck, duckattack, duckatt, duckdepth, duckonset, duckons, duration, dur, end, enhance,
119
+ expression, fadeInTime, fadeOutTime, fadeTime, fanchor, fft, fmi, fm,
120
+ fmattack, fmdecay, fmenv, fmh, fmrelease, fmsustain, fmvelocity, fmwave,
121
+ frameRate, frames, freeze, freq, fshift, fshiftnote, fshiftphase, ftype,
122
+ gain, gate, gat, harmonic, hbrick, hcutoff, hp, hpf, hold, hours, hpattack,
123
+ hpa, hpdecay, hpd, hpenv, hpe, hresonance, hpq, hprelease, hpr, hpsustain,
124
+ hps, imag, iresponse, ir, irbegin, irspeed, kcutoff, krush, label, lbrick,
125
+ leslie, repeatTime, lfo, lock, loop, loopBegin, loopb, loopEnd, loope,
126
+ lpattack, lpa, lpdecay, lpd, lpenv, lpe, resonance, lpq, lprelease, lpr,
127
+ lpsustain, lps, lrate, lsize, midibend, midichan, midicmd, midimap, midiport,
128
+ miditouch, minutes, mode, mtranspose, n, noise, note, nrpnn, nrpv, nudge,
129
+ octave, octaveR, octaves, octer, octersub, octersubsub, offset, orbit,
130
+ oschost, oscport, overgain, overshape, pan, panchor, panorient, panspan,
131
+ pansplay, panwidth, partials, pattack, patt, pcurve, pdecay, pdec, penv,
132
+ phaserrate, ph, phaser, phaserdepth, phasdp, phd, phasercenter, phc,
133
+ phasersweep, phs, pitchJump, pitchJumpTime, polyTouch, postgain, prelease,
134
+ prel, progNum, psustain, psus, pw, pwrate, pwsweep, rate, roomdim, rdim,
135
+ real, release, rel, roomfade, rfade, ring, ringdf, ringf, roomlp, rlp, room,
136
+ roomsize, rsize, size, sz, s, sound, scram, seconds, semitone, shape, slide,
137
+ smear, songPtr, source, src, speed, spread, squiz, stepsPerOctave, stretch,
138
+ sustain, sus, sustainpedal, sysexdata, sysexid, tremolo, trem, tremolodepth, tremdepth,
139
+ tremolophase, tremphase, tremoloshape, tremshape, tremoloskew, tremskew, tremolosync, triode, tsdelay, uid,
140
+ unison, unit, vibrato, v, vib, val, velocity, vibmod, vmod, voice, vowel,
141
+ wavetableWarp, warp, warpattack, warpatt, warpdc, warpdecay, warpdec,
142
+ warpdepth, warpenv, wavetableWarpMode, warpmode, warprate, warprelease,
143
+ warprel, warpshape, warpskew, warpsustain, warpsus, warpsync, waveloss,
144
+ wavetablePhaseRand, wtphaserand, wavetablePosition, wt, wtattack, wtatt,
145
+ wtdc, wtdecay, wtdec, wtdepth, wtenv, wtrate, wtrelease, wtrel, wtshape,
146
+ wtskew, wtsustain, wtsus, wtsync, xsdelay, zcrush, zdelay, zmod, znoise,
147
+ zrand, zzfx,
148
+ } = controlFunctions;
149
+
150
+ // --- moved here from the Tier 2/3 batch modules (audit 6) ---------------------
151
+
152
+ // --- sound helpers (spec/functions/sound-helpers.md) ---------------------------
153
+
154
+ const ADSR = ['attack', 'decay', 'sustain', 'release'];
155
+ export const adsr = register('adsr', (pat, x) => {
156
+ const xs = Array.isArray(x) ? x : [x];
157
+ return pat.fmap(assignMap(ADSR.map((k, i) => [k, xs[i] ?? null])));
158
+ });
159
+
160
+ // Method-only controls: duckorbit, tremsync (key tremolosync), density (a
161
+ // control, not fast).
162
+ const methodControl = (name, key) => register(name, (pat, x) => (x instanceof Pattern || typeof x === 'string'
163
+ ? pat.fmap((v) => (y) => { const o = asMap(v); o[key] = y; return o; }).appLeft(reify(x))
164
+ : pat.fmap(assignMap([[key, x]]))), { patternArgs: 0, free: false });
165
+ methodControl('duckorbit', 'duckorbit');
166
+ methodControl('tremsync', 'tremolosync');
167
+ methodControl('density', 'density');
168
+
169
+ // --- ad / ar / ds (spec/functions/envelope-shortcuts.md) ------------------------
170
+ const pair = (v) => (Array.isArray(v) ? v : null);
171
+ function envelope(name, keys, single) {
172
+ const make = (x) => {
173
+ const p = pair(x);
174
+ const o = {};
175
+ if (p) { o[keys[0]] = p[0]; if (p.length > 1) o[keys[1]] = p[1]; } else { o[keys[0]] = x; o[keys[1]] = single(x); }
176
+ return o;
177
+ };
178
+ const merge = (v, x) => ({ ...(isValueMap(v) ? v : {}), ...make(x) });
179
+ return register(name, (pat, x) => {
180
+ if (x instanceof Pattern || typeof x === 'string') return pat.fmap((v) => (y) => merge(v, y)).appLeft(reify(x));
181
+ return pat.fmap((v) => merge(v, x));
182
+ }, { patternArgs: 0 });
183
+ }
184
+ export const ad = envelope('ad', ['attack', 'decay'], (v) => v);
185
+ export const ar = envelope('ar', ['attack', 'release'], (v) => v);
186
+ export const ds = envelope('ds', ['decay', 'sustain'], () => 0);
187
+
188
+ // --- distortion shortcuts (spec/functions/distortion-shortcuts.md) ----------------
189
+ // Method only; writes distort, distorttype and distortvol (1 unless "x:v").
190
+ const DIST_SHAPES = ['soft', 'hard', 'cubic', 'diode', 'asym', 'fold', 'sinefold', 'chebyshev', 'scurve'];
191
+ for (const shape of DIST_SHAPES) {
192
+ const merge = (v, x) => {
193
+ const pair = Array.isArray(x);
194
+ return { ...(isValueMap(v) ? v : {}), distort: pair ? x[0] : x, distorttype: shape, distortvol: pair && x.length > 1 ? x[1] : 1 };
195
+ };
196
+ register(shape, (pat, x) => (isPat(x)
197
+ ? pat.fmap((v) => (y) => merge(v, y)).appLeft(reify(x))
198
+ : pat.fmap((v) => merge(v, x))), { patternArgs: 0, free: false });
199
+ }
package/src/draw.js ADDED
@@ -0,0 +1,252 @@
1
+ // Draw layer (plan 5.1; spec/integration.md 6, 7, 11): pattern draw methods,
2
+ // the RIFF-owned animation loop, the draw-time hap query and canvases.
3
+ //
4
+ // How it fits together: a draw method in user code (`.pianoroll()`,
5
+ // `._scope(id)`, `.onDraw(fn)`) registers a *painter* for the pattern it was
6
+ // called on. The painters of one evaluation become active when that pattern
7
+ // starts playing (`commitPainters`, called by the audio layer), and one Framer
8
+ // then paints them every animation frame, reading the time from the
9
+ // scheduler. `cleanupDraw` stops that loop; SAAI's own canvases and Framers
10
+ // are never touched. The renderers live in src/visuals.js.
11
+ import { Pattern } from './pattern.js';
12
+ import { RENDERERS } from './visuals.js';
13
+
14
+ export const DRAW_METHODS = ['pianoroll', 'punchcard', 'scope', 'tscope', 'spectrum', 'spiral'];
15
+ export const DEFAULT_CANVAS_ID = 'test-canvas';
16
+ export const SPECTRUM_CANVAS_ID = 'riff-spectrum';
17
+
18
+ let handler = null;
19
+ // handler(name, pattern, args) is called on every draw-method call (extra hook
20
+ // for hosts; the built-in painters do not need it).
21
+ export function setDrawHandler(fn) { handler = fn ?? null; }
22
+
23
+ // --- Framer -----------------------------------------------------------------
24
+
25
+ const raf = (fn) => (typeof globalThis.requestAnimationFrame === 'function'
26
+ ? globalThis.requestAnimationFrame(fn) : setTimeout(() => fn(Date.now()), 16));
27
+ const caf = (id) => (typeof globalThis.cancelAnimationFrame === 'function'
28
+ ? globalThis.cancelAnimationFrame(id) : clearTimeout(id));
29
+
30
+ // new Framer(onFrame, onError): start() calls onFrame(timestamp) once per
31
+ // animation frame until stop(). A throwing onFrame goes to onError (or
32
+ // console.warn) and the loop keeps running. stop() is idempotent.
33
+ export class Framer {
34
+ constructor(onFrame, onError) {
35
+ this.onFrame = onFrame;
36
+ this.onError = onError;
37
+ this.id = null;
38
+ this.running = false;
39
+ }
40
+
41
+ start() {
42
+ if (this.running) return this;
43
+ this.running = true;
44
+ const loop = (ts) => {
45
+ if (!this.running) return;
46
+ try { this.onFrame?.(ts); } catch (err) {
47
+ try { (this.onError ?? ((e) => console.warn('[riff] draw error:', e)))(err); } catch { /* ignore */ }
48
+ }
49
+ if (this.running) this.id = raf(loop);
50
+ };
51
+ this.id = raf(loop);
52
+ return this;
53
+ }
54
+
55
+ stop() {
56
+ this.running = false;
57
+ if (this.id !== null) caf(this.id);
58
+ this.id = null;
59
+ return this;
60
+ }
61
+ }
62
+
63
+ // --- draw-time hap query ------------------------------------------------------
64
+
65
+ const num = (x) => Number(x);
66
+
67
+ // queryDrawHaps(pattern, now, { lookbehind, lookahead, overscan }) → the
68
+ // sounding events whose whole overlaps [now − lookbehind, now + lookahead].
69
+ // Only haps with an onset are returned, each drawn from its onset: a note that
70
+ // began before the window is found by querying `overscan` cycles further back
71
+ // (default 1), and fragments without an onset (tails) are never returned
72
+ // (docs/improvements.md 27). Each result is the Hap plus plain numbers
73
+ // { begin, end, active } with active = begin ≤ now < end.
74
+ export function queryDrawHaps(pattern, now, { lookbehind = 0, lookahead = 0, overscan = 1 } = {}) {
75
+ if (!pattern?.queryArc) return [];
76
+ const from = now - lookbehind;
77
+ const to = now + lookahead;
78
+ if (!(to > from - overscan)) return [];
79
+ const out = [];
80
+ for (const hap of pattern.queryArc(from - overscan, to)) {
81
+ if (!hap.hasOnset()) continue;
82
+ const begin = num(hap.whole.begin);
83
+ const end = num(hap.whole.end);
84
+ if (end <= from && !(begin === end && begin >= from)) continue;
85
+ if (begin > to) continue;
86
+ out.push({ hap, value: hap.value, begin, end, active: begin <= now && now < end });
87
+ }
88
+ return out;
89
+ }
90
+
91
+ // --- canvases -----------------------------------------------------------------
92
+
93
+ const dpr = () => globalThis.devicePixelRatio || 1;
94
+
95
+ // Size a canvas to its CSS box times devicePixelRatio (no-op when unchanged).
96
+ export function fitCanvas(canvas, width, height) {
97
+ const r = dpr();
98
+ const w = Math.max(1, Math.round((width ?? canvas.clientWidth ?? canvas.width / r) * r));
99
+ const h = Math.max(1, Math.round((height ?? canvas.clientHeight ?? canvas.height / r) * r));
100
+ if (canvas.width !== w) canvas.width = w;
101
+ if (canvas.height !== h) canvas.height = h;
102
+ return canvas;
103
+ }
104
+
105
+ // getDrawContext(id = 'test-canvas', { contain }) → the 2D context of the
106
+ // full-page canvas `id`, made on first use: fixed, behind the page content
107
+ // (z-index −1; `contain: true` makes it absolute inside its parent instead),
108
+ // pointer events off, sized in device pixels and kept so on resize. Returns
109
+ // null without a DOM.
110
+ export function getDrawContext(id = DEFAULT_CANVAS_ID, options = {}) {
111
+ const doc = globalThis.document;
112
+ if (!doc?.createElement) return null;
113
+ let canvas = doc.getElementById?.(id);
114
+ if (!canvas) {
115
+ canvas = doc.createElement('canvas');
116
+ canvas.id = id;
117
+ const pos = options.contain ? 'absolute' : 'fixed';
118
+ canvas.style.cssText = `position:${pos};top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:${options.zIndex ?? -1}`;
119
+ (doc.body ?? doc.documentElement).appendChild(canvas);
120
+ const size = () => fitCanvas(canvas, globalThis.innerWidth, globalThis.innerHeight);
121
+ if (!options.contain) {
122
+ size();
123
+ globalThis.addEventListener?.('resize', size);
124
+ } else fitCanvas(canvas);
125
+ }
126
+ return canvas.getContext('2d');
127
+ }
128
+
129
+ // The canvas of an inline widget (`._pianoroll(id)`): the element with that id,
130
+ // made by the editor's widget plugin (plan 5.3). Null until it is mounted.
131
+ export function getWidgetContext(id) {
132
+ const el = globalThis.document?.getElementById?.(id);
133
+ if (!el?.getContext) return null;
134
+ fitCanvas(el);
135
+ return el.getContext('2d');
136
+ }
137
+
138
+ // --- painters and the RIFF-owned loop -----------------------------------------
139
+
140
+ // Time source and analysers, installed by the audio layer (src/audio/index.js).
141
+ const env = { now: () => 0, pattern: () => null, analyser: () => null };
142
+ export function setDrawEnvironment({ now, pattern, analyser } = {}) {
143
+ if (now) env.now = now;
144
+ if (pattern) env.pattern = pattern;
145
+ if (analyser) env.analyser = analyser;
146
+ }
147
+
148
+ let pending = []; // registered by the evaluation in progress
149
+ let painters = []; // active, painted every frame
150
+ let framer = null;
151
+
152
+ // Forget painters of an evaluation that did not finish (called before each).
153
+ export function resetPainters() { pending = []; }
154
+
155
+ function register(painter) { pending.push(painter); }
156
+
157
+ // Painters of the pattern that just started playing become the active set.
158
+ // Canvases of painters that went away are cleared once.
159
+ export function commitPainters() {
160
+ const next = pending;
161
+ pending = [];
162
+ const keep = new Set(next.map((p) => p.target));
163
+ for (const p of painters) if (!keep.has(p.target)) clearContext(contextOf(p));
164
+ painters = next;
165
+ if (painters.length === 0) { framer?.stop(); return; }
166
+ framer ??= new Framer(paintFrame, (e) => console.warn('[riff] draw error:', e?.message ?? e));
167
+ framer.start();
168
+ }
169
+
170
+ export const getPainters = () => painters.slice();
171
+
172
+ function contextOf(p) {
173
+ return p.inline ? getWidgetContext(p.target) : getDrawContext(p.target);
174
+ }
175
+
176
+ function clearContext(ctx) {
177
+ if (!ctx?.canvas) return;
178
+ ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
179
+ }
180
+
181
+ // One frame: clear each canvas once (not when a painter on it keeps its
182
+ // trail: spectrum, smear), then paint every painter in registration order.
183
+ export function paintFrame() {
184
+ const now = env.now();
185
+ const groups = new Map();
186
+ for (const p of painters) {
187
+ const ctx = contextOf(p);
188
+ if (!ctx && p.needsCanvas !== false) continue;
189
+ if (!groups.has(ctx)) groups.set(ctx, []);
190
+ groups.get(ctx).push(p);
191
+ }
192
+ for (const [ctx, list] of groups) {
193
+ if (ctx && !list.some((p) => p.keepsTrail)) clearContext(ctx);
194
+ for (const p of list) p.paint(ctx, now, env);
195
+ }
196
+ }
197
+
198
+ // cleanupDraw(clear = true): stop RIFF's draw loop and forget its painters;
199
+ // with `clear`, also clear the canvases they drew on.
200
+ export function cleanupDraw(clear = true) {
201
+ framer?.stop();
202
+ if (clear) for (const p of painters) clearContext(contextOf(p));
203
+ painters = [];
204
+ pending = [];
205
+ }
206
+
207
+ function makePainter(name, pattern, args) {
208
+ const inline = name.startsWith('_');
209
+ const kind = inline ? name.slice(1) : name;
210
+ let id;
211
+ let opts;
212
+ if (inline && typeof args[0] === 'string') { id = args[0]; opts = args[1]; } else { opts = args[0]; }
213
+ opts = opts && typeof opts === 'object' ? opts : {};
214
+ // A background spectrum keeps its trail, so it gets its own canvas.
215
+ const target = inline ? (id ?? `_widget_${kind}`)
216
+ : (opts.id ?? (kind === 'spectrum' ? SPECTRUM_CANVAS_ID : DEFAULT_CANVAS_ID));
217
+ const render = RENDERERS[kind];
218
+ return {
219
+ kind, inline, target, options: opts, pattern,
220
+ keepsTrail: kind === 'spectrum' || Boolean(opts.smear),
221
+ paint: (ctx, now, e) => render?.(ctx, { pattern, now, options: opts, env: e, query: queryDrawHaps }),
222
+ };
223
+ }
224
+
225
+ for (const name of [...DRAW_METHODS, ...DRAW_METHODS.map((n) => `_${n}`)]) {
226
+ const kind = name.replace(/^_/, '');
227
+ Object.defineProperty(Pattern.prototype, name, {
228
+ value: function (...args) {
229
+ handler?.(name, this, args);
230
+ // The pattern stays unchanged (the oracle's haps are the same).
231
+ if (RENDERERS[kind]) register(makePainter(name, this, args));
232
+ return this;
233
+ },
234
+ writable: true, configurable: true,
235
+ });
236
+ }
237
+
238
+ // pattern.onDraw(fn, { lookbehind, lookahead, id }): call fn(haps, now, ctx)
239
+ // every frame with queryDrawHaps' result; ctx is the canvas `id`'s 2D context
240
+ // (the full-page canvas by default; null without a DOM). Returns the pattern.
241
+ Object.defineProperty(Pattern.prototype, 'onDraw', {
242
+ value: function onDraw(fn, options = {}) {
243
+ const { lookbehind = 0, lookahead = 0, id = DEFAULT_CANVAS_ID } = options;
244
+ const pattern = this;
245
+ register({
246
+ kind: 'onDraw', inline: false, target: id, options, pattern, keepsTrail: false, needsCanvas: false,
247
+ paint: (ctx, now) => fn(queryDrawHaps(pattern, now, { lookbehind, lookahead }), now, ctx),
248
+ });
249
+ return this;
250
+ },
251
+ writable: true, configurable: true,
252
+ });
package/src/euclid.js ADDED
@@ -0,0 +1,57 @@
1
+ // Euclidean rhythms (spec/mini.md 3.6): euclid, euclidRot, euclidLegato,
2
+ // euclidLegatoRot. All arguments are patternable.
3
+ import { pure, silence } from './pattern.js';
4
+ import { register } from './register.js';
5
+ import { fastcat, timecat } from './constructors.js';
6
+
7
+ // k hits over n steps, as an array of booleans, by the grouping procedure of
8
+ // spec/mini.md 3.6. k < 0 gives the complement; k > n throws.
9
+ export function bjorklund(k, n) {
10
+ k = Math.trunc(Number(k));
11
+ n = Math.trunc(Number(n));
12
+ if (k < 0) return bjorklund(-k, n).map((b) => !b);
13
+ if (k > n || n < 0) throw new RangeError('Invalid array length');
14
+ let front = Array.from({ length: k }, () => [true]);
15
+ let rest = Array.from({ length: n - k }, () => [false]);
16
+ while (rest.length > 1 && front.length > 0) {
17
+ const m = Math.min(front.length, rest.length);
18
+ const joined = [];
19
+ for (let i = 0; i < m; i++) joined.push([...front[i], ...rest[i]]);
20
+ const left = front.length > m ? front.slice(m) : rest.slice(m);
21
+ front = joined;
22
+ rest = left;
23
+ }
24
+ return [...front, ...rest].flat();
25
+ }
26
+
27
+ // Rotation: hit i of the result is hit i - r of the base; |r| >= n: none.
28
+ export function euclidBools(k, n, r = 0) {
29
+ const base = bjorklund(k, n);
30
+ r = Math.trunc(Number(r));
31
+ const len = base.length;
32
+ if (len === 0 || r === 0 || Math.abs(r) >= len) return base;
33
+ return base.map((_, i) => base[(((i - r) % len) + len) % len]);
34
+ }
35
+
36
+ const boolSeq = (bools) => (bools.some(Boolean) ? fastcat(...bools.map((b) => pure(b))) : silence);
37
+
38
+ // Each hit lasts until the next hit or the end of the cycle; steps before the
39
+ // first hit are silent.
40
+ function legatoStruct(bools) {
41
+ const hits = [];
42
+ bools.forEach((b, i) => { if (b) hits.push(i); });
43
+ if (hits.length === 0) return silence;
44
+ const parts = [];
45
+ if (hits[0] > 0) parts.push([hits[0], silence]);
46
+ hits.forEach((h, j) => parts.push([(hits[j + 1] ?? bools.length) - h, pure(true)]));
47
+ return timecat(...parts);
48
+ }
49
+
50
+ const structBy = (pat, s) => s.filterValues(Boolean).fmap(() => (v) => v).appLeft(pat);
51
+
52
+ export const euclid = register('euclid', (pat, k, n) => structBy(pat, boolSeq(euclidBools(k, n))));
53
+ export const euclidRot = register('euclidRot', (pat, k, n, r) => structBy(pat, boolSeq(euclidBools(k, n, r))), { aliases: ['euclidrot'] });
54
+ export const euclidrot = euclidRot;
55
+ export const euclidLegato = register('euclidLegato', (pat, k, n) => structBy(pat, legatoStruct(euclidBools(k, n))));
56
+ export const euclidLegatoRot = register('euclidLegatoRot', (pat, k, n, r) => structBy(pat, legatoStruct(euclidBools(k, n, r))));
57
+