@vibechain/os 0.5.1 → 0.5.2

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 (43) hide show
  1. package/AGENTS.md +15 -6
  2. package/README.md +35 -10
  3. package/SECURITY.md +3 -1
  4. package/dist/app-client.js +20 -4
  5. package/dist/app-host.d.ts +12 -2
  6. package/dist/app-host.js +12 -2
  7. package/dist/app-protocol.d.ts +21 -0
  8. package/dist/app-protocol.js +9 -0
  9. package/dist/audio.d.ts +65 -0
  10. package/dist/audio.js +162 -0
  11. package/dist/browser.d.ts +1 -0
  12. package/dist/browser.js +1 -0
  13. package/dist/bundle.d.ts +2 -0
  14. package/dist/bundle.js +2 -0
  15. package/dist/cli.js +3 -1
  16. package/dist/commands.d.ts +6 -0
  17. package/dist/commands.js +17 -0
  18. package/dist/index.d.ts +2 -2
  19. package/dist/links.d.ts +6 -0
  20. package/dist/links.js +2 -0
  21. package/dist/os.d.ts +20 -2
  22. package/dist/os.js +30 -5
  23. package/dist/preview-parent.js +15 -2
  24. package/dist/preview-ui.js +1 -1
  25. package/dist/preview.js +1 -1
  26. package/dist/templates/plain/game.js +3 -1
  27. package/dist/testing.d.ts +9 -1
  28. package/dist/testing.js +27 -6
  29. package/dist/vibemarket-os.js +1 -1
  30. package/examples/paw-beat/README.md +28 -9
  31. package/examples/paw-beat/game.ts +280 -123
  32. package/examples/paw-beat/index.html +18 -4
  33. package/examples/paw-beat/main.ts +101 -44
  34. package/examples/paw-beat/music.ts +72 -337
  35. package/examples/paw-beat/stage.ts +23 -9
  36. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  37. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  38. package/examples/paw-beat/synth.ts +477 -0
  39. package/examples/paw-beat/tracks.ts +286 -0
  40. package/examples/paw-beat/vibemarket.json +2 -2
  41. package/examples/vibexp-app/plain/game.ts +6 -2
  42. package/package.json +7 -1
  43. package/skill.md +399 -0
@@ -0,0 +1,477 @@
1
+ import { beatSeconds, chordAt, countInBeats, createTune, sectionAt, songBeats, swung, type Chord, type Section, type Track, type TuneNote } from "./game";
2
+
3
+ /**
4
+ * The instruments, and the player that turns a track's data into sound. Nothing is sampled:
5
+ * every drum, bass, lead, pad and arpeggio is an oscillator or noise shaped by filters and
6
+ * envelopes, mixed through a feedback delay and a small generated reverb, ducked under the
7
+ * kick, and kept in range by a soft limiter.
8
+ *
9
+ * It only builds nodes on the context it is given and hands back its output; making, resuming
10
+ * and muting the context is music.ts's job (with the SDK's audio helper). The same code renders
11
+ * offline into an OfflineAudioContext to check levels and timing.
12
+ */
13
+
14
+ export type KitKind = "punchy" | "soft" | "chip" | "tight";
15
+ export type BassKind = "saw" | "pluck" | "reese" | "upright" | "chip";
16
+ export type LeadKind = "sawsquare" | "whistle" | "pulse" | "supersaw" | "flute" | "musicbox";
17
+ export type PadKind = "warm" | "ep" | "nylon" | "chip" | "glass";
18
+ export type ArpKind = "pluck" | "chip" | "glock";
19
+ export type DrumPart = "kick" | "snare" | "clap" | "hat" | "open" | "rim" | "shaker";
20
+
21
+ /**
22
+ * How a track sounds. Patterns are strings of sixteenth notes, one bar or more, spaces ignored:
23
+ * - drums: "x" a hit, "X" an accent, "g" a ghost note, "." nothing;
24
+ * - bass lines: "R" the chord's root, "O" an octave up, "F" its fifth, "T" its third, "S" its
25
+ * seventh, "L" the fifth below; lower case plays softer; "-" holds; "." rests;
26
+ * - comps (the pad): "S" sustains the chord, "x" a short stab, "X" an accented one, "-" holds;
27
+ * - arps: a digit picks a chord tone (0 the root; past the chord's last tone it climbs an
28
+ * octave), "-" holds, "." rests.
29
+ * The pattern named "none" (or a missing one) is silence.
30
+ */
31
+ export interface TrackSound {
32
+ readonly kit: KitKind; readonly bass: BassKind; readonly lead: LeadKind; readonly lead2: LeadKind;
33
+ readonly pad: PadKind; readonly arp: ArpKind;
34
+ readonly drums: Readonly<Record<string, Partial<Readonly<Record<DrumPart, string>>>>>;
35
+ readonly bassLines: Readonly<Record<string, string>>;
36
+ readonly comps: Readonly<Record<string, string>>;
37
+ readonly arps: Readonly<Record<string, string>>;
38
+ /** Echo and room, 0 to 1. */
39
+ readonly delay: number; readonly reverb: number;
40
+ /** How far the music dips under each kick, 0 to 1. */
41
+ readonly duck: number;
42
+ /** Trim in decibels so every track plays at the same loudness. */
43
+ readonly level: number;
44
+ }
45
+ export interface PlayableTrack extends Track {
46
+ readonly sound: TrackSound;
47
+ /** The stage's two colours for this track. */
48
+ readonly colours: readonly [string, string];
49
+ }
50
+
51
+ export interface Synth {
52
+ /** The mixed, limited stereo output. Connect it to a destination. */
53
+ readonly output: AudioNode;
54
+ /** Schedule everything that starts during song beat `index`, whose straight start is context time `at`. */
55
+ beat(index: number, at: number): void;
56
+ /** Audio nodes made so far (for measuring the graph's cost). */
57
+ readonly nodes: number;
58
+ }
59
+
60
+ const midiHz = (midi: number) => 440 * Math.pow(2, (midi - 69) / 12);
61
+ const dbGain = (db: number) => Math.pow(10, db / 20);
62
+ /** A pattern without its spacing. */
63
+ const tidy = (pattern: string | undefined) => (pattern ?? "").replace(/\s+/g, "");
64
+
65
+ export function createSynth(context: BaseAudioContext, track: PlayableTrack, seed: number): Synth {
66
+ const sound = track.sound, beatLength = beatSeconds(track);
67
+ let nodes = 0;
68
+ const made = <T extends AudioNode>(node: T) => { nodes++; return node; };
69
+
70
+ // ---- The mix ----
71
+ // drums and music meet on the bus; the music (and its echo and room) ducks under each kick.
72
+ // A 25 Hz high-pass keeps rumble and any offset out; the limiter is a wave shaper, straight
73
+ // through below 0.6 and bending toward 0.88, so no sample can clip. (A DynamicsCompressorNode
74
+ // would also work but delays everything by its fixed 6 ms look-ahead, behind the judging clock.)
75
+ const bus = made(context.createGain()), rumble = made(context.createBiquadFilter()), limiter = made(context.createWaveShaper());
76
+ bus.gain.value = 0.5 * dbGain(sound.level);
77
+ rumble.type = "highpass";
78
+ rumble.frequency.value = 25;
79
+ const curve = new Float32Array(2049);
80
+ for (let i = 0; i < curve.length; i++) {
81
+ const x = i / 1024 - 1, size = Math.abs(x);
82
+ curve[i] = Math.sign(x) * (size < 0.6 ? size : 0.6 + 0.35 * Math.tanh((size - 0.6) / 0.35));
83
+ }
84
+ limiter.curve = curve;
85
+ bus.connect(rumble).connect(limiter);
86
+ const drums = made(context.createGain()), music = made(context.createGain());
87
+ drums.connect(bus);
88
+ music.connect(bus);
89
+
90
+ // One second of seeded white noise for drums, breath and risers, and a small room made from it.
91
+ const noise = context.createBuffer(1, context.sampleRate, context.sampleRate), white = noise.getChannelData(0);
92
+ let state = 0x9e3779b9;
93
+ const rand = () => { state = (Math.imul(state, 1664525) + 1013904223) >>> 0; return state / 2147483648 - 1; };
94
+ for (let i = 0; i < white.length; i++) white[i] = rand();
95
+ const room = context.createBuffer(2, Math.floor(context.sampleRate * 1.1), context.sampleRate);
96
+ for (let channel = 0; channel < 2; channel++) {
97
+ const data = room.getChannelData(channel);
98
+ let smooth = 0;
99
+ for (let i = 0; i < data.length; i++) {
100
+ const t = i / context.sampleRate;
101
+ smooth += (rand() - smooth) * (0.85 - 0.55 * Math.min(1, t / 1.1)); // darker as it decays
102
+ data[i] = smooth * Math.exp(-t * 4.2) * (t < 0.012 ? t / 0.012 : 1);
103
+ }
104
+ }
105
+ const reverb = made(context.createConvolver()), reverbIn = made(context.createGain());
106
+ reverb.normalize = true;
107
+ reverb.buffer = room;
108
+ reverbIn.gain.value = 0.35 * sound.reverb;
109
+ reverbIn.connect(reverb).connect(music);
110
+ // A tempo-synced echo (a dotted eighth) whose repeats darken, panned a little to one side.
111
+ const echo = made(context.createDelay(2)), echoBack = made(context.createGain()), echoTone = made(context.createBiquadFilter()), echoIn = made(context.createGain()), echoPan = made(context.createStereoPanner());
112
+ echo.delayTime.value = beatLength * 0.75;
113
+ echoBack.gain.value = 0.32;
114
+ echoTone.type = "lowpass";
115
+ echoTone.frequency.value = 2600;
116
+ echoIn.gain.value = 0.3 * sound.delay;
117
+ echoPan.pan.value = -0.3;
118
+ echoIn.connect(echo).connect(echoTone).connect(echoBack).connect(echo);
119
+ echoTone.connect(echoPan).connect(music);
120
+ /** Fixed places in the stereo field: cheaper than a panner per note, and every place sums cleanly to mono. */
121
+ const place = (pan: number, to: AudioNode) => { const panner = made(context.createStereoPanner()); panner.pan.value = pan; panner.connect(to); return panner; };
122
+ const center = music, left = place(-0.28, music), right = place(0.28, music), hats = place(0.22, drums), shakers = place(-0.3, drums), rims = place(0.15, drums);
123
+
124
+ // ---- Building blocks ----
125
+ /** A gain envelope: attack to `peak`, hold, then an exponential fall to silence by `end`. */
126
+ const envelope = (at: number, peak: number, attack: number, holdUntil: number, end: number, to: AudioNode) => {
127
+ const gain = made(context.createGain());
128
+ gain.gain.setValueAtTime(0, at);
129
+ gain.gain.linearRampToValueAtTime(peak, at + attack);
130
+ gain.gain.setValueAtTime(peak, Math.max(at + attack, holdUntil));
131
+ gain.gain.exponentialRampToValueAtTime(0.0001, Math.max(end, at + attack + 0.01));
132
+ gain.connect(to);
133
+ return gain;
134
+ };
135
+ const tone = (type: OscillatorType, frequency: number, at: number, end: number, to: AudioNode, detune = 0) => {
136
+ const voice = made(context.createOscillator());
137
+ voice.type = type;
138
+ voice.frequency.setValueAtTime(frequency, at);
139
+ voice.detune.value = detune;
140
+ voice.connect(to);
141
+ voice.start(at);
142
+ voice.stop(end + 0.03);
143
+ return voice;
144
+ };
145
+ const filter = (type: BiquadFilterType, frequency: number, q: number, to: AudioNode) => {
146
+ const shape = made(context.createBiquadFilter());
147
+ shape.type = type;
148
+ shape.frequency.value = frequency;
149
+ shape.Q.value = q;
150
+ shape.connect(to);
151
+ return shape;
152
+ };
153
+ const hiss = (at: number, length: number, to: AudioNode) => {
154
+ const source = made(context.createBufferSource());
155
+ source.buffer = noise;
156
+ source.loop = true;
157
+ source.connect(to);
158
+ source.start(at, (at * 7.31) % 0.9);
159
+ source.stop(at + length + 0.03);
160
+ };
161
+ /** Send a voice's output to the echo and the room as well as its place in the mix. */
162
+ const sends = (to: AudioNode, echoLevel: number, roomLevel: number) => {
163
+ const node = made(context.createGain());
164
+ node.connect(to);
165
+ if (echoLevel > 0) { const send = made(context.createGain()); send.gain.value = echoLevel; node.connect(send).connect(echoIn); }
166
+ if (roomLevel > 0) { const send = made(context.createGain()); send.gain.value = roomLevel; node.connect(send).connect(reverbIn); }
167
+ return node;
168
+ };
169
+ // Long-lived send points for each family, so a note needs no send nodes of its own.
170
+ const leadOut = sends(center, 1, 0.6), padOut = sends(center, 0, 0.9), arpLeft = sends(left, 0.6, 0.4), arpRight = sends(right, 0.6, 0.4);
171
+ const bellOut = sends(center, 0.5, 1), snareRoom = sends(drums, 0, 0.35);
172
+ /** The duck: the music dips under the kick and swells back before the off-beat. */
173
+ const duck = (at: number, amount: number) => {
174
+ if (sound.duck <= 0) return;
175
+ music.gain.setValueAtTime(1 - sound.duck * amount, at);
176
+ music.gain.linearRampToValueAtTime(1, at + Math.min(0.22, beatLength * 0.45));
177
+ };
178
+
179
+ // ---- Drums ----
180
+ const kick = (at: number, level: number) => {
181
+ const kit = sound.kit, chip = kit === "chip";
182
+ const length = kit === "soft" ? 0.42 : kit === "tight" ? 0.26 : chip ? 0.18 : 0.38;
183
+ const body = envelope(at, level, kit === "soft" ? 0.006 : 0.002, at + 0.015, at + length, drums);
184
+ tone(chip ? "square" : "sine", chip ? 240 : kit === "soft" ? 120 : 160, at, at + length, chip ? filter("lowpass", 900, 0.7, body) : body).frequency.exponentialRampToValueAtTime(chip ? 55 : 45, at + (chip ? 0.07 : 0.12));
185
+ if (kit !== "soft") hiss(at, 0.012, filter("highpass", 2600, 0.7, envelope(at, level * (chip ? 0.12 : 0.2), 0.001, at, at + 0.012, drums)));
186
+ duck(at, level);
187
+ };
188
+ const snare = (at: number, level: number) => {
189
+ const kit = sound.kit;
190
+ if (kit === "soft") { // a brush: long, dark, soft
191
+ hiss(at, 0.3, filter("lowpass", 4200, 0.5, envelope(at, level * 0.7, 0.012, at, at + 0.3, snareRoom)));
192
+ return;
193
+ }
194
+ const length = kit === "chip" ? 0.12 : kit === "tight" ? 0.16 : 0.2;
195
+ hiss(at, length, filter(kit === "chip" ? "highpass" : "bandpass", kit === "tight" ? 2400 : kit === "chip" ? 1200 : 1800, 0.9, envelope(at, level, 0.002, at, at + length, snareRoom)));
196
+ tone(kit === "chip" ? "square" : "triangle", kit === "tight" ? 220 : 190, at, at + 0.08, envelope(at, level * (kit === "chip" ? 0.25 : 0.55), 0.002, at, at + 0.08, drums));
197
+ };
198
+ const clap = (at: number, level: number) => {
199
+ // Three quick bursts and a tail, like hands that do not quite agree.
200
+ for (const [offset, length] of [[0, 0.02], [0.012, 0.02], [0.024, 0.16]] as const) {
201
+ hiss(at + offset, length, filter("bandpass", 1300, 1.4, envelope(at + offset, level, 0.001, at + offset, at + offset + length, snareRoom)));
202
+ }
203
+ };
204
+ const hat = (at: number, open: boolean, level: number) => {
205
+ const length = open ? 0.3 : sound.kit === "chip" ? 0.03 : 0.06;
206
+ hiss(at, length, filter("highpass", sound.kit === "soft" ? 8000 : sound.kit === "chip" ? 6000 : 7000, 0.8, envelope(at, level, 0.001, at, at + length, hats)));
207
+ };
208
+ const rim = (at: number, level: number) => {
209
+ hiss(at, 0.025, filter("bandpass", 1700, 3, envelope(at, level, 0.001, at, at + 0.025, rims)));
210
+ tone("triangle", 820, at, at + 0.04, envelope(at, level * 0.5, 0.001, at, at + 0.04, rims));
211
+ };
212
+ const shaker = (at: number, level: number) => hiss(at, 0.06, filter("bandpass", 5600, 1.2, envelope(at, level, 0.012, at + 0.01, at + 0.06, shakers)));
213
+ const crash = (at: number, level: number) => hiss(at, 1.8, filter("highpass", 4200, 0.5, envelope(at, level, 0.003, at, at + 1.8, sends(drums, 0, 0.5))));
214
+ /** A cymbal played backwards: swells into the next downbeat. */
215
+ const swell = (at: number, length: number, level: number) => {
216
+ const gain = made(context.createGain());
217
+ gain.gain.setValueAtTime(0.0001, at);
218
+ gain.gain.exponentialRampToValueAtTime(level, at + length);
219
+ gain.gain.linearRampToValueAtTime(0, at + length + 0.02);
220
+ gain.connect(drums);
221
+ hiss(at, length, filter("highpass", 5000, 0.5, gain));
222
+ };
223
+ /** Filtered noise sweeping up into the next section. */
224
+ const riser = (at: number, length: number, level: number) => {
225
+ const sweep = filter("bandpass", 300, 2, envelope(at, level, length * 0.9, at + length * 0.95, at + length, sends(drums, 0, 0.4)));
226
+ sweep.frequency.exponentialRampToValueAtTime(7000, at + length);
227
+ hiss(at, length, sweep);
228
+ };
229
+ const click = (at: number, accent: boolean) => {
230
+ tone("sine", accent ? 1760 : 1320, at, at + 0.07, envelope(at, 0.45, 0.001, at, at + 0.07, drums));
231
+ tone("triangle", accent ? 880 : 660, at, at + 0.05, envelope(at, 0.22, 0.001, at, at + 0.05, drums));
232
+ };
233
+ const DRUM: Readonly<Record<DrumPart, (at: number, level: number) => void>> = {
234
+ kick: (at, level) => kick(at, 0.9 * level), snare: (at, level) => snare(at, 0.36 * level), clap: (at, level) => clap(at, 0.26 * level),
235
+ hat: (at, level) => hat(at, false, 0.13 * level), open: (at, level) => hat(at, true, 0.13 * level), rim: (at, level) => rim(at, 0.26 * level),
236
+ shaker: (at, level) => shaker(at, 0.1 * level),
237
+ };
238
+
239
+ // ---- Pitched instruments ----
240
+ const bass = (at: number, midi: number, length: number, level: number) => {
241
+ const end = at + length, frequency = midiHz(midi);
242
+ switch (sound.bass) {
243
+ case "saw": { // a saw through a resonant low-pass that snaps shut, with a sine underneath
244
+ const shape = filter("lowpass", 900, 5, envelope(at, level, 0.004, at + length * 0.6, end, music));
245
+ shape.frequency.setTargetAtTime(240, at + 0.01, 0.06);
246
+ tone("sawtooth", frequency, at, end, shape);
247
+ tone("sine", frequency, at, end, envelope(at, level * 0.8, 0.004, at + length * 0.6, end, music));
248
+ break;
249
+ }
250
+ case "pluck": { // round and percussive, a little slap at the start
251
+ const shape = filter("lowpass", 1400, 3, envelope(at, level, 0.003, at + 0.02, at + Math.min(length, 0.5), music));
252
+ shape.frequency.setTargetAtTime(300, at + 0.005, 0.05);
253
+ tone("triangle", frequency, at, end, shape);
254
+ tone("sawtooth", frequency, at, end, envelope(at, level * 0.35, 0.002, at, at + 0.06, shape));
255
+ tone("sine", frequency, at, end, envelope(at, level * 0.7, 0.004, at + length * 0.5, end, music));
256
+ break;
257
+ }
258
+ case "reese": { // two saws drifting against each other over a clean sub
259
+ const shape = filter("lowpass", 520, 1.4, envelope(at, level * 0.8, 0.01, end - 0.04, end + 0.05, music));
260
+ tone("sawtooth", frequency, at, end + 0.05, shape, -14);
261
+ tone("sawtooth", frequency, at, end + 0.05, shape, 14);
262
+ tone("sine", frequency, at, end + 0.05, envelope(at, level, 0.01, end - 0.04, end + 0.05, music));
263
+ break;
264
+ }
265
+ case "upright": { // soft attack, woody, dies away like a plucked string
266
+ const shape = filter("lowpass", 700, 1, envelope(at, level, 0.012, at + 0.03, at + Math.max(0.4, length), music));
267
+ tone("triangle", frequency, at, end + 0.1, shape);
268
+ tone("sine", frequency, at, end + 0.1, shape);
269
+ break;
270
+ }
271
+ case "chip": // a triangle channel, as on old game hardware
272
+ tone("triangle", frequency, at, end, envelope(at, level * 1.1, 0.002, end - 0.02, end, music));
273
+ break;
274
+ }
275
+ };
276
+
277
+ const lead = (kind: (typeof sound)["lead"], at: number, midi: number, length: number, level: number, out: AudioNode) => {
278
+ const end = at + length, frequency = midiHz(midi);
279
+ /** Vibrato that eases in on held notes. */
280
+ const vibrato = (voices: OscillatorNode[], depth: number, rate: number, after: number) => {
281
+ if (length < 0.3) return;
282
+ const wobble = made(context.createOscillator()), amount = made(context.createGain());
283
+ wobble.frequency.value = rate;
284
+ amount.gain.setValueAtTime(0, at);
285
+ amount.gain.setValueAtTime(0, at + after);
286
+ amount.gain.linearRampToValueAtTime(depth, at + after + 0.25);
287
+ wobble.connect(amount);
288
+ for (const voice of voices) amount.connect(voice.detune);
289
+ wobble.start(at);
290
+ wobble.stop(end + 0.15);
291
+ };
292
+ switch (kind) {
293
+ case "sawsquare": {
294
+ const shape = filter("lowpass", 3800, 1.5, envelope(at, level, 0.008, end - 0.06, end + 0.08, out));
295
+ vibrato([tone("square", frequency, at, end + 0.08, shape), tone("sawtooth", frequency / 2, at, end + 0.08, shape, 4)], 14, 5.5, 0.12);
296
+ break;
297
+ }
298
+ case "whistle": {
299
+ const body = envelope(at, level * 1.25, 0.035, end - 0.05, end + 0.1, out);
300
+ vibrato([tone("sine", frequency, at, end + 0.1, body), tone("triangle", frequency, at, end + 0.1, envelope(at, level * 0.15, 0.03, end - 0.05, end + 0.1, out))], 18, 5.2, 0.1);
301
+ hiss(at, length, filter("bandpass", frequency * 2, 8, envelope(at, level * 0.12, 0.02, at + 0.05, end, out)));
302
+ break;
303
+ }
304
+ case "pulse": {
305
+ const shape = filter("lowpass", 7000, 0.7, envelope(at, level * 0.75, 0.003, end - 0.03, end + 0.03, out));
306
+ vibrato([tone("square", frequency, at, end + 0.03, shape)], 22, 6.5, 0.14);
307
+ break;
308
+ }
309
+ case "supersaw": {
310
+ const shape = filter("lowpass", 5500, 1, envelope(at, level * 0.8, 0.005, end - 0.04, end + 0.07, out));
311
+ for (const cents of [-13, 0, 13]) tone("sawtooth", frequency, at, end + 0.07, shape, cents);
312
+ break;
313
+ }
314
+ case "flute": {
315
+ const body = filter("lowpass", 6000, 0.7, envelope(at, level * 1.1, 0.045, end - 0.06, end + 0.12, out));
316
+ vibrato([tone("triangle", frequency, at, end + 0.12, body), tone("sine", frequency * 2, at, end + 0.12, envelope(at, level * 0.2, 0.05, end - 0.06, end + 0.12, out))], 16, 4.8, 0.18);
317
+ hiss(at, length + 0.1, filter("bandpass", frequency * 3, 4, envelope(at, level * 0.16, 0.03, at + 0.06, end + 0.1, out)));
318
+ break;
319
+ }
320
+ case "musicbox": { // a struck tine: a sine and two quickly fading partials, ringing past the note
321
+ const ring = Math.max(length, 0.5) + 0.7;
322
+ tone("sine", frequency, at, at + ring, envelope(at, level * 1.2, 0.002, at, at + ring, out));
323
+ tone("sine", frequency * 3, at, at + 0.4, envelope(at, level * 0.25, 0.001, at, at + 0.4, out));
324
+ tone("sine", frequency * 5.4, at, at + 0.15, envelope(at, level * 0.12, 0.001, at, at + 0.15, out));
325
+ break;
326
+ }
327
+ }
328
+ };
329
+ const pluck = (at: number, midi: number, level: number, brightness: number, out: AudioNode) => {
330
+ const frequency = midiHz(midi), shape = filter("lowpass", 900 + brightness * 3000, 2, envelope(at, level, 0.003, at, at + 0.3, out));
331
+ tone("triangle", frequency, at, at + 0.3, shape);
332
+ tone("square", frequency, at, at + 0.3, envelope(at, level * 0.25, 0.003, at, at + 0.12, shape));
333
+ };
334
+ const bell = (at: number, midi: number, length: number, level: number) => {
335
+ const frequency = midiHz(midi);
336
+ tone("sine", frequency, at, at + length + 0.8, envelope(at, level, 0.004, at, at + length + 0.8, bellOut));
337
+ tone("sine", frequency * 2.76, at, at + 0.5, envelope(at, level * 0.35, 0.002, at, at + 0.5, bellOut));
338
+ };
339
+ const arpNote = (at: number, midi: number, length: number, level: number, out: AudioNode) => {
340
+ const frequency = midiHz(midi);
341
+ if (sound.arp === "chip") tone("square", frequency, at, at + length, envelope(at, level * 0.5, 0.002, at + length * 0.7, at + length, filter("lowpass", 6000, 0.7, out)));
342
+ else if (sound.arp === "glock") {
343
+ tone("sine", frequency, at, at + 0.6, envelope(at, level, 0.001, at, at + 0.6, out));
344
+ tone("sine", frequency * 4, at, at + 0.12, envelope(at, level * 0.2, 0.001, at, at + 0.12, out));
345
+ } else pluck(at, midi, level, 0.5, out);
346
+ };
347
+
348
+ /** The chord as close-voiced notes around middle C. */
349
+ const voicing = (chord: Chord) => chord.intervals.map(interval => { let midi = chord.root + 12 + interval; while (midi > 68) midi -= 12; while (midi < 52) midi += 12; return midi; });
350
+ const pad = (at: number, chord: Chord, length: number, base: number, stab: boolean) => {
351
+ const notes = voicing(chord), end = at + length, level = sound.pad === "warm" || sound.pad === "chip" ? base : base * 1.8;
352
+ switch (sound.pad) {
353
+ case "warm": {
354
+ const warm = filter("lowpass", stab ? 2800 : 1800, 0.7, envelope(at, level, stab ? 0.005 : 0.3, end - (stab ? 0.02 : 0.3), end + (stab ? 0.08 : 0.2), padOut));
355
+ for (const midi of notes) { tone("sawtooth", midiHz(midi), at, end + 0.2, warm, -8); tone("sawtooth", midiHz(midi), at, end + 0.2, warm, 8); }
356
+ break;
357
+ }
358
+ case "ep": { // an electric piano: a sine and a bright partial that fades fast, with a slow tremolo
359
+ const body = envelope(at, level * 1.3, 0.004, at + 0.05, end + 0.4, padOut), tremolo = made(context.createOscillator()), depth = made(context.createGain()), shaped = made(context.createGain());
360
+ tremolo.frequency.value = 4.5;
361
+ depth.gain.value = 0.25;
362
+ tremolo.connect(depth).connect(shaped.gain);
363
+ shaped.connect(body);
364
+ tremolo.start(at);
365
+ tremolo.stop(end + 0.45);
366
+ for (const midi of notes) {
367
+ tone("sine", midiHz(midi), at, end + 0.4, shaped);
368
+ tone("sine", midiHz(midi) * 4, at, at + 0.2, envelope(at, level * 0.25, 0.002, at, at + 0.2, padOut));
369
+ }
370
+ break;
371
+ }
372
+ case "nylon": // a strummed guitar: each string a little after the last, ringing out
373
+ notes.forEach((midi, string) => {
374
+ const start = at + string * 0.016, shape = filter("lowpass", 3600, 1, envelope(start, level, 0.003, start + 0.02, start + Math.max(0.5, length), padOut));
375
+ shape.frequency.setTargetAtTime(900, start, 0.15);
376
+ tone("triangle", midiHz(midi), start, start + Math.max(0.5, length), shape);
377
+ tone("sawtooth", midiHz(midi), start, start + 0.1, envelope(start, level * 0.25, 0.002, start, start + 0.1, shape));
378
+ });
379
+ break;
380
+ case "chip": // square-wave chords, the way old consoles played them
381
+ for (const midi of notes) tone("square", midiHz(midi), at, end, envelope(at, level * 0.35, 0.002, end - 0.03, end, filter("lowpass", 4500, 0.7, padOut)));
382
+ break;
383
+ case "glass": { // pure, slow and airy
384
+ const air = envelope(at, level * 1.2, stab ? 0.01 : 0.5, end - 0.3, end + 0.6, padOut);
385
+ for (const midi of notes) { tone("sine", midiHz(midi), at, end + 0.6, air, -4); tone("triangle", midiHz(midi + 12), at, end + 0.6, envelope(at, level * 0.15, 0.6, end - 0.3, end + 0.6, padOut), 5); }
386
+ break;
387
+ }
388
+ }
389
+ };
390
+
391
+ // ---- Reading the arrangement ----
392
+ const tune: TuneNote[][] = Array.from({ length: songBeats(track) }, () => []);
393
+ for (const note of createTune(track, seed)) tune[Math.floor(note.beat)]?.push(note);
394
+ const countIn = countInBeats(track);
395
+ /** Context time of a straight song position, with the track's swing. */
396
+ const when = (at: number, index: number, beat: number) => at + (swung(track, beat) - index) * beatLength;
397
+ /** The pattern step (sixteenth) at `step` sixteenths into the section, and how many sixteenths it holds. */
398
+ const stepOf = (pattern: string, step: number): [string, number] => {
399
+ const char = pattern[step % pattern.length] ?? ".";
400
+ let hold = 1;
401
+ while (pattern[(step + hold) % pattern.length] === "-" && hold < pattern.length) hold++;
402
+ return [char, hold];
403
+ };
404
+ /** The bass plays an octave below the chord's root (E1 to D#2), where a bass guitar lives. */
405
+ const bassNote = (char: string, chord: Chord) => {
406
+ const root = chord.root - 12, third = chord.intervals[1] ?? 4, fifth = chord.intervals[2] ?? 7, seventh = chord.intervals[3] ?? 12;
407
+ switch (char.toUpperCase()) {
408
+ case "O": return root + 12;
409
+ case "F": return root + fifth;
410
+ case "T": return root + third;
411
+ case "S": return root + seventh;
412
+ case "L": return root + fifth - 12;
413
+ default: return root;
414
+ }
415
+ };
416
+ const fx = (section: Section, name: string) => (section.fx ?? "").split(" ").includes(name);
417
+ // Every pattern read once, without its spacing, so a beat only indexes strings.
418
+ const tidied = <T,>(record: Readonly<Record<string, T>>, map: (value: T) => string) => new Map(Object.entries(record).map(([name, value]) => [name, map(value)]));
419
+ const kits = new Map(Object.entries(sound.drums).map(([name, parts]) => [name, (Object.entries(parts) as [DrumPart, string][]).map(([part, pattern]) => [part, tidy(pattern)] as const)]));
420
+ const bassLines = tidied(sound.bassLines, tidy), comps = tidied(sound.comps, tidy), arps = tidied(sound.arps, tidy);
421
+
422
+ return {
423
+ output: limiter,
424
+ get nodes() { return nodes; },
425
+ beat(index, at) {
426
+ if (index < 0 || index >= songBeats(track)) return;
427
+ if (index < countIn) {
428
+ click(at, index === countIn - 1);
429
+ return;
430
+ }
431
+ const section = sectionAt(track, index), inSection = index - section.start, last = section.start + section.beats;
432
+ const bar = track.meter * beatLength, stopped = fx(section, "stop") && index >= last - track.meter / 2;
433
+ if (inSection === 0 && fx(section, "crash")) crash(at, 0.3);
434
+ if (fx(section, "riser") && index === last - 2 * track.meter) riser(at, 2 * bar, 0.2);
435
+ if (fx(section, "swell") && index === last - track.meter) swell(at, bar, 0.14);
436
+ for (let sixteenth = 0; sixteenth < 4; sixteenth++) {
437
+ const step = inSection * 4 + sixteenth, beat = index + sixteenth / 4, time = when(at, index, beat), chord = chordAt(track, beat);
438
+ // Drums, with a snare roll that thickens across the last bar where asked.
439
+ if (!stopped) {
440
+ for (const [part, pattern] of kits.get(section.drums) ?? []) {
441
+ const char = pattern[step % pattern.length];
442
+ if (char === "x" || char === "X" || char === "g") DRUM[part](time, char === "X" ? 1.25 : char === "g" ? 0.35 : 1);
443
+ }
444
+ }
445
+ if (fx(section, "roll") && index >= last - track.meter) DRUM.snare(time, 0.3 + 0.7 * ((index - (last - track.meter)) * 4 + sixteenth) / (track.meter * 4));
446
+ // Bass, pad and arpeggio from their patterns, on the chord of the moment.
447
+ const bassLine = bassLines.get(section.bass);
448
+ if (bassLine && !stopped) {
449
+ const [char, hold] = stepOf(bassLine, step);
450
+ if (/[ROFTSLroftsl]/.test(char)) bass(time, bassNote(char, chord), hold * beatLength / 4 * 0.92, char === char.toLowerCase() ? 0.22 : 0.32);
451
+ }
452
+ const comp = comps.get(section.pad ?? "none");
453
+ if (comp) {
454
+ const [char, hold] = stepOf(comp, step);
455
+ if (char === "S") pad(time, chord, hold * beatLength / 4, 0.07, false);
456
+ else if (char === "x" || char === "X") pad(time, chord, Math.max(hold * beatLength / 4, 0.12), char === "X" ? 0.08 : 0.06, true);
457
+ }
458
+ const arp = arps.get(section.arp ?? "none");
459
+ if (arp && !stopped) {
460
+ const [char, hold] = stepOf(arp, step), digit = Number(char);
461
+ if (char >= "0" && char <= "9") {
462
+ const tones = chord.intervals, midi = chord.root + 24 + (tones[digit % tones.length] ?? 0) + 12 * Math.floor(digit / tones.length);
463
+ arpNote(time, midi, hold * beatLength / 4 * 0.9, 0.11, step % 2 === 0 ? arpLeft : arpRight);
464
+ }
465
+ }
466
+ }
467
+ // The tune.
468
+ for (const note of tune[index] ?? []) {
469
+ const time = when(at, index, note.beat), length = Math.max(0.08, (swung(track, note.beat + note.length) - swung(track, note.beat)) * beatLength);
470
+ if (note.voice === "lead") lead(sound.lead, time, note.midi, length, 0.15, leadOut);
471
+ else if (note.voice === "lead2") lead(sound.lead2, time, note.midi, length, 0.15, leadOut);
472
+ else if (note.voice === "pluck") pluck(time, note.midi, 0.22, 0.4, leadOut);
473
+ else bell(time, note.midi, length, 0.18);
474
+ }
475
+ },
476
+ };
477
+ }