From 68d6d6a583363294d634b3a435ace2e3a91cb6eb Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 13:39:31 -0600 Subject: [PATCH 01/31] =?UTF-8?q?Plan:=20S7,=20F=C3=BCr=20Elise=20as=20the?= =?UTF-8?q?=20third=20Showcase?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index a61423b..dafc3b8 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6509,6 +6509,45 @@ column lit whole where one face meets another — now the default of `fog.column **Not yet:** Textures, sprites (a monster drawn as a scaled picture in front of the walls), a floor with distance, more than one level. +### S7. Für Elise, the third Showcase (asked 2026-11-08) + +The user: "for our next showcase trigscript map i want to show off the sound/music capabilities … Für Elise with a +cool visualizer … make it sound as awesome as possible". Showcase #3 (the raycaster becomes #4; the two run +alongside). + +**Decided (the user, 2026-11-08):** the arc, not plain piano — A as an intimate solo piano; the stormy D-minor C +section turns into a full arrangement (strings, low brass, timpani) switched in with `Band`; the last A back to solo +piano in a big hall, ending on the soft final chord. Probes first: one for the sound, one for the visualizer's timing. + +**Why the library needs work for a solo piano** (read 2026-11-08): +- `sampler()` takes one recording and pitches it everywhere — away from its root the notes sound sped up or slowed. + `fmSynth` gives an electric piano, not a grand. +- `midi()` snaps every note to a step grid at the file's first tempo; velocity only changes loudness, not tone; no + sustain pedal. A grid Für Elise sounds like a ringtone; the piece lives on rubato and pedalled arpeggios. +- Played note by note, a sound starts on a 42 ms frame plus the mixer's 21.3 ms grid (sd 7.8 ms against the same + song pre-mixed). Under a band that is not heard; a lone piano's sixteenths (~115 ms) would wobble. So the piano is + **rendered** (`render` / `stems`) and the visuals follow the note timeline known when the script is built. + +**The plan:** +1. *Sound.* A multisampled instrument in `trigscript/music`: recordings across the keyboard, velocity layers (a soft + note sounds soft, not just quieter), release samples, a sustain pedal with sympathetic resonance. A performance + that is not a grid: notes at their own times and velocities, a tempo map (rubato), pedal. Sources: the Salamander + Grand Piano V3 (Alexander Holm, CC-BY 3.0 — credit in the map description and the docs) and VSCO 2 Community + Edition (Versilian Studios, CC0) for strings, brass and timpani. Both are additions every later map can use. +2. *Visualizer.* Minimap: notes falling onto a keyboard row that lights as each key sounds, coloured by hand (the + Overlord colour board, `probes/lib/unit-screen.ts`). Main screen: StarCraft as the stage — a visible effect on each + note (melody, the left hand's arpeggios across a terrain keyboard, big effects on the C section's chords). +3. Showcase build, recording, the Showcase entry in scm-js docs/trigscript.md — as Korobeiniki did. + +**Rights (keep):** Beethoven's score is public domain; the transcription and the arrangement are ours, written from +the score — never an existing MIDI file or someone's arrangement. Samples only from the two libraries above (or +another with a licence that allows putting them in a map). Never a Blizzard sound. Nothing called "Für Elise" by +anyone else's name. + +**Probes (2026-11-08):** branch `fur-elise` (sound: worktree ~/github/plugin-trigscript-fur-elise) and +`fur-elise-visual` (visualizer: worktree ~/github/plugin-trigscript-fur-elise-visual). Each records its results +below in its own subsection. + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice From 32463e7dade0b9ba561256a7c7827cfa7c6b906e Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 14:19:08 -0600 Subject: [PATCH 02/31] Sampled instruments: the .samples file, samples(), loudness and a piano's sympathetic strings A `.samples` file is a sampled instrument among a script's files: recordings and the zones that say which keys and strengths each plays (SFZ's regions: trigger on attack, release or the pedal, volume, amp_veltrack, ampeg_release, rt_decay, tune, keytrack, round robin, lorand/hirand). The recordings are 16-bit, coded without loss (four fixed predictors and Rice codes, a block of 4096 at a time): the Salamander Grand Piano's 483 recordings, 16 layers, keys 28-91, cut to 10 s, are 125 MB of text where plain 16-bit in base64 would be 787. A recording is decoded when a build first needs it; a check names every clip made from one by its key (`storedClip`) without decoding. scripts/make-samples.mts makes one from an SFZ instrument or a folder of recordings named by note (--keys, --layers, --seconds, --octave, --detect, --pitch). `samples(zones)` makes one in a script from clips it has. The hover and a small viewer say what one holds; the editor does not make them yet. Clip gains `lufs` (ITU-R BS.1770-4, as libebur128 designs the K-weighting for any rate), `loudness(lufs)` and `resonance({ pedal, amount, decay })`: a comb filter a string from A0 to E6, fed while the pedal is down, damped in 0.1 s when it comes up. Nothing an existing clip does changes, so ENGINE stays "sound 3". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- .gitignore | 2 + compiler/declarations.ts | 80 +++++++++- compiler/dsp.ts | 102 ++++++++++++ compiler/media.ts | 12 +- compiler/runtime.ts | 4 +- compiler/samples.ts | 335 +++++++++++++++++++++++++++++++++++++++ compiler/sound.ts | 41 ++++- editor.ts | 10 +- ko.ts | 1 + notesImport.ts | 20 +++ scripts/make-samples.mts | 238 +++++++++++++++++++++++++++ scripts/script-files.mts | 6 +- 12 files changed, 834 insertions(+), 17 deletions(-) create mode 100644 compiler/samples.ts create mode 100644 scripts/make-samples.mts diff --git a/.gitignore b/.gitignore index 371d800..c46d9b3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ probes/*.video probes/*.image # The sound demo's imported sound: made on the spot by probes/lib/sound-demo-gen.mts. probes/*.sound +# Sampled instruments a probe imports (probes/fur-elise-sound.ts): made from sample libraries outside the repository by scripts/make-samples.mts, never committed. +probes/*.samples diff --git a/compiler/declarations.ts b/compiler/declarations.ts index e9cf7e4..97d4034 100644 --- a/compiler/declarations.ts +++ b/compiler/declarations.ts @@ -561,6 +561,11 @@ ${kw}interface Clip { readonly channels: 1 | 2; /** The loudest sample, 0 to 1; above 1 is cut off when the map's file is written. */ readonly peak: number; + /** + * How loud it is as a whole, in LUFS (ITU-R BS.1770, the figure EBU R 128 and the streaming services use): −14 to + * −16 for music heard on its own, −23 for broadcast. Reading it works the samples out. + */ + readonly lufs: number; /** The part from \`from\` to \`to\` seconds (the end when left out). */ trim(from: number, to?: number): Clip; /** Louder or quieter: 0.5 is half as loud, 2 twice. The game plays it as loud as written. */ @@ -639,6 +644,15 @@ ${kw}interface Clip { * \`makeup\` dB after (0). Evens a part out, or glues a mix. */ compress(options?: { readonly threshold?: number; readonly ratio?: number; readonly attack?: number; readonly release?: number; readonly knee?: number; readonly makeup?: number }): Clip; + /** Louder or quieter as a whole, so its loudness (\`lufs\`) is \`lufs\`: \`mix.loudness(-15).limit()\`. */ + loudness(lufs: number): Clip; + /** + * What a piano's strings add while its sustain pedal is down: each string, A0 to E6, answers the partials of the + * notes that fall on its own and rings on, until the pedal comes up and the dampers stop it. \`pedal\`: [down, up] + * in seconds; \`amount\` how loud a string answers (0.25), \`decay\` seconds it rings (3). Two channels, the + * low strings to the left. \`music.sampled\` does this itself with its \`resonance\` option. + */ + resonance(options: { readonly pedal: readonly (readonly [number, number])[]; readonly amount?: number; readonly decay?: number }): Clip; } /** * When the script is built: a tone of \`pitch\` — hertz, or a note's name: "A4" (440), "C#5", "Eb3" — for @@ -1235,6 +1249,63 @@ export function beforeEach(fn: (sim: Sim) => void): void; export function afterEach(fn: (sim: Sim) => void): void; `; +/** + * Sampled instruments: in the full declarations, not the compact variant a language model reads (they come from a + * \`.samples\` file the editor does not make yet, or from \`samples()\`). + */ +const SAMPLED = (kw: string): string => `/** + * A sampled instrument when the script is built (\`import piano from "./piano.samples"\`, made from an SFZ + * instrument by scripts/make-samples.mts): its recordings, and the keys and strengths each plays (its zones). + * \`music.sampled(piano)\` plays it. + */ +${kw}interface Samples { + readonly name: string; + /** Who made the recordings and under what licence: what a map that plays them should say. */ + readonly credit: string; + readonly rate: number; + readonly zones: readonly SampleZone[]; + /** Seconds of recordings in it. */ + readonly seconds: number; +} +/** One zone of a sampled instrument: a recording, the keys and strengths it plays, and how it is played. */ +${kw}interface SampleZone { + readonly clip: Clip; + /** The key it was recorded at (60 is C4), and the keys it plays, lo … hi. */ + readonly key: number; + readonly lo: number; + readonly hi: number; + /** The strengths it plays (velocity, 1 … 127). */ + readonly vlo: number; + readonly vhi: number; + /** What starts it: a key struck (when left out), let go, the pedal pressed or lifted. */ + readonly trigger?: "attack" | "release" | "pedal-down" | "pedal-up"; + /** dB, 0 as recorded. */ + readonly volume?: number; + /** How much the strength changes its loudness, 0 … 1 (1). */ + readonly veltrack?: number; + /** Seconds a note takes to die away after it is let go. */ + readonly release?: number; + /** A release zone: dB quieter each second the key was held. */ + readonly decay?: number; + /** Cents it is tuned up or down. */ + readonly tune?: number; + /** false: played at its own pitch whatever the key. */ + readonly pitched?: boolean; + /** Zones of the same keys and strengths played in turn: this one's turn of \`turns\`. */ + readonly turn?: number; + readonly turns?: number; + /** Zones of the same keys chosen by chance: this one when a number 0 … 1 falls in [from, to). */ + readonly chance?: readonly [number, number]; +} +/** + * When the script is built: a sampled instrument from clips the script has — recordings it imports (.sound), or ones + * it makes — for \`music.sampled\`. Each zone a clip, the key it plays at (60 or "C4"), and, when left out, every key + * and strength: a note is played from the zone whose key is nearest it. + * const piano = music.sampled(samples([{ clip: c3, key: "C3" }, { clip: c4, key: "C4" }, { clip: c5, key: "C5" }])); + */ +${kw}function samples(zones: readonly ({ readonly clip: Clip; readonly key: number | string; readonly lo?: number | string; readonly hi?: number | string } & Partial>)[], options?: { readonly name?: string; readonly credit?: string }): Samples; +`; + /** The whole declaration file for a set of names. */ /** What importing one of the script's media files gives (`media.ts`). */ const MEDIA_MODULES = `// ── A video the script imports: import badApple from "./bad-apple.video"; ── @@ -1252,6 +1323,11 @@ declare module "*.sound" { const sound: Clip; export default sound; } +// ── A sampled instrument the script imports: import piano from "./piano.samples"; ── +declare module "*.samples" { + const samples: Samples; + export default samples; +} // ── Notes the script imports, from a MIDI file: import tune from "./tune.notes"; ── declare module "*.notes" { const notes: Notes; @@ -1263,7 +1339,7 @@ export function generateDeclarations(names: ScriptNames = defaultScriptNames(), const compact = options.compact === true; const globals = body("declare ", "", names, compact); if (compact) return `${HEADER}${globals}\n${ARRAYS}`; - const module = `${body("export ", "export ", names, false)}\n${TESTING}`.split("\n").map((l) => (l ? ` ${l}` : l)).join("\n"); - return `${HEADER}${globals}\n${ARRAYS}\n// ── The same names, as a module: import { trigger, units } from "${MODULE_NAME}"; ──\ndeclare module "${MODULE_NAME}" {\n${module}\n}\n${MEDIA_MODULES}`; + const module = `${body("export ", "export ", names, false)}\n${SAMPLED("export ")}\n${TESTING}`.split("\n").map((l) => (l ? ` ${l}` : l)).join("\n"); + return `${HEADER}${globals}\n${SAMPLED("declare ")}\n${ARRAYS}\n// ── The same names, as a module: import { trigger, units } from "${MODULE_NAME}"; ──\ndeclare module "${MODULE_NAME}" {\n${module}\n}\n${MEDIA_MODULES}`; } diff --git a/compiler/dsp.ts b/compiler/dsp.ts index 6a4907c..a853444 100644 --- a/compiler/dsp.ts +++ b/compiler/dsp.ts @@ -314,3 +314,105 @@ export function pluckVoice(hz: number, rate: number, n: number, brightness: numb } return out; } + +/* ── Loudness, and strings that ring in sympathy ── */ + +/** A biquad's coefficients, b over a (a0 = 1). */ +type Biquad = readonly [b0: number, b1: number, b2: number, a1: number, a2: number]; +function biquad(x: Float32Array, [b0, b1, b2, a1, a2]: Biquad): Float32Array { + const out = new Float32Array(x.length); + let x1 = 0, x2 = 0, y1 = 0, y2 = 0; + for (let i = 0; i < x.length; i++) { + const y = b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; + x2 = x1; x1 = x[i]; y2 = y1; y1 = y; out[i] = y; + } + return out; +} + +/** + * Integrated loudness in LUFS, as ITU-R BS.1770-4 measures it (EBU R 128's figure): each channel through the K-weighting + * (a high shelf, +4 dB above 1.7 kHz, then a high-pass at 38 Hz, made for the clip's rate as libebur128 makes them), + * its power over 400 ms blocks three-quarters overlapping, the blocks under −70 LUFS left out, then those more than + * 10 LU under the mean of the rest. −Infinity for silence. + */ +export function loudness(chans: Channels, rate: number): number { + let K = Math.tan((Math.PI * 1681.974450955533) / rate); + const Vh = 10 ** (3.999843853973347 / 20), Vb = Vh ** 0.4996667741545416, Q1 = 0.7071752369554196; + let a0 = 1 + K / Q1 + K * K; + const shelf: Biquad = [(Vh + (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - Vh)) / a0, (Vh - (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - 1)) / a0, (1 - K / Q1 + K * K) / a0]; + K = Math.tan((Math.PI * 38.13547087602444) / rate); + const Q2 = 0.5003270373238773; + a0 = 1 + K / Q2 + K * K; + const high: Biquad = [1, -2, 1, (2 * (K * K - 1)) / a0, (1 - K / Q2 + K * K) / a0]; + const weighted = chans.map((c) => biquad(biquad(c, shelf), high)); + const n = chans[0].length, block = Math.round(0.4 * rate), step = Math.round(0.1 * rate); + if (n < block) return -Infinity; + // The power of each block, the channels added (each weighs 1: left and right, or the one). + const powers: number[] = []; + const prefix = weighted.map((w) => { const p = new Float64Array(n + 1); for (let i = 0; i < n; i++) p[i + 1] = p[i] + w[i] * w[i]; return p; }); + for (let from = 0; from + block <= n; from += step) { + let z = 0; + for (const p of prefix) z += (p[from + block] - p[from]) / block; + powers.push(z); + } + const lufs = (z: number) => -0.691 + 10 * Math.log10(z); + const above = powers.filter((z) => z > 0 && lufs(z) > -70); + if (above.length === 0) return -Infinity; + const gate = lufs(above.reduce((a, b) => a + b, 0) / above.length) - 10; + const kept = above.filter((z) => lufs(z) > gate); + return lufs(kept.reduce((a, b) => a + b, 0) / kept.length); +} + +/** + * What the strings of a piano add while its sustain pedal is down: every damper lifted, each string answers the + * partials of the notes played that fall on its own — a comb filter a string from A0 to E6 (the keys with dampers), + * tuned to it, each fed the sound while the pedal is down and ringing `decay` seconds (to −60 dB; the low strings + * longer, the high ones shorter), and stopped in a tenth of a second when the pedal comes up and the dampers fall. + * The strings low to high are heard from left to right, as the player hears them. Only what they add comes out, + * `amount` of it (a string answering a partial held on its pitch comes back that loud); `pedal` is [down, up] in seconds. + */ +export function sympathetic(chans: Channels, rate: number, pedal: Points, amount: number, decay: number, frames: number): Float32Array[] { + const n = chans[0].length, L = new Float32Array(frames), R = new Float32Array(frames); + // Whether the dampers are up, each sample, eased over 20 ms either way. + const up = new Float32Array(frames), ease = Math.max(1, Math.round(0.02 * rate)); + for (const [down, lift] of pedal) { + const a = Math.max(0, Math.round(down * rate)), b = Math.min(frames, Math.round(lift * rate)); + for (let i = a; i < b; i++) up[i] = 1; + } + const open = new Float32Array(frames); + let g = 0; + for (let i = 0; i < frames; i++) { g += (up[i] - g) / ease; open[i] = g; } + const x = new Float32Array(frames); + for (let i = 0; i < Math.min(n, frames); i++) { + let s = 0; + for (const c of chans) s += c[i]; + x[i] = (s / chans.length) * open[i]; + } + const damped = 0.1; + for (let m = 21; m <= 88; m++) { + const hz = 440 * 2 ** ((m - 69) / 12), delay = rate / hz; + // The string's ring: the low strings half again as long as `decay`, the top ones half as long. + const t60 = decay * (1.5 - (m - 21) / 67); + const gDown = 10 ** ((-3 * delay) / (rate * t60)), gUp = 10 ** ((-3 * delay) / (rate * damped)); + const size = Math.ceil(delay) + 2, buf = new Float32Array(size); + const d0 = Math.floor(delay), frac = delay - d0; + const pan = (m - 21) / 67, gl = Math.cos((pan * Math.PI) / 2), gr = Math.sin((pan * Math.PI) / 2); + let w = 0, lp = 0, energy = 0; + for (let i = 0; i < frames; i++) { + const r1 = (w - d0 + size) % size, r2 = (r1 - 1 + size) % size; + const back = buf[r1] * (1 - frac) + buf[r2] * frac; + lp = 0.75 * back + 0.25 * lp; + const gk = gUp + (gDown - gUp) * open[i]; + const y = x[i] + gk * lp; + buf[w] = y; + w = (w + 1) % size; + // What comes out is the string's ring alone, scaled so that a partial held on its pitch returns as loud. + const out = (y - x[i]) * (1 - gDown) * amount; + L[i] += gl * out; + R[i] += gr * out; + energy = energy * 0.999 + Math.abs(y); + if (energy < 1e-9 && open[i] === 0 && i > n) break; + } + } + return [L, R]; +} diff --git a/compiler/media.ts b/compiler/media.ts index 4977ada..10130f0 100644 --- a/compiler/media.ts +++ b/compiler/media.ts @@ -20,15 +20,17 @@ import { fromBase64, PROB_HALF, RangeDecoder, RangeEncoder, toBase64 } from "./r import { describeImage, IMAGE_EXTENSION, imageValue } from "./image"; import { clipValue, describeSound, SOUND_EXTENSION } from "./sound"; import { describeNotes, NOTES_EXTENSION, notesValue } from "./notes"; +import { describeSamples, SAMPLES_EXTENSION, samplesValue } from "./samples"; /** The extension of a video among a script's files. */ export const VIDEO_EXTENSION = ".video"; -/** A video, an image (`image.ts`), a sound (`sound.ts`) or notes (`notes.ts`): a file of the script that is no TypeScript, whose import gives a value. */ -export const isMediaFile = (path: string): boolean => /\.(?:video|image|sound|notes)$/i.test(path); +/** A video, an image (`image.ts`), a sound (`sound.ts`), notes (`notes.ts`) or a sampled instrument (`samples.ts`): a file of the script that is no TypeScript, whose import gives a value. */ +export const isMediaFile = (path: string): boolean => /\.(?:video|image|sound|notes|samples)$/i.test(path); export const isVideoFile = (path: string): boolean => path.toLowerCase().endsWith(VIDEO_EXTENSION); export const isImageFile = (path: string): boolean => path.toLowerCase().endsWith(IMAGE_EXTENSION); export const isSoundFile = (path: string): boolean => path.toLowerCase().endsWith(SOUND_EXTENSION); export const isNotesFile = (path: string): boolean => path.toLowerCase().endsWith(NOTES_EXTENSION); +export const isSamplesFile = (path: string): boolean => path.toLowerCase().endsWith(SAMPLES_EXTENSION); /** A game frame on Fastest, in milliseconds: what a video imported "at the game's speed" has a frame for. */ export const FASTEST_FRAME_MS = 42; @@ -177,11 +179,11 @@ export function describeVideo(text: string): string { } } -/** The value an import of a media file gives: an `Image` for an `.image`, a `Clip` for a `.sound`, `Notes` for a `.notes`, a `Video` for a `.video`. */ -export const mediaValue = (path: string, text: string): unknown => (isImageFile(path) ? imageValue(text) : isSoundFile(path) ? clipValue(text) : isNotesFile(path) ? notesValue(text) : videoValue(text)); +/** The value an import of a media file gives: an `Image` for an `.image`, a `Clip` for a `.sound`, `Notes` for a `.notes`, `Samples` for a `.samples`, a `Video` for a `.video`. */ +export const mediaValue = (path: string, text: string): unknown => (isImageFile(path) ? imageValue(text) : isSoundFile(path) ? clipValue(text) : isNotesFile(path) ? notesValue(text) : isSamplesFile(path) ? samplesValue(text) : videoValue(text)); /** What the Explorer's hover says about a media file. */ -export const describeMedia = (path: string, text: string): string => (isImageFile(path) ? describeImage(text) : isSoundFile(path) ? describeSound(text) : isNotesFile(path) ? describeNotes(text) : describeVideo(text)); +export const describeMedia = (path: string, text: string): string => (isImageFile(path) ? describeImage(text) : isSoundFile(path) ? describeSound(text) : isNotesFile(path) ? describeNotes(text) : isSamplesFile(path) ? describeSamples(text) : describeVideo(text)); /* ── The coding: a tile's odds by the tiles around it, for LZMA's binary range coder (`rangeCoder.ts`) ── */ diff --git a/compiler/runtime.ts b/compiler/runtime.ts index ccf2eb4..35a2b37 100644 --- a/compiler/runtime.ts +++ b/compiler/runtime.ts @@ -30,6 +30,7 @@ import { LOCAL_FIELDS, LOCATION_SIDES, localName, locationField, MEMORY_FIELDS, import { coverValue } from "./cover"; import { isVideo } from "./media"; import { clipFile, fm, isClip, mixdown, noise, pluck, silence, together, tone, type ClipFile } from "./sound"; +import { makeSamples } from "./samples"; /** `memory(address, …)` reads `deaths` at player `EPD(address)`, unit 0: the deaths table starts here in 1.16.1's memory. */ export const DEATHS_TABLE_ADDRESS = 0x58a364; @@ -645,6 +646,7 @@ export function createRuntime(names: ScriptNames, collector: Collector, options: rt.silence = built(silence); rt.mixdown = built(mixdown); rt.together = built(together); + rt.samples = built(makeSamples); rt.fm = built(fm); rt.pluck = built(pluck); rt.centerLocation = () => { throw new ScriptError("centerLocation() moves a location while the game runs: use it inside program(), as a statement — centerLocation(locations.Cursor, x, y)."); }; @@ -837,6 +839,6 @@ export function runtimeNames(names: ScriptNames): string[] { out.push("seconds", "minutes", "frames", "cycles", "sleep", "nextFrame", "until", "sync", "select", "local", "start", "rose", "once", "shared", "clamp", "u32", "i32", "fixed"); out.push(...READER_NAMES, "races", "slots", "name", "color", "print"); out.push(...UNIT_CALL_NAMES, "colors", ...INPUT_CALL_NAMES, "bounds"); - out.push("textColors", "ui", "on", "reserveLocation", "cover", "tone", "noise", "silence", "mixdown", "together", "fm", "pluck", "__jsx", "__fragment", "__class", "__fn", "__listen"); + out.push("textColors", "ui", "on", "reserveLocation", "cover", "tone", "noise", "silence", "mixdown", "together", "samples", "fm", "pluck", "__jsx", "__fragment", "__class", "__fn", "__listen"); return out; } diff --git a/compiler/samples.ts b/compiler/samples.ts new file mode 100644 index 0000000..c0823d9 --- /dev/null +++ b/compiler/samples.ts @@ -0,0 +1,335 @@ +/** + * Sampled instruments a script imports: `import piano from "./piano.samples"`. A `.samples` file is one of the + * script's files: the recordings of an instrument — a note every few keys, each at several strengths, and the sounds + * of its keys let go and its pedal — and which key and which strength each one is for (its zones), as a sampler's + * SFZ file says it. `music.sampled(piano)` (`stdlib/music.ts`) plays it: each note from the recording nearest its key + * and the one made at its strength, so a soft note sounds soft, not only quieter. + * + * The file is text, one line of JSON: the zones, and the recordings in base64, 16-bit, coded without loss — each + * sample predicted from the three before it, the best of four fixed predictors a block (as FLAC's), and what is left + * Rice-coded — about half of plain 16-bit for a piano's notes, which ring down to near silence. A recording is + * decoded when a build first needs its samples; a check as the user types decodes none. + * + * `scripts/make-samples.mts` makes one from an SFZ instrument (the Salamander Grand Piano's, VSCO 2's) — choosing + * keys, strengths and the longest a recording may be, since a whole concert grand is half a gigabyte. + */ +import { fromBase64, toBase64 } from "./rangeCoder"; +import { hertz, isClip, storedClip, type Clip } from "./sound"; + +/** The extension of a sampled instrument among a script's files. */ +export const SAMPLES_EXTENSION = ".samples"; +/** The format's version, in the file. */ +const VERSION = 1; + +/** What starts a zone's recording: a key struck, a key let go, the sustain pedal pressed or lifted. */ +export type ZoneTrigger = "attack" | "release" | "pedal-down" | "pedal-up"; + +/** A zone as the file holds it: which recording, for which keys and strengths, and how it is played. */ +export interface ZoneData { + /** The recording, by its place in the file's list. */ + readonly sample: number; + /** The key the recording was made at (MIDI number, 60 is C4); the keys it plays, `lo` … `hi`. */ + readonly key: number; + readonly lo: number; + readonly hi: number; + /** The strengths it plays (MIDI velocity, 1 … 127). */ + readonly vlo: number; + readonly vhi: number; + readonly trigger?: ZoneTrigger; + /** dB, 0 as recorded. */ + readonly volume?: number; + /** How much the strength changes its loudness, 0 … 1 (SFZ's amp_veltrack / 100; 1 when left out). */ + readonly veltrack?: number; + /** Seconds a note takes to die away after it is let go (SFZ's ampeg_release). */ + readonly release?: number; + /** For a release zone: dB quieter each second the key was held (SFZ's rt_decay). */ + readonly decay?: number; + /** Cents the recording is tuned up (or down). */ + readonly tune?: number; + /** false: played at its own pitch whatever the key (a key's thump, the pedal). */ + readonly pitched?: boolean; + /** Round robin: the zone's turn, 1 … `turns`, among zones of the same keys and strengths played in turn. */ + readonly turn?: number; + readonly turns?: number; + /** A choice by chance, `[from, to)` of 0 … 1, among zones of the same keys (SFZ's lorand/hirand). */ + readonly chance?: readonly [number, number]; +} + +/** A recording as the file lists it. */ +interface SampleEntry { readonly name: string; readonly channels: 1 | 2; readonly frames: number; readonly bytes: number } + +interface SamplesHeader { + trigscript: "samples"; + version: number; + rate: number; + name?: string; + credit?: string; + source?: string; + samples: SampleEntry[]; + zones: ZoneData[]; + data: string; +} + +/** A recording to put in a file: its name (for the person), and one or two channels of samples (−1 … 1). */ +export interface SampleInput { readonly name: string; readonly channels: readonly Float32Array[] } + +/** What `writeSamples` takes: the recordings at one rate, the zones over them, and who made them. */ +export interface SamplesInput { + readonly rate: number; + readonly name?: string; + /** Who made the recordings and under what licence: what a map that plays them should say. */ + readonly credit?: string; + readonly source?: string; + readonly samples: readonly SampleInput[]; + readonly zones: readonly ZoneData[]; +} + +/* ── The coding: fixed prediction and Rice codes, a block at a time ── */ + +const BLOCK = 4096; +/** Past this many ones a residual is written whole, 20 bits, after them. */ +const ESCAPE = 24; + +class BitWriter { + bytes = new Uint8Array(1 << 16); + length = 0; + private acc = 0; + private count = 0; + private push(byte: number) { + if (this.length === this.bytes.length) { const b = new Uint8Array(this.bytes.length * 2); b.set(this.bytes); this.bytes = b; } + this.bytes[this.length++] = byte; + } + write(value: number, bits: number) { + for (let k = bits - 1; k >= 0; k--) { + this.acc = (this.acc << 1) | ((value >>> k) & 1); + if (++this.count === 8) { this.push(this.acc); this.acc = 0; this.count = 0; } + } + } + ones(n: number) { for (let k = 0; k < n; k++) this.write(1, 1); } + finish(): Uint8Array { + if (this.count) this.push(this.acc << (8 - this.count)); + this.acc = 0; this.count = 0; + return this.bytes.subarray(0, this.length); + } +} + +class BitReader { + private at = 0; + private bit = 0; + private readonly bytes: Uint8Array; + constructor(bytes: Uint8Array) { this.bytes = bytes; } + one(): number { + if (this.at >= this.bytes.length) throw new Error("A recording in this .samples file ends too soon: the file is cut short."); + const b = (this.bytes[this.at] >> (7 - this.bit)) & 1; + if (++this.bit === 8) { this.bit = 0; this.at++; } + return b; + } + read(bits: number): number { let v = 0; for (let k = 0; k < bits; k++) v = (v << 1) | this.one(); return v >>> 0; } +} + +/** The four fixed predictions of x[n] from the samples before it (0 before the start). */ +const predict = (order: number, a: number, b: number, c: number): number => (order === 0 ? 0 : order === 1 ? a : order === 2 ? 2 * a - b : 3 * a - 3 * b + c); + +/** One channel, as 16-bit integers, coded. */ +function encodeChannel(s: Int16Array, w: BitWriter): void { + for (let from = 0; from < s.length; from += BLOCK) { + const to = Math.min(s.length, from + BLOCK); + const at = (i: number) => (i >= 0 ? s[i] : 0); + // The order whose residuals are smallest. + let order = 0, least = Infinity; + for (let o = 0; o < 4; o++) { + let sum = 0; + for (let i = from; i < to; i++) sum += Math.abs(s[i] - predict(o, at(i - 1), at(i - 2), at(i - 3))); + if (sum < least) { least = sum; order = o; } + } + const u = new Uint32Array(to - from); + for (let i = from; i < to; i++) { const r = s[i] - predict(order, at(i - 1), at(i - 2), at(i - 3)); u[i - from] = r >= 0 ? 2 * r : -2 * r - 1; } + // The Rice parameter that writes the block in the fewest bits. + let k = 0, best = Infinity; + for (let kk = 0; kk < 20; kk++) { + let bits = 0; + for (let j = 0; j < u.length; j++) { const q = u[j] >>> kk; bits += q >= ESCAPE ? ESCAPE + 20 : q + 1 + kk; } + if (bits < best) { best = bits; k = kk; } + } + w.write(order, 2); + w.write(k, 5); + for (let j = 0; j < u.length; j++) { + const q = u[j] >>> k; + if (q >= ESCAPE) { w.ones(ESCAPE); w.write(u[j], 20); } + else { w.ones(q); w.write(0, 1); if (k) w.write(u[j] & ((1 << k) - 1), k); } + } + } +} + +function decodeChannel(r: BitReader, frames: number): Float32Array { + const out = new Float32Array(frames), s = new Int32Array(frames); + for (let from = 0; from < frames; from += BLOCK) { + const to = Math.min(frames, from + BLOCK), order = r.read(2), k = r.read(5); + for (let i = from; i < to; i++) { + let q = 0; + while (q < ESCAPE && r.one()) q++; + const u = q >= ESCAPE ? r.read(20) : ((q << k) | (k ? r.read(k) : 0)) >>> 0; + const res = u & 1 ? -((u + 1) >>> 1) : u >>> 1; + const a = i > 0 ? s[i - 1] : 0, b = i > 1 ? s[i - 2] : 0, c = i > 2 ? s[i - 3] : 0; + s[i] = res + predict(order, a, b, c); + out[i] = s[i] / 32768; + } + } + return out; +} + +const toInt16 = (x: Float32Array): Int16Array => { + const out = new Int16Array(x.length); + for (let i = 0; i < x.length; i++) out[i] = Math.max(-32768, Math.min(32767, Math.round(x[i] * 32768))); + return out; +}; + +/* ── The file ── */ + +/** The `.samples` file's text for these recordings and zones. */ +export function writeSamples(input: SamplesInput): string { + if (!(Number.isInteger(input.rate) && input.rate >= 8000 && input.rate <= 96000)) throw new Error(`A sampled instrument's rate is 8 000 to 96 000 samples a second, not ${input.rate}.`); + checkZones(input.zones, input.samples.length); + const parts: Uint8Array[] = [], entries: SampleEntry[] = []; + for (const s of input.samples) { + if (s.channels.length !== 1 && s.channels.length !== 2) throw new Error(`The recording ${s.name} has ${s.channels.length} channels: one or two.`); + const frames = s.channels[0].length; + const w = new BitWriter(); + for (const c of s.channels) { + if (c.length !== frames) throw new Error(`The recording ${s.name}'s channels are not the same length.`); + encodeChannel(toInt16(c), w); + } + const bytes = w.finish().slice(); + parts.push(bytes); + entries.push({ name: s.name, channels: s.channels.length as 1 | 2, frames, bytes: bytes.length }); + } + const all = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let o = 0; + for (const p of parts) { all.set(p, o); o += p.length; } + const header: SamplesHeader = { + trigscript: "samples", version: VERSION, rate: input.rate, + ...(input.name ? { name: input.name } : {}), ...(input.credit ? { credit: input.credit } : {}), ...(input.source ? { source: input.source } : {}), + samples: entries, zones: input.zones.map((z) => ({ ...z })), data: toBase64(all), + }; + return JSON.stringify(header); +} + +function checkZones(zones: readonly ZoneData[], samples: number): void { + zones.forEach((z, k) => { + const where = `Zone ${k + 1} of the instrument`; + if (!(Number.isInteger(z.sample) && z.sample >= 0 && z.sample < samples)) throw new Error(`${where} names recording ${z.sample}, of 0 … ${samples - 1}.`); + for (const [name, v, lo, hi] of [["key", z.key, 0, 127], ["lo", z.lo, 0, 127], ["hi", z.hi, 0, 127], ["vlo", z.vlo, 0, 127], ["vhi", z.vhi, 0, 127]] as const) { + if (!(Number.isInteger(v) && v >= lo && v <= hi)) throw new Error(`${where}: its ${name} is a whole number ${lo} … ${hi}, not ${v}.`); + } + if (z.lo > z.hi || z.vlo > z.vhi) throw new Error(`${where} plays no key or no strength: keys ${z.lo} … ${z.hi}, strengths ${z.vlo} … ${z.vhi}.`); + if (z.trigger !== undefined && !["attack", "release", "pedal-down", "pedal-up"].includes(z.trigger)) throw new Error(`${where}: its trigger is "attack", "release", "pedal-down" or "pedal-up", not ${JSON.stringify(z.trigger)}.`); + }); +} + +/** One zone of a sampled instrument, as a script gets it: the zone's numbers, and its recording as a clip. */ +export interface Zone extends ZoneData { + readonly clip: Clip; +} + +/** A sampled instrument, as a script gets it (`import piano from "./piano.samples"`). */ +export interface Samples { + readonly __trigscript: "samples"; + readonly name: string; + readonly credit: string; + readonly rate: number; + readonly zones: readonly Zone[]; + /** Seconds of recordings in it, every zone's once. */ + readonly seconds: number; +} + +export const isSamples = (v: unknown): v is Samples => typeof v === "object" && v !== null && (v as Samples).__trigscript === "samples"; + +/** Two 32-bit hashes of some bytes, as 16 hex digits: what a recording's clip is named by. */ +function hashBytes(b: Uint8Array): string { + let a = 0x811c9dc5, c = 0x9747b28c; + const words = Math.floor(b.length / 4), view = new DataView(b.buffer, b.byteOffset, b.byteLength); + for (let i = 0; i < words; i++) { const x = view.getUint32(i * 4, true); a = Math.imul(a ^ x, 0x01000193) >>> 0; c = Math.imul(c ^ x, 0x5bd1e995) >>> 0; c = (c ^ (c >>> 15)) >>> 0; } + for (let i = words * 4; i < b.length; i++) { a = Math.imul(a ^ b[i], 0x01000193) >>> 0; c = Math.imul(c ^ b[i], 0x5bd1e995) >>> 0; } + return a.toString(16).padStart(8, "0") + c.toString(16).padStart(8, "0"); +} + +/** Read a `.samples` file's text. Throws, in words for the person, when it is not one. */ +export function readSamples(text: string): Samples { + let h: Partial; + try { h = JSON.parse(text) as Partial; } catch { throw new Error("This is not a sampled instrument TrigScript made: a .samples file is one line of JSON."); } + if (h?.trigscript !== "samples" || typeof h.data !== "string" || !Array.isArray(h.samples) || !Array.isArray(h.zones)) throw new Error("This is not a sampled instrument TrigScript made."); + if (h.version !== VERSION) throw new Error(`This instrument was written by a newer TrigScript (format ${h.version}); update the plugin to read it.`); + const rate = Number(h.rate); + if (!(Number.isInteger(rate) && rate >= 8000 && rate <= 96000)) throw new Error(`The instrument's rate is 8 000 to 96 000 samples a second, not ${h.rate}.`); + checkZones(h.zones, h.samples.length); + const data = fromBase64(h.data); + let o = 0, seconds = 0; + const clips = h.samples.map((s) => { + const bytes = data.subarray(o, o + s.bytes); + o += s.bytes; + if (bytes.length < s.bytes) throw new Error(`The recording ${s.name} ends too soon: the file is cut short.`); + seconds += s.frames / rate; + return storedClip(`samples:${hashBytes(bytes)}:${s.channels}:${s.frames}:${rate}`, rate, s.frames, s.channels, () => { + const r = new BitReader(bytes); + return Array.from({ length: s.channels }, () => decodeChannel(r, s.frames)); + }); + }); + const zones = h.zones.map((z) => Object.freeze({ ...z, clip: clips[z.sample] })); + return Object.freeze({ + __trigscript: "samples" as const, name: typeof h.name === "string" ? h.name : "", credit: typeof h.credit === "string" ? h.credit : "", + rate, zones: Object.freeze(zones), seconds, + }); +} + +/** The value an import of a `.samples` file gives, kept while the text is the same (a build reads the files each time). */ +const values = new Map(); + +export function samplesValue(text: string): Samples { + const hit = values.get(text); + if (hit) return hit; + const v = readSamples(text); + // Few instruments at a time, and large: the oldest goes when a fifth arrives. + if (values.size >= 4) values.delete(values.keys().next().value!); + values.set(text, v); + return v; +} + +/** What the hover on an import says: "A sampled instrument, Salamander Grand Piano: 241 recordings (12.3 minutes), 263 zones at 44 100 Hz." */ +export function describeSamples(text: string): string { + try { + // The header alone, before the data: a .samples file can be large. + const cut = text.indexOf(',"data":"'); + const h = JSON.parse(cut > 0 ? `${text.slice(0, cut)}}` : text) as Partial; + if (h?.trigscript !== "samples" || !Array.isArray(h.samples) || !Array.isArray(h.zones)) return "This is not a sampled instrument TrigScript made."; + const rate = Number(h.rate), seconds = h.samples.reduce((n, s) => n + s.frames / rate, 0); + return `A sampled instrument${h.name ? `, ${h.name}` : ""}: ${h.samples.length} recording${h.samples.length === 1 ? "" : "s"} (${(seconds / 60).toFixed(1)} minutes), ${h.zones.length} zone${h.zones.length === 1 ? "" : "s"} at ${rate.toLocaleString("en-US")} Hz${h.credit ? `. ${h.credit}` : ""}.`; + } catch (err) { + return err instanceof Error ? err.message : String(err); + } +} + +/** + * A sampled instrument made in the script, from clips it has — imported recordings (`.sound`), or made: `samples([{ + * clip: c3, key: "C3" }, { clip: c4, key: "C4" }])`. Each zone's keys and strengths default to all of them: a note is + * played from the zone whose key is nearest it. `options`: its name and whom to credit. + */ +export function makeSamples(zones: unknown, options?: { readonly name?: string; readonly credit?: string }): Samples { + if (!Array.isArray(zones) || zones.length === 0) throw new Error("samples() takes zones, one at least: samples([{ clip: c4, key: \"C4\" }])."); + const keyOf = (v: unknown, what: string): number => { + if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 127) return v; + if (typeof v === "string") return Math.round(69 + 12 * Math.log2(hertz(v) / 440)); + throw new Error(`${what} is a key: a note's name ("C4") or its number (60), not ${JSON.stringify(v)}.`); + }; + const made = zones.map((z: Record, k) => { + const where = `samples()' zone ${k + 1}`; + if (!z || !isClip(z.clip)) throw new Error(`${where} has no clip: { clip, key: "C4" }.`); + const key = keyOf(z.key, `${where}'s key`); + const data: Record = { ...z, sample: k, key, lo: z.lo === undefined ? 0 : keyOf(z.lo, `${where}'s lo`), hi: z.hi === undefined ? 127 : keyOf(z.hi, `${where}'s hi`), vlo: z.vlo ?? 1, vhi: z.vhi ?? 127 }; + return data as unknown as Zone; + }); + checkZones(made, made.length); + return Object.freeze({ + __trigscript: "samples" as const, name: options?.name ?? "", credit: options?.credit ?? "", rate: made[0].clip.rate, + zones: Object.freeze(made.map((z) => Object.freeze({ ...z }))), seconds: made.reduce((n, z) => n + z.clip.seconds, 0), + }); +} diff --git a/compiler/sound.ts b/compiler/sound.ts index fa8e966..24a1c9b 100644 --- a/compiler/sound.ts +++ b/compiler/sound.ts @@ -19,7 +19,7 @@ * written. IMA ADPCM, PCM and Ogg Vorbis play; Ogg Opus does not. */ import { fromBase64, toBase64 } from "./rangeCoder"; -import { chorus, compressor, curve, echo, echoTail, eq, fmVoice, plate, plateTail, pluckVoice, saturate, seeded, svf, type FilterType, type Points } from "./dsp"; +import { chorus, compressor, curve, echo, echoTail, eq, fmVoice, loudness, plate, plateTail, pluckVoice, saturate, seeded, svf, sympathetic, type FilterType, type Points } from "./dsp"; /** The extension of a sound among a script's files. */ export const SOUND_EXTENSION = ".sound"; @@ -222,6 +222,8 @@ export interface Clip { readonly channels: 1 | 2; /** The loudest sample, 0 … 1 (more than 1 clips when the map's file is written). Reading it works the samples out. */ readonly peak: number; + /** Its loudness in LUFS (ITU-R BS.1770, as EBU R 128 measures a programme). Reading it works the samples out. */ + readonly lufs: number; trim(from: number, to?: number): Clip; gain(factor: number): Clip; fade(inSeconds: number, outSeconds?: number): Clip; @@ -243,6 +245,8 @@ export interface Clip { reverb(options?: { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly mix?: number; readonly dry?: number; readonly width?: number }): Clip; chorus(options?: { readonly speed?: number; readonly depth?: number; readonly mix?: number }): Clip; compress(options?: { readonly threshold?: number; readonly ratio?: number; readonly attack?: number; readonly release?: number; readonly knee?: number; readonly makeup?: number }): Clip; + loudness(lufs: number): Clip; + resonance(options: { readonly pedal: readonly (readonly [number, number])[]; readonly amount?: number; readonly decay?: number }): Clip; } interface ClipInside { @@ -251,6 +255,7 @@ interface ClipInside { channels?: readonly Float32Array[]; compute?: () => readonly Float32Array[]; peak?: number; + lufs?: number; adpcm?: Uint8Array; wav?: boolean; /** The Ogg Vorbis quality it goes in the map at, when it is one (`VORBIS_QUALITY` when not said). */ @@ -394,6 +399,14 @@ export function makeClip(samples: Float32Array | readonly Float32Array[], rate: return lazyClip(rate, frames, chans.length as 1 | 2, () => chans, { channels: chans, ...(adpcm ? { adpcm } : {}), ...(wav ? { wav } : {}) }); } +/** + * A clip of samples kept elsewhere — a recording of a sampled instrument (`samples.ts`) — named by `key`, which says + * what the samples are, so that a check names what is made from it without decoding them. + */ +export function storedClip(key: string, rate: number, frames: number, channels: 1 | 2, compute: () => readonly Float32Array[]): Clip { + return made(key, () => lazyClip(rate, frames, channels, compute)); +} + /** A clip `frames` long whose samples `compute` works out when they are asked for. */ function lazyClip(rate: number, frames: number, channels: 1 | 2, compute: () => readonly Float32Array[], extra: Partial = {}): Clip { if (frames / rate > MAX_SECONDS) throw new Error(`A clip is at most ${MAX_SECONDS / 60} minutes long, not ${(frames / rate / 60).toFixed(1)}.`); @@ -417,6 +430,11 @@ function lazyClip(rate: number, frames: number, channels: 1 | 2, compute: () => } return own.peak; }, + get lufs() { + const own = inside.get(clip)!; + if (own.lufs === undefined) own.lufs = loudness(samplesOf(clip), rate); + return own.lufs; + }, trim(from, to = seconds) { num(from, "trim()'s start"); num(to, "trim()'s end"); if (from < 0 || to > seconds + 1e-9 || to <= from) throw new RangeError(`trim(${from}, ${to}) is not inside the clip, which is ${seconds.toFixed(3)} seconds.`); @@ -574,6 +592,27 @@ function lazyClip(rate: number, frames: number, channels: 1 | 2, compute: () => if (!(num(o.makeup, "compress()'s makeup") >= -24 && o.makeup <= 24)) throw new RangeError(`compress()'s makeup is −24 to 24 dB, not ${o.makeup}.`); return same("compress", o, (cs) => compressor(cs, rate, o)); }, + loudness(target) { + if (!(num(target, "loudness()") >= -70 && target <= 0)) throw new RangeError(`loudness() is LUFS, −70 to 0 (−16 for music heard on its own, −23 for broadcast), not ${target}.`); + return same("loudness", [target], (cs) => { const now = clip.lufs; return Number.isFinite(now) ? cs.map((s) => scale(s, 10 ** ((target - now) / 20))) : cs; }); + }, + resonance(options) { + const pedal = options?.pedal, amount = options?.amount ?? 0.25, decay = options?.decay ?? 3; + if (!Array.isArray(pedal)) throw new Error("resonance() takes the pedal: { pedal: [[down, up], …] } in seconds."); + const ps = pedal.map((p, k) => { + if (!Array.isArray(p) || p.length !== 2 || !(num(p[0], "a pedal's down") >= 0) || !(num(p[1], "a pedal's up") >= p[0])) throw new Error(`resonance()'s pedal ${k + 1} is [down, up], seconds, up after down.`); + return [p[0], p[1]] as [number, number]; + }); + if (!(num(amount, "resonance()'s amount") >= 0 && amount <= 2)) throw new RangeError(`resonance()'s amount is 0 to 2, not ${amount}.`); + if (!(num(decay, "resonance()'s decay") > 0 && decay <= 20)) throw new RangeError(`resonance()'s decay is seconds, more than 0, at most 20, not ${decay}.`); + // As long again as the pedal may still be down at the end, the low strings' ring. + const last = ps.reduce((m, p) => Math.max(m, p[1]), 0), tail = last >= seconds - 1e-9 ? Math.round(decay * 1.5 * rate) : 0; + return derive("resonance", [ps, amount, decay], frames + tail, 2, (cs) => { + const ring = sympathetic(cs, rate, ps, amount, decay, frames + tail); + const dry = cs.length === 1 ? [cs[0], cs[0]] : cs; + return ring.map((r, side) => { for (let i = 0; i < frames; i++) r[i] += dry[side][i]; return r; }); + }); + }, }; inside.set(clip, { frames, compute, ...extra }); return Object.freeze(clip); diff --git a/editor.ts b/editor.ts index ab5d26d..62af008 100644 --- a/editor.ts +++ b/editor.ts @@ -60,10 +60,10 @@ import { DEBUG_STYLE, Debugger, type DebugGameView } from "./debugger"; import type { DebugRecording } from "./compiler/gameDebug"; import type { ScmSimDebugView } from "./vendor/scmSim"; import type { Translate } from "./i18n"; -import { describeMedia, isImageFile, isMediaFile, isNotesFile, isSoundFile } from "./compiler/media"; +import { describeMedia, isImageFile, isMediaFile, isNotesFile, isSamplesFile, isSoundFile } from "./compiler/media"; import { importMedia, showImage, showVideo } from "./videoImport"; import { isSoundSource, showSound } from "./soundImport"; -import { isMidiSource, showNotes } from "./notesImport"; +import { isMidiSource, showNotes, showSamples } from "./notesImport"; export const TEMPLATE = `// TrigScript: ordinary TypeScript that runs when you build. Every trigger() call becomes // one trigger of the map, in order; code inside program(() => { … }) runs in the game. @@ -557,7 +557,7 @@ function createWorkspace(svc: ScriptService, options: OpenOptions, mode: Workspa if (!editor) return; const p = normalizePath(path); if (files[p] === undefined) return; - if (isMediaFile(p)) { (isImageFile(p) ? showImage : isSoundFile(p) ? showSound : isNotesFile(p) ? showNotes : showVideo)(api, t, p, files[p]); return; } + if (isMediaFile(p)) { (isImageFile(p) ? showImage : isSoundFile(p) ? showSound : isNotesFile(p) ? showNotes : isSamplesFile(p) ? showSamples : showVideo)(api, t, p, files[p]); return; } if (!openTabs.includes(p)) openTabs.push(p); editor.show(p); renderFiles(); @@ -664,7 +664,7 @@ function createWorkspace(svc: ScriptService, options: OpenOptions, mode: Workspa const path = node.path; const fixed = path === ENTRY_FILE; const row = el("li", { className: path === active ? "tsd-row tsd-active" : "tsd-row", title: isMediaFile(path) ? `${path}\n${describeMedia(path, files[path])}` : path, onClick: () => openFile(path) }, - isMediaFile(path) ? shell.icon(isImageFile(path) ? "file-media" : isSoundFile(path) ? "unmute" : isNotesFile(path) ? "music" : "device-camera-video") : el("span", { className: "tsd-ts" }, "TS"), + isMediaFile(path) ? shell.icon(isImageFile(path) ? "file-media" : isSoundFile(path) ? "unmute" : isNotesFile(path) || isSamplesFile(path) ? "music" : "device-camera-video") : el("span", { className: "tsd-ts" }, "TS"), el("span", { className: broken.has(path) ? "tsd-name tsd-problem" : "tsd-name" }, node.name), el("span", { className: "tsd-row-actions" }, !fixed ? shell.iconButton({ icon: "edit", title: t("Rename or move…"), run: () => { void renameFile(path); } }).element : undefined, @@ -1834,7 +1834,7 @@ function createWorkspace(svc: ScriptService, options: OpenOptions, mode: Workspa const renameFile = async (path: string) => { if (!editor || path === ENTRY_FILE) return; - const name = await askName(t("Rename {path} to (a folder before the name moves it):", { path }), path, "", isMediaFile(path) ? (isImageFile(path) ? ".image" : isSoundFile(path) ? ".sound" : isNotesFile(path) ? ".notes" : ".video") : ".ts"); + const name = await askName(t("Rename {path} to (a folder before the name moves it):", { path }), path, "", isMediaFile(path) ? (isImageFile(path) ? ".image" : isSoundFile(path) ? ".sound" : isNotesFile(path) ? ".notes" : isSamplesFile(path) ? ".samples" : ".video") : ".ts"); if (!name) return; moveTo(path, name); }; diff --git a/ko.ts b/ko.ts index a2f8dc6..68d5bdd 100644 --- a/ko.ts +++ b/ko.ts @@ -438,6 +438,7 @@ export const KO: Record = { "Stop": "정지", "Rate": "샘플링 속도", "Kept in mono, as the game's own sounds are. A program plays it with playWav(); clips made from it — trim, gain, pitch — are made when the script is built.": "게임의 소리처럼 모노로 저장합니다. program에서 playWav()로 재생하고, 이것으로 만든 클립(trim, gain, pitch)은 스크립트를 빌드할 때 만들어집니다.", + "Import it with import {name} from \"./{file}\", play it with music.sampled({name}).": "import {name} from \"./{file}\"로 가져오고 music.sampled({name})로 연주합니다.", "{seconds} seconds at {rate} Hz{from}. Import it with import {name} from \"./{file}\", play it with playWav({name}).": "{seconds}초, {rate} Hz{from}. import {name} from \"./{file}\"로 가져오고 playWav({name})로 재생합니다.", "{path} is in the script: import {name} from \"./{path}\"; then music.midi({name}, { … }) makes a song of its tracks.": "{path}이(가) 스크립트에 들어갔습니다. import {name} from \"./{path}\"로 가져오면 music.midi({name}, { … })가 그 트랙들로 곡을 만듭니다.", "{tracks} tracks, {notes} notes, {bpm} beats a minute ({time}).": "트랙 {tracks}개, 음표 {notes}개, 분당 {bpm}박 ({time}).", diff --git a/notesImport.ts b/notesImport.ts index 7afab9f..0b0b225 100644 --- a/notesImport.ts +++ b/notesImport.ts @@ -7,6 +7,7 @@ import type { PluginApi } from "@scm-js/plugin-api"; import type { Translate } from "./i18n"; import { readMidi, readNotes, writeNotes, type NotesData } from "./compiler/notes"; +import { describeSamples } from "./compiler/samples"; export const MIDI_FILES = ".mid,.midi,audio/midi,audio/x-midi"; export const isMidiSource = (f: File): boolean => /\.midi?$/i.test(f.name) || f.type === "audio/midi" || f.type === "audio/x-midi"; @@ -176,3 +177,22 @@ export function showNotes(api: PluginApi, t: Translate, path: string, text: stri }, }); } + +/** A `.samples` file of the script (a sampled instrument, made by scripts/make-samples.mts), shown: what it holds, and how a script plays it. */ +export function showSamples(api: PluginApi, t: Translate, path: string, text: string): void { + const w = api.ui.widgets; + const stem = (path.split("/").pop() ?? path).replace(/\.samples$/i, ""); + const name = stem.replace(/[^A-Za-z0-9]+(.)?/g, (_m, c: string | undefined) => (c ? c.toUpperCase() : "")).replace(/^[^A-Za-z_]+/, "") || "piano"; + api.ui.dialog({ + title: path, + size: "md", + mount(body) { + body.append( + w.hint(describeSamples(text)), + w.hint(t("Import it with import {name} from \"./{file}\", play it with music.sampled({name}).", { name, file: path.split("/").pop() ?? path })), + ); + return () => {}; + }, + }); +} + diff --git a/scripts/make-samples.mts b/scripts/make-samples.mts new file mode 100644 index 0000000..befdbb5 --- /dev/null +++ b/scripts/make-samples.mts @@ -0,0 +1,238 @@ +/** + * A sampled instrument for a script (`.samples`, compiler/samples.ts) from recordings on disk: an SFZ instrument's + * regions, or a folder of recordings named by their note ("VlnEns_susVib_A3_v1.wav": A3, the first strength). + * + * npx tsx scripts/make-samples.mts [options] + * npx tsx scripts/make-samples.mts --names [options] + * + * --keys 40-90 only the zones of these keys (MIDI numbers, or names: E2-C7); the pedal's are kept + * --layers 2,4,6 only these strengths of the notes, by number from the softest (1); the ones kept widen to cover the rest + * --seconds 10 each recording cut to this long at most, faded out over its last --fade seconds (1.5) + * --release 0.3 a note's release, seconds, where the instrument says none (--names: 0.3) + * --volume -6 dB on every zone + * --detect --names: each recording's note found from its sound, for names that carry none (timpani) + * --octave 1 --names: the names' octaves moved by this many (VSCO 2 names middle C "C3": --octave 1) + * --pitch T1=41.5,T2=46.8 --names: the pitch (a MIDI number, a fraction for cents) of the recordings whose names hold + * each text — a drum measured by ear or by its spectrum, where --detect is unsure + * --name "…" --credit "…" what the file says it is, and whom to credit + * + * The recordings stay where they are (never in a repository: a sample library is its makers' and is large); the file + * made holds what the build needs, coded without loss. + */ +import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { basename, dirname, join, resolve } from "node:path"; +import { writeSamples, type ZoneData } from "../compiler/samples"; + +const args = process.argv.slice(2); +const option = (name: string) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }; +const flag = (name: string) => args.includes(name); +const positional = args.filter((a, i) => !a.startsWith("--") && !(i > 0 && args[i - 1].startsWith("--") && !["--detect", "--names"].includes(args[i - 1]))); +const byNames = flag("--names"); +const [source, out] = positional; +if (!source || !out) { console.error("usage: make-samples [--keys lo-hi] [--layers 1,3,…] [--seconds s] | --names [--detect]"); process.exit(2); } + +/* ── WAV ── */ + +interface Wav { rate: number; channels: Float32Array[] } +function readWav(path: string): Wav { + const b = readFileSync(path), v = new DataView(b.buffer, b.byteOffset, b.byteLength); + if (b.toString("latin1", 0, 4) !== "RIFF" || b.toString("latin1", 8, 12) !== "WAVE") throw new Error(`${path} is not a WAV file.`); + let at = 12, format = 0, channels = 0, rate = 0, bits = 0, data: [number, number] | null = null; + while (at + 8 <= b.length) { + const id = b.toString("latin1", at, at + 4), size = v.getUint32(at + 4, true); + if (id === "fmt ") { format = v.getUint16(at + 8, true); channels = v.getUint16(at + 10, true); rate = v.getUint32(at + 12, true); bits = v.getUint16(at + 22, true); if (format === 0xfffe) format = v.getUint16(at + 32, true); } + if (id === "data") data = [at + 8, Math.min(size, b.length - at - 8)]; + at += 8 + size + (size & 1); + } + if (!data || !channels) throw new Error(`${path}: no format or no data.`); + const width = bits / 8, frames = Math.floor(data[1] / (width * channels)); + const out = Array.from({ length: channels }, () => new Float32Array(frames)); + for (let i = 0; i < frames; i++) for (let c = 0; c < channels; c++) { + const p = data[0] + (i * channels + c) * width; + out[c][i] = format === 3 ? (bits === 32 ? v.getFloat32(p, true) : v.getFloat64(p, true)) + : bits === 16 ? v.getInt16(p, true) / 32768 + : bits === 24 ? ((b[p] | (b[p + 1] << 8) | (b[p + 2] << 16)) << 8 >> 8) / 8388608 + : bits === 32 ? v.getInt32(p, true) / 2147483648 : (b[p] - 128) / 128; + } + return { rate, channels: out.slice(0, 2) }; +} + +/* ── Notes ── */ + +const SEMI: Record = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 }; +/** A key: a MIDI number, or a name ("c4", "F#3", "Bb2"; 60 is C4). */ +function keyOf(text: string): number { + if (/^-?\d+$/.test(text)) return Number(text); + const m = /^([A-Ga-g])([#b]?)(-?\d)$/.exec(text); + if (!m) throw new Error(`Not a key: ${text}`); + return 12 * (Number(m[3]) + 1) + SEMI[m[1].toLowerCase()] + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0); +} + +/* ── An SFZ instrument's regions ── */ + +interface Region { sample: string; opcodes: Record } +function readSfz(path: string): Region[] { + const text = readFileSync(path, "utf8").replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, ""); + const regions: Region[] = []; + let global: Record = {}, group: Record = {}, current: Record | null = null, control: Record = {}; + let header = ""; + const flush = () => { if (header === "region" && current) regions.push({ sample: current.sample ?? "", opcodes: current }); }; + // Headers and opcodes; a sample's path may hold spaces, up to the next opcode. + const tokens = text.split(/(<\w+>)/); + for (const part of tokens) { + const h = /^<(\w+)>$/.exec(part); + if (h) { + flush(); + header = h[1]; + if (header === "global") global = {}; + if (header === "group" || header === "master") group = {}; + if (header === "control") control = {}; + current = header === "region" ? { ...global, ...group } : null; + continue; + } + const target = header === "region" ? current! : header === "group" || header === "master" ? group : header === "global" ? global : header === "control" ? control : null; + if (!target) continue; + for (const m of part.matchAll(/(\w+)=([\s\S]*?)(?=\s+\w+=|$)/g)) target[m[1]] = m[2].trim(); + } + flush(); + const base = control.default_path ?? ""; + return regions.filter((r) => r.sample).map((r) => ({ ...r, sample: (base + r.sample).replace(/\\/g, "/") })); +} + +function zonesFromSfz(path: string): { files: string[]; zones: ZoneData[] } { + const regions = readSfz(path), files: string[] = [], zones: ZoneData[] = []; + const release = Number(option("--release") ?? 0.3); + for (const r of regions) { + const o = r.opcodes, num = (k: string, d: number) => (o[k] !== undefined ? Number(o[k]) : d); + let trigger: ZoneData["trigger"] = o.trigger === "release" ? "release" : "attack"; + if (o.on_locc64 !== undefined || o.on_hicc64 !== undefined) trigger = Number(o.on_hicc64 ?? 127) >= 64 ? "pedal-down" : "pedal-up"; + const key = o.key !== undefined ? keyOf(o.key) : undefined; + const lo = key ?? (o.lokey !== undefined ? keyOf(o.lokey) : 0), hi = key ?? (o.hikey !== undefined ? keyOf(o.hikey) : 127); + if (trigger === "attack" || trigger === "release") if (lo < 0 || hi < 0) continue; + const centre = o.pitch_keycenter !== undefined ? keyOf(o.pitch_keycenter) : key ?? lo; + let k = files.indexOf(r.sample); + if (k < 0) { files.push(r.sample); k = files.length - 1; } + const zone: ZoneData = { + sample: k, key: Math.max(0, Math.min(127, centre)), lo: Math.max(0, lo), hi: Math.max(0, Math.min(127, hi)), vlo: Math.max(1, num("lovel", 1)), vhi: Math.min(127, num("hivel", 127)), + ...(trigger !== "attack" ? { trigger } : {}), + ...(o.volume !== undefined ? { volume: Number(o.volume) } : {}), + ...(o.amp_veltrack !== undefined ? { veltrack: Number(o.amp_veltrack) / 100 } : {}), + release: o.ampeg_release !== undefined ? Number(o.ampeg_release) : release, + ...(o.rt_decay !== undefined ? { decay: Number(o.rt_decay) } : {}), + ...(o.tune !== undefined ? { tune: Number(o.tune) } : {}), + ...(o.pitch_keytrack !== undefined && Number(o.pitch_keytrack) === 0 ? { pitched: false } : {}), + ...(o.seq_length !== undefined ? { turns: Number(o.seq_length), turn: num("seq_position", 1) } : {}), + ...(o.lorand !== undefined || o.hirand !== undefined ? { chance: [num("lorand", 0), num("hirand", 1)] as const } : {}), + }; + if (trigger === "pedal-down" || trigger === "pedal-up") zones.push({ ...zone, key: 60, lo: 0, hi: 127, pitched: false }); + else zones.push(zone); + } + return { files: files.map((f) => resolve(dirname(path), f)), zones }; +} + +/* ── A folder of recordings named by note ── */ + +/** The note a recording plays, by autocorrelation over 0.1 … 0.6 s of it, its fundamental 40 … 1000 Hz: [key, cents]. */ +function detect(w: Wav): [number, number] { + const x = w.channels[0], from = Math.round(0.1 * w.rate), n = Math.min(Math.round(0.5 * w.rate), x.length - from - 2048); + const lo = Math.floor(w.rate / 1000), hi = Math.ceil(w.rate / 40); + let best = 0, lag = lo; + const r = new Float64Array(hi + 2); + for (let l = lo; l <= hi + 1; l++) { + let s = 0, e1 = 0, e2 = 0; + for (let i = from; i < from + n; i++) { s += x[i] * x[i + l]; e1 += x[i] * x[i]; e2 += x[i + l] * x[i + l]; } + r[l] = s / Math.sqrt(e1 * e2 || 1); + } + // The first lag that comes near the best, so an octave below is not taken for the note. + for (let l = lo; l <= hi; l++) if (r[l] > best) best = r[l]; + for (let l = lo + 1; l <= hi; l++) if (r[l] >= 0.9 * best && r[l] >= r[l - 1] && r[l] >= r[l + 1]) { lag = l; break; } + // Between samples, by the parabola through the peak. + const a = r[lag - 1], b = r[lag], c = r[lag + 1], shift = (a - c) / (2 * (a - 2 * b + c) || 1); + const hz = w.rate / (lag + shift), midi = 69 + 12 * Math.log2(hz / 440), key = Math.round(midi); + return [key, Math.round((midi - key) * 100)]; +} + +function zonesFromNames(folder: string): { files: string[]; zones: ZoneData[] } { + const list = readdirSync(folder).filter((f) => /\.wav$/i.test(f) && statSync(join(folder, f)).isFile()).sort(); + const release = Number(option("--release") ?? 0.3); + type Rec = { file: string; key: number; tune: number; layer: number; turn: number }; + const recs: Rec[] = list.map((f) => { + const stem = f.replace(/\.wav$/i, ""); + const note = /(?:^|[_\s-])([A-G]#?-?\d)(?=[_\s-]|$)/.exec(stem); + const layer = Number(/(?:^|_)v(\d+)(?:_|$)/i.exec(stem)?.[1] ?? 1); + const turn = Number(/(?:^|_)rr(\d+)(?:_|$)/i.exec(stem)?.[1] ?? /_(\d+)$/.exec(stem)?.[1] ?? 1); + let key: number, tune = 0; + const given = (option("--pitch") ?? "").split(",").filter(Boolean).map((p) => p.split("=")).find(([name]) => stem.includes(name)); + if (given) { const midi = Number(given[1]); key = Math.round(midi); tune = Math.round((midi - key) * 100); } + else if (flag("--detect") || !note) { [key, tune] = detect(readWav(join(folder, f))); console.log(`${f}: ${key} ${tune >= 0 ? "+" : ""}${tune} cents`); } + else key = keyOf(note[1]) + 12 * Number(option("--octave") ?? 0); + return { file: join(folder, f), key, tune, layer, turn }; + }); + const keys = [...new Set(recs.map((r) => r.key))].sort((a, b) => a - b); + const zones: ZoneData[] = []; + recs.forEach((r, k) => { + const i = keys.indexOf(r.key); + const lo = i === 0 ? Math.max(0, r.key - 12) : Math.floor((keys[i - 1] + r.key) / 2) + 1, hi = i === keys.length - 1 ? Math.min(127, r.key + 12) : Math.floor((r.key + keys[i + 1]) / 2); + const layers = [...new Set(recs.filter((x) => x.key === r.key).map((x) => x.layer))].sort((a, b) => a - b), li = layers.indexOf(r.layer); + const turns = new Set(recs.filter((x) => x.key === r.key && x.layer === r.layer).map((x) => x.turn)).size; + zones.push({ + sample: k, key: r.key, lo, hi, vlo: li === 0 ? 1 : Math.floor((127 * li) / layers.length) + 1, vhi: Math.floor((127 * (li + 1)) / layers.length), release, + ...(r.tune ? { tune: r.tune } : {}), + ...(turns > 1 ? { turns, turn: [...new Set(recs.filter((x) => x.key === r.key && x.layer === r.layer).map((x) => x.turn))].sort((a, b) => a - b).indexOf(r.turn) + 1 } : {}), + }); + }); + return { files: recs.map((r) => r.file), zones }; +} + +/* ── Choosing, cutting, writing ── */ + +let { files, zones } = byNames ? zonesFromNames(source) : zonesFromSfz(source); +const keys = option("--keys"); +if (keys) { + const [lo, hi] = keys.split("-").map(keyOf); + zones = zones.filter((z) => z.trigger === "pedal-down" || z.trigger === "pedal-up" || (z.hi >= lo && z.lo <= hi)); +} +const layers = option("--layers"); +if (layers) { + const keep = new Set(layers.split(",").map(Number)); + // A layer's number among the strengths of its keys and trigger, from the softest. + const groupOf = (z: ZoneData) => `${z.trigger ?? "attack"}|${z.lo}|${z.hi}`; + const groups = new Map(); + for (const z of zones) { const g = groups.get(groupOf(z)); if (g) g.push(z); else groups.set(groupOf(z), [z]); } + const kept: ZoneData[] = []; + for (const g of groups.values()) { + const levels = [...new Set(g.map((z) => z.vlo))].sort((a, b) => a - b); + // Only the notes' strengths are chosen: the sounds of keys let go and of the pedal stay as they are. + if (levels.length < 2 || (g[0].trigger ?? "attack") !== "attack") { kept.push(...g); continue; } + const chosen = g.filter((z) => keep.has(levels.indexOf(z.vlo) + 1)).sort((a, b) => a.vlo - b.vlo); + // Each kept layer reaches down to the one kept below it; the top one to 127. + const tops = [...new Set(chosen.map((z) => z.vhi))].sort((a, b) => a - b); + for (const z of chosen) { + const t = tops.indexOf(z.vhi); + kept.push({ ...z, vlo: t === 0 ? 1 : tops[t - 1] + 1, vhi: t === tops.length - 1 ? 127 : z.vhi }); + } + } + zones = kept; +} +const volume = Number(option("--volume") ?? 0); +if (volume) zones = zones.map((z) => ({ ...z, volume: (z.volume ?? 0) + volume })); +// Only the recordings the zones kept, renumbered. +const used = [...new Set(zones.map((z) => z.sample))].sort((a, b) => a - b); +zones = zones.map((z) => ({ ...z, sample: used.indexOf(z.sample) })); +const seconds = Number(option("--seconds") ?? 0), fade = Number(option("--fade") ?? 1.5); +let rate = 0; +const samples = used.map((k) => { + const w = readWav(files[k]); + if (rate && w.rate !== rate) throw new Error(`${files[k]} is at ${w.rate} Hz; the others at ${rate}.`); + rate = w.rate; + let chans = w.channels; + if (seconds > 0 && chans[0].length > seconds * rate) { + const n = Math.round(seconds * rate), f = Math.round(Math.min(fade, seconds / 2) * rate); + chans = chans.map((c) => { const o = c.slice(0, n); for (let i = 0; i < f; i++) o[n - f + i] *= Math.cos(((i / f) * Math.PI) / 2) ** 2; return o; }); + } + return { name: basename(files[k]), channels: chans }; +}); +const text = writeSamples({ rate, samples, zones, ...(option("--name") ? { name: option("--name") } : {}), ...(option("--credit") ? { credit: option("--credit") } : {}), source: basename(source) }); +writeFileSync(out, text); +const raw = samples.reduce((n, s) => n + s.channels.length * s.channels[0].length * 2, 0); +console.log(`${out}: ${samples.length} recordings, ${zones.length} zones, ${(samples.reduce((n, s) => n + s.channels[0].length, 0) / rate / 60).toFixed(1)} minutes; ${(text.length / 1048576).toFixed(1)} MB (16-bit would be ${(raw / 1048576).toFixed(1)} MB, in base64 ${((raw * 4) / 3 / 1048576).toFixed(1)}).`); diff --git a/scripts/script-files.mts b/scripts/script-files.mts index 8fa91fe..c8604f8 100644 --- a/scripts/script-files.mts +++ b/scripts/script-files.mts @@ -1,6 +1,6 @@ /** * A script on disk as the compiler takes it: the file itself as main.ts (or main.tsx), and every file it imports by a - * relative path, followed from file to file, under the path it has from the script's folder — videos, images, sounds and notes too. For the + * relative path, followed from file to file, under the path it has from the script's folder — videos, images, sounds, notes and sampled instruments too. For the * probes, whose libraries sit beside them (probes/lib/…). */ import { existsSync, readFileSync } from "node:fs"; @@ -15,10 +15,10 @@ export function scriptFiles(path: string): Record { files[as] = text; for (const m of text.matchAll(/\bfrom\s+["'](\.{1,2}\/[^"']+)["']/g)) { const base = resolve(dirname(file), m[1]); - const found = [base, `${base}.ts`, `${base}.tsx`].find((f) => existsSync(f) && /\.(tsx?|video|image|sound|notes)$/.test(f)); + const found = [base, `${base}.ts`, `${base}.tsx`].find((f) => existsSync(f) && /\.(tsx?|video|image|sound|notes|samples)$/.test(f)); if (!found) continue; // A video, an image, a sound or notes (compiler/media.ts) is taken as it is; nothing in it imports anything. - if (/\.(?:video|image|sound|notes)$/.test(found)) files[relative(root, found).split("\\").join("/")] = readFileSync(found, "utf8"); + if (/\.(?:video|image|sound|notes|samples)$/.test(found)) files[relative(root, found).split("\\").join("/")] = readFileSync(found, "utf8"); else visit(found, relative(root, found).split("\\").join("/")); } }; From c3b49c38a4396f67a82f47301f9241e2ae61f471 Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 14:19:08 -0600 Subject: [PATCH 03/31] music: sampled instruments, and performances that are not on a grid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `music.sampled(set, options)`: each note from the recording nearest its key (moved the few semitones to it, cut to what is heard before it is moved), and among those the one made at its strength; let go, it dies 60 dB over its release and the instrument's release zones play (a piano's damper and its strings settling, quieter the longer the key was held). Instruments may now `strike` a note at a velocity (a pattern's "@" chooses the recording, not only the gain) and play a performance's notes `together`: the sustain pedal holds what is let go and makes its own sound, a key struck again stops the sound before, and `resonance` rings the strings while the pedal is down. `music.perform(options, parts)` reads a score's notation a part at a time: lengths after "/" (dots, triplets), ties, rests, "@" velocities, ' staccato, ! accents, pp … ff and hairpins, "ped" and "*", and bar lines that are checked. A tempo map ([bar, bpm] points, changing evenly between them), holds and a seeded unevenness place every note in seconds. What comes back is the timeline a picture can follow: each note's time, end, key, velocity, part, chord voice, bar, beat and frame; bar starts; the pedal. `music.render` mixes a performance as it mixes a song (parts on one instrument played by it together) and takes `loudness`: LUFS the mix is brought to before the limiter. Songs whose instruments have no `strike` make the same clips as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- compiler/generated/stdlib.ts | 2 +- ledger/sounds/music-perform.ts | 14 + ledger/sounds/music-sampled.ts | 10 + stdlib/music.ts | 532 ++++++++++++++++++++++++++++++++- tests/sampled.test.ts | 216 +++++++++++++ 5 files changed, 757 insertions(+), 17 deletions(-) create mode 100644 ledger/sounds/music-perform.ts create mode 100644 ledger/sounds/music-sampled.ts create mode 100644 tests/sampled.test.ts diff --git a/compiler/generated/stdlib.ts b/compiler/generated/stdlib.ts index a658cf7..f961af5 100644 --- a/compiler/generated/stdlib.ts +++ b/compiler/generated/stdlib.ts @@ -3,7 +3,7 @@ export const STDLIB_SOURCES: Readonly> = { "cutscene": "/**\n * Scenes acted out in the game: the standard library's \"trigscript/cutscene\" (TrigScript 4).\n *\n * import { Camera, walk, line, play, SECOND } from \"trigscript/cutscene\";\n *\n * async function intro(raider: Unit) {\n * const cam = new Camera(raider.x, raider.y);\n * await line(units.JimRaynorMarine, \"Something's moving out there.\", 3 * SECOND);\n * const there = start(walk(raider, 1200, 640)); // the walk goes on while the camera follows\n * await cam.follow(raider, 2 * SECOND);\n * await there;\n * await cam.pan(1600, 400, 2 * SECOND);\n * await cam.shake(12);\n * }\n *\n * program(async () => {\n * const raider = first(unitsAt(locations.Base, { owner: P1, type: units.TerranMarine }));\n * if (!raider) return;\n * const skipped = await play(P1, start(intro(raider))); // Escape skips the rest of it\n * if (skipped) print(\"Skipped.\");\n * });\n *\n * Everything here is what a trigger can do, done a frame at a time: the camera is Center View on a location the library\n * keeps for itself, moved to where the camera should look; a unit walks by a Move order to another; a line is the\n * speaker's portrait talking and the words in the middle of the screen. Places are pixels (32 a tile), (0, 0) the map's\n * top left; time is frames of the game, 24 a second on Fastest (`SECOND`). The camera is the one of the player the\n * program runs as, as Center View's is.\n */\nimport { centerLocation, centerView, reserveLocation, talkingPortrait, print, sleep, frames, nextFrame, keyPressed, type Player, type Task, type Unit, type UnitType } from \"trigscript\";\nimport { easeInOutQuad, easeInQuad, easeOutQuad, easeOutBack } from \"trigscript/math\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nexport const SECOND = 24;\n\nconst VIEW = reserveLocation(\"cutscene: where the camera looks\");\nconst GOAL = reserveLocation(\"cutscene: where a unit is sent\");\n\n/** How a glide speeds up and slows down: evenly, starting slow, ending slow, both, or ending past the mark and back. */\nexport type Ease = \"linear\" | \"in\" | \"out\" | \"inOut\" | \"back\";\n\n/** How far along a glide is at `t` (0 at its start, 1 at its end), as `ease` has it. */\nfunction eased(t: fixed, ease: Ease): fixed {\n if (ease === \"in\") return easeInQuad(t);\n if (ease === \"out\") return easeOutQuad(t);\n if (ease === \"inOut\") return easeInOutQuad(t);\n if (ease === \"back\") return easeOutBack(t);\n return t;\n}\n\n/**\n * The camera of the player the program runs as: where it looks, and how it gets somewhere else. It looks at its first\n * place as soon as it is made.\n */\nexport class Camera {\n /** The point the camera is centred on, in pixels. */\n x: number;\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /** Look at a point, now. */\n look(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /**\n * Glide to a point over `time` frames, looking at each place on the way a frame at a time.\n * @param ease How it speeds up and slows down; \"inOut\" unless it says.\n */\n async pan(x: number, y: number, time: number, ease: Ease = \"inOut\") {\n const fromX = this.x;\n const fromY = this.y;\n let i = 1;\n while (i <= time) {\n const k = eased(fixed(i) / time, ease);\n this.look(fromX + Math.round((x - fromX) * k), fromY + Math.round((y - fromY) * k));\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n\n /** Keep a unit in the middle of the screen for `time` frames, or until it is gone. */\n async follow(u: Unit, time: number) {\n let i = 0;\n while (i < time && u) {\n this.look(u.x, u.y);\n await nextFrame();\n i++;\n }\n }\n\n /** Shake for `time` frames, `size` pixels each way (8 unless it says), and settle where it was. */\n async shake(time: number, size: number = 8) {\n const x = this.x;\n const y = this.y;\n let i = 0;\n while (i < time) {\n const left = (i % 4) < 2;\n const up = (i % 2) === 0;\n centerLocation(VIEW, left ? x - size : x + size, up ? y - size : y + size);\n centerView(VIEW);\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n}\n\n/**\n * Send a unit to a point by a Move order, and wait until it is there — within `near` pixels (48 unless it says) — or\n * `limit` frames have passed (30 seconds unless it says), or it is gone.\n * @returns Whether it got there.\n */\nexport async function walk(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"move\", near, limit);\n}\n\n/** The same with an Attack order: the unit fights what it meets on the way. */\nexport async function charge(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"attack\", near, limit);\n}\n\nasync function go(u: Unit, x: number, y: number, how: \"move\" | \"attack\", near: number, limit: number): Promise {\n centerLocation(GOAL, x, y);\n u.order(how, GOAL);\n let waited = 0;\n while (u && Math.abs(u.x - x) + Math.abs(u.y - y) > near && waited < limit) {\n await nextFrame();\n waited++;\n }\n return !!u && Math.abs(u.x - x) + Math.abs(u.y - y) <= near;\n}\n\n/**\n * Send every unit of a group to a point together, and wait until each is there, gone, or `limit` frames have passed.\n * @returns How many got there.\n */\nexport async function walkAll(group: Unit[], x: number, y: number, near: number = 64, limit: number = 30 * SECOND): Promise {\n centerLocation(GOAL, x, y);\n for (const u of group) if (u) u.order(\"move\", GOAL);\n let waited = 0;\n let there = 0;\n while (waited < limit) {\n there = 0;\n let moving = 0;\n for (const u of group) {\n if (!u) continue;\n if (Math.abs(u.x - x) + Math.abs(u.y - y) <= near) there++;\n else moving++;\n }\n if (moving === 0) break;\n await nextFrame();\n waited++;\n }\n return there;\n}\n\n/**\n * A line of the scene: the speaker's portrait talks and the words show in the middle of the screen, for `time` frames\n * (3 seconds unless it says), and then the scene goes on.\n */\nexport async function line(speaker: UnitType, text: string, time: number = 3 * SECOND) {\n talkingPortrait(speaker, Math.round((time * 1000) / SECOND));\n print(text, { position: \"center\" });\n await sleep(frames(time));\n}\n\n/**\n * Play a scene, started as a task (`start(intro())`), for a player who may skip it: when they press `key` (Escape unless\n * it says) the scene stops where it is. Put things where the scene would have left them when it gives true.\n * @returns Whether it was skipped.\n */\nexport async function play(player: Player, scene: Task, key: \"Escape\" | \"Space\" | \"Enter\" = \"Escape\"): Promise {\n while (scene.running) {\n if (keyPressed(player, key)) {\n scene.cancel();\n return true;\n }\n await nextFrame();\n }\n return false;\n}\n", "fog": "/**\n * Fog of war as a picture: the standard library's \"trigscript/fog\" (TrigScript 4).\n *\n * import { fog } from \"trigscript/fog\";\n *\n * const heart = fog.picture([\".##.##.\", \"#######\", \".#####.\", \"..###..\"]);\n *\n * program(async () => {\n * fog.reveal(P1); // the whole map lit once: from now on dark is fog, not black\n * while (true) {\n * fog.light(P1, 30, 20, 5); // a disc of size 5 around tile (30, 20), this frame only\n * fog.light(P1, 60, 40, heart); // a picture, its top left on tile (60, 40)\n * await nextFrame();\n * }\n * });\n *\n * The fog is a canvas that starts every frame dark: what a program lights this frame is what shows this frame, and\n * nothing else needs doing. There is no dark brush — the game's sight only ever reveals — so dark is whatever is not\n * lit; to draw dark shapes, light around them (a picture with `{ ink: \"dark\" }`). Dark is also the sharper ink: a lit\n * part is at least a brush wide (3 tiles across, 4 down), while a dark line one tile wide stays exactly that. Nothing\n * else needs doing — the library writes the game's vision countdown after every frame (memory.vision.countdown), so\n * the next frame starts from a wiped board. Watch it on the minimap. With Classic graphics (Options > Graphics) a tile\n * of the map is a pixel there, sharp; Remastered graphics blurs it a few tiles wide.\n *\n * What the board is made of decides how far apart lit and fog look. Remastered draws a tile on the minimap as the\n * average of its art and fog as 0.64 of lit, whatever the tile, so the brightest art is the best board there: plain\n * Ice snow (lit 130 against fog 82, measured 2026-10-19). Classic draws a tile as one colour of its own; Badlands\n * tile 23778 is the widest apart there, and dim and textured in Remastered. Snow played the better of the two.\n *\n * How it draws, played in StarCraft: Remastered (2026-10-17): a brush is a unit made on a tile and taken away in the\n * same trigger pass; the tiles its sight revealed stay lit through the frame. A brush's size is the unit's sight\n * range, so each size is a unit type of its own — the flying heroes below, which no ordinary map places — whose sight\n * is set every frame (Remastered takes a sight write a frame late, so one type cannot change size within a frame).\n * Coordinates are tiles, (0, 0) the map's top left. About 800 brushes a frame is the most the game makes: it keeps a\n * removed unit's place until the next frame.\n */\nimport { game, program, sleep, frames, stats, units, createUnit, removeUnit, centerLocation, reserveLocation, memory, cover, nextFrame, type Player, type UnitType, type Video } from \"trigscript\";\n\n/**\n * Each brush's shape, sizes 1 to 11: the tiles a flying unit of that sight range reveals, read out of the game.\n * \"@\" is the tile the brush is centred on. The game's air sight leaves the centre's row one short below, so every\n * shape reaches a row further up than down.\n */\nexport const SHAPES: readonly (readonly string[])[] = [\n // 1\n [\"###\", \"###\", \"#@#\", \"###\"],\n // 2\n [\".###.\", \"#####\", \"#####\", \"##@##\", \"#####\", \"#####\"],\n // 3\n [\"..###..\", \"#######\", \"#######\", \"#######\", \"###@###\", \"#######\", \"#######\", \"#######\"],\n // 4\n [\"..#####...\", \".#######..\", \"#########.\", \"##########\", \"##########\", \"####@#####\", \"##########\", \"##########\", \"#########.\", \".#######..\", \"......#...\"],\n // 5\n [\"...#####....\", \"..#######...\", \".#########..\", \"###########.\", \"############\", \"############\", \"#####@######\", \"############\", \"############\", \"###########.\", \".#########..\", \"..#######...\", \".......#....\"],\n // 6\n [\"....#####.....\", \"..#########...\", \".###########..\", \"#############.\", \"#############.\", \"##############\", \"##############\", \"######@#######\", \"##############\", \"##############\", \"#############.\", \"#############.\", \".###########..\", \"..#########...\", \"........#.....\"],\n // 7\n [\".....#####......\", \"...#########....\", \"..###########...\", \".#############..\", \"###############.\", \"###############.\", \"################\", \"################\", \"#######@########\", \"################\", \"################\", \"###############.\", \"###############.\", \".#############..\", \"..###########...\", \"...#########....\", \".........#......\"],\n // 8\n [\"......#####.......\", \"....#########.....\", \"..#############...\", \".###############..\", \".###############..\", \"#################.\", \"#################.\", \"##################\", \"##################\", \"########@#########\", \"##################\", \"##################\", \"#################.\", \"#################.\", \".###############..\", \".###############..\", \"..#############...\", \"....#########.....\", \"..........#.......\"],\n // 9\n [\"......#######.......\", \"....###########.....\", \"...#############....\", \"..###############...\", \".#################..\", \"###################.\", \"###################.\", \"####################\", \"####################\", \"####################\", \"#########@##########\", \"####################\", \"####################\", \"####################\", \"###################.\", \"###################.\", \".#################..\", \"..###############...\", \"...#############....\", \"....###########.....\", \"........#####.......\"],\n // 10\n [\".......#######........\", \".....###########......\", \"....#############.....\", \"..#################...\", \"..#################...\", \".###################..\", \"#####################.\", \"#####################.\", \"######################\", \"######################\", \"######################\", \"##########@###########\", \"######################\", \"######################\", \"######################\", \"#####################.\", \"#####################.\", \".###################..\", \"..#################...\", \"..#################...\", \"....#############.....\", \".....###########......\", \".........#####........\"],\n // 11\n [\"........#######.........\", \"......###########.......\", \"....###############.....\", \"...#################....\", \"..###################...\", \".#####################..\", \".#####################..\", \"#######################.\", \"#######################.\", \"########################\", \"########################\", \"########################\", \"###########@############\", \"########################\", \"########################\", \"########################\", \"#######################.\", \"#######################.\", \".#####################..\", \".#####################..\", \"..###################...\", \"...#################....\", \"....###############.....\", \"......###########.......\", \"..........#####.........\"],\n];\n\n/** Each size's unit, size 1 first: flying heroes without a sight upgrade. A map that places one gets odd sight from it. */\nconst BRUSHES: readonly UnitType[] = [\n units.KukulzaMutalisk, units.KukulzaGuardian, units.YggdrasillOverlord, units.MagellanScienceVessel,\n units.GantrithorCarrier, units.HyperionBattlecruiser, units.NoradIIBattlecruiser, units.TomKazanskyWraith,\n units.DanimothArbiter, units.MojoScout, units.ArtanisScout,\n];\n\n/** Where each brush is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"fog: where each brush is made\");\n\n/**\n * One disc: the tiles a brush of `size` covers (SHAPES), centred on tile (x, y). What light() does with a size. A brush\n * is a unit made where SPOT is and taken away again at once; each branch makes its own size's, so that the unit type\n * of the action is known when the script is built (one given by the program costs writing it into the action).\n */\nconst disc = game((player: Player, x: number, y: number, size: number) => {\n discPx(player, x * 32 + 16, y * 32 + 16, size);\n});\n\n/**\n * disc() in pixels, (px, py) the centre of the tile: what a caller with many brushes uses, its products by 32 worked\n * out once and the brushes' offsets added (a product by 32 of a number the game holds is a test a bit, about 0.4 µs).\n */\nconst discPx = game((player: Player, px: number, py: number, size: number) => {\n centerLocation(SPOT, px, py, 32, 32);\n switch (size) {\n case 0: case 1: createUnit(player, BRUSHES[0], 1, SPOT); removeUnit(player, BRUSHES[0]); break;\n case 2: createUnit(player, BRUSHES[1], 1, SPOT); removeUnit(player, BRUSHES[1]); break;\n case 3: createUnit(player, BRUSHES[2], 1, SPOT); removeUnit(player, BRUSHES[2]); break;\n case 4: createUnit(player, BRUSHES[3], 1, SPOT); removeUnit(player, BRUSHES[3]); break;\n case 5: createUnit(player, BRUSHES[4], 1, SPOT); removeUnit(player, BRUSHES[4]); break;\n case 6: createUnit(player, BRUSHES[5], 1, SPOT); removeUnit(player, BRUSHES[5]); break;\n case 7: createUnit(player, BRUSHES[6], 1, SPOT); removeUnit(player, BRUSHES[6]); break;\n case 8: createUnit(player, BRUSHES[7], 1, SPOT); removeUnit(player, BRUSHES[7]); break;\n case 9: createUnit(player, BRUSHES[8], 1, SPOT); removeUnit(player, BRUSHES[8]); break;\n case 10: createUnit(player, BRUSHES[9], 1, SPOT); removeUnit(player, BRUSHES[9]); break;\n default: createUnit(player, BRUSHES[10], 1, SPOT); removeUnit(player, BRUSHES[10]);\n }\n});\n\n/**\n * Light the whole map once, so that from now on a tile left dark shows as fog (grey) rather than as never seen\n * (black) — every picture then has the same two tones. Takes one frame.\n * @param player Whose fog: P1 … P8, known when the script is built.\n */\nexport const reveal = game((player: Player) => {\n const width = memory.map.width;\n const height = memory.map.height;\n // Size 11 is 23 tiles wide: a brush every 14 tiles leaves no gap, and one more past the end, kept inside, reaches the edge.\n for (let y = 2; y < height + 12; y += 14) {\n for (let x = 2; x < width + 12; x += 14) disc(player, Math.min(x, width - 3), Math.min(y, height - 3), 11);\n }\n});\n\n/**\n * Light a rectangle of tiles for this frame, worked out while the game runs: its top left on tile (x, y), `width`\n * tiles across and `height` down. Every one of the five may change from frame to frame — the walls of a raycaster, a\n * bar of a chart. It is exact from 3 × 4 up (the smallest brush); a thinner one is lit a brush wide, centred.\n *\n * fog.rect(P1, 10, 20, 3, wall); // a column 3 tiles wide, `wall` tall\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of its left edge.\n * @param y The row of its top edge.\n * @param width How many tiles across.\n * @param height How many tiles down.\n */\nexport const rect = game((player: Player, x: number, y: number, width: number, height: number) => {\n if (width < 1 || height < 1) return;\n // Size 1 is 3 tiles across and 4 down, its centre the middle column and the third row: a grid of them, the last\n // column and row moved back to end on the edge (overlapping the one before), covers the rectangle exactly.\n const right = Math.max(x + width - 2, x + 1);\n const bottom = Math.max(y + height - 2, y + 2);\n // (The brush made here, not through disc(): its unit type is then known when the script is built, which makes the\n // action a constant — a size from the program costs a branch and a written field a brush.)\n let cy = y + 2;\n while (true) {\n let cx = x + 1;\n while (true) {\n centerLocation(SPOT, cx * 32 + 16, cy * 32 + 16, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (cx >= right) break;\n cx = Math.min(cx + 3, right);\n }\n if (cy >= bottom) break;\n cy = Math.min(cy + 4, bottom);\n }\n});\n\n/** A picture for the fog, made when the script is built: its size in tiles and the brushes that draw it. */\nexport interface Picture {\n readonly width: number;\n readonly height: number;\n readonly brushes: readonly { readonly x: number; readonly y: number; readonly size: number }[];\n}\n\n/**\n * A picture from rows of text, worked out when the script is built: `#` is the ink, anything else is not.\n *\n * fog.picture([\"..##..\", \".####.\", \"######\"]) // light ink: the # tiles are lit\n * fog.picture([\"..##..\", \".####.\", \"######\"], { ink: \"dark\" }) // dark ink: the # tiles stay dark, the rest is lit\n *\n * With light ink a lit part thinner than a brush (3 tiles across, 4 down) is drawn a tile or two thicker. An image's\n * halftone (`fog.picture(photo.halftone(6))`) is drawn with the brushes it was made of, one a cell. With dark\n * ink every tile of the picture's rectangle that is not `#` is lit and the `#` tiles keep their shape exactly,\n * however thin — the ink for line art and silhouettes.\n */\nexport function picture(rows: readonly string[], options: { readonly ink?: \"light\" | \"dark\" } = {}): Picture {\n const height = rows.length;\n const width = Math.max(0, ...rows.map((r) => r.length));\n // An image's halftone (image.halftone(6)) comes with the brushes that drew it: a brush a cell, as they are.\n const drawn = (rows as { readonly brushes?: readonly { readonly x: number; readonly y: number; readonly shape: number }[] }).brushes;\n if (drawn && options.ink !== \"dark\") return Object.freeze({ width, height, brushes: Object.freeze(drawn.map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }))) });\n // Dark ink: the picture's rectangle lit but for the # tiles, so what is covered is the rest.\n const ink = options.ink === \"dark\" ? Array.from({ length: height }, (_, y) => Array.from({ length: width }, (_, x) => (rows[y][x] === \"#\" ? \".\" : \"#\")).join(\"\")) : rows;\n const brushes = cover(ink, SHAPES).map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }));\n return Object.freeze({ width, height, brushes: Object.freeze(brushes) });\n}\n\n/**\n * A video's frames as brushes, worked out when the script is built: a word a brush (x | y << 8 | size << 16), the\n * frames one after another, and where each one starts — the tables the game reads a frame from. Once a build.\n */\ninterface Film { readonly words: readonly number[]; readonly starts: readonly number[] }\nconst films = new Map();\nfunction film(video: Video): Film {\n const had = films.get(video);\n if (had) return had;\n const words: number[] = [], starts: number[] = [0];\n for (const brushes of cover(video, SHAPES)) {\n for (const b of brushes) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n starts.push(words.length);\n }\n const made = { words, starts };\n films.set(video, made);\n return made;\n}\n\n/**\n * Light the fog for this frame: a disc, a picture or a frame of a video. Tiles count from the map's top left, (0, 0).\n *\n * fog.light(P1, 30, 20, 5); // a disc of size 5 centred on tile (30, 20)\n * fog.light(P1, 60, 40, heart); // a picture (fog.picture), its top left on tile (60, 40)\n * fog.light(P1, 0, 0, badApple, f); // frame f of a video the script imports, its top left on tile (0, 0)\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The tile's column: a disc's centre, a picture's left edge.\n * @param y The tile's row: a disc's centre, a picture's top edge.\n * @param shape A size, 1 (3 tiles wide) to 11 (23 wide) — it may change while the game runs — a picture, or a video.\n * @param frame Of a video, which frame, from 0: it may change while the game runs. Past the end, nothing is lit.\n */\nexport const light = game((player: Player, x: number, y: number, shape: number | Picture | Video, frame: number = 0) => {\n if (typeof shape === \"number\") disc(player, x, y, shape);\n else {\n // The picture's corner in pixels once; each brush is its offset from there (a constant of a picture).\n const px = x * 32 + 16, py = y * 32 + 16;\n if (\"brushes\" in shape) for (const b of shape.brushes) discPx(player, px + b.x * 32, py + b.y * 32, b.size);\n else {\n const { words, starts } = film(shape);\n const end = starts[frame + 1];\n for (let i = starts[frame]; i < end; i++) {\n const w = words[i];\n // (A row's offset in pixels straight from its byte: the same as ((w >> 8) & 255) * 32, and the shift only has\n // the byte's eight bits to look at.)\n discPx(player, px + (w & 255) * 32, py + ((w & 0xff00) >> 3), w >> 16);\n }\n }\n }\n});\n\n/**\n * Play a video in the fog, a frame of it every frame of the game, from its first to its last; resolves when it ends.\n * Inside an async program: `await fog.play(P1, badApple)`. On Fastest a game frame is 42 ms, which is what Import\n * Video makes a video's frames by default; the game runs a little slower when a frame is heavy, and so does the video.\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param video A video the script imports.\n * @param x The column of its left edge, 0 by default.\n * @param y The row of its top edge, 0 by default.\n */\nexport const play = game(async (player: Player, video: Video, x: number = 0, y: number = 0) => {\n // (A while: a for over a length known when the script is built would be unrolled, a copy of the body a frame.)\n let f = 0;\n while (f < video.length) {\n light(player, x, y, video, f);\n await nextFrame();\n f++;\n }\n});\n\n/**\n * How fog.columns() lays its columns out, known when the script is built: `count` columns side by side, each `width`\n * tiles across (3, a brush's width, by default) and up to `height` tiles tall, centred on the middle row. `ink`:\n * \"light\" lights each column (the walls of a raycaster bright, on fog), \"dark\" lights all but the columns (dark walls\n * between a lit ceiling and floor); dark is cheaper when columns fill most of the board, light when they are short.\n */\nexport interface ColumnLayout {\n readonly count: number;\n readonly height: number;\n readonly width?: number;\n readonly ink?: \"light\" | \"dark\";\n /**\n * How the walls are told apart, with fog.columns()'s `faces`. \"outline\", the default: every wall drawn as its edges —\n * its top and bottom, a brush deep, and a column lit whole wherever one face meets another (on the nearer of the\n * two) — so that blocks read as boxes, the look of the raycasters of monochrome screens; with dark ink, the edges are\n * lit lines through dark walls. A few brushes a column. Chosen over the rest when played (2026-10-17).\n *\n * The others shade the faces whose number is odd (a raycaster's other side) and leave the rest whole: \"hollow\" —\n * dark, lit only along its top and bottom edges; \"ribbed\" — hollow and lit across the middle of each half; \"panelled\"\n * — hollow and lit across its quarters; \"line\" / \"lines\" — dark lines a tile thick across it at its middle or its\n * quarters (the finest, and two dozen brushes a column near the eye: for a view with room to spare).\n */\n readonly shading?: \"outline\" | \"lines\" | \"line\" | \"hollow\" | \"ribbed\" | \"panelled\";\n}\n\n/**\n * What fog.columns() reads, worked out once a layout when the script is built: for each level of the drawing that is\n * wider than a column (all the columns, a group of them, the last group) and each depth from 0 to half the height, the\n * brushes that cover a rectangle that wide and that deep exactly — the encoder's covers (cover()), a few large brushes\n * in the middle and small ones at the edges. A brush is a word, dx | dy << 8 | size << 16 from the rectangle's top\n * left; `starts` says where each (level, depth) begins.\n */\ninterface ColumnPlan { readonly words: readonly number[]; readonly starts: readonly number[]; readonly group: number; readonly half: number }\nconst columnPlans = new Map();\nconst COLUMN_GROUP = 6;\nfunction columnPlan(layout: ColumnLayout): ColumnPlan {\n const width = layout.width ?? 3, half = layout.height >> 1, group = Math.min(COLUMN_GROUP, layout.count);\n const key = `${layout.count}:${width}:${half}`;\n const had = columnPlans.get(key);\n if (had) return had;\n const words: number[] = [], starts: number[] = [];\n for (const columns of [layout.count, group, layout.count % group || group]) {\n for (let depth = 0; depth <= half; depth++) {\n starts.push(words.length);\n if (depth === 0) continue;\n // A rectangle shallower than a brush is drawn a brush deep, the rest of it on what the level before lit.\n const rows = Array.from({ length: Math.max(depth, 4) }, () => \"#\".repeat(columns * width));\n for (const b of cover(rows, SHAPES)) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n }\n }\n starts.push(words.length);\n const made = { words, starts, group, half };\n columnPlans.set(key, made);\n return made;\n}\n\n/**\n * One rectangle of fog.columns() wider than a column: the cover at `at` (a level and a depth) drawn twice, the half\n * above the middle and the half below, its top rows `top` and `bottom`, from column `x`.\n */\nconst columnRect = game((player: Player, words: readonly number[], starts: readonly number[], at: number, x: number, top: number, bottom: number) => {\n let i = starts[at];\n const end = starts[at + 1];\n // In pixels once; each brush is its offset (a few bits, a few tests) from there.\n const px = x * 32 + 16, pt = top * 32 + 16, pb = bottom * 32 + 16;\n while (i < end) {\n const w = words[i];\n const dx = (w & 255) * 32, dy = (w & 0xff00) >> 3, size = w >> 16;\n discPx(player, px + dx, pt + dy, size);\n discPx(player, px + dx, pb + dy, size);\n i++;\n }\n});\n\n/**\n * One column's part of fog.columns(), in pixels: brushes (3 × 4) a column of 4 rows apart and the last moved back to\n * end on the edge, twice — from `pt` and from `pb`, the centres of the first brush of each — down a column `k32`\n * pixels deep (32 a row; under 4 rows, a brush deep), centred on `px`. What the smallest brush covers exactly, worked out\n * here rather than read: it is the most common rectangle by far. In pixels because the caller has them, stepped: a\n * product by 32 of a number the game holds is a test a bit, about 0.4 µs, where a step is an add.\n */\nconst columnBarPx = game((player: Player, px: number, pt: number, pb: number, k32: number) => {\n // How far down the last brush is from the first.\n const end = Math.max(k32, 128) - 128;\n let r = 0;\n while (true) {\n centerLocation(SPOT, px, pt, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n centerLocation(SPOT, px, pb, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (r >= end) break;\n const step = Math.min(end - r, 128);\n r += step;\n pt += step;\n pb += step;\n }\n});\n\n/** columnBarPx() in tiles: `k` rows from row `top` down and from row `bottom` down, centred on column `x`. */\nconst columnBar = game((player: Player, x: number, top: number, bottom: number, k: number) => {\n columnBarPx(player, x * 32 + 16, top * 32 + 80, bottom * 32 + 80, k * 32);\n});\n\n/**\n * A shaded column of fog.columns() (ColumnLayout's `shading`): `a` is half its height, `lines` how many lines across\n * each half — 0 hollow, 1 at its middle, 3 at its quarters. A line is a dark row through a lit column (light ink), or\n * a lit band a brush deep through a dark one; a column too short for its lines is drawn plain.\n */\nconst columnShaded = game((player: Player, cx: number, mid: number, a: number, dark: boolean, lines: number) => {\n if (lines <= 0) {\n if (dark) { if (a >= 6) columnBar(player, cx, mid - 4, mid, 4); }\n else if (a < 8) columnBar(player, cx, mid - a, mid, a);\n else {\n // Hollow: the edges. Ribbed (-1) and panelled (-3): bands across each half too, centred on its middle or\n // quarters, where there is room for them between the edges.\n columnBar(player, cx, mid - a, mid + a - 4, 4);\n const ribs = -lines;\n if (ribs > 0 && a >= 6 * (ribs + 1)) {\n let k = 1;\n while (k <= ribs) {\n const at = (a * k) / (ribs + 1);\n columnBar(player, cx, mid - at - 2, mid + at - 2, 4);\n k++;\n }\n }\n }\n } else if (a < 5 * (lines + 1)) {\n if (!dark) columnBar(player, cx, mid - a, mid, a);\n } else {\n // From the middle out: lit up to each line, the line's row dark (light ink); or a lit band on each line (dark ink).\n let from = 0, k = 1;\n while (k <= lines + 1) {\n const to = k > lines ? a : (a * k) / (lines + 1);\n if (dark) { if (k <= lines) columnBar(player, cx, mid - to - 2, mid + to - 2, 4); }\n else columnBar(player, cx, mid - to, mid + from, to - from);\n from = to + 1;\n k++;\n }\n }\n});\n\n/**\n * Light columns for this frame — the walls of a raycaster, a bar chart — each as tall as the program says, centred on\n * the layout's middle row. The covers are worked out when the script is built (see ColumnLayout), so a frame costs a\n * brush for each part of the picture that differs from its neighbours, not one for every few tiles: a wall that fills\n * the board is a few large brushes.\n *\n * const VIEW = { count: 42, height: 96, ink: \"dark\" } as const;\n * fog.columns(P1, 1, 0, VIEW, heights); // heights: one a column, in tiles, the program's\n * fog.columns(P1, 1, 0, VIEW, heights, faces); // faces: which face of which wall each column shows\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of the layout's left edge.\n * @param y The row of its top edge.\n * @param layout How the columns are laid out: known when the script is built.\n * @param heights Each column's height in tiles (0 to the layout's height), an array of the program's.\n * @param faces Which face of which wall each column shows, a number the same for every column of one face — in a\n * raycaster, \\`(mapY * width + mapX) * 2 + side\\` — an array of the program's as long as `heights`: what the\n * layout's `shading` tells walls apart by. Optional: without it, every column is lit whole (a bar chart).\n */\nexport const columns = game((player: Player, x: number, y: number, layout: ColumnLayout, heights: readonly number[], faces?: readonly number[]) => {\n const { words, starts, half, group } = columnPlan(layout);\n const count = layout.count, width = layout.width ?? 3, dark = layout.ink === \"dark\";\n // (Dark lines through a lit column count up; lit bands through a dark one, ribbed and panelled, down.)\n // (Without faces there is nothing to tell apart, and every column is whole.)\n const outline = faces !== undefined && (layout.shading === undefined || layout.shading === \"outline\");\n const lines = layout.shading === \"lines\" ? 3 : layout.shading === \"line\" ? 1 : layout.shading === \"ribbed\" ? -1 : layout.shading === \"hollow\" ? 0 : -3;\n const span = half + 1;\n // Each column's depth from where its lit part starts: the middle row for light ink, the top and bottom for dark.\n // A shaded column of light ink is drawn on its own, after the rest: to the rest it is as if it were not there — and\n // so is every column of a light outline, which is all edges.\n const depth: number[] = new Array(count).fill(0);\n // Half of each column's height, at most half the layout's: worked out once. (Clamped before the shift, the same\n // number: the shift then has the few bits the clamp leaves, where a height from the program could have any.)\n const halves: number[] = new Array(count).fill(0);\n // And in pixels (32 a row), for the bars, which place their brushes in pixels: a small number times 32 is a few tests.\n const halves32: number[] = new Array(count).fill(0);\n let least = half, most = 0;\n // (A light outline is all edges: every depth is 0, nothing to work out.)\n const flat = !dark && outline;\n if (flat) least = 0;\n let i = 0;\n while (i < count) {\n const a = Math.min(Math.max(heights[i], 0), 2 * half + 1) >> 1;\n halves[i] = a;\n halves32[i] = a * 32;\n if (!flat) {\n let d = dark ? half - a : a;\n if (faces !== undefined && !dark && !outline && (faces[i] & 1) != 0) d = 0;\n depth[i] = d;\n if (d < least) least = d;\n if (d > most) most = d;\n }\n i++;\n }\n // A rectangle from depth p, k deep, starts on the rows above and below the middle (light) or below the top and above\n // the bottom (dark); one shallower than 4 is drawn 4 deep, reaching back over what is lit already.\n const mid = y + half;\n // Every column, from depth 0 to the least.\n if (least > 0) {\n const k = Math.max(least, 4);\n if (dark) columnRect(player, words, starts, least, x, y + least - k, y + 2 * half - least);\n else columnRect(player, words, starts, least, x, mid - least, mid + least - k);\n }\n // Each group of columns, from the least to the group's least; then each column, from there to its own. (Nothing,\n // when every column's depth is the least: a light outline's always.)\n let g = most > least ? 0 : count;\n while (g < count) {\n const last = Math.min(g + group, count);\n let gl = half;\n let j = g;\n while (j < last) { if (depth[j] < gl) gl = depth[j]; j++; }\n const level = last - g === group ? 1 : 2;\n if (gl > least) {\n const k = gl - least, kk = Math.max(k, 4);\n if (dark) columnRect(player, words, starts, level * span + k, x + g * width, y + gl - kk, y + 2 * half - gl);\n else columnRect(player, words, starts, level * span + k, x + g * width, mid - gl, mid + gl - kk);\n }\n j = g;\n while (j < last) {\n const k = depth[j] - gl;\n if (k > 0) {\n const kk = Math.max(k, 4), cx = x + j * width + 1;\n if (dark) columnBar(player, cx, y + depth[j] - kk, y + 2 * half - depth[j], k);\n else columnBar(player, cx, mid - depth[j], mid + depth[j] - kk, k);\n }\n j++;\n }\n g = last;\n }\n if (outline) {\n // Where one face meets another, the nearer (taller) of the two columns is an edge.\n const edge: number[] = new Array(count).fill(0);\n let face = faces[0], tall = heights[0];\n i = 1;\n while (i < count) {\n const f = faces[i], h = heights[i];\n if (f != face) { if (h >= tall) edge[i] = 1; else edge[i - 1] = 1; }\n face = f;\n tall = h;\n i++;\n }\n // The bars in pixels: a column's centre stepped across, the middle row's worked out once.\n const mid80 = mid * 32 + 80;\n let px = (x + 1) * 32 + 16;\n i = 0;\n while (i < count) {\n const a = halves[i], a32 = halves32[i];\n if (dark) { if (edge[i] != 0 && a >= 2) columnBarPx(player, px, mid80 - a32, mid80, a32); }\n else if (a > 0) {\n if (edge[i] != 0 || a < 8) columnBarPx(player, px, mid80 - a32, mid80, a32);\n else columnBarPx(player, px, mid80 - a32, mid80 + a32 - 128, 128);\n }\n px += width * 32;\n i++;\n }\n } else if (faces !== undefined) {\n i = 0;\n while (i < count) {\n if ((faces[i] & 1) != 0) columnShaded(player, x + i * width + 1, mid, halves[i], dark, lines);\n i++;\n }\n }\n});\n\n/**\n * Keep what was lit this frame on the board for `n` frames, and wait them out: \\`await fog.show(2)\\` in place of\n * \\`await nextFrame()\\` draws every other frame at half the cost. StarCraft: Remastered redraws the fog on the minimap\n * every other frame (measured in two played recordings, 2026-10-17), so a picture drawn every other frame looks the\n * same there as one drawn every frame. The board is wiped at the start of the frame after them, ready for the next.\n *\n * @param n How many frames, 1 to 24, known when the script is built.\n */\nexport const show = game(async (n: number) => {\n memory.vision.countdown = n;\n await sleep(frames(n));\n});\n\n/** Everything above as one name: import { fog } from \"trigscript/fog\"; fog.light(P1, x, y, 3). */\nexport const fog = { light, rect, columns, show, play, reveal, picture, SHAPES };\n\n/** The longest fog.show() keeps a picture: the countdown the game sets itself after a wipe is longer than this. */\nconst SHOW_MOST = 24;\n\n// The canvas: every brush's sight set, every frame, and the board wiped on the next — for as long as the game runs —\n// unless a program asked for the picture to stay (fog.show), when the countdown is that program's to run down.\nprogram(() => {\n while (true) {\n for (let s = 1; s <= 11; s++) stats(BRUSHES[s - 1]).sight = s;\n const left = memory.vision.countdown;\n if (left == 0 || left > SHOW_MOST) memory.vision.countdown = 1;\n sleep(frames(1));\n }\n});\n", "math": "/**\n * Numbers for motion and play: the standard library's \"trigscript/math\" (TrigScript 4).\n *\n * import { Vec, lerp, easeOutQuad, distance, angleTo, approach, wrap } from \"trigscript/math\";\n *\n * const t = fixed(frame) / 48; // 0 to 1 over two seconds\n * const x = lerp(fromX, toX, easeOutQuad(t)); // eased from one place to another\n * const v = Vec.fromAngle(angleTo(x, y, tx, ty), fixed(4));\n * pos = pos.add(v);\n *\n * Fractions are the language's fixed numbers (16.16: four decimal places or so, from about −32 768 to 32 767): a\n * number becomes one when a fraction is stored into it, or written `fixed(…)`. Angles are radians, as JavaScript's are.\n * Whole numbers stay whole where they can — `distanceSq`, `manhattan`, `wrap`, `sign` — and cost less.\n */\n\n/** π, and a whole turn. */\nexport const PI = Math.PI;\nexport const TAU = Math.PI * 2;\n\n/** From a to b by t: a at 0, b at 1, between them in between (t outside 0 … 1 goes past). */\nexport function lerp(a: fixed, b: fixed, t: fixed): fixed {\n return a + (b - a) * t;\n}\n\n/** Where v is from a to b, as lerp's t: 0 at a, 1 at b. */\nexport function inverseLerp(a: fixed, b: fixed, v: fixed): fixed {\n return b === a ? fixed(0) : (v - a) / (b - a);\n}\n\n/** v from the range a1 … b1 into a2 … b2. */\nexport function remap(v: fixed, a1: fixed, b1: fixed, a2: fixed, b2: fixed): fixed {\n return lerp(a2, b2, inverseLerp(a1, b1, v));\n}\n\n/** t kept inside 0 … 1. */\nexport function clamp01(t: fixed): fixed {\n return t < 0 ? fixed(0) : t > 1 ? fixed(1) : t;\n}\n\n/** From `current` towards `target` by at most `step`, never past it: a value that follows another at a speed. */\nexport function approach(current: number, target: number, step: number): number {\n if (current < target) return current + step > target ? target : current + step;\n return current - step < target ? target : current - step;\n}\n\n/** n into 0 … size − 1, going round: wrap(-1, 10) is 9, wrap(12, 10) is 2. */\nexport function wrap(n: number, size: number): number {\n return ((n % size) + size) % size;\n}\n\n/** −1, 0 or 1, by whether n is below, at or above zero. */\nexport function sign(n: number): number {\n return n > 0 ? 1 : n < 0 ? -1 : 0;\n}\n\n/** The distance from one point to another, as the crow flies. */\nexport function distance(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.hypot(x2 - x1, y2 - y1);\n}\n\n/** The distance squared: whole, and cheaper — compare it with a range squared. */\nexport function distanceSq(x1: number, y1: number, x2: number, y2: number): number {\n return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n}\n\n/** The distance along the axes, |dx| + |dy|: what the game's own \"nearest\" goes by. */\nexport function manhattan(x1: number, y1: number, x2: number, y2: number): number {\n return Math.abs(x2 - x1) + Math.abs(y2 - y1);\n}\n\n/** The angle from one point to another, in radians from −π to π: 0 is to the right (east), π / 2 down (south, y grows down). */\nexport function angleTo(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.atan2(y2 - y1, x2 - x1);\n}\n\n/** Degrees as radians. */\nexport function radians(degrees: fixed): fixed {\n return (degrees * PI) / 180;\n}\n\n/** Radians as degrees. */\nexport function degrees(radians: fixed): fixed {\n return (radians * 180) / PI;\n}\n\n/* Easing: t from 0 to 1, how far along a motion is at that point of its time — slow then fast, fast then slow, … */\n\n/** Slow at the start. */\nexport function easeInQuad(t: fixed): fixed {\n return t * t;\n}\n\n/** Slow at the end. */\nexport function easeOutQuad(t: fixed): fixed {\n return t * (2 - t);\n}\n\n/** Slow at both ends. */\nexport function easeInOutQuad(t: fixed): fixed {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n}\n\n/** Slower at the start than easeInQuad. */\nexport function easeInCubic(t: fixed): fixed {\n return t * t * t;\n}\n\n/** Slower at the end than easeOutQuad. */\nexport function easeOutCubic(t: fixed): fixed {\n const u = t - 1;\n return u * u * u + 1;\n}\n\n/** Goes a little past the end and comes back. */\nexport function easeOutBack(t: fixed): fixed {\n const u = t - 1;\n return 1 + 2.70158 * u * u * u + 1.70158 * u * u;\n}\n\n/** Slow at both ends, smoothly (Hermite: 3t² − 2t³). */\nexport function smoothstep(t: fixed): fixed {\n return t * t * (3 - 2 * t);\n}\n\n/**\n * A point, or a direction and a length: two fixed numbers. Each operation gives a new Vec.\n *\n * let pos = new Vec(fixed(x), fixed(y));\n * const toward = new Vec(fixed(tx), fixed(ty)).sub(pos).normalized().scale(fixed(3));\n * pos = pos.add(toward);\n */\nexport class Vec {\n x: fixed;\n y: fixed;\n\n constructor(x: fixed, y: fixed) {\n this.x = x;\n this.y = y;\n }\n\n /** A direction `length` long at `angle` radians (0 to the right, π / 2 down). */\n static fromAngle(angle: fixed, length: fixed): Vec {\n return new Vec(Math.cos(angle) * length, Math.sin(angle) * length);\n }\n\n add(o: Vec): Vec {\n return new Vec(this.x + o.x, this.y + o.y);\n }\n\n sub(o: Vec): Vec {\n return new Vec(this.x - o.x, this.y - o.y);\n }\n\n scale(k: fixed): Vec {\n return new Vec(this.x * k, this.y * k);\n }\n\n dot(o: Vec): fixed {\n return this.x * o.x + this.y * o.y;\n }\n\n /** How long it is. */\n length(): fixed {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n }\n\n /** The same direction, 1 long (or none, for none). */\n normalized(): Vec {\n const l = this.length();\n const k: fixed = l === 0 ? fixed(0) : 1 / l;\n return new Vec(this.x * k, this.y * k);\n }\n\n /** Its angle, in radians from −π to π. */\n angle(): fixed {\n return Math.atan2(this.y, this.x);\n }\n\n /** Turned by `angle` radians (clockwise on the map, where y grows down). */\n rotate(angle: fixed): Vec {\n const c = Math.cos(angle);\n const s = Math.sin(angle);\n return new Vec(this.x * c - this.y * s, this.x * s + this.y * c);\n }\n\n /** How far it is from another point. */\n distanceTo(o: Vec): fixed {\n return this.sub(o).length();\n }\n\n /** From this towards another by t (0 here, 1 there). */\n lerp(o: Vec, t: fixed): Vec {\n return new Vec(this.x + (o.x - this.x) * t, this.y + (o.y - this.y) * t);\n }\n}\n", - "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n}\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n};\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n const base = (n: Score) => n.hit ?? (n.track.instrument as Instrument).note(n.name!, n.seconds!);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, n.velocity === 1 ? base(n) : base(n).gain(n.velocity)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song, options: { readonly rate?: number; readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number }; readonly reverb?: ReverbOptions; readonly master?: (mix: Clip) => Clip } = {}): Clip {\n const rate = options.rate ?? 44100, score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => { const c = n.hit ?? (t.instrument as Instrument).note(n.name!, n.seconds!, rate); return n.velocity === 1 ? c : c.gain(n.velocity); };\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (sends.length) {\n const r = options.reverb ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n mixed = mixdown(parts, least, rate);\n }\n if (options.master) mixed = options.master(mixed);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => { const c = n.hit ?? (t.instrument as Instrument).note(n.name!, n.seconds!, rate); return n.velocity === 1 ? c : c.gain(n.velocity); };\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", + "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false;\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one.\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) { if (order[j].at < off) { off = order[j].at; stolen = true; } break; }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, stolen ? 0.12 : releaseOf(z), rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n if (releases) for (const [down, up] of pedal) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n};\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n for (const { part } of inside.parts) {\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) throw new Error(\"render(): the performance plays no notes.\");\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", "random": "/**\n * Chance: the standard library's \"trigscript/random\" (TrigScript 4).\n *\n * import { chance, range, pick, shuffle, weighted, Random } from \"trigscript/random\";\n *\n * if (chance(25)) dropLoot(); // one time in four\n * const lane = range(1, 3); // 1, 2 or 3\n * const boss = pick(BOSSES); // any one of a list\n * shuffle(order); // an array of the program, in place\n * const tier = weighted([70, 25, 5]); // 0 most of the time, 2 rarely\n *\n * const rng = new Random(seed); // the same numbers every time for the same seed\n * const x = rng.range(0, 63);\n *\n * The functions use the game's own random numbers, which every player's game draws alike, so nothing goes out of step\n * in a game of several players. `Random` is a generator of your own (xorshift), seeded: the same seed gives the same\n * numbers, game after game — a level made from a seed, a save code that holds one.\n */\nimport { random } from \"trigscript\";\n\n/** True `percent` times in a hundred (25: one time in four). */\nexport function chance(percent: number): boolean {\n return random(100) < percent;\n}\n\n/** A whole number from `min` to `max`, both included. */\nexport function range(min: number, max: number): number {\n return min + random(max - min + 1);\n}\n\n/** The total of `count` dice of `sides` sides each (3, 6: from 3 to 18). */\nexport function dice(count: number, sides: number): number {\n let total = 0;\n let i = 0;\n while (i < count) { total += 1 + random(sides); i++; }\n return total;\n}\n\n/** One of a list, any one alike; a list the script has, or an array of the program (the first's 0 when it is empty). */\nexport function pick(items: readonly T[]): T {\n return items[random(items.length)];\n}\n\n/** The place of one of the weights, each as likely as its share of their total: [70, 25, 5] gives 0 most of the time. */\nexport function weighted(weights: readonly number[]): number {\n let total = 0;\n for (const w of weights) total += w;\n let roll = random(total);\n let i = 0;\n while (i < weights.length) {\n if (roll < weights[i]) return i;\n roll -= weights[i];\n i++;\n }\n return weights.length - 1;\n}\n\n/** An array of the program in a random order, in place (Fisher–Yates: every order alike). */\nexport function shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = random(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n}\n\n/**\n * A generator of random numbers of your own, seeded: the same seed gives the same numbers, in the game and when the\n * script is tested. Make it in the program (`const rng = new Random(1234)`).\n */\nexport class Random {\n state: number;\n\n /** Seeded with any whole number (0 is taken as 1). */\n constructor(seed: number) {\n this.state = seed === 0 ? 1 : seed;\n }\n\n /** The next number, from 0 to 2 147 483 647. */\n next(): number {\n let x = this.state;\n x ^= x << 13;\n x ^= x >>> 17;\n x ^= x << 5;\n this.state = x;\n return x & 0x7fffffff;\n }\n\n /** A whole number from 0 to n − 1. */\n int(n: number): number {\n return this.next() % n;\n }\n\n /** A whole number from `min` to `max`, both included. */\n range(min: number, max: number): number {\n return min + this.int(max - min + 1);\n }\n\n /** True `percent` times in a hundred. */\n chance(percent: number): boolean {\n return this.int(100) < percent;\n }\n\n /** One of a list, any one alike. */\n pick(items: readonly T[]): T {\n return items[this.int(items.length)];\n }\n\n /** An array of the program in a random order, in place. */\n shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = this.int(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n }\n}\n", "screen": "/**\n * Pixel screens: the standard library's \"trigscript/screen\" (TrigScript 4).\n *\n * import { Screen, ScreenView, sprite } from \"trigscript/screen\";\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n *\n * program(async () => {\n * const screen = new Screen(4, 4, 24, 16); // 24 × 16 pixels, its corner on tile (4, 4)\n * let x = 10;\n * while (true) {\n * screen.clear();\n * screen.rect(0, 15, 24, 1, 5); // the ground, in colour 5\n * screen.blit(SHIP, x, 12);\n * screen.number(score, 1, 1, 2); // digits 3 × 5 pixels, in colour 2\n * screen.present(); // on the map, and so on the minimap (screen.reveal(P1) once first)\n * await nextFrame();\n * }\n * });\n *\n * A screen is a grid of pixels, each 0 (empty) or a colour from 1 to 7; drawing changes the grid, and `present()`\n * shows it: a pixel is a unit on the map, owned by the player whose colour it is, so the minimap shows the picture —\n * neighbouring pixels of one colour join into a solid block there. Only the pixels that changed since the last\n * `present()` are made or taken away, and only the pixels drawn since are looked at, so a still picture costs nothing to\n * show. Draw through the methods (`set`, `clear`, `rect`, …): a pixel written into `pixels` directly is not seen. The same grid can be shown in a\n * player's text lines too, as squares (`ScreenView` in a `ui.lines` view): one game, two screens, as the Tetris probe has it.\n *\n * A player sees the pixels only where they have vision: `screen.reveal(P1)` once gives them Map Revealers over it.\n *\n * Two looks (the constructor's last argument): \"dots\", Overlords, which fly — the minimap draws each as a dot with a gap\n * round it, the screen may be over Space; and \"solid\", Pylons, which the minimap draws as their whole two-tile\n * footprint, so pixels side by side are one block — on buildable ground (probes/lib/screen-map.mts --ground).\n *\n * What the map needs, found playing the unit-pixel probe in StarCraft: Remastered (2026-10-16): the owners of the\n * pixels (P3, P4, P5, P1, P6, P7, P8 below; their colours are theirs on the map, so give them the colours of TEXT_COLORS) must not\n * be computers — a computer moves its own units — and Remastered will not start a game without a computer, so one slot\n * (P2 here) is a computer that owns no pixel. A pixel is an Overlord, which sits on any ground and on nothing else; keep\n * the screen's tiles clear of buildings. A Pylon needs buildable ground, and none of the map's own units in the way. About 80 pixels made and taken away in a frame did not slow the game.\n */\nimport { centerLocation, createUnit, removeUnitAt, reserveLocation, textColors, units, P1, P3, P4, P5, P6, P7, P8, type Player } from \"trigscript\";\n\n/**\n * Whose units show colours 1 to 7 on the map, in the order of TEXT_COLORS: give each player that colour in the map\n * (cyan, yellow, purple, green, red, blue, orange). Green is P1's — your own units are green on the minimap anyway.\n * Not computers.\n */\nexport const OWNERS: readonly Player[] = [P3, P4, P5, P1, P6, P7, P8];\n/** The same colours in the text lines (`ScreenView`), 0 an empty square: cyan, yellow, purple, green, red, blue, orange. */\nexport const TEXT_COLORS: readonly number[] = [0, textColors.cyan, textColors.yellow, textColors.purple, textColors.green, textColors.red, textColors.blue, textColors.orange];\n\n/** Where each pixel's unit is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"screen: where each pixel is made\");\n\n/** A picture known when the script is built, to `blit` onto a screen: its size, and its pixels a row at a time (0 is see-through). */\nexport interface Sprite { readonly width: number; readonly height: number; readonly cells: readonly number[] }\n\n/**\n * A sprite from rows of text, when the script is built: \"1\" … \"7\" a pixel of that colour, anything else see-through.\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n */\nexport function sprite(rows: readonly string[]): Sprite {\n const width = Math.max(0, ...rows.map((r) => r.length));\n const cells: number[] = [];\n for (const row of rows) for (let x = 0; x < width; x++) { const c = Number(row[x]); cells.push(c >= 1 && c <= 7 ? c : 0); }\n return { width, height: rows.length, cells };\n}\n\n/** The digits 0 to 9, three pixels wide and five high, for `number()`: each fifteen pixels, a row at a time. */\nconst DIGITS: readonly number[] = [\n \"111101101101111\", \"010110010010111\", \"111001111100111\", \"111001111001111\", \"101101111001001\",\n \"111100111001111\", \"111100111101111\", \"111001001010010\", \"111101111101111\", \"111101111001111\",\n].flatMap((d) => d.split(\"\").map(Number));\n\n/** The most pixels a screen has: 32 × 32 at two tiles a pixel covers a 64 × 64 map, 64 × 32 half of a 128 × 128 one. */\nexport const MAX_PIXELS = 2048;\n\nexport class Screen {\n /** The picture being drawn: a colour a pixel, a row at a time (the first width × height of them). */\n pixels: number[] = new Array(MAX_PIXELS).fill(0);\n /** What the map shows now: the picture as it was at the last `present()`. */\n shown: number[] = new Array(MAX_PIXELS).fill(0);\n /** The pixels drawn a colour they were not since the last `present()`, in order: each one's place and its x and y. */\n drawnAt: number[] = new Array(MAX_PIXELS).fill(0);\n drawnX: number[] = new Array(MAX_PIXELS).fill(0);\n drawnY: number[] = new Array(MAX_PIXELS).fill(0);\n drawn = 0;\n /** More drawn than the list holds: `present()` looks at every pixel instead. */\n overflow = false;\n x: number;\n y: number;\n width: number;\n height: number;\n cell: number;\n /** The unit a pixel is: an Overlord (\"dots\"), or a Pylon (\"solid\"). */\n unit = 0;\n\n /**\n * A screen `width` × `height` pixels (MAX_PIXELS at most), its top left corner on tile (x, y) of the map, a pixel two\n * tiles across.\n * @param look \"dots\" (the default): a pixel is an Overlord, which the minimap draws as a dot, a gap round it — it flies,\n * so the screen may be over anything, Space too. \"solid\": a pixel is a Pylon, which the minimap draws as its whole\n * footprint, two tiles square, so pixels side by side are one block — it needs buildable ground under the screen,\n * and gives its owner Protoss supply. (Overlords a tile apart do not fit: the game will not place most of them.)\n */\n constructor(x: number, y: number, width: number, height: number, look: \"dots\" | \"solid\" = \"dots\") {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.cell = 64;\n this.unit = look === \"solid\" ? units.ProtossPylon : units.ZergOverlord;\n }\n\n /** Every pixel the colour (0, empty, unless it says). */\n clear(color: number = 0) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.put(i, x, y, color); i++; x++; }\n y++;\n }\n }\n\n /** One pixel; nothing happens outside the screen. */\n set(x: number, y: number, color: number) {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) this.put(y * this.width + x, x, y, color);\n }\n\n /** A pixel written, and listed for `present()` when its colour changed. */\n private put(i: number, x: number, y: number, color: number) {\n if (this.pixels[i] === color) return;\n this.pixels[i] = color;\n if (this.drawn < MAX_PIXELS) {\n this.drawnAt[this.drawn] = i;\n this.drawnX[this.drawn] = x;\n this.drawnY[this.drawn] = y;\n this.drawn++;\n } else this.overflow = true;\n }\n\n /** The colour of a pixel; 0 outside the screen. */\n get(x: number, y: number): number {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) return this.pixels[y * this.width + x];\n return 0;\n }\n\n /** A filled rectangle, its top left at (x, y); what is outside the screen is left out. */\n rect(x: number, y: number, width: number, height: number, color: number) {\n let j = 0;\n while (j < height) {\n let i = 0;\n while (i < width) { this.set(x + i, y + j, color); i++; }\n j++;\n }\n }\n\n /** A line from (x0, y0) to (x1, y1), both ends drawn. */\n line(x0: number, y0: number, x1: number, y1: number, color: number) {\n const dx = Math.abs(x1 - x0);\n const dy = -Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx + dy;\n let x = x0;\n let y = y0;\n while (true) {\n this.set(x, y, color);\n if (x === x1 && y === y1) break;\n const e2 = 2 * err;\n if (e2 >= dy) { err += dy; x += sx; }\n if (e2 <= dx) { err += dx; y += sy; }\n }\n }\n\n /** A sprite with its top left at (x, y): its see-through pixels leave what is under them. */\n blit(s: Sprite, x: number, y: number) {\n let k = 0;\n let j = 0;\n while (j < s.height) {\n let i = 0;\n while (i < s.width) {\n const c = s.cells[k];\n if (c !== 0) this.set(x + i, y + j, c);\n k++;\n i++;\n }\n j++;\n }\n }\n\n /** A whole number's digits, 3 × 5 pixels each with a pixel between, its top left at (x, y): a score on the minimap. */\n number(n: number, x: number, y: number, color: number) {\n let rest = n < 0 ? -n : n;\n let count = 1;\n let probe = rest;\n while (probe >= 10) { probe = Math.floor(probe / 10); count++; }\n let place = x + (count - 1) * 4;\n while (true) {\n const d = rest % 10;\n let k = 0;\n while (k < 15) {\n if (DIGITS[d * 15 + k] === 1) this.set(place + (k % 3), y + Math.floor(k / 3), color);\n k++;\n }\n rest = Math.floor(rest / 10);\n place -= 4;\n if (rest === 0) break;\n }\n }\n\n /**\n * Let a player see the screen: Map Revealers of theirs over it, for the rest of the game. Without them its pixels,\n * owned by other players, are hidden by the fog of war — on the map and on the minimap. Once, before the first\n * `present()`.\n * @param player Who sees it: P1 … P8, known when the script is built.\n */\n reveal(player: Player) {\n // A Map Revealer sees ten tiles round; one every six tiles leaves no gap.\n const right = this.x * 32 + this.width * this.cell;\n const bottom = this.y * 32 + this.height * this.cell;\n let py = this.y * 32 + 96;\n while (py < bottom + 96) {\n let px = this.x * 32 + 96;\n while (px < right + 96) {\n centerLocation(SPOT, px, py, 32, 32);\n createUnit(player, units.MapRevealer, 1, SPOT);\n px += 192;\n }\n py += 192;\n }\n }\n\n /**\n * The picture on the map: each pixel that changed since the last time taken away and made again in its colour. Only\n * the pixels drawn since are looked at (one drawn and drawn back is passed over), unless more were drawn than the list\n * holds.\n */\n present() {\n if (this.overflow) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.show(i, x, y); i++; x++; }\n y++;\n }\n this.overflow = false;\n } else {\n for (let k = 0; k < this.drawn; k++) this.show(this.drawnAt[k], this.drawnX[k], this.drawnY[k]);\n }\n this.drawn = 0;\n }\n\n /** One pixel on the map as it is in the picture, when it is not already. */\n private show(i: number, x: number, y: number) {\n const now = this.pixels[i];\n const was = this.shown[i];\n if (now === was) return;\n const half = this.cell >> 1;\n centerLocation(SPOT, this.x * 32 + x * this.cell + half, this.y * 32 + y * this.cell + half, 32, 32);\n OWNERS.forEach((owner, k) => { if (was === k + 1) removeUnitAt(owner, this.unit, 1, SPOT); });\n OWNERS.forEach((owner, k) => { if (now === k + 1) createUnit(owner, this.unit, 1, SPOT); });\n this.shown[i] = now;\n }\n}\n\n/**\n * A screen in the text lines, a square a pixel — filled in its colour, or empty — a line a row. For a `ui.lines` view:\n * ``, the screen's size known when the script is built. Eleven lines\n * show at once, sixty squares across.\n */\nexport function ScreenView({ screen, width, height }: { screen: Screen; width: number; height: number }) {\n return <>{UP_TO_60.map((y) => y < height && {UP_TO_60.map((x) => x < width && )})};\n}\n\n/** 0 … 59: the places a view's rows and columns are counted over, the ones past its size left out when the script is built. */\nconst UP_TO_60: readonly number[] = Array.from({ length: 60 }, (_, i) => i);\n", "signals": "/**\n * Events of your own: the standard library's \"trigscript/signals\" (TrigScript 4).\n *\n * import { Signal } from \"trigscript/signals\";\n *\n * const waveCleared = new Signal();\n *\n * program(async () => {\n * waveCleared.on((wave) => { setResources(P1, \"add\", 100 * wave, \"ore\"); }); // braces: a handler gives back no action\n * waveCleared.once((wave) => print(`First wave down!`));\n * const id = waveCleared.on((wave) => print(`Wave ${wave} cleared`));\n * …\n * waveCleared.emit(3); // every handler, in the order they were added\n * waveCleared.off(id);\n * });\n *\n * A signal lets one part of a map say that something happened without knowing who listens: the shop, the score and the\n * music each add a handler, and the wave code only emits. What it carries is one value of the type it is made with —\n * a number, a boolean, a text or a unit (`new Signal()`). Its handlers are functions kept as values: they may use\n * what the block they were written in has, and they run to their end, one after another, within the frame.\n *\n * Make a signal inside the program that uses it (`const s = new Signal()` at its top): a signal is variables\n * of a program, as anything a program writes is.\n */\n\nexport class Signal {\n /** The handlers, by the number `on` gave; one taken off is undefined, and its place is given to the next one added. */\n handlers: (((value: T) => void) | undefined)[] = [];\n /** Which handlers go once they have run once. */\n onceOnly: boolean[] = [];\n\n /**\n * Add a handler: it runs at every `emit`, handed the value.\n * @returns Its number, for `off`.\n */\n on(handler: (value: T) => void): number {\n return this.add(handler, false);\n }\n\n /** Add a handler that runs at the next `emit` only. @returns Its number, for `off` before then. */\n once(handler: (value: T) => void): number {\n return this.add(handler, true);\n }\n\n /** Take a handler off, by the number `on` or `once` gave. */\n off(id: number) {\n if (id >= 0 && id < this.handlers.length) this.handlers[id] = undefined;\n }\n\n /** Run every handler, in the order they were added, each handed `value`. */\n emit(value: T) {\n let i = 0;\n while (i < this.handlers.length) {\n const h = this.handlers[i];\n if (h) {\n if (this.onceOnly[i]) this.handlers[i] = undefined;\n h(value);\n }\n i++;\n }\n }\n\n /** How many handlers it has. */\n count(): number {\n let n = 0;\n for (const h of this.handlers) if (h) n++;\n return n;\n }\n\n /** Take every handler off. */\n clear() {\n let i = 0;\n while (i < this.handlers.length) { this.handlers[i] = undefined; i++; }\n }\n\n private add(handler: (value: T) => void, once: boolean): number {\n // A place one was taken off from, or a new one at the end.\n let i = 0;\n while (i < this.handlers.length) {\n if (!this.handlers[i]) {\n this.handlers[i] = handler;\n this.onceOnly[i] = once;\n return i;\n }\n i++;\n }\n this.handlers.push(handler);\n this.onceOnly.push(once);\n return this.handlers.length - 1;\n }\n}\n", diff --git a/ledger/sounds/music-perform.ts b/ledger/sounds/music-perform.ts new file mode 100644 index 0000000..e70c762 --- /dev/null +++ b/ledger/sounds/music-perform.ts @@ -0,0 +1,14 @@ +// ledger: step 5, takes +// A performance (`music.perform`): notes at their own times — lengths, dynamics, the pedal, a tempo that slows — each +// struck when its time comes, rendered into one clip; `lufs` read and `loudness` set when the script is built. +import { music } from "trigscript/music"; +const keys = music.synth({ wave: "triangle", volume: 0.3 }); +const take = music.perform({ meter: "3/8", bpm: 120, pickup: "1/8", tempo: [[1, 120], [2, 96]] }, { + right: { instrument: keys, notes: ["pp E5/16 D#5", "E5 D#5 E5 B4 D5 C5", "A4/4."] }, + left: { instrument: keys, notes: ["r/8", "r/4.", "ped A2/16 E3 A3 r/8. *"] }, +}); +const mix = music.render(take, { loudness: -18 }); +const rung = mix.resonance({ pedal: take.pedal }); +program(async () => { + playWav(mix.lufs < -17 ? rung : mix, 0); +}); diff --git a/ledger/sounds/music-sampled.ts b/ledger/sounds/music-sampled.ts new file mode 100644 index 0000000..319dbf5 --- /dev/null +++ b/ledger/sounds/music-sampled.ts @@ -0,0 +1,10 @@ +// ledger: step 5, takes +// A sampled instrument (`music.sampled`) from clips the script makes (`samples()`): each note from the zone nearest +// its key, struck at the strength "@" says; a song rendered. +import { music } from "trigscript/music"; +const low = tone("C3", 1, { volume: 0.4 }).fade(0, 0.5), high = tone("C5", 1, { volume: 0.2 }).fade(0, 0.5); +const keys = music.sampled(samples([{ clip: low, key: "C3" }, { clip: high, key: "C5" }], { name: "Two tones" })); +const tune = music.song({ bpm: 120 }, music.track(keys, "C3 E3@0.5 G4 C5@1.2")); +program(async () => { + playWav(music.render(tune), 0); +}); diff --git a/stdlib/music.ts b/stdlib/music.ts index 1c55aff..0c834c7 100644 --- a/stdlib/music.ts +++ b/stdlib/music.ts @@ -54,7 +54,7 @@ * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing, * nothing to change while it plays. A program plays to its own player; a program for each player plays to each. */ -import { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes } from "trigscript"; +import { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from "trigscript"; /** Seconds a frame lasts on Fastest, the speed a map is played at. */ const FRAME = 0.042; @@ -69,8 +69,22 @@ export interface Instrument { * second, for an instrument that makes its notes (render asks for 44 100). */ note(name: string, seconds: number, rate?: number): Clip; + /** + * The note struck at `velocity` — a pattern's "@", 1 as written — for an instrument whose strength changes more than + * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter. + */ + strike?(name: string, seconds: number, velocity: number, rate?: number): Clip; + /** + * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal — + * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its + * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time. + */ + together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip; } +/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */ +export interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number } + /** What plays a pattern's letters: a clip a letter. */ export interface Kit { readonly kind: "kit"; @@ -206,6 +220,160 @@ export function strings(options: { readonly brightness?: number; readonly decay? }); } +/** How a sampled instrument (`sampled`) plays. */ +export interface SampledOptions { + /** How loud, 1 as recorded. */ + readonly volume?: number; + /** The velocity (1 … 127) a pattern's note strikes at "@1", as written (100, as `midi` reads a file's). */ + readonly velocity?: number; + /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */ + readonly release?: number; + /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */ + readonly releases?: boolean; + /** + * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's. + * Only in a performance (`perform`), which has a pedal. + */ + readonly resonance?: number; + /** Seconds the strings ring with the pedal down (3). */ + readonly ring?: number; + /** Semitones every note is moved by (0). */ + readonly transpose?: number; +} + +/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */ +const velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2; +const dB = (x: number) => 10 ** (x / 20); + +/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */ +function zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] { + const of = zones.filter((z) => (z.trigger ?? "attack") === trigger); + if (of.length === 0) return []; + // The nearest keys first: the zones that play the key, or else those whose range is closest to it. + const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0); + const near = Math.min(...of.map(keyGap)); + const keyed = of.filter((z) => keyGap(z) === near); + const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0); + const best = Math.min(...keyed.map(velGap)); + return keyed.filter((z) => velGap(z) === best); +} + +/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */ +function pick(list: readonly SampleZone[], count: number, roll: number): SampleZone { + if (list.length === 1) return list[0]; + const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined); + if (turns.length) { + const n = turns[0].turns ?? turns.length, want = (count % n) + 1; + return turns.find((z) => z.turn === want) ?? turns[0]; + } + const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]); + return chance ?? list[count % list.length]; +} + +/** + * An instrument played from recordings (`import piano from "./piano.samples"`, made from an SFZ instrument by + * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no + * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned + * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let + * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is + * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before, + * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, "@" chooses the strength: + * "@1" is velocity 100 (`velocity`), "@0.5" 50. + */ +export function sampled(set: Samples, options: SampledOptions = {}): Instrument { + const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true; + const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0; + if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`); + if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`); + if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`); + if (set.zones.filter((z) => (z.trigger ?? "attack") === "attack").length === 0) throw new Error(`The instrument ${set.name || "given"} has no zone a key plays.`); + /** A zone's recording at `key`: moved to it, its own tuning undone. */ + const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100); + /** + * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The + * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little. + */ + const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => { + const shift = pitched(z, key), speed = 2 ** (shift / 12); + const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01); + let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip; + if (Math.abs(shift) > 1e-6) c = c.pitch(shift); + if (held < c.seconds) { + // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve. + const points: [number, number][] = [[0, 1], [held, 1]]; + for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]); + c = c.envelope(...points); + if (c.seconds > heard) c = c.trim(0, heard); + } + const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1); + const made = g === 1 ? c : c.gain(g); + return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate); + }; + /** The sound of a key let go after `held` seconds, if the instrument has one for it. */ + const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => { + if (!releases) return null; + const list = zonesFor(set.zones, "release", key, velocity).filter((z) => key >= z.lo && key <= z.hi); + if (list.length === 0) return null; + // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another). + const groups = new Map(); + for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); } + let out: Clip | null = null; + for (const g of groups.values()) { + const z = pick(g, count, 0), shift = pitched(z, key); + const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1); + if (level < 1e-4) continue; + const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level); + out = out ? out.mix(c) : c; + } + return out; + }; + const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra; + const midiOf = (name: string) => noteNumber(name) + transpose; + return Object.freeze({ + kind: "notes" as const, + note: remembering((name, seconds, rate) => { + const key = midiOf(name), z = pick(zonesFor(set.zones, "attack", key, base), 0, 0); + return voice(z, key, base, seconds, releaseOf(z), rate); + }), + strike(name: string, seconds: number, velocity: number, rate?: number): Clip { + const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, "attack", key, v), 0, 0); + return voice(z, key, v, seconds, releaseOf(z), rate); + }, + together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip { + const order = [...notes].sort((a, b) => a.at - b.at); + const parts: { clip: Clip; at: number }[] = []; + const counts = new Map(); + let roll = 0x2545f491; + const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; }; + // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then. + const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; }; + order.forEach((n, k) => { + const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity))); + const count = counts.get(key) ?? 0; + counts.set(key, count + 1); + const z = pick(zonesFor(set.zones, "attack", key, v), count, random()); + let off = damped(n.end), stolen = false; + // The same key struck again while it sounds: the sound before stops, quickly, under the new one. + for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) { if (order[j].at < off) { off = order[j].at; stolen = true; } break; } + const held = Math.max(0.005, off - n.at); + parts.push({ clip: voice(z, key, v, held, stolen ? 0.12 : releaseOf(z), rate), at: n.at }); + if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); } + }); + if (releases) for (const [down, up] of pedal) { + for (const [trigger, at] of [["pedal-down", down], ["pedal-up", up]] as const) { + const list = set.zones.filter((z) => z.trigger === trigger); + if (list.length === 0) continue; + const z = pick(list, 0, random()); + parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at }); + } + } + if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate); + const mixed = mixdown(parts, undefined, rate); + return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed; + }, + }); +} + /** * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its * own: `music.presets.supersaw({ volume: 0.1 })`. @@ -604,6 +772,18 @@ function placed(t: Track, made: Map, c: Clip): Clip { return p; } +/** + * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note, + * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it. + */ +function sounded(t: Track, n: Score, rate?: number): Clip { + if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity); + const inst = t.instrument as Instrument; + if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate); + const c = inst.note(n.name!, n.seconds!, rate); + return n.velocity === 1 ? c : c.gain(n.velocity); +} + /** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */ interface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip } const scores = new WeakMap(); @@ -693,12 +873,11 @@ function compose(options: SongOptions, tracks: readonly Track[], sections: reado }); } score.sort((a, b) => a.at - b.at); - const base = (n: Score) => n.hit ?? (n.track.instrument as Instrument).note(n.name!, n.seconds!); // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game. let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null; const tables = () => { if (table) return table; - const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, n.velocity === 1 ? base(n) : base(n).gain(n.velocity)) })); + const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) })); // How many sound at once: at each note's start, those started before it and not yet over. let voices = 0, peakStep = 0; notes.forEach((n, k) => { @@ -791,6 +970,264 @@ export function midi(notes: Notes, parts: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 }; + +/** A length as written after "/": "8" an eighth, "8." dotted, "16t" a sixteenth of a triplet. In ticks. */ +function lengthOf(text: string, where: string): number { + const m = /^(1|2|4|8|16|32|64)(t?)(\.{0,2})$/.exec(text); + if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — "8", "8.", "16t" — not ${JSON.stringify(text)}.`); + let t = WHOLE / Number(m[1]); + if (m[2]) t = (t * 2) / 3; + if (m[3].length === 1) t *= 1.5; + if (m[3].length === 2) t *= 1.75; + return t; +} + +/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */ +interface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean } +function readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } { + const words = typeof text === "string" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : ["|", ...wordsOf2(bar)])); + const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = []; + const marks: { tick: number; level: number }[] = [], hairpins: number[] = []; + const pedal: [number, number | null][] = []; + let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0; + const open = new Map(); + const where = () => `${name}, ${bar === 0 ? "the pickup" : `bar ${bar}`}`; + marks.push({ tick: 0, level }); + for (const w of words) { + if (w === "|") { + // The first bar line ends the pickup, when there is one; every other, a bar. + const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16; + if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? "the pickup is" : `a bar of ${meter} is`} ${want / sixteenth}.`); + line = tick; + bar = bar + 1; + continue; + } + if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; } + if (w === "<" || w === ">") { hairpins.push(tick); continue; } + if (w === "ped") { + const last = pedal[pedal.length - 1]; + if (last && last[1] === null) last[1] = tick; + pedal.push([tick, null]); + continue; + } + if (w === "*") { + const last = pedal[pedal.length - 1]; + if (!last || last[1] !== null) throw new Error(`${where()}: "*" lifts the pedal, which is not down ("ped" puts it down).`); + last[1] = tick; + continue; + } + const m = /^(r|[A-Ga-g][#b]?-?\d(?:\+[A-Ga-g][#b]?-?\d)*)(?:\/([0-9]+t?\.{0,2}))?(?:@([+-]?\d+))?(['!~]*)$/.exec(w); + if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, "E5", chords joined by +, "A3+C4"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; "r" a rest; "pp" … "ff" the dynamics, "<" and ">" towards the next; "ped" and "*" the pedal; "|" a bar line.`); + if (m[2] !== undefined) length = lengthOf(m[2], where()); + if (m[1] !== "r") { + const pitches = m[1].split("+").map(noteNumber).sort((a, b) => a - b); + const flags = m[4] ?? ""; + pitches.forEach((pitch, voice) => { + // A note tied from the one before is not struck again: the one before lasts longer. + const tied = open.get(pitch); + if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) { + notes[tied].length += length; + if (!flags.includes("~")) open.delete(pitch); + return; + } + const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]); + notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes("!"), voice, staccato: flags.includes("'"), tie: flags.includes("~") }); + if (flags.includes("~")) open.set(pitch, notes.length - 1); + }); + } + tick += length; + } + // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them. + const levelAt = (t: number) => { + let k = 0; + while (k + 1 < marks.length && marks[k + 1].tick <= t) k++; + const from = marks[k], to = marks[k + 1]; + const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick)); + if (!to || pin === undefined || t < pin) return from.level; + return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin); + }; + return { + notes: notes.map((n) => { + const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0); + return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato }; + }), + pedal, + }; +} +/** A text's words, "|" kept (a bar line is checked in a performance). */ +const wordsOf2 = (t: string): string[] => t.split(/\s+/).filter((w) => w !== ""); + +/** + * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths, + * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength. + * + * const take = music.perform({ meter: "3/8", bpm: 132, pickup: "1/8", tempo: [[1, 132], [7, 132], [8, 112]] }, { + * right: { instrument: piano, notes: ["pp E5/16 D#5", "E5 D#5 E5 B4 D5 C5", "A4/8 r/16 C4 E4 A4"] }, + * left: { instrument: piano, notes: ["r/8", "r/4.", "ped A2/16 E3 A3 r/16 r/8 *"] }, + * }); + * playWav(music.render(take, { reverb: { decay: 0.85 } })); + * + * A note is its name and octave ("E5", "F#4", "Bb2"; a chord "A3+C4+E4"), then its length after "/" — 1, 2, 4, 8, 16, + * 32 or 64, "t" for a triplet's, a dot or two ("8." a dotted eighth) — the last one's when left out; "@90" how hard + * (1 … 127), "@+10" or "@-10" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note + * next. "r" is a rest. "pp", "p", "mp", "mf", "f", "ff" (and ppp, fff) set how hard what follows is struck, "<" and ">" + * move there evenly from where they stand to the next mark. "ped" puts the sustain pedal down (again, while it is down: + * lifts it and puts it down at once), "*" lifts it: an instrument holds every note let go while it is down, and a + * performance's parts on the same instrument share it. "|" is a bar line, checked: a part whose bar is too long or + * short is refused, by its bar. A text a bar puts the bar lines between the texts. + * + * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where + * the pedal is — for a picture that follows the music — and `render` mixes it into one clip. + */ +export function perform(options: PerformOptions, parts: Readonly>): Performance { + const meter = options.meter ?? "4/4", mm = /^(\d+)\/(1|2|4|8|16)$/.exec(meter); + if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, "3/8", "4/4", "6/8" — not ${JSON.stringify(meter)}.`); + const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks; + if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`); + const pickup = options.pickup ? (() => { const p = /^1\/(\d+)$/.exec(options.pickup!) ?? /^(\d+)\/(\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, "1/8", "3/16" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0; + const names = Object.keys(parts); + if (names.length === 0) throw new Error("perform() takes its parts, one at least: { right: { instrument: piano, notes: \"…\" } }."); + const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) })); + const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks; + // Ticks to seconds: the tempo at each tick, added up; the holds where they fall. + const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks); + const points = (options.tempo ?? []).map(([b, bpm]) => { + if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`); + return [barTick(b), bpm] as const; + }).sort((a, b) => a[0] - b[0]); + const bpmAt = (t: number) => { + if (points.length === 0) return options.bpm; + if (t <= points[0][0]) return points[0][1]; + for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); } + return points[points.length - 1][1]; + }; + const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; }); + const secs: number[] = [0]; + for (let t = 0; t < lastTick; t++) { + let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks); + for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec; + secs.push(next); + } + const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); }; + // A player's unevenness: the same numbers every build. + const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0; + let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1; + const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; }; + const wobble = () => (random() + random() + random() - 1.5) / 0.5; + const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = []; + let first = Infinity; + for (const r of read) { + const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1; + for (const n of r.notes) { + const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead; + const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble()))); + const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1; + const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks; + out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 }); + first = Math.min(first, at); + } + const list = pedalOf.get(r.part.instrument) ?? []; + for (const [down, up] of r.pedal) { + // A "ped" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it. + const a = timeOf(down), b = up === null ? null : timeOf(up); + const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9; + list.push([changed ? a + 0.06 : a, b ?? Infinity]); + } + pedalOf.set(r.part.instrument, list); + } + // Nothing before 0: a lead or a wobble at the very start moves everything a little later. + const shift = first < 0 ? -first : 0; + const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch); + const seconds = Math.max(0, ...notes.map((n) => n.end)); + for (const [inst, list] of pedalOf) { + // A pedal never lifted comes up three seconds after the last note is let go: the end rings. + const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]); + pedalOf.set(inst, fixed); + allPedal.push(...fixed); + } + const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)]; + const made: Performance = Object.freeze({ + kind: "performance" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))), + bars: Object.freeze(bars), parts: Object.freeze(names), seconds, + }); + performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf }); + return made; +} + +/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */ +const performances = new WeakMap }>(); + /** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */ export interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number } @@ -804,8 +1241,77 @@ export interface ReverbOptions { readonly decay?: number; readonly damping?: num * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a * program plays goes in the map as Ogg Vorbis, two channels when it has two. */ -export function render(s: Song, options: { readonly rate?: number; readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number }; readonly reverb?: ReverbOptions; readonly master?: (mix: Clip) => Clip } = {}): Clip { - const rate = options.rate ?? 44100, score = scores.get(s), least = s.steps * s.stepFrames * FRAME; +export function render(s: Song | Performance, options: RenderOptions = {}): Clip { + const rate = options.rate ?? 44100; + let mixed: Clip; + if ("kind" in s && s.kind === "performance") mixed = mixPerformance(s, rate, options); + else mixed = mixSong(s as Song, rate, options); + if (options.master) mixed = options.master(mixed); + if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness); + const limit = options.limit ?? true; + return limit === false ? mixed : mixed.limit(limit === true ? {} : limit); +} + +/** How `render` mixes. */ +export interface RenderOptions { + /** Samples a second (44 100). */ + readonly rate?: number; + /** The limiter last (true), its ceiling and release, or false for none. */ + readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number }; + /** The room the parts' `reverb` sends go to. */ + readonly reverb?: ReverbOptions; + /** What the whole mix goes through before the limiter. */ + readonly master?: (mix: Clip) => Clip; + /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */ + readonly loudness?: number; +} + +/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */ +function withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip { + if (sends.length) { + const r = room ?? {}; + parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 }); + } + return mixdown(parts, least, rate); +} + +/** + * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one + * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are. + */ +function mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip { + const inside = performances.get(p); + if (!inside) throw new Error("render() takes a performance made by music.perform."); + const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = []; + const done = new Set(); + for (const { part } of inside.parts) { + const inst = part.instrument; + if (done.has(inst)) continue; + done.add(inst); + const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name); + const own = p.notes.filter((n) => names.includes(n.part)); + if (own.length === 0) continue; + const pedal = inside.pedal.get(inst) ?? []; + let clip: Clip; + if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate); + else { + // An instrument that plays note by note: each held as long as the key, or the pedal, holds it. + const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; }; + clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate); + } + if (part.fx) clip = part.fx(clip); + if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1); + if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0); + parts.push({ clip, at: 0 }); + if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 }); + } + if (parts.length === 0) throw new Error("render(): the performance plays no notes."); + return withReverb(parts, sends, p.seconds, rate, options.reverb); +} + +/** A song mixed, as a mixing desk does. */ +function mixSong(s: Song, rate: number, options: RenderOptions): Clip { + const score = scores.get(s), least = s.steps * s.stepFrames * FRAME; let mixed: Clip; if (!score) { // (A song from elsewhere, without its score: its own clips, at their rate.) @@ -815,7 +1321,7 @@ export function render(s: Song, options: { readonly rate?: number; readonly limi const byTrack = new Map(); for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); } for (const [t, notes] of byTrack) { - const clipOf = (n: Score) => { const c = n.hit ?? (t.instrument as Instrument).note(n.name!, n.seconds!, rate); return n.velocity === 1 ? c : c.gain(n.velocity); }; + const clipOf = (n: Score) => sounded(t, n, rate); // The notes as they are, and each section's that has effects of its own mixed apart and through them. const entries: { clip: Clip; at: number }[] = [], apart = new Map(); for (const n of notes) { @@ -834,15 +1340,9 @@ export function render(s: Song, options: { readonly rate?: number; readonly limi parts.push({ clip: part, at: 0 }); if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 }); } - if (sends.length) { - const r = options.reverb ?? {}; - parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 }); - } - mixed = mixdown(parts, least, rate); + mixed = withReverb(parts, sends, least, rate, options.reverb); } - if (options.master) mixed = options.master(mixed); - const limit = options.limit ?? true; - return limit === false ? mixed : mixed.limit(limit === true ? {} : limit); + return mixed; } /* ── Music that follows the game: a song cut into pieces, played piece by piece ── */ @@ -952,7 +1452,7 @@ export function stems(s: Song, options: StemsOptions): Stems { const m = cells[g][l], list = m.get(n.track); if (list) list.push(n); else m.set(n.track, [n]); } - const clipOf = (t: Track, n: Score) => { const c = n.hit ?? (t.instrument as Instrument).note(n.name!, n.seconds!, rate); return n.velocity === 1 ? c : c.gain(n.velocity); }; + const clipOf = (t: Track, n: Score) => sounded(t, n, rate); // Each layer's last piece with notes: it rings out whole, as the song ends. const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; }); // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb. @@ -1173,6 +1673,6 @@ export const loop = game(async (s: Song) => { /** Everything above as one name: import { music } from "trigscript/music"; music.play(song). */ export const music = { - sampler, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop, + sampler, sampled, perform, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop, part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct, }; diff --git a/tests/sampled.test.ts b/tests/sampled.test.ts new file mode 100644 index 0000000..7d2a25c --- /dev/null +++ b/tests/sampled.test.ts @@ -0,0 +1,216 @@ +/** + * Sampled instruments and performances (S7, Für Elise's sound): the `.samples` file and its coding without loss; an + * instrument that plays each note from the recording nearest its key and strength, holds it with its pedal, plays the + * sound of a key let go; a performance read from a score's notation — lengths, dynamics, the pedal, bar lines checked, + * a tempo that moves; loudness as BS.1770 measures it; strings that ring in sympathy while the pedal is down. + */ +import ts from "typescript"; +import { describe, expect, it } from "vitest"; +import { compileScript, type CompileResult } from "../compiler/compiler"; +import { defaultScriptNames } from "../compiler/names"; +import { defaultLib } from "../bundle/lib.mjs"; +import { clipChannels, decodeAdpcm, makeClip, tone } from "../compiler/sound"; +import { describeSamples, readSamples, writeSamples, type ZoneData } from "../compiler/samples"; + +const LIB = defaultLib(); +const errors = (r: CompileResult) => r.diagnostics.map((d) => `${d.file}:${d.line}: ${d.message}`); +const RATE = 22050; + +/** A sine `hz` for `seconds`, dying away, at `level`: a stand-in for a recording. */ +function ring(hz: number, seconds: number, level: number, channels = 1): Float32Array[] { + const n = Math.round(seconds * RATE), x = new Float32Array(n); + for (let i = 0; i < n; i++) x[i] = level * Math.sin((2 * Math.PI * hz * i) / RATE) * Math.exp(-i / (RATE * 0.8)); + return Array.from({ length: channels }, () => x.slice()); +} + +/** + * An instrument of four recordings: A3 (220 Hz) and A4 (440 Hz), each soft (a quiet sine) and loud (a loud one, a fifth + * up from where it says — so which was played can be heard in its pitch); a key's release, a click; the pedal's thump. + */ +function instrument(): string { + const zones: ZoneData[] = [ + { sample: 0, key: 57, lo: 50, hi: 62, vlo: 1, vhi: 63, release: 0.1, veltrack: 0 }, + { sample: 1, key: 57, lo: 50, hi: 62, vlo: 64, vhi: 127, release: 0.1, veltrack: 0 }, + { sample: 2, key: 69, lo: 63, hi: 75, vlo: 1, vhi: 63, release: 0.1, veltrack: 0 }, + { sample: 3, key: 69, lo: 63, hi: 75, vlo: 64, vhi: 127, release: 0.1, veltrack: 0 }, + { sample: 4, key: 60, lo: 50, hi: 75, vlo: 1, vhi: 127, trigger: "release", pitched: false, volume: -6 }, + { sample: 5, key: 60, lo: 0, hi: 127, vlo: 1, vhi: 127, trigger: "pedal-down", pitched: false }, + ]; + const click = new Float32Array(Math.round(0.05 * RATE)).map((_, i) => (i < 20 ? 0.5 : 0)); + return writeSamples({ + rate: RATE, name: "Test", credit: "Ours (CC0)", + samples: [ + { name: "A3 soft", channels: ring(220, 2, 0.2) }, { name: "A3 loud", channels: ring(330, 2, 0.8) }, + { name: "A4 soft", channels: ring(440, 2, 0.2) }, { name: "A4 loud", channels: ring(660, 2, 0.8) }, + { name: "release", channels: [click] }, { name: "pedal", channels: [click.slice()] }, + ], + zones, + }); +} + +/** A WAV the build wrote — IMA ADPCM or 16-bit — read back. */ +function wavSamples(b: Uint8Array): { rate: number; channels: Float32Array[] } { + const v = new DataView(b.buffer, b.byteOffset, b.byteLength), text = (at: number) => String.fromCharCode(...b.subarray(at, at + 4)); + let at = 12, format = 0, count = 0, rate = 0, frames = 0, data: Uint8Array | null = null; + while (at + 8 <= b.length) { + const id = text(at), size = v.getUint32(at + 4, true); + if (id === "fmt ") { format = v.getUint16(at + 8, true); count = v.getUint16(at + 10, true); rate = v.getUint32(at + 12, true); } + if (id === "fact") frames = v.getUint32(at + 8, true); + if (id === "data") data = b.subarray(at + 8, at + 8 + size); + at += 8 + size + (size & 1); + } + if (format === 0x11) return { rate, channels: [decodeAdpcm(data!, rate, frames)] }; + const n = data!.length / 2 / count, d = new DataView(data!.buffer, data!.byteOffset, data!.byteLength); + const channels = Array.from({ length: count }, () => new Float32Array(n)); + for (let i = 0; i < n; i++) for (let c = 0; c < count; c++) channels[c][i] = d.getInt16(2 * (i * count + c), true) / 32768; + return { rate, channels }; +} + +/** Hertz of a clip's start, by its crossings of zero (a sine's). */ +function pitchOf(x: Float32Array, rate: number, from = 0.05, to = 0.4): number { + let n = 0; + const a = Math.round(from * rate), b = Math.round(to * rate); + for (let i = a + 1; i < b; i++) if (x[i - 1] < 0 && x[i] >= 0) n++; + return n / (to - from); +} +const rms = (x: Float32Array, from: number, to: number, rate: number) => { + let s = 0; + const a = Math.round(from * rate), b = Math.min(x.length, Math.round(to * rate)); + for (let i = a; i < b; i++) s += x[i] * x[i]; + return Math.sqrt(s / Math.max(1, b - a)); +}; + +/** A script with the instrument beside it, which checks its own results and throws (a build error) when they are wrong. */ +const run = (body: string) => compileScript(ts, { "main.ts": `import { music } from "trigscript/music";\nimport inst from "./inst.samples";\nconst fail = (what: string) => { throw new Error(what); };\n${body}\n`, "inst.samples": instrument() }, defaultScriptNames(), { lib: LIB }); + +describe("the .samples file", () => { + it("keeps every sample: coded without loss, and smaller than 16-bit for a sound that dies away", () => { + const rec = ring(440, 2, 0.7, 2); + const text = writeSamples({ rate: RATE, samples: [{ name: "a", channels: rec }], zones: [{ sample: 0, key: 69, lo: 0, hi: 127, vlo: 1, vhi: 127 }] }); + const back = clipChannels(readSamples(text).zones[0].clip); + for (let c = 0; c < 2; c++) for (let i = 0; i < rec[c].length; i += 97) expect(Math.abs(back[c][i] - Math.round(rec[c][i] * 32768) / 32768)).toBeLessThan(1e-6); + // 16-bit in base64 would be 4/3 of 4 bytes a frame. + expect(text.length).toBeLessThan(rec[0].length * 4 * (4 / 3) * 0.6); + }); + + it("refuses a zone that names no recording, and says what it holds on the hover", () => { + expect(() => writeSamples({ rate: RATE, samples: [], zones: [{ sample: 0, key: 60, lo: 0, hi: 127, vlo: 1, vhi: 127 }] })).toThrow(/names recording 0/); + expect(describeSamples(instrument())).toMatch(/^A sampled instrument, Test: 6 recordings .* 6 zones at 22,050 Hz\. Ours \(CC0\)\.$/); + }); + + it("names a clip without decoding it, so a check makes no samples", () => { + const r = compileScript(ts, { "main.ts": `import inst from "./inst.samples";\nprogram(async () => { playWav(inst.zones[0].clip.gain(0.5), 0); });`, "inst.samples": instrument() }, defaultScriptNames(), { lib: LIB, sounds: false }); + expect(errors(r)).toEqual([]); + expect(r.sounds.length).toBe(1); + expect(r.sounds[0].bytes).toBeUndefined(); + }); +}); + +describe("music.sampled", () => { + it("chooses by strength, moves a note only from the recording nearest it, and dies away after it is let go", () => { + const r = run(` + const piano = music.sampled(inst); + for (const c of [piano.strike!("A4", 0.5, 0.3), piano.strike!("B4", 0.5, 1.2)]) if (Math.abs(c.seconds - 0.6) > 0.01) fail(\`\${c.seconds} seconds\`); + program(async () => { playWav(piano.strike!("A4", 0.5, 0.3).wav(), 0); playWav(piano.strike!("B4", 0.5, 1.2).wav(), 0); playWav(piano.strike!("C4", 0.5, 0.3).wav(), 0); });`); + expect(errors(r)).toEqual([]); + const [a4, b4, c4] = r.sounds.map((s) => wavSamples(s.bytes!).channels[0]); + expect(pitchOf(a4, RATE)).toBeCloseTo(440, -1); + expect(pitchOf(b4, RATE)).toBeCloseTo(660 * 2 ** (2 / 12), -1); + // C4 (60) is in A3's zone (50 … 62): A3's soft recording, three semitones up. + expect(pitchOf(c4, RATE)).toBeCloseTo(220 * 2 ** (3 / 12), -1); + // Let go at 0.5 s: down 60 dB over the 0.1 s release. + expect(rms(a4, 0.57, 0.6, RATE)).toBeLessThan(rms(a4, 0.4, 0.45, RATE) / 30); + }); +}); + +describe("music.perform", () => { + const take = ` + const piano = music.sampled(inst); + const take = music.perform({ meter: "3/8", bpm: 120, pickup: "1/8" }, { + right: { instrument: piano, notes: ["pp A4/16 B4", "A4/8 r/16 A4 A4 A4", "f A4/4."] }, + left: { instrument: piano, notes: ["r/8", "ped A3/8 r/4 *", "A3/4."] }, + });`; + + it("places each note at its time: lengths as written, the pickup before bar 1, the parts together", () => { + const r = run(`${take} + const at = take.notes.map((n) => \`\${n.part[0]}\${n.note}@\${n.at.toFixed(3)}\`).join(" "); + if (at !== "rA4@0.000 rB4@0.250 lA3@0.500 rA4@0.500 rA4@1.250 rA4@1.500 rA4@1.750 lA3@2.000 rA4@2.000") fail(at); + if (take.bars.map((b) => b.toFixed(2)).join() !== "0.00,0.50,2.00,3.50") fail(take.bars.join()); + const n = take.notes[3]; + if (n.bar !== 1 || n.beat !== 0 || n.frame !== Math.round(0.5 / 0.042) || Math.abs(n.end - 1.0) > 1e-9) fail(JSON.stringify(n)); + if (take.pedal.length !== 1 || Math.abs(take.pedal[0][0] - 0.5) > 1e-9 || Math.abs(take.pedal[0][1] - 2) > 1e-9) fail(JSON.stringify(take.pedal));`); + expect(errors(r)).toEqual([]); + }); + + it("strikes as the dynamics say, and moves between them where a hairpin says", () => { + const r = run(` + const piano = music.sampled(inst); + const take = music.perform({ meter: "4/4", bpm: 60 }, { a: { instrument: piano, notes: "p A4/4 < A4 A4 A4 | f A4/4 A4@+10 A4@64 A4! " } }); + const v = take.notes.map((n) => n.velocity).join(); + // The hairpin from the second note's p to bar 2's f, over the three notes before it. + if (v !== "46,46,61,75,90,100,64,102") fail(v);`); + expect(errors(r)).toEqual([]); + }); + + it("checks the bar lines, and says which bar is too long", () => { + const r = run(`const take = music.perform({ meter: "3/8", bpm: 120 }, { right: { instrument: music.sampled(inst), notes: "A4/8 A4 A4 | A4/4 A4 | A4/4." } });`); + expect(errors(r).join("\n")).toMatch(/right, bar 2 is 8 sixteenths long; a bar of 3\/8 is 6/); + }); + + it("slows where the tempo says and waits where a hold says; a tie strikes once", () => { + const r = run(` + const piano = music.sampled(inst); + const take = music.perform({ meter: "4/4", bpm: 60, tempo: [[1, 60], [2, 60], [3, 30]], holds: [[3, 0.5]] }, { a: { instrument: piano, notes: "A4/1 | A4/2~ A4/4 A4/4 | A4/1" } }); + const at = take.notes.map((n) => n.at.toFixed(3)).join() + " / " + take.bars.map((b) => b.toFixed(3)).join(); + // Bar 2 slows from 60 to 30 evenly over its four beats: the seconds to beat b are 8 ln(60 / (60 − 7.5 b)). + if (take.notes.length !== 4 || Math.abs(take.notes[1].at - 4) > 1e-6 || Math.abs(take.notes[1].end - (4 + 8 * Math.log(60 / 37.5))) > 0.01) fail(at); + if (Math.abs(take.notes[2].at - (4 + 8 * Math.log(60 / 37.5))) > 0.01) fail(at); + if (Math.abs(take.bars[3] - take.bars[2] - (8 * Math.log(2) + 0.5)) > 0.01 || Math.abs(take.notes[3].at - take.bars[3]) > 1e-9) fail(at);`); + expect(errors(r)).toEqual([]); + }); + + it("renders: the pedal holds what is let go, its sound plays, and the same humanized take comes out every build", () => { + const body = `${take} + const dry = music.render(music.perform({ meter: "3/8", bpm: 120, pickup: "1/8" }, { right: { instrument: music.sampled(inst, { releases: false }), notes: ["r/8", "A4/16 r/16 r/4"] } }), { limit: false }); + const held = music.render(music.perform({ meter: "3/8", bpm: 120, pickup: "1/8" }, { right: { instrument: music.sampled(inst, { releases: false }), notes: ["r/8", "ped A4/16 r/16 r/4", "r/4. *"] } }), { limit: false }); + const human = music.perform({ meter: "3/8", bpm: 120, humanize: { time: 0.01, velocity: 6, seed: 3 } }, { right: { instrument: music.sampled(inst), notes: "A4/16 A4 A4 A4 A4 A4" } }); + export const times = human.notes.map((n) => n.at.toFixed(4) + "/" + n.velocity).join(" "); + program(async () => { playWav(dry.wav(), 0); playWav(held.wav(), 0); playWav(music.render(take).ogg(5), 0); });`; + const a = run(body), b = run(body); + expect(errors(a)).toEqual([]); + // (The build lists its sounds in its own order: the dry one is the shorter.) + const [dry, held] = a.sounds.filter((s) => s.bytes).map((s) => wavSamples(s.bytes!).channels[0]).sort((x, y) => x.length - y.length); + const rate = 44100; + // A sixteenth at 120 eighths a minute is 0.25 s: let go at 0.75 s and gone 0.1 s later, dry; held by the pedal, + // the recording rings to its end (2 s from 0.5). + expect(dry.length / rate).toBeCloseTo(0.85, 2); + expect(rms(dry, 0.84, 0.85, rate)).toBeLessThan(rms(dry, 0.6, 0.7, rate) / 100); + expect(held.length / rate).toBeCloseTo(2.5, 2); + expect(rms(held, 1.5, 2.0, rate)).toBeGreaterThan(0.05); + expect(a.sounds.find((s) => s.vorbis)).toBeDefined(); + expect(a.sounds.map((s) => s.path)).toEqual(b.sounds.map((s) => s.path)); + }); +}); + +describe("loudness and sympathy", () => { + it("measures a full-scale 997 Hz sine on one channel at −3.01 LUFS, and brings a clip to a loudness", () => { + const sine = tone(997, 3, { volume: 1, rate: 48000 }); + expect(sine.lufs).toBeCloseTo(-3.01, 1); + expect(sine.gain(0.1).loudness(-20).lufs).toBeCloseTo(-20, 1); + expect(makeClip(new Float32Array(48000), 48000).lufs).toBe(-Infinity); + }); + + it("rings the strings while the pedal is down and stops them when it comes up", () => { + // A held A3 (220 Hz) for a second: with the pedal down until 2 s, A2's and A3's strings answer and ring after it. + const note = tone(220, 1, { volume: 0.5, rate: 22050 }); + const rung = clipChannels(note.resonance({ pedal: [[0, 2]], amount: 0.5, decay: 3 })); + const left = rung[0], right = rung[1]; + const after = rms(left, 1.2, 1.8, 22050) + rms(right, 1.2, 1.8, 22050); + const stopped = rms(left, 2.4, 2.9, 22050) + rms(right, 2.4, 2.9, 22050); + expect(after).toBeGreaterThan(0.005); + expect(stopped).toBeLessThan(after / 100); + // Without the pedal nothing is added. + const none = clipChannels(note.resonance({ pedal: [], amount: 0.5 })); + expect(rms(none[0], 1.2, 1.8, 22050)).toBe(0); + }); +}); From f9e8cdf9fce5bebee116a5ad4ffdca1ab8b2a28c Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 14:20:22 -0600 Subject: [PATCH 04/31] =?UTF-8?q?F=C3=BCr=20Elise=20probe:=20a=20note=20ti?= =?UTF-8?q?meline=20for=20pictures,=20and=20our=20transcription?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit probes/lib/note-timeline.ts turns a performance's notes into what a map shows frame by frame, all when the script is built: notes on the game's clock (nearest frame, chords marked), the keyboard they need, a piano roll's cells at a frame (falling or rising, a row standing for some frames), and pictures turned into the changes from frame to frame. probes/lib/fur-elise-score.ts is our own transcription of Für Elise's A section from the public-domain score (bars 12-14 still to be checked against an edition) and a stormy D-minor passage of our own in the manner of the C section, played on a tempo that moves: downbeats a little long, bars marked to slow down. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- probes/lib/fur-elise-score.ts | 171 ++++++++++++++++++++++++++++++++++ probes/lib/note-timeline.ts | 156 +++++++++++++++++++++++++++++++ tests/note-timeline.test.ts | 166 +++++++++++++++++++++++++++++++++ 3 files changed, 493 insertions(+) create mode 100644 probes/lib/fur-elise-score.ts create mode 100644 probes/lib/note-timeline.ts create mode 100644 tests/note-timeline.test.ts diff --git a/probes/lib/fur-elise-score.ts b/probes/lib/fur-elise-score.ts new file mode 100644 index 0000000..8d620d0 --- /dev/null +++ b/probes/lib/fur-elise-score.ts @@ -0,0 +1,171 @@ +// Für Elise (Beethoven, Bagatelle in A minor, WoO 59), the notes the visualizer probe plays (probes/fur-elise-visual.ts): +// our own transcription, written from the public-domain score — never from a MIDI file or anyone's arrangement — of the +// A section, and a passage of our own in the manner of the stormy D-minor C section (not a transcription of it), so that +// the probe has something dense, with chords and repeated low notes, to show the "big" look on. +// +// Bars 12–14 (the octave E's before the theme comes back) are written from memory of the score and still have to be +// checked against an edition; the rest of the A section is the theme as every edition has it. The probe's sound is a +// stand-in (an FM electric piano); the Showcase's own transcription and performance come from the sound probe. +// +// A bar is a text a hand, a sixteenth a word (3/8: six a bar): a note's name starts it ("E5", "D#5"), several with + sound +// together, "-" holds what sounds a sixteenth longer, "." rests, "|" is for the eye. `perform` turns bars into notes with +// times, on a tempo that moves: each downbeat a little long, a bar marked `rit` slowing to its end. + +/** A bar: what each hand plays, and how it is played. */ +export interface Bar { + readonly rh: string; + readonly lh: string; + /** How much slower the bar's last sixteenth is than its first (0.3: 30%), slowing evenly across the bar. */ + readonly rit?: number; + /** How loud, 0 … 1 (the section's when left out). */ + readonly velocity?: number; +} + +/** A note of a performance: start and written length in seconds, its number (60 is C4), hand (0 right, 1 left), loudness. */ +export interface PlayedNote { readonly time: number; readonly seconds: number; readonly note: number; readonly hand: number; readonly velocity: number } + +const SEMITONE: Readonly> = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 }; + +/** A note's number from its name: "C4" is 60, "D#5" 75, "Bb3" 58. */ +export function noteNumber(name: string): number { + const m = /^([A-G])([#b]?)(-?\d)$/.exec(name); + if (!m) throw new Error(`Not a note: ${JSON.stringify(name)}.`); + return 12 * (Number(m[3]) + 1) + SEMITONE[m[1]] + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0); +} + +/** A hand's text as words: a sixteenth each. */ +const words = (text: string) => text.split(/\s+/).filter((w) => w && w !== "|"); + +/** Sixteenths a bar of the given bars has (they must agree hand with hand). */ +function slotsOf(bar: Bar): number { + const r = words(bar.rh).length, l = words(bar.lh).length; + if (r !== l) throw new Error(`A bar's hands differ in length: ${r} and ${l} sixteenths ("${bar.rh}" / "${bar.lh}").`); + return r; +} + +/** How a performance moves: seconds a sixteenth, how much longer a downbeat's sixteenth is, how loud by default. */ +export interface Performance { readonly sixteenth: number; readonly downbeat?: number; readonly velocity?: number } + +/** + * The bars played: each note's time and written length in seconds. A sixteenth lasts `sixteenth`, a downbeat's + * `downbeat` more (0.06: 6%); a bar with `rit` slows evenly to its last sixteenth, `rit` longer. + */ +export function perform(bars: readonly Bar[], how: Performance): PlayedNote[] { + const notes: PlayedNote[] = []; + let now = 0; + for (const bar of bars) { + const n = slotsOf(bar); + // When each sixteenth of the bar starts, and the bar's end. + const starts: number[] = []; + for (let s = 0; s < n; s++) { + starts.push(now); + const rit = bar.rit ? 1 + (bar.rit * s) / Math.max(1, n - 1) : 1; + // (A bar shorter than six sixteenths is an upbeat: no downbeat in it.) + now += how.sixteenth * rit * (s === 0 && n === 6 ? 1 + (how.downbeat ?? 0) : 1); + } + starts.push(now); + const velocity = bar.velocity ?? how.velocity ?? 0.7; + for (const [hand, text] of [[0, bar.rh], [1, bar.lh]] as const) { + const ws = words(text); + ws.forEach((w, s) => { + if (w === "-" || w === ".") return; + let len = 1; + while (s + len < ws.length && ws[s + len] === "-") len++; + const [body, at] = w.split("@"); + for (const name of body.split("+")) { + notes.push({ time: starts[s], seconds: starts[s + len] - starts[s], note: noteNumber(name), hand, velocity: at ? velocity * Number(at) : velocity }); + } + }); + } + } + notes.sort((a, b) => a.time - b.time || a.note - b.note); + return notes; +} + +/** Seconds the bars last as `perform` plays them. */ +export function length(bars: readonly Bar[], how: Performance): number { + let now = 0; + for (const bar of bars) { + const n = slotsOf(bar); + for (let s = 0; s < n; s++) now += how.sixteenth * (bar.rit ? 1 + (bar.rit * s) / Math.max(1, n - 1) : 1) * (s === 0 && n === 6 ? 1 + (how.downbeat ?? 0) : 1); + } + return now; +} + +/** When each bar starts, in seconds from the first, as `perform` plays them; one more at the end. */ +export function barStarts(bars: readonly Bar[], how: Performance): number[] { + const at = [0]; + bars.forEach((_, k) => at.push(length(bars.slice(0, k + 1), how))); + return at; +} + +/* ── The A section ── */ + +const REST = ". . . . . ."; +/** The upbeat: E5 D#5. */ +export const UPBEAT: Bar = { rh: "E5 D#5", lh: ". ." }; +/** The theme's bars 1–7, as the A section plays them three times. */ +const THEME: readonly Bar[] = [ + { rh: "E5 D#5 E5 B4 D5 C5", lh: REST }, + { rh: "A4 - . C4 E4 A4", lh: "A2 E3 A3 . . ." }, + { rh: "B4 - . E4 G#4 B4", lh: "E2 E3 G#3 . . ." }, + { rh: "C5 - . E4 E5 D#5", lh: "A2 E3 A3 . . ." }, + { rh: "E5 D#5 E5 B4 D5 C5", lh: REST }, + { rh: "A4 - . C4 E4 A4", lh: "A2 E3 A3 . . ." }, + { rh: "B4 - . E4 C5 B4", lh: "E2 E3 G#3 . . ." }, +]; +/** Bar 8, three ways: back to the start (the upbeat again), on to bar 9, and the end. */ +const BACK: Bar = { rh: "A4 - . . E5 D#5", lh: "A2 E3 A3 . . .", rit: 0.15 }; +const ON: Bar = { rh: "A4 - . B4 C5 D5", lh: "A2 E3 A3 . . ." }; +const END: Bar = { rh: "A4 - - - - -", lh: "A2+E3+A3 - - - - -", rit: 0.6 }; +/** Bars 9–14: C major, G, A minor, E, and the octave E's that lead back to the theme. */ +const EPISODE: readonly Bar[] = [ + { rh: "E5 - . G4 F5 E5", lh: "C3 G3 C4 . . ." }, + { rh: "D5 - . F4 E5 D5", lh: "G2 G3 B3 . . ." }, + { rh: "C5 - . E4 D5 C5", lh: "A2 E3 A3 . . ." }, + { rh: "B4 - . E4 E5 .", lh: "E2 E3 . . . ." }, + { rh: ". E5 E6 . . D#5", lh: REST }, + { rh: "E5 . . D#5 E5 D#5", lh: REST, rit: 0.25 }, +]; + +/** The A section, as the probe plays it: bars 1–8 twice, then 9–22 twice, ending on the last A (45 bars, about 34 s). */ +export const A_SECTION: readonly Bar[] = [ + UPBEAT, ...THEME, BACK, + ...THEME, ON, + ...EPISODE, ...THEME, { ...ON, rit: 0.1 }, + ...EPISODE, ...THEME, END, +]; + +/** The theme once round with its repeat: bars 1–8 twice, ending on the A (17 bars, about 12 s). For the sync parts. */ +export const THEME_TWICE: readonly Bar[] = [UPBEAT, ...THEME, BACK, ...THEME, END]; + +/** How the A section is played: Poco moto, a sixteenth 0.125 s, downbeats 6% long. */ +export const A_PLAYING: Performance = { sixteenth: 0.125, downbeat: 0.06, velocity: 0.62 }; + +/* ── A stormy passage in D minor (ours, after the C section's manner) ── */ + +/** Six of the same low note: the repeated sixteenths under the C section. */ +const drum = (n: string) => [n, n, n, n, n, n].join(" "); +/** + * Fourteen bars: right-hand chords on every eighth over repeated low D's, rising; a diminished arpeggio climbing over + * repeated A's; the chords again; a last D-minor chord, rung out. + */ +export const STORM: readonly Bar[] = [ + { rh: "A3+D4+F4 - A3+D4+F4 - A3+D4+F4 -", lh: drum("D2"), velocity: 0.7 }, + { rh: "A3+D4+F4 - A3+C#4+E4 - A3+D4+F4 -", lh: drum("D2"), velocity: 0.72 }, + { rh: "Bb3+D4+G4 - Bb3+D4+G4 - Bb3+D4+G4 -", lh: drum("D2"), velocity: 0.75 }, + { rh: "A3+D4+F4 - A3+D4+F4 - A3+C#4+E4 -", lh: drum("D2"), velocity: 0.78 }, + { rh: "A3+D4+F4 - D4+F4+A4 - F4+A4+D5 -", lh: drum("D2"), velocity: 0.82 }, + { rh: "G4+Bb4+D5 - G4+Bb4+E5 - A4+C#5+E5 -", lh: "G2 G2 G2 A2 A2 A2", velocity: 0.86 }, + { rh: "A4+D5+F5 - - - - -", lh: "D2+D3 - - D2 D2 D2", velocity: 0.95 }, + { rh: "C#4 E4 G4 Bb4 C#5 E5", lh: drum("A2"), velocity: 0.7 }, + { rh: "G5 Bb5 C#6 E6 C#6 Bb5", lh: drum("A2"), velocity: 0.8 }, + { rh: "G5 E5 C#5 Bb4 G4 E4", lh: drum("A2"), velocity: 0.75 }, + { rh: "C#4 E4 G4 A4 C#5 E5", lh: drum("A2"), velocity: 0.8 }, + { rh: "D5+F5+A5 - D5+F5+A5 - C#5+E5+A5 -", lh: "D2 D2 D2 A2 A2 A2", velocity: 0.9 }, + { rh: "D5+F5+A5 - - - - -", lh: "D2+D3 - - D2 D2 D2", velocity: 0.95, rit: 0.3 }, + { rh: "D4+F4+A4+D5 - - - - -", lh: "D2+A2+D3 - - - - -", velocity: 1, rit: 0.8 }, +]; + +/** How the storm is played: faster, a sixteenth 0.105 s, downbeats 4% long. */ +export const STORM_PLAYING: Performance = { sixteenth: 0.105, downbeat: 0.04, velocity: 0.8 }; diff --git a/probes/lib/note-timeline.ts b/probes/lib/note-timeline.ts new file mode 100644 index 0000000..6449099 --- /dev/null +++ b/probes/lib/note-timeline.ts @@ -0,0 +1,156 @@ +// A performance's notes turned into what a map shows frame by frame (the Für Elise visualizer, TrigScript 4's third +// Showcase). Everything here runs when the script is built: the notes are known then, with their times to the sample, +// so the picture of every frame can be worked out beforehand and the game only has to play the changes back. +// +// - `frameNotes`: each note's first frame and how many frames it lasts, from its time in seconds; +// - `keyRange`, `isBlack`, `whiteKeys`: the keyboard a set of notes needs, from a white key to a white key; +// - `rollCells`: the cells of a piano roll at a frame, notes falling onto the keyboard (or rising from it); +// - `changesOver`: pictures, frame by frame, turned into the cells that change from one frame to the next. +// +// Plain functions of plain data, so they are tested on their own (tests/note-timeline.test.ts) as well as used by a +// script. + +/** Seconds a frame lasts on Fastest, the speed a map is played at. */ +export const FRAME = 0.042; + +/** A note as a performance plays it: when it starts and how long it is written, in seconds; its number (60 is C4). */ +export interface TimedNote { + readonly time: number; + readonly seconds: number; + readonly note: number; + /** Which hand, or part: 0 the right hand, 1 the left, anything else a part of its own. */ + readonly hand: number; + readonly velocity: number; +} + +/** A note on the game's clock: the frame it starts on and the frames it lasts (at least one). */ +export interface FramedNote { + /** The note as it was played. */ + readonly source: T; + readonly on: number; + readonly len: number; + readonly note: number; + readonly hand: number; + readonly velocity: number; + /** Whether it starts with two or more other notes of its hand: a chord. */ + readonly chord: boolean; +} + +/** + * Each note on the game's clock, from a performance that starts on frame `start`: its first frame is the one nearest its + * time (a frame is 42 ms; a sound the game starts lands within 21 ms of its frame anyway), its length the frames its + * written length covers, at least `least`. In the order they start. + */ +export function frameNotes(notes: readonly T[], start: number = 0, least: number = 1): FramedNote[] { + const on = (n: TimedNote) => start + Math.round(n.time / FRAME); + const framed = notes.map((n) => { + const first = on(n); + const last = start + Math.round((n.time + n.seconds) / FRAME); + return { source: n, on: first, len: Math.max(least, last - first), note: n.note, hand: n.hand, velocity: n.velocity, chord: false }; + }); + framed.sort((a, b) => a.on - b.on || a.note - b.note); + // A chord: three notes or more of one hand starting on the same frame. + const count = new Map(); + for (const n of framed) count.set(`${n.on} ${n.hand}`, (count.get(`${n.on} ${n.hand}`) ?? 0) + 1); + return framed.map((n) => ({ ...n, chord: (count.get(`${n.on} ${n.hand}`) ?? 0) >= 3 })); +} + +/** Whether a key is black: C#, D#, F#, G#, A#. */ +export function isBlack(note: number): boolean { + return [1, 3, 6, 8, 10].includes(((note % 12) + 12) % 12); +} + +/** The keyboard the notes need: from the lowest to the highest, each end moved out to a white key. */ +export function keyRange(notes: readonly { readonly note: number }[]): { lo: number; hi: number } { + if (!notes.length) throw new Error("keyRange: no notes."); + let lo = Math.min(...notes.map((n) => n.note)); + let hi = Math.max(...notes.map((n) => n.note)); + if (isBlack(lo)) lo--; + if (isBlack(hi)) hi++; + return { lo, hi }; +} + +/** The white keys from lo to hi, in order. */ +export function whiteKeys(lo: number, hi: number): number[] { + const keys: number[] = []; + for (let n = lo; n <= hi; n++) if (!isBlack(n)) keys.push(n); + return keys; +} + +/** + * Where a key sits along a keyboard of white keys `pitch` apart, the first white key's middle at 0: a black key halfway + * between the white keys either side of it. + */ +export function keyX(note: number, lo: number, pitch: number): number { + let whites = 0; + for (let n = lo; n < note; n++) if (!isBlack(n)) whites++; + return isBlack(note) ? (whites - 0.5) * pitch : whites * pitch; +} + +/** How a roll shows the notes: `rows` cells above the keyboard, each `step` frames of music. */ +export interface RollOptions { + readonly rows: number; + readonly step: number; + /** "falling": the notes to come, reaching the keyboard as they sound; "rising": the notes played, leaving it. */ + readonly direction: "falling" | "rising"; +} + +/** A cell of a roll: the note, its row counted up from the keyboard (0 the row next to it), and the note itself. */ +export interface RollCell { readonly row: number; readonly n: FramedNote } + +/** + * The cells a roll shows at frame `f`. The roll moves a row every `step` frames (on the frames that are a multiple of + * it), so a cell stands for `step` frames of music: falling, row r the frames r·step + 1 … (r + 1)·step after the last + * step — a note's first cell reaches the row next to the keyboard the step before it sounds; rising, row r the frames + * just played, r·step + 1 … (r + 1)·step before. + */ +export function rollCells(notes: readonly FramedNote[], f: number, options: RollOptions): RollCell[] { + const { rows, step, direction } = options; + const at = Math.floor(f / step) * step; + const cells: RollCell[] = []; + for (const n of notes) { + const end = n.on + n.len - 1; + // Rows the note's frames fall in, if any are on the roll. + let first: number, last: number; + if (direction === "falling") { + // Row r holds the frames at + r·step + 1 … at + (r + 1)·step. + first = Math.ceil((n.on - at) / step) - 1; + last = Math.ceil((end - at) / step) - 1; + } else { + // Row r holds the frames at − (r + 1)·step + 1 … at − r·step. + first = Math.ceil((at - end + 1) / step) - 1; + last = Math.floor((at - n.on) / step); + } + for (let r = Math.max(0, first); r <= Math.min(rows - 1, last); r++) cells.push({ row: r, n }); + } + return cells; +} + +/** A unit standing for a pixel: where it is on the map, in pixels, what it is (a number the script gives) and its colour. */ +export interface Pixel { readonly x: number; readonly y: number; readonly unit: number; readonly color: number } + +/** One cell that changes: where, which kind of unit, the colour it had (0 none) and the colour it takes (0 none). */ +export interface Change { readonly x: number; readonly y: number; readonly unit: number; readonly from: number; readonly to: number } + +/** + * Pictures frame by frame, from frame 0 to `frames` − 1, turned into what changes: for each frame, the cells whose + * colour differs from the frame before (frame 0 against an empty map). A picture is its pixels; two at one place and + * of one kind, the last given wins. + */ +export function changesOver(frames: number, picture: (f: number) => readonly Pixel[]): Change[][] { + const out: Change[][] = []; + let shown = new Map(); + for (let f = 0; f < frames; f++) { + const now = new Map(); + for (const p of picture(f)) now.set(`${p.unit} ${p.x} ${p.y}`, p); + const changes: Change[] = []; + for (const [k, p] of now) { + const was = shown.get(k); + if (!was || was.color !== p.color) changes.push({ x: p.x, y: p.y, unit: p.unit, from: was?.color ?? 0, to: p.color }); + } + for (const [k, was] of shown) if (!now.has(k)) changes.push({ x: was.x, y: was.y, unit: was.unit, from: was.color, to: 0 }); + out.push(changes); + shown = now; + } + return out; +} diff --git a/tests/note-timeline.test.ts b/tests/note-timeline.test.ts new file mode 100644 index 0000000..7b884db --- /dev/null +++ b/tests/note-timeline.test.ts @@ -0,0 +1,166 @@ +/** + * The Für Elise visualizer's build-time helpers (probes/lib/note-timeline.ts, probes/lib/fur-elise-score.ts): notes on + * the game's clock, the keyboard they need, a piano roll's cells frame by frame, pictures turned into changes, and the + * transcription played on a tempo that moves. + */ +import { describe, expect, it } from "vitest"; +import { FRAME, changesOver, frameNotes, isBlack, keyRange, keyX, rollCells, whiteKeys, type FramedNote, type Pixel } from "../probes/lib/note-timeline"; +import { A_PLAYING, A_SECTION, STORM, STORM_PLAYING, THEME_TWICE, barStarts, length, noteNumber, perform } from "../probes/lib/fur-elise-score"; + +const note = (time: number, seconds: number, n: number, hand = 0) => ({ time, seconds, note: n, hand, velocity: 1 }); +const framed = (on: number, len: number, n = 60): FramedNote => ({ source: note(0, 0, n), on, len, note: n, hand: 0, velocity: 1, chord: false }); + +describe("notes on the game's clock", () => { + it("starts a note on the frame nearest its time and lasts the frames its length covers, at least one", () => { + const fs = frameNotes([note(0, 0.125, 64), note(0.125, 0.125, 63), note(1.0, 0.01, 60)], 10); + expect(fs.map((n) => [n.on, n.len])).toEqual([[10, 3], [13, 3], [34, 1]]); + expect(Math.round(1.0 / FRAME)).toBe(24); + }); + + it("marks a chord: three notes or more of one hand starting together", () => { + const fs = frameNotes([note(0, 0.2, 57), note(0, 0.2, 62), note(0, 0.2, 65), note(0, 0.2, 38, 1), note(0, 0.2, 50, 1)]); + expect(fs.filter((n) => n.chord).map((n) => n.note)).toEqual([57, 62, 65]); + }); + + it("orders the notes by their first frame, each keeping the note it was made from", () => { + const later = note(0.5, 0.1, 70), first = note(0, 0.1, 60); + const fs = frameNotes([later, first]); + expect(fs.map((n) => n.note)).toEqual([60, 70]); + expect(fs[1].source).toBe(later); + }); +}); + +describe("the keyboard", () => { + it("knows the black keys", () => { + expect([60, 61, 62, 63, 64, 65, 66].map(isBlack)).toEqual([false, true, false, true, false, false, true]); + }); + + it("reaches from a white key to a white key", () => { + expect(keyRange([{ note: 63 }, { note: 70 }])).toEqual({ lo: 62, hi: 71 }); + expect(keyRange([{ note: 40 }, { note: 88 }])).toEqual({ lo: 40, hi: 88 }); + }); + + it("puts a black key halfway between its white neighbours", () => { + expect(whiteKeys(60, 64)).toEqual([60, 62, 64]); + expect(keyX(60, 60, 20)).toBe(0); + expect(keyX(61, 60, 20)).toBe(10); + expect(keyX(62, 60, 20)).toBe(20); + expect(keyX(65, 60, 20)).toBe(60); + }); +}); + +describe("a piano roll", () => { + const falling = { rows: 10, step: 1, direction: "falling" } as const; + + it("brings a falling note's first cell next to the keyboard the frame before it sounds", () => { + const n = framed(20, 3); + expect(rollCells([n], 19, falling).map((c) => c.row)).toEqual([0, 1, 2]); + // Ten frames before, its first cell enters the top row; earlier, it is not on the roll. + expect(rollCells([n], 10, falling).map((c) => c.row)).toEqual([9]); + expect(rollCells([n], 9, falling)).toEqual([]); + // Sounding, it has left the roll from the bottom. + expect(rollCells([n], 20, falling).map((c) => c.row)).toEqual([0, 1]); + expect(rollCells([n], 22, falling)).toEqual([]); + }); + + it("moves a row every step, a cell standing for step frames", () => { + const opts = { rows: 10, step: 2, direction: "falling" } as const; + const n = framed(20, 1); + // Frames 18 and 19 are the same step (18): the note, two to four frames away, in row 0. + expect(rollCells([n], 18, opts).map((c) => c.row)).toEqual([0]); + expect(rollCells([n], 19, opts).map((c) => c.row)).toEqual([0]); + expect(rollCells([n], 16, opts).map((c) => c.row)).toEqual([1]); + // A note of six frames covers three cells. + expect(rollCells([framed(21, 6)], 18, opts).map((c) => c.row)).toEqual([1, 2, 3]); + }); + + it("lets a rising note leave the keyboard as it sounds", () => { + const rising = { rows: 10, step: 1, direction: "rising" } as const; + const n = framed(20, 3); + expect(rollCells([n], 19, rising)).toEqual([]); + expect(rollCells([n], 20, rising).map((c) => c.row)).toEqual([0]); + expect(rollCells([n], 22, rising).map((c) => c.row)).toEqual([0, 1, 2]); + expect(rollCells([n], 25, rising).map((c) => c.row)).toEqual([3, 4, 5]); + expect(rollCells([n], 31, rising).map((c) => c.row)).toEqual([9]); + expect(rollCells([n], 32, rising)).toEqual([]); + }); + + it("shows a note in a row once for each step its frames touch", () => { + // Row 4's cell stands for the frames k·step + 1 … (k + 1)·step as the roll moves: the note is in it for as many + // steps as there are such blocks among its frames. + for (const step of [1, 2, 3]) { + for (const [on, len] of [[50, 5], [51, 1], [52, 7]]) { + let shown = 0; + for (let f = 0; f < 90; f += step) shown += rollCells([framed(on, len)], f, { rows: 20, step, direction: "falling" }).filter((c) => c.row === 4).length; + const end = on + len - 1; + expect(shown).toBe(Math.floor((end - 1) / step) - Math.floor((on - 1) / step) + 1); + } + } + }); +}); + +describe("pictures turned into changes", () => { + const p = (x: number, color: number, unit = 0): Pixel => ({ x, y: 0, unit, color }); + + it("makes, recolours and takes away only what differs from the frame before", () => { + const pictures: Pixel[][] = [[p(0, 1), p(10, 2)], [p(0, 1), p(10, 3)], [p(10, 3), p(20, 1, 1)], []]; + const cs = changesOver(4, (f) => pictures[f]); + expect(cs[0]).toEqual([{ x: 0, y: 0, unit: 0, from: 0, to: 1 }, { x: 10, y: 0, unit: 0, from: 0, to: 2 }]); + expect(cs[1]).toEqual([{ x: 10, y: 0, unit: 0, from: 2, to: 3 }]); + expect(cs[2]).toEqual([{ x: 20, y: 0, unit: 1, from: 0, to: 1 }, { x: 0, y: 0, unit: 0, from: 1, to: 0 }]); + expect(cs[3].map((c) => [c.x, c.from, c.to])).toEqual([[10, 3, 0], [20, 1, 0]]); + }); + + it("keeps the last of two pixels at one place, and a still picture costs nothing", () => { + const cs = changesOver(3, () => [p(0, 1), p(0, 2)]); + expect(cs.map((c) => c.length)).toEqual([1, 0, 0]); + expect(cs[0][0].to).toBe(2); + }); +}); + +describe("the transcription, played", () => { + it("reads note names", () => { + expect([noteNumber("C4"), noteNumber("D#5"), noteNumber("Bb3"), noteNumber("E2"), noteNumber("E6")]).toEqual([60, 75, 58, 40, 88]); + }); + + it("opens with E5 D#5 E5 B4 D5 C5, then A4 over A2 E3 A3", () => { + const ns = perform(A_SECTION, A_PLAYING); + const rh = ns.filter((n) => n.hand === 0).slice(0, 9).map((n) => n.note); + expect(rh).toEqual([76, 75, 76, 75, 76, 71, 74, 72, 69]); + const lh = ns.filter((n) => n.hand === 1).slice(0, 3).map((n) => n.note); + expect(lh).toEqual([45, 52, 57]); + // The A4 and the A2 under it start together, on the second bar's downbeat. + const a4 = ns.find((n) => n.note === 69)!, a2 = ns.find((n) => n.note === 45)!; + expect(a4.time).toBe(a2.time); + // The A4 is an eighth: the downbeat's long sixteenth and one more. + expect(a4.seconds).toBeCloseTo(a2.seconds + A_PLAYING.sixteenth, 6); + }); + + it("plays a sixteenth at the tempo, a downbeat a little long, and slows where a bar says", () => { + const ns = perform([{ rh: "C4 D4 E4 F4 G4 A4", lh: ". . . . . ." }, { rh: "C5 . . . . .", lh: ". . . . . ." }], { sixteenth: 0.1, downbeat: 0.1 }); + expect(ns[1].time).toBeCloseTo(0.11, 6); + expect(ns[2].time - ns[1].time).toBeCloseTo(0.1, 6); + expect(ns[6].time).toBeCloseTo(0.61, 6); + const slow = perform([{ rh: "C4 D4 E4 F4 G4 A4", lh: ". . . . . .", rit: 0.5 }], { sixteenth: 0.1 }); + expect(slow[5].seconds).toBeCloseTo(0.15, 6); + expect(length([{ rh: "C4 D4 E4 F4 G4 A4", lh: ". . . . . .", rit: 0.5 }], { sixteenth: 0.1 })).toBeCloseTo(0.75, 6); + }); + + it("refuses a bar whose hands differ in length", () => { + expect(() => perform([{ rh: "C4 D4", lh: "." }], { sixteenth: 0.1 })).toThrow(/differ in length/); + }); + + it("lasts about 34 s (the A section), 12 s (the theme twice) and 9 s (the storm), from E2/D2 to E6", () => { + expect(length(A_SECTION, A_PLAYING)).toBeGreaterThan(30); + expect(length(A_SECTION, A_PLAYING)).toBeLessThan(40); + expect(length(THEME_TWICE, A_PLAYING)).toBeGreaterThan(11); + expect(length(THEME_TWICE, A_PLAYING)).toBeLessThan(14); + expect(length(STORM, STORM_PLAYING)).toBeGreaterThan(8); + expect(length(STORM, STORM_PLAYING)).toBeLessThan(11); + const all = [...perform(A_SECTION, A_PLAYING), ...perform(STORM, STORM_PLAYING)]; + expect(keyRange(all)).toEqual({ lo: 38, hi: 88 }); + const bars = barStarts(THEME_TWICE, A_PLAYING); + expect(bars.length).toBe(THEME_TWICE.length + 1); + expect(bars.at(-1)).toBeCloseTo(length(THEME_TWICE, A_PLAYING), 9); + }); +}); From 3a98370d1fec9c98263eb042c9aba146b5a68211 Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 14:20:27 -0600 Subject: [PATCH 05/31] =?UTF-8?q?F=C3=BCr=20Elise=20probe:=20the=20layout,?= =?UTF-8?q?=20the=20base=20map,=20and=20the=20run=20frame=20by=20frame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 128 x 128 Space Platform map: a piano roll of Overlords on the minimap's Space (D2-E6, 40 rows, a row every two frames), and a stage on Platform the camera looks at, a keyboard of Flag-looking Spider Mines with notes falling onto it and a sync lamp (a start-location ring, white on every frame a note starts). probes/lib/fur-elise-run.ts lays the parts end to end (clicks, the A section, the storm, the theme as one clip and as a clip a bar, other looks), draws every frame's picture and flattens the changes into the tables the program reads. A Spider Mine is never asked for where it would overlap one of its frame or the frame before: the game would put it beside its place. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- probes/lib/fur-elise-layout.ts | 45 +++++++ probes/lib/fur-elise-map.mts | 51 ++++++++ probes/lib/fur-elise-run.ts | 210 +++++++++++++++++++++++++++++++++ tests/fur-elise-run.test.ts | 95 +++++++++++++++ 4 files changed, 401 insertions(+) create mode 100644 probes/lib/fur-elise-layout.ts create mode 100644 probes/lib/fur-elise-map.mts create mode 100644 probes/lib/fur-elise-run.ts create mode 100644 tests/fur-elise-run.test.ts diff --git a/probes/lib/fur-elise-layout.ts b/probes/lib/fur-elise-layout.ts new file mode 100644 index 0000000..c4d69b5 --- /dev/null +++ b/probes/lib/fur-elise-layout.ts @@ -0,0 +1,45 @@ +// Where the Für Elise visualizer probe draws on its 128 × 128 map, shared by the script (probes/fur-elise-visual.ts) +// and its base map (probes/lib/fur-elise-map.mts). Map pixels unless a name says tiles. +// +// The top of the map is Space, black on the minimap: the piano roll, a cell an Overlord two tiles square (Korobeiniki's +// board, played), a column a key. The bottom is Platform, ground a unit stands on: the stage the camera looks at, a +// keyboard of Spider Mines given a Flag's looks (the main-screen spike's pixel, played: placed exactly where asked). + +/** The keyboard: D2 to E6, every note the probe plays (keyRange of the A section and the storm). */ +export const LO = 38, HI = 88, KEYS = HI - LO + 1; + +/** The map, in tiles. */ +export const MAP_W = 128, MAP_H = 128; + +/* ── The minimap roll ── */ + +/** A roll cell is two tiles square: its centre is 64·c + 32. */ +export const CELL = 64; +/** The column of the lowest key: the 51 keys in the middle of the map's 64 columns. */ +export const ROLL_COL = Math.floor((MAP_W / 2 - KEYS) / 2); +/** The keyboard's two rows of cells: the upper has every key (black ones in their colour), the lower the white keys' fronts. */ +export const ROLL_KEY_ROW = 42; +/** Rows of falling notes above the keyboard, and the frames a row stands for (Remastered redraws its minimap about every other frame). */ +export const ROLL_ROWS = 40, ROLL_STEP = 2; + +/* ── The stage, on the main screen ── */ + +/** + * The view's top left corner on the map, the camera centred 426 × 240 from it (Remastered's widescreen view is 852 + * game pixels across; the console hides the bottom ~150). Text lines show along the view's left, x 0 … 233 between y + * 100 and 290 (measured in earlier recordings), so the stage keeps to the right of x 240. + */ +export const VIEW_X = 1664, VIEW_Y = 3200, CAM_X = VIEW_X + 426, CAM_Y = VIEW_Y + 240; +/** The keyboard on the stage: white keys PITCH apart from view x WHITE_X0, their row at view y WHITE_Y; black keys a row above. */ +export const PITCH = 20, WHITE_X0 = 250, WHITE_Y = 262, BLACK_Y = 242; +/** + * Falling notes: STAGE_ROWS rows of Flags, ROW_GAP apart, upwards from view y FALL_Y0; a row a frame. A trigger cannot + * make a Spider Mine overlapping another (the game puts it beside its place), and in the lifted game one made 16 pixels + * above a neighbour 10 across was moved: so rows are 18 apart (and the lowest 18 above the black keys), white keys 20, + * a black key 10 across and 20 up from its white neighbours; two Flags are never in one row closer than 16. + */ +export const STAGE_ROWS = 12, ROW_GAP = 18, FALL_Y0 = 224; +/** The sync lamp: a start-location ring, black, white on the frame a note starts. In view pixels. */ +export const LAMP_X = 120, LAMP_Y = 50; +/** The Platform under the stage and the start locations, in tiles. */ +export const STAGE_TILES = { x: 36, y: 96, w: 70, h: 32 } as const; diff --git a/probes/lib/fur-elise-map.mts b/probes/lib/fur-elise-map.mts new file mode 100644 index 0000000..22b7ed4 --- /dev/null +++ b/probes/lib/fur-elise-map.mts @@ -0,0 +1,51 @@ +// The base map of the Für Elise visualizer probe (probes/fur-elise-visual.ts): 128 × 128 Space Platform, Space at the +// top for the minimap's piano roll (black there, the Overlords' colours on it) and Platform at the bottom for the stage +// the camera looks at (probes/lib/fur-elise-layout.ts); Player 1's Map Revealers placed over the whole map, so every +// player's units are seen (they are kept by 1.16.1 too, which refuses a revealer a trigger makes); the start locations +// on the platform, out of the camera's way. +// +// MAP_NAME="Für Elise visual probe" npx tsx probes/lib/fur-elise-map.mts +// +// Needs a scm-js checkout beside this one with its tileset data (npm run extract). +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { MAP_H, MAP_W, STAGE_TILES } from "./fur-elise-layout.ts"; + +const E = process.env.SCMJS_DIR ?? join(import.meta.dirname, "..", "..", "..", "scm-js"); +const { createScenario } = await import(join(E, "src/formats/chk/create.ts")); +const { markDirty, serializeScenario } = await import(join(E, "src/formats/chk/scenario.ts")); +const { saveMap } = await import(join(E, "src/formats/mpq/scm.ts")); +const { TILESET_FILENAMES } = await import(join(E, "src/formats/tileset/load.ts")); +const { loadTileset } = await import(join(E, "src/formats/tileset/decode.ts")); +const { baseTerrain, flatTerrain } = await import(join(E, "src/formats/tileset/terrain.ts")); + +const [out] = process.argv.slice(2); +if (!out) { console.error("usage: fur-elise-map.mts "); process.exit(2); } +/** Space Platform; its ISOM terrains Space (2) and Platform (3). */ +const ERA = 1, PLATFORM = 3, SPACE = 2, W = MAP_W, H = MAP_H; +const part = (ext: string) => new Uint8Array(readFileSync(join(E, "public/tileset", `${TILESET_FILENAMES[ERA]}.${ext}`))); +const ts = loadTileset({ cv5: part("cv5"), vf4: part("vf4"), vr4: part("vr4"), vx4: part("vx4"), wpe: part("wpe") }); +let seed = 1; +const rnd = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x80000000); +const space = flatTerrain(W, H, baseTerrain(ts, SPACE), ts, rnd, ERA); +const platform = flatTerrain(W, H, baseTerrain(ts, PLATFORM), ts, rnd, ERA); +const tiles = space.tiles.slice(); +for (let y = STAGE_TILES.y; y < Math.min(H, STAGE_TILES.y + STAGE_TILES.h); y++) for (let x = STAGE_TILES.x; x < STAGE_TILES.x + STAGE_TILES.w; x++) tiles[y * W + x] = platform.tiles[y * W + x]; +const scn = createScenario({ + width: W, height: H, era: ERA, tiles, isom: space.isom, + name: process.env.MAP_NAME ?? "Für Elise visual probe", + description: process.env.MAP_DESCRIPTION ?? "Für Elise (Beethoven), drawn as it plays: falling notes on the minimap and on the main screen. A probe of TrigScript (scmjs.dev). Host as multiplayer, alone, with the game's music off.", +}); +scn.playerTypes = scn.playerTypes.map((t: number, i: number) => (i === 0 ? 6 : i === 1 ? 5 : i < 8 ? 0 : t)); +scn.editorPlayerTypes = [...scn.playerTypes]; +scn.playerRaces = scn.playerRaces.map((r: number, i: number) => (i === 0 ? 1 : i === 1 ? 0 : i < 8 ? 7 : r)); +const unit = (unitId: number, owner: number, x: number, y: number, serial: number) => ({ classInstance: serial, x, y, unitId, relationFlags: 0, validStates: 0, validProperties: 0, owner, hitPointsPercent: 100, shieldPercent: 100, energyPercent: 100, resourceAmount: 0, hangarUnits: 0, stateFlags: 0, unused: 0, relatedSerial: 0 }); +const START_LOCATION = 214, MAP_REVEALER = 101; +let serial = 1; +// The start locations at the platform's right end, below the stage's view. +const sx = STAGE_TILES.x + STAGE_TILES.w - 4, sy = STAGE_TILES.y + STAGE_TILES.h - 3; +scn.units.push(unit(START_LOCATION, 0, sx * 32 + 16, sy * 32 + 16, serial++), unit(START_LOCATION, 1, (sx - 4) * 32 + 16, sy * 32 + 16, serial++)); +// Map Revealers every 14 tiles (a sight of 10 reaches the corners between them). +for (let y = 7; y < H; y += 14) for (let x = 7; x < W; x += 14) scn.units.push(unit(MAP_REVEALER, 0, x * 32 + 16, y * 32 + 16, serial++)); +markDirty(scn, "OWNR", "IOWN", "SIDE", "UNIT", "MTXM", "TILE", "ISOM"); +writeFileSync(out, await saveMap(serializeScenario(scn), { extras: new Map(), compress: "pkware", listfile: true })); diff --git a/probes/lib/fur-elise-run.ts b/probes/lib/fur-elise-run.ts new file mode 100644 index 0000000..b4823ef --- /dev/null +++ b/probes/lib/fur-elise-run.ts @@ -0,0 +1,210 @@ +// The Für Elise visualizer probe's run (probes/fur-elise-visual.ts), worked out when the script is built: which clip +// starts on which frame, the text shown, and the picture of every frame on both screens, turned into the changes the +// program plays back. Plain data and functions — no sound, nothing of the game's — so the same run is what the probe +// plays, what tests/fur-elise-run.test.ts checks and what a picture of a frame is drawn from +// (probes/lib/fur-elise-frames.mts). +import { FRAME, changesOver, frameNotes, isBlack, keyRange, keyX, rollCells, type FramedNote, type Pixel } from "./note-timeline"; +import { A_PLAYING, A_SECTION, STORM, STORM_PLAYING, THEME_TWICE, barStarts, length, perform, type PlayedNote } from "./fur-elise-score"; +import { + LO, HI, CELL, ROLL_COL, ROLL_KEY_ROW, ROLL_ROWS, ROLL_STEP, VIEW_X, VIEW_Y, CAM_X, PITCH, WHITE_X0, WHITE_Y, BLACK_Y, + STAGE_ROWS, ROW_GAP, FALL_Y0, LAMP_X, LAMP_Y, +} from "./fur-elise-layout"; + +/* ── The notes ── */ + +export const A_NOTES = perform(A_SECTION, A_PLAYING); +export const STORM_NOTES = perform(STORM, STORM_PLAYING); +export const THEME_NOTES = perform(THEME_TWICE, A_PLAYING); +export const A_LONG = length(A_SECTION, A_PLAYING), STORM_LONG = length(STORM, STORM_PLAYING), THEME_LONG = length(THEME_TWICE, A_PLAYING); +/** When each bar of the theme starts, in seconds, and the frame it starts in: the S2 part plays a clip a bar from there. */ +export const BAR_AT = barStarts(THEME_TWICE, A_PLAYING); +export const BAR_FRAME = BAR_AT.map((t) => Math.floor(t / FRAME + 1e-9)); +/** Clicks, CLICK_EVERY frames apart: the lamp's calibration. */ +export const CLICK_EVERY = 24, CLICKS = 6; +/** The clips, by their place in the probe's list: the clicks, the A section, the storm, the theme, then the theme's bars. */ +export const CLIP_CLICKS = 0, CLIP_A = 1, CLIP_STORM = 2, CLIP_THEME = 3, CLIP_BAR0 = 4; + +/* ── The run, frame by frame ── */ + +/** How a part looks: each screen's roll, and the storm's extras. */ +export interface Look { + readonly roll: "falling" | "rising" | "keys"; + /** Frames a row of the stage's roll stands for: 1, a row a frame (the main screen is redrawn every frame), or 2. */ + readonly stageStep: number; + readonly flash: boolean; + readonly boom: boolean; + readonly webs: boolean; +} +const PLAIN: Look = { roll: "falling", stageStep: 1, flash: false, boom: false, webs: false }; +/** A note of the run: on the game's clock, with its part's look and whether it is a bar's first. */ +export interface RunNote extends FramedNote { readonly look: Look; readonly downbeat: boolean } + +export const runNotes: RunNote[] = []; +export const captions: { frame: number; text: string }[] = []; +export const plays: { frame: number; clip: number }[] = []; +/** Frames the lamp is lit by itself (the clicks). */ +export const clicks = new Set(); +/** The effects: a frame, a kind (1 a Wraith's explosion, 2 a Battlecruiser's, 3 a Disruption Web made, 4 one taken away), where. */ +export const fxList: { frame: number; kind: number; x: number; y: number }[] = []; + +/** A part's notes put on the run from `start`, each with its look (by its time), downbeats marked from the bar starts. */ +function place(played: readonly PlayedNote[], start: number, look: (time: number) => Look, bars: readonly number[]) { + for (const n of frameNotes(played, start, 2)) { + const t = n.source.time; + runNotes.push({ ...n, look: look(t), downbeat: bars.some((b) => Math.abs(b - t) < 1e-6) }); + } +} + +export const SETUP = 8; +let at = 48; +captions.push({ frame: 4, text: "Für Elise visual probe. Remastered graphics, the game's music off; record it all. About 100 seconds." }); +// T: the clicks. +captions.push({ frame: at - 24, text: "T: six clicks, the lamp (top left) white on each." }); +plays.push({ frame: at, clip: CLIP_CLICKS }); +for (let k = 0; k < CLICKS; k++) clicks.add(at + k * CLICK_EVERY); +at += CLICKS * CLICK_EVERY + 24; +// A: the A section. +captions.push({ frame: at - 24, text: "A1: the A section. Falling notes, right hand gold, left cyan." }); +plays.push({ frame: at, clip: CLIP_A }); +// From bar 9 the first time (the 18th bar played) the main screen's notes fall half as fast. +export const A_BARS = barStarts(A_SECTION, A_PLAYING); +place(A_NOTES, at, (t) => (t < A_BARS[17] - 1e-6 ? PLAIN : { ...PLAIN, stageStep: 2 }), A_BARS); +captions.push({ frame: at + Math.round(A_BARS[17] / FRAME) - 6, text: "A2: the main screen's notes fall half as fast." }); +at += Math.round(A_LONG / FRAME) + 48; +// C: the storm, its first seven bars quiet, the rest with explosions. +export const STORM_BARS = barStarts(STORM, STORM_PLAYING); +captions.push({ frame: at - 24, text: "C-a: the storm. Red flashes on the chords, Disruption Webs." }); +plays.push({ frame: at, clip: CLIP_STORM }); +export const C_START = at; +place(STORM_NOTES, at, (t) => (t < STORM_BARS[7] - 1e-6 ? { ...PLAIN, flash: true, webs: true } : { ...PLAIN, flash: true, boom: true }), STORM_BARS); +captions.push({ frame: at + Math.round(STORM_BARS[7] / FRAME) - 6, text: "C-b: explosions (the game's own explosion sounds)." }); +at += Math.round(STORM_LONG / FRAME) + 60; +// S1 and S2: the theme twice, as one clip and as a clip a bar. +captions.push({ frame: at - 24, text: "S1: the theme as one clip." }); +plays.push({ frame: at, clip: CLIP_THEME }); +place(THEME_NOTES, at, () => PLAIN, BAR_AT); +export const S1_START = at; +at += Math.round(THEME_LONG / FRAME) + 48; +captions.push({ frame: at - 24, text: "S2: the same, a clip a bar." }); +BAR_AT.slice(0, -1).forEach((_, k) => plays.push({ frame: at + BAR_FRAME[k], clip: CLIP_BAR0 + k })); +place(THEME_NOTES, at, () => PLAIN, BAR_AT); +export const S2_START = at; +at += Math.round(THEME_LONG / FRAME) + 48; +// V: the theme again, two other looks. +captions.push({ frame: at - 24, text: "V1: notes rising from the keys." }); +plays.push({ frame: at, clip: CLIP_THEME }); +place(THEME_NOTES, at, (t) => ({ ...PLAIN, roll: t < BAR_AT[9] - 1e-6 ? "rising" : "keys" }), BAR_AT); +captions.push({ frame: at + Math.round(BAR_AT[9] / FRAME) - 6, text: "V2: the keys alone." }); +at += Math.round(THEME_LONG / FRAME) + 72; +captions.push({ frame: at, text: "The end. Thank you." }); +export const TOTAL = at + 24; + +const range = keyRange(runNotes); +if (range.lo !== LO || range.hi !== HI) throw new Error(`The notes need the keys ${range.lo}…${range.hi}; the layout has ${LO}…${HI}.`); + +/* ── What each frame shows ── */ + +/** The colours, as players: 1 white (P3), 2 indigo (P4), 3 gold (P5), 4 cyan (P6), 5 red (P7), 6 black (P8). */ +export const WHITE = 1, INDIGO = 2, GOLD = 3, CYAN = 4, RED = 5, BLACK = 6; +/** Kinds of pixel: an Overlord on the minimap, a Flag on the stage, the lamp's ring. */ +export const OVERLORD = 0, FLAG = 1, RING = 2; +const colorOf = (n: RunNote) => (n.hand === 1 ? CYAN : n.look.flash && n.chord ? RED : GOLD); +/** Frames a key stays lit: its note's, at least two. */ +const lit = (n: RunNote, f: number) => n.on <= f && f < n.on + Math.max(2, n.len); + +export const rollX = (note: number) => (ROLL_COL + note - LO) * CELL + CELL / 2; +export const rollY = (row: number) => row * CELL + CELL / 2; +export const stageX = (note: number) => VIEW_X + WHITE_X0 + keyX(note, LO, PITCH); +const KEY_LIST = Array.from({ length: HI - LO + 1 }, (_, k) => LO + k); + +/** The notes near frame f, by when they start: those a roll or a key might show. */ +const SPAN = Math.max(ROLL_ROWS * ROLL_STEP, STAGE_ROWS * 2) + 4; +function near(f: number): RunNote[] { + return runNotes.filter((n) => n.on - SPAN <= f && f <= n.on + n.len + SPAN); +} + +/** Whether two Flags would overlap: a Spider Mine is 15 pixels square (units.dat: 7 each way from its middle). */ +const overlap = (a: Pixel, x: number, y: number) => a.unit !== OVERLORD && Math.abs(a.x - x) < 16 && Math.abs(a.y - y) < 16 && (a.x !== x || a.y !== y); + +/** + * The picture of frame f, given the frame before's (`before`). A trigger cannot make a Spider Mine where it would overlap + * another — the game puts it beside its place — and one taken away still stands until the frame ends (both found in + * the lifted game: the E5 leaving a row as the D#5 next to it came in). So a falling Flag that would overlap one of + * this frame or the last waits a frame; the keys and the rows are laid out never to. + */ +function draw(f: number, before: readonly Pixel[]): Pixel[] { + const out: Pixel[] = []; + if (f < SETUP) return out; + const close = near(f); + // The keys: lit by the last note to start on each, else idle; the storm's chords flash the white keys red. + const flash = close.some((n) => n.look.flash && n.hand === 0 && n.chord && n.on <= f && f < n.on + 2); + for (const key of KEY_LIST) { + const on = close.filter((n) => n.note === key && lit(n, f)); + const idle = isBlack(key) ? INDIGO : flash ? RED : WHITE; + const color = on.length ? colorOf(on[on.length - 1]) : idle; + // The minimap: the upper row every key, the lower the white keys' fronts (lit too). + out.push({ x: rollX(key), y: rollY(ROLL_KEY_ROW), unit: OVERLORD, color }); + if (!isBlack(key)) out.push({ x: rollX(key), y: rollY(ROLL_KEY_ROW + 1), unit: OVERLORD, color }); + // The stage: white keys in a row, black ones above. + if (f >= SETUP + 1) out.push({ x: stageX(key), y: VIEW_Y + (isBlack(key) ? BLACK_Y : WHITE_Y), unit: FLAG, color }); + } + // The rolls, by each note's look. + for (const look of ["falling", "rising"] as const) { + // Each note a row short on a roll, so that a key struck again shows as two (the storm's repeated D's). + const short = (ns: readonly RunNote[], by: number) => ns.map((n) => ({ ...n, len: Math.max(1, n.len - by) })); + const these = close.filter((n) => n.look.roll === look); + const fast = short(these.filter((n) => n.look.stageStep === 1), 1), slow = short(these.filter((n) => n.look.stageStep === 2), 2); + for (const c of rollCells(short(these, ROLL_STEP), f, { rows: ROLL_ROWS, step: ROLL_STEP, direction: look })) { + out.push({ x: rollX(c.n.note), y: rollY(ROLL_KEY_ROW - 1 - c.row), unit: OVERLORD, color: colorOf(c.n as RunNote) }); + } + for (const c of [...rollCells(fast, f, { rows: STAGE_ROWS, step: 1, direction: look }), ...rollCells(slow, f, { rows: STAGE_ROWS, step: 2, direction: look })]) { + const x = stageX(c.n.note), y = VIEW_Y + FALL_Y0 - c.row * ROW_GAP; + if (out.some((p) => overlap(p, x, y)) || before.some((p) => overlap(p, x, y))) continue; + out.push({ x, y, unit: FLAG, color: colorOf(c.n as RunNote) }); + } + } + // The lamp: white on a frame a note starts (or a click), else black. + if (f >= SETUP + 2) out.push({ x: VIEW_X + LAMP_X, y: VIEW_Y + LAMP_Y, unit: RING, color: clicks.has(f) || close.some((n) => n.on === f) ? WHITE : BLACK }); + // One pixel a place: where two are drawn, the last. + return [...new Map(out.map((p) => [`${p.unit} ${p.x} ${p.y}`, p])).values()]; +} + +/** Every frame's picture, worked out once, in order (each depends on the one before). */ +const PICTURES: Pixel[][] = []; +export function pictureAt(f: number): Pixel[] { + while (PICTURES.length <= f) PICTURES.push(draw(PICTURES.length, PICTURES.length ? PICTURES[PICTURES.length - 1] : [])); + return PICTURES[f]; +} + +// The storm's effects: a Disruption Web over each C-a downbeat's chord for 8 frames; in C-b an explosion on each downbeat +// over its highest note, and Battlecruisers across the stage on the last two chords. +for (const n of runNotes) { + if (!n.downbeat || n.hand !== 0) continue; + const top = runNotes.filter((m) => m.on === n.on && m.hand === 0).every((m) => m.note <= n.note); + if (!top) continue; + const x = stageX(n.note), y = VIEW_Y + 120; + if (n.look.webs) { fxList.push({ frame: n.on, kind: 3, x, y }); fxList.push({ frame: n.on + 8, kind: 4, x, y }); } + if (n.look.boom) { + if (n.on >= C_START + Math.round(STORM_BARS[12] / FRAME) - 1) for (const dx of [-240, 0, 240]) fxList.push({ frame: n.on, kind: 2, x: CAM_X + 40 + dx, y: VIEW_Y + 110 }); + else fxList.push({ frame: n.on, kind: 1, x, y }); + } +} +fxList.sort((a, b) => a.frame - b.frame); + +/* ── The tables the program plays back ── */ + +export const CHANGES = changesOver(TOTAL, pictureAt); +/** Where each frame's changes start in the lists below; one more at the end. */ +export const STARTS: number[] = []; +export const CX: number[] = [], CY: number[] = [], CKIND: number[] = [], CTO: number[] = []; +CHANGES.forEach((cs) => { + STARTS.push(CX.length); + for (const c of cs) { CX.push(c.x); CY.push(c.y); CKIND.push(c.unit * 8 + c.from); CTO.push(c.to); } +}); +STARTS.push(CX.length); +export const SOUND_F: number[] = plays.map((s) => s.frame), SOUND_K: number[] = plays.map((s) => s.clip); +export const LABEL_F: number[] = captions.map((l) => l.frame), LABEL_TEXT: string[] = captions.map((l) => l.text); +export const FX_F: number[] = fxList.map((e) => e.frame), FX_K: number[] = fxList.map((e) => e.kind), FX_X: number[] = fxList.map((e) => e.x), FX_Y: number[] = fxList.map((e) => e.y); +/** The most changes in a frame, and where: for the cost. */ +export const BUSIEST = CHANGES.reduce((best, cs, f) => (cs.length > best.n ? { f, n: cs.length } : best), { f: 0, n: 0 }); + diff --git a/tests/fur-elise-run.test.ts b/tests/fur-elise-run.test.ts new file mode 100644 index 0000000..c85c724 --- /dev/null +++ b/tests/fur-elise-run.test.ts @@ -0,0 +1,95 @@ +/** + * The Für Elise visualizer probe's run (probes/lib/fur-elise-run.ts), as the build works it out: the clips start on the + * frames their first notes are drawn, the lamp is lit exactly on onsets, the picture never asks the game for two Flags + * it would not make, and the changes the program plays back rebuild every frame's picture. + */ +import { describe, expect, it } from "vitest"; +import { FRAME, type Pixel } from "../probes/lib/note-timeline"; +import { CELL, VIEW_X, VIEW_Y, LAMP_X, LAMP_Y } from "../probes/lib/fur-elise-layout"; +import { + BAR_FRAME, CHANGES, CLICKS, CLIP_A, CLIP_BAR0, CLIP_STORM, CLIP_THEME, C_START, FLAG, FX_F, LABEL_F, OVERLORD, RING, S1_START, S2_START, + SOUND_F, SOUND_K, STARTS, TOTAL, WHITE, clicks, pictureAt, plays, runNotes, +} from "../probes/lib/fur-elise-run"; + +const onsets = new Set(runNotes.map((n) => n.on)); + +describe("the run", () => { + it("lasts about 100 seconds, its lists in the order the program reads them", () => { + expect(TOTAL * FRAME).toBeGreaterThan(90); + expect(TOTAL * FRAME).toBeLessThan(115); + for (const list of [SOUND_F, LABEL_F, FX_F, STARTS]) expect(list.every((f, k) => k === 0 || list[k - 1] <= f)).toBe(true); + expect(STARTS.length).toBe(TOTAL + 1); + }); + + it("starts each part's clip on the frame its first note is drawn", () => { + const firstFrom = (from: number) => Math.min(...runNotes.filter((n) => n.on >= from).map((n) => n.on)); + const at = (clip: number) => plays.filter((p) => p.clip === clip).map((p) => p.frame); + // The A section, the storm, and the theme as one clip (S1, and V after it). + for (const f of [...at(CLIP_A), ...at(CLIP_STORM), ...at(CLIP_THEME)]) expect(firstFrom(f)).toBe(f); + expect(at(CLIP_THEME)[0]).toBe(S1_START); + expect(at(CLIP_STORM)[0]).toBe(C_START); + // S2: a clip a bar, from the frame each bar starts in; the bar's first note is drawn on that frame or the next. + BAR_FRAME.slice(0, -1).forEach((b, k) => { + const f = at(CLIP_BAR0 + k)[0]; + expect(f).toBe(S2_START + b); + expect(firstFrom(f) - f).toBeLessThanOrEqual(1); + }); + }); + + it("lights the lamp on the frames a note starts, and on the clicks, and on no other", () => { + expect(clicks.size).toBe(CLICKS); + for (let f = 0; f < TOTAL; f++) { + const lamp = pictureAt(f).find((p) => p.unit === RING); + if (!lamp) continue; + expect(lamp.x === VIEW_X + LAMP_X && lamp.y === VIEW_Y + LAMP_Y).toBe(true); + expect(lamp.color === WHITE).toBe(onsets.has(f) || clicks.has(f)); + } + }); + + it("never asks for a Flag overlapping another of its frame or of the frame before", () => { + // A Spider Mine is 15 pixels square: the game puts one made overlapping another beside its place, and one taken away + // stands until its frame ends. + const close = (a: Pixel, b: Pixel) => Math.abs(a.x - b.x) < 16 && Math.abs(a.y - b.y) < 16 && (a.x !== b.x || a.y !== b.y); + let before: Pixel[] = []; + for (let f = 0; f < TOTAL; f++) { + const flags = pictureAt(f).filter((p) => p.unit !== OVERLORD); + for (const p of flags) { + const bad = flags.find((q) => close(p, q)) ?? before.find((q) => close(p, q)); + if (bad) throw new Error(`frame ${f}: ${p.x},${p.y} beside ${bad.x},${bad.y}`); + } + before = flags; + } + }); + + it("plays back changes that rebuild every frame's picture, a unit a pixel", () => { + const shown = new Map(); + let most = 0; + CHANGES.forEach((cs, f) => { + for (const c of cs) { + const k = `${c.unit} ${c.x} ${c.y}`; + expect(shown.get(k) ?? 0).toBe(c.from); + if (c.to) shown.set(k, c.to); + else shown.delete(k); + } + const want = pictureAt(f); + expect(shown.size).toBe(want.length); + for (const p of want) expect(shown.get(`${p.unit} ${p.x} ${p.y}`)).toBe(p.color); + most = Math.max(most, shown.size); + }); + // Units for the pictures at the most, of the game's 1,700. + expect(most).toBeLessThan(600); + }); + + it("keeps the minimap's Overlords on cells two tiles apart, and the stage's Flags on the stage", () => { + for (let f = 0; f < TOTAL; f += 7) { + for (const p of pictureAt(f)) { + if (p.unit === OVERLORD) expect((p.x - CELL / 2) % CELL === 0 && (p.y - CELL / 2) % CELL === 0 && p.y < 92 * 32).toBe(true); + if (p.unit === FLAG) expect(p.x >= VIEW_X + 240 && p.x <= VIEW_X + 852 && p.y >= VIEW_Y + 16 && p.y <= VIEW_Y + 300).toBe(true); + } + } + }); + + it("names the clips it plays in the probe's order", () => { + expect(Math.max(...SOUND_K)).toBe(CLIP_BAR0 + BAR_FRAME.length - 2); + }); +}); From e22ee9bb49ce2302fed499572ade793788e93090 Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 14:20:37 -0600 Subject: [PATCH 06/31] =?UTF-8?q?F=C3=BCr=20Elise=20visualizer=20probe:=20?= =?UTF-8?q?the=20map,=20its=20answer=20sheet,=20and=20pictures=20of=20its?= =?UTF-8?q?=20frames?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit probes/fur-elise-visual.ts plays the run back: a stand-in piano (an FM electric piano) rendered as one clip a part and, for S2, a clip a bar, each started on the frame its first note is drawn; per frame the clips, the text, the pixel changes (made, taken away, or handed to another player with Give Units, which recolours a unit where it stands) and the storm's effects. Parts: clicks with the lamp, the A section (falling a row a frame, then every other frame), the storm (red flashes and Disruption Webs, then explosions), the theme as one clip and as a clip a bar, then rising notes and the keys alone. About 100 seconds. In the lifted game every frame holds exactly the picture worked out (2,470 frames); at most 0.55 ms a frame by Remastered's weights; game-check finds nothing Remastered refuses or ignores. probes/lib/fur-elise-frames.mts draws chosen frames as PNGs from the same run, to look at before a play. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- probes/answers/fur-elise-visual.txt | 62 +++++++++ probes/fur-elise-visual.ts | 203 ++++++++++++++++++++++++++++ probes/lib/fur-elise-frames.mts | 77 +++++++++++ 3 files changed, 342 insertions(+) create mode 100644 probes/answers/fur-elise-visual.txt create mode 100644 probes/fur-elise-visual.ts create mode 100644 probes/lib/fur-elise-frames.mts diff --git a/probes/answers/fur-elise-visual.txt b/probes/answers/fur-elise-visual.txt new file mode 100644 index 0000000..08e0213 --- /dev/null +++ b/probes/answers/fur-elise-visual.txt @@ -0,0 +1,62 @@ +TrigScript Showcase #3 probe: the Für Elise visualizer +====================================================== + +Map: trigscript-fur-elise-visual.scx (lobby "Für Elise visual probe"). About 100 seconds, nothing to press. + +What it asks: does a piano roll drawn by the game look good on video, and does the picture stay with the music? The +piano is a stand-in (an electric piano); the real piano comes from the sound probe. Every note's time is worked out +when the map is built, and the picture of every frame with it. + +What to record +-------------- +- Host it as a multiplayer game, alone (the computer slot stays a computer). Remastered graphics, no F5. +- Options: game MUSIC OFF, sound effects ON (the piano is played as sound effects). Widescreen, as you normally play. +- Record the whole run from the lobby to "The end. Thank you." Do not move the camera or click on the map; the camera + is put back on the stage every 4 seconds anyway. + +What is where +------------- +- Minimap: a piano roll on black. Notes fall onto a keyboard row (white keys white, black keys indigo) that lights as + each key sounds: right hand gold, left hand cyan, the storm's chords red. +- Main screen: the same as Flags: a keyboard of 30 white keys with the black keys above them, notes falling onto it. +- Top left of the main screen: the sync lamp, a start-location ring. Black, and white on each frame a note starts + (and on each click in part T). This is what the recording is measured by: keep it in view. + +The parts (seconds from the start of the game, about; each is named in the text lines as it starts) +--------------------------------------------------------------------------------------------------- +T 2 six clicks, a second apart, the lamp white on each. +A1 9 the A section. Falling notes, a row every frame on the main screen. +A2 22 the same music on: the main screen's notes fall half as fast (a row every other frame). +C-a 45 a stormy passage in D minor: the white keys flash red on each chord, Disruption Webs on the downbeats. +C-b 50 the same storm with explosions on the downbeats (Wraiths, and three Battlecruisers on the last chords). + The game's own explosion sounds will be heard here. +S1 57 the theme twice, played as one long clip. +S2 72 the same theme, played as a clip a bar, each bar started by the game. +V1 86 the theme again, the notes rising from the keys after they sound. +V2 93 the keys alone, no rolls. + 102 "The end. Thank you." + +Questions +--------- +1. Did the lobby show the name with the ü ("Für Elise visual probe"), and the first text line too? -> +2. Minimap: do the falling notes read as a piano roll (columns of dots onto the keyboard row)? Too small, too sparse? -> +3. Minimap: can you tell the hands apart (gold / cyan), and the black keys from the white? -> +4. Main screen: do the Flags read as a keyboard, and the falling notes as notes? Which colours get lost? -> +5. Main screen: A1 (a row a frame) or A2 (half as fast): which is better to watch? Does A1 look smooth? -> +6. Does the picture feel in time with the sound everywhere? Anywhere it feels early or late? -> +7. C-a: do the red flashes look good or too much? Did any Disruption Web appear, and did it make a sound? -> +8. C-b: did the explosions appear where the chords are, and are the game's explosion sounds acceptable over the + music, or should effects be silent? -> +9. S1 and S2 should sound the same. Any stutter, flam or gap in S2 at the bar lines? -> +10. V1 (rising) and V2 (keys alone) against A1 (falling): which look do you want for the Showcase? -> +11. Did the game slow down or stutter anywhere? -> +12. Anything else (a unit in the wrong place, a stray Flag or Overlord, an error text)? -> + +What I measure from the recording (no need to fill in) +------------------------------------------------------ +- T: each click's start in the audio against the lamp turning white: the plain delay between sound and picture. +- A, S1: each note's start (the audio's attacks) against the lamp's flashes, over the whole clip: the delay and + whether it grows (drift) over 34 s and 12 s. +- S2 against S1: the same notes, the same lamp. Each bar of S2 starts on the mixer's 21.3 ms grid on its own, so its + delay may change by up to 21 ms from bar to bar; S1's should stay the same through the clip. +- Minimap redraws: how often the roll moves (expected about 12 times a second). diff --git a/probes/fur-elise-visual.ts b/probes/fur-elise-visual.ts new file mode 100644 index 0000000..6ac74fe --- /dev/null +++ b/probes/fur-elise-visual.ts @@ -0,0 +1,203 @@ +// The Für Elise visualizer probe (TrigScript 4, Showcase #3, S7): does a piano roll drawn by the game look good, and +// does it stay with the music? The piano is rendered when the script is built (an FM electric piano stands in for the +// sound probe's grand), so every note's time is known to the sample; the picture of every frame is worked out then too +// (probes/lib/note-timeline.ts), and the program only plays the changes back, a frame at a time, starting each clip on +// the frame its first note is drawn. +// +// Two screens (probes/lib/fur-elise-layout.ts): +// - the minimap: notes falling onto a keyboard row that lights as each key sounds; a cell an Overlord two tiles +// square over Space (Korobeiniki's board), coloured by hand — right gold, left cyan, the storm's chords red; +// - the main screen: the same as Flags (Spider Mines given a Flag's looks, the main-screen spike's pixel), a keyboard +// of 30 white keys with the black ones above, notes falling a row a frame; a sync lamp at the top left, a start +// location's ring that is white on each frame a note starts and black otherwise. +// +// The parts, each named in the text lines as it starts (seconds from the start of the game, about): +// T 2 six clicks 24 frames apart, the lamp white on each: the plain delay between a sound and a picture +// A1 9 the A section (bars 1–22 with repeats, 34 s): falling notes on both screens, a row a frame on the main one +// A2 22 the same from bar 9: the main screen's notes fall half as fast (a row every other frame) +// C-a 45 a stormy passage in D minor: the white keys flash red on the chords, Disruption Webs on the downbeats +// C-b 50 explosions on the downbeats (Wraiths and Battlecruisers killed: their own explosion sounds will be heard) +// S1 57 the theme twice (12 s) as one clip +// S2 72 the same, a clip a bar, each started on its frame: drift and jitter against S1 +// V1 86 the same again, notes rising from the keys; V2 (93) the keys alone +// the end at 102 +// +// Host it as multiplayer, alone, Remastered graphics, the game's music off; record the whole run. Answer sheet: +// probes/answers/fur-elise-visual.txt. +// +// MAP_NAME="Für Elise visual probe" npx tsx probes/lib/fur-elise-map.mts fixtures/eud/fur-elise-visual-base.scx +// MAP_NAME="Für Elise visual probe" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-visual.ts fixtures/eud/fur-elise-visual.scx fixtures/eud/fur-elise-visual-base.scx +// SCM_SIM_DIR=~/github/scm-sim-eud npx tsx scripts/test-game.mts probes/fur-elise-visual.ts fixtures/eud/fur-elise-visual-base.scx +// +// Remastered will not start a game without a computer, and a computer moves its own units, so Player 2 is a computer +// that owns nothing; P3 … P8 own the pixels, each given a colour: P3 white (white keys, the lamp lit), P4 indigo (black +// keys), P5 gold (right hand), P6 cyan (left hand), P7 red (the storm), P8 black (the lamp dark). +// probe-players: {"0":{"rgb":[16,252,24]},"1":{"rgb":[120,120,120]},"2":{"rgb":[240,240,240]},"3":{"rgb":[72,56,200]},"4":{"rgb":[255,190,0]},"5":{"rgb":[0,200,255]},"6":{"rgb":[235,20,50]},"7":{"rgb":[16,16,16]}} +import { program, nextFrame, print, playWav, centerView, centerLocation, reserveLocation, createUnit, removeUnitAt, killUnitAt, giveUnits, setMemory, units, mixdown, tone, P3, P4, P5, P6, P7, P8, test, expect, type Clip } from "trigscript"; +import { music } from "trigscript/music"; +import { FRAME } from "./lib/note-timeline"; +import type { PlayedNote } from "./lib/fur-elise-score"; +import { CAM_X, CAM_Y, CELL } from "./lib/fur-elise-layout"; +import { + A_NOTES, STORM_NOTES, THEME_NOTES, A_LONG, STORM_LONG, THEME_LONG, BAR_AT, BAR_FRAME, CLICK_EVERY, CLICKS, OVERLORD, + TOTAL, C_START, STARTS, CX, CY, CKIND, CTO, SOUND_F, SOUND_K, LABEL_F, LABEL_TEXT, FX_F, FX_K, FX_X, FX_Y, pictureAt, +} from "./lib/fur-elise-run"; + +/* ── The sound (a stand-in) ── */ + +const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]; +const nameOf = (n: number) => `${NAMES[n % 12]}${Math.floor(n / 12) - 1}`; +const RATE = 44100; +const piano = music.presets.keys({ volume: 0.3 }); +const strings = music.presets.pad({ volume: 0.05 }); +/** How long a note rings: the left hand held as under the pedal, the right a little past its length. */ +const ringing = (n: PlayedNote) => (n.hand === 1 ? Math.max(n.seconds, 0.7) : n.seconds + 0.08); +const hall = (c: Clip) => c.reverb({ decay: 0.75, damping: 0.45, mix: 0.22 }); +/** Notes mixed at their times, from `from` seconds, `seconds` long (tails ring past it); the storm's with the pad under it. */ +function mixNotes(notes: readonly PlayedNote[], from: number, seconds: number, pad: boolean): Clip { + const parts = notes.map((n) => ({ clip: piano.note(nameOf(n.note), ringing(n), RATE).gain(n.velocity), at: n.time - from })); + if (pad) for (const n of notes) parts.push({ clip: strings.note(nameOf(n.note), n.seconds + 0.2, RATE).gain(n.velocity), at: n.time - from }); + return hall(mixdown(parts, seconds + 1.5, RATE)); +} + +const A_CLIP = mixNotes(A_NOTES, 0, A_LONG, false).normalize(0.8); +const STORM_CLIP = mixNotes(STORM_NOTES, 0, STORM_LONG, true).normalize(0.8); +const THEME_MIX = mixNotes(THEME_NOTES, 0, THEME_LONG, false); +const THEME_GAIN = 0.8 / THEME_MIX.peak; +const THEME_CLIP = THEME_MIX.gain(THEME_GAIN); +/** The theme a bar a clip: each bar's notes from the frame the bar starts in, so that played on that frame each lands where the whole clip has it. */ +const BAR_CLIPS: Clip[] = BAR_AT.slice(0, -1).map((t, k) => { + const notes = THEME_NOTES.filter((n) => n.time >= t - 1e-9 && n.time < BAR_AT[k + 1] - 1e-9); + return mixNotes(notes, BAR_FRAME[k] * FRAME, BAR_AT[k + 1] - BAR_FRAME[k] * FRAME, false).gain(THEME_GAIN).ogg(5); +}); +/** The clicks as one clip: the lamp's calibration. */ +const CLICK_CLIP = mixdown(Array.from({ length: CLICKS }, (_, k) => ({ clip: tone(1760, 0.03, { volume: 0.7, rate: RATE }).fade(0, 0.01), at: k * CLICK_EVERY * FRAME })), CLICKS * CLICK_EVERY * FRAME + 0.5, RATE); +/** In the order the run numbers them (CLIP_CLICKS, CLIP_A, …). */ +const CLIPS: Clip[] = [CLICK_CLIP, A_CLIP, STORM_CLIP, THEME_CLIP, ...BAR_CLIPS]; + +/* ── The game side ── */ + +/** units.dat's flingy bytes of types 12 … 15 (Battlecruiser, Spider Mine, Nuclear Missile, Civilian), one dword. */ +const LOOKS = 0x664504; +const looks = (flingy: number) => 70 + flingy * 256 + 109 * 65536 + 71 * 16777216; +/** The flingies a Spider Mine is made with: a Flag's, a start location's ring, its own. */ +const FLAG_LOOK = looks(126), RING_LOOK = looks(140), MINE_LOOK = looks(89); +const OWNERS = [P3, P4, P5, P6, P7, P8]; +const AT = reserveLocation("fur elise: where a pixel is made"); +const FX = reserveLocation("fur elise: where an effect is made"); +const VIEW = reserveLocation("fur elise: the camera"); + +/** + * One pixel changed (kind: unit · 8 + its old colour, 0 none): made, taken away, or handed to the player of its new + * colour — a unit's colour is its owner's, and Give Units changes it where it stands (making one again where one was + * taken away in the same frame would not do: the old one still stands there until the frame ends, and a Spider Mine + * would be put beside it). + */ +function change(x: number, y: number, kind: number, to: number) { + if (kind < 8) { + centerLocation(AT, x, y, 32, 32); + if (kind === 0) OWNERS.forEach((p, k) => { if (to === k + 1) createUnit(p, units.ZergOverlord, 1, AT); }); + else if (to === 0) OWNERS.forEach((p, k) => { if (kind === k + 1) removeUnitAt(p, units.ZergOverlord, 1, AT); }); + else OWNERS.forEach((p, a) => { if (kind === a + 1) OWNERS.forEach((q, b) => { if (to === b + 1) giveUnits(p, q, units.ZergOverlord, 1, AT); }); }); + } else { + centerLocation(AT, x, y, 4, 4); + const from = kind & 7; + if (from === 0) { + if (kind === 16) setMemory(LOOKS, "set", RING_LOOK); + OWNERS.forEach((p, k) => { if (to === k + 1) createUnit(p, units.SpiderMine, 1, AT); }); + if (kind === 16) setMemory(LOOKS, "set", FLAG_LOOK); + } else if (to === 0) OWNERS.forEach((p, k) => { if (from === k + 1) removeUnitAt(p, units.SpiderMine, 1, AT); }); + else OWNERS.forEach((p, a) => { if (from === a + 1) OWNERS.forEach((q, b) => { if (to === b + 1) giveUnits(p, q, units.SpiderMine, 1, AT); }); }); + } +} + +function effect(kind: number, x: number, y: number) { + centerLocation(FX, x, y, 64, 64); + if (kind === 1) { createUnit(P7, units.TerranWraith, 1, FX); killUnitAt(P7, units.TerranWraith, 1, FX); } + else if (kind === 2) { createUnit(P7, units.TerranBattlecruiser, 1, FX); killUnitAt(P7, units.TerranBattlecruiser, 1, FX); } + else if (kind === 3) createUnit(P7, units.DisruptionWeb, 1, FX); + else removeUnitAt(P7, units.DisruptionWeb, 1, FX); +} + +program(async () => { + centerLocation(VIEW, CAM_X, CAM_Y, 32, 32); + centerView(VIEW); + let g = 0, i = 0, s = 0, l = 0, e = 0, camera = 0; + while (g < TOTAL) { + // The sounds of this frame first, then its picture: both reach the game in the same pass of its triggers. + while (s < SOUND_F.length && SOUND_F[s] === g) { + const k = SOUND_K[s]; + CLIPS.forEach((c, j) => { if (k === j) playWav(c, 0); }); + s++; + } + while (l < LABEL_F.length && LABEL_F[l] === g) { + const k = l; + LABEL_TEXT.forEach((t, j) => { if (k === j) print(t); }); + l++; + } + const end = STARTS[g + 1]; + if (i < end) { + setMemory(LOOKS, "set", FLAG_LOOK); + while (i < end) { change(CX[i], CY[i], CKIND[i], CTO[i]); i++; } + setMemory(LOOKS, "set", MINE_LOOK); + } + while (e < FX_F.length && FX_F[e] === g) { effect(FX_K[e], FX_X[e], FX_Y[e]); e++; } + // The camera put back on the stage now and then, in case it was moved. + camera++; + if (camera >= 96) { camera = 0; centerView(VIEW); } + await nextFrame(); + g++; + } +}); + +/* ── Tests: the picture the game holds is the one worked out ── */ + +/** The pixels a frame shows, as text to compare: "unit owner x y" each, sorted. */ +function expected(f: number): string[] { + return pictureAt(f).map((p) => `${p.unit === OVERLORD ? "o" : "m"} ${p.color + 1} ${p.x} ${p.y}`).sort(); +} + +/** What the game holds: Overlords and Spider Mines of P3 … P8 where the board is, as the same text. */ +function held(sim: { units(q: { type: number }): readonly { x: number; y: number; owner: number; alive: boolean }[] }, snap: (v: number) => number): string[] { + const out: string[] = []; + for (const u of sim.units({ type: units.ZergOverlord })) if (u.alive && u.owner >= 2 && u.owner <= 7) out.push(`o ${u.owner} ${snap(u.x)} ${snap(u.y)}`); + for (const u of sim.units({ type: units.SpiderMine })) if (u.alive && u.owner >= 2 && u.owner <= 7) out.push(`m ${u.owner} ${u.x} ${u.y}`); + return out.sort(); +} + +/** Whether what the game holds after `frames` is the picture of one of the frames around then (the program starts a frame or two in). */ +function matches(sim: Parameters[0], frames: number): string { + // An Overlord is made a few pixels off its cell's centre: snapped back to it. + const got = held(sim, (v) => Math.round((v - CELL / 2) / CELL) * CELL + CELL / 2); + for (let f = frames - 4; f <= frames; f++) if (expected(f).join("|") === got.join("|")) return ""; + const want = expected(frames - 2); + const missing = want.filter((w) => !got.includes(w)), extra = got.filter((w) => !want.includes(w)); + return `frame ${frames}: ${missing.length} missing (${missing.slice(0, 4).join(", ")}), ${extra.length} extra (${extra.slice(0, 4).join(", ")})`; +} + +test("every frame of the run shows the picture worked out, and the end is said", (sim) => { + sim.frames(20); + let wrong = "", most = 0; + for (let f = 21; f < TOTAL && !wrong; f++) { + sim.frames(1); + wrong = matches(sim, f); + most = Math.max(most, sim.units({}).filter((u) => u.alive).length); + } + expect(wrong).toBe(""); + // Of the game's 1,700 units, with the Map Revealers. + expect(most < 1000 ? "fewer than 1000" : `${most}`).toBe("fewer than 1000"); + sim.frames(20); + expect(sim).toHavePrinted("The end. Thank you."); +}); + +test("the storm's effects: the explosions leave nothing behind, and no Disruption Web stays", (sim) => { + // Each explosion is a Wraith or a Battlecruiser made and killed in one pass: none is ever seen alive. (Made and not + // killed, all five Wraiths stood there, in the game and the simulator; a Disruption Web made by a trigger is refused + // by 1.16.1, the lifted game — whether Remastered makes it is for the play.) + const alive = () => sim.units({ type: units.TerranWraith }).filter((u) => u.alive).length + sim.units({ type: units.TerranBattlecruiser }).filter((u) => u.alive).length; + sim.frames(C_START); + let most = 0; + for (let f = 0; f < Math.round(STORM_LONG / FRAME) + 20; f++) { sim.frames(1); most = Math.max(most, alive()); } + expect(most).toBe(0); + expect(sim.units({ type: units.DisruptionWeb }).filter((u) => u.alive).length).toBe(0); +}); diff --git a/probes/lib/fur-elise-frames.mts b/probes/lib/fur-elise-frames.mts new file mode 100644 index 0000000..c4840e3 --- /dev/null +++ b/probes/lib/fur-elise-frames.mts @@ -0,0 +1,77 @@ +// Pictures of the Für Elise visualizer probe's frames as the build works them out (probes/lib/fur-elise-run.ts), to +// look at before a play: the minimap at Remastered's 3 pixels a tile (Space black, the stage's Platform grey, a unit a +// dot in its owner's colour) beside the main screen's view (852 × 330 game pixels, a Flag a coloured block, the lamp a +// ring). Not the game's own drawing — the lifted game draws nothing — but its units, where the probe puts them. +// +// npx tsx probes/lib/fur-elise-frames.mts [frame …] +// +// Writes /frame-NNNN.png for each frame (some of each part when none is named) and /sheet.png of them. +// Needs a scm-js checkout beside this one (its PNG encoder). +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { MAP_W, MAP_H, STAGE_TILES, VIEW_X, VIEW_Y } from "./fur-elise-layout.ts"; +import { A_BARS, BAR_AT, C_START, OVERLORD, RING, S1_START, STORM_BARS, TOTAL, pictureAt, plays, CLIP_A, CLIP_THEME } from "./fur-elise-run.ts"; +import { FRAME } from "./note-timeline.ts"; + +const E = process.env.SCMJS_DIR ?? join(import.meta.dirname, "..", "..", "..", "scm-js"); +const { encodePng } = await import(join(E, "src/formats/png.ts")); +const [out, ...named] = process.argv.slice(2); +if (!out) { console.error("usage: fur-elise-frames.mts [frame …]"); process.exit(2); } +mkdirSync(out, { recursive: true }); + +/** The colours of P3 … P8 as the map gives them (the probe's probe-players line), by the run's colour numbers 1 … 6. */ +const RGB: readonly (readonly [number, number, number])[] = [[0, 0, 0], [240, 240, 240], [72, 56, 200], [255, 190, 0], [0, 200, 255], [235, 20, 50], [16, 16, 16]]; +const A_START = plays.find((p) => p.clip === CLIP_A)!.frame; +const V_START = plays.filter((p) => p.clip === CLIP_THEME)[1].frame; +const at = (start: number, seconds: number) => start + Math.round(seconds / FRAME); +const frames = named.length ? named.map(Number) : [ + at(A_START, 3), at(A_START, A_BARS[3]), at(A_START, A_BARS[20]), at(C_START, STORM_BARS[2] + 0.01), at(C_START, STORM_BARS[9]), + at(C_START, STORM_BARS[13]), at(S1_START, 6), at(V_START, BAR_AT[4]), at(V_START, BAR_AT[12]), +].filter((f) => f < TOTAL).sort((a, b) => a - b); + +const T = 3, MW = MAP_W * T, MH = MAP_H * T, VW = 852, VH = 330, GAP = 12; +const W = MW + GAP + VW, H = Math.max(MH, VH); + +function render(f: number): Uint8Array { + const px = new Uint8Array(W * H * 4).fill(255); + const set = (x: number, y: number, [r, g, b]: readonly number[]) => { + if (x < 0 || y < 0 || x >= W || y >= H) return; + const i = (Math.floor(y) * W + Math.floor(x)) * 4; + px[i] = r; px[i + 1] = g; px[i + 2] = b; + }; + const box = (x0: number, y0: number, w: number, h: number, c: readonly number[]) => { for (let y = y0; y < y0 + h; y++) for (let x = x0; x < x0 + w; x++) set(x, y, c); }; + box(0, 0, W, H, [24, 24, 24]); + // The minimap: Space black above, the Platform grey where the stage is. + box(0, 0, MW, MH, [4, 4, 10]); + box(STAGE_TILES.x * T, STAGE_TILES.y * T, STAGE_TILES.w * T, Math.min(STAGE_TILES.h, MAP_H - STAGE_TILES.y) * T, [70, 70, 78]); + // The main screen's view: the Platform. + box(MW + GAP, 0, VW, VH, [58, 60, 66]); + for (const p of pictureAt(f)) { + const c = RGB[p.color]; + // On the minimap, every unit a dot: an Overlord's two tiles, a Spider Mine's one. + const s = p.unit === OVERLORD ? 5 : 2; + box(Math.round((p.x / 32) * T - s / 2), Math.round((p.y / 32) * T - s / 2), s, s, c); + if (p.unit === OVERLORD) continue; + const vx = MW + GAP + p.x - VIEW_X, vy = p.y - VIEW_Y; + if (p.unit === RING) { + // A start location's ring, 121 × 62, as an outline. + for (let a = 0; a < 360; a += 1) for (const r of [0.92, 1]) set(vx + Math.cos((a * Math.PI) / 180) * 60 * r, vy + Math.sin((a * Math.PI) / 180) * 31 * r, c); + } else { + // A Flag: its cloth in the owner's colour, about 14 × 12 above a grey pole. + box(vx - 1, vy - 14, 2, 26, [150, 150, 150]); + box(vx + 1, vy - 14, 12, 11, c); + } + } + return px; +} + +const cols = 2, SW = cols * (W + 8), SH = Math.ceil(frames.length / cols) * (H + 8); +const sheet = new Uint8Array(SW * SH * 4).fill(200); +for (const [i, f] of frames.entries()) { + const px = render(f); + writeFileSync(join(out, `frame-${String(f).padStart(4, "0")}.png`), await encodePng({ width: W, height: H, rgba: px })); + const left = (i % cols) * (W + 8) + 4, top = Math.floor(i / cols) * (H + 8) + 4; + for (let y = 0; y < H; y++) sheet.set(px.subarray(y * W * 4, (y + 1) * W * 4), ((top + y) * SW + left) * 4); +} +writeFileSync(join(out, "sheet.png"), await encodePng({ width: SW, height: SH, rgba: sheet })); +console.log(`${frames.length} frames (${frames.map((f) => `${f} = ${(f * FRAME).toFixed(1)} s`).join(", ")}) to ${out}`); From 3160bb471990e0f7fe027cd9e7fcbd02d013b1db Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 14:20:42 -0600 Subject: [PATCH 07/31] Plan: the S7 visualizer probe as built What the probe draws and how, what the lifted game showed (a Spider Mine is never made overlapping another, and one taken away stands until its frame ends; Give Units recolours in place; 1.16.1 refuses a Disruption Web), its cost, what to measure from the recording, and the choices left for after the play. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index dafc3b8..41941e8 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6548,6 +6548,73 @@ anyone else's name. `fur-elise-visual` (visualizer: worktree ~/github/plugin-trigscript-fur-elise-visual). Each records its results below in its own subsection. +#### S7 visualizer probe (built 2026-11-08) + +Branch `fur-elise-visual`. The question: does a piano roll drawn by the game look good, and does it stay with the music +when the music is rendered and the picture is played back frame by frame? + +**How it is made.** Everything is worked out when the script is built. `probes/lib/fur-elise-score.ts` is our own +transcription of the A section (bars 1–22 with both repeats, 45 bars, 34 s) and a passage of our own in the manner of the +D-minor C section (14 bars, 10 s: chords on every eighth over repeated low D's, a diminished arpeggio over repeated A's, +a last chord), played on a tempo that moves (downbeats 6% long, `rit` bars slowing to their end), so the notes are not +on a grid. Bars 12–14 (the octave E's before the theme returns) are from memory and must be checked against an edition. +The sound is a stand-in: `music.presets.keys` mixed at each note's time with `mixdown`, a plate reverb, one Ogg a part; +the storm adds a pad. `probes/lib/note-timeline.ts` (tested in `tests/note-timeline.test.ts`) puts notes on the game's +clock (`frameNotes`: nearest frame, at least one frame long, chords marked), fits the keyboard (`keyRange`, `keyX`), +works out a roll's cells at a frame (`rollCells`, falling or rising, a row standing for `step` frames) and turns pictures +into changes (`changesOver`). `probes/lib/fur-elise-run.ts` (tested in `tests/fur-elise-run.test.ts`) lays the parts +end to end, draws every frame's picture and flattens the changes into four tables (x, y, unit and old colour, new +colour; 78,861 changes over 2,451 frames, 1.5 MB of payload). The program only reads them: per frame, the clips that +start, the text, the changes (made, taken away, or handed to another player with Give Units), the effects. + +**The screens** (`probes/lib/fur-elise-layout.ts`, base map `probes/lib/fur-elise-map.mts`, 128 × 128 Space Platform, +Map Revealers placed): the minimap roll is Korobeiniki's Overlord board, a cell two tiles, a column a key, D2–E6 (51 of +the 64 columns), 40 rows a row every two frames (3.4 s ahead), a two-row keyboard (every key above, the white keys' +fronts below). The main screen is a stage on Platform: 30 white keys 20 px apart with the black keys a row above, +falling notes 12 rows of 18 px, all Flag-looking Spider Mines (the S6 spike's pixel, made with units.dat's flingy +written around each Create Unit). Colours by owner, set with CRGB: P3 white keys, P4 indigo black keys, P5 gold right +hand, P6 cyan left hand, P7 red storm chords, P8 black; P2 the computer owns nothing. The sync lamp is a start-location +ring at the view's top left, white on every frame a note starts and black otherwise. + +**The parts** (seconds from the start): T 2, six clicks 24 frames apart in one clip with the lamp; A1 9, the A section, +the stage falling a row a frame; A2 22, from bar 9 the stage falls a row every two frames; C-a 45, the storm, white +keys flashing red for two frames on each chord, a Disruption Web over each downbeat for 8 frames; C-b 50, explosions +(a Wraith made and killed on each downbeat, three Battlecruisers on the last two chords; their death sounds are +heard); S1 57, the theme twice (17 bars, 12 s) as one clip; S2 72, the same as a clip a bar, each bar's notes mixed from +the frame the bar starts in and played on that frame, so each note lands where S1 has it; V1 86, the theme with notes +rising from the keys; V2 93, the keys alone; the end at 102. + +**Found on the way, in the lifted game:** +- A Spider Mine made where it would overlap another is put beside its place, and one taken away in the same frame still + counts until the frame ends. Recolouring by Remove + Create at the same spot moved the new one; Give Units (the + owner, so the colour, changes where the unit stands) does not. The layout keeps every two mines at least 16 px apart + and rows 18 apart; a falling cell that would overlap one of its frame or the frame before waits a frame (the D#5 next + to a departing E5 was the case that showed it). With that, every frame of the run in the lifted game holds exactly + the worked-out picture (test "every frame of the run …", 2,470 frames). +- A Disruption Web made by Create Unit is refused by 1.16.1; Remastered is for the play. Wraiths and Battlecruisers are + made (seen with the kill left out) and none is ever alive after its frame. Reading their deaths gave 0 — the build's + variables live in the deaths table, so deaths are no check for this. +- A probe's module-level `sounds` collides with a name of the build (`Identifier 'sounds' has already been declared`). + +**Cost** (A4's tap, lifted game): 8,775 conditions and actions a frame on average, 54,932 at the most (frame 1078, the +storm's flashes and chords: 193 changes in one frame) — 0.09 ms on average, 0.55 ms at the most by Remastered's weights, +of ~15 ms. `game-check`: 321,098 accesses, 0 ending the game, 0 ignored, 0 never seen. Units for the pictures: under 600 +at once. Map 1.66 MB (the payload, 1.5 MB, compresses well; the rest is the Ogg clips). + +**What to measure from the recording** (sheet `probes/answers/fur-elise-visual.txt`; Remastered graphics, music off, +sound effects on, the whole run): T, each click against the lamp turning white — the plain audio-to-picture delay; +A and S1, each attack in the audio against the lamp, over 34 s and 12 s — the delay and any drift within one long clip; +S2 against S1, the same notes, each bar on the mixer's grid on its own (0–21 ms bar to bar); the minimap's redraw rate +from the roll's movement. Bad Apple's picture led its sound by 23 ms with no drift over 3½ minutes; if the delay here is +steady, the Showcase can shift the picture by a frame to meet it. + +**Open, for the user after the play:** falling (A1/A2) or rising (V1) or keys alone (V2); a row a frame or every other +frame on the main screen; red flashes and Disruption Webs (if Remastered makes them) for the storm, or explosions with +their sounds, or neither; whether the Flags read as a keyboard (the S6 rule: bright, saturated colours only); whether the +minimap roll is big enough to show in the video or the main screen carries it alone. Not built: a fog-board roll +(Remastered graphics blurs the fog minimap and it has two tones, no hands; the unit board played well for Korobeiniki), +hallucinations (a unit's hallucinated flag is not its tint) and spells by order (no Cast order from a trigger). + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice From 2d2f85e695444ebef39dd15814a8f3005c47ca15 Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 14:34:27 -0600 Subject: [PATCH 08/31] Loudness as the game plays one channel; a re-struck key cuts the tail before it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Clip.lufs` measured a clip of one channel as BS.1770 does, on one side: 3 dB under what the game plays (it plays one channel from both sides), so a mono render brought to −16 came out at −12.9. Measured from both sides now. A sampled note let go (no pedal) died over its release — a second on a piano — and a fast repeated note (Für Elise's E–D#) struck again 0.23 s later still had the one before 7 dB down under it. The release now ends a tenth of a second after the key is struck again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- compiler/declarations.ts | 3 ++- compiler/dsp.ts | 4 +++- compiler/generated/stdlib.ts | 2 +- stdlib/music.ts | 14 ++++++++++---- tests/sampled.test.ts | 5 +++-- 5 files changed, 19 insertions(+), 9 deletions(-) diff --git a/compiler/declarations.ts b/compiler/declarations.ts index 97d4034..42d64bc 100644 --- a/compiler/declarations.ts +++ b/compiler/declarations.ts @@ -563,7 +563,8 @@ ${kw}interface Clip { readonly peak: number; /** * How loud it is as a whole, in LUFS (ITU-R BS.1770, the figure EBU R 128 and the streaming services use): −14 to - * −16 for music heard on its own, −23 for broadcast. Reading it works the samples out. + * −16 for music heard on its own, −23 for broadcast. One channel is measured as the game plays it, from both + * sides. Reading it works the samples out. */ readonly lufs: number; /** The part from \`from\` to \`to\` seconds (the end when left out). */ diff --git a/compiler/dsp.ts b/compiler/dsp.ts index a853444..6931951 100644 --- a/compiler/dsp.ts +++ b/compiler/dsp.ts @@ -333,9 +333,11 @@ function biquad(x: Float32Array, [b0, b1, b2, a1, a2]: Biquad): Float32Array { * Integrated loudness in LUFS, as ITU-R BS.1770-4 measures it (EBU R 128's figure): each channel through the K-weighting * (a high shelf, +4 dB above 1.7 kHz, then a high-pass at 38 Hz, made for the clip's rate as libebur128 makes them), * its power over 400 ms blocks three-quarters overlapping, the blocks under −70 LUFS left out, then those more than - * 10 LU under the mean of the rest. −Infinity for silence. + * 10 LU under the mean of the rest. −Infinity for silence. A clip of one channel is measured as the game plays it, from + * both sides (a full-scale 997 Hz sine: 0 LUFS, where BS.1770 has −3.01 for it on one channel alone). */ export function loudness(chans: Channels, rate: number): number { + if (chans.length === 1) chans = [chans[0], chans[0]]; let K = Math.tan((Math.PI * 1681.974450955533) / rate); const Vh = 10 ** (3.999843853973347 / 20), Vb = Vh ** 0.4996667741545416, Q1 = 0.7071752369554196; let a0 = 1 + K / Q1 + K * K; diff --git a/compiler/generated/stdlib.ts b/compiler/generated/stdlib.ts index f961af5..61c3935 100644 --- a/compiler/generated/stdlib.ts +++ b/compiler/generated/stdlib.ts @@ -3,7 +3,7 @@ export const STDLIB_SOURCES: Readonly> = { "cutscene": "/**\n * Scenes acted out in the game: the standard library's \"trigscript/cutscene\" (TrigScript 4).\n *\n * import { Camera, walk, line, play, SECOND } from \"trigscript/cutscene\";\n *\n * async function intro(raider: Unit) {\n * const cam = new Camera(raider.x, raider.y);\n * await line(units.JimRaynorMarine, \"Something's moving out there.\", 3 * SECOND);\n * const there = start(walk(raider, 1200, 640)); // the walk goes on while the camera follows\n * await cam.follow(raider, 2 * SECOND);\n * await there;\n * await cam.pan(1600, 400, 2 * SECOND);\n * await cam.shake(12);\n * }\n *\n * program(async () => {\n * const raider = first(unitsAt(locations.Base, { owner: P1, type: units.TerranMarine }));\n * if (!raider) return;\n * const skipped = await play(P1, start(intro(raider))); // Escape skips the rest of it\n * if (skipped) print(\"Skipped.\");\n * });\n *\n * Everything here is what a trigger can do, done a frame at a time: the camera is Center View on a location the library\n * keeps for itself, moved to where the camera should look; a unit walks by a Move order to another; a line is the\n * speaker's portrait talking and the words in the middle of the screen. Places are pixels (32 a tile), (0, 0) the map's\n * top left; time is frames of the game, 24 a second on Fastest (`SECOND`). The camera is the one of the player the\n * program runs as, as Center View's is.\n */\nimport { centerLocation, centerView, reserveLocation, talkingPortrait, print, sleep, frames, nextFrame, keyPressed, type Player, type Task, type Unit, type UnitType } from \"trigscript\";\nimport { easeInOutQuad, easeInQuad, easeOutQuad, easeOutBack } from \"trigscript/math\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nexport const SECOND = 24;\n\nconst VIEW = reserveLocation(\"cutscene: where the camera looks\");\nconst GOAL = reserveLocation(\"cutscene: where a unit is sent\");\n\n/** How a glide speeds up and slows down: evenly, starting slow, ending slow, both, or ending past the mark and back. */\nexport type Ease = \"linear\" | \"in\" | \"out\" | \"inOut\" | \"back\";\n\n/** How far along a glide is at `t` (0 at its start, 1 at its end), as `ease` has it. */\nfunction eased(t: fixed, ease: Ease): fixed {\n if (ease === \"in\") return easeInQuad(t);\n if (ease === \"out\") return easeOutQuad(t);\n if (ease === \"inOut\") return easeInOutQuad(t);\n if (ease === \"back\") return easeOutBack(t);\n return t;\n}\n\n/**\n * The camera of the player the program runs as: where it looks, and how it gets somewhere else. It looks at its first\n * place as soon as it is made.\n */\nexport class Camera {\n /** The point the camera is centred on, in pixels. */\n x: number;\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /** Look at a point, now. */\n look(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /**\n * Glide to a point over `time` frames, looking at each place on the way a frame at a time.\n * @param ease How it speeds up and slows down; \"inOut\" unless it says.\n */\n async pan(x: number, y: number, time: number, ease: Ease = \"inOut\") {\n const fromX = this.x;\n const fromY = this.y;\n let i = 1;\n while (i <= time) {\n const k = eased(fixed(i) / time, ease);\n this.look(fromX + Math.round((x - fromX) * k), fromY + Math.round((y - fromY) * k));\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n\n /** Keep a unit in the middle of the screen for `time` frames, or until it is gone. */\n async follow(u: Unit, time: number) {\n let i = 0;\n while (i < time && u) {\n this.look(u.x, u.y);\n await nextFrame();\n i++;\n }\n }\n\n /** Shake for `time` frames, `size` pixels each way (8 unless it says), and settle where it was. */\n async shake(time: number, size: number = 8) {\n const x = this.x;\n const y = this.y;\n let i = 0;\n while (i < time) {\n const left = (i % 4) < 2;\n const up = (i % 2) === 0;\n centerLocation(VIEW, left ? x - size : x + size, up ? y - size : y + size);\n centerView(VIEW);\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n}\n\n/**\n * Send a unit to a point by a Move order, and wait until it is there — within `near` pixels (48 unless it says) — or\n * `limit` frames have passed (30 seconds unless it says), or it is gone.\n * @returns Whether it got there.\n */\nexport async function walk(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"move\", near, limit);\n}\n\n/** The same with an Attack order: the unit fights what it meets on the way. */\nexport async function charge(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"attack\", near, limit);\n}\n\nasync function go(u: Unit, x: number, y: number, how: \"move\" | \"attack\", near: number, limit: number): Promise {\n centerLocation(GOAL, x, y);\n u.order(how, GOAL);\n let waited = 0;\n while (u && Math.abs(u.x - x) + Math.abs(u.y - y) > near && waited < limit) {\n await nextFrame();\n waited++;\n }\n return !!u && Math.abs(u.x - x) + Math.abs(u.y - y) <= near;\n}\n\n/**\n * Send every unit of a group to a point together, and wait until each is there, gone, or `limit` frames have passed.\n * @returns How many got there.\n */\nexport async function walkAll(group: Unit[], x: number, y: number, near: number = 64, limit: number = 30 * SECOND): Promise {\n centerLocation(GOAL, x, y);\n for (const u of group) if (u) u.order(\"move\", GOAL);\n let waited = 0;\n let there = 0;\n while (waited < limit) {\n there = 0;\n let moving = 0;\n for (const u of group) {\n if (!u) continue;\n if (Math.abs(u.x - x) + Math.abs(u.y - y) <= near) there++;\n else moving++;\n }\n if (moving === 0) break;\n await nextFrame();\n waited++;\n }\n return there;\n}\n\n/**\n * A line of the scene: the speaker's portrait talks and the words show in the middle of the screen, for `time` frames\n * (3 seconds unless it says), and then the scene goes on.\n */\nexport async function line(speaker: UnitType, text: string, time: number = 3 * SECOND) {\n talkingPortrait(speaker, Math.round((time * 1000) / SECOND));\n print(text, { position: \"center\" });\n await sleep(frames(time));\n}\n\n/**\n * Play a scene, started as a task (`start(intro())`), for a player who may skip it: when they press `key` (Escape unless\n * it says) the scene stops where it is. Put things where the scene would have left them when it gives true.\n * @returns Whether it was skipped.\n */\nexport async function play(player: Player, scene: Task, key: \"Escape\" | \"Space\" | \"Enter\" = \"Escape\"): Promise {\n while (scene.running) {\n if (keyPressed(player, key)) {\n scene.cancel();\n return true;\n }\n await nextFrame();\n }\n return false;\n}\n", "fog": "/**\n * Fog of war as a picture: the standard library's \"trigscript/fog\" (TrigScript 4).\n *\n * import { fog } from \"trigscript/fog\";\n *\n * const heart = fog.picture([\".##.##.\", \"#######\", \".#####.\", \"..###..\"]);\n *\n * program(async () => {\n * fog.reveal(P1); // the whole map lit once: from now on dark is fog, not black\n * while (true) {\n * fog.light(P1, 30, 20, 5); // a disc of size 5 around tile (30, 20), this frame only\n * fog.light(P1, 60, 40, heart); // a picture, its top left on tile (60, 40)\n * await nextFrame();\n * }\n * });\n *\n * The fog is a canvas that starts every frame dark: what a program lights this frame is what shows this frame, and\n * nothing else needs doing. There is no dark brush — the game's sight only ever reveals — so dark is whatever is not\n * lit; to draw dark shapes, light around them (a picture with `{ ink: \"dark\" }`). Dark is also the sharper ink: a lit\n * part is at least a brush wide (3 tiles across, 4 down), while a dark line one tile wide stays exactly that. Nothing\n * else needs doing — the library writes the game's vision countdown after every frame (memory.vision.countdown), so\n * the next frame starts from a wiped board. Watch it on the minimap. With Classic graphics (Options > Graphics) a tile\n * of the map is a pixel there, sharp; Remastered graphics blurs it a few tiles wide.\n *\n * What the board is made of decides how far apart lit and fog look. Remastered draws a tile on the minimap as the\n * average of its art and fog as 0.64 of lit, whatever the tile, so the brightest art is the best board there: plain\n * Ice snow (lit 130 against fog 82, measured 2026-10-19). Classic draws a tile as one colour of its own; Badlands\n * tile 23778 is the widest apart there, and dim and textured in Remastered. Snow played the better of the two.\n *\n * How it draws, played in StarCraft: Remastered (2026-10-17): a brush is a unit made on a tile and taken away in the\n * same trigger pass; the tiles its sight revealed stay lit through the frame. A brush's size is the unit's sight\n * range, so each size is a unit type of its own — the flying heroes below, which no ordinary map places — whose sight\n * is set every frame (Remastered takes a sight write a frame late, so one type cannot change size within a frame).\n * Coordinates are tiles, (0, 0) the map's top left. About 800 brushes a frame is the most the game makes: it keeps a\n * removed unit's place until the next frame.\n */\nimport { game, program, sleep, frames, stats, units, createUnit, removeUnit, centerLocation, reserveLocation, memory, cover, nextFrame, type Player, type UnitType, type Video } from \"trigscript\";\n\n/**\n * Each brush's shape, sizes 1 to 11: the tiles a flying unit of that sight range reveals, read out of the game.\n * \"@\" is the tile the brush is centred on. The game's air sight leaves the centre's row one short below, so every\n * shape reaches a row further up than down.\n */\nexport const SHAPES: readonly (readonly string[])[] = [\n // 1\n [\"###\", \"###\", \"#@#\", \"###\"],\n // 2\n [\".###.\", \"#####\", \"#####\", \"##@##\", \"#####\", \"#####\"],\n // 3\n [\"..###..\", \"#######\", \"#######\", \"#######\", \"###@###\", \"#######\", \"#######\", \"#######\"],\n // 4\n [\"..#####...\", \".#######..\", \"#########.\", \"##########\", \"##########\", \"####@#####\", \"##########\", \"##########\", \"#########.\", \".#######..\", \"......#...\"],\n // 5\n [\"...#####....\", \"..#######...\", \".#########..\", \"###########.\", \"############\", \"############\", \"#####@######\", \"############\", \"############\", \"###########.\", \".#########..\", \"..#######...\", \".......#....\"],\n // 6\n [\"....#####.....\", \"..#########...\", \".###########..\", \"#############.\", \"#############.\", \"##############\", \"##############\", \"######@#######\", \"##############\", \"##############\", \"#############.\", \"#############.\", \".###########..\", \"..#########...\", \"........#.....\"],\n // 7\n [\".....#####......\", \"...#########....\", \"..###########...\", \".#############..\", \"###############.\", \"###############.\", \"################\", \"################\", \"#######@########\", \"################\", \"################\", \"###############.\", \"###############.\", \".#############..\", \"..###########...\", \"...#########....\", \".........#......\"],\n // 8\n [\"......#####.......\", \"....#########.....\", \"..#############...\", \".###############..\", \".###############..\", \"#################.\", \"#################.\", \"##################\", \"##################\", \"########@#########\", \"##################\", \"##################\", \"#################.\", \"#################.\", \".###############..\", \".###############..\", \"..#############...\", \"....#########.....\", \"..........#.......\"],\n // 9\n [\"......#######.......\", \"....###########.....\", \"...#############....\", \"..###############...\", \".#################..\", \"###################.\", \"###################.\", \"####################\", \"####################\", \"####################\", \"#########@##########\", \"####################\", \"####################\", \"####################\", \"###################.\", \"###################.\", \".#################..\", \"..###############...\", \"...#############....\", \"....###########.....\", \"........#####.......\"],\n // 10\n [\".......#######........\", \".....###########......\", \"....#############.....\", \"..#################...\", \"..#################...\", \".###################..\", \"#####################.\", \"#####################.\", \"######################\", \"######################\", \"######################\", \"##########@###########\", \"######################\", \"######################\", \"######################\", \"#####################.\", \"#####################.\", \".###################..\", \"..#################...\", \"..#################...\", \"....#############.....\", \".....###########......\", \".........#####........\"],\n // 11\n [\"........#######.........\", \"......###########.......\", \"....###############.....\", \"...#################....\", \"..###################...\", \".#####################..\", \".#####################..\", \"#######################.\", \"#######################.\", \"########################\", \"########################\", \"########################\", \"###########@############\", \"########################\", \"########################\", \"########################\", \"#######################.\", \"#######################.\", \".#####################..\", \".#####################..\", \"..###################...\", \"...#################....\", \"....###############.....\", \"......###########.......\", \"..........#####.........\"],\n];\n\n/** Each size's unit, size 1 first: flying heroes without a sight upgrade. A map that places one gets odd sight from it. */\nconst BRUSHES: readonly UnitType[] = [\n units.KukulzaMutalisk, units.KukulzaGuardian, units.YggdrasillOverlord, units.MagellanScienceVessel,\n units.GantrithorCarrier, units.HyperionBattlecruiser, units.NoradIIBattlecruiser, units.TomKazanskyWraith,\n units.DanimothArbiter, units.MojoScout, units.ArtanisScout,\n];\n\n/** Where each brush is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"fog: where each brush is made\");\n\n/**\n * One disc: the tiles a brush of `size` covers (SHAPES), centred on tile (x, y). What light() does with a size. A brush\n * is a unit made where SPOT is and taken away again at once; each branch makes its own size's, so that the unit type\n * of the action is known when the script is built (one given by the program costs writing it into the action).\n */\nconst disc = game((player: Player, x: number, y: number, size: number) => {\n discPx(player, x * 32 + 16, y * 32 + 16, size);\n});\n\n/**\n * disc() in pixels, (px, py) the centre of the tile: what a caller with many brushes uses, its products by 32 worked\n * out once and the brushes' offsets added (a product by 32 of a number the game holds is a test a bit, about 0.4 µs).\n */\nconst discPx = game((player: Player, px: number, py: number, size: number) => {\n centerLocation(SPOT, px, py, 32, 32);\n switch (size) {\n case 0: case 1: createUnit(player, BRUSHES[0], 1, SPOT); removeUnit(player, BRUSHES[0]); break;\n case 2: createUnit(player, BRUSHES[1], 1, SPOT); removeUnit(player, BRUSHES[1]); break;\n case 3: createUnit(player, BRUSHES[2], 1, SPOT); removeUnit(player, BRUSHES[2]); break;\n case 4: createUnit(player, BRUSHES[3], 1, SPOT); removeUnit(player, BRUSHES[3]); break;\n case 5: createUnit(player, BRUSHES[4], 1, SPOT); removeUnit(player, BRUSHES[4]); break;\n case 6: createUnit(player, BRUSHES[5], 1, SPOT); removeUnit(player, BRUSHES[5]); break;\n case 7: createUnit(player, BRUSHES[6], 1, SPOT); removeUnit(player, BRUSHES[6]); break;\n case 8: createUnit(player, BRUSHES[7], 1, SPOT); removeUnit(player, BRUSHES[7]); break;\n case 9: createUnit(player, BRUSHES[8], 1, SPOT); removeUnit(player, BRUSHES[8]); break;\n case 10: createUnit(player, BRUSHES[9], 1, SPOT); removeUnit(player, BRUSHES[9]); break;\n default: createUnit(player, BRUSHES[10], 1, SPOT); removeUnit(player, BRUSHES[10]);\n }\n});\n\n/**\n * Light the whole map once, so that from now on a tile left dark shows as fog (grey) rather than as never seen\n * (black) — every picture then has the same two tones. Takes one frame.\n * @param player Whose fog: P1 … P8, known when the script is built.\n */\nexport const reveal = game((player: Player) => {\n const width = memory.map.width;\n const height = memory.map.height;\n // Size 11 is 23 tiles wide: a brush every 14 tiles leaves no gap, and one more past the end, kept inside, reaches the edge.\n for (let y = 2; y < height + 12; y += 14) {\n for (let x = 2; x < width + 12; x += 14) disc(player, Math.min(x, width - 3), Math.min(y, height - 3), 11);\n }\n});\n\n/**\n * Light a rectangle of tiles for this frame, worked out while the game runs: its top left on tile (x, y), `width`\n * tiles across and `height` down. Every one of the five may change from frame to frame — the walls of a raycaster, a\n * bar of a chart. It is exact from 3 × 4 up (the smallest brush); a thinner one is lit a brush wide, centred.\n *\n * fog.rect(P1, 10, 20, 3, wall); // a column 3 tiles wide, `wall` tall\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of its left edge.\n * @param y The row of its top edge.\n * @param width How many tiles across.\n * @param height How many tiles down.\n */\nexport const rect = game((player: Player, x: number, y: number, width: number, height: number) => {\n if (width < 1 || height < 1) return;\n // Size 1 is 3 tiles across and 4 down, its centre the middle column and the third row: a grid of them, the last\n // column and row moved back to end on the edge (overlapping the one before), covers the rectangle exactly.\n const right = Math.max(x + width - 2, x + 1);\n const bottom = Math.max(y + height - 2, y + 2);\n // (The brush made here, not through disc(): its unit type is then known when the script is built, which makes the\n // action a constant — a size from the program costs a branch and a written field a brush.)\n let cy = y + 2;\n while (true) {\n let cx = x + 1;\n while (true) {\n centerLocation(SPOT, cx * 32 + 16, cy * 32 + 16, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (cx >= right) break;\n cx = Math.min(cx + 3, right);\n }\n if (cy >= bottom) break;\n cy = Math.min(cy + 4, bottom);\n }\n});\n\n/** A picture for the fog, made when the script is built: its size in tiles and the brushes that draw it. */\nexport interface Picture {\n readonly width: number;\n readonly height: number;\n readonly brushes: readonly { readonly x: number; readonly y: number; readonly size: number }[];\n}\n\n/**\n * A picture from rows of text, worked out when the script is built: `#` is the ink, anything else is not.\n *\n * fog.picture([\"..##..\", \".####.\", \"######\"]) // light ink: the # tiles are lit\n * fog.picture([\"..##..\", \".####.\", \"######\"], { ink: \"dark\" }) // dark ink: the # tiles stay dark, the rest is lit\n *\n * With light ink a lit part thinner than a brush (3 tiles across, 4 down) is drawn a tile or two thicker. An image's\n * halftone (`fog.picture(photo.halftone(6))`) is drawn with the brushes it was made of, one a cell. With dark\n * ink every tile of the picture's rectangle that is not `#` is lit and the `#` tiles keep their shape exactly,\n * however thin — the ink for line art and silhouettes.\n */\nexport function picture(rows: readonly string[], options: { readonly ink?: \"light\" | \"dark\" } = {}): Picture {\n const height = rows.length;\n const width = Math.max(0, ...rows.map((r) => r.length));\n // An image's halftone (image.halftone(6)) comes with the brushes that drew it: a brush a cell, as they are.\n const drawn = (rows as { readonly brushes?: readonly { readonly x: number; readonly y: number; readonly shape: number }[] }).brushes;\n if (drawn && options.ink !== \"dark\") return Object.freeze({ width, height, brushes: Object.freeze(drawn.map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }))) });\n // Dark ink: the picture's rectangle lit but for the # tiles, so what is covered is the rest.\n const ink = options.ink === \"dark\" ? Array.from({ length: height }, (_, y) => Array.from({ length: width }, (_, x) => (rows[y][x] === \"#\" ? \".\" : \"#\")).join(\"\")) : rows;\n const brushes = cover(ink, SHAPES).map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }));\n return Object.freeze({ width, height, brushes: Object.freeze(brushes) });\n}\n\n/**\n * A video's frames as brushes, worked out when the script is built: a word a brush (x | y << 8 | size << 16), the\n * frames one after another, and where each one starts — the tables the game reads a frame from. Once a build.\n */\ninterface Film { readonly words: readonly number[]; readonly starts: readonly number[] }\nconst films = new Map();\nfunction film(video: Video): Film {\n const had = films.get(video);\n if (had) return had;\n const words: number[] = [], starts: number[] = [0];\n for (const brushes of cover(video, SHAPES)) {\n for (const b of brushes) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n starts.push(words.length);\n }\n const made = { words, starts };\n films.set(video, made);\n return made;\n}\n\n/**\n * Light the fog for this frame: a disc, a picture or a frame of a video. Tiles count from the map's top left, (0, 0).\n *\n * fog.light(P1, 30, 20, 5); // a disc of size 5 centred on tile (30, 20)\n * fog.light(P1, 60, 40, heart); // a picture (fog.picture), its top left on tile (60, 40)\n * fog.light(P1, 0, 0, badApple, f); // frame f of a video the script imports, its top left on tile (0, 0)\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The tile's column: a disc's centre, a picture's left edge.\n * @param y The tile's row: a disc's centre, a picture's top edge.\n * @param shape A size, 1 (3 tiles wide) to 11 (23 wide) — it may change while the game runs — a picture, or a video.\n * @param frame Of a video, which frame, from 0: it may change while the game runs. Past the end, nothing is lit.\n */\nexport const light = game((player: Player, x: number, y: number, shape: number | Picture | Video, frame: number = 0) => {\n if (typeof shape === \"number\") disc(player, x, y, shape);\n else {\n // The picture's corner in pixels once; each brush is its offset from there (a constant of a picture).\n const px = x * 32 + 16, py = y * 32 + 16;\n if (\"brushes\" in shape) for (const b of shape.brushes) discPx(player, px + b.x * 32, py + b.y * 32, b.size);\n else {\n const { words, starts } = film(shape);\n const end = starts[frame + 1];\n for (let i = starts[frame]; i < end; i++) {\n const w = words[i];\n // (A row's offset in pixels straight from its byte: the same as ((w >> 8) & 255) * 32, and the shift only has\n // the byte's eight bits to look at.)\n discPx(player, px + (w & 255) * 32, py + ((w & 0xff00) >> 3), w >> 16);\n }\n }\n }\n});\n\n/**\n * Play a video in the fog, a frame of it every frame of the game, from its first to its last; resolves when it ends.\n * Inside an async program: `await fog.play(P1, badApple)`. On Fastest a game frame is 42 ms, which is what Import\n * Video makes a video's frames by default; the game runs a little slower when a frame is heavy, and so does the video.\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param video A video the script imports.\n * @param x The column of its left edge, 0 by default.\n * @param y The row of its top edge, 0 by default.\n */\nexport const play = game(async (player: Player, video: Video, x: number = 0, y: number = 0) => {\n // (A while: a for over a length known when the script is built would be unrolled, a copy of the body a frame.)\n let f = 0;\n while (f < video.length) {\n light(player, x, y, video, f);\n await nextFrame();\n f++;\n }\n});\n\n/**\n * How fog.columns() lays its columns out, known when the script is built: `count` columns side by side, each `width`\n * tiles across (3, a brush's width, by default) and up to `height` tiles tall, centred on the middle row. `ink`:\n * \"light\" lights each column (the walls of a raycaster bright, on fog), \"dark\" lights all but the columns (dark walls\n * between a lit ceiling and floor); dark is cheaper when columns fill most of the board, light when they are short.\n */\nexport interface ColumnLayout {\n readonly count: number;\n readonly height: number;\n readonly width?: number;\n readonly ink?: \"light\" | \"dark\";\n /**\n * How the walls are told apart, with fog.columns()'s `faces`. \"outline\", the default: every wall drawn as its edges —\n * its top and bottom, a brush deep, and a column lit whole wherever one face meets another (on the nearer of the\n * two) — so that blocks read as boxes, the look of the raycasters of monochrome screens; with dark ink, the edges are\n * lit lines through dark walls. A few brushes a column. Chosen over the rest when played (2026-10-17).\n *\n * The others shade the faces whose number is odd (a raycaster's other side) and leave the rest whole: \"hollow\" —\n * dark, lit only along its top and bottom edges; \"ribbed\" — hollow and lit across the middle of each half; \"panelled\"\n * — hollow and lit across its quarters; \"line\" / \"lines\" — dark lines a tile thick across it at its middle or its\n * quarters (the finest, and two dozen brushes a column near the eye: for a view with room to spare).\n */\n readonly shading?: \"outline\" | \"lines\" | \"line\" | \"hollow\" | \"ribbed\" | \"panelled\";\n}\n\n/**\n * What fog.columns() reads, worked out once a layout when the script is built: for each level of the drawing that is\n * wider than a column (all the columns, a group of them, the last group) and each depth from 0 to half the height, the\n * brushes that cover a rectangle that wide and that deep exactly — the encoder's covers (cover()), a few large brushes\n * in the middle and small ones at the edges. A brush is a word, dx | dy << 8 | size << 16 from the rectangle's top\n * left; `starts` says where each (level, depth) begins.\n */\ninterface ColumnPlan { readonly words: readonly number[]; readonly starts: readonly number[]; readonly group: number; readonly half: number }\nconst columnPlans = new Map();\nconst COLUMN_GROUP = 6;\nfunction columnPlan(layout: ColumnLayout): ColumnPlan {\n const width = layout.width ?? 3, half = layout.height >> 1, group = Math.min(COLUMN_GROUP, layout.count);\n const key = `${layout.count}:${width}:${half}`;\n const had = columnPlans.get(key);\n if (had) return had;\n const words: number[] = [], starts: number[] = [];\n for (const columns of [layout.count, group, layout.count % group || group]) {\n for (let depth = 0; depth <= half; depth++) {\n starts.push(words.length);\n if (depth === 0) continue;\n // A rectangle shallower than a brush is drawn a brush deep, the rest of it on what the level before lit.\n const rows = Array.from({ length: Math.max(depth, 4) }, () => \"#\".repeat(columns * width));\n for (const b of cover(rows, SHAPES)) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n }\n }\n starts.push(words.length);\n const made = { words, starts, group, half };\n columnPlans.set(key, made);\n return made;\n}\n\n/**\n * One rectangle of fog.columns() wider than a column: the cover at `at` (a level and a depth) drawn twice, the half\n * above the middle and the half below, its top rows `top` and `bottom`, from column `x`.\n */\nconst columnRect = game((player: Player, words: readonly number[], starts: readonly number[], at: number, x: number, top: number, bottom: number) => {\n let i = starts[at];\n const end = starts[at + 1];\n // In pixels once; each brush is its offset (a few bits, a few tests) from there.\n const px = x * 32 + 16, pt = top * 32 + 16, pb = bottom * 32 + 16;\n while (i < end) {\n const w = words[i];\n const dx = (w & 255) * 32, dy = (w & 0xff00) >> 3, size = w >> 16;\n discPx(player, px + dx, pt + dy, size);\n discPx(player, px + dx, pb + dy, size);\n i++;\n }\n});\n\n/**\n * One column's part of fog.columns(), in pixels: brushes (3 × 4) a column of 4 rows apart and the last moved back to\n * end on the edge, twice — from `pt` and from `pb`, the centres of the first brush of each — down a column `k32`\n * pixels deep (32 a row; under 4 rows, a brush deep), centred on `px`. What the smallest brush covers exactly, worked out\n * here rather than read: it is the most common rectangle by far. In pixels because the caller has them, stepped: a\n * product by 32 of a number the game holds is a test a bit, about 0.4 µs, where a step is an add.\n */\nconst columnBarPx = game((player: Player, px: number, pt: number, pb: number, k32: number) => {\n // How far down the last brush is from the first.\n const end = Math.max(k32, 128) - 128;\n let r = 0;\n while (true) {\n centerLocation(SPOT, px, pt, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n centerLocation(SPOT, px, pb, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (r >= end) break;\n const step = Math.min(end - r, 128);\n r += step;\n pt += step;\n pb += step;\n }\n});\n\n/** columnBarPx() in tiles: `k` rows from row `top` down and from row `bottom` down, centred on column `x`. */\nconst columnBar = game((player: Player, x: number, top: number, bottom: number, k: number) => {\n columnBarPx(player, x * 32 + 16, top * 32 + 80, bottom * 32 + 80, k * 32);\n});\n\n/**\n * A shaded column of fog.columns() (ColumnLayout's `shading`): `a` is half its height, `lines` how many lines across\n * each half — 0 hollow, 1 at its middle, 3 at its quarters. A line is a dark row through a lit column (light ink), or\n * a lit band a brush deep through a dark one; a column too short for its lines is drawn plain.\n */\nconst columnShaded = game((player: Player, cx: number, mid: number, a: number, dark: boolean, lines: number) => {\n if (lines <= 0) {\n if (dark) { if (a >= 6) columnBar(player, cx, mid - 4, mid, 4); }\n else if (a < 8) columnBar(player, cx, mid - a, mid, a);\n else {\n // Hollow: the edges. Ribbed (-1) and panelled (-3): bands across each half too, centred on its middle or\n // quarters, where there is room for them between the edges.\n columnBar(player, cx, mid - a, mid + a - 4, 4);\n const ribs = -lines;\n if (ribs > 0 && a >= 6 * (ribs + 1)) {\n let k = 1;\n while (k <= ribs) {\n const at = (a * k) / (ribs + 1);\n columnBar(player, cx, mid - at - 2, mid + at - 2, 4);\n k++;\n }\n }\n }\n } else if (a < 5 * (lines + 1)) {\n if (!dark) columnBar(player, cx, mid - a, mid, a);\n } else {\n // From the middle out: lit up to each line, the line's row dark (light ink); or a lit band on each line (dark ink).\n let from = 0, k = 1;\n while (k <= lines + 1) {\n const to = k > lines ? a : (a * k) / (lines + 1);\n if (dark) { if (k <= lines) columnBar(player, cx, mid - to - 2, mid + to - 2, 4); }\n else columnBar(player, cx, mid - to, mid + from, to - from);\n from = to + 1;\n k++;\n }\n }\n});\n\n/**\n * Light columns for this frame — the walls of a raycaster, a bar chart — each as tall as the program says, centred on\n * the layout's middle row. The covers are worked out when the script is built (see ColumnLayout), so a frame costs a\n * brush for each part of the picture that differs from its neighbours, not one for every few tiles: a wall that fills\n * the board is a few large brushes.\n *\n * const VIEW = { count: 42, height: 96, ink: \"dark\" } as const;\n * fog.columns(P1, 1, 0, VIEW, heights); // heights: one a column, in tiles, the program's\n * fog.columns(P1, 1, 0, VIEW, heights, faces); // faces: which face of which wall each column shows\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of the layout's left edge.\n * @param y The row of its top edge.\n * @param layout How the columns are laid out: known when the script is built.\n * @param heights Each column's height in tiles (0 to the layout's height), an array of the program's.\n * @param faces Which face of which wall each column shows, a number the same for every column of one face — in a\n * raycaster, \\`(mapY * width + mapX) * 2 + side\\` — an array of the program's as long as `heights`: what the\n * layout's `shading` tells walls apart by. Optional: without it, every column is lit whole (a bar chart).\n */\nexport const columns = game((player: Player, x: number, y: number, layout: ColumnLayout, heights: readonly number[], faces?: readonly number[]) => {\n const { words, starts, half, group } = columnPlan(layout);\n const count = layout.count, width = layout.width ?? 3, dark = layout.ink === \"dark\";\n // (Dark lines through a lit column count up; lit bands through a dark one, ribbed and panelled, down.)\n // (Without faces there is nothing to tell apart, and every column is whole.)\n const outline = faces !== undefined && (layout.shading === undefined || layout.shading === \"outline\");\n const lines = layout.shading === \"lines\" ? 3 : layout.shading === \"line\" ? 1 : layout.shading === \"ribbed\" ? -1 : layout.shading === \"hollow\" ? 0 : -3;\n const span = half + 1;\n // Each column's depth from where its lit part starts: the middle row for light ink, the top and bottom for dark.\n // A shaded column of light ink is drawn on its own, after the rest: to the rest it is as if it were not there — and\n // so is every column of a light outline, which is all edges.\n const depth: number[] = new Array(count).fill(0);\n // Half of each column's height, at most half the layout's: worked out once. (Clamped before the shift, the same\n // number: the shift then has the few bits the clamp leaves, where a height from the program could have any.)\n const halves: number[] = new Array(count).fill(0);\n // And in pixels (32 a row), for the bars, which place their brushes in pixels: a small number times 32 is a few tests.\n const halves32: number[] = new Array(count).fill(0);\n let least = half, most = 0;\n // (A light outline is all edges: every depth is 0, nothing to work out.)\n const flat = !dark && outline;\n if (flat) least = 0;\n let i = 0;\n while (i < count) {\n const a = Math.min(Math.max(heights[i], 0), 2 * half + 1) >> 1;\n halves[i] = a;\n halves32[i] = a * 32;\n if (!flat) {\n let d = dark ? half - a : a;\n if (faces !== undefined && !dark && !outline && (faces[i] & 1) != 0) d = 0;\n depth[i] = d;\n if (d < least) least = d;\n if (d > most) most = d;\n }\n i++;\n }\n // A rectangle from depth p, k deep, starts on the rows above and below the middle (light) or below the top and above\n // the bottom (dark); one shallower than 4 is drawn 4 deep, reaching back over what is lit already.\n const mid = y + half;\n // Every column, from depth 0 to the least.\n if (least > 0) {\n const k = Math.max(least, 4);\n if (dark) columnRect(player, words, starts, least, x, y + least - k, y + 2 * half - least);\n else columnRect(player, words, starts, least, x, mid - least, mid + least - k);\n }\n // Each group of columns, from the least to the group's least; then each column, from there to its own. (Nothing,\n // when every column's depth is the least: a light outline's always.)\n let g = most > least ? 0 : count;\n while (g < count) {\n const last = Math.min(g + group, count);\n let gl = half;\n let j = g;\n while (j < last) { if (depth[j] < gl) gl = depth[j]; j++; }\n const level = last - g === group ? 1 : 2;\n if (gl > least) {\n const k = gl - least, kk = Math.max(k, 4);\n if (dark) columnRect(player, words, starts, level * span + k, x + g * width, y + gl - kk, y + 2 * half - gl);\n else columnRect(player, words, starts, level * span + k, x + g * width, mid - gl, mid + gl - kk);\n }\n j = g;\n while (j < last) {\n const k = depth[j] - gl;\n if (k > 0) {\n const kk = Math.max(k, 4), cx = x + j * width + 1;\n if (dark) columnBar(player, cx, y + depth[j] - kk, y + 2 * half - depth[j], k);\n else columnBar(player, cx, mid - depth[j], mid + depth[j] - kk, k);\n }\n j++;\n }\n g = last;\n }\n if (outline) {\n // Where one face meets another, the nearer (taller) of the two columns is an edge.\n const edge: number[] = new Array(count).fill(0);\n let face = faces[0], tall = heights[0];\n i = 1;\n while (i < count) {\n const f = faces[i], h = heights[i];\n if (f != face) { if (h >= tall) edge[i] = 1; else edge[i - 1] = 1; }\n face = f;\n tall = h;\n i++;\n }\n // The bars in pixels: a column's centre stepped across, the middle row's worked out once.\n const mid80 = mid * 32 + 80;\n let px = (x + 1) * 32 + 16;\n i = 0;\n while (i < count) {\n const a = halves[i], a32 = halves32[i];\n if (dark) { if (edge[i] != 0 && a >= 2) columnBarPx(player, px, mid80 - a32, mid80, a32); }\n else if (a > 0) {\n if (edge[i] != 0 || a < 8) columnBarPx(player, px, mid80 - a32, mid80, a32);\n else columnBarPx(player, px, mid80 - a32, mid80 + a32 - 128, 128);\n }\n px += width * 32;\n i++;\n }\n } else if (faces !== undefined) {\n i = 0;\n while (i < count) {\n if ((faces[i] & 1) != 0) columnShaded(player, x + i * width + 1, mid, halves[i], dark, lines);\n i++;\n }\n }\n});\n\n/**\n * Keep what was lit this frame on the board for `n` frames, and wait them out: \\`await fog.show(2)\\` in place of\n * \\`await nextFrame()\\` draws every other frame at half the cost. StarCraft: Remastered redraws the fog on the minimap\n * every other frame (measured in two played recordings, 2026-10-17), so a picture drawn every other frame looks the\n * same there as one drawn every frame. The board is wiped at the start of the frame after them, ready for the next.\n *\n * @param n How many frames, 1 to 24, known when the script is built.\n */\nexport const show = game(async (n: number) => {\n memory.vision.countdown = n;\n await sleep(frames(n));\n});\n\n/** Everything above as one name: import { fog } from \"trigscript/fog\"; fog.light(P1, x, y, 3). */\nexport const fog = { light, rect, columns, show, play, reveal, picture, SHAPES };\n\n/** The longest fog.show() keeps a picture: the countdown the game sets itself after a wipe is longer than this. */\nconst SHOW_MOST = 24;\n\n// The canvas: every brush's sight set, every frame, and the board wiped on the next — for as long as the game runs —\n// unless a program asked for the picture to stay (fog.show), when the countdown is that program's to run down.\nprogram(() => {\n while (true) {\n for (let s = 1; s <= 11; s++) stats(BRUSHES[s - 1]).sight = s;\n const left = memory.vision.countdown;\n if (left == 0 || left > SHOW_MOST) memory.vision.countdown = 1;\n sleep(frames(1));\n }\n});\n", "math": "/**\n * Numbers for motion and play: the standard library's \"trigscript/math\" (TrigScript 4).\n *\n * import { Vec, lerp, easeOutQuad, distance, angleTo, approach, wrap } from \"trigscript/math\";\n *\n * const t = fixed(frame) / 48; // 0 to 1 over two seconds\n * const x = lerp(fromX, toX, easeOutQuad(t)); // eased from one place to another\n * const v = Vec.fromAngle(angleTo(x, y, tx, ty), fixed(4));\n * pos = pos.add(v);\n *\n * Fractions are the language's fixed numbers (16.16: four decimal places or so, from about −32 768 to 32 767): a\n * number becomes one when a fraction is stored into it, or written `fixed(…)`. Angles are radians, as JavaScript's are.\n * Whole numbers stay whole where they can — `distanceSq`, `manhattan`, `wrap`, `sign` — and cost less.\n */\n\n/** π, and a whole turn. */\nexport const PI = Math.PI;\nexport const TAU = Math.PI * 2;\n\n/** From a to b by t: a at 0, b at 1, between them in between (t outside 0 … 1 goes past). */\nexport function lerp(a: fixed, b: fixed, t: fixed): fixed {\n return a + (b - a) * t;\n}\n\n/** Where v is from a to b, as lerp's t: 0 at a, 1 at b. */\nexport function inverseLerp(a: fixed, b: fixed, v: fixed): fixed {\n return b === a ? fixed(0) : (v - a) / (b - a);\n}\n\n/** v from the range a1 … b1 into a2 … b2. */\nexport function remap(v: fixed, a1: fixed, b1: fixed, a2: fixed, b2: fixed): fixed {\n return lerp(a2, b2, inverseLerp(a1, b1, v));\n}\n\n/** t kept inside 0 … 1. */\nexport function clamp01(t: fixed): fixed {\n return t < 0 ? fixed(0) : t > 1 ? fixed(1) : t;\n}\n\n/** From `current` towards `target` by at most `step`, never past it: a value that follows another at a speed. */\nexport function approach(current: number, target: number, step: number): number {\n if (current < target) return current + step > target ? target : current + step;\n return current - step < target ? target : current - step;\n}\n\n/** n into 0 … size − 1, going round: wrap(-1, 10) is 9, wrap(12, 10) is 2. */\nexport function wrap(n: number, size: number): number {\n return ((n % size) + size) % size;\n}\n\n/** −1, 0 or 1, by whether n is below, at or above zero. */\nexport function sign(n: number): number {\n return n > 0 ? 1 : n < 0 ? -1 : 0;\n}\n\n/** The distance from one point to another, as the crow flies. */\nexport function distance(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.hypot(x2 - x1, y2 - y1);\n}\n\n/** The distance squared: whole, and cheaper — compare it with a range squared. */\nexport function distanceSq(x1: number, y1: number, x2: number, y2: number): number {\n return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n}\n\n/** The distance along the axes, |dx| + |dy|: what the game's own \"nearest\" goes by. */\nexport function manhattan(x1: number, y1: number, x2: number, y2: number): number {\n return Math.abs(x2 - x1) + Math.abs(y2 - y1);\n}\n\n/** The angle from one point to another, in radians from −π to π: 0 is to the right (east), π / 2 down (south, y grows down). */\nexport function angleTo(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.atan2(y2 - y1, x2 - x1);\n}\n\n/** Degrees as radians. */\nexport function radians(degrees: fixed): fixed {\n return (degrees * PI) / 180;\n}\n\n/** Radians as degrees. */\nexport function degrees(radians: fixed): fixed {\n return (radians * 180) / PI;\n}\n\n/* Easing: t from 0 to 1, how far along a motion is at that point of its time — slow then fast, fast then slow, … */\n\n/** Slow at the start. */\nexport function easeInQuad(t: fixed): fixed {\n return t * t;\n}\n\n/** Slow at the end. */\nexport function easeOutQuad(t: fixed): fixed {\n return t * (2 - t);\n}\n\n/** Slow at both ends. */\nexport function easeInOutQuad(t: fixed): fixed {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n}\n\n/** Slower at the start than easeInQuad. */\nexport function easeInCubic(t: fixed): fixed {\n return t * t * t;\n}\n\n/** Slower at the end than easeOutQuad. */\nexport function easeOutCubic(t: fixed): fixed {\n const u = t - 1;\n return u * u * u + 1;\n}\n\n/** Goes a little past the end and comes back. */\nexport function easeOutBack(t: fixed): fixed {\n const u = t - 1;\n return 1 + 2.70158 * u * u * u + 1.70158 * u * u;\n}\n\n/** Slow at both ends, smoothly (Hermite: 3t² − 2t³). */\nexport function smoothstep(t: fixed): fixed {\n return t * t * (3 - 2 * t);\n}\n\n/**\n * A point, or a direction and a length: two fixed numbers. Each operation gives a new Vec.\n *\n * let pos = new Vec(fixed(x), fixed(y));\n * const toward = new Vec(fixed(tx), fixed(ty)).sub(pos).normalized().scale(fixed(3));\n * pos = pos.add(toward);\n */\nexport class Vec {\n x: fixed;\n y: fixed;\n\n constructor(x: fixed, y: fixed) {\n this.x = x;\n this.y = y;\n }\n\n /** A direction `length` long at `angle` radians (0 to the right, π / 2 down). */\n static fromAngle(angle: fixed, length: fixed): Vec {\n return new Vec(Math.cos(angle) * length, Math.sin(angle) * length);\n }\n\n add(o: Vec): Vec {\n return new Vec(this.x + o.x, this.y + o.y);\n }\n\n sub(o: Vec): Vec {\n return new Vec(this.x - o.x, this.y - o.y);\n }\n\n scale(k: fixed): Vec {\n return new Vec(this.x * k, this.y * k);\n }\n\n dot(o: Vec): fixed {\n return this.x * o.x + this.y * o.y;\n }\n\n /** How long it is. */\n length(): fixed {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n }\n\n /** The same direction, 1 long (or none, for none). */\n normalized(): Vec {\n const l = this.length();\n const k: fixed = l === 0 ? fixed(0) : 1 / l;\n return new Vec(this.x * k, this.y * k);\n }\n\n /** Its angle, in radians from −π to π. */\n angle(): fixed {\n return Math.atan2(this.y, this.x);\n }\n\n /** Turned by `angle` radians (clockwise on the map, where y grows down). */\n rotate(angle: fixed): Vec {\n const c = Math.cos(angle);\n const s = Math.sin(angle);\n return new Vec(this.x * c - this.y * s, this.x * s + this.y * c);\n }\n\n /** How far it is from another point. */\n distanceTo(o: Vec): fixed {\n return this.sub(o).length();\n }\n\n /** From this towards another by t (0 here, 1 there). */\n lerp(o: Vec, t: fixed): Vec {\n return new Vec(this.x + (o.x - this.x) * t, this.y + (o.y - this.y) * t);\n }\n}\n", - "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false;\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one.\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) { if (order[j].at < off) { off = order[j].at; stolen = true; } break; }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, stolen ? 0.12 : releaseOf(z), rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n if (releases) for (const [down, up] of pedal) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n};\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n for (const { part } of inside.parts) {\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) throw new Error(\"render(): the performance plays no notes.\");\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", + "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false, release = releaseOf(z);\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one — held by the\n // pedal or still dying away after it was let go (a string struck again starts again).\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) {\n const next = order[j].at;\n if (next < off) { off = next; stolen = true; release = 0.12; }\n else if (next < off + release) release = Math.max(0.1, next - off + 0.1);\n break;\n }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n if (releases) for (const [down, up] of pedal) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n};\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n for (const { part } of inside.parts) {\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) throw new Error(\"render(): the performance plays no notes.\");\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", "random": "/**\n * Chance: the standard library's \"trigscript/random\" (TrigScript 4).\n *\n * import { chance, range, pick, shuffle, weighted, Random } from \"trigscript/random\";\n *\n * if (chance(25)) dropLoot(); // one time in four\n * const lane = range(1, 3); // 1, 2 or 3\n * const boss = pick(BOSSES); // any one of a list\n * shuffle(order); // an array of the program, in place\n * const tier = weighted([70, 25, 5]); // 0 most of the time, 2 rarely\n *\n * const rng = new Random(seed); // the same numbers every time for the same seed\n * const x = rng.range(0, 63);\n *\n * The functions use the game's own random numbers, which every player's game draws alike, so nothing goes out of step\n * in a game of several players. `Random` is a generator of your own (xorshift), seeded: the same seed gives the same\n * numbers, game after game — a level made from a seed, a save code that holds one.\n */\nimport { random } from \"trigscript\";\n\n/** True `percent` times in a hundred (25: one time in four). */\nexport function chance(percent: number): boolean {\n return random(100) < percent;\n}\n\n/** A whole number from `min` to `max`, both included. */\nexport function range(min: number, max: number): number {\n return min + random(max - min + 1);\n}\n\n/** The total of `count` dice of `sides` sides each (3, 6: from 3 to 18). */\nexport function dice(count: number, sides: number): number {\n let total = 0;\n let i = 0;\n while (i < count) { total += 1 + random(sides); i++; }\n return total;\n}\n\n/** One of a list, any one alike; a list the script has, or an array of the program (the first's 0 when it is empty). */\nexport function pick(items: readonly T[]): T {\n return items[random(items.length)];\n}\n\n/** The place of one of the weights, each as likely as its share of their total: [70, 25, 5] gives 0 most of the time. */\nexport function weighted(weights: readonly number[]): number {\n let total = 0;\n for (const w of weights) total += w;\n let roll = random(total);\n let i = 0;\n while (i < weights.length) {\n if (roll < weights[i]) return i;\n roll -= weights[i];\n i++;\n }\n return weights.length - 1;\n}\n\n/** An array of the program in a random order, in place (Fisher–Yates: every order alike). */\nexport function shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = random(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n}\n\n/**\n * A generator of random numbers of your own, seeded: the same seed gives the same numbers, in the game and when the\n * script is tested. Make it in the program (`const rng = new Random(1234)`).\n */\nexport class Random {\n state: number;\n\n /** Seeded with any whole number (0 is taken as 1). */\n constructor(seed: number) {\n this.state = seed === 0 ? 1 : seed;\n }\n\n /** The next number, from 0 to 2 147 483 647. */\n next(): number {\n let x = this.state;\n x ^= x << 13;\n x ^= x >>> 17;\n x ^= x << 5;\n this.state = x;\n return x & 0x7fffffff;\n }\n\n /** A whole number from 0 to n − 1. */\n int(n: number): number {\n return this.next() % n;\n }\n\n /** A whole number from `min` to `max`, both included. */\n range(min: number, max: number): number {\n return min + this.int(max - min + 1);\n }\n\n /** True `percent` times in a hundred. */\n chance(percent: number): boolean {\n return this.int(100) < percent;\n }\n\n /** One of a list, any one alike. */\n pick(items: readonly T[]): T {\n return items[this.int(items.length)];\n }\n\n /** An array of the program in a random order, in place. */\n shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = this.int(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n }\n}\n", "screen": "/**\n * Pixel screens: the standard library's \"trigscript/screen\" (TrigScript 4).\n *\n * import { Screen, ScreenView, sprite } from \"trigscript/screen\";\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n *\n * program(async () => {\n * const screen = new Screen(4, 4, 24, 16); // 24 × 16 pixels, its corner on tile (4, 4)\n * let x = 10;\n * while (true) {\n * screen.clear();\n * screen.rect(0, 15, 24, 1, 5); // the ground, in colour 5\n * screen.blit(SHIP, x, 12);\n * screen.number(score, 1, 1, 2); // digits 3 × 5 pixels, in colour 2\n * screen.present(); // on the map, and so on the minimap (screen.reveal(P1) once first)\n * await nextFrame();\n * }\n * });\n *\n * A screen is a grid of pixels, each 0 (empty) or a colour from 1 to 7; drawing changes the grid, and `present()`\n * shows it: a pixel is a unit on the map, owned by the player whose colour it is, so the minimap shows the picture —\n * neighbouring pixels of one colour join into a solid block there. Only the pixels that changed since the last\n * `present()` are made or taken away, and only the pixels drawn since are looked at, so a still picture costs nothing to\n * show. Draw through the methods (`set`, `clear`, `rect`, …): a pixel written into `pixels` directly is not seen. The same grid can be shown in a\n * player's text lines too, as squares (`ScreenView` in a `ui.lines` view): one game, two screens, as the Tetris probe has it.\n *\n * A player sees the pixels only where they have vision: `screen.reveal(P1)` once gives them Map Revealers over it.\n *\n * Two looks (the constructor's last argument): \"dots\", Overlords, which fly — the minimap draws each as a dot with a gap\n * round it, the screen may be over Space; and \"solid\", Pylons, which the minimap draws as their whole two-tile\n * footprint, so pixels side by side are one block — on buildable ground (probes/lib/screen-map.mts --ground).\n *\n * What the map needs, found playing the unit-pixel probe in StarCraft: Remastered (2026-10-16): the owners of the\n * pixels (P3, P4, P5, P1, P6, P7, P8 below; their colours are theirs on the map, so give them the colours of TEXT_COLORS) must not\n * be computers — a computer moves its own units — and Remastered will not start a game without a computer, so one slot\n * (P2 here) is a computer that owns no pixel. A pixel is an Overlord, which sits on any ground and on nothing else; keep\n * the screen's tiles clear of buildings. A Pylon needs buildable ground, and none of the map's own units in the way. About 80 pixels made and taken away in a frame did not slow the game.\n */\nimport { centerLocation, createUnit, removeUnitAt, reserveLocation, textColors, units, P1, P3, P4, P5, P6, P7, P8, type Player } from \"trigscript\";\n\n/**\n * Whose units show colours 1 to 7 on the map, in the order of TEXT_COLORS: give each player that colour in the map\n * (cyan, yellow, purple, green, red, blue, orange). Green is P1's — your own units are green on the minimap anyway.\n * Not computers.\n */\nexport const OWNERS: readonly Player[] = [P3, P4, P5, P1, P6, P7, P8];\n/** The same colours in the text lines (`ScreenView`), 0 an empty square: cyan, yellow, purple, green, red, blue, orange. */\nexport const TEXT_COLORS: readonly number[] = [0, textColors.cyan, textColors.yellow, textColors.purple, textColors.green, textColors.red, textColors.blue, textColors.orange];\n\n/** Where each pixel's unit is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"screen: where each pixel is made\");\n\n/** A picture known when the script is built, to `blit` onto a screen: its size, and its pixels a row at a time (0 is see-through). */\nexport interface Sprite { readonly width: number; readonly height: number; readonly cells: readonly number[] }\n\n/**\n * A sprite from rows of text, when the script is built: \"1\" … \"7\" a pixel of that colour, anything else see-through.\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n */\nexport function sprite(rows: readonly string[]): Sprite {\n const width = Math.max(0, ...rows.map((r) => r.length));\n const cells: number[] = [];\n for (const row of rows) for (let x = 0; x < width; x++) { const c = Number(row[x]); cells.push(c >= 1 && c <= 7 ? c : 0); }\n return { width, height: rows.length, cells };\n}\n\n/** The digits 0 to 9, three pixels wide and five high, for `number()`: each fifteen pixels, a row at a time. */\nconst DIGITS: readonly number[] = [\n \"111101101101111\", \"010110010010111\", \"111001111100111\", \"111001111001111\", \"101101111001001\",\n \"111100111001111\", \"111100111101111\", \"111001001010010\", \"111101111101111\", \"111101111001111\",\n].flatMap((d) => d.split(\"\").map(Number));\n\n/** The most pixels a screen has: 32 × 32 at two tiles a pixel covers a 64 × 64 map, 64 × 32 half of a 128 × 128 one. */\nexport const MAX_PIXELS = 2048;\n\nexport class Screen {\n /** The picture being drawn: a colour a pixel, a row at a time (the first width × height of them). */\n pixels: number[] = new Array(MAX_PIXELS).fill(0);\n /** What the map shows now: the picture as it was at the last `present()`. */\n shown: number[] = new Array(MAX_PIXELS).fill(0);\n /** The pixels drawn a colour they were not since the last `present()`, in order: each one's place and its x and y. */\n drawnAt: number[] = new Array(MAX_PIXELS).fill(0);\n drawnX: number[] = new Array(MAX_PIXELS).fill(0);\n drawnY: number[] = new Array(MAX_PIXELS).fill(0);\n drawn = 0;\n /** More drawn than the list holds: `present()` looks at every pixel instead. */\n overflow = false;\n x: number;\n y: number;\n width: number;\n height: number;\n cell: number;\n /** The unit a pixel is: an Overlord (\"dots\"), or a Pylon (\"solid\"). */\n unit = 0;\n\n /**\n * A screen `width` × `height` pixels (MAX_PIXELS at most), its top left corner on tile (x, y) of the map, a pixel two\n * tiles across.\n * @param look \"dots\" (the default): a pixel is an Overlord, which the minimap draws as a dot, a gap round it — it flies,\n * so the screen may be over anything, Space too. \"solid\": a pixel is a Pylon, which the minimap draws as its whole\n * footprint, two tiles square, so pixels side by side are one block — it needs buildable ground under the screen,\n * and gives its owner Protoss supply. (Overlords a tile apart do not fit: the game will not place most of them.)\n */\n constructor(x: number, y: number, width: number, height: number, look: \"dots\" | \"solid\" = \"dots\") {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.cell = 64;\n this.unit = look === \"solid\" ? units.ProtossPylon : units.ZergOverlord;\n }\n\n /** Every pixel the colour (0, empty, unless it says). */\n clear(color: number = 0) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.put(i, x, y, color); i++; x++; }\n y++;\n }\n }\n\n /** One pixel; nothing happens outside the screen. */\n set(x: number, y: number, color: number) {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) this.put(y * this.width + x, x, y, color);\n }\n\n /** A pixel written, and listed for `present()` when its colour changed. */\n private put(i: number, x: number, y: number, color: number) {\n if (this.pixels[i] === color) return;\n this.pixels[i] = color;\n if (this.drawn < MAX_PIXELS) {\n this.drawnAt[this.drawn] = i;\n this.drawnX[this.drawn] = x;\n this.drawnY[this.drawn] = y;\n this.drawn++;\n } else this.overflow = true;\n }\n\n /** The colour of a pixel; 0 outside the screen. */\n get(x: number, y: number): number {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) return this.pixels[y * this.width + x];\n return 0;\n }\n\n /** A filled rectangle, its top left at (x, y); what is outside the screen is left out. */\n rect(x: number, y: number, width: number, height: number, color: number) {\n let j = 0;\n while (j < height) {\n let i = 0;\n while (i < width) { this.set(x + i, y + j, color); i++; }\n j++;\n }\n }\n\n /** A line from (x0, y0) to (x1, y1), both ends drawn. */\n line(x0: number, y0: number, x1: number, y1: number, color: number) {\n const dx = Math.abs(x1 - x0);\n const dy = -Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx + dy;\n let x = x0;\n let y = y0;\n while (true) {\n this.set(x, y, color);\n if (x === x1 && y === y1) break;\n const e2 = 2 * err;\n if (e2 >= dy) { err += dy; x += sx; }\n if (e2 <= dx) { err += dx; y += sy; }\n }\n }\n\n /** A sprite with its top left at (x, y): its see-through pixels leave what is under them. */\n blit(s: Sprite, x: number, y: number) {\n let k = 0;\n let j = 0;\n while (j < s.height) {\n let i = 0;\n while (i < s.width) {\n const c = s.cells[k];\n if (c !== 0) this.set(x + i, y + j, c);\n k++;\n i++;\n }\n j++;\n }\n }\n\n /** A whole number's digits, 3 × 5 pixels each with a pixel between, its top left at (x, y): a score on the minimap. */\n number(n: number, x: number, y: number, color: number) {\n let rest = n < 0 ? -n : n;\n let count = 1;\n let probe = rest;\n while (probe >= 10) { probe = Math.floor(probe / 10); count++; }\n let place = x + (count - 1) * 4;\n while (true) {\n const d = rest % 10;\n let k = 0;\n while (k < 15) {\n if (DIGITS[d * 15 + k] === 1) this.set(place + (k % 3), y + Math.floor(k / 3), color);\n k++;\n }\n rest = Math.floor(rest / 10);\n place -= 4;\n if (rest === 0) break;\n }\n }\n\n /**\n * Let a player see the screen: Map Revealers of theirs over it, for the rest of the game. Without them its pixels,\n * owned by other players, are hidden by the fog of war — on the map and on the minimap. Once, before the first\n * `present()`.\n * @param player Who sees it: P1 … P8, known when the script is built.\n */\n reveal(player: Player) {\n // A Map Revealer sees ten tiles round; one every six tiles leaves no gap.\n const right = this.x * 32 + this.width * this.cell;\n const bottom = this.y * 32 + this.height * this.cell;\n let py = this.y * 32 + 96;\n while (py < bottom + 96) {\n let px = this.x * 32 + 96;\n while (px < right + 96) {\n centerLocation(SPOT, px, py, 32, 32);\n createUnit(player, units.MapRevealer, 1, SPOT);\n px += 192;\n }\n py += 192;\n }\n }\n\n /**\n * The picture on the map: each pixel that changed since the last time taken away and made again in its colour. Only\n * the pixels drawn since are looked at (one drawn and drawn back is passed over), unless more were drawn than the list\n * holds.\n */\n present() {\n if (this.overflow) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.show(i, x, y); i++; x++; }\n y++;\n }\n this.overflow = false;\n } else {\n for (let k = 0; k < this.drawn; k++) this.show(this.drawnAt[k], this.drawnX[k], this.drawnY[k]);\n }\n this.drawn = 0;\n }\n\n /** One pixel on the map as it is in the picture, when it is not already. */\n private show(i: number, x: number, y: number) {\n const now = this.pixels[i];\n const was = this.shown[i];\n if (now === was) return;\n const half = this.cell >> 1;\n centerLocation(SPOT, this.x * 32 + x * this.cell + half, this.y * 32 + y * this.cell + half, 32, 32);\n OWNERS.forEach((owner, k) => { if (was === k + 1) removeUnitAt(owner, this.unit, 1, SPOT); });\n OWNERS.forEach((owner, k) => { if (now === k + 1) createUnit(owner, this.unit, 1, SPOT); });\n this.shown[i] = now;\n }\n}\n\n/**\n * A screen in the text lines, a square a pixel — filled in its colour, or empty — a line a row. For a `ui.lines` view:\n * ``, the screen's size known when the script is built. Eleven lines\n * show at once, sixty squares across.\n */\nexport function ScreenView({ screen, width, height }: { screen: Screen; width: number; height: number }) {\n return <>{UP_TO_60.map((y) => y < height && {UP_TO_60.map((x) => x < width && )})};\n}\n\n/** 0 … 59: the places a view's rows and columns are counted over, the ones past its size left out when the script is built. */\nconst UP_TO_60: readonly number[] = Array.from({ length: 60 }, (_, i) => i);\n", "signals": "/**\n * Events of your own: the standard library's \"trigscript/signals\" (TrigScript 4).\n *\n * import { Signal } from \"trigscript/signals\";\n *\n * const waveCleared = new Signal();\n *\n * program(async () => {\n * waveCleared.on((wave) => { setResources(P1, \"add\", 100 * wave, \"ore\"); }); // braces: a handler gives back no action\n * waveCleared.once((wave) => print(`First wave down!`));\n * const id = waveCleared.on((wave) => print(`Wave ${wave} cleared`));\n * …\n * waveCleared.emit(3); // every handler, in the order they were added\n * waveCleared.off(id);\n * });\n *\n * A signal lets one part of a map say that something happened without knowing who listens: the shop, the score and the\n * music each add a handler, and the wave code only emits. What it carries is one value of the type it is made with —\n * a number, a boolean, a text or a unit (`new Signal()`). Its handlers are functions kept as values: they may use\n * what the block they were written in has, and they run to their end, one after another, within the frame.\n *\n * Make a signal inside the program that uses it (`const s = new Signal()` at its top): a signal is variables\n * of a program, as anything a program writes is.\n */\n\nexport class Signal {\n /** The handlers, by the number `on` gave; one taken off is undefined, and its place is given to the next one added. */\n handlers: (((value: T) => void) | undefined)[] = [];\n /** Which handlers go once they have run once. */\n onceOnly: boolean[] = [];\n\n /**\n * Add a handler: it runs at every `emit`, handed the value.\n * @returns Its number, for `off`.\n */\n on(handler: (value: T) => void): number {\n return this.add(handler, false);\n }\n\n /** Add a handler that runs at the next `emit` only. @returns Its number, for `off` before then. */\n once(handler: (value: T) => void): number {\n return this.add(handler, true);\n }\n\n /** Take a handler off, by the number `on` or `once` gave. */\n off(id: number) {\n if (id >= 0 && id < this.handlers.length) this.handlers[id] = undefined;\n }\n\n /** Run every handler, in the order they were added, each handed `value`. */\n emit(value: T) {\n let i = 0;\n while (i < this.handlers.length) {\n const h = this.handlers[i];\n if (h) {\n if (this.onceOnly[i]) this.handlers[i] = undefined;\n h(value);\n }\n i++;\n }\n }\n\n /** How many handlers it has. */\n count(): number {\n let n = 0;\n for (const h of this.handlers) if (h) n++;\n return n;\n }\n\n /** Take every handler off. */\n clear() {\n let i = 0;\n while (i < this.handlers.length) { this.handlers[i] = undefined; i++; }\n }\n\n private add(handler: (value: T) => void, once: boolean): number {\n // A place one was taken off from, or a new one at the end.\n let i = 0;\n while (i < this.handlers.length) {\n if (!this.handlers[i]) {\n this.handlers[i] = handler;\n this.onceOnly[i] = once;\n return i;\n }\n i++;\n }\n this.handlers.push(handler);\n this.onceOnly.push(once);\n return this.handlers.length - 1;\n }\n}\n", diff --git a/stdlib/music.ts b/stdlib/music.ts index 0c834c7..1f9f50c 100644 --- a/stdlib/music.ts +++ b/stdlib/music.ts @@ -352,11 +352,17 @@ export function sampled(set: Samples, options: SampledOptions = {}): Instrument const count = counts.get(key) ?? 0; counts.set(key, count + 1); const z = pick(zonesFor(set.zones, "attack", key, v), count, random()); - let off = damped(n.end), stolen = false; - // The same key struck again while it sounds: the sound before stops, quickly, under the new one. - for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) { if (order[j].at < off) { off = order[j].at; stolen = true; } break; } + let off = damped(n.end), stolen = false, release = releaseOf(z); + // The same key struck again while it sounds: the sound before stops, quickly, under the new one — held by the + // pedal or still dying away after it was let go (a string struck again starts again). + for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) { + const next = order[j].at; + if (next < off) { off = next; stolen = true; release = 0.12; } + else if (next < off + release) release = Math.max(0.1, next - off + 0.1); + break; + } const held = Math.max(0.005, off - n.at); - parts.push({ clip: voice(z, key, v, held, stolen ? 0.12 : releaseOf(z), rate), at: n.at }); + parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at }); if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); } }); if (releases) for (const [down, up] of pedal) { diff --git a/tests/sampled.test.ts b/tests/sampled.test.ts index 7d2a25c..daeb772 100644 --- a/tests/sampled.test.ts +++ b/tests/sampled.test.ts @@ -193,9 +193,10 @@ describe("music.perform", () => { }); describe("loudness and sympathy", () => { - it("measures a full-scale 997 Hz sine on one channel at −3.01 LUFS, and brings a clip to a loudness", () => { + it("measures a full-scale 997 Hz sine at −3.01 LUFS on one side, 0 from both (as the game plays one channel), and brings a clip to a loudness", () => { const sine = tone(997, 3, { volume: 1, rate: 48000 }); - expect(sine.lufs).toBeCloseTo(-3.01, 1); + expect(sine.pan(-1).lufs).toBeCloseTo(-3.01, 1); + expect(sine.lufs).toBeCloseTo(0, 1); expect(sine.gain(0.1).loudness(-20).lufs).toBeCloseTo(-20, 1); expect(makeClip(new Float32Array(48000), 48000).lufs).toBe(-Infinity); }); From b1125ca5510644b8502c6b6ec8fdcbe4d25aa1c5 Mon Sep 17 00:00:00 2001 From: Jeany Date: Sun, 8 Nov 2026 14:34:27 -0600 Subject: [PATCH 09/31] =?UTF-8?q?S7:=20the=20F=C3=BCr=20Elise=20sound=20pr?= =?UTF-8?q?obe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five rendered items in a map, each announced: the old single-sample sampler on the grid, the Salamander grand on the grid, the A section played (tempo map, dynamics, Beethoven's pedal marks, sympathetic strings, a hall), the D minor storm with strings, horns, trombones, tuba and timpani, and the theme's last bars into the storm. The transcription (probes/lib/fur-elise-score.ts) is ours, from the Breitkopf & Härtel complete edition (1888, public domain); the orchestra's parts are our arrangement. The instruments are made from the sample libraries outside the repository by probes/lib/fur-elise-sound-gen.mts. Map 3.5 MB (five Oggs, 3.36 MB, quality 6), 3:46 a run; −17 LUFS for the piano items, −15 for the storm, true peaks under −1.4 dBTP decoded; the lifted game clean over 5,800 frames. The plan's S7 has what was built and what is open. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 50 ++++++++ probes/answers/fur-elise-sound.txt | 59 +++++++++ probes/fur-elise-sound.ts | 155 ++++++++++++++++++++++++ probes/lib/fur-elise-score.ts | 184 +++++++++++++++++++++++++++++ probes/lib/fur-elise-sound-gen.mts | 51 ++++++++ 5 files changed, 499 insertions(+) create mode 100644 probes/answers/fur-elise-sound.txt create mode 100644 probes/fur-elise-sound.ts create mode 100644 probes/lib/fur-elise-score.ts create mode 100644 probes/lib/fur-elise-sound-gen.mts diff --git a/docs/v4-plan.md b/docs/v4-plan.md index dafc3b8..19f0383 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6548,6 +6548,56 @@ anyone else's name. `fur-elise-visual` (visualizer: worktree ~/github/plugin-trigscript-fur-elise-visual). Each records its results below in its own subsection. +#### S7 sound probe (built 2026-11-08) + +Branch `fur-elise`, three commits on the library and one on the probe; not played yet. + +**The library gained:** +- *`.samples` files* (`compiler/samples.ts`): a sampled instrument among a script's files — recordings and zones as an + SFZ instrument has them (keys, strengths, attack / release / pedal triggers, volume, amp_veltrack, ampeg_release, + rt_decay, tune, keytrack, round robin, lorand/hirand), 16-bit coded without loss (fixed predictors and Rice codes, + about a sixth of 16-bit in base64 for a piano's decaying notes). Decoded when a build first needs a recording; a + check names everything by key without decoding. `scripts/make-samples.mts` makes one from an SFZ file or a folder + named by note (`--keys --layers --seconds --octave --detect --pitch`). `samples(zones)` makes one in a script from + its own clips (imported `.sound` files, say). In the full declarations only, not the compact one a language model + reads (it would go over its third). +- *`music.sampled(set, options)`*: the recording nearest each key (moved at most to it), the one made at the note's + strength; let go, 60 dB down over the zone's release and the release zones play (damper, string resonance, quieter + the longer it was held). Instruments may `strike` at a velocity (a pattern's "@" picks the recording) and play a + performance's notes `together`: the pedal holds what is let go and sounds itself, a re-struck key cuts the sound + before, `resonance` adds sympathetic strings. +- *`music.perform(options, parts)`*: a score's notation a part at a time — lengths with dots and triplets, ties, + rests, `@` velocities, staccato, accents, pp … ff and hairpins, `ped` / `*`, bar lines checked — at a tempo map + ([bar, bpm] points), holds and seeded unevenness. It returns the timeline the visualizer needs: each note's `at`, + `end`, `pitch`, `velocity`, `part`, `voice`, `bar`, `beat`, `frame`; `bars`; `pedal`. `music.render` mixes it (parts + on one instrument played together, heard as the first of them) and takes `loudness` (LUFS before the limiter). +- *`Clip.lufs`, `loudness(lufs)`* (BS.1770-4; a clip of one channel measured as heard from both sides, as the game + plays it) and *`Clip.resonance({ pedal })`* (a comb filter a string, A0 … E6). ENGINE stays "sound 3": no existing + clip is made differently. + +**The probe** (`probes/fur-elise-sound.ts`, sheet `probes/answers/fur-elise-sound.txt`, transcription +`probes/lib/fur-elise-score.ts` from the Breitkopf & Härtel complete edition on Wikimedia Commons; instruments by +`probes/lib/fur-elise-sound-gen.mts` from ~/github/samples, never committed): five rendered items, each announced — +1 the old single-sample sampler on the grid, 2 the Salamander grand on the grid (mf), 3 the A section played (tempo +map, dynamics, Beethoven's pedal marks, resonance 0.07, hall plate 0.84, 49 s), 4 the storm C1 … C17 with strings, +horns, trombones, tuba and timpani (32 s), 5 the theme's last bars into the storm (46 s). Map 3.5 MB, the five Oggs +3.36 MB (quality 6), the run 5,377 frames (3:46). Measured on the decoded files: −17.0 LUFS for 1–3, −15.1 for 4–5, +true peaks −1.4 … −6.5 dBTP; the limiter takes at most 2.5 dB off the theme's loudest notes (at −16 it took 5.7, so +−17), 4 dB off the storm's hits. The orchestra's parts balanced by measuring each alone. Lifted game (game-check, +5,800 frames): 0 ending, 0 never seen; the labels and items on the frames written. Instruments: piano 125 MB of +`.samples` (483 recordings, keys 28–91, 16 layers, 10 s), VSCO 2.1–15 MB each; a check 2.8 s, a build 18 s. + +**Found on the way:** the first loudness read mono clips 3 dB low against the game (which plays one channel from +both sides); a re-struck key's release tail ran on under the new note (now cut); bar 11 marked mp stood 4 dB over the +rest and the limiter flattened it (now p with the melody note leaning). + +**Open:** the user's ears — items 1–5 and the questions on the sheet (resonance amount, hall, balance, the change into +the storm). The editor cannot make a `.samples` file, and a map keeps a script's files: a 125 MB piano in the map is +out of the question — a sampled instrument wants to live outside the map (a library the plugin fetches, or the +user's disk) with only the renders inside. Velocity crossfades between layers and per-note release velocity are not +modelled. The C section's bars C6 and C16 were hard to read in the scan (C6's chord read as C4 F#4 A4 over D#2, a +diminished seventh to the E of C7; C16's bass as A2). + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice diff --git a/probes/answers/fur-elise-sound.txt b/probes/answers/fur-elise-sound.txt new file mode 100644 index 0000000..d40af31 --- /dev/null +++ b/probes/answers/fur-elise-sound.txt @@ -0,0 +1,59 @@ +TrigScript Showcase #3, Für Elise: the sound probe +================================================= + +StarCraft: Remastered, hosted as a multiplayer game, alone, with the game's MUSIC OFF. Headphones help. +Record one run (about 3 min 45 s). It plays five items, each announced in the text lines before it, a few +seconds apart, then says it is done. Each item is one sound mixed when the map was built, so every note is +exactly where it was written. +The five items are also beside this sheet, in fur-elise-sound-preview/, to play outside the game (the same Ogg +files the map has). + +The lobby should say "Für Elise sound probe". Does the ü show, or something else? -> + +1 of 5 — the old way (32 s): one recording of the piano's middle C, sped up or slowed for every other key, imported + as the editor imports a sound (one channel, 22 kHz), every note on the grid at one strength, no pedal. + This is what music.sampler could do before. It is here only to compare with. + How does it sound to you (a few words)? -> + +2 of 5 — the sampled piano, still on the grid (35 s): the Salamander grand, the recording made nearest each key + (a recording every three keys, moved at most one semitone), the one made at each note's strength (16 strengths), + the damper's sound when a key is let go. Same notes, same tempo, same strength as item 1, no pedal. + Better than 1? Does it sound like a real grand piano? -> + Anything wrong: a note out of tune, a click, a note cut off oddly? -> + +3 of 5 — played (49 s): the same opening, but with its own tempo (it leans into bar 4, slows into the middle part, + holds back on the turn to the high E, slows into the last A), dynamics (p, the middle part rising, pp on the turn, + the last A ppp), the pedal on each arpeggio as Beethoven marks it (and its sound), the strings ringing with the + pedal down (sympathetic resonance), and a concert hall. + Times in the item: 0:13 the middle part (C major), 0:17 the turn (E, the high E, E–D#), 0:23 the theme again, + 0:34 the last A, held in the pedal until about 0:40, then the hall's tail. + Does it feel played by a person, or still mechanical? -> + The tempo: too much rubato, too little, or right? -> + The pedal: is each arpeggio's pedal clean (no blur into the E–D# figure)? -> + The strings ringing with the pedal: can you hear them? Do they sound like a piano, or like a metallic ring? -> + The hall: too much, too little, right? (The plan is a smaller room for the first A, this hall for the last.) -> + Loudness: the piano items are made to −17 LUFS, the storm to −15. Too quiet against the game, fine? -> + +4 of 5 — the storm (32 s): the D minor section over the drumming A (C1 … C17), piano and orchestra: violins on the + chords' top line, violas under them, celli spiccato doubling the drumming bass, basses an octave down, horns and + trombones on the harmony, tuba on the bass, timpani on A and E. f, a lighter middle (mf), then rising over the + B-flat and B to the ff A minor chord, and the quiet E chord that ends it. + Times: 0:00 C1 (the diminished chord), 0:11 C9 (it starts again), 0:15 the climb over B-flat, 0:20 the ff chord. + Does the orchestra sound like an orchestra? Which instrument sounds worst? -> + Balance: is the piano still the lead? Too much brass? Timpani? Strings too quiet or too loud? -> + Is it "stormy" enough, or should it be bigger (faster, louder, more timpani, rolls)? -> + +5 of 5 — into the storm (46 s): the theme's last bars as in item 3 (pp), one bar of the drumming A alone getting + louder under a soft timpani roll, then the storm's first phrase with the orchestra coming in (at 0:12). + Does the change from the solo piano to the orchestra work? Too sudden, too soft, right? -> + +Anything wrong anywhere: crackle, clipping, a sound that cuts off, a hitch in the game? -> + +What to decide (your call): + - The arc: keep the orchestra to the storm only, or let the strings creep in earlier (the last bars before it)? -> + - Item 3's hall for the last A; a smaller room for the first? -> + - More velocity layers are in the piano (16); the probe uses all of them. Fine to keep the map at ~3.5 MB? -> + +Credits (in the map description too): Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). +Orchestra: VSCO 2 Community Edition by Versilian Studios (CC0). Beethoven's score is in the public domain; the +transcription and the arrangement are ours, written from the Breitkopf & Härtel complete edition (1888). diff --git a/probes/fur-elise-sound.ts b/probes/fur-elise-sound.ts new file mode 100644 index 0000000..fef8192 --- /dev/null +++ b/probes/fur-elise-sound.ts @@ -0,0 +1,155 @@ +// TrigScript Showcase #3, Für Elise: the sound probe (S7 in docs/v4-plan.md). Five items, each announced on the screen +// and played as one clip mixed when the map is built (so every note is where it was written: played note by note, a +// sound starts on the game's 42 ms frame and the mixer's 21 ms grid, which a lone piano would show), a few seconds apart: +// +// 1 The old way: one recording of the piano's middle C, sped up or slowed for every key (`music.sampler`), on the grid +// 2 The sampled piano (`music.sampled`): the recording nearest each key, at each note's strength — still on the grid +// 3 Played (`music.perform`): its own tempo and dynamics, the pedal and the strings ringing with it, a hall +// 4 The storm (the D minor section over the drumming A): piano and orchestra +// 5 From the theme's last bars into the storm, as the Showcase would go +// +// Host it as a multiplayer game, alone, the game's music off. The notes are ours, from the public-domain score +// (probes/lib/fur-elise-score.ts). Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). Orchestra: VSCO 2 +// Community Edition by Versilian Studios (CC0). The instruments are made from the libraries, which stay outside the +// repository, by probes/lib/fur-elise-sound-gen.mts. +// +// npx tsx probes/lib/fur-elise-sound-gen.mts # the instruments, into probes/ (ignored) +// MAP_NAME="Für Elise sound probe" MAP_DESCRIPTION="…" npx tsx probes/lib/raycaster-map.mts fixtures/eud/fur-elise-sound-base.scx +// npx tsx scripts/build-fixture.mts probes/fur-elise-sound.ts fixtures/eud/fur-elise-sound.scx fixtures/eud/fur-elise-sound-base.scx +import { music, type Instrument } from "trigscript/music"; +import piano from "./salamander-grand.samples"; +import middleC from "./salamander-c4.sound"; +import violinsSet from "./vsco-violins.samples"; +import violasSet from "./vsco-violas.samples"; +import celliSet from "./vsco-celli-spic.samples"; +import bassesSet from "./vsco-bass-spic.samples"; +import hornsSet from "./vsco-horns.samples"; +import tromboneSet from "./vsco-trombone.samples"; +import tubaSet from "./vsco-tuba.samples"; +import timpaniSet from "./vsco-timpani.samples"; +import rollsSet from "./vsco-timpani-rolls.samples"; +import { + A_RIGHT, A_LEFT, A_TEMPO, A_HOLDS, plain, rests, sixteenths, + C_RIGHT, C_LEFT, C_TEMPO, C_VIOLINS, C_VIOLAS, C_CELLI, C_BASSES, C_HORNS, C_TROMBONES, C_TUBA, C_TIMPANI, +} from "./lib/fur-elise-score"; + +/** + * How loud the piano items are made: a solo piano's loudest notes stand 19 … 20 dB over its loudness, so at −17 LUFS the + * limiter takes at most a few dB off the one or two loudest (at −16 it took 5.7 dB off the middle part's top). + */ +const PIANO_LUFS = -17; +/** The storm, louder: the arc's climax, a gentle compressor holding the orchestra together and the limiter its peaks. */ +const STORM_LUFS = -15; +/** A concert hall: a long, darkening tail after 32 ms. The plate's decay 0.84 rings about 7 s to silence. */ +const HALL = { decay: 0.84, damping: 0.5, predelay: 0.032 }; +/** A smaller room, for the theme played close. */ +const ROOM = { decay: 0.7, damping: 0.55, predelay: 0.018 }; +/** What every item goes through last, before the loudness and the limiter: nothing under 28 Hz. */ +const MASTER = (c: Clip) => c.filter("highpass", 28); +/** Ogg Vorbis quality: 6, about 190 kbit/s for two channels, so the solo piano's quiet tails keep their grain. */ +const QUALITY = 6; + +/* ── 1 and 2: on the grid ── */ + +const GRID = { meter: "3/8", bpm: 126, pickup: "1/8" }; +const onTheGrid = (instrument: Instrument) => music.perform(GRID, { right: { instrument, notes: plain(A_RIGHT) }, left: { instrument, notes: plain(A_LEFT) } }); +const oldPiano = music.sampler(middleC, "C4", { release: 0.08 }); +const item1 = music.render(onTheGrid(oldPiano), { master: MASTER, loudness: PIANO_LUFS }).ogg(QUALITY); +const item2 = music.render(onTheGrid(music.sampled(piano)), { master: MASTER, loudness: PIANO_LUFS }).ogg(QUALITY); + +/* ── 3: played ── */ + +// The strings in sympathy about 11 dB under the notes as a whole (0.2 made them 7 under: more ring than a piano has). +const grand = music.sampled(piano, { resonance: 0.07 }); +const PLAYED = { meter: "3/8", bpm: 120, pickup: "1/8", tempo: A_TEMPO, holds: A_HOLDS, humanize: { time: 0.004, velocity: 3, seed: 7 } }; +export const theme = music.perform(PLAYED, { + right: { instrument: grand, notes: A_RIGHT, lead: 0.008, reverb: 0.24 }, + left: { instrument: grand, notes: A_LEFT, velocity: 0.92 }, +}); +const item3 = music.render(theme, { reverb: HALL, master: MASTER, loudness: PIANO_LUFS }).ogg(QUALITY); + +/* ── 4: the storm ── */ + +const strings = { + violins: music.sampled(violinsSet), violas: music.sampled(violasSet), celli: music.sampled(celliSet), basses: music.sampled(bassesSet), +}; +const brass = { horns: music.sampled(hornsSet), trombones: music.sampled(tromboneSet), tuba: music.sampled(tubaSet) }; +const timpani = music.sampled(timpaniSet), rolls = music.sampled(rollsSet); +const stormPiano = music.sampled(piano, { resonance: 0.04 }); + +/** + * The orchestra's parts, each `before` bars of rest first, then the storm's. Their volumes set by measuring each alone + * (`lufs`, 2026-11-08) against the storm's piano at −16: violins −22, violas −24, celli −23, basses −25, horns −24, + * trombones −25, tuba −26, timpani −22 — the piano on top, the strings next. + */ +const orchestra = (before: number) => { + const lead = rests(before); + return { + violins: { instrument: strings.violins, notes: [...lead, ...C_VIOLINS], pan: -0.45, volume: 2.8, reverb: 0.32 }, + violas: { instrument: strings.violas, notes: [...lead, ...C_VIOLAS], pan: 0.2, volume: 0.85, reverb: 0.32 }, + celli: { instrument: strings.celli, notes: [...lead, ...C_CELLI], pan: 0.4, volume: 1.35, reverb: 0.25 }, + basses: { instrument: strings.basses, notes: [...lead, ...C_BASSES], pan: 0.55, volume: 1.55, reverb: 0.25 }, + horns: { instrument: brass.horns, notes: [...lead, ...C_HORNS], pan: -0.2, volume: 0.8, reverb: 0.4 }, + trombones: { instrument: brass.trombones, notes: [...lead, ...C_TROMBONES], pan: 0.25, volume: 2.8, reverb: 0.35 }, + tuba: { instrument: brass.tuba, notes: [...lead, ...C_TUBA], pan: 0.3, volume: 2.0, reverb: 0.3 }, + timpani: { instrument: timpani, notes: [...lead, ...C_TIMPANI], pan: -0.1, volume: 1.9, reverb: 0.45 }, + }; +}; + +export const storm = music.perform({ meter: "3/8", bpm: 134, tempo: C_TEMPO, humanize: { time: 0.004, velocity: 3, seed: 11 } }, { + right: { instrument: stormPiano, notes: C_RIGHT, reverb: 0.2 }, + left: { instrument: stormPiano, notes: C_LEFT, velocity: 0.82 }, + ...orchestra(0), +}); +/** The storm's bus: the low cut, and 2:1 above −20 dB, slow enough to let each chord's attack through. */ +const BUS = (c: Clip) => MASTER(c).compress({ threshold: -20, ratio: 2, attack: 0.02, release: 0.25, knee: 6 }); +const item4 = music.render(storm, { reverb: HALL, master: BUS, loudness: STORM_LUFS }).ogg(QUALITY); + +/* ── 5: into the storm ── */ + +// The theme's last bars (15 … 21) as item 3 plays them, a bar of the drumming A alone (the printed bar before the +// storm), and the storm's first phrase (C1 … C8): the orchestra comes in under a timpani roll. +const INTO = { meter: "3/8", bpm: 120, tempo: [[1, 122], [4, 124], [5, 118], [6, 120], [7, 112], [8, 120], [8.8, 130], [9, 134], [16, 134], [16.5, 124], [17, 110]] as const, humanize: { time: 0.004, velocity: 3, seed: 5 } }; +export const into = music.perform(INTO, { + right: { instrument: stormPiano, notes: [...A_RIGHT.slice(15, 22).map((b, k) => (k === 0 ? `pp ${b}` : b)), "A4/8 r r", ...C_RIGHT.slice(0, 8)], lead: 0.008, reverb: 0.2 }, + left: { instrument: stormPiano, notes: [`pp ${A_LEFT[15]}`, ...A_LEFT.slice(16, 22), `p < ${sixteenths("A2")}`, ...C_LEFT.slice(0, 8)], velocity: 0.85 }, + ...orchestra(8), + roll: { instrument: rolls, notes: [...rests(7), "pp A2/4.", ...rests(8)], volume: 0.9, reverb: 0.45 }, +}); +const item5 = music.render(into, { reverb: HALL, master: BUS, loudness: STORM_LUFS }).ogg(QUALITY); + +/* ── The program: each item announced, played, and a few seconds after it ends ── */ + +const GAP = 3; +const waitFor = (c: Clip) => Math.ceil((c.seconds + GAP) / 0.042); +const PARK = reserveLocation("fur elise: the camera"); + +program(async () => { + removeUnit(P1, units.AnyUnit); + removeUnit(P2, units.AnyUnit); + centerLocation(PARK, 64 * 32, 112 * 32); + centerView(PARK); + displayText("\x04Für Elise, the sound probe: five items, each announced before it plays. Game music off; record one run."); + await sleep(frames(96)); + displayText("\x031 of 5 \x04— the old way: one recording (middle C) sped up or slowed for every key, on the grid"); + await sleep(frames(60)); + playWav(item1, 0); + await sleep(frames(waitFor(item1))); + displayText("\x032 of 5 \x04— the sampled piano: the recording nearest each key, at each note's strength; still on the grid"); + await sleep(frames(60)); + playWav(item2, 0); + await sleep(frames(waitFor(item2))); + displayText("\x033 of 5 \x04— played: its own tempo and dynamics, the pedal, the strings ringing with it, a hall"); + await sleep(frames(60)); + playWav(item3, 0); + await sleep(frames(waitFor(item3))); + displayText("\x034 of 5 \x04— the storm (D minor, over the drumming A): piano and orchestra"); + await sleep(frames(60)); + playWav(item4, 0); + await sleep(frames(waitFor(item4))); + displayText("\x035 of 5 \x04— from the theme's last bars into the storm, as the Showcase would go"); + await sleep(frames(60)); + playWav(item5, 0); + await sleep(frames(waitFor(item5))); + displayText("\x04That is all: the five items are also in Maps/TrigScript/fur-elise-sound-preview/ to play outside the game."); +}); diff --git a/probes/lib/fur-elise-score.ts b/probes/lib/fur-elise-score.ts new file mode 100644 index 0000000..776544e --- /dev/null +++ b/probes/lib/fur-elise-score.ts @@ -0,0 +1,184 @@ +// Für Elise (Beethoven, WoO 59, "Clavierstück in A moll"): the notes, ours, written from the public-domain score — +// Beethoven's Werke, Serie 25 No. 298 (Breitkopf & Härtel, 1888), the scan on Wikimedia Commons — in the notation +// `music.perform` reads. Never from anyone's MIDI file or arrangement. A text a bar; [0] is the pickup where there is +// one. The orchestra's parts in the stormy section (C) are our arrangement. +// +// Bar numbers here: A section — 0 the pickup, 1 … 7, 8 the second ending (into the middle part), 9 … 21 as printed +// (12 … 14 the passage back to the theme), 22 the theme's last A, held. C section — C1 … C17, the D minor storm over +// the drumming A (printed bars 77 … 93 in the usual count), to the E chord before the pp arpeggios. + +/** `n` sixteenths of one note or chord: a bar of the drumming bass. */ +export const sixteenths = (note: string, n = 6) => [`${note}/16`, ...Array.from({ length: n - 1 }, () => note)].join(" "); +/** Bars of rest, 3/8 each. */ +export const rests = (n: number): string[] => Array.from({ length: n }, () => "r/4."); + +/* ── The A section ── */ + +// The right hand: the melody a little over its own arpeggio (the C4 E4 A4 that answers the left hand quieter), the +// turn's D#5 under its E5s. +export const A_RIGHT = [ + /* 0 */ "p E5/16@+2 D#5@-3", + /* 1 */ "E5/16@+3 D#5@-3 E5@+1 B4@-4 D5@-2 C5@-3", + /* 2 */ "A4/8 r/16 C4@-12 E4@-9 A4@-5", + /* 3 */ "B4/8@+2 r/16 E4@-12 G#4@-8 B4@-4", + /* 4 */ "C5/8@+5 r/16 E4@-10 E5@-1 D#5@-4", + /* 5 */ "E5/16@+2 D#5@-4 E5 B4@-5 D5@-3 C5@-4", + /* 6 */ "A4/8 r/16 C4@-12 E4@-9 A4@-5", + /* 7 */ "B4/8 r/16 E4@-12 C5@-4 B4@-6", + /* 8 */ "A4/8@-2 r/16 B4@-8 C5@-5 D5@-2", + /* 9 */ "p < E5/8.@+2 G4/16@-12 F5@-1 E5@-4", + /* 10 */ "D5/8.@+5 F4/16@-12 E5@-1 D5@-4", + /* 11 */ "p > C5/8.@+8 E4/16@-12 D5@-2 C5@-4", + /* 12 */ "B4/8 r/16 E4@-12 E5@-6 r", + /* 13 */ "pp r/16 E5@-2 E6@-8 r r D#5@-4", + /* 14 */ "E5/8 r/16 D#5@-4 E5@-2 D#5@-4", + /* 15 */ "E5/16@+2 D#5@-4 E5 B4@-5 D5@-3 C5@-4", + /* 16 */ "A4/8 r/16 C4@-12 E4@-9 A4@-5", + /* 17 */ "B4/8@+2 r/16 E4@-12 G#4@-8 B4@-4", + /* 18 */ "C5/8@+5 r/16 E4@-10 E5@-1 D#5@-4", + /* 19 */ "E5/16@+2 D#5@-4 E5 B4@-5 D5@-3 C5@-4", + /* 20 */ "A4/8 r/16 C4@-12 E4@-9 A4@-5", + /* 21 */ "> B4/8 r/16 E4@-12 C5@-5 B4@-7", + /* 22 */ "ppp A4/4.@+8", +]; + +// The left hand: each arpeggio under its pedal, as printed ("Ped." on the bar, "*" at its end); the turn in bars 12 … 14 +// handed across to it (its E4 tied over the bar line, then D#5 E5 in the treble). The last A is held in the pedal for two +// bars more, so it rings out before the dampers fall. +export const A_LEFT = [ + /* 0 */ "p r/8", + /* 1 */ "r/4.", + /* 2 */ "ped A2/16 E3 A3 r r/8 *", + /* 3 */ "ped E2/16 E3 G#3 r r/8 *", + /* 4 */ "ped A2/16 E3 A3 r r/8 *", + /* 5 */ "r/4.", + /* 6 */ "ped A2/16 E3 A3 r r/8 *", + /* 7 */ "ped E2/16 E3 G#3 r r/8 *", + /* 8 */ "ped A2/16 E3 A3 r r/8 *", + /* 9 */ "p ped C3/16 G3 C4 r r/8 *", + /* 10 */ "ped G2/16 G3 B3 r r/8 *", + /* 11 */ "p > ped A2/16 E3 A3 r r/8 *", + /* 12 */ "ped E2/16 E3 E4 r r E4~", + /* 13 */ "pp E4/16 r r * D#5@-6 E5@-6 r", + /* 14 */ "r/16 D#5@-6 E5@-6 r r/8", + /* 15 */ "r/4.", + /* 16 */ "ped A2/16 E3 A3 r r/8 *", + /* 17 */ "ped E2/16 E3 G#3 r r/8 *", + /* 18 */ "ped A2/16 E3 A3 r r/8 *", + /* 19 */ "r/4.", + /* 20 */ "ped A2/16 E3 A3 r r/8 *", + /* 21 */ "> ped E2/16 E3 G#3 r r/8 *", + /* 22 */ "ppp ped A2/16@+4 E3@+2 A3@+2 r r/8 | r/4. | r/4. *", +]; + +/** + * The A section's tempo, in eighths a minute: poco moto, the first phrase leaning on bar 4 and slowing into bar 8, the + * middle part moving on, the turn back to the theme (12 … 14) held back and let go, and the last bars slowing to the + * held A. [bar, bpm]: 0.5 is inside the pickup. + */ +export const A_TEMPO: readonly (readonly [number, number])[] = [ + [0.4, 112], [1, 120], [3, 124], [4, 118], [4.6, 110], [5, 120], [7, 120], [8, 104], [8.67, 112], [9, 124], [10.6, 128], [11.5, 118], + [12.5, 106], [13.4, 94], [14.2, 106], [14.9, 118], [15, 122], [18, 124], [19, 118], [20, 120], [21, 110], [21.7, 90], [22, 84], +]; +/** Breaths: before the middle part, on the high E, before the theme comes back, before the last A. */ +export const A_HOLDS: readonly (readonly [number, number])[] = [[9, 0.1], [13.33, 0.12], [15, 0.06], [22, 0.16]]; + +/** A part without its expression: no dynamics, no "@", no pedal — every note as a sequencer's grid plays it. */ +export const plain = (bars: readonly string[]): string[] => bars.map((b) => + b.split(/\s+/).filter((w) => w && !/^(ppp|pp|p|mp|mf|f|ff|fff|<|>|ped|\*)$/.test(w)).map((w) => w.replace(/@[+-]?\d+/, "")).join(" ")); + +/* ── The C section: the storm over the drumming A ── */ + +export const C_RIGHT = [ + /* C1 */ "f E4+G4+Bb4+C#5/4.!", + /* C2 */ "F4+A4+D5/4 C#5+E5/16 D5+F5", + /* C3 */ "G#4+D5+F5/4@+4 G#4+D5+F5/8", + /* C4 */ "A4+C5+E5/4.", + /* C5 */ "mf F4+D5/4 E4+C5/16 D4+B4", + /* C6 */ "C4+F#4+A4/4@+4 C4+A4/8", + /* C7 */ "C4+A4/8 E4+C5 D4+B4", + /* C8 */ "C4+A4/4.", + /* C9 */ "f E4+G4+Bb4+C#5/4.!", + /* C10 */ "F4+A4+D5/4 C#5+E5/16 D5+F5", + /* C11 */ "D5+F5/4@+4 D5+F5/8", + /* C12 */ "< D5+F5/4.", + /* C13 */ "G4+Eb5/4 F4+D5/16 Eb4+C5", + /* C14 */ "D4+F4+Bb4/4 D4+F4+A4/8", + /* C15 */ "D4+F4+G#4/4 D4+F4+G#4/8", + /* C16 */ "ff C4+E4+A4/4! r/8", + /* C17 */ "p E4+B4/8 r r", +]; +export const C_LEFT = [ + /* C1 */ `f ${sixteenths("A2")}`, + /* C2 */ sixteenths("A2"), + /* C3 */ sixteenths("A2"), + /* C4 */ sixteenths("A2"), + /* C5 */ `mf ${sixteenths("D2+A2")}`, + /* C6 */ sixteenths("D#2+A2"), + /* C7 */ "E2+A2/16 E2+A2 E2+A2 E2+A2 E2+G#2 E2+G#2", + /* C8 */ "A1+A2/16 A2 A2 A2 A2 A2", + /* C9 */ `f ${sixteenths("A2")}`, + /* C10 */ sixteenths("A2"), + /* C11 */ sixteenths("A2"), + /* C12 */ `< ${sixteenths("Bb2")}`, + /* C13 */ sixteenths("Bb2"), + /* C14 */ sixteenths("Bb2"), + /* C15 */ sixteenths("B2"), + /* C16 */ "ff A2/4! r/8", + /* C17 */ "p E3+G#3/8 r r", +]; + +/** The storm's tempo: driven, a little faster than the theme, broadening into its last chords. */ +export const C_TEMPO: readonly (readonly [number, number])[] = [[1, 134], [8, 134], [8.7, 124], [9, 134], [15, 132], [16, 116], [17, 100]]; + +// The orchestra, our arrangement: the violins on the chords' top line, the violas under them, the celli spiccato on the +// drumming bass and the basses on its eighths an octave down, horns and trombones holding the harmony where it is +// loudest, the tuba on the bass, the timpani on A and E. +export const C_VIOLINS = [ + "f C#5/4.", "D5/4 E5/16 F5", "F5/4 F5/8", "E5/4.", + "mf D5/4 C5/16 B4", "A4/4 A4/8", "A4/8 C5 B4", "A4/4.", + "f C#5/4.", "D5/4 E5/16 F5", "F5/4 F5/8", "< F5/4.", + "Eb5/4 D5/16 C5", "Bb4/4 A4/8", "G#4/4 G#4/8", "ff A4/4 r/8", "p B4/8 r r", +]; +export const C_VIOLAS = [ + "f Bb4/4.", "A4/4 C#5/16 D5", "D5/4 D5/8", "C5/4.", + "mf F4/4 E4/16 D4", "F#4/4 C4/8", "C4/8 E4 D4", "C4/4.", + "f Bb4/4.", "A4/4 C#5/16 D5", "D5/4 D5/8", "< D5/4.", + "G4/4 F4/16 Eb4", "F4/4 F4/8", "F4/4 F4/8", "ff E4/4 r/8", "p E4/8 r r", +]; +export const C_CELLI = [ + `f ${sixteenths("A2")}`, sixteenths("A2"), sixteenths("A2"), sixteenths("A2"), + `mf ${sixteenths("D3")}`, sixteenths("D#3"), "E3/16 E3 E3 E3 E3 E3", sixteenths("A2"), + `f ${sixteenths("A2")}`, sixteenths("A2"), sixteenths("A2"), `< ${sixteenths("Bb2")}`, + sixteenths("Bb2"), sixteenths("Bb2"), sixteenths("B2"), "ff A2/4! r/8", "p E3/8 r r", +]; +export const C_BASSES = [ + "f A1/8 A1 A1", "A1/8 A1 A1", "A1/8 A1 A1", "A1/8 A1 A1", + "mf D2/8 D2 D2", "D#2/8 D#2 D#2", "E2/8 E2 E2", "A1/8 A1 A1", + "f A1/8 A1 A1", "A1/8 A1 A1", "A1/8 A1 A1", "< Bb1/8 Bb1 Bb1", + "Bb1/8 Bb1 Bb1", "Bb1/8 Bb1 Bb1", "B1/8 B1 B1", "ff A1/4! r/8", "p E2/8 r r", +]; +export const C_HORNS = [ + "f E4+G4/4.", "D4+F4/4.", "D4+F4/4.", "C4+E4/4.", + "mf D4+F4/4.", "C4+F#4/4.", "C4+E4/4 B3+D4/8", "A3+C4/4.", + "f E4+G4/4.", "D4+F4/4.", "D4+F4/4.", "< D4+F4/4.", + "Eb4+G4/4.", "D4+F4/4.", "D4+F4/4.", "ff C4+E4/4! r/8", "r/4.", +]; +export const C_TROMBONES = [ + "f C#3+G3/4.!", "D3+F3/4.", "D3+G#3/4.", "C3+E3/4.", + ...rests(3), "mf C3+E3/4.", + "f C#3+G3/4.!", "D3+F3/4.", "D3+F3/4.", "< D3+F3/4.", + "Eb3+G3/4.", "D3+F3/4.", "D3+F3/4.", "ff C3+E3/4! r/8", "r/4.", +]; +export const C_TUBA = [ + "f A1/4.", "r/4.", "A1/4.", "r/4.", + "mf D2/4.", "D#2/4.", "E2/4.", "A1/4.", + "f A1/4.", "r/4.", "A1/4.", "< Bb1/4.", + "Bb1/4.", "Bb1/4.", "B1/4.", "ff A1/4! r/8", "p E2/8 r r", +]; +export const C_TIMPANI = [ + "f A2/4.!", "A2/8 r r", "A2/4.", "A2/8 A2/16 A2 A2/8", + ...rests(2), "E3/8 r E3", "A2/4.", + "ff A2/4.!", "A2/8 r r", "A2/8 A2/16 A2 A2/8", ...rests(3), + "E3/8 E3/16 E3 E3/8", "ff A2/4! r/8", "mf E3/8 r r", +]; diff --git a/probes/lib/fur-elise-sound-gen.mts b/probes/lib/fur-elise-sound-gen.mts new file mode 100644 index 0000000..dc30209 --- /dev/null +++ b/probes/lib/fur-elise-sound-gen.mts @@ -0,0 +1,51 @@ +// The Für Elise sound probe's instruments (probes/fur-elise-sound.ts), made from sample libraries kept outside the +// repository (never committed: they are their makers', and large) — SAMPLES_DIR, ~/github/samples by default: +// +// salamander-grand-v3/ Salamander Grand Piano V3, 44.1 kHz 16-bit (Alexander Holm, CC BY 3.0), from +// freepats.zenvoid.org: SalamanderGrandPianoV3+20161209_44khz16bit.tar.xz, unpacked into extracted/ +// vsco2-ce/ VSCO 2 Community Edition (Versilian Studios, CC0), from github.com/sgossner/VSCO-2-CE: the +// string sections' sustains and spiccati, tenor trombone, tuba, horn, timpani +// +// and one .sound: the piano's middle C at one strength, imported the old way (22 050 Hz, one channel, IMA ADPCM), for +// the probe's first item. Everything lands in probes/ (ignored by git). +// +// npx tsx probes/lib/fur-elise-sound-gen.mts +import { execFileSync } from "node:child_process"; +import { readFileSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { clipSamples, makeClip, mixdown, writeSound } from "../../compiler/sound"; + +const root = join(import.meta.dirname, "..", ".."), out = join(root, "probes"); +const S = process.env.SAMPLES_DIR ?? join(homedir(), "github", "samples"); +const SAL = join(S, "salamander-grand-v3", "extracted", "SalamanderGrandPianoV3_44.1khz16bit"), V = join(S, "vsco2-ce"); +const make = (...args: string[]) => execFileSync("npx", ["tsx", join(root, "scripts", "make-samples.mts"), ...args], { stdio: "inherit" }); +const VSCO = "VSCO 2 Community Edition by Versilian Studios (CC0)"; + +make(join(SAL, "SalamanderGrandPianoV3.sfz"), join(out, "salamander-grand.samples"), "--keys", "28-91", "--seconds", "10", "--name", "Salamander Grand Piano V3", "--credit", "Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0)"); +const vsco = (folder: string, file: string, name: string, ...more: string[]) => make("--names", join(V, folder), join(out, `${file}.samples`), "--name", name, "--credit", VSCO, ...more); +vsco("Strings/Violin Section/susVib", "vsco-violins", "Violins (VSCO 2 CE)", "--octave", "1", "--seconds", "6", "--release", "0.35"); +vsco("Strings/Violin Section/Spic", "vsco-violins-spic", "Violins spiccato (VSCO 2 CE)", "--octave", "1", "--release", "0.15"); +vsco("Strings/Viola Section/susvib", "vsco-violas", "Violas (VSCO 2 CE)", "--octave", "1", "--seconds", "6", "--release", "0.35"); +vsco("Strings/Viola Section/spic", "vsco-violas-spic", "Violas spiccato (VSCO 2 CE)", "--octave", "1", "--release", "0.15"); +vsco("Strings/Cello Section/susvib", "vsco-celli", "Celli (VSCO 2 CE)", "--octave", "1", "--seconds", "6", "--release", "0.35"); +vsco("Strings/Cello Section/spic", "vsco-celli-spic", "Celli spiccato (VSCO 2 CE)", "--octave", "1", "--release", "0.15"); +vsco("Strings/Solo Contrabass/SusVib", "vsco-bass", "Contrabass (VSCO 2 CE)", "--octave", "1", "--seconds", "6", "--release", "0.35"); +vsco("Strings/Solo Contrabass/Spic", "vsco-bass-spic", "Contrabass spiccato (VSCO 2 CE)", "--octave", "1", "--release", "0.15"); +vsco("Brass/Tenor Trombone/sus", "vsco-trombone", "Tenor trombone (VSCO 2 CE)", "--octave", "1", "--seconds", "6", "--release", "0.25"); +vsco("Brass/Tuba/sus", "vsco-tuba", "Tuba (VSCO 2 CE)", "--octave", "1", "--seconds", "6", "--release", "0.25"); +vsco("Brass/F Horn/sus", "vsco-horns", "French horn (VSCO 2 CE)", "--octave", "1", "--seconds", "6", "--release", "0.3"); +// The timpani's names carry no note: each drum's pitch is its principal tone, read from its spectrum (the (2,1) mode a +// fifth above it beside it in every drum). +vsco("Percussion/Timpani", "vsco-timpani", "Timpani (VSCO 2 CE)", "--pitch", "Timpani1=41.45,Timpani2=46.75,Timpani3=49.5,Timpani4=52.45,Timpani5=54.6", "--seconds", "6", "--release", "2"); +vsco("Percussion/Timpani/Rolls", "vsco-timpani-rolls", "Timpani rolls (VSCO 2 CE)", "--pitch", "Timpani1=42,Timpani2=47,Timpani3=49.5,Timpani4=52.5,Timpani5=55", "--seconds", "12", "--release", "1"); + +// Middle C, one strength (the 10th of 16), as Import Video… would have made it: one channel, 22 050 Hz, the first 8 s. +const wav = readFileSync(join(SAL, "44.1khz16bit", "C4v10.wav")); +const data = wav.indexOf("data"), n = Math.min(wav.readUInt32LE(data + 4) / 4, 8 * 44100); +const mono = new Float32Array(n); +for (let i = 0; i < n; i++) mono[i] = (wav.readInt16LE(data + 8 + 4 * i) + wav.readInt16LE(data + 10 + 4 * i)) / 65536; +for (let i = 0; i < 22050; i++) mono[n - 1 - i] *= i / 22050; +const at22 = clipSamples(mixdown([{ clip: makeClip(mono, 44100), at: 0 }], undefined, 22050)); +writeFileSync(join(out, "salamander-c4.sound"), writeSound({ rate: 22050, samples: at22, source: "C4v10.wav (Salamander Grand Piano V3)" })); +console.log("probes/salamander-c4.sound"); From cec5337feff9e69e7841e5016d1e27368b3a97b3 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:08:44 -0600 Subject: [PATCH 10/31] S7: the sound probe as played Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 6 ++++++ probes/answers/fur-elise-sound.txt | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index 19f0383..078d92b 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6598,6 +6598,12 @@ user's disk) with only the renders inside. Velocity crossfades between layers an modelled. The C section's bars C6 and C16 were hard to read in the scan (C6's chord read as C4 F#4 A4 over D#2, a diminished seventh to the E of C7; C16's bass as A2). +**Played 2026-11-09** (recording StarCraft 2026.11.09 - 05.02.42.14.mp4): the user, "sounds great". Measured against the +five files: each heard whole (fit 1.000), at the file's level (+0.7 dB), no drift, stereo kept, nothing at full scale; +the game's text shows the ü. The sheet's choices were not answered one by one, so the defaults stand: the orchestra in +the storm only, a smaller room for the first A and the hall for the last, −17 / −15 LUFS, all 16 piano layers. + + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice diff --git a/probes/answers/fur-elise-sound.txt b/probes/answers/fur-elise-sound.txt index d40af31..04b31d0 100644 --- a/probes/answers/fur-elise-sound.txt +++ b/probes/answers/fur-elise-sound.txt @@ -57,3 +57,15 @@ What to decide (your call): Credits (in the map description too): Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). Orchestra: VSCO 2 Community Edition by Versilian Studios (CC0). Beethoven's score is in the public domain; the transcription and the arrangement are ours, written from the Breitkopf & Härtel complete edition (1888). + +Results (played 2026-11-09, recording StarCraft 2026.11.09 - 05.02.42.14.mp4, 3:50) +------------------------------------------------------------------------------------ +The user: "sounds great". No answers given item by item; the defaults below stand. +Measured against the five files (scripts/recording-check.mts): + - all five heard, each a perfect fit (1.000), at the file's own level (+0.67 … +0.69 dB, steady to 0.2 dB a second), + no drift (0 samples at 48 kHz at every 10 s), stereo as the file (L − R follows at 1.000; item 1 is one channel), + no sample at full scale, peaks 0.51 … 0.92. + - starts at 7.85, 45.31, 85.61, 140.46, 178.45 s of the recording. + - the game's text shows "Für Elise" with the ü (the lobby was not in the recording). +Defaults taken: orchestra in the storm only; a smaller room for the first A, this hall for the last; loudness +−17 / −15 LUFS; all 16 piano layers; resonance 0.07. From 12347b301cdb18748954ca80983b05df042139dc Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:20:55 -0600 Subject: [PATCH 11/31] S7: the visualizer probe as played Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 7 +++++++ probes/answers/fur-elise-visual.txt | 16 ++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index 41941e8..8684b50 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6615,6 +6615,13 @@ minimap roll is big enough to show in the video or the main screen carries it al (Remastered graphics blurs the fog minimap and it has two tones, no hands; the unit board played well for Korobeiniki), hallucinations (a unit's hallucinated flag is not its tint) and spells by order (no Cast order from a trigger). +**Played 2026-11-09** (recording StarCraft 2026.11.09 - 05.14.55.15.mp4): the lobby shows the ü; everything draws as +built. The picture leads the sound by a steady ~95 ms (clicks −88 … −100 ms; the music 85–115 ms in every 3 s window, +no drift over the 35 s A clip), so the Showcase starts each clip ~2 frames before its picture. A clip a bar (S2) lands +−40 … +30 ms off the one clip (S1), bar to bar: one clip a section or one for the whole piece, never a clip a bar. No +Disruption Web in Remastered either. The explosions show on the downbeats. + + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice diff --git a/probes/answers/fur-elise-visual.txt b/probes/answers/fur-elise-visual.txt index 08e0213..000dea7 100644 --- a/probes/answers/fur-elise-visual.txt +++ b/probes/answers/fur-elise-visual.txt @@ -60,3 +60,19 @@ What I measure from the recording (no need to fill in) - S2 against S1: the same notes, the same lamp. Each bar of S2 starts on the mixer's 21.3 ms grid on its own, so its delay may change by up to 21 ms from bar to bar; S1's should stay the same through the clip. - Minimap redraws: how often the roll moves (expected about 12 times a second). + +Results (played 2026-11-09, recording StarCraft 2026.11.09 - 05.14.55.15.mp4, 1:57, Remastered graphics) +--------------------------------------------------------------------------------------------------------- +No comments from the user; measured from the recording (lamp = mean grey of a 160×20 crop at (270,80), 60 fps; +audio onsets where the game's digital silence ends; music by onset strength against the lamp's flashes). +1. The lobby shows "Für Elise visual probe" with the ü. +2–4. The minimap roll and the main screen's Flags draw as built: falling notes, gold/cyan hands, red storm chords. +6. The picture LEADS the sound by a steady ~95 ms: T's clicks −100, −88, −98, −89, −96 ms (lamp before click); + the music 85–115 ms in every 3-second window of A1, A2, C-a, S1, S2 and V1, no trend over the 35 s A clip. + (The theme's even sixteenths make the match repeat every ~130 ms; the search was held to 40–170 ms.) + The Showcase starts each clip ~2 frames before its picture (or holds the picture 2 frames). +7. No Disruption Web appeared: Remastered refuses it from a trigger, as 1.16.1 does. The red flashes show. +8. The explosions (Wraiths, then Battlecruisers) show on the downbeats. +9. S2 (a clip a bar) against S1 (one clip): each bar lands −40 … +30 ms off S1's place — audible unevenness. One + long clip (or a clip a section) is the way; never a clip a bar. +5, 10: the look and speed are the user's choice. From 25003245c9e21c37db8bc900745e0fcea1f46dbf Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:21:48 -0600 Subject: [PATCH 12/31] S7: the looks chosen after the visualizer probe Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index 8684b50..a323431 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6620,6 +6620,8 @@ built. The picture leads the sound by a steady ~95 ms (clicks −88 … −100 m no drift over the 35 s A clip), so the Showcase starts each clip ~2 frames before its picture. A clip a bar (S2) lands −40 … +30 ms off the one clip (S1), bar to bar: one clip a section or one for the whole piece, never a clip a bar. No Disruption Web in Remastered either. The explosions show on the downbeats. +**Chosen (the user, 2026-11-09):** falling notes; the main screen a row every other frame (A2); the storm with red +flashes on each chord and explosions on the big downbeats only (their game sounds heard). ### Smaller things that show well From abae53096f52c26d9138211137d2e6b40a3b6516 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:25:01 -0600 Subject: [PATCH 13/31] music.excerpt, and together() to a loudness: a long piece rendered a section at a time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `music.excerpt(performance, from, to)` is the bars asked for as a performance of its own from 0, with `at` where it begins: the notes struck in it, and the pedal — a pedal put down before it is down already (a negative down), holding what it holds but making no sound of its own there, since the excerpt before has it. Rendered apart, each section can have its room, its tail ringing under the next when they are added up at their `at`s. `together(parts, { lufs })` turns sections made apart up or down by one gain, so what they add up to has that loudness and they stay as loud against one another as they were played. Without `lufs` it makes the same clips (and names) as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- compiler/declarations.ts | 6 ++++-- compiler/generated/stdlib.ts | 2 +- compiler/sound.ts | 17 +++++++++++++---- ledger/sounds/music-perform.ts | 6 +++++- stdlib/music.ts | 32 ++++++++++++++++++++++++++++++-- tests/sampled.test.ts | 33 +++++++++++++++++++++++++++++++++ 6 files changed, 86 insertions(+), 10 deletions(-) diff --git a/compiler/declarations.ts b/compiler/declarations.ts index 42d64bc..9f8248b 100644 --- a/compiler/declarations.ts +++ b/compiler/declarations.ts @@ -691,9 +691,11 @@ ${kw}function mixdown(parts: readonly { readonly clip: Clip; readonly at: number * over them — each turned down by one gain, so what they add up to never goes over \`peak\` (0.84, −1.5 dB), between * the samples too: what a limiter does for a mix, for sounds the game adds up itself. Never turned up. The same clip * given twice comes back as one. \`over\`: clips that may play on top, each at any of its times (a stinger on any bar - * line), room left for them too; they come back after the parts, turned down with them. When the script is built: \`const [a, b] = together([{ clip: x, at: 0 }, { clip: y, at: 1 }])\` + * line), room left for them too; they come back after the parts, turned down with them. \`lufs\`: instead the one gain, + * up or down, that brings them together to that loudness — sections of a piece rendered apart, kept as loud against + * one another as they were played. When the script is built: \`const [a, b] = together([{ clip: x, at: 0 }, { clip: y, at: 1 }])\` */ -${kw}function together(parts: readonly { readonly clip: Clip; readonly at: number }[], options?: { readonly peak?: number; readonly over?: readonly { readonly clip: Clip; readonly at: readonly number[] }[] }): Clip[]; +${kw}function together(parts: readonly { readonly clip: Clip; readonly at: number }[], options?: { readonly peak?: number; readonly lufs?: number; readonly over?: readonly { readonly clip: Clip; readonly at: readonly number[] }[] }): Clip[]; /** A brush of cover(): which of the shapes (0 the first), centred on tile (x, y) of the picture. */ ${kw}interface Brush { readonly x: number; readonly y: number; readonly shape: number } /** diff --git a/compiler/generated/stdlib.ts b/compiler/generated/stdlib.ts index 61c3935..c7ea8f0 100644 --- a/compiler/generated/stdlib.ts +++ b/compiler/generated/stdlib.ts @@ -3,7 +3,7 @@ export const STDLIB_SOURCES: Readonly> = { "cutscene": "/**\n * Scenes acted out in the game: the standard library's \"trigscript/cutscene\" (TrigScript 4).\n *\n * import { Camera, walk, line, play, SECOND } from \"trigscript/cutscene\";\n *\n * async function intro(raider: Unit) {\n * const cam = new Camera(raider.x, raider.y);\n * await line(units.JimRaynorMarine, \"Something's moving out there.\", 3 * SECOND);\n * const there = start(walk(raider, 1200, 640)); // the walk goes on while the camera follows\n * await cam.follow(raider, 2 * SECOND);\n * await there;\n * await cam.pan(1600, 400, 2 * SECOND);\n * await cam.shake(12);\n * }\n *\n * program(async () => {\n * const raider = first(unitsAt(locations.Base, { owner: P1, type: units.TerranMarine }));\n * if (!raider) return;\n * const skipped = await play(P1, start(intro(raider))); // Escape skips the rest of it\n * if (skipped) print(\"Skipped.\");\n * });\n *\n * Everything here is what a trigger can do, done a frame at a time: the camera is Center View on a location the library\n * keeps for itself, moved to where the camera should look; a unit walks by a Move order to another; a line is the\n * speaker's portrait talking and the words in the middle of the screen. Places are pixels (32 a tile), (0, 0) the map's\n * top left; time is frames of the game, 24 a second on Fastest (`SECOND`). The camera is the one of the player the\n * program runs as, as Center View's is.\n */\nimport { centerLocation, centerView, reserveLocation, talkingPortrait, print, sleep, frames, nextFrame, keyPressed, type Player, type Task, type Unit, type UnitType } from \"trigscript\";\nimport { easeInOutQuad, easeInQuad, easeOutQuad, easeOutBack } from \"trigscript/math\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nexport const SECOND = 24;\n\nconst VIEW = reserveLocation(\"cutscene: where the camera looks\");\nconst GOAL = reserveLocation(\"cutscene: where a unit is sent\");\n\n/** How a glide speeds up and slows down: evenly, starting slow, ending slow, both, or ending past the mark and back. */\nexport type Ease = \"linear\" | \"in\" | \"out\" | \"inOut\" | \"back\";\n\n/** How far along a glide is at `t` (0 at its start, 1 at its end), as `ease` has it. */\nfunction eased(t: fixed, ease: Ease): fixed {\n if (ease === \"in\") return easeInQuad(t);\n if (ease === \"out\") return easeOutQuad(t);\n if (ease === \"inOut\") return easeInOutQuad(t);\n if (ease === \"back\") return easeOutBack(t);\n return t;\n}\n\n/**\n * The camera of the player the program runs as: where it looks, and how it gets somewhere else. It looks at its first\n * place as soon as it is made.\n */\nexport class Camera {\n /** The point the camera is centred on, in pixels. */\n x: number;\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /** Look at a point, now. */\n look(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /**\n * Glide to a point over `time` frames, looking at each place on the way a frame at a time.\n * @param ease How it speeds up and slows down; \"inOut\" unless it says.\n */\n async pan(x: number, y: number, time: number, ease: Ease = \"inOut\") {\n const fromX = this.x;\n const fromY = this.y;\n let i = 1;\n while (i <= time) {\n const k = eased(fixed(i) / time, ease);\n this.look(fromX + Math.round((x - fromX) * k), fromY + Math.round((y - fromY) * k));\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n\n /** Keep a unit in the middle of the screen for `time` frames, or until it is gone. */\n async follow(u: Unit, time: number) {\n let i = 0;\n while (i < time && u) {\n this.look(u.x, u.y);\n await nextFrame();\n i++;\n }\n }\n\n /** Shake for `time` frames, `size` pixels each way (8 unless it says), and settle where it was. */\n async shake(time: number, size: number = 8) {\n const x = this.x;\n const y = this.y;\n let i = 0;\n while (i < time) {\n const left = (i % 4) < 2;\n const up = (i % 2) === 0;\n centerLocation(VIEW, left ? x - size : x + size, up ? y - size : y + size);\n centerView(VIEW);\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n}\n\n/**\n * Send a unit to a point by a Move order, and wait until it is there — within `near` pixels (48 unless it says) — or\n * `limit` frames have passed (30 seconds unless it says), or it is gone.\n * @returns Whether it got there.\n */\nexport async function walk(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"move\", near, limit);\n}\n\n/** The same with an Attack order: the unit fights what it meets on the way. */\nexport async function charge(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"attack\", near, limit);\n}\n\nasync function go(u: Unit, x: number, y: number, how: \"move\" | \"attack\", near: number, limit: number): Promise {\n centerLocation(GOAL, x, y);\n u.order(how, GOAL);\n let waited = 0;\n while (u && Math.abs(u.x - x) + Math.abs(u.y - y) > near && waited < limit) {\n await nextFrame();\n waited++;\n }\n return !!u && Math.abs(u.x - x) + Math.abs(u.y - y) <= near;\n}\n\n/**\n * Send every unit of a group to a point together, and wait until each is there, gone, or `limit` frames have passed.\n * @returns How many got there.\n */\nexport async function walkAll(group: Unit[], x: number, y: number, near: number = 64, limit: number = 30 * SECOND): Promise {\n centerLocation(GOAL, x, y);\n for (const u of group) if (u) u.order(\"move\", GOAL);\n let waited = 0;\n let there = 0;\n while (waited < limit) {\n there = 0;\n let moving = 0;\n for (const u of group) {\n if (!u) continue;\n if (Math.abs(u.x - x) + Math.abs(u.y - y) <= near) there++;\n else moving++;\n }\n if (moving === 0) break;\n await nextFrame();\n waited++;\n }\n return there;\n}\n\n/**\n * A line of the scene: the speaker's portrait talks and the words show in the middle of the screen, for `time` frames\n * (3 seconds unless it says), and then the scene goes on.\n */\nexport async function line(speaker: UnitType, text: string, time: number = 3 * SECOND) {\n talkingPortrait(speaker, Math.round((time * 1000) / SECOND));\n print(text, { position: \"center\" });\n await sleep(frames(time));\n}\n\n/**\n * Play a scene, started as a task (`start(intro())`), for a player who may skip it: when they press `key` (Escape unless\n * it says) the scene stops where it is. Put things where the scene would have left them when it gives true.\n * @returns Whether it was skipped.\n */\nexport async function play(player: Player, scene: Task, key: \"Escape\" | \"Space\" | \"Enter\" = \"Escape\"): Promise {\n while (scene.running) {\n if (keyPressed(player, key)) {\n scene.cancel();\n return true;\n }\n await nextFrame();\n }\n return false;\n}\n", "fog": "/**\n * Fog of war as a picture: the standard library's \"trigscript/fog\" (TrigScript 4).\n *\n * import { fog } from \"trigscript/fog\";\n *\n * const heart = fog.picture([\".##.##.\", \"#######\", \".#####.\", \"..###..\"]);\n *\n * program(async () => {\n * fog.reveal(P1); // the whole map lit once: from now on dark is fog, not black\n * while (true) {\n * fog.light(P1, 30, 20, 5); // a disc of size 5 around tile (30, 20), this frame only\n * fog.light(P1, 60, 40, heart); // a picture, its top left on tile (60, 40)\n * await nextFrame();\n * }\n * });\n *\n * The fog is a canvas that starts every frame dark: what a program lights this frame is what shows this frame, and\n * nothing else needs doing. There is no dark brush — the game's sight only ever reveals — so dark is whatever is not\n * lit; to draw dark shapes, light around them (a picture with `{ ink: \"dark\" }`). Dark is also the sharper ink: a lit\n * part is at least a brush wide (3 tiles across, 4 down), while a dark line one tile wide stays exactly that. Nothing\n * else needs doing — the library writes the game's vision countdown after every frame (memory.vision.countdown), so\n * the next frame starts from a wiped board. Watch it on the minimap. With Classic graphics (Options > Graphics) a tile\n * of the map is a pixel there, sharp; Remastered graphics blurs it a few tiles wide.\n *\n * What the board is made of decides how far apart lit and fog look. Remastered draws a tile on the minimap as the\n * average of its art and fog as 0.64 of lit, whatever the tile, so the brightest art is the best board there: plain\n * Ice snow (lit 130 against fog 82, measured 2026-10-19). Classic draws a tile as one colour of its own; Badlands\n * tile 23778 is the widest apart there, and dim and textured in Remastered. Snow played the better of the two.\n *\n * How it draws, played in StarCraft: Remastered (2026-10-17): a brush is a unit made on a tile and taken away in the\n * same trigger pass; the tiles its sight revealed stay lit through the frame. A brush's size is the unit's sight\n * range, so each size is a unit type of its own — the flying heroes below, which no ordinary map places — whose sight\n * is set every frame (Remastered takes a sight write a frame late, so one type cannot change size within a frame).\n * Coordinates are tiles, (0, 0) the map's top left. About 800 brushes a frame is the most the game makes: it keeps a\n * removed unit's place until the next frame.\n */\nimport { game, program, sleep, frames, stats, units, createUnit, removeUnit, centerLocation, reserveLocation, memory, cover, nextFrame, type Player, type UnitType, type Video } from \"trigscript\";\n\n/**\n * Each brush's shape, sizes 1 to 11: the tiles a flying unit of that sight range reveals, read out of the game.\n * \"@\" is the tile the brush is centred on. The game's air sight leaves the centre's row one short below, so every\n * shape reaches a row further up than down.\n */\nexport const SHAPES: readonly (readonly string[])[] = [\n // 1\n [\"###\", \"###\", \"#@#\", \"###\"],\n // 2\n [\".###.\", \"#####\", \"#####\", \"##@##\", \"#####\", \"#####\"],\n // 3\n [\"..###..\", \"#######\", \"#######\", \"#######\", \"###@###\", \"#######\", \"#######\", \"#######\"],\n // 4\n [\"..#####...\", \".#######..\", \"#########.\", \"##########\", \"##########\", \"####@#####\", \"##########\", \"##########\", \"#########.\", \".#######..\", \"......#...\"],\n // 5\n [\"...#####....\", \"..#######...\", \".#########..\", \"###########.\", \"############\", \"############\", \"#####@######\", \"############\", \"############\", \"###########.\", \".#########..\", \"..#######...\", \".......#....\"],\n // 6\n [\"....#####.....\", \"..#########...\", \".###########..\", \"#############.\", \"#############.\", \"##############\", \"##############\", \"######@#######\", \"##############\", \"##############\", \"#############.\", \"#############.\", \".###########..\", \"..#########...\", \"........#.....\"],\n // 7\n [\".....#####......\", \"...#########....\", \"..###########...\", \".#############..\", \"###############.\", \"###############.\", \"################\", \"################\", \"#######@########\", \"################\", \"################\", \"###############.\", \"###############.\", \".#############..\", \"..###########...\", \"...#########....\", \".........#......\"],\n // 8\n [\"......#####.......\", \"....#########.....\", \"..#############...\", \".###############..\", \".###############..\", \"#################.\", \"#################.\", \"##################\", \"##################\", \"########@#########\", \"##################\", \"##################\", \"#################.\", \"#################.\", \".###############..\", \".###############..\", \"..#############...\", \"....#########.....\", \"..........#.......\"],\n // 9\n [\"......#######.......\", \"....###########.....\", \"...#############....\", \"..###############...\", \".#################..\", \"###################.\", \"###################.\", \"####################\", \"####################\", \"####################\", \"#########@##########\", \"####################\", \"####################\", \"####################\", \"###################.\", \"###################.\", \".#################..\", \"..###############...\", \"...#############....\", \"....###########.....\", \"........#####.......\"],\n // 10\n [\".......#######........\", \".....###########......\", \"....#############.....\", \"..#################...\", \"..#################...\", \".###################..\", \"#####################.\", \"#####################.\", \"######################\", \"######################\", \"######################\", \"##########@###########\", \"######################\", \"######################\", \"######################\", \"#####################.\", \"#####################.\", \".###################..\", \"..#################...\", \"..#################...\", \"....#############.....\", \".....###########......\", \".........#####........\"],\n // 11\n [\"........#######.........\", \"......###########.......\", \"....###############.....\", \"...#################....\", \"..###################...\", \".#####################..\", \".#####################..\", \"#######################.\", \"#######################.\", \"########################\", \"########################\", \"########################\", \"###########@############\", \"########################\", \"########################\", \"########################\", \"#######################.\", \"#######################.\", \".#####################..\", \".#####################..\", \"..###################...\", \"...#################....\", \"....###############.....\", \"......###########.......\", \"..........#####.........\"],\n];\n\n/** Each size's unit, size 1 first: flying heroes without a sight upgrade. A map that places one gets odd sight from it. */\nconst BRUSHES: readonly UnitType[] = [\n units.KukulzaMutalisk, units.KukulzaGuardian, units.YggdrasillOverlord, units.MagellanScienceVessel,\n units.GantrithorCarrier, units.HyperionBattlecruiser, units.NoradIIBattlecruiser, units.TomKazanskyWraith,\n units.DanimothArbiter, units.MojoScout, units.ArtanisScout,\n];\n\n/** Where each brush is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"fog: where each brush is made\");\n\n/**\n * One disc: the tiles a brush of `size` covers (SHAPES), centred on tile (x, y). What light() does with a size. A brush\n * is a unit made where SPOT is and taken away again at once; each branch makes its own size's, so that the unit type\n * of the action is known when the script is built (one given by the program costs writing it into the action).\n */\nconst disc = game((player: Player, x: number, y: number, size: number) => {\n discPx(player, x * 32 + 16, y * 32 + 16, size);\n});\n\n/**\n * disc() in pixels, (px, py) the centre of the tile: what a caller with many brushes uses, its products by 32 worked\n * out once and the brushes' offsets added (a product by 32 of a number the game holds is a test a bit, about 0.4 µs).\n */\nconst discPx = game((player: Player, px: number, py: number, size: number) => {\n centerLocation(SPOT, px, py, 32, 32);\n switch (size) {\n case 0: case 1: createUnit(player, BRUSHES[0], 1, SPOT); removeUnit(player, BRUSHES[0]); break;\n case 2: createUnit(player, BRUSHES[1], 1, SPOT); removeUnit(player, BRUSHES[1]); break;\n case 3: createUnit(player, BRUSHES[2], 1, SPOT); removeUnit(player, BRUSHES[2]); break;\n case 4: createUnit(player, BRUSHES[3], 1, SPOT); removeUnit(player, BRUSHES[3]); break;\n case 5: createUnit(player, BRUSHES[4], 1, SPOT); removeUnit(player, BRUSHES[4]); break;\n case 6: createUnit(player, BRUSHES[5], 1, SPOT); removeUnit(player, BRUSHES[5]); break;\n case 7: createUnit(player, BRUSHES[6], 1, SPOT); removeUnit(player, BRUSHES[6]); break;\n case 8: createUnit(player, BRUSHES[7], 1, SPOT); removeUnit(player, BRUSHES[7]); break;\n case 9: createUnit(player, BRUSHES[8], 1, SPOT); removeUnit(player, BRUSHES[8]); break;\n case 10: createUnit(player, BRUSHES[9], 1, SPOT); removeUnit(player, BRUSHES[9]); break;\n default: createUnit(player, BRUSHES[10], 1, SPOT); removeUnit(player, BRUSHES[10]);\n }\n});\n\n/**\n * Light the whole map once, so that from now on a tile left dark shows as fog (grey) rather than as never seen\n * (black) — every picture then has the same two tones. Takes one frame.\n * @param player Whose fog: P1 … P8, known when the script is built.\n */\nexport const reveal = game((player: Player) => {\n const width = memory.map.width;\n const height = memory.map.height;\n // Size 11 is 23 tiles wide: a brush every 14 tiles leaves no gap, and one more past the end, kept inside, reaches the edge.\n for (let y = 2; y < height + 12; y += 14) {\n for (let x = 2; x < width + 12; x += 14) disc(player, Math.min(x, width - 3), Math.min(y, height - 3), 11);\n }\n});\n\n/**\n * Light a rectangle of tiles for this frame, worked out while the game runs: its top left on tile (x, y), `width`\n * tiles across and `height` down. Every one of the five may change from frame to frame — the walls of a raycaster, a\n * bar of a chart. It is exact from 3 × 4 up (the smallest brush); a thinner one is lit a brush wide, centred.\n *\n * fog.rect(P1, 10, 20, 3, wall); // a column 3 tiles wide, `wall` tall\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of its left edge.\n * @param y The row of its top edge.\n * @param width How many tiles across.\n * @param height How many tiles down.\n */\nexport const rect = game((player: Player, x: number, y: number, width: number, height: number) => {\n if (width < 1 || height < 1) return;\n // Size 1 is 3 tiles across and 4 down, its centre the middle column and the third row: a grid of them, the last\n // column and row moved back to end on the edge (overlapping the one before), covers the rectangle exactly.\n const right = Math.max(x + width - 2, x + 1);\n const bottom = Math.max(y + height - 2, y + 2);\n // (The brush made here, not through disc(): its unit type is then known when the script is built, which makes the\n // action a constant — a size from the program costs a branch and a written field a brush.)\n let cy = y + 2;\n while (true) {\n let cx = x + 1;\n while (true) {\n centerLocation(SPOT, cx * 32 + 16, cy * 32 + 16, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (cx >= right) break;\n cx = Math.min(cx + 3, right);\n }\n if (cy >= bottom) break;\n cy = Math.min(cy + 4, bottom);\n }\n});\n\n/** A picture for the fog, made when the script is built: its size in tiles and the brushes that draw it. */\nexport interface Picture {\n readonly width: number;\n readonly height: number;\n readonly brushes: readonly { readonly x: number; readonly y: number; readonly size: number }[];\n}\n\n/**\n * A picture from rows of text, worked out when the script is built: `#` is the ink, anything else is not.\n *\n * fog.picture([\"..##..\", \".####.\", \"######\"]) // light ink: the # tiles are lit\n * fog.picture([\"..##..\", \".####.\", \"######\"], { ink: \"dark\" }) // dark ink: the # tiles stay dark, the rest is lit\n *\n * With light ink a lit part thinner than a brush (3 tiles across, 4 down) is drawn a tile or two thicker. An image's\n * halftone (`fog.picture(photo.halftone(6))`) is drawn with the brushes it was made of, one a cell. With dark\n * ink every tile of the picture's rectangle that is not `#` is lit and the `#` tiles keep their shape exactly,\n * however thin — the ink for line art and silhouettes.\n */\nexport function picture(rows: readonly string[], options: { readonly ink?: \"light\" | \"dark\" } = {}): Picture {\n const height = rows.length;\n const width = Math.max(0, ...rows.map((r) => r.length));\n // An image's halftone (image.halftone(6)) comes with the brushes that drew it: a brush a cell, as they are.\n const drawn = (rows as { readonly brushes?: readonly { readonly x: number; readonly y: number; readonly shape: number }[] }).brushes;\n if (drawn && options.ink !== \"dark\") return Object.freeze({ width, height, brushes: Object.freeze(drawn.map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }))) });\n // Dark ink: the picture's rectangle lit but for the # tiles, so what is covered is the rest.\n const ink = options.ink === \"dark\" ? Array.from({ length: height }, (_, y) => Array.from({ length: width }, (_, x) => (rows[y][x] === \"#\" ? \".\" : \"#\")).join(\"\")) : rows;\n const brushes = cover(ink, SHAPES).map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }));\n return Object.freeze({ width, height, brushes: Object.freeze(brushes) });\n}\n\n/**\n * A video's frames as brushes, worked out when the script is built: a word a brush (x | y << 8 | size << 16), the\n * frames one after another, and where each one starts — the tables the game reads a frame from. Once a build.\n */\ninterface Film { readonly words: readonly number[]; readonly starts: readonly number[] }\nconst films = new Map();\nfunction film(video: Video): Film {\n const had = films.get(video);\n if (had) return had;\n const words: number[] = [], starts: number[] = [0];\n for (const brushes of cover(video, SHAPES)) {\n for (const b of brushes) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n starts.push(words.length);\n }\n const made = { words, starts };\n films.set(video, made);\n return made;\n}\n\n/**\n * Light the fog for this frame: a disc, a picture or a frame of a video. Tiles count from the map's top left, (0, 0).\n *\n * fog.light(P1, 30, 20, 5); // a disc of size 5 centred on tile (30, 20)\n * fog.light(P1, 60, 40, heart); // a picture (fog.picture), its top left on tile (60, 40)\n * fog.light(P1, 0, 0, badApple, f); // frame f of a video the script imports, its top left on tile (0, 0)\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The tile's column: a disc's centre, a picture's left edge.\n * @param y The tile's row: a disc's centre, a picture's top edge.\n * @param shape A size, 1 (3 tiles wide) to 11 (23 wide) — it may change while the game runs — a picture, or a video.\n * @param frame Of a video, which frame, from 0: it may change while the game runs. Past the end, nothing is lit.\n */\nexport const light = game((player: Player, x: number, y: number, shape: number | Picture | Video, frame: number = 0) => {\n if (typeof shape === \"number\") disc(player, x, y, shape);\n else {\n // The picture's corner in pixels once; each brush is its offset from there (a constant of a picture).\n const px = x * 32 + 16, py = y * 32 + 16;\n if (\"brushes\" in shape) for (const b of shape.brushes) discPx(player, px + b.x * 32, py + b.y * 32, b.size);\n else {\n const { words, starts } = film(shape);\n const end = starts[frame + 1];\n for (let i = starts[frame]; i < end; i++) {\n const w = words[i];\n // (A row's offset in pixels straight from its byte: the same as ((w >> 8) & 255) * 32, and the shift only has\n // the byte's eight bits to look at.)\n discPx(player, px + (w & 255) * 32, py + ((w & 0xff00) >> 3), w >> 16);\n }\n }\n }\n});\n\n/**\n * Play a video in the fog, a frame of it every frame of the game, from its first to its last; resolves when it ends.\n * Inside an async program: `await fog.play(P1, badApple)`. On Fastest a game frame is 42 ms, which is what Import\n * Video makes a video's frames by default; the game runs a little slower when a frame is heavy, and so does the video.\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param video A video the script imports.\n * @param x The column of its left edge, 0 by default.\n * @param y The row of its top edge, 0 by default.\n */\nexport const play = game(async (player: Player, video: Video, x: number = 0, y: number = 0) => {\n // (A while: a for over a length known when the script is built would be unrolled, a copy of the body a frame.)\n let f = 0;\n while (f < video.length) {\n light(player, x, y, video, f);\n await nextFrame();\n f++;\n }\n});\n\n/**\n * How fog.columns() lays its columns out, known when the script is built: `count` columns side by side, each `width`\n * tiles across (3, a brush's width, by default) and up to `height` tiles tall, centred on the middle row. `ink`:\n * \"light\" lights each column (the walls of a raycaster bright, on fog), \"dark\" lights all but the columns (dark walls\n * between a lit ceiling and floor); dark is cheaper when columns fill most of the board, light when they are short.\n */\nexport interface ColumnLayout {\n readonly count: number;\n readonly height: number;\n readonly width?: number;\n readonly ink?: \"light\" | \"dark\";\n /**\n * How the walls are told apart, with fog.columns()'s `faces`. \"outline\", the default: every wall drawn as its edges —\n * its top and bottom, a brush deep, and a column lit whole wherever one face meets another (on the nearer of the\n * two) — so that blocks read as boxes, the look of the raycasters of monochrome screens; with dark ink, the edges are\n * lit lines through dark walls. A few brushes a column. Chosen over the rest when played (2026-10-17).\n *\n * The others shade the faces whose number is odd (a raycaster's other side) and leave the rest whole: \"hollow\" —\n * dark, lit only along its top and bottom edges; \"ribbed\" — hollow and lit across the middle of each half; \"panelled\"\n * — hollow and lit across its quarters; \"line\" / \"lines\" — dark lines a tile thick across it at its middle or its\n * quarters (the finest, and two dozen brushes a column near the eye: for a view with room to spare).\n */\n readonly shading?: \"outline\" | \"lines\" | \"line\" | \"hollow\" | \"ribbed\" | \"panelled\";\n}\n\n/**\n * What fog.columns() reads, worked out once a layout when the script is built: for each level of the drawing that is\n * wider than a column (all the columns, a group of them, the last group) and each depth from 0 to half the height, the\n * brushes that cover a rectangle that wide and that deep exactly — the encoder's covers (cover()), a few large brushes\n * in the middle and small ones at the edges. A brush is a word, dx | dy << 8 | size << 16 from the rectangle's top\n * left; `starts` says where each (level, depth) begins.\n */\ninterface ColumnPlan { readonly words: readonly number[]; readonly starts: readonly number[]; readonly group: number; readonly half: number }\nconst columnPlans = new Map();\nconst COLUMN_GROUP = 6;\nfunction columnPlan(layout: ColumnLayout): ColumnPlan {\n const width = layout.width ?? 3, half = layout.height >> 1, group = Math.min(COLUMN_GROUP, layout.count);\n const key = `${layout.count}:${width}:${half}`;\n const had = columnPlans.get(key);\n if (had) return had;\n const words: number[] = [], starts: number[] = [];\n for (const columns of [layout.count, group, layout.count % group || group]) {\n for (let depth = 0; depth <= half; depth++) {\n starts.push(words.length);\n if (depth === 0) continue;\n // A rectangle shallower than a brush is drawn a brush deep, the rest of it on what the level before lit.\n const rows = Array.from({ length: Math.max(depth, 4) }, () => \"#\".repeat(columns * width));\n for (const b of cover(rows, SHAPES)) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n }\n }\n starts.push(words.length);\n const made = { words, starts, group, half };\n columnPlans.set(key, made);\n return made;\n}\n\n/**\n * One rectangle of fog.columns() wider than a column: the cover at `at` (a level and a depth) drawn twice, the half\n * above the middle and the half below, its top rows `top` and `bottom`, from column `x`.\n */\nconst columnRect = game((player: Player, words: readonly number[], starts: readonly number[], at: number, x: number, top: number, bottom: number) => {\n let i = starts[at];\n const end = starts[at + 1];\n // In pixels once; each brush is its offset (a few bits, a few tests) from there.\n const px = x * 32 + 16, pt = top * 32 + 16, pb = bottom * 32 + 16;\n while (i < end) {\n const w = words[i];\n const dx = (w & 255) * 32, dy = (w & 0xff00) >> 3, size = w >> 16;\n discPx(player, px + dx, pt + dy, size);\n discPx(player, px + dx, pb + dy, size);\n i++;\n }\n});\n\n/**\n * One column's part of fog.columns(), in pixels: brushes (3 × 4) a column of 4 rows apart and the last moved back to\n * end on the edge, twice — from `pt` and from `pb`, the centres of the first brush of each — down a column `k32`\n * pixels deep (32 a row; under 4 rows, a brush deep), centred on `px`. What the smallest brush covers exactly, worked out\n * here rather than read: it is the most common rectangle by far. In pixels because the caller has them, stepped: a\n * product by 32 of a number the game holds is a test a bit, about 0.4 µs, where a step is an add.\n */\nconst columnBarPx = game((player: Player, px: number, pt: number, pb: number, k32: number) => {\n // How far down the last brush is from the first.\n const end = Math.max(k32, 128) - 128;\n let r = 0;\n while (true) {\n centerLocation(SPOT, px, pt, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n centerLocation(SPOT, px, pb, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (r >= end) break;\n const step = Math.min(end - r, 128);\n r += step;\n pt += step;\n pb += step;\n }\n});\n\n/** columnBarPx() in tiles: `k` rows from row `top` down and from row `bottom` down, centred on column `x`. */\nconst columnBar = game((player: Player, x: number, top: number, bottom: number, k: number) => {\n columnBarPx(player, x * 32 + 16, top * 32 + 80, bottom * 32 + 80, k * 32);\n});\n\n/**\n * A shaded column of fog.columns() (ColumnLayout's `shading`): `a` is half its height, `lines` how many lines across\n * each half — 0 hollow, 1 at its middle, 3 at its quarters. A line is a dark row through a lit column (light ink), or\n * a lit band a brush deep through a dark one; a column too short for its lines is drawn plain.\n */\nconst columnShaded = game((player: Player, cx: number, mid: number, a: number, dark: boolean, lines: number) => {\n if (lines <= 0) {\n if (dark) { if (a >= 6) columnBar(player, cx, mid - 4, mid, 4); }\n else if (a < 8) columnBar(player, cx, mid - a, mid, a);\n else {\n // Hollow: the edges. Ribbed (-1) and panelled (-3): bands across each half too, centred on its middle or\n // quarters, where there is room for them between the edges.\n columnBar(player, cx, mid - a, mid + a - 4, 4);\n const ribs = -lines;\n if (ribs > 0 && a >= 6 * (ribs + 1)) {\n let k = 1;\n while (k <= ribs) {\n const at = (a * k) / (ribs + 1);\n columnBar(player, cx, mid - at - 2, mid + at - 2, 4);\n k++;\n }\n }\n }\n } else if (a < 5 * (lines + 1)) {\n if (!dark) columnBar(player, cx, mid - a, mid, a);\n } else {\n // From the middle out: lit up to each line, the line's row dark (light ink); or a lit band on each line (dark ink).\n let from = 0, k = 1;\n while (k <= lines + 1) {\n const to = k > lines ? a : (a * k) / (lines + 1);\n if (dark) { if (k <= lines) columnBar(player, cx, mid - to - 2, mid + to - 2, 4); }\n else columnBar(player, cx, mid - to, mid + from, to - from);\n from = to + 1;\n k++;\n }\n }\n});\n\n/**\n * Light columns for this frame — the walls of a raycaster, a bar chart — each as tall as the program says, centred on\n * the layout's middle row. The covers are worked out when the script is built (see ColumnLayout), so a frame costs a\n * brush for each part of the picture that differs from its neighbours, not one for every few tiles: a wall that fills\n * the board is a few large brushes.\n *\n * const VIEW = { count: 42, height: 96, ink: \"dark\" } as const;\n * fog.columns(P1, 1, 0, VIEW, heights); // heights: one a column, in tiles, the program's\n * fog.columns(P1, 1, 0, VIEW, heights, faces); // faces: which face of which wall each column shows\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of the layout's left edge.\n * @param y The row of its top edge.\n * @param layout How the columns are laid out: known when the script is built.\n * @param heights Each column's height in tiles (0 to the layout's height), an array of the program's.\n * @param faces Which face of which wall each column shows, a number the same for every column of one face — in a\n * raycaster, \\`(mapY * width + mapX) * 2 + side\\` — an array of the program's as long as `heights`: what the\n * layout's `shading` tells walls apart by. Optional: without it, every column is lit whole (a bar chart).\n */\nexport const columns = game((player: Player, x: number, y: number, layout: ColumnLayout, heights: readonly number[], faces?: readonly number[]) => {\n const { words, starts, half, group } = columnPlan(layout);\n const count = layout.count, width = layout.width ?? 3, dark = layout.ink === \"dark\";\n // (Dark lines through a lit column count up; lit bands through a dark one, ribbed and panelled, down.)\n // (Without faces there is nothing to tell apart, and every column is whole.)\n const outline = faces !== undefined && (layout.shading === undefined || layout.shading === \"outline\");\n const lines = layout.shading === \"lines\" ? 3 : layout.shading === \"line\" ? 1 : layout.shading === \"ribbed\" ? -1 : layout.shading === \"hollow\" ? 0 : -3;\n const span = half + 1;\n // Each column's depth from where its lit part starts: the middle row for light ink, the top and bottom for dark.\n // A shaded column of light ink is drawn on its own, after the rest: to the rest it is as if it were not there — and\n // so is every column of a light outline, which is all edges.\n const depth: number[] = new Array(count).fill(0);\n // Half of each column's height, at most half the layout's: worked out once. (Clamped before the shift, the same\n // number: the shift then has the few bits the clamp leaves, where a height from the program could have any.)\n const halves: number[] = new Array(count).fill(0);\n // And in pixels (32 a row), for the bars, which place their brushes in pixels: a small number times 32 is a few tests.\n const halves32: number[] = new Array(count).fill(0);\n let least = half, most = 0;\n // (A light outline is all edges: every depth is 0, nothing to work out.)\n const flat = !dark && outline;\n if (flat) least = 0;\n let i = 0;\n while (i < count) {\n const a = Math.min(Math.max(heights[i], 0), 2 * half + 1) >> 1;\n halves[i] = a;\n halves32[i] = a * 32;\n if (!flat) {\n let d = dark ? half - a : a;\n if (faces !== undefined && !dark && !outline && (faces[i] & 1) != 0) d = 0;\n depth[i] = d;\n if (d < least) least = d;\n if (d > most) most = d;\n }\n i++;\n }\n // A rectangle from depth p, k deep, starts on the rows above and below the middle (light) or below the top and above\n // the bottom (dark); one shallower than 4 is drawn 4 deep, reaching back over what is lit already.\n const mid = y + half;\n // Every column, from depth 0 to the least.\n if (least > 0) {\n const k = Math.max(least, 4);\n if (dark) columnRect(player, words, starts, least, x, y + least - k, y + 2 * half - least);\n else columnRect(player, words, starts, least, x, mid - least, mid + least - k);\n }\n // Each group of columns, from the least to the group's least; then each column, from there to its own. (Nothing,\n // when every column's depth is the least: a light outline's always.)\n let g = most > least ? 0 : count;\n while (g < count) {\n const last = Math.min(g + group, count);\n let gl = half;\n let j = g;\n while (j < last) { if (depth[j] < gl) gl = depth[j]; j++; }\n const level = last - g === group ? 1 : 2;\n if (gl > least) {\n const k = gl - least, kk = Math.max(k, 4);\n if (dark) columnRect(player, words, starts, level * span + k, x + g * width, y + gl - kk, y + 2 * half - gl);\n else columnRect(player, words, starts, level * span + k, x + g * width, mid - gl, mid + gl - kk);\n }\n j = g;\n while (j < last) {\n const k = depth[j] - gl;\n if (k > 0) {\n const kk = Math.max(k, 4), cx = x + j * width + 1;\n if (dark) columnBar(player, cx, y + depth[j] - kk, y + 2 * half - depth[j], k);\n else columnBar(player, cx, mid - depth[j], mid + depth[j] - kk, k);\n }\n j++;\n }\n g = last;\n }\n if (outline) {\n // Where one face meets another, the nearer (taller) of the two columns is an edge.\n const edge: number[] = new Array(count).fill(0);\n let face = faces[0], tall = heights[0];\n i = 1;\n while (i < count) {\n const f = faces[i], h = heights[i];\n if (f != face) { if (h >= tall) edge[i] = 1; else edge[i - 1] = 1; }\n face = f;\n tall = h;\n i++;\n }\n // The bars in pixels: a column's centre stepped across, the middle row's worked out once.\n const mid80 = mid * 32 + 80;\n let px = (x + 1) * 32 + 16;\n i = 0;\n while (i < count) {\n const a = halves[i], a32 = halves32[i];\n if (dark) { if (edge[i] != 0 && a >= 2) columnBarPx(player, px, mid80 - a32, mid80, a32); }\n else if (a > 0) {\n if (edge[i] != 0 || a < 8) columnBarPx(player, px, mid80 - a32, mid80, a32);\n else columnBarPx(player, px, mid80 - a32, mid80 + a32 - 128, 128);\n }\n px += width * 32;\n i++;\n }\n } else if (faces !== undefined) {\n i = 0;\n while (i < count) {\n if ((faces[i] & 1) != 0) columnShaded(player, x + i * width + 1, mid, halves[i], dark, lines);\n i++;\n }\n }\n});\n\n/**\n * Keep what was lit this frame on the board for `n` frames, and wait them out: \\`await fog.show(2)\\` in place of\n * \\`await nextFrame()\\` draws every other frame at half the cost. StarCraft: Remastered redraws the fog on the minimap\n * every other frame (measured in two played recordings, 2026-10-17), so a picture drawn every other frame looks the\n * same there as one drawn every frame. The board is wiped at the start of the frame after them, ready for the next.\n *\n * @param n How many frames, 1 to 24, known when the script is built.\n */\nexport const show = game(async (n: number) => {\n memory.vision.countdown = n;\n await sleep(frames(n));\n});\n\n/** Everything above as one name: import { fog } from \"trigscript/fog\"; fog.light(P1, x, y, 3). */\nexport const fog = { light, rect, columns, show, play, reveal, picture, SHAPES };\n\n/** The longest fog.show() keeps a picture: the countdown the game sets itself after a wipe is longer than this. */\nconst SHOW_MOST = 24;\n\n// The canvas: every brush's sight set, every frame, and the board wiped on the next — for as long as the game runs —\n// unless a program asked for the picture to stay (fog.show), when the countdown is that program's to run down.\nprogram(() => {\n while (true) {\n for (let s = 1; s <= 11; s++) stats(BRUSHES[s - 1]).sight = s;\n const left = memory.vision.countdown;\n if (left == 0 || left > SHOW_MOST) memory.vision.countdown = 1;\n sleep(frames(1));\n }\n});\n", "math": "/**\n * Numbers for motion and play: the standard library's \"trigscript/math\" (TrigScript 4).\n *\n * import { Vec, lerp, easeOutQuad, distance, angleTo, approach, wrap } from \"trigscript/math\";\n *\n * const t = fixed(frame) / 48; // 0 to 1 over two seconds\n * const x = lerp(fromX, toX, easeOutQuad(t)); // eased from one place to another\n * const v = Vec.fromAngle(angleTo(x, y, tx, ty), fixed(4));\n * pos = pos.add(v);\n *\n * Fractions are the language's fixed numbers (16.16: four decimal places or so, from about −32 768 to 32 767): a\n * number becomes one when a fraction is stored into it, or written `fixed(…)`. Angles are radians, as JavaScript's are.\n * Whole numbers stay whole where they can — `distanceSq`, `manhattan`, `wrap`, `sign` — and cost less.\n */\n\n/** π, and a whole turn. */\nexport const PI = Math.PI;\nexport const TAU = Math.PI * 2;\n\n/** From a to b by t: a at 0, b at 1, between them in between (t outside 0 … 1 goes past). */\nexport function lerp(a: fixed, b: fixed, t: fixed): fixed {\n return a + (b - a) * t;\n}\n\n/** Where v is from a to b, as lerp's t: 0 at a, 1 at b. */\nexport function inverseLerp(a: fixed, b: fixed, v: fixed): fixed {\n return b === a ? fixed(0) : (v - a) / (b - a);\n}\n\n/** v from the range a1 … b1 into a2 … b2. */\nexport function remap(v: fixed, a1: fixed, b1: fixed, a2: fixed, b2: fixed): fixed {\n return lerp(a2, b2, inverseLerp(a1, b1, v));\n}\n\n/** t kept inside 0 … 1. */\nexport function clamp01(t: fixed): fixed {\n return t < 0 ? fixed(0) : t > 1 ? fixed(1) : t;\n}\n\n/** From `current` towards `target` by at most `step`, never past it: a value that follows another at a speed. */\nexport function approach(current: number, target: number, step: number): number {\n if (current < target) return current + step > target ? target : current + step;\n return current - step < target ? target : current - step;\n}\n\n/** n into 0 … size − 1, going round: wrap(-1, 10) is 9, wrap(12, 10) is 2. */\nexport function wrap(n: number, size: number): number {\n return ((n % size) + size) % size;\n}\n\n/** −1, 0 or 1, by whether n is below, at or above zero. */\nexport function sign(n: number): number {\n return n > 0 ? 1 : n < 0 ? -1 : 0;\n}\n\n/** The distance from one point to another, as the crow flies. */\nexport function distance(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.hypot(x2 - x1, y2 - y1);\n}\n\n/** The distance squared: whole, and cheaper — compare it with a range squared. */\nexport function distanceSq(x1: number, y1: number, x2: number, y2: number): number {\n return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n}\n\n/** The distance along the axes, |dx| + |dy|: what the game's own \"nearest\" goes by. */\nexport function manhattan(x1: number, y1: number, x2: number, y2: number): number {\n return Math.abs(x2 - x1) + Math.abs(y2 - y1);\n}\n\n/** The angle from one point to another, in radians from −π to π: 0 is to the right (east), π / 2 down (south, y grows down). */\nexport function angleTo(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.atan2(y2 - y1, x2 - x1);\n}\n\n/** Degrees as radians. */\nexport function radians(degrees: fixed): fixed {\n return (degrees * PI) / 180;\n}\n\n/** Radians as degrees. */\nexport function degrees(radians: fixed): fixed {\n return (radians * 180) / PI;\n}\n\n/* Easing: t from 0 to 1, how far along a motion is at that point of its time — slow then fast, fast then slow, … */\n\n/** Slow at the start. */\nexport function easeInQuad(t: fixed): fixed {\n return t * t;\n}\n\n/** Slow at the end. */\nexport function easeOutQuad(t: fixed): fixed {\n return t * (2 - t);\n}\n\n/** Slow at both ends. */\nexport function easeInOutQuad(t: fixed): fixed {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n}\n\n/** Slower at the start than easeInQuad. */\nexport function easeInCubic(t: fixed): fixed {\n return t * t * t;\n}\n\n/** Slower at the end than easeOutQuad. */\nexport function easeOutCubic(t: fixed): fixed {\n const u = t - 1;\n return u * u * u + 1;\n}\n\n/** Goes a little past the end and comes back. */\nexport function easeOutBack(t: fixed): fixed {\n const u = t - 1;\n return 1 + 2.70158 * u * u * u + 1.70158 * u * u;\n}\n\n/** Slow at both ends, smoothly (Hermite: 3t² − 2t³). */\nexport function smoothstep(t: fixed): fixed {\n return t * t * (3 - 2 * t);\n}\n\n/**\n * A point, or a direction and a length: two fixed numbers. Each operation gives a new Vec.\n *\n * let pos = new Vec(fixed(x), fixed(y));\n * const toward = new Vec(fixed(tx), fixed(ty)).sub(pos).normalized().scale(fixed(3));\n * pos = pos.add(toward);\n */\nexport class Vec {\n x: fixed;\n y: fixed;\n\n constructor(x: fixed, y: fixed) {\n this.x = x;\n this.y = y;\n }\n\n /** A direction `length` long at `angle` radians (0 to the right, π / 2 down). */\n static fromAngle(angle: fixed, length: fixed): Vec {\n return new Vec(Math.cos(angle) * length, Math.sin(angle) * length);\n }\n\n add(o: Vec): Vec {\n return new Vec(this.x + o.x, this.y + o.y);\n }\n\n sub(o: Vec): Vec {\n return new Vec(this.x - o.x, this.y - o.y);\n }\n\n scale(k: fixed): Vec {\n return new Vec(this.x * k, this.y * k);\n }\n\n dot(o: Vec): fixed {\n return this.x * o.x + this.y * o.y;\n }\n\n /** How long it is. */\n length(): fixed {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n }\n\n /** The same direction, 1 long (or none, for none). */\n normalized(): Vec {\n const l = this.length();\n const k: fixed = l === 0 ? fixed(0) : 1 / l;\n return new Vec(this.x * k, this.y * k);\n }\n\n /** Its angle, in radians from −π to π. */\n angle(): fixed {\n return Math.atan2(this.y, this.x);\n }\n\n /** Turned by `angle` radians (clockwise on the map, where y grows down). */\n rotate(angle: fixed): Vec {\n const c = Math.cos(angle);\n const s = Math.sin(angle);\n return new Vec(this.x * c - this.y * s, this.x * s + this.y * c);\n }\n\n /** How far it is from another point. */\n distanceTo(o: Vec): fixed {\n return this.sub(o).length();\n }\n\n /** From this towards another by t (0 here, 1 there). */\n lerp(o: Vec, t: fixed): Vec {\n return new Vec(this.x + (o.x - this.x) * t, this.y + (o.y - this.y) * t);\n }\n}\n", - "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false, release = releaseOf(z);\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one — held by the\n // pedal or still dying away after it was let go (a string struck again starts again).\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) {\n const next = order[j].at;\n if (next < off) { off = next; stolen = true; release = 0.12; }\n else if (next < off + release) release = Math.max(0.1, next - off + 0.1);\n break;\n }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n if (releases) for (const [down, up] of pedal) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n};\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n for (const { part } of inside.parts) {\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) throw new Error(\"render(): the performance plays no notes.\");\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", + "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false, release = releaseOf(z);\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one — held by the\n // pedal or still dying away after it was let go (a string struck again starts again).\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) {\n const next = order[j].at;\n if (next < off) { off = next; stolen = true; release = 0.12; }\n else if (next < off + release) release = Math.max(0.1, next - off + 0.1);\n break;\n }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n // (A pedal down before 0 was put down, and comes up, in the excerpt before this one: no sound of it here.)\n if (releases) for (const [down, up] of pedal) if (down >= 0) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n};\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/**\n * The part of a performance from bar `from` up to bar `to` (not included; to its end when left out), bars as\n * `performance.bars` counts them, as a performance from 0 of its own: the notes struck in it, their times from its\n * start, and the pedal — down already when the pedal went down before it (its sound is the excerpt's before), held to\n * where it comes up. Render a long piece a section at a time, each with its room, its tail ringing on under the next\n * when the sections are added up at their `at`s: `music.render(music.excerpt(take, 44, 60), { reverb: ROOM })`.\n */\nexport function excerpt(p: Performance, from: number, to?: number): Performance & { readonly at: number } {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"excerpt() takes a performance made by music.perform.\");\n const last = p.bars.length - 1;\n if (!(Number.isInteger(from) && from >= 0 && from <= last)) throw new Error(`excerpt() starts on a bar, 0 to ${last}, not ${from}.`);\n if (to !== undefined && !(Number.isInteger(to) && to > from && to <= last)) throw new Error(`excerpt() ends on a bar after ${from}, at most ${last}, not ${to}.`);\n const a = p.bars[from], b = to === undefined ? Infinity : p.bars[to];\n const notes = p.notes.filter((n) => n.at >= a - 1e-9 && n.at < b - 1e-9).map((n) => Object.freeze({ ...n, at: n.at - a, end: n.end - a, frame: Math.round((n.at - a) / FRAME) }));\n const clip = (list: readonly (readonly [number, number])[]) => list.filter(([d, u]) => u > a && d < b).map(([d, u]) => [d - a, u - a] as [number, number]);\n const pedal = new Map();\n for (const [inst, list] of inside.pedal) pedal.set(inst, clip(list));\n const made = Object.freeze({\n kind: \"performance\" as const, at: a, notes: Object.freeze(notes), pedal: Object.freeze(clip(p.pedal).map((x) => Object.freeze(x))),\n bars: Object.freeze(p.bars.slice(from, to === undefined ? undefined : to + 1).map((t) => t - a)), parts: p.parts,\n seconds: Math.max(0, ...notes.map((n) => n.end)),\n });\n performances.set(made, { parts: inside.parts, pedal });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n for (const { part } of inside.parts) {\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) throw new Error(\"render(): the performance plays no notes.\");\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, excerpt, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", "random": "/**\n * Chance: the standard library's \"trigscript/random\" (TrigScript 4).\n *\n * import { chance, range, pick, shuffle, weighted, Random } from \"trigscript/random\";\n *\n * if (chance(25)) dropLoot(); // one time in four\n * const lane = range(1, 3); // 1, 2 or 3\n * const boss = pick(BOSSES); // any one of a list\n * shuffle(order); // an array of the program, in place\n * const tier = weighted([70, 25, 5]); // 0 most of the time, 2 rarely\n *\n * const rng = new Random(seed); // the same numbers every time for the same seed\n * const x = rng.range(0, 63);\n *\n * The functions use the game's own random numbers, which every player's game draws alike, so nothing goes out of step\n * in a game of several players. `Random` is a generator of your own (xorshift), seeded: the same seed gives the same\n * numbers, game after game — a level made from a seed, a save code that holds one.\n */\nimport { random } from \"trigscript\";\n\n/** True `percent` times in a hundred (25: one time in four). */\nexport function chance(percent: number): boolean {\n return random(100) < percent;\n}\n\n/** A whole number from `min` to `max`, both included. */\nexport function range(min: number, max: number): number {\n return min + random(max - min + 1);\n}\n\n/** The total of `count` dice of `sides` sides each (3, 6: from 3 to 18). */\nexport function dice(count: number, sides: number): number {\n let total = 0;\n let i = 0;\n while (i < count) { total += 1 + random(sides); i++; }\n return total;\n}\n\n/** One of a list, any one alike; a list the script has, or an array of the program (the first's 0 when it is empty). */\nexport function pick(items: readonly T[]): T {\n return items[random(items.length)];\n}\n\n/** The place of one of the weights, each as likely as its share of their total: [70, 25, 5] gives 0 most of the time. */\nexport function weighted(weights: readonly number[]): number {\n let total = 0;\n for (const w of weights) total += w;\n let roll = random(total);\n let i = 0;\n while (i < weights.length) {\n if (roll < weights[i]) return i;\n roll -= weights[i];\n i++;\n }\n return weights.length - 1;\n}\n\n/** An array of the program in a random order, in place (Fisher–Yates: every order alike). */\nexport function shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = random(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n}\n\n/**\n * A generator of random numbers of your own, seeded: the same seed gives the same numbers, in the game and when the\n * script is tested. Make it in the program (`const rng = new Random(1234)`).\n */\nexport class Random {\n state: number;\n\n /** Seeded with any whole number (0 is taken as 1). */\n constructor(seed: number) {\n this.state = seed === 0 ? 1 : seed;\n }\n\n /** The next number, from 0 to 2 147 483 647. */\n next(): number {\n let x = this.state;\n x ^= x << 13;\n x ^= x >>> 17;\n x ^= x << 5;\n this.state = x;\n return x & 0x7fffffff;\n }\n\n /** A whole number from 0 to n − 1. */\n int(n: number): number {\n return this.next() % n;\n }\n\n /** A whole number from `min` to `max`, both included. */\n range(min: number, max: number): number {\n return min + this.int(max - min + 1);\n }\n\n /** True `percent` times in a hundred. */\n chance(percent: number): boolean {\n return this.int(100) < percent;\n }\n\n /** One of a list, any one alike. */\n pick(items: readonly T[]): T {\n return items[this.int(items.length)];\n }\n\n /** An array of the program in a random order, in place. */\n shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = this.int(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n }\n}\n", "screen": "/**\n * Pixel screens: the standard library's \"trigscript/screen\" (TrigScript 4).\n *\n * import { Screen, ScreenView, sprite } from \"trigscript/screen\";\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n *\n * program(async () => {\n * const screen = new Screen(4, 4, 24, 16); // 24 × 16 pixels, its corner on tile (4, 4)\n * let x = 10;\n * while (true) {\n * screen.clear();\n * screen.rect(0, 15, 24, 1, 5); // the ground, in colour 5\n * screen.blit(SHIP, x, 12);\n * screen.number(score, 1, 1, 2); // digits 3 × 5 pixels, in colour 2\n * screen.present(); // on the map, and so on the minimap (screen.reveal(P1) once first)\n * await nextFrame();\n * }\n * });\n *\n * A screen is a grid of pixels, each 0 (empty) or a colour from 1 to 7; drawing changes the grid, and `present()`\n * shows it: a pixel is a unit on the map, owned by the player whose colour it is, so the minimap shows the picture —\n * neighbouring pixels of one colour join into a solid block there. Only the pixels that changed since the last\n * `present()` are made or taken away, and only the pixels drawn since are looked at, so a still picture costs nothing to\n * show. Draw through the methods (`set`, `clear`, `rect`, …): a pixel written into `pixels` directly is not seen. The same grid can be shown in a\n * player's text lines too, as squares (`ScreenView` in a `ui.lines` view): one game, two screens, as the Tetris probe has it.\n *\n * A player sees the pixels only where they have vision: `screen.reveal(P1)` once gives them Map Revealers over it.\n *\n * Two looks (the constructor's last argument): \"dots\", Overlords, which fly — the minimap draws each as a dot with a gap\n * round it, the screen may be over Space; and \"solid\", Pylons, which the minimap draws as their whole two-tile\n * footprint, so pixels side by side are one block — on buildable ground (probes/lib/screen-map.mts --ground).\n *\n * What the map needs, found playing the unit-pixel probe in StarCraft: Remastered (2026-10-16): the owners of the\n * pixels (P3, P4, P5, P1, P6, P7, P8 below; their colours are theirs on the map, so give them the colours of TEXT_COLORS) must not\n * be computers — a computer moves its own units — and Remastered will not start a game without a computer, so one slot\n * (P2 here) is a computer that owns no pixel. A pixel is an Overlord, which sits on any ground and on nothing else; keep\n * the screen's tiles clear of buildings. A Pylon needs buildable ground, and none of the map's own units in the way. About 80 pixels made and taken away in a frame did not slow the game.\n */\nimport { centerLocation, createUnit, removeUnitAt, reserveLocation, textColors, units, P1, P3, P4, P5, P6, P7, P8, type Player } from \"trigscript\";\n\n/**\n * Whose units show colours 1 to 7 on the map, in the order of TEXT_COLORS: give each player that colour in the map\n * (cyan, yellow, purple, green, red, blue, orange). Green is P1's — your own units are green on the minimap anyway.\n * Not computers.\n */\nexport const OWNERS: readonly Player[] = [P3, P4, P5, P1, P6, P7, P8];\n/** The same colours in the text lines (`ScreenView`), 0 an empty square: cyan, yellow, purple, green, red, blue, orange. */\nexport const TEXT_COLORS: readonly number[] = [0, textColors.cyan, textColors.yellow, textColors.purple, textColors.green, textColors.red, textColors.blue, textColors.orange];\n\n/** Where each pixel's unit is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"screen: where each pixel is made\");\n\n/** A picture known when the script is built, to `blit` onto a screen: its size, and its pixels a row at a time (0 is see-through). */\nexport interface Sprite { readonly width: number; readonly height: number; readonly cells: readonly number[] }\n\n/**\n * A sprite from rows of text, when the script is built: \"1\" … \"7\" a pixel of that colour, anything else see-through.\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n */\nexport function sprite(rows: readonly string[]): Sprite {\n const width = Math.max(0, ...rows.map((r) => r.length));\n const cells: number[] = [];\n for (const row of rows) for (let x = 0; x < width; x++) { const c = Number(row[x]); cells.push(c >= 1 && c <= 7 ? c : 0); }\n return { width, height: rows.length, cells };\n}\n\n/** The digits 0 to 9, three pixels wide and five high, for `number()`: each fifteen pixels, a row at a time. */\nconst DIGITS: readonly number[] = [\n \"111101101101111\", \"010110010010111\", \"111001111100111\", \"111001111001111\", \"101101111001001\",\n \"111100111001111\", \"111100111101111\", \"111001001010010\", \"111101111101111\", \"111101111001111\",\n].flatMap((d) => d.split(\"\").map(Number));\n\n/** The most pixels a screen has: 32 × 32 at two tiles a pixel covers a 64 × 64 map, 64 × 32 half of a 128 × 128 one. */\nexport const MAX_PIXELS = 2048;\n\nexport class Screen {\n /** The picture being drawn: a colour a pixel, a row at a time (the first width × height of them). */\n pixels: number[] = new Array(MAX_PIXELS).fill(0);\n /** What the map shows now: the picture as it was at the last `present()`. */\n shown: number[] = new Array(MAX_PIXELS).fill(0);\n /** The pixels drawn a colour they were not since the last `present()`, in order: each one's place and its x and y. */\n drawnAt: number[] = new Array(MAX_PIXELS).fill(0);\n drawnX: number[] = new Array(MAX_PIXELS).fill(0);\n drawnY: number[] = new Array(MAX_PIXELS).fill(0);\n drawn = 0;\n /** More drawn than the list holds: `present()` looks at every pixel instead. */\n overflow = false;\n x: number;\n y: number;\n width: number;\n height: number;\n cell: number;\n /** The unit a pixel is: an Overlord (\"dots\"), or a Pylon (\"solid\"). */\n unit = 0;\n\n /**\n * A screen `width` × `height` pixels (MAX_PIXELS at most), its top left corner on tile (x, y) of the map, a pixel two\n * tiles across.\n * @param look \"dots\" (the default): a pixel is an Overlord, which the minimap draws as a dot, a gap round it — it flies,\n * so the screen may be over anything, Space too. \"solid\": a pixel is a Pylon, which the minimap draws as its whole\n * footprint, two tiles square, so pixels side by side are one block — it needs buildable ground under the screen,\n * and gives its owner Protoss supply. (Overlords a tile apart do not fit: the game will not place most of them.)\n */\n constructor(x: number, y: number, width: number, height: number, look: \"dots\" | \"solid\" = \"dots\") {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.cell = 64;\n this.unit = look === \"solid\" ? units.ProtossPylon : units.ZergOverlord;\n }\n\n /** Every pixel the colour (0, empty, unless it says). */\n clear(color: number = 0) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.put(i, x, y, color); i++; x++; }\n y++;\n }\n }\n\n /** One pixel; nothing happens outside the screen. */\n set(x: number, y: number, color: number) {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) this.put(y * this.width + x, x, y, color);\n }\n\n /** A pixel written, and listed for `present()` when its colour changed. */\n private put(i: number, x: number, y: number, color: number) {\n if (this.pixels[i] === color) return;\n this.pixels[i] = color;\n if (this.drawn < MAX_PIXELS) {\n this.drawnAt[this.drawn] = i;\n this.drawnX[this.drawn] = x;\n this.drawnY[this.drawn] = y;\n this.drawn++;\n } else this.overflow = true;\n }\n\n /** The colour of a pixel; 0 outside the screen. */\n get(x: number, y: number): number {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) return this.pixels[y * this.width + x];\n return 0;\n }\n\n /** A filled rectangle, its top left at (x, y); what is outside the screen is left out. */\n rect(x: number, y: number, width: number, height: number, color: number) {\n let j = 0;\n while (j < height) {\n let i = 0;\n while (i < width) { this.set(x + i, y + j, color); i++; }\n j++;\n }\n }\n\n /** A line from (x0, y0) to (x1, y1), both ends drawn. */\n line(x0: number, y0: number, x1: number, y1: number, color: number) {\n const dx = Math.abs(x1 - x0);\n const dy = -Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx + dy;\n let x = x0;\n let y = y0;\n while (true) {\n this.set(x, y, color);\n if (x === x1 && y === y1) break;\n const e2 = 2 * err;\n if (e2 >= dy) { err += dy; x += sx; }\n if (e2 <= dx) { err += dx; y += sy; }\n }\n }\n\n /** A sprite with its top left at (x, y): its see-through pixels leave what is under them. */\n blit(s: Sprite, x: number, y: number) {\n let k = 0;\n let j = 0;\n while (j < s.height) {\n let i = 0;\n while (i < s.width) {\n const c = s.cells[k];\n if (c !== 0) this.set(x + i, y + j, c);\n k++;\n i++;\n }\n j++;\n }\n }\n\n /** A whole number's digits, 3 × 5 pixels each with a pixel between, its top left at (x, y): a score on the minimap. */\n number(n: number, x: number, y: number, color: number) {\n let rest = n < 0 ? -n : n;\n let count = 1;\n let probe = rest;\n while (probe >= 10) { probe = Math.floor(probe / 10); count++; }\n let place = x + (count - 1) * 4;\n while (true) {\n const d = rest % 10;\n let k = 0;\n while (k < 15) {\n if (DIGITS[d * 15 + k] === 1) this.set(place + (k % 3), y + Math.floor(k / 3), color);\n k++;\n }\n rest = Math.floor(rest / 10);\n place -= 4;\n if (rest === 0) break;\n }\n }\n\n /**\n * Let a player see the screen: Map Revealers of theirs over it, for the rest of the game. Without them its pixels,\n * owned by other players, are hidden by the fog of war — on the map and on the minimap. Once, before the first\n * `present()`.\n * @param player Who sees it: P1 … P8, known when the script is built.\n */\n reveal(player: Player) {\n // A Map Revealer sees ten tiles round; one every six tiles leaves no gap.\n const right = this.x * 32 + this.width * this.cell;\n const bottom = this.y * 32 + this.height * this.cell;\n let py = this.y * 32 + 96;\n while (py < bottom + 96) {\n let px = this.x * 32 + 96;\n while (px < right + 96) {\n centerLocation(SPOT, px, py, 32, 32);\n createUnit(player, units.MapRevealer, 1, SPOT);\n px += 192;\n }\n py += 192;\n }\n }\n\n /**\n * The picture on the map: each pixel that changed since the last time taken away and made again in its colour. Only\n * the pixels drawn since are looked at (one drawn and drawn back is passed over), unless more were drawn than the list\n * holds.\n */\n present() {\n if (this.overflow) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.show(i, x, y); i++; x++; }\n y++;\n }\n this.overflow = false;\n } else {\n for (let k = 0; k < this.drawn; k++) this.show(this.drawnAt[k], this.drawnX[k], this.drawnY[k]);\n }\n this.drawn = 0;\n }\n\n /** One pixel on the map as it is in the picture, when it is not already. */\n private show(i: number, x: number, y: number) {\n const now = this.pixels[i];\n const was = this.shown[i];\n if (now === was) return;\n const half = this.cell >> 1;\n centerLocation(SPOT, this.x * 32 + x * this.cell + half, this.y * 32 + y * this.cell + half, 32, 32);\n OWNERS.forEach((owner, k) => { if (was === k + 1) removeUnitAt(owner, this.unit, 1, SPOT); });\n OWNERS.forEach((owner, k) => { if (now === k + 1) createUnit(owner, this.unit, 1, SPOT); });\n this.shown[i] = now;\n }\n}\n\n/**\n * A screen in the text lines, a square a pixel — filled in its colour, or empty — a line a row. For a `ui.lines` view:\n * ``, the screen's size known when the script is built. Eleven lines\n * show at once, sixty squares across.\n */\nexport function ScreenView({ screen, width, height }: { screen: Screen; width: number; height: number }) {\n return <>{UP_TO_60.map((y) => y < height && {UP_TO_60.map((x) => x < width && )})};\n}\n\n/** 0 … 59: the places a view's rows and columns are counted over, the ones past its size left out when the script is built. */\nconst UP_TO_60: readonly number[] = Array.from({ length: 60 }, (_, i) => i);\n", "signals": "/**\n * Events of your own: the standard library's \"trigscript/signals\" (TrigScript 4).\n *\n * import { Signal } from \"trigscript/signals\";\n *\n * const waveCleared = new Signal();\n *\n * program(async () => {\n * waveCleared.on((wave) => { setResources(P1, \"add\", 100 * wave, \"ore\"); }); // braces: a handler gives back no action\n * waveCleared.once((wave) => print(`First wave down!`));\n * const id = waveCleared.on((wave) => print(`Wave ${wave} cleared`));\n * …\n * waveCleared.emit(3); // every handler, in the order they were added\n * waveCleared.off(id);\n * });\n *\n * A signal lets one part of a map say that something happened without knowing who listens: the shop, the score and the\n * music each add a handler, and the wave code only emits. What it carries is one value of the type it is made with —\n * a number, a boolean, a text or a unit (`new Signal()`). Its handlers are functions kept as values: they may use\n * what the block they were written in has, and they run to their end, one after another, within the frame.\n *\n * Make a signal inside the program that uses it (`const s = new Signal()` at its top): a signal is variables\n * of a program, as anything a program writes is.\n */\n\nexport class Signal {\n /** The handlers, by the number `on` gave; one taken off is undefined, and its place is given to the next one added. */\n handlers: (((value: T) => void) | undefined)[] = [];\n /** Which handlers go once they have run once. */\n onceOnly: boolean[] = [];\n\n /**\n * Add a handler: it runs at every `emit`, handed the value.\n * @returns Its number, for `off`.\n */\n on(handler: (value: T) => void): number {\n return this.add(handler, false);\n }\n\n /** Add a handler that runs at the next `emit` only. @returns Its number, for `off` before then. */\n once(handler: (value: T) => void): number {\n return this.add(handler, true);\n }\n\n /** Take a handler off, by the number `on` or `once` gave. */\n off(id: number) {\n if (id >= 0 && id < this.handlers.length) this.handlers[id] = undefined;\n }\n\n /** Run every handler, in the order they were added, each handed `value`. */\n emit(value: T) {\n let i = 0;\n while (i < this.handlers.length) {\n const h = this.handlers[i];\n if (h) {\n if (this.onceOnly[i]) this.handlers[i] = undefined;\n h(value);\n }\n i++;\n }\n }\n\n /** How many handlers it has. */\n count(): number {\n let n = 0;\n for (const h of this.handlers) if (h) n++;\n return n;\n }\n\n /** Take every handler off. */\n clear() {\n let i = 0;\n while (i < this.handlers.length) { this.handlers[i] = undefined; i++; }\n }\n\n private add(handler: (value: T) => void, once: boolean): number {\n // A place one was taken off from, or a new one at the end.\n let i = 0;\n while (i < this.handlers.length) {\n if (!this.handlers[i]) {\n this.handlers[i] = handler;\n this.onceOnly[i] = once;\n return i;\n }\n i++;\n }\n this.handlers.push(handler);\n this.onceOnly.push(once);\n return this.handlers.length - 1;\n }\n}\n", diff --git a/compiler/sound.ts b/compiler/sound.ts index 24a1c9b..0e97531 100644 --- a/compiler/sound.ts +++ b/compiler/sound.ts @@ -600,7 +600,8 @@ function lazyClip(rate: number, frames: number, channels: 1 | 2, compute: () => const pedal = options?.pedal, amount = options?.amount ?? 0.25, decay = options?.decay ?? 3; if (!Array.isArray(pedal)) throw new Error("resonance() takes the pedal: { pedal: [[down, up], …] } in seconds."); const ps = pedal.map((p, k) => { - if (!Array.isArray(p) || p.length !== 2 || !(num(p[0], "a pedal's down") >= 0) || !(num(p[1], "a pedal's up") >= p[0])) throw new Error(`resonance()'s pedal ${k + 1} is [down, up], seconds, up after down.`); + // (A down before 0: the pedal was down already when the clip begins.) + if (!Array.isArray(p) || p.length !== 2 || !Number.isFinite(num(p[0], "a pedal's down")) || !(num(p[1], "a pedal's up") >= p[0])) throw new Error(`resonance()'s pedal ${k + 1} is [down, up], seconds, up after down.`); return [p[0], p[1]] as [number, number]; }); if (!(num(amount, "resonance()'s amount") >= 0 && amount <= 2)) throw new RangeError(`resonance()'s amount is 0 to 2, not ${amount}.`); @@ -744,9 +745,11 @@ export function mixdown(parts: unknown, seconds?: unknown, rate?: number): Clip * samples too, however loud each is: what a limiter does for a mix, for sounds the game adds up itself. Never turned * up. A clip given several times is one clip back, and one file in the map. `over`: clips that may play on top, each at * any of its times (a stinger on any bar line) — the gain leaves room for them too, and they come back after the parts, - * turned down with them. The gain is worked out when a build needs the samples, from the whole mix. + * turned down with them. The gain is worked out when a build needs the samples, from the whole mix. `lufs`: instead, the + * one gain — up or down — that brings what they add up to to that loudness (`Clip.lufs`): sections of a piece made + * apart, kept as loud against one another as they were played. */ -export function together(parts: unknown, options?: { readonly peak?: number; readonly over?: readonly { readonly clip: Clip; readonly at: readonly number[] }[] }): Clip[] { +export function together(parts: unknown, options?: { readonly peak?: number; readonly lufs?: number; readonly over?: readonly { readonly clip: Clip; readonly at: readonly number[] }[] }): Clip[] { if (!Array.isArray(parts) || parts.length === 0) throw new Error("together() takes { clip, at } parts, one at least."); const list = parts.map((p, k) => { const c = (p as { clip?: unknown })?.clip, at = (p as { at?: unknown })?.at ?? 0; @@ -760,9 +763,15 @@ export function together(parts: unknown, options?: { readonly peak?: number; rea if (!isClip(o?.clip) || !Array.isArray(o.at)) throw new Error(`together()'s over ${k + 1} is { clip, at: [seconds, …] }.`); return { clip: o.clip, at: o.at.map((t) => num(t, "an over's time")) }; }); - const whole = recipe("together", [list.map((p) => [p.clip, p.at]), peak, over.map((o) => [o.clip, o.at])]); + const lufs = options?.lufs; + if (lufs !== undefined && !(num(lufs, "together()'s lufs") >= -70 && lufs <= 0)) throw new RangeError(`together()'s lufs is −70 to 0, not ${lufs}.`); + const whole = recipe("together", [list.map((p) => [p.clip, p.at]), peak, over.map((o) => [o.clip, o.at]), ...(lufs === undefined ? [] : [lufs])]); let gain: number | undefined; const turn = () => { + if (gain === undefined && lufs !== undefined) { + const now = mixdown(list).lufs; + gain = Number.isFinite(now) ? 10 ** ((lufs - now) / 20) : 1; + } if (gain === undefined) { const sum = samplesOf(mixdown(list)); let top = 0; diff --git a/ledger/sounds/music-perform.ts b/ledger/sounds/music-perform.ts index e70c762..147c58a 100644 --- a/ledger/sounds/music-perform.ts +++ b/ledger/sounds/music-perform.ts @@ -1,6 +1,7 @@ // ledger: step 5, takes // A performance (`music.perform`): notes at their own times — lengths, dynamics, the pedal, a tempo that slows — each -// struck when its time comes, rendered into one clip; `lufs` read and `loudness` set when the script is built. +// struck when its time comes, rendered into one clip, and from its second bar on apart; `lufs` read and `loudness` set +// when the script is built. import { music } from "trigscript/music"; const keys = music.synth({ wave: "triangle", volume: 0.3 }); const take = music.perform({ meter: "3/8", bpm: 120, pickup: "1/8", tempo: [[1, 120], [2, 96]] }, { @@ -8,7 +9,10 @@ const take = music.perform({ meter: "3/8", bpm: 120, pickup: "1/8", tempo: [[1, left: { instrument: keys, notes: ["r/8", "r/4.", "ped A2/16 E3 A3 r/8. *"] }, }); const mix = music.render(take, { loudness: -18 }); +// The second bar on, rendered apart (`music.excerpt`), as a long piece is a section at a time. +const rest = music.render(music.excerpt(take, 2)); const rung = mix.resonance({ pedal: take.pedal }); program(async () => { playWav(mix.lufs < -17 ? rung : mix, 0); + playWav(rest, 0); }); diff --git a/stdlib/music.ts b/stdlib/music.ts index 1f9f50c..e88d3d3 100644 --- a/stdlib/music.ts +++ b/stdlib/music.ts @@ -365,7 +365,8 @@ export function sampled(set: Samples, options: SampledOptions = {}): Instrument parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at }); if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); } }); - if (releases) for (const [down, up] of pedal) { + // (A pedal down before 0 was put down, and comes up, in the excerpt before this one: no sound of it here.) + if (releases) for (const [down, up] of pedal) if (down >= 0) { for (const [trigger, at] of [["pedal-down", down], ["pedal-up", up]] as const) { const list = set.zones.filter((z) => z.trigger === trigger); if (list.length === 0) continue; @@ -1231,6 +1232,33 @@ export function perform(options: PerformOptions, parts: Readonly= 0 && from <= last)) throw new Error(`excerpt() starts on a bar, 0 to ${last}, not ${from}.`); + if (to !== undefined && !(Number.isInteger(to) && to > from && to <= last)) throw new Error(`excerpt() ends on a bar after ${from}, at most ${last}, not ${to}.`); + const a = p.bars[from], b = to === undefined ? Infinity : p.bars[to]; + const notes = p.notes.filter((n) => n.at >= a - 1e-9 && n.at < b - 1e-9).map((n) => Object.freeze({ ...n, at: n.at - a, end: n.end - a, frame: Math.round((n.at - a) / FRAME) })); + const clip = (list: readonly (readonly [number, number])[]) => list.filter(([d, u]) => u > a && d < b).map(([d, u]) => [d - a, u - a] as [number, number]); + const pedal = new Map(); + for (const [inst, list] of inside.pedal) pedal.set(inst, clip(list)); + const made = Object.freeze({ + kind: "performance" as const, at: a, notes: Object.freeze(notes), pedal: Object.freeze(clip(p.pedal).map((x) => Object.freeze(x))), + bars: Object.freeze(p.bars.slice(from, to === undefined ? undefined : to + 1).map((t) => t - a)), parts: p.parts, + seconds: Math.max(0, ...notes.map((n) => n.end)), + }); + performances.set(made, { parts: inside.parts, pedal }); + return made; +} + /** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */ const performances = new WeakMap }>(); @@ -1679,6 +1707,6 @@ export const loop = game(async (s: Song) => { /** Everything above as one name: import { music } from "trigscript/music"; music.play(song). */ export const music = { - sampler, sampled, perform, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop, + sampler, sampled, perform, excerpt, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop, part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct, }; diff --git a/tests/sampled.test.ts b/tests/sampled.test.ts index daeb772..9cd1aea 100644 --- a/tests/sampled.test.ts +++ b/tests/sampled.test.ts @@ -192,6 +192,39 @@ describe("music.perform", () => { }); }); +describe("music.excerpt", () => { + it("takes the bars asked for, from 0, with the pedal down already where it went down before them", () => { + const r = run(` + const piano = music.sampled(inst, { releases: false }); + const take = music.perform({ meter: "3/8", bpm: 120, pickup: "1/8" }, { + right: { instrument: piano, notes: ["A4/8", "A4/8 B4 C5", "ped A4/4.", "B4/8 C5 D5 *"] }, + }); + const part = music.excerpt(take, 3); + const opening = music.excerpt(take, 0, 3); + const show = (p: typeof part) => p.notes.map((n) => \`\${n.note}@\${n.at.toFixed(2)}/\${n.bar}\`).join(" "); + if (Math.abs(part.at - 3.5) > 1e-6) fail(\`at \${part.at}\`); + if (show(part) !== "B4@0.00/3 C5@0.50/3 D5@1.00/3") fail(show(part)); + if (show(opening) !== "A4@0.00/0 A4@0.50/1 B4@1.00/1 C5@1.50/1 A4@2.00/2") fail(show(opening)); + if (part.pedal.length !== 1 || Math.abs(part.pedal[0][0] + 1.5) > 1e-6 || Math.abs(part.pedal[0][1] - 1.5) > 1e-6) fail(JSON.stringify(part.pedal)); + if (part.bars.length !== 2 || part.bars[0] !== 0) fail(part.bars.join()); + // The pedal down before the excerpt holds its B4 to the pedal's lift (1.5 s), and makes no sound of its own. + const held = music.render(part, { limit: false }); + if (Math.abs(held.seconds - Math.max(1.5 + 0.1, 1.0 + 0.5 + 0.1)) > 0.05) fail(\`\${held.seconds}\`); + program(async () => { playWav(held.wav(), 0); });`); + expect(errors(r)).toEqual([]); + }); + + it("brings sections made apart to one loudness with one gain, as loud against one another as they were", () => { + const r = run(` + const loud = tone("A4", 2, { volume: 0.5 }), soft = tone("A4", 2, { volume: 0.05 }); + const [a, b] = together([{ clip: loud, at: 0 }, { clip: soft, at: 2 }], { lufs: -20 }); + const sum = mixdown([{ clip: a, at: 0 }, { clip: b, at: 2 }]); + if (Math.abs(sum.lufs + 20) > 0.2) fail(\`\${sum.lufs}\`); + if (Math.abs(a.peak / b.peak - 10) > 0.01) fail(\`\${a.peak / b.peak}\`);`); + expect(errors(r)).toEqual([]); + }); +}); + describe("loudness and sympathy", () => { it("measures a full-scale 997 Hz sine at −3.01 LUFS on one side, 0 from both (as the game plays one channel), and brings a clip to a loudness", () => { const sine = tone(997, 3, { volume: 1, rate: 48000 }); From 41055e48291d1510f0202d98f1d5268190f0745f Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:33:00 -0600 Subject: [PATCH 14/31] =?UTF-8?q?S7:=20the=20F=C3=BCr=20Elise=20soundtrack?= =?UTF-8?q?,=20the=20whole=20piece?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The whole of WoO 59 from the 1888 Breitkopf scan, every repeat taken: the A section with both repeats, the F major episode (grace notes, the thirty-second passage twice), the theme again, the bar of drumming A and the storm, the arpeggios and the chromatic run (the 8va bar an octave up), the last theme and the held A. Bars 12 … 14 read again against the scan: the left hand's E4 → E5 over the bar line is a slur, not a tie (the probe had it tied). probes/fur-elise.ts plays it as the probe's item 3 was played, extended, and renders it a section at a time: A, the episode and the theme again in the smaller room, the storm and the closing in the hall, added up with their tails so the room changes where the storm comes in. One clip for the whole piece (3:33.4, −16.7 LUFS, −1.3 dBTP decoded, 4.2 MB), each section's clip with its tail as the fallback. probes/lib/fur-elise-timeline.ts is the timeline for the picture (1,340 notes with hand or part, the sections with their frames, bars, pedal), written by fur-elise-timeline-gen.mts from the build itself. The piano's samples now reach key 101: the arpeggios climb to E7. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 39 + probes/fur-elise.ts | 93 ++ probes/lib/fur-elise-score.ts | 161 ++- probes/lib/fur-elise-sound-gen.mts | 2 +- probes/lib/fur-elise-timeline-gen.mts | 60 ++ probes/lib/fur-elise-timeline.ts | 1431 +++++++++++++++++++++++++ 6 files changed, 1779 insertions(+), 7 deletions(-) create mode 100644 probes/fur-elise.ts create mode 100644 probes/lib/fur-elise-timeline-gen.mts create mode 100644 probes/lib/fur-elise-timeline.ts diff --git a/docs/v4-plan.md b/docs/v4-plan.md index 078d92b..898a1cf 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6604,6 +6604,45 @@ the game's text shows the ü. The sheet's choices were not answered one by one, the storm only, a smaller room for the first A and the hall for the last, −17 / −15 LUFS, all 16 piano layers. +#### S7 the full soundtrack (built 2026-11-09) + +After the sound probe ("sounds great") and the visualizer probe (one long clip keeps time with the game, a steady +~95 ms; a clip a bar wanders −40 … +30 ms): the whole piece is one Ogg, the sections with their tails only a fallback. + +- **The notes** (`probes/lib/fur-elise-score.ts`, from the same 1888 Breitkopf scan, every repeat taken): the A + section (pickup, 1 … 7 and the first ending, 1 … 7 and the second, the middle part 9 … 21 with its first ending, and + again), the F major episode B0 … B15 (B0 the second ending's C7; the tune with its grace notes as sixty-fourths; the + thirty-second passage twice, the second as an echo; the E–D# back), the theme again, the bar of drumming A and the + storm C1 … C17, the arpeggios in sixteenth triplets P1 … P3 (P3 an octave up, the score's 8va) and the chromatic + run P4 … P5, the theme a last time and the held A. Read against the scan: bars 12 … 14 — the left hand ends bar 12 + on E4 and starts bar 13 on E5 (slurred, not tied: the probe had it tied), the right hand's E5 E6 between; bar 14's + E5 an eighth on page 1 and the last A, a sixteenth on page 2 (each as printed). +- **Unsure, chosen by harmony:** B12's left-hand chord (read G#3+B3; two sharps printed, one placed oddly), B6's + left hand (E3 A3 C4 A3, then D3+D4, F3), B8/B10's three sixteenth chords (F4+G4, E4+G4, D4+F4+G4), the left hand's + A minor chord under the arpeggios (A3+C4+E4), and as before C6 and C16. +- **Played** as item 3 was, extended: the theme's tempo shape every time (a little calmer on its repeat and its last + time), the episode lyrical and slowing into the theme, the storm as item 4, the arpeggios flowing, the last bars + slowing to the A held in the pedal (the score lets it go short). The pedal as printed, plus the last A's. +- **The arc:** sections rendered apart with `music.excerpt` — A, B and the theme again in the smaller room (plate 0.7), + the storm and the closing in the hall (0.84) — and added up at their times, each tail under what follows, so the room + changes where the storm comes in without a seam. The piano's sections share one gain (`together(…, { lufs: −17 })`, + kept as loud against one another as played); the storm at −15 alone; the whole limited once. +- **Output** (`probes/fur-elise.ts`; previews in Maps/TrigScript/fur-elise-sound-preview/full/): the whole piece + 3:33.4 (the music 3:19, then the held A's ring and the hall), −16.7 LUFS, true peak −1.3 dBTP decoded, 4.2 MB at + quality 6; sections A 0:00 (frame 0) 76.1 s −17.4, B 1:07.8 (1,613) 33.1 s −16.8, the theme again 1:34.4 (2,248) + 41.1 s −16.2, the storm 2:07.1 (3,027) 35.6 s −15.1, the closing 2:32.9 (3,641) 60.5 s −17.3. A build 34 s. +- **The timeline** for the picture: `probes/lib/fur-elise-timeline.ts`, written by + `probes/lib/fur-elise-timeline-gen.mts` from the soundtrack's own build — 1,340 notes `[at, end, pitch, velocity, + part, voice, bar, beat, frame]` (parts: right, left, then the orchestra's), the sections with their frames, the bars, + the pedal. A program imports it as data, no samples needed. +- **Library:** `music.excerpt(performance, from, to)` (a pedal down before an excerpt is down already there, without + its sound twice); `together(parts, { lufs })`. +- The piano's `.samples` now spans keys 28 … 101 (557 recordings, 137 MB): P3 reaches E7. + +**Open:** the user's ears on the whole. The storm's short-term loudness (−13 … −16) is barely over the theme's loudest +bars (−13.7): at the probe's −17 / −15 the climax is bigger in sound, not much in level — lower the piano to −18.5 if +it should stand out more. + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice diff --git a/probes/fur-elise.ts b/probes/fur-elise.ts new file mode 100644 index 0000000..33527c7 --- /dev/null +++ b/probes/fur-elise.ts @@ -0,0 +1,93 @@ +// TrigScript Showcase #3, Für Elise: the soundtrack. The whole piece, every repeat the score has (probes/lib/ +// fur-elise-score.ts, ours from the public-domain score), played as the sound probe's item 3 was played and extended in +// its spirit, in the arc the user chose (2026-11-08): the A section and the F major episode on the solo piano in a +// smaller room, the theme again into the storm, the storm with the orchestra in the hall, and the closing theme on the +// piano in the hall, ending on the held A. +// +// Rendered when the script is built, a section at a time (`music.excerpt`), each in its room with its tail, and added +// up into one clip for the whole piece — the showcase's sound: one long clip keeps time with the game (the visualizer +// probe, 2026-11-09: a steady ~95 ms, no drift over 35 s). Each section's clip, tail and all, is the fallback. +// The timeline for the picture is probes/lib/fur-elise-timeline.ts (probes/lib/fur-elise-timeline-gen.mts). +// +// Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). Orchestra: VSCO 2 Community Edition by Versilian +// Studios (CC0). Instruments made by probes/lib/fur-elise-sound-gen.mts. +// +// npx tsx scripts/sound-dump.mts probes/fur-elise.ts +import { music, type Instrument } from "trigscript/music"; +import piano from "./salamander-grand.samples"; +import violinsSet from "./vsco-violins.samples"; +import violasSet from "./vsco-violas.samples"; +import celliSet from "./vsco-celli-spic.samples"; +import bassesSet from "./vsco-bass-spic.samples"; +import hornsSet from "./vsco-horns.samples"; +import tromboneSet from "./vsco-trombone.samples"; +import tubaSet from "./vsco-tuba.samples"; +import timpaniSet from "./vsco-timpani.samples"; +import rollsSet from "./vsco-timpani-rolls.samples"; +import { piece } from "./lib/fur-elise-score"; + +/** The solo piano at −17 LUFS (the probe's choice), the storm at −15. */ +const PIANO_LUFS = -17; +const STORM_LUFS = -15; +/** The smaller room for the first half, and the hall (the probe's) for the storm and the end. */ +const ROOM = { decay: 0.7, damping: 0.55, predelay: 0.018 }; +const HALL = { decay: 0.84, damping: 0.5, predelay: 0.032 }; +const MASTER = (c: Clip) => c.filter("highpass", 28); +const BUS = (c: Clip) => MASTER(c).compress({ threshold: -20, ratio: 2, attack: 0.02, release: 0.25, knee: 6 }); +const QUALITY = 6; + +const written = piece(); +const grand = music.sampled(piano, { resonance: 0.07 }); +const orchestra = (name: string, instrument: Instrument, pan: number, volume: number, reverb: number) => + ({ instrument, notes: (written.orchestra as Record)[name], pan, volume, reverb }); + +/** The piece as played: one performance, so every note has its time in the whole. */ +export const take = music.perform({ meter: "3/8", bpm: 120, pickup: "1/8", tempo: written.tempo, holds: written.holds, humanize: { time: 0.004, velocity: 3, seed: 7 } }, { + right: { instrument: grand, notes: written.right, lead: 0.008, reverb: 0.24 }, + left: { instrument: grand, notes: written.left, velocity: 0.92 }, + violins: orchestra("violins", music.sampled(violinsSet), -0.45, 2.8, 0.32), + violas: orchestra("violas", music.sampled(violasSet), 0.2, 0.85, 0.32), + celli: orchestra("celli", music.sampled(celliSet), 0.4, 1.35, 0.25), + basses: orchestra("basses", music.sampled(bassesSet), 0.55, 1.55, 0.25), + horns: orchestra("horns", music.sampled(hornsSet), -0.2, 0.8, 0.4), + trombones: orchestra("trombones", music.sampled(tromboneSet), 0.25, 2.8, 0.35), + tuba: orchestra("tuba", music.sampled(tubaSet), 0.3, 2.0, 0.3), + timpani: orchestra("timpani", music.sampled(timpaniSet), -0.1, 1.9, 0.45), + roll: orchestra("roll", music.sampled(rollsSet), -0.1, 0.9, 0.45), +}); + +/** The sections, where each begins in seconds and frames, and its bars. */ +export const sections = written.sections.map((s) => ({ name: s.name, from: s.from, to: s.to, at: take.bars[s.from], frame: Math.round(take.bars[s.from] / 0.042) })); + +/* ── Rendered a section at a time ── */ + +const raw = written.sections.map((s) => { + const hall = s.name === "storm" || s.name === "closing"; + return music.render(music.excerpt(take, s.from, s.to < take.bars.length - 1 ? s.to : undefined), { reverb: hall ? HALL : ROOM, master: s.name === "storm" ? BUS : MASTER, limit: false }); +}); +const piano4 = [0, 1, 2, 4]; +// The piano's sections turned by one gain, so they keep the levels they were played at; the storm on its own. +const pianoLevel = together(piano4.map((k) => ({ clip: raw[k], at: sections[k].at })), { lufs: PIANO_LUFS }); +const level = raw.map((c, k) => (k === 3 ? c.loudness(STORM_LUFS) : pianoLevel[piano4.indexOf(k)])); + +/** The whole piece, one clip: the sections added up at their times, tails under what follows, limited once. */ +export const whole = mixdown(level.map((c, k) => ({ clip: c, at: sections[k].at }))).limit().ogg(QUALITY); +/** Each section with its tail, for a showcase that restarts the sound a section at a time. */ +export const A = level[0].limit().ogg(QUALITY); +export const B = level[1].limit().ogg(QUALITY); +export const again = level[2].limit().ogg(QUALITY); +export const storm = level[3].limit().ogg(QUALITY); +export const closing = level[4].limit().ogg(QUALITY); + +program(async () => { + displayText("\x04Für Elise: the whole piece. Keys 1-5 play a section on its own."); + playWav(whole, 0); + while (true) { + if (keyPressed(P1, "1")) playWav(A, 0); + if (keyPressed(P1, "2")) playWav(B, 0); + if (keyPressed(P1, "3")) playWav(again, 0); + if (keyPressed(P1, "4")) playWav(storm, 0); + if (keyPressed(P1, "5")) playWav(closing, 0); + await nextFrame(); + } +}); diff --git a/probes/lib/fur-elise-score.ts b/probes/lib/fur-elise-score.ts index 776544e..99cfacf 100644 --- a/probes/lib/fur-elise-score.ts +++ b/probes/lib/fur-elise-score.ts @@ -4,8 +4,10 @@ // one. The orchestra's parts in the stormy section (C) are our arrangement. // // Bar numbers here: A section — 0 the pickup, 1 … 7, 8 the second ending (into the middle part), 9 … 21 as printed -// (12 … 14 the passage back to the theme), 22 the theme's last A, held. C section — C1 … C17, the D minor storm over -// the drumming A (printed bars 77 … 93 in the usual count), to the E chord before the pp arpeggios. +// (12 … 14 the passage back to the theme), 22 the theme's last A, held. B — the F major episode, B0 (the second ending +// of the middle part's repeat) … B15. C section — C1 … C17, the D minor storm over the drumming A (printed bars 77 … 93 +// in the usual count), to the E chord; P1 … P5 the pp arpeggios and the chromatic run down to the theme. `piece()` puts +// them in the order the score plays them, every repeat taken. /** `n` sixteenths of one note or chord: a bar of the drumming bass. */ export const sixteenths = (note: string, n = 6) => [`${note}/16`, ...Array.from({ length: n - 1 }, () => note)].join(" "); @@ -43,8 +45,9 @@ export const A_RIGHT = [ ]; // The left hand: each arpeggio under its pedal, as printed ("Ped." on the bar, "*" at its end); the turn in bars 12 … 14 -// handed across to it (its E4 tied over the bar line, then D#5 E5 in the treble). The last A is held in the pedal for two -// bars more, so it rings out before the dampers fall. +// handed across to it (bar 12 ends on E4, bar 13 starts an octave up on E5 — slurred, not tied — then D#5 E5 in the +// treble, the right hand's E5 E6 between). The last A is held in the pedal for two bars more, so it rings out before +// the dampers fall. export const A_LEFT = [ /* 0 */ "p r/8", /* 1 */ "r/4.", @@ -58,8 +61,8 @@ export const A_LEFT = [ /* 9 */ "p ped C3/16 G3 C4 r r/8 *", /* 10 */ "ped G2/16 G3 B3 r r/8 *", /* 11 */ "p > ped A2/16 E3 A3 r r/8 *", - /* 12 */ "ped E2/16 E3 E4 r r E4~", - /* 13 */ "pp E4/16 r r * D#5@-6 E5@-6 r", + /* 12 */ "ped E2/16 E3 E4 r r E4@-4", + /* 13 */ "pp E5/16@-4 r r * D#5@-6 E5@-6 r", /* 14 */ "r/16 D#5@-6 E5@-6 r r/8", /* 15 */ "r/4.", /* 16 */ "ped A2/16 E3 A3 r r/8 *", @@ -182,3 +185,149 @@ export const C_TIMPANI = [ "ff A2/4.!", "A2/8 r r", "A2/8 A2/16 A2 A2/8", ...rests(3), "E3/8 E3/16 E3 E3/8", "ff A2/4! r/8", "mf E3/8 r r", ]; + +/* ── The F major episode (B) ── */ + +// B0 is the middle part's second ending: A, then the C7 that turns to F. B1 … B7 the episode's tune over the left +// hand's broken chords; B8 … B11 the thirty-seconds over C and G7; B12 … B15 the E–D# that leads back to the theme +// (its last D#5 the theme's pickup). Grace notes are written as sixty-fourths taken from the note after them. +export const B_RIGHT = [ + /* B0 */ "p A4/8@-2 r/16 E4+C5@-8 F4+C5@-6 E4+G4+C5@-4", + /* B1 */ "p F4/64@-16 A4/64@-14 C5/8..@+4 F5/16.@+6 E5/32@-2", + /* B2 */ "E5/8@+2 D5@-3 Bb5/16.@+6 A5/32@-2", + /* B3 */ "A5/16@+3 G5@-1 F5@-2 E5@-3 D5@-4 C5@-5", + /* B4 */ "Bb4/8@-2 A4/16..@-4 Bb4/64@-12 A4/32@-6 G4@-8 A4@-6 Bb4@-4", + /* B5 */ "< C5/4 D5/16@-2 D#5", + /* B6 */ "p E5/8.@+8 E5/16@+2 F5@+4 A4@-6", + /* B7 */ "C5/4@+2 D5/16.@+2 B4/32@-6", + /* B8 */ "p C5/32@+2 G5@-6 G4@-10 G5@-6 A4@-8 G5@-6 B4@-6 G5@-6 C5@-3 G5@-6 D5@-2 G5@-6", + /* B9 */ "E5/32@+2 G5@-6 C6@+4 B5@-2 A5@-4 G5@-5 F5@-5 E5@-6 D5@-7 G5@-5 F5@-6 D5@-8", + /* B10 */ "pp C5/32@+4 G5@-6 G4@-10 G5@-6 A4@-8 G5@-6 B4@-6 G5@-6 C5@-3 G5@-6 D5@-2 G5@-6", + /* B11 */ "E5/32@+2 G5@-6 C6@+4 B5@-2 A5@-4 G5@-5 F5@-5 E5@-6 D5@-7 G5@-5 F5@-6 D5@-8", + /* B12 */ "pp E5/32@-2 F5@-4 E5 D#5@-3 E5 B4@-5 E5 D#5@-3 E5 B4@-5 E5 D#5@-3", + /* B13 */ "E5/8.@+2 B4/32@-6 E5@-2 D#5/8@-2", + /* B14 */ "E5/8.@+1 B4/32@-7 E5@-3 D#5/8@-3", + /* B15 */ "> E5/8 D#5/32@-4 E5@-3 D#5@-4 E5@-3 D#5/8@-2", +]; +export const B_LEFT = [ + /* B0 */ "p ped A2/16@-6 E3@-8 A3@-8 Bb3+C4@-8 A3+C4@-8 G3+Bb3+C4@-6", + /* B1 */ "p * ped F3/16@-8 A3@-12 C4@-12 A3@-14 C4@-12 A3@-14", + /* B2 */ "* ped F3/16@-8 Bb3@-12 D4@-12 Bb3@-14 D4@-12 Bb3@-14", + /* B3 */ "* F3/16@-8 E4@-10 G3+Bb3@-12 E4@-10 G3+Bb3@-12 E4@-12", + /* B4 */ "F3/16@-8 A3@-12 C4@-12 A3@-14 C4@-12 A3@-14", + /* B5 */ "< F3/16@-8 A3@-12 C4@-12 A3@-14 C4@-12 A3@-14", + /* B6 */ "p E3/16@-8 A3@-12 C4@-12 A3@-14 D3+D4@-10 F3@-12", + /* B7 */ "G3/16@-8 E4@-12 G3@-12 F4@-12 G3@-12 F4@-12", + /* B8 */ "p C4+E4/8@-8 r/16 F4+G4@-14 E4+G4@-14 D4+F4+G4@-12", + /* B9 */ "C4+E4+G4/8@-8 G3+B3@-14 G3+B3@-16", + /* B10 */ "pp C4+E4/8@-6 r/16 F4+G4@-14 E4+G4@-14 D4+F4+G4@-12", + /* B11 */ "C4+E4+G4/8@-8 G3+B3@-14 G3+B3@-16", + /* B12 */ "pp G#3+B3/8@-6 r r", + /* B13 */ "r/4.", + /* B14 */ "r/4.", + /* B15 */ "r/4.", +]; + +/* ── The pp arpeggios and the chromatic run (P), after the storm ── */ + +// Sixteenth triplets: the A minor arpeggio climbing over three bars (P3 an octave up, as the score's 8va has it), then +// down by semitones from B-flat to F, into the theme. The pedal held through the arpeggios, lifted for the run. +export const P_RIGHT = [ + /* P1 */ "pp A3/16t@-6 C4@-6 E4@-4 A4@-4 C5@-2 E5 D5@-2 C5@-3 B4@-4", + /* P2 */ "A4/16t@-6 C5@-5 E5@-3 A5@-2 C6@-1 E6@+1 D6@-1 C6@-2 B5@-3", + /* P3 */ "A5/16t@-6 C6@-5 E6@-3 A6@-2 C7@-1 E7 D7@-2 C7@-3 B6@-4", + /* P4 */ "> Bb6/16t@-4 A6@-5 G#6@-5 G6@-6 F#6@-6 F6@-7 E6@-7 D#6@-8 D6@-8", + /* P5 */ "C#6/16t@-8 C6@-9 B5@-9 Bb5@-10 A5@-10 G#5@-10 G5@-10 F#5@-10 F5@-10", +]; +export const P_LEFT = [ + /* P1 */ "pp ped A1/8@+4 r A3+C4+E4@-10", + /* P2 */ "A3+C4+E4/8@-10 r A3+C4+E4@-12", + /* P3 */ "A3+C4+E4/8@-12 r A3+C4+E4@-14", + /* P4 */ "* A3+C4+E4/8@-14 r r", + /* P5 */ "r/4.", +]; + +/* ── The whole piece ── */ + +/** A section of the piece: its name, and the bars [from, to) of `piece().right` it takes. */ +export interface PieceSection { readonly name: string; readonly from: number; readonly to: number } + +/** Theme bars `list` (by the numbers above) for one hand, the first with `mark` (a dynamic) before it. */ +const theme = (hand: readonly string[], list: readonly number[], mark = "") => list.map((k, i) => (i === 0 && mark ? `${mark} ${hand[k].replace(/^(ppp|pp|p|mp|mf|f|ff) /, "")}` : hand[k])); +const range = (a: number, b: number) => Array.from({ length: b - a + 1 }, (_, i) => a + i); +/** Tempo points written in theme bar numbers, placed where theme bar `first` stands in the piece (`at`). */ +const place = (points: readonly (readonly [number, number])[], first: number, at: number) => points.map(([x, v]) => [at + (x - first), v] as [number, number]); + +/** The theme's tempo for bars 1 … 8, and for 9 … 21 (A_TEMPO's), and a closing variant: slower, more inward. */ +const THEME_1_8 = A_TEMPO.filter(([x]) => x >= 1 && x < 9); +const THEME_9_21 = A_TEMPO.filter(([x]) => x >= 9 && x <= 21); +const calmer = (points: readonly (readonly [number, number])[], by: number) => points.map(([x, v]) => [x, v - by] as [number, number]); + +/** + * Für Elise as the score plays it, every repeat taken: the A section (the theme, its repeat, the middle part twice), + * the F major episode, the theme again into the storm, the storm, the arpeggios and the run, the theme a last time and + * the end. A text a bar for each hand and each orchestral part (rests where it does not play), [0] the pickup; its + * sections by bar; its tempo map and holds in those bars. + */ +export function piece() { + const right: string[] = [], left: string[] = [], sections: PieceSection[] = []; + const add = (name: string, r: readonly string[], l: readonly string[]) => { + if (r.length !== l.length) throw new Error(`${name}: ${r.length} bars for the right hand, ${l.length} for the left.`); + sections.push({ name, from: right.length, to: right.length + r.length }); + right.push(...r); left.push(...l); + }; + const ending8a = { r: "A4/4 E5/16@+2 D#5@-3", l: "ped A2/16 E3 A3 r * r/8" }; + const ending22a = { r: A_RIGHT[8], l: A_LEFT[8] }; + // A: pickup, 1 … 7, first ending; 1 … 7, second ending; the middle part 9 … 21 with its first ending, and again. + add("A", [ + A_RIGHT[0], ...theme(A_RIGHT, range(1, 7)), ending8a.r, ...theme(A_RIGHT, range(1, 7), "pp"), A_RIGHT[8], + ...theme(A_RIGHT, range(9, 21)), ending22a.r, ...theme(A_RIGHT, range(9, 21)), + ], [ + A_LEFT[0], ...theme(A_LEFT, range(1, 7)), ending8a.l, ...theme(A_LEFT, range(1, 7), "pp"), A_LEFT[8], + ...theme(A_LEFT, range(9, 21)), ending22a.l, ...theme(A_LEFT, range(9, 21)), + ]); + add("B", B_RIGHT, B_LEFT); + // The theme again (no pickup: the episode's last D#5 is it). Its bar 14 as page 2 prints it: E5 a sixteenth. + const again = theme(A_RIGHT, [...range(1, 8), ...range(9, 21)], "p").map((b, i) => (i === 13 ? "E5/16 r r D#5@-4 E5@-2 D#5@-4" : b)); + add("A again", again, theme(A_LEFT, [...range(1, 8), ...range(9, 21)], "p")); + // The storm: the bar of drumming A that leads in (the theme's last A over it), then C1 … C17. + add("storm", ["A4/8@-4 r r", ...C_RIGHT], [`p < ${sixteenths("A2")}`, ...C_LEFT]); + // The arpeggios, the run, the theme a last time, and the last A held in the pedal (the score lets it go short). + add("closing", [ + ...P_RIGHT, ...theme(A_RIGHT, [...range(1, 8), ...range(9, 21)], "p"), "ppp A4/4.@+8", + ], [ + ...P_LEFT, ...theme(A_LEFT, [...range(1, 8), ...range(9, 21)], "p"), "ppp ped A1+A2/4.@+6 | r/4. | r/4. *", + ]); + const storm = sections.find((x) => x.name === "storm")!; + // The orchestra rests to the storm; a timpani roll under its first bar. + const before = ["r/8", ...rests(storm.from - 1)]; + const orchestra = { + violins: [...before, "r/4.", ...C_VIOLINS], violas: [...before, "r/4.", ...C_VIOLAS], celli: [...before, "r/4.", ...C_CELLI], + basses: [...before, "r/4.", ...C_BASSES], horns: [...before, "r/4.", ...C_HORNS], trombones: [...before, "r/4.", ...C_TROMBONES], + tuba: [...before, "r/4.", ...C_TUBA], timpani: [...before, "r/4.", ...C_TIMPANI], roll: [...before, "pp A2/4."], + }; + const at = (name: string) => sections.find((x) => x.name === name)!.from; + const A = at("A"), B = at("B"), A2 = at("A again"), S = storm.from, C = at("closing"); + // The tempo, eighths a minute: item 3's shape for the theme every time, a little calmer on its repeat and its last + // time; the episode lyrical, its thirty-seconds steady, slowing into the theme; the storm driven; the arpeggios + // flowing and the run slowing into the last theme, which slows to the held A. + const tempo: [number, number][] = [ + [A + 0.4, 112], ...place(THEME_1_8, 1, A + 1), + ...place(calmer(THEME_1_8, 2), 1, A + 9), + ...place(THEME_9_21, 9, A + 17), [A + 29.8, 112], [A + 30, 118], [A + 30.67, 112], + ...place(THEME_9_21, 9, A + 31), [A + 43.7, 100], + [B, 108], [B + 1, 112], [B + 2, 114], [B + 3, 110], [B + 4, 112], [B + 5, 116], [B + 6, 112], [B + 7, 110], [B + 7.8, 102], + [B + 8, 118], [B + 11.8, 118], [B + 12, 114], [B + 13, 106], [B + 14, 98], [B + 15, 90], [B + 15.8, 84], + ...place(THEME_1_8, 1, A2), ...place(THEME_9_21, 9, A2 + 8), [A2 + 20, 110], [A2 + 20.7, 104], + [S, 118], [S + 1, 134], ...place(C_TEMPO.filter(([x]) => x > 1), 1, S + 1), + [C, 112], [C + 2, 118], [C + 3, 120], [C + 4, 112], [C + 4.8, 94], + ...place(calmer(THEME_1_8, 6), 1, C + 5), ...place(calmer(THEME_9_21.filter(([x]) => x < 20), 6), 9, C + 13), + [C + 24, 108], [C + 25, 96], [C + 25.7, 78], [C + 26, 70], + ]; + const holds: [number, number][] = [ + [A + 17, 0.1], [A + 21.33, 0.12], [A + 23, 0.06], [A + 31, 0.08], [A + 35.33, 0.12], [A + 37, 0.06], + [B, 0.08], [B + 8, 0.06], [A2, 0.25], [A2 + 8, 0.1], [A2 + 12.33, 0.12], [A2 + 14, 0.06], + [C, 0.6], [C + 5, 0.15], [C + 13, 0.12], [C + 17.33, 0.15], [C + 19, 0.08], [C + 26, 0.3], + ]; + return { right, left, orchestra, sections, tempo, holds }; +} diff --git a/probes/lib/fur-elise-sound-gen.mts b/probes/lib/fur-elise-sound-gen.mts index dc30209..ae13c43 100644 --- a/probes/lib/fur-elise-sound-gen.mts +++ b/probes/lib/fur-elise-sound-gen.mts @@ -22,7 +22,7 @@ const SAL = join(S, "salamander-grand-v3", "extracted", "SalamanderGrandPianoV3_ const make = (...args: string[]) => execFileSync("npx", ["tsx", join(root, "scripts", "make-samples.mts"), ...args], { stdio: "inherit" }); const VSCO = "VSCO 2 Community Edition by Versilian Studios (CC0)"; -make(join(SAL, "SalamanderGrandPianoV3.sfz"), join(out, "salamander-grand.samples"), "--keys", "28-91", "--seconds", "10", "--name", "Salamander Grand Piano V3", "--credit", "Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0)"); +make(join(SAL, "SalamanderGrandPianoV3.sfz"), join(out, "salamander-grand.samples"), "--keys", "28-101", "--seconds", "10", "--name", "Salamander Grand Piano V3", "--credit", "Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0)"); const vsco = (folder: string, file: string, name: string, ...more: string[]) => make("--names", join(V, folder), join(out, `${file}.samples`), "--name", name, "--credit", VSCO, ...more); vsco("Strings/Violin Section/susVib", "vsco-violins", "Violins (VSCO 2 CE)", "--octave", "1", "--seconds", "6", "--release", "0.35"); vsco("Strings/Violin Section/Spic", "vsco-violins-spic", "Violins spiccato (VSCO 2 CE)", "--octave", "1", "--release", "0.15"); diff --git a/probes/lib/fur-elise-timeline-gen.mts b/probes/lib/fur-elise-timeline-gen.mts new file mode 100644 index 0000000..1c807d8 --- /dev/null +++ b/probes/lib/fur-elise-timeline-gen.mts @@ -0,0 +1,60 @@ +// The Für Elise soundtrack's timeline, written out as data a showcase program imports (probes/lib/fur-elise-timeline.ts): +// every note as probes/fur-elise.ts plays it — when it is struck and let go, its key, how hard, which hand or part, its +// place in its chord, its bar, beat and frame — the sections with their frames, the bars, the pedal. Worked out by the +// script's own build (a check: no samples made), so it is the soundtrack's timing exactly. +// +// npx tsx probes/lib/fur-elise-timeline-gen.mts +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import ts from "typescript"; +import { compileScript } from "../../compiler/compiler"; +import { defaultScriptNames } from "../../compiler/names"; +import { defaultLib } from "../../bundle/lib.mjs"; +import { scriptFiles } from "../../scripts/script-files.mts"; + +const root = join(import.meta.dirname, "..", ".."); +const files = scriptFiles(join(root, "probes", "fur-elise.ts")); +// The build hands values back only in its words: the line it fails with carries them. +files["main.ts"] += ` +const r3 = (x: number) => Math.round(x * 1000) / 1000; +throw new Error("TIMELINE " + JSON.stringify({ + seconds: r3(take.seconds), parts: take.parts, bars: take.bars.map(r3), pedal: take.pedal.map((p) => [r3(p[0]), r3(p[1])]), + sections: sections.map((s) => ({ name: s.name, bar: s.from, at: r3(s.at), frame: s.frame })), + notes: take.notes.map((n) => [r3(n.at), r3(n.end), n.pitch, n.velocity, take.parts.indexOf(n.part), n.voice, n.bar, r3(n.beat), n.frame]), +})); +`; +const r = compileScript(ts, files, defaultScriptNames(), { lib: defaultLib(), sounds: false }); +const line = r.diagnostics.map((d) => d.message).find((m) => m.includes("TIMELINE ")); +if (!line) { for (const d of r.diagnostics) console.error(d.message); process.exit(1); } +const t = JSON.parse(line.slice(line.indexOf("TIMELINE ") + 9)) as { seconds: number; parts: string[]; bars: number[]; pedal: number[][]; sections: { name: string; bar: number; at: number; frame: number }[]; notes: number[][] }; +const rows = (list: unknown[][]) => list.map((x) => ` ${JSON.stringify(x)},`).join("\n"); +const text = `// Generated by probes/lib/fur-elise-timeline-gen.mts from probes/fur-elise.ts: do not edit, make it again. +// Für Elise as the soundtrack plays it (the whole piece as one clip, from 0). Seconds from its start; a frame is 42 ms +// (Fastest). The picture runs ahead of a long clip's sound by about 95 ms (the visualizer probe, 2026-11-09): the +// program shifts the picture, not these numbers. + +/** Seconds from the first note to the last let go (the held A's ring and the hall's tail come after). */ +export const SECONDS = ${t.seconds}; +/** The parts, by the number NOTES gives them: the hands, then the orchestra's parts (only in the storm). */ +export const PARTS = ${JSON.stringify(t.parts)} as const; +/** The sections, in order: the bar each begins on (BARS' numbering), and where, in seconds and frames. */ +export const SECTIONS: readonly { readonly name: string; readonly bar: number; readonly at: number; readonly frame: number }[] = ${JSON.stringify(t.sections)}; +/** Seconds each bar begins: [0] the pickup's start, [k] bar k's. */ +export const BARS: readonly number[] = ${JSON.stringify(t.bars)}; +/** The piano's sustain pedal: [down, up] in seconds. */ +export const PEDAL: readonly (readonly [number, number])[] = [ +${rows(t.pedal)} +]; +/** What NOTES' columns hold. */ +export const AT = 0, END = 1, PITCH = 2, VELOCITY = 3, PART = 4, VOICE = 5, BAR = 6, BEAT = 7, FRAME = 8; +/** + * Every note in the order struck: [at, end, pitch, velocity, part, voice, bar, beat, frame] — seconds struck and let go + * (the key; the pedal may hold it on), the key (60 is C4), 1 … 127, PARTS' number, its place in its chord (0 the lowest), + * the bar, the beat in it (eighths from 0), the frame it is struck on. + */ +export const NOTES: readonly (readonly number[])[] = [ +${rows(t.notes)} +]; +`; +writeFileSync(join(root, "probes", "lib", "fur-elise-timeline.ts"), text); +console.log(`probes/lib/fur-elise-timeline.ts: ${t.notes.length} notes, ${t.sections.length} sections, ${t.seconds} s`); diff --git a/probes/lib/fur-elise-timeline.ts b/probes/lib/fur-elise-timeline.ts new file mode 100644 index 0000000..7971efb --- /dev/null +++ b/probes/lib/fur-elise-timeline.ts @@ -0,0 +1,1431 @@ +// Generated by probes/lib/fur-elise-timeline-gen.mts from probes/fur-elise.ts: do not edit, make it again. +// Für Elise as the soundtrack plays it (the whole piece as one clip, from 0). Seconds from its start; a frame is 42 ms +// (Fastest). The picture runs ahead of a long clip's sound by about 95 ms (the visualizer probe, 2026-11-09): the +// program shifts the picture, not these numbers. + +/** Seconds from the first note to the last let go (the held A's ring and the hall's tail come after). */ +export const SECONDS = 198.988; +/** The parts, by the number NOTES gives them: the hands, then the orchestra's parts (only in the storm). */ +export const PARTS = ["right","left","violins","violas","celli","basses","horns","trombones","tuba","timpani","roll"] as const; +/** The sections, in order: the bar each begins on (BARS' numbering), and where, in seconds and frames. */ +export const SECTIONS: readonly { readonly name: string; readonly bar: number; readonly at: number; readonly frame: number }[] = [{"name":"A","bar":0,"at":0,"frame":0},{"name":"B","bar":44,"at":67.761,"frame":1613},{"name":"A again","bar":60,"at":94.434,"frame":2248},{"name":"storm","bar":81,"at":127.133,"frame":3027},{"name":"closing","bar":99,"at":152.906,"frame":3641}]; +/** Seconds each bar begins: [0] the pickup's start, [k] bar k's. */ +export const BARS: readonly number[] = [0,0.53,2.017,3.481,4.969,6.543,8.043,9.543,11.153,12.787,14.299,15.787,17.3,18.902,20.428,21.953,23.592,25.339,26.776,28.197,29.725,31.428,33.39,35.071,36.542,38.006,39.461,40.949,42.462,44.028,45.638,47.271,48.708,50.13,51.658,53.361,55.323,57.003,58.475,59.938,61.394,62.882,64.394,65.961,67.761,69.397,70.99,72.598,74.219,75.798,77.378,78.999,80.746,82.272,83.797,85.323,86.853,88.49,90.256,92.172,94.434,95.922,97.386,98.873,100.448,101.948,103.448,105.058,106.779,108.216,109.637,111.165,112.868,114.83,116.511,117.982,119.446,120.901,122.389,123.902,125.468,127.133,128.563,129.907,131.25,132.593,133.937,135.28,136.623,137.966,139.362,140.707,142.056,143.407,144.762,146.121,147.483,148.936,150.606,152.906,154.492,156.037,157.55,159.102,161.001,162.566,164.105,165.67,167.332,168.911,170.49,172.191,174.025,175.534,177.026,178.637,180.442,182.555,184.348,185.896,187.434,188.964,190.529,192.166,193.933,196.417,198.988,201.559,204.131]; +/** The piano's sustain pedal: [down, up] in seconds. */ +export const PEDAL: readonly (readonly [number, number])[] = [ + [2.017,3.481], + [3.541,4.969], + [5.029,6.543], + [8.043,9.543], + [9.603,11.153], + [11.213,12.265], + [14.299,15.787], + [15.847,17.3], + [17.36,18.902], + [20.428,21.953], + [22.013,23.592], + [23.652,25.339], + [25.399,26.776], + [26.836,28.197], + [28.257,29.725], + [29.785,32.483], + [36.542,38.006], + [38.066,39.461], + [39.521,40.949], + [42.462,44.028], + [44.088,45.638], + [45.698,47.271], + [47.331,48.708], + [48.768,50.13], + [50.19,51.658], + [51.718,54.416], + [58.475,59.938], + [59.998,61.394], + [61.454,62.882], + [64.394,65.961], + [66.021,67.761], + [67.821,69.397], + [69.457,70.99], + [71.05,72.598], + [95.922,97.386], + [97.446,98.873], + [98.933,100.448], + [101.948,103.448], + [103.508,105.058], + [105.118,106.779], + [106.839,108.216], + [108.276,109.637], + [109.697,111.165], + [111.225,113.923], + [117.982,119.446], + [119.506,120.901], + [120.961,122.389], + [123.902,125.468], + [125.528,127.133], + [152.906,157.55], + [162.566,164.105], + [164.165,165.67], + [165.73,167.332], + [168.911,170.49], + [170.55,172.191], + [172.251,174.025], + [174.085,175.534], + [175.594,177.026], + [177.086,178.637], + [178.697,181.589], + [185.896,187.434], + [187.494,188.964], + [189.024,190.529], + [192.166,193.933], + [193.993,196.417], + [196.477,204.131], +]; +/** What NOTES' columns hold. */ +export const AT = 0, END = 1, PITCH = 2, VELOCITY = 3, PART = 4, VOICE = 5, BAR = 6, BEAT = 7, FRAME = 8; +/** + * Every note in the order struck: [at, end, pitch, velocity, part, voice, bar, beat, frame] — seconds struck and let go + * (the key; the pedal may hold it on), the key (60 is C4), 1 … 127, PARTS' number, its place in its chord (0 the lowest), + * the bar, the beat in it (eighths from 0), the frame it is struck on. + */ +export const NOTES: readonly (readonly number[])[] = [ + [0,0.264,76,45,0,0,0,0,0], + [0.264,0.522,75,40,0,0,0,0.5,6], + [0.522,0.771,76,47,0,0,1,0,12], + [0.776,1.02,75,40,0,0,1,0.5,18], + [1.027,1.269,76,44,0,0,1,1,24], + [1.267,1.516,71,47,0,0,1,1.5,30], + [1.517,1.763,74,39,0,0,1,2,36], + [1.766,2.009,72,50,0,0,1,2.5,42], + [2.004,2.5,69,53,0,0,2,0,48], + [2.013,2.263,45,37,1,0,2,0,48], + [2.262,2.508,52,47,1,0,2,0.5,54], + [2.505,2.752,57,40,1,0,2,1,60], + [2.747,2.988,60,32,0,0,2,1.5,65], + [2.983,3.231,64,37,0,0,2,2,71], + [3.237,3.473,69,45,0,0,2,2.5,77], + [3.471,3.961,71,50,0,0,3,0,83], + [3.477,3.724,40,43,1,0,3,0,83], + [3.724,3.969,52,43,1,0,3,0.5,89], + [3.967,4.216,56,41,1,0,3,1,94], + [4.205,4.456,64,32,0,0,3,1.5,100], + [4.459,4.708,68,39,0,0,3,2,106], + [4.702,4.961,71,41,0,0,3,2.5,112], + [4.958,5.479,72,53,0,0,4,0,118], + [4.972,5.225,45,41,1,0,4,0,118], + [5.222,5.487,52,43,1,0,4,0.5,124], + [5.488,5.754,57,38,1,0,4,1,131], + [5.741,6.017,64,34,0,0,4,1.5,137], + [6.021,6.28,76,47,0,0,4,2,143], + [6.278,6.535,75,37,0,0,4,2.5,149], + [6.543,6.785,76,50,0,0,5,0,156], + [6.782,7.035,75,44,0,0,5,0.5,161], + [7.032,7.285,76,41,0,0,5,1,167], + [7.287,7.535,71,42,0,0,5,1.5,174], + [7.533,7.785,74,43,0,0,5,2,179], + [7.794,8.035,72,45,0,0,5,2.5,186], + [8.031,8.535,69,47,0,0,6,0,191], + [8.043,8.293,45,43,1,0,6,0,192], + [8.299,8.543,52,43,1,0,6,0.5,198], + [8.544,8.793,57,45,1,0,6,1,203], + [8.787,9.035,60,29,0,0,6,1.5,209], + [9.035,9.285,64,37,0,0,6,2,215], + [9.285,9.535,69,42,0,0,6,2.5,221], + [9.532,10.046,71,45,0,0,7,0,227], + [9.545,9.796,40,49,1,0,7,0,227], + [9.793,10.054,52,43,1,0,7,0.5,233], + [10.057,10.319,56,44,1,0,7,1,239], + [10.308,10.582,64,34,0,0,7,1.5,245], + [10.582,10.86,72,43,0,0,7,2,252], + [10.862,11.145,71,39,0,0,7,2.5,259], + [11.151,12.257,69,45,0,0,8,0,266], + [11.156,11.439,45,44,1,0,8,0,266], + [11.438,11.719,52,40,1,0,8,0.5,272], + [11.722,11.994,57,38,1,0,8,1,279], + [12.253,12.521,76,46,0,0,8,2,292], + [12.519,12.779,75,48,0,0,8,2.5,298], + [12.775,13.033,76,37,0,0,9,0,304], + [13.032,13.286,75,24,0,0,9,0.5,310], + [13.288,13.538,76,38,0,0,9,1,316], + [13.53,13.79,71,29,0,0,9,1.5,322], + [13.78,14.041,74,28,0,0,9,2,328], + [14.045,14.291,72,31,0,0,9,2.5,334], + [14.289,14.79,69,32,0,0,10,0,340], + [14.302,14.549,45,24,1,0,10,0,341], + [14.547,14.798,52,28,1,0,10,0.5,346], + [14.801,15.046,57,32,1,0,10,1,352], + [15.037,15.286,60,21,0,0,10,1.5,358], + [15.289,15.533,64,25,0,0,10,2,364], + [15.533,15.779,69,33,0,0,10,2.5,370], + [15.78,16.275,71,35,0,0,11,0,376], + [15.787,16.034,40,30,1,0,11,0,376], + [16.034,16.283,52,32,1,0,11,0.5,382], + [16.282,16.534,56,29,1,0,11,1,388], + [16.52,16.779,64,19,0,0,11,1.5,393], + [16.776,17.034,68,26,0,0,11,2,399], + [17.034,17.292,71,31,0,0,11,2.5,406], + [17.293,17.819,72,38,0,0,12,0,412], + [17.303,17.561,45,28,1,0,12,0,412], + [17.555,17.827,52,29,1,0,12,0.5,418], + [17.822,18.099,57,27,1,0,12,1,424], + [18.09,18.367,64,23,0,0,12,1.5,431], + [18.363,18.635,76,32,0,0,12,2,437], + [18.637,18.894,75,27,0,0,12,2.5,444], + [18.897,19.148,76,31,0,0,13,0,450], + [19.15,19.403,75,27,0,0,13,0.5,456], + [19.408,19.657,76,31,0,0,13,1,462], + [19.652,19.911,71,22,0,0,13,1.5,468], + [19.905,20.165,74,33,0,0,13,2,474], + [20.161,20.42,72,24,0,0,13,2.5,480], + [20.425,20.928,69,30,0,0,14,0,486], + [20.431,20.682,45,31,1,0,14,0,486], + [20.682,20.936,52,32,1,0,14,0.5,492], + [20.942,21.19,57,32,1,0,14,1,499], + [21.178,21.436,60,23,0,0,14,1.5,504], + [21.427,21.691,64,22,0,0,14,2,510], + [21.694,21.945,69,24,0,0,14,2.5,517], + [21.948,22.21,40,23,1,0,15,0,523], + [21.952,22.465,71,33,0,0,15,0,523], + [22.21,22.473,52,30,1,0,15,0.5,529], + [22.471,22.743,56,25,1,0,15,1,535], + [22.735,23.011,64,18,0,0,15,1.5,541], + [23.007,23.294,72,25,0,0,15,2,548], + [23.297,23.584,71,28,0,0,15,2.5,555], + [23.587,24.161,69,29,0,0,16,0,562], + [23.598,23.884,45,26,1,0,16,0,562], + [23.884,24.169,52,29,1,0,16,0.5,569], + [24.174,24.45,57,31,1,0,16,1,576], + [24.44,24.717,71,26,0,0,16,1.5,582], + [24.712,24.982,72,27,0,0,16,2,588], + [24.986,25.331,74,26,0,0,16,2.5,595], + [25.324,26.053,76,54,0,0,17,0,603], + [25.342,25.58,48,47,1,0,17,0,603], + [25.579,25.821,55,41,1,0,17,0.5,609], + [25.825,26.061,60,42,1,0,17,1,615], + [26.062,26.292,67,34,0,0,17,1.5,621], + [26.29,26.53,77,44,0,0,17,2,626], + [26.523,26.768,76,44,0,0,17,2.5,632], + [26.766,27.476,74,44,0,0,18,0,637], + [26.777,27.013,43,38,1,0,18,0,638], + [27.019,27.249,55,46,1,0,18,0.5,643], + [27.25,27.484,59,46,1,0,18,1,649], + [27.478,27.711,65,27,0,0,18,1.5,654], + [27.715,27.948,76,45,0,0,18,2,660], + [27.949,28.189,74,37,0,0,18,2.5,665], + [28.189,28.934,72,54,0,0,19,0,671], + [28.193,28.442,45,40,1,0,19,0,671], + [28.438,28.69,52,46,1,0,19,0.5,677], + [28.691,28.942,57,42,1,0,19,1,683], + [28.94,29.191,64,30,0,0,19,1.5,689], + [29.19,29.452,74,36,0,0,19,2,695], + [29.453,29.717,72,36,0,0,19,2.5,701], + [29.717,30.263,71,32,0,0,20,0,708], + [29.723,29.996,40,34,1,0,20,0,708], + [29.994,30.271,52,33,1,0,20,0.5,714], + [30.262,30.551,64,31,1,0,20,1,721], + [30.542,30.829,64,24,0,0,20,1.5,727], + [30.831,31.121,76,25,0,0,20,2,734], + [31.13,31.428,64,27,1,0,20,2.5,741], + [31.431,31.734,76,27,1,0,21,0,748], + [31.726,32.158,76,31,0,0,21,0.5,755], + [32.164,32.475,88,26,0,0,21,1,766], + [32.486,32.793,75,21,1,0,21,1.5,773], + [32.789,33.095,76,19,1,0,21,2,781], + [33.078,33.382,75,27,0,0,21,2.5,788], + [33.379,33.951,76,29,0,0,22,0,795], + [33.679,33.959,75,20,1,0,22,0.5,802], + [33.959,34.232,76,25,1,0,22,1,809], + [34.22,34.491,75,31,0,0,22,1.5,815], + [34.497,34.751,76,29,0,0,22,2,821], + [34.753,35.063,75,32,0,0,22,2.5,827], + [35.063,35.309,76,31,0,0,23,0,835], + [35.308,35.554,75,31,0,0,23,0.5,841], + [35.556,35.8,76,26,0,0,23,1,847], + [35.794,36.045,71,23,0,0,23,1.5,852], + [36.039,36.29,74,35,0,0,23,2,858], + [36.293,36.534,72,30,0,0,23,2.5,864], + [36.531,37.023,69,38,0,0,24,0,870], + [36.545,36.787,45,27,1,0,24,0,870], + [36.791,37.031,52,27,1,0,24,0.5,876], + [37.035,37.275,57,29,1,0,24,1,882], + [37.27,37.511,60,19,0,0,24,1.5,887], + [37.509,37.754,64,27,0,0,24,2,893], + [37.75,37.998,69,25,0,0,24,2.5,899], + [37.996,38.484,71,36,0,0,25,0,905], + [38.01,38.249,40,33,1,0,25,0,905], + [38.245,38.492,52,32,1,0,25,0.5,911], + [38.491,38.735,56,28,1,0,25,1,916], + [38.724,38.969,64,19,0,0,25,1.5,922], + [38.965,39.211,68,24,0,0,25,2,928], + [39.21,39.453,71,23,0,0,25,2.5,934], + [39.449,39.941,72,39,0,0,26,0,939], + [39.46,39.704,45,28,1,0,26,0,940], + [39.709,39.949,52,28,1,0,26,0.5,945], + [39.953,40.196,57,28,1,0,26,1,951], + [40.195,40.437,64,20,0,0,26,1.5,957], + [40.435,40.688,76,26,0,0,26,2,963], + [40.692,40.941,75,27,0,0,26,2.5,969], + [40.936,41.195,76,33,0,0,27,0,975], + [41.19,41.448,75,24,0,0,27,0.5,981], + [41.44,41.701,76,32,0,0,27,1,987], + [41.705,41.952,71,23,0,0,27,1.5,993], + [41.952,42.203,74,31,0,0,27,2,999], + [42.204,42.454,72,28,0,0,27,2.5,1005], + [42.446,42.961,69,28,0,0,28,0,1011], + [42.47,42.714,45,33,1,0,28,0,1011], + [42.721,42.969,52,25,1,0,28,0.5,1017], + [42.967,43.228,57,22,1,0,28,1,1023], + [43.225,43.483,60,19,0,0,28,1.5,1029], + [43.485,43.749,64,21,0,0,28,2,1035], + [43.754,44.02,69,24,0,0,28,2.5,1042], + [44.013,44.563,71,31,0,0,29,0,1048], + [44.018,44.3,40,30,1,0,29,0,1048], + [44.294,44.571,52,29,1,0,29,0.5,1055], + [44.574,44.842,56,31,1,0,29,1,1061], + [44.827,45.103,64,21,0,0,29,1.5,1067], + [45.105,45.371,72,33,0,0,29,2,1074], + [45.37,45.63,71,28,0,0,29,2.5,1080], + [45.632,46.146,69,36,0,0,30,0,1086], + [45.641,45.894,45,35,1,0,30,0,1087], + [45.889,46.154,52,39,1,0,30,0.5,1093], + [46.156,46.416,57,37,1,0,30,1,1099], + [46.411,46.674,71,37,0,0,30,1.5,1105], + [46.671,46.935,72,43,0,0,30,2,1111], + [46.935,47.263,74,46,0,0,30,2.5,1117], + [47.266,47.513,48,41,1,0,31,0,1125], + [47.268,47.985,76,48,0,0,31,0,1125], + [47.512,47.754,55,42,1,0,31,0.5,1131], + [47.754,47.993,60,43,1,0,31,1,1137], + [47.99,48.225,67,32,0,0,31,1.5,1143], + [48.225,48.463,77,44,0,0,31,2,1148], + [48.468,48.7,76,39,0,0,31,2.5,1154], + [48.699,49.408,74,53,0,0,32,0,1159], + [48.716,48.945,43,48,1,0,32,0,1160], + [48.938,49.181,55,38,1,0,32,0.5,1165], + [49.187,49.416,59,42,1,0,32,1,1171], + [49.41,49.643,65,30,0,0,32,1.5,1176], + [49.643,49.881,76,44,0,0,32,2,1182], + [49.882,50.122,74,43,0,0,32,2.5,1188], + [50.126,50.374,45,42,1,0,33,0,1193], + [50.131,50.867,72,56,0,0,33,0,1194], + [50.368,50.623,52,38,1,0,33,0.5,1199], + [50.624,50.875,57,42,1,0,33,1,1205], + [50.87,51.123,64,30,0,0,33,1.5,1211], + [51.126,51.384,74,46,0,0,33,2,1217], + [51.383,51.65,72,36,0,0,33,2.5,1223], + [51.654,52.195,71,38,0,0,34,0,1230], + [51.663,51.928,40,38,1,0,34,0,1230], + [51.932,52.203,52,35,1,0,34,0.5,1236], + [52.208,52.484,64,37,1,0,34,1,1243], + [52.471,52.762,64,25,0,0,34,1.5,1249], + [52.765,53.054,76,34,0,0,34,2,1256], + [53.068,53.361,64,25,1,0,34,2.5,1264], + [53.361,53.666,76,29,1,0,35,0,1270], + [53.661,54.091,76,30,0,0,35,0.5,1278], + [54.098,54.408,88,26,0,0,35,1,1288], + [54.417,54.726,75,23,1,0,35,1.5,1296], + [54.717,55.028,76,29,1,0,35,2,1303], + [55.019,55.315,75,28,0,0,35,2.5,1310], + [55.313,55.883,76,28,0,0,36,0,1317], + [55.609,55.891,75,21,1,0,36,0.5,1324], + [55.891,56.165,76,24,1,0,36,1,1331], + [56.153,56.423,75,29,0,0,36,1.5,1337], + [56.425,56.683,76,32,0,0,36,2,1343], + [56.682,56.995,75,29,0,0,36,2.5,1350], + [56.997,57.241,76,33,0,0,37,0,1357], + [57.245,57.487,75,30,0,0,37,0.5,1363], + [57.478,57.732,76,33,0,0,37,1,1369], + [57.73,57.977,71,25,0,0,37,1.5,1375], + [57.974,58.222,74,30,0,0,37,2,1380], + [58.221,58.467,72,24,0,0,37,2.5,1386], + [58.468,58.955,69,28,0,0,38,0,1392], + [58.473,58.719,45,30,1,0,38,0,1392], + [58.713,58.963,52,33,1,0,38,0.5,1398], + [58.961,59.208,57,32,1,0,38,1,1404], + [59.195,59.443,60,19,0,0,38,1.5,1409], + [59.436,59.687,64,23,0,0,38,2,1415], + [59.691,59.93,69,31,0,0,38,2.5,1421], + [59.931,60.416,71,36,0,0,39,0,1427], + [59.933,60.181,40,32,1,0,39,0,1427], + [60.18,60.424,52,32,1,0,39,0.5,1433], + [60.423,60.667,56,27,1,0,39,1,1439], + [60.655,60.901,64,23,0,0,39,1.5,1444], + [60.904,61.144,68,25,0,0,39,2,1450], + [61.139,61.386,71,29,0,0,39,2.5,1456], + [61.384,61.874,72,35,0,0,40,0,1462], + [61.391,61.637,45,25,1,0,40,0,1462], + [61.642,61.882,52,33,1,0,40,0.5,1468], + [61.885,62.128,57,33,1,0,40,1,1473], + [62.121,62.369,64,24,0,0,40,1.5,1479], + [62.368,62.62,76,32,0,0,40,2,1485], + [62.624,62.874,75,22,0,0,40,2.5,1491], + [62.874,63.128,76,33,0,0,41,0,1497], + [63.125,63.381,75,28,0,0,41,0.5,1503], + [63.374,63.633,76,27,0,0,41,1,1509], + [63.635,63.885,71,24,0,0,41,1.5,1515], + [63.885,64.136,74,26,0,0,41,2,1521], + [64.131,64.386,72,22,0,0,41,2.5,1527], + [64.386,64.893,69,36,0,0,42,0,1533], + [64.391,64.646,45,26,1,0,42,0,1533], + [64.645,64.901,52,28,1,0,42,0.5,1539], + [64.898,65.16,57,30,1,0,42,1,1545], + [65.149,65.415,60,16,0,0,42,1.5,1551], + [65.415,65.682,64,23,0,0,42,2,1558], + [65.679,65.953,69,29,0,0,42,2.5,1564], + [65.948,66.51,71,32,0,0,43,0,1570], + [65.957,66.236,40,31,1,0,43,0,1570], + [66.234,66.518,52,30,1,0,43,0.5,1577], + [66.519,66.806,56,33,1,0,43,1,1584], + [66.796,67.094,64,28,0,0,43,1.5,1590], + [67.093,67.389,72,36,0,0,43,2,1597], + [67.384,67.753,71,36,0,0,43,2.5,1604], + [67.761,68.305,69,48,0,0,44,0,1613], + [67.762,68.038,45,40,1,0,44,0,1613], + [68.041,68.313,52,38,1,0,44,0.5,1620], + [68.322,68.587,57,35,1,0,44,1,1627], + [68.576,68.851,64,38,0,0,44,1.5,1633], + [68.579,68.851,72,37,0,1,44,1.5,1633], + [68.584,68.859,58,32,1,0,44,1.5,1633], + [68.586,68.859,60,37,1,1,44,1.5,1633], + [68.84,69.121,65,42,0,0,44,2,1639], + [68.859,69.121,72,43,0,1,44,2,1640], + [68.859,69.129,60,34,1,1,44,2,1640], + [68.864,69.129,57,33,1,0,44,2,1640], + [69.115,69.389,67,36,0,1,44,2.5,1646], + [69.122,69.397,60,35,1,2,44,2.5,1646], + [69.122,69.397,58,32,1,1,44,2.5,1646], + [69.124,69.389,64,41,0,0,44,2.5,1646], + [69.124,69.389,72,41,0,2,44,2.5,1646], + [69.127,69.397,55,38,1,0,44,2.5,1646], + [69.387,69.456,65,30,0,0,45,0,1652], + [69.398,69.665,53,29,1,0,45,0,1652], + [69.463,69.523,69,27,0,0,45,0.125,1654], + [69.528,70.455,72,46,0,0,45,0.25,1655], + [69.67,69.932,57,37,1,0,45,0.5,1659], + [69.932,70.197,60,28,1,0,45,1,1665], + [70.199,70.463,57,27,1,0,45,1.5,1671], + [70.456,70.851,77,52,0,0,45,2,1678], + [70.462,70.727,60,32,1,0,45,2,1678], + [70.727,70.99,57,27,1,0,45,2.5,1684], + [70.849,70.982,76,46,0,0,45,2.75,1687], + [70.985,71.512,76,54,0,0,46,0,1690], + [70.988,71.254,53,28,1,0,46,0,1690], + [71.257,71.52,58,30,1,0,46,0.5,1697], + [71.51,72.048,74,40,0,0,46,1,1703], + [71.526,71.787,62,36,1,0,46,1,1703], + [71.793,72.056,58,35,1,0,46,1.5,1709], + [72.043,72.454,82,52,0,0,46,2,1715], + [72.054,72.326,62,28,1,0,46,2,1716], + [72.33,72.598,58,26,1,0,46,2.5,1722], + [72.454,72.59,81,48,0,0,46,2.75,1725], + [72.591,72.862,81,49,0,0,47,0,1728], + [72.602,72.87,53,38,1,0,47,0,1729], + [72.863,73.134,79,42,0,0,47,0.5,1735], + [72.876,73.142,64,36,1,0,47,0.5,1735], + [73.134,73.404,77,51,0,0,47,1,1741], + [73.139,73.412,55,31,1,0,47,1,1741], + [73.14,73.412,58,31,1,1,47,1,1741], + [73.404,73.674,76,36,0,0,47,1.5,1748], + [73.417,73.682,64,33,1,0,47,1.5,1748], + [73.674,73.943,74,46,0,0,47,2,1754], + [73.68,73.951,58,34,1,1,47,2,1754], + [73.682,73.951,55,28,1,0,47,2,1754], + [73.948,74.219,64,27,1,0,47,2.5,1761], + [73.949,74.211,72,44,0,0,47,2.5,1761], + [74.211,74.744,70,39,0,0,48,0,1767], + [74.217,74.486,53,37,1,0,48,0,1767], + [74.484,74.752,57,32,1,0,48,0.5,1773], + [74.745,75.205,69,41,0,0,48,1,1780], + [74.747,75.016,60,27,1,0,48,1,1780], + [75.011,75.278,57,29,1,0,48,1.5,1786], + [75.207,75.27,70,34,0,0,48,1.875,1791], + [75.274,75.401,69,39,0,0,48,2,1792], + [75.278,75.539,60,35,1,0,48,2,1792], + [75.4,75.531,67,40,0,0,48,2.25,1795], + [75.522,75.661,69,40,0,0,48,2.5,1798], + [75.539,75.798,57,30,1,0,48,2.5,1799], + [75.666,75.79,70,42,0,0,48,2.75,1802], + [75.787,76.837,72,49,0,0,49,0,1804], + [75.799,76.058,53,37,1,0,49,0,1805], + [76.061,76.319,57,31,1,0,49,0.5,1811], + [76.311,76.581,60,29,1,0,49,1,1817], + [76.582,76.845,57,27,1,0,49,1.5,1823], + [76.839,77.103,74,42,0,0,49,2,1829], + [76.845,77.111,60,31,1,0,49,2,1830], + [77.103,77.37,75,48,0,0,49,2.5,1836], + [77.115,77.378,57,30,1,0,49,2.5,1836], + [77.369,78.177,76,58,0,0,50,0,1842], + [77.377,77.646,52,38,1,0,50,0,1842], + [77.645,77.915,57,32,1,0,50,0.5,1849], + [77.918,78.185,60,32,1,0,50,1,1855], + [78.183,78.447,76,46,0,0,50,1.5,1861], + [78.186,78.455,57,32,1,0,50,1.5,1862], + [78.447,78.719,77,46,0,0,50,2,1868], + [78.457,78.727,50,32,1,0,50,2,1868], + [78.46,78.727,62,35,1,1,50,2,1868], + [78.72,78.991,69,42,0,0,50,2.5,1874], + [78.724,78.999,53,28,1,0,50,2.5,1874], + [78.985,80.117,72,44,0,0,51,0,1881], + [79.001,79.274,55,36,1,0,51,0,1881], + [79.278,79.553,64,27,1,0,51,0.5,1888], + [79.549,79.837,55,28,1,0,51,1,1894], + [79.835,80.125,65,36,1,0,51,1.5,1901], + [80.111,80.547,74,49,0,0,51,2,1907], + [80.126,80.416,55,31,1,0,51,2,1908], + [80.413,80.746,65,33,1,0,51,2.5,1915], + [80.548,80.738,71,40,0,0,51,2.75,1918], + [80.741,81.255,64,39,1,1,52,0,1922], + [80.746,80.865,72,48,0,0,52,0,1923], + [80.749,81.255,60,37,1,0,52,0,1923], + [80.865,80.992,79,44,0,0,52,0.25,1925], + [80.991,81.12,67,37,0,0,52,0.5,1928], + [81.114,81.247,79,37,0,0,52,0.75,1931], + [81.248,81.374,69,40,0,0,52,1,1934], + [81.374,81.501,79,45,0,0,52,1.25,1937], + [81.499,81.628,71,37,0,0,52,1.5,1940], + [81.506,81.763,65,31,1,0,52,1.5,1941], + [81.513,81.763,67,29,1,1,52,1.5,1941], + [81.626,81.755,79,39,0,0,52,1.75,1943], + [81.751,81.882,72,39,0,0,52,2,1946], + [81.76,82.017,64,26,1,0,52,2,1947], + [81.76,82.017,67,34,1,1,52,2,1947], + [81.885,82.009,79,43,0,0,52,2.25,1950], + [82.014,82.272,65,33,1,1,52,2.5,1953], + [82.015,82.137,74,45,0,0,52,2.5,1953], + [82.017,82.272,67,35,1,2,52,2.5,1953], + [82.017,82.272,62,27,1,0,52,2.5,1953], + [82.128,82.264,79,40,0,0,52,2.75,1955], + [82.268,82.391,76,53,0,0,53,0,1959], + [82.269,82.78,67,34,1,2,53,0,1959], + [82.273,82.78,60,35,1,0,53,0,1959], + [82.274,82.78,64,32,1,1,53,0,1959], + [82.388,82.518,79,44,0,0,53,0.25,1962], + [82.52,82.645,84,52,0,0,53,0.5,1965], + [82.646,82.772,83,45,0,0,53,0.75,1968], + [82.765,82.899,81,42,0,0,53,1,1971], + [82.776,83.289,55,28,1,0,53,1,1971], + [82.78,83.289,59,26,1,1,53,1,1971], + [82.905,83.026,79,40,0,0,53,1.25,1974], + [83.033,83.154,77,47,0,0,53,1.5,1977], + [83.158,83.281,76,41,0,0,53,1.75,1980], + [83.282,83.408,74,38,0,0,53,2,1983], + [83.285,83.797,59,30,1,1,53,2,1983], + [83.285,83.797,55,27,1,0,53,2,1983], + [83.406,83.535,79,43,0,0,53,2.25,1986], + [83.536,83.662,77,39,0,0,53,2.5,1989], + [83.665,83.789,74,41,0,0,53,2.75,1992], + [83.789,83.916,72,41,0,0,54,0,1995], + [83.798,84.306,60,26,1,0,54,0,1995], + [83.802,84.306,64,22,1,1,54,0,1995], + [83.914,84.043,79,27,0,0,54,0.25,1998], + [84.039,84.17,67,23,0,0,54,0.5,2001], + [84.177,84.298,79,28,0,0,54,0.75,2004], + [84.297,84.425,69,22,0,0,54,1,2007], + [84.421,84.552,79,26,0,0,54,1.25,2010], + [84.549,84.679,71,24,0,0,54,1.5,2013], + [84.557,84.814,67,20,1,1,54,1.5,2013], + [84.559,84.814,65,16,1,0,54,1.5,2013], + [84.675,84.806,79,24,0,0,54,1.75,2016], + [84.807,84.933,72,32,0,0,54,2,2019], + [84.812,85.068,64,16,1,0,54,2,2019], + [84.816,85.068,67,18,1,1,54,2,2019], + [84.941,85.06,79,29,0,0,54,2.25,2022], + [85.055,85.187,74,29,0,0,54,2.5,2025], + [85.065,85.323,67,23,1,2,54,2.5,2025], + [85.072,85.323,65,23,1,1,54,2.5,2026], + [85.072,85.323,62,17,1,0,54,2.5,2026], + [85.199,85.315,79,23,0,0,54,2.75,2029], + [85.313,85.442,76,31,0,0,55,0,2031], + [85.324,85.831,67,18,1,2,55,0,2032], + [85.326,85.831,64,17,1,1,55,0,2032], + [85.328,85.831,60,24,1,0,55,0,2032], + [85.44,85.569,79,22,0,0,55,0.25,2034], + [85.57,85.696,84,39,0,0,55,0.5,2037], + [85.694,85.823,83,27,0,0,55,0.75,2040], + [85.828,86.339,55,17,1,0,55,1,2044], + [85.829,85.95,81,26,0,0,55,1,2044], + [85.835,86.339,59,13,1,1,55,1,2044], + [85.951,86.077,79,22,0,0,55,1.25,2046], + [86.077,86.204,77,31,0,0,55,1.5,2049], + [86.204,86.331,76,28,0,0,55,1.75,2052], + [86.331,86.459,74,23,0,0,55,2,2055], + [86.333,86.853,55,10,1,0,55,2,2056], + [86.339,86.853,59,9,1,1,55,2,2056], + [86.449,86.586,79,27,0,0,55,2.25,2058], + [86.581,86.715,77,25,0,0,55,2.5,2061], + [86.708,86.845,74,21,0,0,55,2.75,2064], + [86.84,86.977,76,33,0,0,56,0,2068], + [86.849,87.386,59,26,1,1,56,0,2068], + [86.854,87.386,56,20,1,0,56,0,2068], + [86.983,87.11,77,26,0,0,56,0.25,2071], + [87.108,87.243,76,30,0,0,56,0.5,2074], + [87.242,87.378,75,25,0,0,56,0.75,2077], + [87.376,87.513,76,34,0,0,56,1,2080], + [87.514,87.649,71,22,0,0,56,1.25,2084], + [87.643,87.786,76,37,0,0,56,1.5,2087], + [87.782,87.923,75,27,0,0,56,1.75,2090], + [87.921,88.062,76,32,0,0,56,2,2093], + [88.061,88.201,71,26,0,0,56,2.25,2097], + [88.208,88.341,76,36,0,0,56,2.5,2100], + [88.341,88.482,75,28,0,0,56,2.75,2103], + [88.478,89.348,76,33,0,0,57,0,2107], + [89.342,89.495,71,24,0,0,57,1.5,2127], + [89.495,89.644,76,25,0,0,57,1.75,2131], + [89.645,90.248,75,30,0,0,57,2,2134], + [90.245,91.186,76,37,0,0,58,0,2149], + [91.18,91.346,71,22,0,0,58,1.5,2171], + [91.345,91.507,76,32,0,0,58,1.75,2175], + [91.507,92.164,75,29,0,0,58,2,2179], + [92.168,92.84,76,35,0,0,59,0,2194], + [92.846,93.012,75,38,0,0,59,1,2211], + [93.014,93.185,76,33,0,0,59,1.25,2215], + [93.181,93.36,75,32,0,0,59,1.5,2219], + [93.362,93.536,76,36,0,0,59,1.75,2223], + [93.54,94.426,75,42,0,0,59,2,2227], + [94.422,94.676,76,48,0,0,60,0,2248], + [94.666,94.925,75,41,0,0,60,0.5,2254], + [94.922,95.173,76,49,0,0,60,1,2260], + [95.173,95.421,71,39,0,0,60,1.5,2266], + [95.421,95.668,74,43,0,0,60,2,2272], + [95.672,95.914,72,46,0,0,60,2.5,2278], + [95.919,96.168,45,44,1,0,61,0,2284], + [95.92,96.405,69,45,0,0,61,0,2284], + [96.169,96.413,52,41,1,0,61,0.5,2290], + [96.412,96.657,57,39,1,0,61,1,2296], + [96.646,96.892,60,35,0,0,61,1.5,2301], + [96.889,97.135,64,39,0,0,61,2,2307], + [97.134,97.378,69,36,0,0,61,2.5,2313], + [97.382,97.865,71,45,0,0,62,0,2319], + [97.391,97.628,40,43,1,0,62,0,2319], + [97.629,97.873,52,49,1,0,62,0.5,2325], + [97.877,98.12,56,43,1,0,62,1,2330], + [98.109,98.361,64,34,0,0,62,1.5,2336], + [98.362,98.612,68,37,0,0,62,2,2342], + [98.613,98.865,71,42,0,0,62,2.5,2348], + [98.862,99.384,72,51,0,0,63,0,2354], + [98.873,99.13,45,43,1,0,63,0,2354], + [99.13,99.392,52,43,1,0,63,0.5,2360], + [99.386,99.659,57,47,1,0,63,1,2366], + [99.652,99.922,64,37,0,0,63,1.5,2373], + [99.923,100.185,76,45,0,0,63,2,2379], + [100.181,100.44,75,36,0,0,63,2.5,2385], + [100.441,100.69,76,49,0,0,64,0,2391], + [100.696,100.94,75,43,0,0,64,0.5,2398], + [100.941,101.19,76,54,0,0,64,1,2403], + [101.196,101.44,71,45,0,0,64,1.5,2409], + [101.433,101.69,74,45,0,0,64,2,2415], + [101.692,101.94,72,41,0,0,64,2.5,2421], + [101.947,102.44,69,48,0,0,65,0,2427], + [101.951,102.198,45,43,1,0,65,0,2427], + [102.204,102.448,52,38,1,0,65,0.5,2433], + [102.442,102.698,57,40,1,0,65,1,2439], + [102.685,102.94,60,34,0,0,65,1.5,2445], + [102.939,103.19,64,39,0,0,65,2,2451], + [103.192,103.44,69,43,0,0,65,2.5,2457], + [103.437,103.951,71,49,0,0,66,0,2463], + [103.449,103.701,40,35,1,0,66,0,2463], + [103.703,103.959,52,40,1,0,66,0.5,2469], + [103.957,104.224,56,42,1,0,66,1,2475], + [104.224,104.487,64,37,0,0,66,1.5,2482], + [104.486,104.765,72,45,0,0,66,2,2488], + [104.761,105.05,71,38,0,0,66,2.5,2494], + [105.047,105.616,69,50,0,0,67,0,2501], + [105.062,105.343,45,41,1,0,67,0,2501], + [105.335,105.624,52,43,1,0,67,0.5,2508], + [105.63,105.899,57,40,1,0,67,1,2515], + [105.893,106.161,71,38,0,0,67,1.5,2521], + [106.16,106.423,72,39,0,0,67,2,2528], + [106.424,106.771,74,43,0,0,67,2.5,2534], + [106.772,107.493,76,49,0,0,68,0,2542], + [106.781,107.02,48,42,1,0,68,0,2542], + [107.013,107.261,55,41,1,0,68,0.5,2548], + [107.262,107.501,60,45,1,0,68,1,2554], + [107.496,107.732,67,31,0,0,68,1.5,2559], + [107.727,107.97,77,42,0,0,68,2,2565], + [107.974,108.208,76,46,0,0,68,2.5,2571], + [108.205,108.916,74,52,0,0,69,0,2576], + [108.218,108.453,43,40,1,0,69,0,2577], + [108.451,108.689,55,43,1,0,69,0.5,2582], + [108.688,108.924,59,43,1,0,69,1,2588], + [108.91,109.151,65,34,0,0,69,1.5,2593], + [109.15,109.388,76,47,0,0,69,2,2599], + [109.391,109.629,74,44,0,0,69,2.5,2605], + [109.631,110.374,72,57,0,0,70,0,2610], + [109.637,109.882,45,39,1,0,70,0,2610], + [109.879,110.13,52,45,1,0,70,0.5,2616], + [110.128,110.382,57,40,1,0,70,1,2622], + [110.374,110.631,64,30,0,0,70,1.5,2628], + [110.629,110.892,74,36,0,0,70,2,2634], + [110.893,111.157,72,35,0,0,70,2.5,2640], + [111.151,111.703,71,40,0,0,71,0,2646], + [111.163,111.435,40,38,1,0,71,0,2647], + [111.436,111.711,52,33,1,0,71,0.5,2653], + [111.713,111.991,64,30,1,0,71,1,2660], + [111.981,112.269,64,29,0,0,71,1.5,2666], + [112.267,112.561,76,25,0,0,71,2,2673], + [112.573,112.868,64,30,1,0,71,2.5,2680], + [112.869,113.173,76,22,1,0,72,0,2687], + [113.169,113.598,76,26,0,0,72,0.5,2694], + [113.604,113.915,88,27,0,0,72,1,2705], + [113.921,114.233,75,24,1,0,72,1.5,2712], + [114.23,114.535,76,21,1,0,72,2,2720], + [114.531,114.822,75,23,0,0,72,2.5,2727], + [114.83,115.11,76,34,0,0,73,0,2734], + [115.114,115.399,75,24,1,0,73,0.5,2741], + [115.399,115.672,76,23,1,0,73,1,2748], + [115.67,115.931,75,30,0,0,73,1.5,2754], + [115.931,116.191,76,23,0,0,73,2,2760], + [116.193,116.503,75,31,0,0,73,2.5,2766], + [116.509,116.749,76,34,0,0,74,0,2774], + [116.743,116.994,75,30,0,0,74,0.5,2780], + [116.988,117.239,76,29,0,0,74,1,2785], + [117.237,117.485,71,26,0,0,74,1.5,2791], + [117.486,117.729,74,30,0,0,74,2,2797], + [117.736,117.974,72,28,0,0,74,2.5,2803], + [117.975,118.463,69,35,0,0,75,0,2809], + [117.988,118.227,45,27,1,0,75,0,2809], + [118.224,118.471,52,33,1,0,75,0.5,2815], + [118.468,118.715,57,30,1,0,75,1,2821], + [118.707,118.951,60,20,0,0,75,1.5,2826], + [118.951,119.194,64,29,0,0,75,2,2832], + [119.196,119.438,69,25,0,0,75,2.5,2838], + [119.431,119.924,71,35,0,0,76,0,2844], + [119.445,119.689,40,32,1,0,76,0,2844], + [119.689,119.932,52,28,1,0,76,0.5,2850], + [119.934,120.174,56,34,1,0,76,1,2856], + [120.167,120.409,64,20,0,0,76,1.5,2861], + [120.405,120.651,68,22,0,0,76,2,2867], + [120.645,120.893,71,31,0,0,76,2.5,2872], + [120.893,121.381,72,37,0,0,77,0,2878], + [120.908,121.144,45,31,1,0,77,0,2879], + [121.137,121.389,52,32,1,0,77,0.5,2884], + [121.388,121.636,57,23,1,0,77,1,2890], + [121.631,121.877,64,22,0,0,77,1.5,2896], + [121.873,122.128,76,36,0,0,77,2,2902], + [122.128,122.381,75,31,0,0,77,2.5,2908], + [122.377,122.635,76,32,0,0,78,0,2914], + [122.628,122.888,75,31,0,0,78,0.5,2920], + [122.891,123.141,76,29,0,0,78,1,2926], + [123.145,123.392,71,23,0,0,78,1.5,2932], + [123.39,123.643,74,27,0,0,78,2,2938], + [123.638,123.894,72,26,0,0,78,2.5,2944], + [123.894,124.401,69,38,0,0,79,0,2950], + [123.902,124.153,45,27,1,0,79,0,2950], + [124.153,124.409,52,31,1,0,79,0.5,2956], + [124.406,124.668,57,22,1,0,79,1,2962], + [124.665,124.923,60,16,0,0,79,1.5,2968], + [124.92,125.189,64,29,0,0,79,2,2974], + [125.195,125.46,69,24,0,0,79,2.5,2981], + [125.458,126.013,71,34,0,0,80,0,2987], + [125.465,125.742,40,28,1,0,80,0,2987], + [125.736,126.021,52,32,1,0,80,0.5,2994], + [126.026,126.302,56,32,1,0,80,1,3001], + [126.291,126.58,64,36,0,0,80,1.5,3007], + [126.586,126.862,72,46,0,0,80,2,3014], + [126.862,127.125,71,47,0,0,80,2.5,3021], + [127.12,127.622,69,58,0,0,81,0,3027], + [127.128,128.563,45,32,10,0,81,0,3027], + [127.129,127.384,45,39,1,0,81,0,3027], + [127.381,127.63,45,48,1,0,81,0.5,3033], + [127.633,127.871,45,64,1,0,81,1,3039], + [127.871,128.106,45,67,1,0,81,1.5,3045], + [128.113,128.337,45,67,1,0,81,2,3050], + [128.341,128.563,45,82,1,0,81,2.5,3056], + [128.557,129.899,64,103,0,0,82,0,3061], + [128.558,128.787,45,81,1,0,82,0,3061], + [128.558,129.011,33,85,5,0,82,0,3061], + [128.558,129.899,67,102,0,1,82,0,3061], + [128.559,129.907,49,104,7,0,82,0,3061], + [128.56,129.907,73,90,2,0,82,0,3061], + [128.561,128.787,45,90,4,0,82,0,3061], + [128.562,129.907,45,105,9,0,82,0,3061], + [128.562,129.899,70,104,0,2,82,0,3061], + [128.563,129.907,64,87,6,0,82,0,3061], + [128.563,129.899,73,101,0,3,82,0,3061], + [128.566,129.907,70,94,3,0,82,0,3061], + [128.567,129.907,55,107,7,1,82,0,3061], + [128.569,129.907,67,87,6,1,82,0,3061], + [128.571,129.907,33,90,8,0,82,0,3061], + [128.783,129.011,45,92,4,0,82,0.5,3066], + [128.791,129.011,45,81,1,0,82,0.5,3066], + [129.01,129.235,45,89,4,0,82,1,3072], + [129.016,129.459,33,91,5,0,82,1,3072], + [129.02,129.235,45,82,1,0,82,1,3072], + [129.236,129.459,45,89,4,0,82,1.5,3077], + [129.237,129.459,45,87,1,0,82,1.5,3077], + [129.456,129.907,33,85,5,0,82,2,3082], + [129.457,129.683,45,92,4,0,82,2,3082], + [129.458,129.683,45,80,1,0,82,2,3082], + [129.68,129.907,45,90,1,0,82,2.5,3088], + [129.685,129.907,45,86,4,0,82,2.5,3088], + [129.896,130.794,69,89,0,1,83,0,3093], + [129.898,130.794,65,95,0,0,83,0,3093], + [129.901,130.794,74,92,0,2,83,0,3093], + [129.903,131.25,62,91,6,0,83,0,3093], + [129.905,131.25,50,91,7,0,83,0,3093], + [129.906,131.25,65,93,6,1,83,0,3093], + [129.906,130.354,33,87,5,0,83,0,3093], + [129.908,130.131,45,80,1,0,83,0,3093], + [129.908,131.25,53,90,7,1,83,0,3093], + [129.909,130.802,74,88,2,0,83,0,3093], + [129.91,130.354,45,91,9,0,83,0,3093], + [129.911,130.131,45,90,4,0,83,0,3093], + [129.911,130.802,69,93,3,0,83,0,3093], + [130.13,130.354,45,86,4,0,83,0.5,3098], + [130.135,130.354,45,81,1,0,83,0.5,3098], + [130.353,130.578,45,85,1,0,83,1,3104], + [130.354,130.802,33,92,5,0,83,1,3104], + [130.36,130.578,45,91,4,0,83,1,3104], + [130.583,130.802,45,90,4,0,83,1.5,3109], + [130.586,130.802,45,79,1,0,83,1.5,3109], + [130.797,131.018,76,93,0,1,83,2,3114], + [130.797,131.026,45,86,4,0,83,2,3114], + [130.797,131.018,73,84,0,0,83,2,3114], + [130.799,131.25,33,91,5,0,83,2,3114], + [130.804,131.026,45,81,1,0,83,2,3114], + [130.805,131.026,73,89,3,0,83,2,3114], + [130.807,131.026,76,88,2,0,83,2,3114], + [131.015,131.242,77,86,0,1,83,2.5,3119], + [131.016,131.242,74,88,0,0,83,2.5,3119], + [131.019,131.25,45,76,1,0,83,2.5,3119], + [131.024,131.25,77,96,2,0,83,2.5,3120], + [131.028,131.25,74,90,3,0,83,2.5,3120], + [131.031,131.25,45,89,4,0,83,2.5,3120], + [131.243,132.593,33,92,8,0,84,0,3125], + [131.243,132.137,68,94,0,0,84,0,3125], + [131.243,131.474,45,90,4,0,84,0,3125], + [131.244,132.137,77,95,0,2,84,0,3125], + [131.245,132.593,65,89,6,1,84,0,3125], + [131.247,132.593,62,90,6,0,84,0,3125], + [131.248,132.137,74,90,0,1,84,0,3125], + [131.249,132.145,77,88,2,0,84,0,3125], + [131.249,131.474,45,82,1,0,84,0,3125], + [131.25,132.145,74,87,3,0,84,0,3125], + [131.253,132.593,50,88,7,0,84,0,3125], + [131.254,132.593,56,90,7,1,84,0,3125], + [131.254,132.593,45,92,9,0,84,0,3125], + [131.255,131.698,33,90,5,0,84,0,3125], + [131.468,131.698,45,84,1,0,84,0.5,3130], + [131.475,131.698,45,85,4,0,84,0.5,3130], + [131.693,131.922,45,88,4,0,84,1,3136], + [131.693,131.922,45,83,1,0,84,1,3136], + [131.701,132.145,33,95,5,0,84,1,3136], + [131.922,132.145,45,77,1,0,84,1.5,3141], + [131.928,132.145,45,93,4,0,84,1.5,3141], + [132.133,132.585,68,93,0,0,84,2,3146], + [132.135,132.585,77,91,0,2,84,2,3146], + [132.138,132.585,74,84,0,1,84,2,3146], + [132.144,132.593,74,93,3,0,84,2,3146], + [132.145,132.593,77,87,2,0,84,2,3146], + [132.147,132.593,33,88,5,0,84,2,3146], + [132.148,132.369,45,78,1,0,84,2,3146], + [132.148,132.369,45,89,4,0,84,2,3146], + [132.363,132.593,45,85,4,0,84,2.5,3152], + [132.373,132.593,45,77,1,0,84,2.5,3152], + [132.584,133.929,76,86,0,2,85,0,3157], + [132.586,133.929,69,85,0,0,85,0,3157], + [132.587,133.929,72,87,0,1,85,0,3157], + [132.587,133.937,48,93,7,0,85,0,3157], + [132.587,133.937,64,88,6,1,85,0,3157], + [132.59,133.041,33,88,5,0,85,0,3157], + [132.591,133.041,45,88,9,0,85,0,3157], + [132.593,133.937,60,94,6,0,85,0,3157], + [132.595,132.817,45,79,1,0,85,0,3157], + [132.595,132.817,45,90,4,0,85,0,3157], + [132.596,133.937,52,87,7,1,85,0,3157], + [132.599,133.937,76,86,2,0,85,0,3157], + [132.6,133.937,72,90,3,0,85,0,3157], + [132.81,133.041,45,90,4,0,85,0.5,3162], + [132.811,133.041,45,79,1,0,85,0.5,3162], + [133.036,133.265,45,90,9,0,85,1,3168], + [133.041,133.265,45,88,4,0,85,1,3168], + [133.043,133.265,45,83,1,0,85,1,3168], + [133.044,133.489,33,89,5,0,85,1,3168], + [133.261,133.489,45,79,1,0,85,1.5,3173], + [133.266,133.489,45,95,9,0,85,1.5,3173], + [133.267,133.489,45,91,4,0,85,1.5,3173], + [133.487,133.713,45,89,1,0,85,2,3178], + [133.491,133.937,33,93,5,0,85,2,3178], + [133.496,133.713,45,87,4,0,85,2,3178], + [133.498,133.937,45,85,9,0,85,2,3179], + [133.707,133.937,45,79,1,0,85,2.5,3184], + [133.711,133.937,45,93,4,0,85,2.5,3184], + [133.925,134.824,65,71,0,0,86,0,3189], + [133.928,134.824,74,77,0,1,86,0,3189], + [133.93,134.384,38,76,5,0,86,0,3189], + [133.932,134.832,65,67,3,0,86,0,3189], + [133.934,134.832,74,75,2,0,86,0,3189], + [133.936,134.16,38,66,1,0,86,0,3189], + [133.937,135.28,38,72,8,0,86,0,3189], + [133.938,135.28,65,72,6,1,86,0,3189], + [133.938,135.28,62,75,6,0,86,0,3189], + [133.94,134.16,50,73,4,0,86,0,3189], + [133.944,134.16,45,66,1,1,86,0,3189], + [134.157,134.384,45,67,1,1,86,0.5,3194], + [134.16,134.384,38,63,1,0,86,0.5,3194], + [134.16,134.384,50,74,4,0,86,0.5,3194], + [134.379,134.608,50,70,4,0,86,1,3200], + [134.383,134.608,38,68,1,0,86,1,3200], + [134.384,134.608,45,66,1,1,86,1,3200], + [134.388,134.832,38,76,5,0,86,1,3200], + [134.606,134.832,38,69,1,0,86,1.5,3205], + [134.609,134.832,50,71,4,0,86,1.5,3205], + [134.609,134.832,45,70,1,1,86,1.5,3205], + [134.821,135.048,64,76,0,0,86,2,3210], + [134.823,135.056,50,73,4,0,86,2,3210], + [134.825,135.056,64,77,3,0,86,2,3210], + [134.83,135.048,72,68,0,1,86,2,3210], + [134.83,135.056,38,67,1,0,86,2,3210], + [134.833,135.056,72,72,2,0,86,2,3210], + [134.834,135.056,45,69,1,1,86,2,3210], + [134.834,135.28,38,74,5,0,86,2,3210], + [135.047,135.272,62,72,0,0,86,2.5,3215], + [135.051,135.272,71,78,0,1,86,2.5,3216], + [135.052,135.28,50,78,4,0,86,2.5,3216], + [135.053,135.28,62,73,3,0,86,2.5,3216], + [135.053,135.28,71,74,2,0,86,2.5,3216], + [135.053,135.28,38,68,1,0,86,2.5,3216], + [135.057,135.28,45,67,1,1,86,2.5,3216], + [135.268,136.167,69,79,0,2,87,0,3221], + [135.273,136.167,60,81,0,0,87,0,3221], + [135.276,136.175,66,78,3,0,87,0,3221], + [135.276,136.623,39,73,8,0,87,0,3221], + [135.277,136.167,66,79,0,1,87,0,3221], + [135.277,135.504,51,72,4,0,87,0,3221], + [135.278,135.504,45,70,1,1,87,0,3221], + [135.281,136.175,69,78,2,0,87,0,3221], + [135.282,136.623,66,74,6,1,87,0,3221], + [135.282,136.623,60,75,6,0,87,0,3221], + [135.284,135.504,39,69,1,0,87,0,3221], + [135.286,135.728,39,76,5,0,87,0,3221], + [135.495,135.728,39,65,1,0,87,0.5,3226], + [135.497,135.728,45,70,1,1,87,0.5,3226], + [135.507,135.728,51,72,4,0,87,0.5,3226], + [135.72,135.951,51,74,4,0,87,1,3231], + [135.723,135.951,45,63,1,1,87,1,3231], + [135.725,135.951,39,70,1,0,87,1,3232], + [135.728,136.175,39,77,5,0,87,1,3232], + [135.949,136.175,51,74,4,0,87,1.5,3237], + [135.95,136.175,45,69,1,1,87,1.5,3237], + [135.955,136.175,39,71,1,0,87,1.5,3237], + [136.169,136.615,69,79,0,1,87,2,3242], + [136.171,136.623,69,71,2,0,87,2,3242], + [136.173,136.623,39,75,5,0,87,2,3242], + [136.173,136.399,51,72,4,0,87,2,3242], + [136.176,136.615,60,75,0,0,87,2,3242], + [136.179,136.399,39,66,1,0,87,2,3242], + [136.181,136.399,45,68,1,1,87,2,3242], + [136.183,136.623,60,77,3,0,87,2,3242], + [136.395,136.623,51,72,4,0,87,2.5,3248], + [136.398,136.623,45,65,1,1,87,2.5,3248], + [136.401,136.623,39,71,1,0,87,2.5,3248], + [136.614,137.063,60,74,0,0,88,0,3253], + [136.615,137.063,69,75,0,1,88,0,3253], + [136.617,136.847,40,72,1,0,88,0,3253], + [136.618,137.519,64,79,6,1,88,0,3253], + [136.618,136.847,52,76,4,0,88,0,3253], + [136.619,137.519,60,81,6,0,88,0,3253], + [136.623,137.966,40,73,8,0,88,0,3253], + [136.623,136.847,45,68,1,1,88,0,3253], + [136.625,137.071,52,97,9,0,88,0,3253], + [136.625,137.071,69,73,2,0,88,0,3253], + [136.628,137.071,60,76,3,0,88,0,3253], + [136.631,137.071,40,70,5,0,88,0,3253], + [136.845,137.071,40,69,1,0,88,0.5,3258], + [136.845,137.071,45,61,1,1,88,0.5,3258], + [136.846,137.071,52,73,4,0,88,0.5,3258], + [137.058,137.511,72,69,0,1,88,1,3263], + [137.061,137.511,64,75,0,0,88,1,3263], + [137.064,137.519,40,77,5,0,88,1,3263], + [137.064,137.295,45,70,1,1,88,1,3263], + [137.068,137.519,72,77,2,0,88,1,3264], + [137.069,137.295,52,73,4,0,88,1,3264], + [137.073,137.519,64,73,3,0,88,1,3264], + [137.078,137.295,40,69,1,0,88,1,3264], + [137.293,137.519,40,65,1,0,88,1.5,3269], + [137.294,137.519,52,74,4,0,88,1.5,3269], + [137.295,137.519,45,68,1,1,88,1.5,3269], + [137.506,137.958,62,78,0,0,88,2,3274], + [137.512,137.966,40,73,5,0,88,2,3274], + [137.513,137.742,40,75,1,0,88,2,3274], + [137.514,137.742,52,72,4,0,88,2,3274], + [137.514,137.958,71,73,0,1,88,2,3274], + [137.515,137.742,44,72,1,1,88,2,3274], + [137.517,137.966,52,93,9,0,88,2,3274], + [137.519,137.966,62,72,3,0,88,2,3274], + [137.522,137.966,59,71,6,0,88,2,3274], + [137.524,137.966,71,79,2,0,88,2,3274], + [137.524,137.966,62,70,6,1,88,2,3274], + [137.742,137.966,44,73,1,1,88,2.5,3280], + [137.743,137.966,52,73,4,0,88,2.5,3280], + [137.75,137.966,40,71,1,0,88,2.5,3280], + [137.959,139.362,52,77,7,1,89,0,3285], + [137.959,139.354,60,75,0,0,89,0,3285], + [137.962,139.354,69,77,0,1,89,0,3285], + [137.963,139.362,60,74,6,1,89,0,3285], + [137.964,139.362,33,75,8,0,89,0,3285], + [137.964,138.422,33,72,5,0,89,0,3285], + [137.967,139.362,57,78,6,0,89,0,3285], + [137.968,139.362,48,73,7,0,89,0,3285], + [137.968,139.362,45,90,9,0,89,0,3285], + [137.968,139.362,60,79,3,0,89,0,3285], + [137.968,138.192,45,77,4,0,89,0,3285], + [137.969,138.192,33,69,1,0,89,0,3285], + [137.969,138.192,45,67,1,1,89,0,3285], + [137.97,139.362,69,81,2,0,89,0,3285], + [138.19,138.422,45,66,1,0,89,0.5,3290], + [138.196,138.422,45,74,4,0,89,0.5,3290], + [138.419,138.895,33,72,5,0,89,1,3296], + [138.419,138.657,45,70,1,0,89,1,3296], + [138.425,138.657,45,75,4,0,89,1,3296], + [138.652,138.895,45,73,4,0,89,1.5,3301], + [138.652,138.895,45,74,1,0,89,1.5,3301], + [138.893,139.134,45,68,4,0,89,2,3307], + [138.896,139.134,45,69,1,0,89,2,3307], + [138.898,139.362,33,75,5,0,89,2,3307], + [139.134,139.362,45,69,4,0,89,2.5,3313], + [139.137,139.362,45,70,1,0,89,2.5,3313], + [139.352,140.699,64,103,0,0,90,0,3318], + [139.352,140.699,73,107,0,3,90,0,3318], + [139.352,139.586,45,90,4,0,90,0,3318], + [139.355,140.699,67,104,0,1,90,0,3318], + [139.358,140.707,70,94,3,0,90,0,3318], + [139.359,140.699,70,104,0,2,90,0,3318], + [139.361,140.707,67,85,6,1,90,0,3318], + [139.362,140.707,64,89,6,0,90,0,3318], + [139.362,140.707,49,103,7,0,90,0,3318], + [139.362,140.707,45,124,9,0,90,0,3318], + [139.364,140.707,55,99,7,1,90,0,3318], + [139.364,140.707,73,88,2,0,90,0,3318], + [139.365,140.707,33,89,8,0,90,0,3318], + [139.367,139.586,45,78,1,0,90,0,3318], + [139.367,139.81,33,93,5,0,90,0,3318], + [139.587,139.81,45,86,4,0,90,0.5,3323], + [139.591,139.81,45,86,1,0,90,0.5,3324], + [139.805,140.034,45,86,4,0,90,1,3329], + [139.812,140.034,45,80,1,0,90,1,3329], + [139.818,140.259,33,89,5,0,90,1,3329], + [140.034,140.259,45,87,4,0,90,1.5,3334], + [140.036,140.259,45,76,1,0,90,1.5,3334], + [140.249,140.707,33,94,5,0,90,2,3339], + [140.249,140.483,45,86,1,0,90,2,3339], + [140.257,140.483,45,93,4,0,90,2,3339], + [140.482,140.707,45,82,1,0,90,2.5,3345], + [140.485,140.707,45,87,4,0,90,2.5,3345], + [140.699,141.598,69,94,0,1,91,0,3350], + [140.7,141.156,33,94,5,0,91,0,3350], + [140.701,141.598,65,87,0,0,91,0,3350], + [140.704,142.056,53,95,7,1,91,0,3350], + [140.706,141.156,45,114,9,0,91,0,3350], + [140.707,140.932,45,75,1,0,91,0,3350], + [140.707,141.598,74,92,0,2,91,0,3350], + [140.707,142.056,62,86,6,0,91,0,3350], + [140.709,141.606,69,89,3,0,91,0,3350], + [140.71,142.056,65,92,6,1,91,0,3350], + [140.712,140.932,45,87,4,0,91,0,3350], + [140.715,142.056,50,89,7,0,91,0,3350], + [140.717,141.606,74,87,2,0,91,0,3350], + [140.933,141.156,45,95,4,0,91,0.5,3356], + [140.933,141.156,45,88,1,0,91,0.5,3356], + [141.154,141.381,45,89,1,0,91,1,3361], + [141.157,141.381,45,89,4,0,91,1,3361], + [141.161,141.606,33,93,5,0,91,1,3361], + [141.374,141.606,45,81,1,0,91,1.5,3366], + [141.38,141.606,45,90,4,0,91,1.5,3366], + [141.597,141.823,73,88,0,0,91,2,3371], + [141.601,141.823,76,90,0,1,91,2,3371], + [141.602,141.831,45,84,1,0,91,2,3371], + [141.605,141.831,73,92,3,0,91,2,3372], + [141.606,141.831,45,88,4,0,91,2,3372], + [141.607,141.831,76,90,2,0,91,2,3372], + [141.609,142.056,33,90,5,0,91,2,3372], + [141.821,142.048,74,90,0,0,91,2.5,3377], + [141.829,142.056,74,90,3,0,91,2.5,3377], + [141.829,142.048,77,92,0,1,91,2.5,3377], + [141.834,142.056,45,84,4,0,91,2.5,3377], + [141.834,142.056,45,84,1,0,91,2.5,3377], + [141.835,142.056,77,91,2,0,91,2.5,3377], + [142.043,142.948,77,89,0,1,92,0,3382], + [142.046,142.948,74,97,0,0,92,0,3382], + [142.05,142.956,77,91,2,0,92,0,3382], + [142.052,142.281,45,81,1,0,92,0,3382], + [142.053,143.407,65,87,6,1,92,0,3382], + [142.053,143.407,50,85,7,0,92,0,3382], + [142.054,143.407,62,88,6,0,92,0,3382], + [142.054,143.407,53,86,7,1,92,0,3382], + [142.057,143.407,33,89,8,0,92,0,3382], + [142.058,142.281,45,95,4,0,92,0,3382], + [142.06,142.506,33,90,5,0,92,0,3382], + [142.06,142.506,45,109,9,0,92,0,3382], + [142.065,142.956,74,94,3,0,92,0,3383], + [142.281,142.506,45,81,1,0,92,0.5,3388], + [142.282,142.506,45,87,4,0,92,0.5,3388], + [142.501,142.731,45,88,4,0,92,1,3393], + [142.504,142.731,45,83,1,0,92,1,3393], + [142.504,142.956,33,85,5,0,92,1,3393], + [142.507,142.731,45,108,9,0,92,1,3393], + [142.725,142.956,45,88,4,0,92,1.5,3398], + [142.727,142.956,45,109,9,0,92,1.5,3398], + [142.73,142.956,45,82,1,0,92,1.5,3398], + [142.948,143.399,74,91,0,0,92,2,3404], + [142.948,143.399,77,95,0,1,92,2,3404], + [142.951,143.407,33,88,5,0,92,2,3404], + [142.955,143.182,45,85,1,0,92,2,3404], + [142.956,143.407,45,104,9,0,92,2,3404], + [142.956,143.407,74,92,3,0,92,2,3404], + [142.956,143.182,45,90,4,0,92,2,3404], + [142.958,143.407,77,95,2,0,92,2,3404], + [143.177,143.407,45,88,4,0,92,2.5,3409], + [143.189,143.407,45,82,1,0,92,2.5,3409], + [143.397,144.754,74,92,0,0,93,0,3414], + [143.398,144.754,77,89,0,1,93,0,3414], + [143.404,143.633,46,81,1,0,93,0,3414], + [143.404,143.633,46,95,4,0,93,0,3414], + [143.406,144.762,34,95,8,0,93,0,3414], + [143.406,144.762,50,87,7,0,93,0,3414], + [143.406,143.859,34,86,5,0,93,0,3414], + [143.408,144.762,77,85,2,0,93,0,3414], + [143.409,144.762,74,90,3,0,93,0,3415], + [143.412,144.762,65,90,6,1,93,0,3415], + [143.414,144.762,53,90,7,1,93,0,3415], + [143.416,144.762,62,90,6,0,93,0,3415], + [143.627,143.859,46,90,4,0,93,0.5,3420], + [143.634,143.859,46,85,1,0,93,0.5,3420], + [143.858,144.084,46,90,1,0,93,1,3425], + [143.859,144.084,46,90,4,0,93,1,3425], + [143.866,144.31,34,95,5,0,93,1,3425], + [144.082,144.31,46,85,1,0,93,1.5,3431], + [144.085,144.31,46,92,4,0,93,1.5,3431], + [144.31,144.536,46,84,1,0,93,2,3436], + [144.311,144.536,46,96,4,0,93,2,3436], + [144.317,144.762,34,98,5,0,93,2,3436], + [144.532,144.762,46,88,1,0,93,2.5,3441], + [144.538,144.762,46,94,4,0,93,2.5,3441], + [144.755,145.66,67,93,0,0,94,0,3447], + [144.756,145.66,75,90,0,1,94,0,3447], + [144.757,146.121,67,90,6,1,94,0,3447], + [144.76,145.668,75,96,2,0,94,0,3447], + [144.76,145.668,67,95,3,0,94,0,3447], + [144.761,145.215,34,93,5,0,94,0,3447], + [144.762,146.121,34,91,8,0,94,0,3447], + [144.764,144.989,46,90,4,0,94,0,3447], + [144.766,144.989,46,79,1,0,94,0,3447], + [144.766,146.121,63,96,6,0,94,0,3447], + [144.768,146.121,55,88,7,1,94,0,3447], + [144.769,146.121,51,90,7,0,94,0,3447], + [144.987,145.215,46,97,4,0,94,0.5,3452], + [144.989,145.215,46,83,1,0,94,0.5,3452], + [145.217,145.441,46,101,4,0,94,1,3458], + [145.217,145.441,46,86,1,0,94,1,3458], + [145.218,145.668,34,98,5,0,94,1,3458], + [145.441,145.668,46,94,4,0,94,1.5,3463], + [145.446,145.668,46,85,1,0,94,1.5,3463], + [145.658,145.886,74,98,0,1,94,2,3468], + [145.658,145.886,65,94,0,0,94,2,3468], + [145.663,145.894,46,94,1,0,94,2,3468], + [145.664,145.894,65,99,3,0,94,2,3468], + [145.671,145.894,74,94,2,0,94,2,3468], + [145.671,146.121,34,97,5,0,94,2,3468], + [145.674,145.894,46,96,4,0,94,2,3468], + [145.882,146.113,63,98,0,0,94,2.5,3473], + [145.883,146.113,72,97,0,1,94,2.5,3473], + [145.886,146.121,63,98,3,0,94,2.5,3473], + [145.887,146.121,46,86,1,0,94,2.5,3474], + [145.896,146.121,72,100,2,0,94,2.5,3474], + [145.901,146.121,46,98,4,0,94,2.5,3474], + [146.109,147.021,70,99,0,2,95,0,3479], + [146.112,147.021,62,96,0,0,95,0,3479], + [146.113,147.029,70,102,2,0,95,0,3479], + [146.113,146.348,46,104,4,0,95,0,3479], + [146.115,147.483,34,98,8,0,95,0,3479], + [146.115,147.029,65,102,3,0,95,0,3479], + [146.116,147.021,65,98,0,1,95,0,3479], + [146.121,147.483,53,102,7,1,95,0,3479], + [146.121,147.483,65,93,6,1,95,0,3479], + [146.123,147.483,50,101,7,0,95,0,3479], + [146.125,146.575,34,97,5,0,95,0,3479], + [146.125,147.483,62,103,6,0,95,0,3479], + [146.128,146.348,46,93,1,0,95,0,3479], + [146.341,146.575,46,97,1,0,95,0.5,3484], + [146.348,146.575,46,96,4,0,95,0.5,3484], + [146.572,146.801,46,90,1,0,95,1,3490], + [146.573,146.801,46,103,4,0,95,1,3490], + [146.583,147.029,34,100,5,0,95,1,3490], + [146.798,147.029,46,91,1,0,95,1.5,3495], + [146.8,147.029,46,98,4,0,95,1.5,3495], + [147.02,147.475,65,95,0,1,95,2,3500], + [147.022,147.475,69,100,0,2,95,2,3501], + [147.022,147.475,62,96,0,0,95,2,3501], + [147.025,147.483,65,101,3,0,95,2,3501], + [147.028,147.256,46,95,1,0,95,2,3501], + [147.03,147.483,34,103,5,0,95,2,3501], + [147.03,147.256,46,103,4,0,95,2,3501], + [147.032,147.483,69,103,2,0,95,2,3501], + [147.254,147.483,46,101,4,0,95,2.5,3506], + [147.259,147.483,46,93,1,0,95,2.5,3506], + [147.472,148.423,65,100,0,1,96,0,3511], + [147.476,148.423,68,105,0,2,96,0,3511], + [147.476,148.936,35,100,8,0,96,0,3511], + [147.476,148.936,62,100,6,0,96,0,3511], + [147.479,148.423,62,104,0,0,96,0,3511], + [147.48,147.712,47,93,1,0,96,0,3511], + [147.48,147.947,35,101,5,0,96,0,3511], + [147.481,147.947,52,109,9,0,96,0,3511], + [147.483,148.936,65,103,6,1,96,0,3511], + [147.484,147.712,47,102,4,0,96,0,3512], + [147.487,148.431,65,102,3,0,96,0,3512], + [147.487,148.936,53,105,7,1,96,0,3512], + [147.487,148.936,50,106,7,0,96,0,3512], + [147.489,148.431,68,103,2,0,96,0,3512], + [147.71,147.947,47,106,4,0,96,0.5,3517], + [147.714,147.947,47,96,1,0,96,0.5,3517], + [147.942,148.186,47,98,1,0,96,1,3522], + [147.944,148.431,35,108,5,0,96,1,3522], + [147.945,148.186,47,104,4,0,96,1,3522], + [147.95,148.186,52,104,9,0,96,1,3523], + [148.185,148.431,47,106,4,0,96,1.5,3528], + [148.189,148.431,47,89,1,0,96,1.5,3528], + [148.19,148.431,52,104,9,0,96,1.5,3528], + [148.422,148.928,68,101,0,2,96,2,3534], + [148.423,148.928,65,107,0,1,96,2,3534], + [148.424,148.928,62,109,0,0,96,2,3534], + [148.427,148.936,68,104,2,0,96,2,3534], + [148.43,148.936,35,102,5,0,96,2,3534], + [148.43,148.681,47,100,4,0,96,2,3534], + [148.432,148.936,52,104,9,0,96,2,3534], + [148.434,148.936,65,107,3,0,96,2,3534], + [148.437,148.681,47,98,1,0,96,2,3534], + [148.682,148.936,47,110,4,0,96,2.5,3540], + [148.684,148.936,47,96,1,0,96,2.5,3540], + [148.923,150.014,60,121,0,0,97,0,3546], + [148.928,150.014,69,114,0,2,97,0,3546], + [148.928,150.014,64,113,0,1,97,0,3546], + [148.932,150.022,33,118,5,0,97,0,3546], + [148.932,150.022,64,116,6,1,97,0,3546], + [148.933,150.022,45,116,9,0,97,0,3546], + [148.935,150.022,48,118,7,0,97,0,3546], + [148.936,150.022,52,114,7,1,97,0,3546], + [148.937,150.022,64,104,3,0,97,0,3546], + [148.939,150.022,45,118,4,0,97,0,3546], + [148.94,150.022,45,107,1,0,97,0,3546], + [148.941,150.022,69,103,2,0,97,0,3546], + [148.942,150.022,60,110,6,0,97,0,3546], + [148.945,150.022,33,121,8,0,97,0,3546], + [150.59,151.187,64,51,0,0,98,0,3585], + [150.595,151.195,71,45,2,0,98,0,3586], + [150.596,151.187,71,43,0,1,98,0,3586], + [150.603,151.195,52,42,4,0,98,0,3586], + [150.603,151.195,40,41,5,0,98,0,3586], + [150.606,151.195,64,46,3,0,98,0,3586], + [150.606,151.195,40,46,8,0,98,0,3586], + [150.607,151.195,52,75,9,0,98,0,3586], + [150.61,151.195,56,40,1,1,98,0,3586], + [150.615,151.195,52,41,1,0,98,0,3586], + [152.898,153.076,57,23,0,0,99,0,3640], + [152.904,153.439,33,36,1,0,99,0,3641], + [153.083,153.254,60,19,0,0,99,0.333,3645], + [153.253,153.431,64,22,0,0,99,0.667,3649], + [153.432,153.608,69,26,0,0,99,1,3653], + [153.606,153.784,72,28,0,0,99,1.333,3657], + [153.791,153.96,76,30,0,0,99,1.667,3662], + [153.959,154.135,74,31,0,0,99,2,3666], + [153.971,154.492,64,18,1,2,99,2,3666], + [153.973,154.492,57,13,1,0,99,2,3666], + [153.975,154.492,60,23,1,1,99,2,3666], + [154.136,154.31,72,31,0,0,99,2.333,3670], + [154.31,154.484,71,25,0,0,99,2.667,3674], + [154.485,154.658,69,29,0,0,100,0,3678], + [154.489,155.012,57,21,1,0,100,0,3678], + [154.491,155.012,64,24,1,2,100,0,3678], + [154.491,155.012,60,18,1,1,100,0,3678], + [154.657,154.831,72,24,0,0,100,0.333,3682], + [154.827,155.004,76,28,0,0,100,0.667,3686], + [155.006,155.176,81,37,0,0,100,1,3691], + [155.177,155.347,84,30,0,0,100,1.333,3695], + [155.348,155.519,88,35,0,0,100,1.667,3699], + [155.517,155.689,86,29,0,0,100,2,3703], + [155.524,156.037,64,21,1,2,100,2,3703], + [155.524,156.037,57,17,1,0,100,2,3703], + [155.531,156.037,60,20,1,1,100,2,3703], + [155.694,155.86,84,30,0,0,100,2.333,3707], + [155.86,156.029,83,29,0,0,100,2.667,3711], + [156.032,156.544,57,16,1,0,101,0,3715], + [156.033,156.544,64,20,1,2,101,0,3715], + [156.035,156.199,81,31,0,0,101,0,3715], + [156.036,156.544,60,13,1,1,101,0,3715], + [156.197,156.368,84,27,0,0,101,0.333,3719], + [156.369,156.536,88,30,0,0,101,0.667,3723], + [156.537,156.705,93,30,0,0,101,1,3727], + [156.704,156.873,96,32,0,0,101,1.333,3731], + [156.874,157.041,100,35,0,0,101,1.667,3735], + [157.036,157.208,98,30,0,0,101,2,3739], + [157.04,157.55,64,13,1,2,101,2,3739], + [157.046,157.55,60,14,1,1,101,2,3739], + [157.054,157.55,57,22,1,0,101,2,3739], + [157.2,157.375,96,36,0,0,101,2.333,3743], + [157.383,157.542,95,31,0,0,101,2.667,3747], + [157.534,157.709,94,31,0,0,102,0,3751], + [157.547,158.056,57,14,1,0,102,0,3751], + [157.551,158.056,64,17,1,2,102,0,3751], + [157.556,158.056,60,15,1,1,102,0,3751], + [157.708,157.878,93,25,0,0,102,0.333,3755], + [157.874,158.048,92,25,0,0,102,0.667,3759], + [158.045,158.219,91,26,0,0,102,1,3763], + [158.229,158.391,90,32,0,0,102,1.333,3767], + [158.398,158.565,89,25,0,0,102,1.667,3771], + [158.564,158.74,88,26,0,0,102,2,3775], + [158.738,158.916,87,29,0,0,102,2.333,3779], + [158.913,159.094,86,29,0,0,102,2.667,3784], + [159.092,159.275,85,31,0,0,103,0,3788], + [159.268,159.46,84,34,0,0,103,0.333,3792], + [159.465,159.649,83,30,0,0,103,0.667,3797], + [159.652,159.842,82,28,0,0,103,1,3801], + [159.842,160.041,81,29,0,0,103,1.333,3806], + [160.044,160.245,80,35,0,0,103,1.667,3811], + [160.245,160.453,79,34,0,0,103,2,3815], + [160.452,160.659,78,31,0,0,103,2.333,3820], + [160.661,160.993,77,34,0,0,103,2.667,3825], + [160.991,161.256,76,52,0,0,104,0,3833], + [161.261,161.518,75,45,0,0,104,0.5,3840], + [161.513,161.779,76,49,0,0,104,1,3846], + [161.786,162.04,71,44,0,0,104,1.5,3852], + [162.046,162.299,74,41,0,0,104,2,3858], + [162.289,162.558,72,45,0,0,104,2.5,3864], + [162.559,163.074,69,46,0,0,105,0,3870], + [162.567,162.825,45,42,1,0,105,0,3871], + [162.818,163.082,52,45,1,0,105,0.5,3877], + [163.078,163.339,57,45,1,0,105,1,3883], + [163.329,163.587,60,32,0,0,105,1.5,3889], + [163.586,163.842,64,35,0,0,105,2,3895], + [163.843,164.097,69,44,0,0,105,2.5,3901], + [164.098,164.61,71,50,0,0,106,0,3907], + [164.107,164.36,40,39,1,0,106,0,3907], + [164.359,164.618,52,44,1,0,106,0.5,3913], + [164.623,164.877,56,41,1,0,106,1,3920], + [164.869,165.131,64,29,0,0,106,1.5,3925], + [165.127,165.396,68,36,0,0,106,2,3932], + [165.398,165.662,71,43,0,0,106,2.5,3938], + [165.658,166.209,72,49,0,0,107,0,3944], + [165.673,165.941,45,46,1,0,107,0,3945], + [165.938,166.217,52,39,1,0,107,0.5,3951], + [166.216,166.499,57,40,1,0,107,1,3958], + [166.49,166.777,64,39,0,0,107,1.5,3964], + [166.78,167.056,76,40,0,0,107,2,3971], + [167.06,167.324,75,41,0,0,107,2.5,3978], + [167.317,167.587,76,46,0,0,108,0,3984], + [167.592,167.85,75,44,0,0,108,0.5,3990], + [167.85,168.113,76,45,0,0,108,1,3996], + [168.119,168.377,71,37,0,0,108,1.5,4003], + [168.375,168.64,74,43,0,0,108,2,4009], + [168.645,168.903,72,44,0,0,108,2.5,4015], + [168.904,169.429,69,45,0,0,109,0,4022], + [168.908,169.174,45,45,1,0,109,0,4022], + [169.168,169.437,52,49,1,0,109,0.5,4028], + [169.434,169.7,57,42,1,0,109,1,4034], + [169.692,169.956,60,29,0,0,109,1.5,4040], + [169.953,170.219,64,35,0,0,109,2,4046], + [170.223,170.482,69,43,0,0,109,2.5,4053], + [170.481,171.021,71,46,0,0,110,0,4059], + [170.491,170.756,40,41,1,0,110,0,4059], + [170.752,171.029,52,46,1,0,110,0.5,4066], + [171.034,171.308,56,41,1,0,110,1,4072], + [171.301,171.587,64,37,0,0,110,1.5,4079], + [171.591,171.881,72,38,0,0,110,2,4085], + [171.877,172.183,71,42,0,0,110,2.5,4092], + [172.184,172.783,69,36,0,0,111,0,4100], + [172.193,172.494,45,35,1,0,111,0,4100], + [172.495,172.791,52,47,1,0,111,0.5,4107], + [172.794,173.083,57,45,1,0,111,1,4114], + [173.078,173.36,71,37,0,0,111,1.5,4121], + [173.357,173.636,72,43,0,0,111,2,4128], + [173.632,174.017,74,45,0,0,111,2.5,4134], + [174.014,174.776,76,51,0,0,112,0,4143], + [174.027,174.279,48,43,1,0,112,0,4143], + [174.278,174.532,55,41,1,0,112,0.5,4149], + [174.527,174.784,60,36,1,0,112,1,4155], + [174.772,175.027,67,32,0,0,112,1.5,4161], + [175.027,175.277,77,44,0,0,112,2,4167], + [175.277,175.526,76,36,0,0,112,2.5,4173], + [175.525,176.27,74,53,0,0,113,0,4179], + [175.532,175.783,43,41,1,0,113,0,4179], + [175.779,176.031,55,44,1,0,113,0.5,4185], + [176.026,176.278,59,40,1,0,113,1,4191], + [176.277,176.516,65,32,0,0,113,1.5,4197], + [176.514,176.765,76,41,0,0,113,2,4203], + [176.763,177.018,74,41,0,0,113,2.5,4209], + [177.016,177.803,72,53,0,0,114,0,4215], + [177.022,177.284,45,46,1,0,114,0,4215], + [177.283,177.545,52,39,1,0,114,0.5,4221], + [177.547,177.811,57,44,1,0,114,1,4227], + [177.807,178.073,64,31,0,0,114,1.5,4234], + [178.069,178.348,74,47,0,0,114,2,4240], + [178.351,178.629,72,39,0,0,114,2.5,4246], + [178.631,179.206,71,42,0,0,115,0,4253], + [178.639,178.922,40,37,1,0,115,0,4253], + [178.916,179.214,52,30,1,0,115,0.5,4260], + [179.214,179.511,64,31,1,0,115,1,4267], + [179.506,179.806,64,19,0,0,115,1.5,4274], + [179.807,180.116,76,30,0,0,115,2,4281], + [180.128,180.442,64,28,1,0,115,2.5,4289], + [180.434,180.767,76,25,1,0,116,0,4296], + [180.756,181.243,76,31,0,0,116,0.5,4304], + [181.244,181.581,88,30,0,0,116,1,4315], + [181.593,181.92,75,24,1,0,116,1.5,4324], + [181.921,182.242,76,24,1,0,116,2,4331], + [182.236,182.547,75,26,0,0,116,2.5,4339], + [182.547,183.15,76,28,0,0,117,0,4346], + [182.862,183.158,75,28,1,0,117,0.5,4354], + [183.154,183.447,76,19,1,0,117,1,4361], + [183.444,183.72,75,27,0,0,117,1.5,4368], + [183.712,183.995,76,30,0,0,117,2,4374], + [183.998,184.34,75,29,0,0,117,2.5,4381], + [184.346,184.599,76,33,0,0,118,0,4389], + [184.601,184.857,75,28,0,0,118,0.5,4395], + [184.856,185.115,76,35,0,0,118,1,4401], + [185.114,185.373,71,32,0,0,118,1.5,4407], + [185.376,185.63,74,22,0,0,118,2,4414], + [185.631,185.888,72,27,0,0,118,2.5,4420], + [185.884,186.401,69,28,0,0,119,0,4426], + [185.888,186.153,45,29,1,0,119,0,4426], + [186.153,186.409,52,33,1,0,119,0.5,4432], + [186.404,186.666,57,33,1,0,119,1,4438], + [186.655,186.914,60,23,0,0,119,1.5,4444], + [186.914,187.17,64,23,0,0,119,2,4450], + [187.169,187.426,69,25,0,0,119,2.5,4456], + [187.423,187.937,71,34,0,0,120,0,4462], + [187.435,187.69,40,29,1,0,120,0,4463], + [187.691,187.945,52,28,1,0,120,0.5,4469], + [187.938,188.2,56,33,1,0,120,1,4475], + [188.2,188.447,64,21,0,0,120,1.5,4481], + [188.444,188.701,68,26,0,0,120,2,4487], + [188.7,188.956,71,33,0,0,120,2.5,4493], + [188.955,189.469,72,37,0,0,121,0,4499], + [188.966,189.219,45,31,1,0,121,0,4499], + [189.211,189.477,52,26,1,0,121,0.5,4505], + [189.477,189.736,57,29,1,0,121,1,4511], + [189.721,189.99,64,25,0,0,121,1.5,4517], + [189.991,190.255,76,30,0,0,121,2,4524], + [190.261,190.521,75,31,0,0,121,2.5,4530], + [190.527,190.79,76,28,0,0,122,0,4536], + [190.792,191.06,75,27,0,0,122,0.5,4543], + [191.06,191.332,76,28,0,0,122,1,4549], + [191.329,191.606,71,25,0,0,122,1.5,4555], + [191.606,191.881,74,33,0,0,122,2,4562], + [191.873,192.158,72,24,0,0,122,2.5,4568], + [192.164,192.724,69,34,0,0,123,0,4575], + [192.172,192.446,45,28,1,0,123,0,4576], + [192.446,192.732,52,27,1,0,123,0.5,4582], + [192.728,193.023,57,29,1,0,123,1,4589], + [193.008,193.312,60,24,0,0,123,1.5,4595], + [193.314,193.615,64,27,0,0,123,2,4603], + [193.617,193.925,69,25,0,0,123,2.5,4610], + [193.93,194.579,71,34,0,0,124,0,4617], + [193.932,194.252,40,32,1,0,124,0,4617], + [194.256,194.587,52,30,1,0,124,0.5,4625], + [194.589,194.939,56,26,1,0,124,1,4633], + [194.929,195.302,64,12,0,0,124,1.5,4641], + [195.301,195.693,72,17,0,0,124,2,4650], + [195.696,196.409,71,15,0,0,124,2.5,4659], + [196.405,198.98,69,27,0,0,125,0,4676], + [196.414,198.988,45,22,1,1,125,0,4677], + [196.423,198.988,33,29,1,0,125,0,4677], +]; From a530a33f976885eefc5fa9c8719e72f6b1db79e3 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:40:47 -0600 Subject: [PATCH 15/31] =?UTF-8?q?F=C3=BCr=20Elise:=20the=20soundtrack=20as?= =?UTF-8?q?=20a=20module=20without=20a=20program?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit probes/lib/fur-elise-soundtrack.ts holds the whole piece's sound (take, sections, whole and the section clips) so that the showcase can import it without the soundtrack probe's own program; probes/fur-elise.ts imports and plays it as before. The same six clips by name, and the timeline made again from it is the same to the byte. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- probes/fur-elise.ts | 70 ++--------------------------- probes/lib/fur-elise-soundtrack.ts | 71 ++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 66 deletions(-) create mode 100644 probes/lib/fur-elise-soundtrack.ts diff --git a/probes/fur-elise.ts b/probes/fur-elise.ts index 33527c7..c2713cf 100644 --- a/probes/fur-elise.ts +++ b/probes/fur-elise.ts @@ -10,74 +10,12 @@ // The timeline for the picture is probes/lib/fur-elise-timeline.ts (probes/lib/fur-elise-timeline-gen.mts). // // Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). Orchestra: VSCO 2 Community Edition by Versilian -// Studios (CC0). Instruments made by probes/lib/fur-elise-sound-gen.mts. +// Studios (CC0). Instruments made by probes/lib/fur-elise-sound-gen.mts. The sound itself is worked out in +// probes/lib/fur-elise-soundtrack.ts, which a showcase imports without this program. // // npx tsx scripts/sound-dump.mts probes/fur-elise.ts -import { music, type Instrument } from "trigscript/music"; -import piano from "./salamander-grand.samples"; -import violinsSet from "./vsco-violins.samples"; -import violasSet from "./vsco-violas.samples"; -import celliSet from "./vsco-celli-spic.samples"; -import bassesSet from "./vsco-bass-spic.samples"; -import hornsSet from "./vsco-horns.samples"; -import tromboneSet from "./vsco-trombone.samples"; -import tubaSet from "./vsco-tuba.samples"; -import timpaniSet from "./vsco-timpani.samples"; -import rollsSet from "./vsco-timpani-rolls.samples"; -import { piece } from "./lib/fur-elise-score"; - -/** The solo piano at −17 LUFS (the probe's choice), the storm at −15. */ -const PIANO_LUFS = -17; -const STORM_LUFS = -15; -/** The smaller room for the first half, and the hall (the probe's) for the storm and the end. */ -const ROOM = { decay: 0.7, damping: 0.55, predelay: 0.018 }; -const HALL = { decay: 0.84, damping: 0.5, predelay: 0.032 }; -const MASTER = (c: Clip) => c.filter("highpass", 28); -const BUS = (c: Clip) => MASTER(c).compress({ threshold: -20, ratio: 2, attack: 0.02, release: 0.25, knee: 6 }); -const QUALITY = 6; - -const written = piece(); -const grand = music.sampled(piano, { resonance: 0.07 }); -const orchestra = (name: string, instrument: Instrument, pan: number, volume: number, reverb: number) => - ({ instrument, notes: (written.orchestra as Record)[name], pan, volume, reverb }); - -/** The piece as played: one performance, so every note has its time in the whole. */ -export const take = music.perform({ meter: "3/8", bpm: 120, pickup: "1/8", tempo: written.tempo, holds: written.holds, humanize: { time: 0.004, velocity: 3, seed: 7 } }, { - right: { instrument: grand, notes: written.right, lead: 0.008, reverb: 0.24 }, - left: { instrument: grand, notes: written.left, velocity: 0.92 }, - violins: orchestra("violins", music.sampled(violinsSet), -0.45, 2.8, 0.32), - violas: orchestra("violas", music.sampled(violasSet), 0.2, 0.85, 0.32), - celli: orchestra("celli", music.sampled(celliSet), 0.4, 1.35, 0.25), - basses: orchestra("basses", music.sampled(bassesSet), 0.55, 1.55, 0.25), - horns: orchestra("horns", music.sampled(hornsSet), -0.2, 0.8, 0.4), - trombones: orchestra("trombones", music.sampled(tromboneSet), 0.25, 2.8, 0.35), - tuba: orchestra("tuba", music.sampled(tubaSet), 0.3, 2.0, 0.3), - timpani: orchestra("timpani", music.sampled(timpaniSet), -0.1, 1.9, 0.45), - roll: orchestra("roll", music.sampled(rollsSet), -0.1, 0.9, 0.45), -}); - -/** The sections, where each begins in seconds and frames, and its bars. */ -export const sections = written.sections.map((s) => ({ name: s.name, from: s.from, to: s.to, at: take.bars[s.from], frame: Math.round(take.bars[s.from] / 0.042) })); - -/* ── Rendered a section at a time ── */ - -const raw = written.sections.map((s) => { - const hall = s.name === "storm" || s.name === "closing"; - return music.render(music.excerpt(take, s.from, s.to < take.bars.length - 1 ? s.to : undefined), { reverb: hall ? HALL : ROOM, master: s.name === "storm" ? BUS : MASTER, limit: false }); -}); -const piano4 = [0, 1, 2, 4]; -// The piano's sections turned by one gain, so they keep the levels they were played at; the storm on its own. -const pianoLevel = together(piano4.map((k) => ({ clip: raw[k], at: sections[k].at })), { lufs: PIANO_LUFS }); -const level = raw.map((c, k) => (k === 3 ? c.loudness(STORM_LUFS) : pianoLevel[piano4.indexOf(k)])); - -/** The whole piece, one clip: the sections added up at their times, tails under what follows, limited once. */ -export const whole = mixdown(level.map((c, k) => ({ clip: c, at: sections[k].at }))).limit().ogg(QUALITY); -/** Each section with its tail, for a showcase that restarts the sound a section at a time. */ -export const A = level[0].limit().ogg(QUALITY); -export const B = level[1].limit().ogg(QUALITY); -export const again = level[2].limit().ogg(QUALITY); -export const storm = level[3].limit().ogg(QUALITY); -export const closing = level[4].limit().ogg(QUALITY); +import { take, sections, whole, A, B, again, storm, closing } from "./lib/fur-elise-soundtrack"; +export { take, sections, whole, A, B, again, storm, closing }; program(async () => { displayText("\x04Für Elise: the whole piece. Keys 1-5 play a section on its own."); diff --git a/probes/lib/fur-elise-soundtrack.ts b/probes/lib/fur-elise-soundtrack.ts new file mode 100644 index 0000000..21a342f --- /dev/null +++ b/probes/lib/fur-elise-soundtrack.ts @@ -0,0 +1,71 @@ +// The Für Elise soundtrack (TrigScript Showcase #3): the whole piece as probes/fur-elise.ts plays it, kept here without +// a program so that a showcase can import the sound (probes/fur-elise-showcase.ts) — see probes/fur-elise.ts for how it +// is played and why. The timeline (probes/lib/fur-elise-timeline.ts) is made from it by fur-elise-timeline-gen.mts. +// +// Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). Orchestra: VSCO 2 Community Edition by Versilian +// Studios (CC0). Instruments made by probes/lib/fur-elise-sound-gen.mts. +import { music, type Instrument } from "trigscript/music"; +import piano from "../salamander-grand.samples"; +import violinsSet from "../vsco-violins.samples"; +import violasSet from "../vsco-violas.samples"; +import celliSet from "../vsco-celli-spic.samples"; +import bassesSet from "../vsco-bass-spic.samples"; +import hornsSet from "../vsco-horns.samples"; +import tromboneSet from "../vsco-trombone.samples"; +import tubaSet from "../vsco-tuba.samples"; +import timpaniSet from "../vsco-timpani.samples"; +import rollsSet from "../vsco-timpani-rolls.samples"; +import { piece } from "./fur-elise-score"; + +/** The solo piano at −17 LUFS (the probe's choice), the storm at −15. */ +const PIANO_LUFS = -17; +const STORM_LUFS = -15; +/** The smaller room for the first half, and the hall (the probe's) for the storm and the end. */ +const ROOM = { decay: 0.7, damping: 0.55, predelay: 0.018 }; +const HALL = { decay: 0.84, damping: 0.5, predelay: 0.032 }; +const MASTER = (c: Clip) => c.filter("highpass", 28); +const BUS = (c: Clip) => MASTER(c).compress({ threshold: -20, ratio: 2, attack: 0.02, release: 0.25, knee: 6 }); +const QUALITY = 6; + +const written = piece(); +const grand = music.sampled(piano, { resonance: 0.07 }); +const orchestra = (name: string, instrument: Instrument, pan: number, volume: number, reverb: number) => + ({ instrument, notes: (written.orchestra as Record)[name], pan, volume, reverb }); + +/** The piece as played: one performance, so every note has its time in the whole. */ +export const take = music.perform({ meter: "3/8", bpm: 120, pickup: "1/8", tempo: written.tempo, holds: written.holds, humanize: { time: 0.004, velocity: 3, seed: 7 } }, { + right: { instrument: grand, notes: written.right, lead: 0.008, reverb: 0.24 }, + left: { instrument: grand, notes: written.left, velocity: 0.92 }, + violins: orchestra("violins", music.sampled(violinsSet), -0.45, 2.8, 0.32), + violas: orchestra("violas", music.sampled(violasSet), 0.2, 0.85, 0.32), + celli: orchestra("celli", music.sampled(celliSet), 0.4, 1.35, 0.25), + basses: orchestra("basses", music.sampled(bassesSet), 0.55, 1.55, 0.25), + horns: orchestra("horns", music.sampled(hornsSet), -0.2, 0.8, 0.4), + trombones: orchestra("trombones", music.sampled(tromboneSet), 0.25, 2.8, 0.35), + tuba: orchestra("tuba", music.sampled(tubaSet), 0.3, 2.0, 0.3), + timpani: orchestra("timpani", music.sampled(timpaniSet), -0.1, 1.9, 0.45), + roll: orchestra("roll", music.sampled(rollsSet), -0.1, 0.9, 0.45), +}); + +/** The sections, where each begins in seconds and frames, and its bars. */ +export const sections = written.sections.map((s) => ({ name: s.name, from: s.from, to: s.to, at: take.bars[s.from], frame: Math.round(take.bars[s.from] / 0.042) })); + +/* ── Rendered a section at a time ── */ + +const raw = written.sections.map((s) => { + const hall = s.name === "storm" || s.name === "closing"; + return music.render(music.excerpt(take, s.from, s.to < take.bars.length - 1 ? s.to : undefined), { reverb: hall ? HALL : ROOM, master: s.name === "storm" ? BUS : MASTER, limit: false }); +}); +const piano4 = [0, 1, 2, 4]; +// The piano's sections turned by one gain, so they keep the levels they were played at; the storm on its own. +const pianoLevel = together(piano4.map((k) => ({ clip: raw[k], at: sections[k].at })), { lufs: PIANO_LUFS }); +const level = raw.map((c, k) => (k === 3 ? c.loudness(STORM_LUFS) : pianoLevel[piano4.indexOf(k)])); + +/** The whole piece, one clip: the sections added up at their times, tails under what follows, limited once. */ +export const whole = mixdown(level.map((c, k) => ({ clip: c, at: sections[k].at }))).limit().ogg(QUALITY); +/** Each section with its tail, for a showcase that restarts the sound a section at a time. */ +export const A = level[0].limit().ogg(QUALITY); +export const B = level[1].limit().ogg(QUALITY); +export const again = level[2].limit().ogg(QUALITY); +export const storm = level[3].limit().ogg(QUALITY); +export const closing = level[4].limit().ogg(QUALITY); From f3688193dd21ddffab2cc6d247349c0a6abc2fcf Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:54:26 -0600 Subject: [PATCH 16/31] The game's tests of a script that imports media MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A script whose files include a .samples, .sound or other media file could not run beside the game for its tests: the game host ran its modules again without the media, so the import failed. GameTestPayload.media carries them now and scripts/test-game.mts passes them. Found with the Für Elise showcase, whose soundtrack imports the piano's samples. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- compiler/gameTests.ts | 9 +++++++- scripts/test-game.mts | 7 +++++-- tests/game-media.test.ts | 45 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 tests/game-media.test.ts diff --git a/compiler/gameTests.ts b/compiler/gameTests.ts index 0d6ece6..47e4753 100644 --- a/compiler/gameTests.ts +++ b/compiler/gameTests.ts @@ -16,6 +16,7 @@ import { RemasteredWeigh } from "./remasteredCost"; import { EudTracer, type EudTraceHost, type EudTraceRow } from "./eudError"; import { RecordingHandle, type DebugHost, type DebugLimits, type DebugRecording } from "./gameDebug"; import { here, locate, runModules, type LinkedFile } from "./link"; +import { mediaValue } from "./media"; import type { ScriptNames } from "./names"; import { Collector, createRuntime } from "./runtime"; import { isTestFile, listTests, runTests, TestRegistry, TESTING_NAMES, type TestReport, type TestResult } from "./testing"; @@ -41,6 +42,11 @@ export interface GameTestPayload { trace?: boolean; /** Before the tests, the map played this many frames with nobody at it (a script with no tests is traced so). */ play?: number; + /** + * The script's videos, images, sounds, notes and samples by path, as its files hold them: what an import of one gives + * when the modules run again. Absent, a script that imports one cannot run beside the game. + */ + media?: [string, string][]; } /** What `runGameTests` returns: the report, and with `trace` asked, the run's reads and writes by line. */ @@ -55,7 +61,8 @@ function register(payload: GameTestPayload) { registry.where = () => where(new Error()) ?? { file: ENTRY_FILE, line: 1 }; const runtime = { ...createRuntime(payload.names, collector), ...registry.library() }; collector.running = true; - const failure = runModules(linked, entryOf(linked.keys()), runtime, MODULE_NAME, { imported: TESTING_NAMES, then: [...linked.keys()].filter(isTestFile).sort() }); + const media = new Map(payload.media ?? []); + const failure = runModules(linked, entryOf(linked.keys()), runtime, MODULE_NAME, { imported: TESTING_NAMES, then: [...linked.keys()].filter(isTestFile).sort(), media: (path) => { const text = media.get(path); return text === undefined ? undefined : mediaValue(path, text); } }); collector.running = false; return { linked, registry, where, error: failure ? `${failure.file ?? ENTRY_FILE}:${failure.line ?? 1}: ${failure.message}` : null }; } diff --git a/scripts/test-game.mts b/scripts/test-game.mts index d541058..bbeb370 100644 --- a/scripts/test-game.mts +++ b/scripts/test-game.mts @@ -28,6 +28,7 @@ import type { GameTestReport } from "../compiler/gameTests"; import type { TestReport, TestWorld } from "../compiler/testing"; import { defaultLib } from "../bundle/lib.mjs"; import { scriptFiles } from "./script-files.mts"; +import { isMediaFile } from "../compiler/media"; import { shortMs } from "../compiler/gameCost"; import { MOST_MS, SMOOTH_MS } from "../compiler/remasteredCost"; @@ -72,6 +73,8 @@ try { // The tests in the simulator over the map's own world, as the editor runs them; then in the game, the way a host // of the game runs them: the compile's JavaScript handed to dist/gametest.js, loaded from its text. const source = scriptFiles(script); + // (The script's media, for its modules run again beside the game: an import of a .sound or .samples gives its value.) + const media = Object.entries(source).filter(([path]) => isMediaFile(path)) as [string, string][]; const names = defaultScriptNames(); // (The locations from the game once the start-up has run: a build through eudplib kept them scrambled in the file.) const locations = readLocations(handle); @@ -87,7 +90,7 @@ try { const triggerMap = JSON.parse(readFileSync(built.replace(/\.scx$/, ".triggers.json"), "utf8")); if (errorAddress !== null) { const frames = Number(flag("frames") ?? 3000); - const traced = host.runGameTests(handle, { modules: compiled.modules ?? [], names, locations, variables, triggers: triggerMap, trace: true, play: frames }) as GameTestReport; + const traced = host.runGameTests(handle, { modules: compiled.modules ?? [], names, locations, variables, triggers: triggerMap, trace: true, play: frames, media }) as GameTestReport; if (traced.error || traced.traceError || !traced.trace) { console.error(`not traced: ${traced.error ?? traced.traceError ?? "no trace came back"}`); process.exit(1); } const list = JSON.parse(readFileSync(join(root, "data", "allowlist.json"), "utf8")) as Allowlist; const a = findEudError(errorAddress, traced.trace.rows, list); @@ -98,7 +101,7 @@ try { if (!a.lines.length && !(a.unlined.exact + a.unlined.field)) console.log(" nothing in the run touched it"); process.exit(0); } - const inGame = host.runGameTests(handle, { modules: compiled.modules, names, locations, variables, triggers: triggerMap }) as TestReport & { error?: string }; + const inGame = host.runGameTests(handle, { modules: compiled.modules, names, locations, variables, triggers: triggerMap, media }) as TestReport & { error?: string }; if (inGame.error) { console.error(`the script did not run beside the game: ${inGame.error}`); process.exit(1); } const bySim = new Map((simulated?.results ?? []).map((r) => [r.id, r])); let failed = 0; diff --git a/tests/game-media.test.ts b/tests/game-media.test.ts new file mode 100644 index 0000000..e35765e --- /dev/null +++ b/tests/game-media.test.ts @@ -0,0 +1,45 @@ +/** + * A script that imports a sound (or samples, a video …) run again beside the game for its tests (compiler/gameTests.ts): + * its modules get the media from the payload, as the compile's own run does; without them they cannot run. Found with + * the Für Elise showcase, whose soundtrack imports the piano's .samples. + */ +import ts from "typescript"; +import { describe, expect, it } from "vitest"; +import { compileScript } from "../compiler/compiler"; +import { defaultScriptNames } from "../compiler/names"; +import { defaultLib } from "../bundle/lib.mjs"; +import { runGameTests } from "../compiler/gameTests"; +import type { GameHandle } from "../compiler/gameSim"; +import { writeSound } from "../compiler/sound"; + +const boom = writeSound({ rate: 22050, samples: Float32Array.from({ length: 2205 }, (_, i) => Math.sin(i / 10) * 0.5), source: "boom.wav" }); +const files = { + "main.ts": `import { test, expect } from "trigscript";\nimport boom from "./sfx/boom.sound";\nconst LONG = Math.round(boom.seconds * 10);\ntest("the sound's length, beside the game", () => { expect(LONG).toBe(1); });\n`, + "sfx/boom.sound": boom, +}; + +/** A game nothing happens in: enough for a test that only looks at a value of the build. */ +const game = () => ({ + m: new DataView(new ArrayBuffer(8)), u8: new Uint8Array(8), localPlayer: 0, over: false, frame: 0, + step() {}, reset() {}, lines: () => [], action: () => 0, chat() {}, call: () => 0, +}) as unknown as GameHandle; + +describe("the game's tests of a script with media", () => { + const compiled = compileScript(ts, files, defaultScriptNames(), { lib: defaultLib() }); + + it("compiles, its test registered", () => { + expect(compiled.diagnostics.map((d) => d.message)).toEqual([]); + expect(compiled.modules?.length).toBeGreaterThan(0); + }); + + it("runs its modules again with the media the payload gives", () => { + const report = runGameTests(game(), { modules: compiled.modules!, names: defaultScriptNames(), locations: {}, media: [["sfx/boom.sound", boom]] }); + expect(report.error).toBeUndefined(); + expect(report.results.map((r) => r.status)).toEqual(["passed"]); + }); + + it("says what is missing without them", () => { + const report = runGameTests(game(), { modules: compiled.modules!, names: defaultScriptNames(), locations: {} }); + expect(report.error).toMatch(/Cannot find "\.\/sfx\/boom\.sound"/); + }); +}); From 8aef897124e308d3f95b138a81d32ec5f6847f99 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:54:26 -0600 Subject: [PATCH 17/31] note-timeline: fitKeys, a keyboard fitted to the notes within a limit The window of keys (or white keys) holding the most notes, white key to white key, and the rest moved in by octaves: a map has only so many columns for a keyboard. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- probes/lib/note-timeline.ts | 35 +++++++++++++++++++++++++++++++++++ tests/note-timeline.test.ts | 28 +++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/probes/lib/note-timeline.ts b/probes/lib/note-timeline.ts index 6449099..b0271c2 100644 --- a/probes/lib/note-timeline.ts +++ b/probes/lib/note-timeline.ts @@ -154,3 +154,38 @@ export function changesOver(frames: number, picture: (f: number) => readonly Pix } return out; } + +/** A keyboard fitted to notes: its lowest and highest key, and where a note outside it is shown (an octave in). */ +export interface FittedKeys { readonly lo: number; readonly hi: number; fold(note: number): number } + +/** + * The keyboard that shows the most of `pitches` in at most `most` keys (`count: "keys"`) or white keys (`"whites"`), + * from a white key to a white key: every note when they fit; else the window holding the most of them, and each note + * outside it moved by octaves to the nearest it can be inside (a keyboard on a map has only so many columns). + */ +export function fitKeys(pitches: readonly number[], most: number, count: "keys" | "whites" = "keys"): FittedKeys { + if (!pitches.length) throw new Error("fitKeys: no notes."); + const size = (lo: number, hi: number) => (count === "keys" ? hi - lo + 1 : whiteKeys(lo, hi).length); + const all = keyRange(pitches.map((note) => ({ note }))); + let lo = all.lo, hi = all.hi; + if (size(lo, hi) > most) { + // Every window from a white key, as wide as allowed: the one holding the most notes (the lower on a tie). + let best = -1; + for (let a = all.lo; a <= all.hi; a++) { + if (isBlack(a)) continue; + let b = a; + while (b + 1 <= all.hi && size(a, b + 1) <= most) b++; + if (isBlack(b)) b--; + const held = pitches.filter((p) => p >= a && p <= b).length; + if (held > best) { best = held; lo = a; hi = b; } + } + if (hi - lo < 11) throw new Error(`fitKeys: ${most} ${count} cannot hold an octave.`); + } + const fold = (note: number) => { + let n = note; + while (n < lo) n += 12; + while (n > hi) n -= 12; + return n; + }; + return { lo, hi, fold }; +} diff --git a/tests/note-timeline.test.ts b/tests/note-timeline.test.ts index e641790..3f9aab4 100644 --- a/tests/note-timeline.test.ts +++ b/tests/note-timeline.test.ts @@ -4,7 +4,7 @@ * transcription played on a tempo that moves. */ import { describe, expect, it } from "vitest"; -import { FRAME, changesOver, frameNotes, isBlack, keyRange, keyX, rollCells, whiteKeys, type FramedNote, type Pixel } from "../probes/lib/note-timeline"; +import { FRAME, changesOver, fitKeys, frameNotes, isBlack, keyRange, keyX, rollCells, whiteKeys, type FramedNote, type Pixel } from "../probes/lib/note-timeline"; import { A_PLAYING, A_SECTION, STORM, STORM_PLAYING, THEME_TWICE, barStarts, length, noteNumber, perform } from "../probes/lib/fur-elise-probe-score"; const note = (time: number, seconds: number, n: number, hand = 0) => ({ time, seconds, note: n, hand, velocity: 1 }); @@ -164,3 +164,29 @@ describe("the transcription, played", () => { expect(bars.at(-1)).toBeCloseTo(length(THEME_TWICE, A_PLAYING), 9); }); }); + +describe("a keyboard fitted to the notes", () => { + it("holds every note when they fit, white key to white key", () => { + const k = fitKeys([45, 52, 63, 76], 64); + expect([k.lo, k.hi, k.fold(63)]).toEqual([45, 76, 63]); + expect(fitKeys([44, 70], 64)).toMatchObject({ lo: 43, hi: 71 }); + }); + + it("keeps the window with the most notes and moves the rest in by octaves", () => { + // A1 … E7 is 68 keys; 63 hold all but the three A1s, which show an octave up. + const pitches = [33, 33, 33, ...Array.from({ length: 63 }, (_, i) => 38 + i), 100, 100]; + const k = fitKeys(pitches, 63); + expect([k.lo, k.hi]).toEqual([38, 100]); + expect(k.fold(33)).toBe(45); + expect(k.fold(101)).toBe(89); + }); + + it("counts white keys when asked", () => { + // A1 … E7 has 40 white keys: they fit in 40, not in 30. + const k = fitKeys([33, 100], 40, "whites"); + expect([k.lo, k.hi]).toEqual([33, 100]); + const narrow = fitKeys([33, ...Array.from({ length: 30 }, (_, i) => 50 + i)], 30, "whites"); + expect(whiteKeys(narrow.lo, narrow.hi).length).toBeLessThanOrEqual(30); + expect(narrow.fold(33)).toBeGreaterThanOrEqual(narrow.lo); + }); +}); From e67671dc18f53f600026b14b5029b302178066dc Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:55:03 -0600 Subject: [PATCH 18/31] make-samples: an SFZ region with no root is middle C, not its lowest key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Salamander's C4 regions name no pitch_keycenter; taken as their lowest key (B3) they played a semitone sharp on B3, C4 and C#4 — heard in the Für Elise soundtrack (C4 is struck 46 times). Measured on the render: B3/C4 +95/+96 cents before, -5/-5 after. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- scripts/make-samples.mts | 4 +++- tests/make-samples.test.ts | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 tests/make-samples.test.ts diff --git a/scripts/make-samples.mts b/scripts/make-samples.mts index befdbb5..4d37827 100644 --- a/scripts/make-samples.mts +++ b/scripts/make-samples.mts @@ -109,7 +109,9 @@ function zonesFromSfz(path: string): { files: string[]; zones: ZoneData[] } { const key = o.key !== undefined ? keyOf(o.key) : undefined; const lo = key ?? (o.lokey !== undefined ? keyOf(o.lokey) : 0), hi = key ?? (o.hikey !== undefined ? keyOf(o.hikey) : 127); if (trigger === "attack" || trigger === "release") if (lo < 0 || hi < 0) continue; - const centre = o.pitch_keycenter !== undefined ? keyOf(o.pitch_keycenter) : key ?? lo; + // SFZ: `key` sets the root too; with neither, the root is middle C (60), whatever the zone's keys. Salamander's C4 + // regions say no root: taken as their lowest key (B3) they played a semitone sharp on B3, C4 and C#4. + const centre = o.pitch_keycenter !== undefined ? keyOf(o.pitch_keycenter) : key ?? 60; let k = files.indexOf(r.sample); if (k < 0) { files.push(r.sample); k = files.length - 1; } const zone: ZoneData = { diff --git a/tests/make-samples.test.ts b/tests/make-samples.test.ts new file mode 100644 index 0000000..2eacc6e --- /dev/null +++ b/tests/make-samples.test.ts @@ -0,0 +1,37 @@ +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +/** A mono 16-bit WAV of `seconds` of a quiet sine. */ +function wav(seconds: number, rate = 44100): Buffer { + const n = Math.round(seconds * rate), b = Buffer.alloc(44 + n * 2); + b.write("RIFF", 0); b.writeUInt32LE(36 + n * 2, 4); b.write("WAVE", 8); b.write("fmt ", 12); + b.writeUInt32LE(16, 16); b.writeUInt16LE(1, 20); b.writeUInt16LE(1, 22); b.writeUInt32LE(rate, 24); + b.writeUInt32LE(rate * 2, 28); b.writeUInt16LE(2, 32); b.writeUInt16LE(16, 34); b.write("data", 36); b.writeUInt32LE(n * 2, 40); + for (let i = 0; i < n; i++) b.writeInt16LE(Math.round(8000 * Math.sin((2 * Math.PI * 440 * i) / rate)), 44 + i * 2); + return b; +} + +describe("make-samples: an SFZ's root keys", () => { + it("takes pitch_keycenter, then key, then middle C — never the zone's lowest key", () => { + const dir = mkdtempSync(join(tmpdir(), "make-samples-")); + try { + for (const f of ["a.wav", "b.wav", "c.wav"]) writeFileSync(join(dir, f), wav(0.1)); + writeFileSync(join(dir, "x.sfz"), [ + " amp_veltrack=73", + " sample=a.wav lokey=56 hikey=58 pitch_keycenter=57", + // Salamander's C4 regions are written like this one: no root at all, which SFZ reads as 60. + " sample=b.wav lokey=59 hikey=61", + " sample=c.wav key=64", + ].join("\n")); + const out = join(dir, "x.samples"); + execFileSync("npx", ["tsx", join(__dirname, "..", "scripts", "make-samples.mts"), join(dir, "x.sfz"), out], { stdio: "pipe" }); + const zones = (JSON.parse(readFileSync(out, "utf8")) as { zones: { key: number; lo: number; hi: number }[] }).zones; + expect(zones.map((z) => [z.lo, z.hi, z.key])).toEqual([[56, 58, 57], [59, 61, 60], [64, 64, 64]]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); +}); From bfb0b08c3a29ba8e67c215002ccb0039961c1042 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:57:59 -0600 Subject: [PATCH 19/31] =?UTF-8?q?F=C3=BCr=20Elise,=20the=20showcase=20buil?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit probes/fur-elise-showcase.ts (lobby "Für Elise") plays the whole soundtrack as one clip, started two frames before the picture's frame 0 (the probe measured the picture ~95 ms ahead), and plays back the picture worked out at build: notes falling onto a keyboard on both screens (the main screen a row every other frame), right hand gold, left cyan, the loud section's chords red with the white keys flashing red, explosions on its strongest downbeats; the other parts in violet on the minimap only. No sync lamp; a title line, an end line, then the game waits. probes/lib/fur-elise-showcase-run.ts takes everything from the timeline so that a new arrangement drops in: the hands (or the two busiest parts), drums kept off the rolls, both keyboards fitted with fitKeys, the loud sections by velocity, the explosions by the weight of each downbeat (for Für Elise: C1, C9 and C16, the bars the score accents). In the lifted game every one of the 5,180 frames holds the worked-out picture; 0.55 ms a frame at most; game-check finds nothing Remastered refuses or ignores. fur-elise-frames.mts --showcase draws its stills. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- probes/answers/fur-elise-showcase.txt | 33 ++++ probes/fur-elise-showcase.ts | 142 +++++++++++++++ probes/lib/fur-elise-frames.mts | 43 +++-- probes/lib/fur-elise-showcase-run.ts | 245 ++++++++++++++++++++++++++ tests/fur-elise-showcase-run.test.ts | 104 +++++++++++ 5 files changed, 552 insertions(+), 15 deletions(-) create mode 100644 probes/answers/fur-elise-showcase.txt create mode 100644 probes/fur-elise-showcase.ts create mode 100644 probes/lib/fur-elise-showcase-run.ts create mode 100644 tests/fur-elise-showcase-run.test.ts diff --git a/probes/answers/fur-elise-showcase.txt b/probes/answers/fur-elise-showcase.txt new file mode 100644 index 0000000..d9c812d --- /dev/null +++ b/probes/answers/fur-elise-showcase.txt @@ -0,0 +1,33 @@ +Für Elise, the showcase build: a check play +=========================================== + +Map: trigscript-fur-elise.scx (lobby "Für Elise"). About 3 minutes 40 seconds, nothing to press. +Stills of what it should look like: fur-elise-showcase-frames.png beside the map (the minimap on the left, the main +screen on the right, as the build works them out — not the game's own drawing). + +What to record +-------------- +- Host it as a multiplayer game, alone. Remastered graphics, no F5. +- Options: game MUSIC OFF, sound effects ON (the piece plays as a sound effect). +- Record the whole run, from the lobby to the end text and a few seconds after. Don't move the camera or click. + +What is where +------------- +- Main screen: a keyboard of Flags, A1 to E7 (40 white keys, the black keys above them). Notes fall onto it, right hand + gold, left hand cyan; each key lights in its hand's colour while it sounds. +- Minimap: the same notes falling onto a keyboard row (white and indigo keys), the orchestra's parts in violet during + the storm. +- The storm (about 2:10 to 2:35): the right hand's chords red, the white keys flash red on each chord, explosions on + three downbeats (Wraiths at 2:12 and 2:23, three Battlecruisers on the last big chord at 2:33), with their sounds. +- Text: "Für Elise" at the start; "Für Elise — Ludwig van Beethoven" when the last note is let go (about 3:25). + After that the keyboard stays and the game waits; leave when the sound has rung out. + +What to look at +--------------- +1. Do the notes land on the keys as you hear them (not early, not late)? The clip now starts two frames before the + picture, to take up the ~95 ms the probe measured. -> +2. Does the main-screen keyboard fit in the view, both ends visible (A1 at the far left, E7 at the far right)? -> +3. Do the first text line and the end line show the ü and the dash (—) properly? -> +4. The storm: red chords, red flashes, the three explosions: right amount, or too much / too little? -> +5. The minimap: does the violet orchestra in the storm read well, or is it clutter? -> +6. Any stray unit, a Flag or Overlord in the wrong place, an error text, a stutter or slowdown? -> diff --git a/probes/fur-elise-showcase.ts b/probes/fur-elise-showcase.ts new file mode 100644 index 0000000..90e53c4 --- /dev/null +++ b/probes/fur-elise-showcase.ts @@ -0,0 +1,142 @@ +// Für Elise, TrigScript Showcase #3: the whole piece (probes/lib/fur-elise-soundtrack.ts, one clip) drawn as it plays — +// notes falling onto a keyboard on the minimap (Overlords over Space, the other parts in violet) and on the main screen +// (Flag-looking Spider Mines, a row every other frame), right hand gold, left hand cyan, a loud section's chords red +// with the white keys flashing red on each, explosions on its strongest downbeats. +// +// Every frame's picture is worked out when the script is built (probes/lib/fur-elise-showcase-run.ts, from the +// soundtrack's timeline, probes/lib/fur-elise-timeline.ts — made again by fur-elise-timeline-gen.mts when the soundtrack +// changes; the run takes its parts, sections, range and accents from it); the program plays the changes back. The clip starts two frames before the +// picture's frame 0: the visualizer probe measured the picture ~95 ms ahead of a long clip's sound. +// +// Host it as multiplayer, alone, with the game's music off (sound effects on). Check sheet: +// probes/answers/fur-elise-showcase.txt. +// +// MAP_NAME="Für Elise" MAP_DESCRIPTION="…" npx tsx probes/lib/fur-elise-map.mts fixtures/eud/fur-elise-showcase-base.scx (the description: below) +// MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase.scx fixtures/eud/fur-elise-showcase-base.scx +// SCM_SIM_DIR=~/github/scm-sim-eud npx tsx scripts/test-game.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase-base.scx +// +// The piano and orchestra .samples files must be in probes/ (made by probes/lib/fur-elise-sound-gen.mts; never committed). +// +// Players: P1 you (green, owns only the placed Map Revealers), P2 the computer Remastered needs to start a game (owns +// nothing: a computer moves its own units), P3 … P8 own the pixels — P3 white keys, P4 indigo black keys, P5 gold right +// hand, P6 cyan left hand, P7 red storm, P8 violet orchestra. +// probe-players: {"0":{"rgb":[16,252,24]},"1":{"rgb":[120,120,120]},"2":{"rgb":[240,240,240]},"3":{"rgb":[72,56,200]},"4":{"rgb":[255,190,0]},"5":{"rgb":[0,200,255]},"6":{"rgb":[235,20,50]},"7":{"rgb":[170,80,255]}} +import { program, nextFrame, print, playWav, centerView, centerLocation, reserveLocation, createUnit, removeUnitAt, killUnitAt, giveUnits, setMemory, units, P3, P4, P5, P6, P7, P8, test, expect } from "trigscript"; +import { whole } from "./lib/fur-elise-soundtrack"; +import { CAM_X, CAM_Y, CELL } from "./lib/fur-elise-layout"; +import { START, TOTAL, LAST_OFF, STARTS, CX, CY, CKIND, CTO, LABEL_F, LABEL_TEXT, FX_F, FX_K, FX_X, FX_Y, OVERLORD, pictureAt, explosions } from "./lib/fur-elise-showcase-run"; + +/** units.dat's flingy bytes of types 12 … 15 (Battlecruiser, Spider Mine, Nuclear Missile, Civilian), one dword. */ +const LOOKS = 0x664504; +const looks = (flingy: number) => 70 + flingy * 256 + 109 * 65536 + 71 * 16777216; +/** A Spider Mine made with a Flag's looks (flingy 126), and its own put back after (89). */ +const FLAG_LOOK = looks(126), MINE_LOOK = looks(89); +const OWNERS = [P3, P4, P5, P6, P7, P8]; +const AT = reserveLocation("fur elise: where a pixel is made"); +const FX = reserveLocation("fur elise: where an explosion is made"); +const VIEW = reserveLocation("fur elise: the camera"); + +/** + * One pixel changed (kind: unit · 8 + its old colour, 0 none): made, taken away, or handed to the player of its new + * colour with Give Units, which recolours a unit where it stands (made again where one was taken away in the same frame, + * a Spider Mine would be put beside its place). + */ +function change(x: number, y: number, kind: number, to: number) { + if (kind < 8) { + centerLocation(AT, x, y, 32, 32); + if (kind === 0) OWNERS.forEach((p, k) => { if (to === k + 1) createUnit(p, units.ZergOverlord, 1, AT); }); + else if (to === 0) OWNERS.forEach((p, k) => { if (kind === k + 1) removeUnitAt(p, units.ZergOverlord, 1, AT); }); + else OWNERS.forEach((p, a) => { if (kind === a + 1) OWNERS.forEach((q, b) => { if (to === b + 1) giveUnits(p, q, units.ZergOverlord, 1, AT); }); }); + } else { + centerLocation(AT, x, y, 4, 4); + if (kind === 8) OWNERS.forEach((p, k) => { if (to === k + 1) createUnit(p, units.SpiderMine, 1, AT); }); + else if (to === 0) OWNERS.forEach((p, k) => { if (kind === k + 9) removeUnitAt(p, units.SpiderMine, 1, AT); }); + else OWNERS.forEach((p, a) => { if (kind === a + 9) OWNERS.forEach((q, b) => { if (to === b + 1) giveUnits(p, q, units.SpiderMine, 1, AT); }); }); + } +} + +/** An explosion: a Wraith (1) or a Battlecruiser (2) made and killed in one pass, its death on the stage. */ +function explode(kind: number, x: number, y: number) { + centerLocation(FX, x, y, 64, 64); + if (kind === 1) { createUnit(P7, units.TerranWraith, 1, FX); killUnitAt(P7, units.TerranWraith, 1, FX); } + else { createUnit(P7, units.TerranBattlecruiser, 1, FX); killUnitAt(P7, units.TerranBattlecruiser, 1, FX); } +} + +program(async () => { + centerLocation(VIEW, CAM_X, CAM_Y, 32, 32); + centerView(VIEW); + let g = 0, i = 0, l = 0, e = 0, camera = 0; + while (g < TOTAL) { + // The piece, one clip, two frames before its picture begins. + if (g === START) playWav(whole, 0); + while (l < LABEL_F.length && LABEL_F[l] === g) { + const k = l; + LABEL_TEXT.forEach((t, j) => { if (k === j) print(t); }); + l++; + } + const end = STARTS[g + 1]; + if (i < end) { + setMemory(LOOKS, "set", FLAG_LOOK); + while (i < end) { change(CX[i], CY[i], CKIND[i], CTO[i]); i++; } + setMemory(LOOKS, "set", MINE_LOOK); + } + while (e < FX_F.length && FX_F[e] === g) { explode(FX_K[e], FX_X[e], FX_Y[e]); e++; } + // The camera kept on the stage. + camera++; + if (camera >= 96) { camera = 0; centerView(VIEW); } + await nextFrame(); + g++; + } + // The piece is over: the keyboard stays, the game waits. +}); + +/* ── Tests: the picture the game holds is the one worked out ── */ + +/** The pixels a frame shows, as text to compare: "unit owner x y" each, sorted. */ +function expected(f: number): string[] { + return pictureAt(f).map((p) => `${p.unit === OVERLORD ? "o" : "m"} ${p.color + 1} ${p.x} ${p.y}`).sort(); +} + +/** What the game holds: Overlords (snapped to their cell's centre: made a few pixels off it) and Spider Mines of P3 … P8. */ +function held(sim: { units(q: { type: number }): readonly { x: number; y: number; owner: number; alive: boolean }[] }): string[] { + const snap = (v: number) => Math.round((v - CELL / 2) / CELL) * CELL + CELL / 2; + const out: string[] = []; + for (const u of sim.units({ type: units.ZergOverlord })) if (u.alive && u.owner >= 2 && u.owner <= 7) out.push(`o ${u.owner} ${snap(u.x)} ${snap(u.y)}`); + for (const u of sim.units({ type: units.SpiderMine })) if (u.alive && u.owner >= 2 && u.owner <= 7) out.push(`m ${u.owner} ${u.x} ${u.y}`); + return out.sort(); +} + +/** "" when what the game holds after `frames` is the picture of one of the frames just before (the program starts a frame or two in). */ +function matches(sim: Parameters[0], frames: number): string { + const got = held(sim); + for (let f = frames - 4; f <= frames; f++) if (expected(f).join("|") === got.join("|")) return ""; + const want = expected(frames - 2); + const missing = want.filter((w) => !got.includes(w)), extra = got.filter((w) => !want.includes(w)); + return `frame ${frames}: ${missing.length} missing (${missing.slice(0, 4).join(", ")}), ${extra.length} extra (${extra.slice(0, 4).join(", ")})`; +} + +test("every frame of the piece shows the picture worked out, and the end is said", (sim) => { + sim.frames(20); + let wrong = "", most = 0; + for (let f = 21; f < TOTAL && !wrong; f++) { + sim.frames(1); + wrong = matches(sim, f); + if (f % 8 === 0) most = Math.max(most, sim.units({}).filter((u) => u.alive).length); + } + expect(wrong).toBe(""); + // Of the game's 1,700 units, with the Map Revealers. + expect(most < 1000 ? "fewer than 1000" : `${most}`).toBe("fewer than 1000"); + // (The end's line by its ASCII part: the lifted game reads the map's UTF-8 text as Latin-1; Remastered shows the ü.) + expect(sim).toHavePrinted("Ludwig van Beethoven"); +}); + +test("the storm's explosions leave nothing behind", (sim) => { + // Each is a Wraith or a Battlecruiser made and killed in one pass: none is ever seen alive. + const alive = () => sim.units({ type: units.TerranWraith }).filter((u) => u.alive).length + sim.units({ type: units.TerranBattlecruiser }).filter((u) => u.alive).length; + const first = explosions[0].frame, last = explosions[explosions.length - 1].frame; + sim.frames(first - 10); + let most = 0; + for (let f = first - 10; f < last + 20; f++) { sim.frames(1); most = Math.max(most, alive()); } + expect(most).toBe(0); + expect(LAST_OFF < TOTAL).toBe(true); +}); diff --git a/probes/lib/fur-elise-frames.mts b/probes/lib/fur-elise-frames.mts index c4840e3..e4bf03f 100644 --- a/probes/lib/fur-elise-frames.mts +++ b/probes/lib/fur-elise-frames.mts @@ -1,33 +1,46 @@ -// Pictures of the Für Elise visualizer probe's frames as the build works them out (probes/lib/fur-elise-run.ts), to +// Pictures of the Für Elise visualizer probe's frames as the build works them out (probes/lib/fur-elise-run.ts), or the +// showcase's with --showcase (probes/lib/fur-elise-showcase-run.ts), to // look at before a play: the minimap at Remastered's 3 pixels a tile (Space black, the stage's Platform grey, a unit a // dot in its owner's colour) beside the main screen's view (852 × 330 game pixels, a Flag a coloured block, the lamp a // ring). Not the game's own drawing — the lifted game draws nothing — but its units, where the probe puts them. // -// npx tsx probes/lib/fur-elise-frames.mts [frame …] +// npx tsx probes/lib/fur-elise-frames.mts [--showcase] [frame …] // // Writes /frame-NNNN.png for each frame (some of each part when none is named) and /sheet.png of them. // Needs a scm-js checkout beside this one (its PNG encoder). import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { MAP_W, MAP_H, STAGE_TILES, VIEW_X, VIEW_Y } from "./fur-elise-layout.ts"; -import { A_BARS, BAR_AT, C_START, OVERLORD, RING, S1_START, STORM_BARS, TOTAL, pictureAt, plays, CLIP_A, CLIP_THEME } from "./fur-elise-run.ts"; -import { FRAME } from "./note-timeline.ts"; +import { FRAME, type Pixel } from "./note-timeline.ts"; const E = process.env.SCMJS_DIR ?? join(import.meta.dirname, "..", "..", "..", "scm-js"); const { encodePng } = await import(join(E, "src/formats/png.ts")); -const [out, ...named] = process.argv.slice(2); -if (!out) { console.error("usage: fur-elise-frames.mts [frame …]"); process.exit(2); } +const args = process.argv.slice(2); +const showcase = args.includes("--showcase"); +const [out, ...named] = args.filter((a) => a !== "--showcase"); +if (!out) { console.error("usage: fur-elise-frames.mts [--showcase] [frame …]"); process.exit(2); } mkdirSync(out, { recursive: true }); -/** The colours of P3 … P8 as the map gives them (the probe's probe-players line), by the run's colour numbers 1 … 6. */ -const RGB: readonly (readonly [number, number, number])[] = [[0, 0, 0], [240, 240, 240], [72, 56, 200], [255, 190, 0], [0, 200, 255], [235, 20, 50], [16, 16, 16]]; -const A_START = plays.find((p) => p.clip === CLIP_A)!.frame; -const V_START = plays.filter((p) => p.clip === CLIP_THEME)[1].frame; -const at = (start: number, seconds: number) => start + Math.round(seconds / FRAME); -const frames = named.length ? named.map(Number) : [ - at(A_START, 3), at(A_START, A_BARS[3]), at(A_START, A_BARS[20]), at(C_START, STORM_BARS[2] + 0.01), at(C_START, STORM_BARS[9]), - at(C_START, STORM_BARS[13]), at(S1_START, 6), at(V_START, BAR_AT[4]), at(V_START, BAR_AT[12]), -].filter((f) => f < TOTAL).sort((a, b) => a - b); +/** The run to draw: its pictures, its colours (P3 … P8 as its map gives them, by colour number) and frames worth a look. */ +const OVERLORD = 0, RING = 2; +let pictureAt: (f: number) => readonly Pixel[], RGB: readonly (readonly number[])[], preview: number[], TOTAL: number; +if (showcase) { + const r = await import("./fur-elise-showcase-run.ts"); + ({ pictureAt, RGB, TOTAL } = r); + preview = [...r.PREVIEW_FRAMES]; +} else { + const r = await import("./fur-elise-run.ts"); + ({ pictureAt, TOTAL } = r); + RGB = [[0, 0, 0], [240, 240, 240], [72, 56, 200], [255, 190, 0], [0, 200, 255], [235, 20, 50], [16, 16, 16]]; + const A_START = r.plays.find((p) => p.clip === r.CLIP_A)!.frame; + const V_START = r.plays.filter((p) => p.clip === r.CLIP_THEME)[1].frame; + const at = (start: number, seconds: number) => start + Math.round(seconds / FRAME); + preview = [ + at(A_START, 3), at(A_START, r.A_BARS[3]), at(A_START, r.A_BARS[20]), at(r.C_START, r.STORM_BARS[2] + 0.01), at(r.C_START, r.STORM_BARS[9]), + at(r.C_START, r.STORM_BARS[13]), at(r.S1_START, 6), at(V_START, r.BAR_AT[4]), at(V_START, r.BAR_AT[12]), + ]; +} +const frames = named.length ? named.map(Number) : preview.filter((f) => f < TOTAL).sort((a, b) => a - b); const T = 3, MW = MAP_W * T, MH = MAP_H * T, VW = 852, VH = 330, GAP = 12; const W = MW + GAP + VW, H = Math.max(MH, VH); diff --git a/probes/lib/fur-elise-showcase-run.ts b/probes/lib/fur-elise-showcase-run.ts new file mode 100644 index 0000000..49e195d --- /dev/null +++ b/probes/lib/fur-elise-showcase-run.ts @@ -0,0 +1,245 @@ +// The Für Elise showcase's run (probes/fur-elise-showcase.ts), worked out when the script is built from the soundtrack's +// timeline (probes/lib/fur-elise-timeline.ts): when the one clip starts, the text, and the picture of every frame on +// both screens, flattened into the changes the program plays back. Plain data and functions, so the same run is what +// the showcase plays, what tests/fur-elise-showcase-run.test.ts checks and what pictures of it are drawn from +// (probes/lib/fur-elise-frames.mts --showcase). +// +// It is generic over the timeline (the soundtrack may change: a new arrangement brings new parts, sections and range): +// the parts each screen shows, both keyboards, the loud sections and the explosions are all worked out from the data. +// The looks are the ones the user chose after the visualizer probe (2026-11-09): notes falling onto a keyboard on both +// screens, the main screen's a row every other frame; the lead part (the right hand) gold, the other (the left) cyan; +// in a loud section the lead's chords red and the white keys flashing red on each, and explosions on its strongest +// downbeats. The probe measured the picture ~95 ms ahead of a long clip's sound: the clip starts LEAD frames early. +import { FRAME, changesOver, fitKeys, isBlack, keyX, rollCells, whiteKeys, type FramedNote, type Pixel, type TimedNote } from "./note-timeline"; +import { NOTES, PARTS, SECTIONS, SECONDS, AT, END, PITCH, VELOCITY, PART, BAR, BEAT, FRAME as FRAME_COL } from "./fur-elise-timeline"; +import { CELL, VIEW_X, VIEW_Y, CAM_X, BLACK_Y, WHITE_Y, ROW_GAP, FALL_Y0, STAGE_ROWS, MAP_W } from "./fur-elise-layout"; + +/* ── The parts ── */ + +/** A part of drums: its notes are drums, not keys, and no roll shows them (they still count towards a downbeat's weight). */ +export const isDrums = (name: string) => /drum|kit|perc|kick|snare|hat|cymbal|clap/i.test(name); +const PITCHED = PARTS.map((_, k) => k).filter((k) => !isDrums(PARTS[k])); +const count = (k: number) => NOTES.filter((n) => n[PART] === k).length; +const meanPitch = (k: number) => NOTES.filter((n) => n[PART] === k).reduce((sum, n, _, all) => sum + n[PITCH] / all.length, 0); +/** + * The two parts the main screen shows as hands: "right" and "left" when the timeline has them (the piano), else the two + * pitched parts with the most notes, the higher of them the lead. The lead is gold, the other cyan. + */ +export const [LEAD_PART, OTHER_PART] = ((): [number, number] => { + const r = PARTS.indexOf("right" as never), l = PARTS.indexOf("left" as never); + if (r >= 0 && l >= 0) return [r, l]; + const [a, b] = [...PITCHED].sort((x, y) => count(y) - count(x)); + return meanPitch(a) >= meanPitch(b ?? a) ? [a, b ?? a] : [b, a]; +})(); +const onStage = (part: number) => part === LEAD_PART || part === OTHER_PART; + +/* ── The keyboards ── */ + +/** The main screen's keyboard: the hands' notes, at most 40 white keys (16 pixels apart fill the view); outliers by octaves. */ +export const STAGE_KEYS = fitKeys(NOTES.filter((n) => onStage(n[PART])).map((n) => n[PITCH]), 40, "whites"); +export const STAGE_LO = STAGE_KEYS.lo, STAGE_HI = STAGE_KEYS.hi; +/** + * White keys 16 to 20 pixels apart, the last at view x 830 (inside the 852 the widescreen view shows). A Spider Mine is + * 15 pixels square, so neighbours 16 apart never overlap; text lines show over view x 0 … 233, so the fewer keys, the + * fewer under the title. (Für Elise: A1 … E7, 40 white keys 16 apart from x 206; only A1 and B1 under the text.) + */ +export const STAGE_PITCH = Math.max(16, Math.min(20, Math.floor(624 / Math.max(1, whiteKeys(STAGE_LO, STAGE_HI).length - 1)))); +export const STAGE_X0 = 830 - (whiteKeys(STAGE_LO, STAGE_HI).length - 1) * STAGE_PITCH; +/** The minimap's keyboard: every pitched part's notes in the map's 64 columns of cells; outliers by octaves. (Für Elise: D2 … E7, A1 up an octave.) */ +export const ROLL_KEYS = fitKeys(NOTES.filter((n) => !isDrums(PARTS[n[PART]])).map((n) => n[PITCH]), MAP_W / 2, "keys"); +export const ROLL_LO = ROLL_KEYS.lo, ROLL_HI = ROLL_KEYS.hi; +export const ROLL_COL = Math.floor((MAP_W / 2 - (ROLL_HI - ROLL_LO + 1)) / 2); +/** The minimap roll's keyboard rows, and rows of falling notes above them, a row every ROLL_STEP frames. */ +export const ROLL_KEY_ROW = 42, ROLL_ROWS = 40, ROLL_STEP = 2; +/** The main screen's notes fall a row every other frame (the probe's A2, the user's choice). */ +export const STAGE_STEP = 2; + +/* ── The run's clock ── */ + +/** The title at frame 4, the keyboards from SETUP, the clip at START. */ +export const SETUP = 8, START = 84; +/** The picture runs this many frames behind the clip: the probe measured the picture ~95 ms ahead of the sound. */ +export const LEAD = 2; +/** Picture frame 0 of the soundtrack: a note's frame in the timeline plus this. */ +export const ZERO = START + LEAD; +export const LAST_OFF = ZERO + Math.round(Math.max(...NOTES.map((n) => n[END])) / FRAME); +/** The end's text a little after the last note is let go; the tables run 15 s past it, for the clip's ring and tail. */ +export const END_TEXT = LAST_OFF + 48; +export const TOTAL = ZERO + Math.ceil((SECONDS + 15) / FRAME); +export const TITLE = "Für Elise", END_LINE = "Für Elise — Ludwig van Beethoven"; +export const captions: readonly { frame: number; text: string }[] = [{ frame: 4, text: TITLE }, { frame: END_TEXT, text: END_LINE }]; + +/* ── The notes ── */ + +/** Colours, as the players who own them: 1 white (P3), 2 indigo (P4), 3 gold (P5), 4 cyan (P6), 5 red (P7), 6 violet (P8). */ +export const WHITE = 1, INDIGO = 2, GOLD = 3, CYAN = 4, RED = 5, VIOLET = 6; +/** Kinds of pixel: an Overlord on the minimap, a Flag on the stage. */ +export const OVERLORD = 0, FLAG = 1; + +/** A note of the run: on the picture's clock, its part, bar and beat, and whether a chord of the lead in a loud section. */ +export interface ShowNote extends FramedNote { readonly part: number; readonly bar: number; readonly beat: number; readonly stormChord: boolean } + +/** Each section's first bar, and the bar after the last. */ +const sectionEnd = (k: number) => SECTIONS[k + 1]?.bar ?? Infinity; +const meanVelocity = (ns: readonly (readonly number[])[]) => ns.reduce((sum, n) => sum + n[VELOCITY], 0) / Math.max(1, ns.length); +const pitchedNotes = NOTES.filter((n) => !isDrums(PARTS[n[PART]])); +/** The loud sections: played at a quarter or more over the piece's mean velocity (Für Elise: the storm, at 1.9 times). */ +export const LOUD = SECTIONS.filter((s, k) => meanVelocity(pitchedNotes.filter((n) => n[BAR] >= s.bar && n[BAR] < sectionEnd(k))) >= 1.25 * meanVelocity(pitchedNotes)).map((s) => s.name); +const loudBar = (bar: number) => SECTIONS.some((s, k) => LOUD.includes(s.name) && bar >= s.bar && bar < sectionEnd(k)); +/** The lead's notes struck together in a loud section (by bar and beat: the performance spreads a chord by a few ms). */ +const struckWith = new Map(); +for (const n of NOTES) if (n[PART] === LEAD_PART && loudBar(n[BAR])) struckWith.set(`${n[BAR]} ${n[BEAT]}`, (struckWith.get(`${n[BAR]} ${n[BEAT]}`) ?? 0) + 1); + +export const notes: readonly ShowNote[] = NOTES.filter((n) => !isDrums(PARTS[n[PART]])).map((n) => { + // The timeline's own frame for the strike (the soundtrack's), and the frames its key is held. + const on = ZERO + n[FRAME_COL], off = ZERO + Math.round(n[END] / FRAME); + const source: TimedNote = { time: n[AT], seconds: n[END] - n[AT], note: n[PITCH], hand: n[PART], velocity: n[VELOCITY] }; + const stormChord = n[PART] === LEAD_PART && loudBar(n[BAR]) && (struckWith.get(`${n[BAR]} ${n[BEAT]}`) ?? 0) >= 2; + return { source, on, len: Math.max(2, off - on), note: n[PITCH], hand: n[PART], velocity: n[VELOCITY], chord: stormChord, part: n[PART], bar: n[BAR], beat: n[BEAT], stormChord }; +}); +/** The hands, on both screens; the rest (the orchestra, …), on the minimap only. */ +export const piano = notes.filter((n) => onStage(n.part)); +const orchestra = notes.filter((n) => !onStage(n.part)); + +/** The frames the white keys flash red: two from each loud chord's first strike. */ +export const flashes = new Set(); +{ + const first = new Map(); + for (const n of piano) if (n.stormChord) { + const k = `${n.bar} ${n.beat}`; + first.set(k, Math.min(first.get(k) ?? Infinity, n.on)); + } + for (const f of first.values()) { flashes.add(f); flashes.add(f + 1); } +} + +/* ── What each frame shows ── */ + +const colorOf = (n: ShowNote) => (!onStage(n.part) ? VIOLET : n.part === OTHER_PART ? CYAN : n.stormChord ? RED : GOLD); +/** A key's place on each screen (a note outside a keyboard moved in by octaves). */ +export const stageX = (note: number) => VIEW_X + STAGE_X0 + keyX(STAGE_KEYS.fold(note), STAGE_LO, STAGE_PITCH); +const rollKey = (note: number) => ROLL_KEYS.fold(note); +export const rollX = (note: number) => (ROLL_COL + rollKey(note) - ROLL_LO) * CELL + CELL / 2; +export const rollY = (row: number) => row * CELL + CELL / 2; +const STAGE_LIST = Array.from({ length: STAGE_HI - STAGE_LO + 1 }, (_, k) => STAGE_LO + k); +const ROLL_LIST = Array.from({ length: ROLL_HI - ROLL_LO + 1 }, (_, k) => ROLL_LO + k); + +/** The notes a frame may show, found by a window over the notes in the order they start. */ +const SPAN = Math.max(ROLL_ROWS * ROLL_STEP, STAGE_ROWS * STAGE_STEP) + 4; +function near(list: readonly ShowNote[], f: number): ShowNote[] { + const out: ShowNote[] = []; + for (const n of list) { + if (n.on > f + SPAN) break; + if (n.on + n.len + SPAN >= f) out.push(n); + } + return out; +} +/** A roll's notes a row short, so that a key struck again shows as two. */ +const short = (ns: readonly ShowNote[], by: number) => ns.map((n) => ({ ...n, len: Math.max(1, n.len - by) })); +/** Whether a Flag at (x, y) would overlap another: a Spider Mine is 15 pixels square. */ +const overlap = (a: Pixel, x: number, y: number) => a.unit === FLAG && Math.abs(a.x - x) < 16 && Math.abs(a.y - y) < 16 && (a.x !== x || a.y !== y); + +/** + * The picture of frame f, given the frame before's. A trigger cannot make a Spider Mine overlapping another (it is put + * beside its place), and one taken away stands until its frame ends: a falling Flag that would overlap one of this frame + * or the last waits a frame (the probe, in the lifted game). + */ +function draw(f: number, before: readonly Pixel[]): Pixel[] { + const out: Pixel[] = []; + if (f < SETUP) return out; + const ps = near(piano, f), os = near(orchestra, f); + const flash = flashes.has(f); + // A key lit by the last note to strike it that is still held; `key` maps a note to the keyboard's key. + const keyColor = (k: number, idle: number, key: (note: number) => number) => { + const lit = ps.filter((n) => key(n.note) === k && n.on <= f && f < n.on + n.len); + return lit.length ? colorOf(lit[lit.length - 1]) : idle; + }; + // The minimap: the upper keyboard row every key, the lower the white keys' fronts (a note below D2 lights its octave). + for (const key of ROLL_LIST) { + const idle = isBlack(key) ? INDIGO : flash ? RED : WHITE; + const color = keyColor(key, idle, rollKey); + out.push({ x: rollX(key), y: rollY(ROLL_KEY_ROW), unit: OVERLORD, color }); + if (!isBlack(key)) out.push({ x: rollX(key), y: rollY(ROLL_KEY_ROW + 1), unit: OVERLORD, color }); + } + // The main screen's keyboard, from the frame after. + if (f >= SETUP + 1) for (const key of STAGE_LIST) { + const idle = isBlack(key) ? INDIGO : flash ? RED : WHITE; + out.push({ x: stageX(key), y: VIEW_Y + (isBlack(key) ? BLACK_Y : WHITE_Y), unit: FLAG, color: keyColor(key, idle, STAGE_KEYS.fold) }); + } + // The minimap roll: the orchestra first, the piano over it. + for (const c of rollCells(short([...os, ...ps], ROLL_STEP), f, { rows: ROLL_ROWS, step: ROLL_STEP, direction: "falling" })) { + out.push({ x: rollX(c.n.note), y: rollY(ROLL_KEY_ROW - 1 - c.row), unit: OVERLORD, color: colorOf(c.n as ShowNote) }); + } + // The main screen's roll: the piano. + for (const c of rollCells(short(ps, STAGE_STEP), f, { rows: STAGE_ROWS, step: STAGE_STEP, direction: "falling" })) { + const x = stageX(c.n.note), y = VIEW_Y + FALL_Y0 - c.row * ROW_GAP; + if (out.some((p) => overlap(p, x, y)) || before.some((p) => overlap(p, x, y))) continue; + out.push({ x, y, unit: FLAG, color: colorOf(c.n as ShowNote) }); + } + return [...new Map(out.map((p) => [`${p.unit} ${p.x} ${p.y}`, p])).values()]; +} + +const PICTURES: Pixel[][] = []; +/** Every frame's picture, worked out once and in order (each depends on the one before). */ +export function pictureAt(f: number): Pixel[] { + while (PICTURES.length <= f) PICTURES.push(draw(PICTURES.length, PICTURES.length ? PICTURES[PICTURES.length - 1] : [])); + return PICTURES[f]; +} + +/* ── The explosions: the strongest downbeats ── */ + +/** + * The downbeats that get an explosion: in the loud sections (the whole piece when none is), each bar's first beat + * weighed by the velocities of every note struck on it, drums too; the three heaviest at least four bars apart. (Für + * Elise: C16, the ff chord the storm ends on, then C9 and C1 — the three bars the score marks with an accent.) + */ +export const BOOM_BARS: readonly number[] = (() => { + const weight = new Map(); + for (const n of NOTES) if (n[BEAT] === 0 && (!LOUD.length || loudBar(n[BAR]))) weight.set(n[BAR], (weight.get(n[BAR]) ?? 0) + n[VELOCITY]); + const chosen: number[] = []; + for (const [bar] of [...weight].sort((x, y) => y[1] - x[1] || x[0] - y[0])) { + if (chosen.length < 3 && chosen.every((b) => Math.abs(b - bar) >= 4)) chosen.push(bar); + } + return chosen; +})(); +/** + * Each explosion: a frame, a kind (1 a Wraith's, 2 a Battlecruiser's), where. The heaviest downbeat gets three + * Battlecruisers across the stage; the others a Wraith over each note the lead strikes on it (one in the middle if it + * strikes none). Their own explosion sounds are heard (the user's choice). + */ +export const explosions: readonly { frame: number; kind: number; x: number; y: number }[] = (() => { + const list: { frame: number; kind: number; x: number; y: number }[] = []; + BOOM_BARS.forEach((bar, k) => { + const struck = notes.filter((n) => n.bar === bar && n.beat === 0); + const lead = struck.filter((n) => n.part === LEAD_PART); + const frame = Math.min(...struck.map((n) => n.on)); + if (k === 0) for (const dx of [-240, 0, 240]) list.push({ frame, kind: 2, x: CAM_X + 40 + dx, y: VIEW_Y + 110 }); + else if (lead.length) for (const n of lead) list.push({ frame, kind: 1, x: stageX(n.note), y: VIEW_Y + 120 }); + else list.push({ frame, kind: 1, x: CAM_X + 40, y: VIEW_Y + 120 }); + }); + return list.sort((a, b) => a.frame - b.frame); +})(); + +/* ── The tables the program plays back ── */ + +export const CHANGES = changesOver(TOTAL, pictureAt); +/** Where each frame's changes start in the lists below; one more at the end. */ +export const STARTS: number[] = []; +export const CX: number[] = [], CY: number[] = [], CKIND: number[] = [], CTO: number[] = []; +CHANGES.forEach((cs) => { + STARTS.push(CX.length); + for (const c of cs) { CX.push(c.x); CY.push(c.y); CKIND.push(c.unit * 8 + c.from); CTO.push(c.to); } +}); +STARTS.push(CX.length); +export const LABEL_F: number[] = captions.map((l) => l.frame), LABEL_TEXT: string[] = captions.map((l) => l.text); +export const FX_F: number[] = explosions.map((e) => e.frame), FX_K: number[] = explosions.map((e) => e.kind), FX_X: number[] = explosions.map((e) => e.x), FX_Y: number[] = explosions.map((e) => e.y); + +/** The colours of P3 … P8 as the map gives them (the showcase's probe-players line), by colour number. */ +export const RGB: readonly (readonly [number, number, number])[] = [[0, 0, 0], [240, 240, 240], [72, 56, 200], [255, 190, 0], [0, 200, 255], [235, 20, 50], [170, 80, 255]]; +/** Frames worth a look before a play: two in each section, each explosion, the end. */ +export const PREVIEW_FRAMES: readonly number[] = [ + ...SECTIONS.flatMap((s, k) => { + const to = (SECTIONS[k + 1]?.frame ?? LAST_OFF - ZERO); + return [s.frame + Math.round((to - s.frame) / 3), s.frame + Math.round(((to - s.frame) * 2) / 3)].map((f) => ZERO + f); + }), + ...new Set(explosions.map((e) => e.frame)), LAST_OFF - 20, +].sort((a, b) => a - b); diff --git a/tests/fur-elise-showcase-run.test.ts b/tests/fur-elise-showcase-run.test.ts new file mode 100644 index 0000000..8450f02 --- /dev/null +++ b/tests/fur-elise-showcase-run.test.ts @@ -0,0 +1,104 @@ +/** + * The Für Elise showcase's run (probes/lib/fur-elise-showcase-run.ts), from the soundtrack's timeline: the keyboards + * hold every note (folded by octaves where they must), the hands and the loud section are found from the data, the + * explosions land on the strongest downbeats, the picture never asks the game for two Flags it would not make, and the + * changes the program plays back rebuild every frame's picture. + */ +import { describe, expect, it } from "vitest"; +import { isBlack, whiteKeys, type Pixel } from "../probes/lib/note-timeline"; +import { NOTES, PARTS, SECTIONS, BAR, BEAT, VELOCITY } from "../probes/lib/fur-elise-timeline"; +import { CELL, VIEW_X, VIEW_Y } from "../probes/lib/fur-elise-layout"; +import { + BOOM_BARS, CHANGES, FLAG, FX_F, LABEL_F, LAST_OFF, LEAD, LEAD_PART, LOUD, OTHER_PART, OVERLORD, ROLL_COL, ROLL_HI, ROLL_KEYS, ROLL_LO, + STAGE_HI, STAGE_KEYS, STAGE_LO, STAGE_PITCH, STAGE_X0, STARTS, START, TOTAL, ZERO, explosions, flashes, notes, piano, pictureAt, +} from "../probes/lib/fur-elise-showcase-run"; + +describe("the showcase's run", () => { + it("starts the clip LEAD frames before the picture's frame 0, and runs past the last note", () => { + expect(ZERO - START).toBe(LEAD); + expect(LEAD).toBe(2); + expect(TOTAL).toBeGreaterThan(LAST_OFF); + for (const list of [LABEL_F, FX_F, STARTS]) expect(list.every((f, k) => k === 0 || list[k - 1] <= f)).toBe(true); + expect(STARTS.length).toBe(TOTAL + 1); + // Every note on the timeline's own frame, from ZERO. + expect(notes.every((n) => NOTES.some((m) => m[8] + ZERO === n.on))).toBe(true); + }); + + it("finds the hands and the loud section in the data", () => { + expect([PARTS[LEAD_PART], PARTS[OTHER_PART]]).toEqual(["right", "left"]); + expect(LOUD).toEqual(["storm"]); + expect(piano.every((n) => n.part === LEAD_PART || n.part === OTHER_PART)).toBe(true); + }); + + it("fits both keyboards: the main screen every key the hands play, 40 white keys 16 apart inside the view", () => { + expect([STAGE_LO, STAGE_HI]).toEqual([33, 100]); + expect(whiteKeys(STAGE_LO, STAGE_HI).length).toBe(40); + expect(STAGE_PITCH).toBe(16); + expect(STAGE_X0 + 39 * STAGE_PITCH).toBe(830); + for (const n of piano) expect(STAGE_KEYS.fold(n.note)).toBe(n.note); + // The minimap: 64 columns, every note on one of them. + expect(ROLL_HI - ROLL_LO + 1).toBeLessThanOrEqual(64); + expect(ROLL_COL).toBeGreaterThanOrEqual(0); + for (const n of notes) { const k = ROLL_KEYS.fold(n.note); expect(k >= ROLL_LO && k <= ROLL_HI && k % 12 === n.note % 12).toBe(true); } + expect(isBlack(ROLL_LO) || isBlack(ROLL_HI)).toBe(false); + }); + + it("explodes on the three strongest downbeats of the loud section, the strongest with Battlecruisers", () => { + const storm = SECTIONS.find((s) => s.name === "storm")!; + const weight = (bar: number) => NOTES.filter((n) => n[BAR] === bar && n[BEAT] === 0).reduce((s, n) => s + n[VELOCITY], 0); + expect(BOOM_BARS.length).toBe(3); + expect(BOOM_BARS.every((b) => b > storm.bar)).toBe(true); + expect(weight(BOOM_BARS[0])).toBeGreaterThanOrEqual(Math.max(weight(BOOM_BARS[1]), weight(BOOM_BARS[2]))); + // For Für Elise these are the bars the score marks with an accent: C1, C9 and C16. + expect([...BOOM_BARS].sort((a, b) => a - b)).toEqual([storm.bar + 1, storm.bar + 9, storm.bar + 16]); + expect(explosions.filter((e) => e.kind === 2).length).toBe(3); + }); + + it("flashes the white keys red only in the loud section, on the lead's chords", () => { + const storm = SECTIONS.find((s) => s.name === "storm")!, closing = SECTIONS.find((s) => s.name === "closing")!; + expect(flashes.size).toBeGreaterThan(20); + for (const f of flashes) expect(f >= ZERO + storm.frame && f < ZERO + closing.frame + 2).toBe(true); + }); + + it("never asks for a Flag overlapping another of its frame or of the frame before", () => { + const close = (a: Pixel, b: Pixel) => Math.abs(a.x - b.x) < 16 && Math.abs(a.y - b.y) < 16 && (a.x !== b.x || a.y !== b.y); + let before: Pixel[] = []; + for (let f = 0; f < TOTAL; f++) { + const flags = pictureAt(f).filter((p) => p.unit === FLAG); + for (const p of flags) { + const bad = flags.find((q) => close(p, q)) ?? before.find((q) => close(p, q)); + if (bad) throw new Error(`frame ${f}: ${p.x},${p.y} beside ${bad.x},${bad.y}`); + } + before = flags; + } + }); + + it("plays back changes that rebuild every frame's picture, the units on the map well under the game's 1,700", () => { + const shown = new Map(); + let most = 0; + CHANGES.forEach((cs, f) => { + for (const c of cs) { + const k = `${c.unit} ${c.x} ${c.y}`; + expect(shown.get(k) ?? 0).toBe(c.from); + if (c.to) shown.set(k, c.to); + else shown.delete(k); + } + if (f % 50 === 0) { + const want = pictureAt(f); + expect(shown.size).toBe(want.length); + for (const p of want) expect(shown.get(`${p.unit} ${p.x} ${p.y}`)).toBe(p.color); + } + most = Math.max(most, shown.size); + }); + expect(most).toBeLessThan(700); + }); + + it("keeps the Overlords on the minimap's cells and the Flags in the view, right of the text", () => { + for (let f = 0; f < TOTAL; f += 11) { + for (const p of pictureAt(f)) { + if (p.unit === OVERLORD) expect((p.x - CELL / 2) % CELL === 0 && (p.y - CELL / 2) % CELL === 0 && p.y < 92 * 32).toBe(true); + else expect(p.x >= VIEW_X + 200 && p.x <= VIEW_X + 836 && p.y >= VIEW_Y + 16 && p.y <= VIEW_Y + 300).toBe(true); + } + } + }); +}); From f424f466ef85c0b6e4df174bdb2d6e3aeba56a1b Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 05:57:59 -0600 Subject: [PATCH 20/31] Plan: the S7 showcase build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit How the showcase is built and why it is generic over the timeline, the choices for Für Elise as it is now (the key range, the orchestra on the minimap), what was checked and what turned up on the way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index 7d3b300..b9e3d0a 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6718,6 +6718,52 @@ Disruption Web in Remastered either. The explosions show on the downbeats. **Chosen (the user, 2026-11-09):** falling notes; the main screen a row every other frame (A2); the storm with red flashes on each chord and explosions on the big downbeats only (their game sounds heard). +#### S7 the showcase build (built 2026-11-09) + +Branch `fur-elise-visual`, with `fur-elise` (the soundtrack) merged in. `probes/fur-elise-showcase.ts`, lobby "Für +Elise": the whole piece as one clip, started two frames before the picture's frame 0 (the probe's ~95 ms becomes +~11 ms), the picture played back from tables worked out when the script is built. + +**Generic over the timeline.** The soundtrack will change (an arrangement in a style still to choose), so +`probes/lib/fur-elise-showcase-run.ts` takes everything from `probes/lib/fur-elise-timeline.ts` (made again by +`fur-elise-timeline-gen.mts`): +- *The hands:* parts "right" and "left" when there are, else the two pitched parts with the most notes (the higher the + lead). Drum parts (by name: drum, kit, perc, kick, snare, hat, cymbal, clap) are drawn on no roll; they still weigh + in the downbeats. +- *The keyboards:* `fitKeys` (in `probes/lib/note-timeline.ts`, tested) takes the window of keys that holds the most + notes within a limit and moves the rest in by octaves. Main screen: at most 40 white keys, 16–20 px apart, the last at + view x 830. Minimap: at most 64 keys, the map's columns of cells. +- *The loud sections:* those whose mean velocity is at least 1.25 times the piece's. There the lead's chords (two or + more notes on one bar and beat) are red and the white keys flash red for two frames on each. +- *The explosions:* the downbeats of the loud sections weighed by the velocities struck on them, the three heaviest at + least four bars apart; the heaviest gets three Battlecruisers across the stage, the others a Wraith over each lead + note. For Für Elise that picks C16, C9 and C1, the three bars the score marks with an accent. +- *The end:* the end line 48 frames after the last note is let go, the tables 15 s past it; then the program stops + and the game waits, the keyboard up. + +**Für Elise as it is now** (the 3:33 soundtrack, a stand-in until the arrangement is chosen): the hands play A1 … E7, 68 +keys. The main screen holds all of them: 40 white keys 16 px apart from view x 206 (the probe's 20 px would need +800); a Spider Mine is 15 px square, so 16 apart never overlap, and only A1 and B1 sit under where the text lines +show. The minimap's 64 columns take A1 … C7, so E7's run shows an octave down there. The orchestra (violins … timpani, +the storm only) is drawn on the minimap in violet, under the piano: the minimap then shows the storm as the full +arrangement it is, while the main screen stays a piano keyboard; the orchestra's notes on the stage's keys would light +keys the piano does not play. Colours by owner (CRGB): P3 white keys, P4 indigo black keys, P5 gold right hand, P6 +cyan left hand, P7 red, P8 violet. The sync lamp is gone. + +**Checked.** `tests/fur-elise-showcase-run.test.ts` (keyboards, hands, loud section, explosions, flashes, no overlapping +Flags, the changes rebuild the pictures); in the lifted game the test "every frame of the piece shows the picture +worked out" holds over all 5,180 frames, and none of the explosions' units outlives its frame. The text test reads the +end line by its ASCII part: the lifted game shows the map's UTF-8 as Latin-1 ("Für"), where Remastered showed the ü in +the probe's lobby. + +**Found on the way:** +- The soundtrack had to be importable without its probe's program: `probes/lib/fur-elise-soundtrack.ts` holds it now, + `probes/fur-elise.ts` imports it (the same six clips by name, the timeline the same to the byte). +- A script that imports media (a `.samples`, `.sound`, …) could not run beside the game for its tests: the game host + ran the modules without the media. `GameTestPayload.media` carries them now (`scripts/test-game.mts` passes them; + `tests/game-media.test.ts`). The editor's host does not pass them yet. +- A module-level name `together` collides with the library's (as `sounds` did in the probe). + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice From 1360be3f6279a010797d5a31a137cd307fedec21 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 06:03:12 -0600 Subject: [PATCH 21/31] Tuning checks, a kit from recordings, music.hits and the trailer presets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit scripts/tuning-check.mts measures a render against its timeline: for each pitch, the median cents of its fundamental and second harmonic just after each onset (FFT, parabola), flagging a pitch more than 25 cents off (above C6 the piano's stretch allowed; under 200 Hz judged by the second harmonic, which 0.2 s can place). From the coordinator's script that found B3/C4/C#4 a semitone sharp. The straight soundtrack, re-rendered: 60 pitches, none off. scripts/samples-tuning.mts measures each pitched zone's recording of a .samples file against its key and tune, flagging a zone whose fundamental and second harmonic are both off. The probe's instruments: none off in the piano (with the stretch above C6), the string sections or the trombone; the horn's G2 zones (+34 and −79 cents), the tuba's F1 (−39), the fifth timpani's ff (+40) and some timpani rolls are — none of them in the notes the arrangements play. make-samples --kit: percussion, a key a drum, from a JSON of name patterns; strengths read from "v3" or ppp … fff in the names, the rest played in turn. `music.hits({ C2: clip, … })`: one-shots as a part of a performance, each whole and unpitched at its velocity. Presets braam (a trailer's low blast), pulse (a sixteenth ostinato) and sub. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- compiler/generated/stdlib.ts | 2 +- ledger/sounds/music-hits.ts | 12 +++++ scripts/make-samples.mts | 47 ++++++++++++++++-- scripts/samples-tuning.mts | 78 ++++++++++++++++++++++++++++++ scripts/tuning-check.mts | 93 ++++++++++++++++++++++++++++++++++++ stdlib/music.ts | 31 +++++++++++- tests/make-samples.test.ts | 23 ++++++++- tests/sampled.test.ts | 21 ++++++++ 8 files changed, 301 insertions(+), 6 deletions(-) create mode 100644 ledger/sounds/music-hits.ts create mode 100644 scripts/samples-tuning.mts create mode 100644 scripts/tuning-check.mts diff --git a/compiler/generated/stdlib.ts b/compiler/generated/stdlib.ts index c7ea8f0..f78e5ab 100644 --- a/compiler/generated/stdlib.ts +++ b/compiler/generated/stdlib.ts @@ -3,7 +3,7 @@ export const STDLIB_SOURCES: Readonly> = { "cutscene": "/**\n * Scenes acted out in the game: the standard library's \"trigscript/cutscene\" (TrigScript 4).\n *\n * import { Camera, walk, line, play, SECOND } from \"trigscript/cutscene\";\n *\n * async function intro(raider: Unit) {\n * const cam = new Camera(raider.x, raider.y);\n * await line(units.JimRaynorMarine, \"Something's moving out there.\", 3 * SECOND);\n * const there = start(walk(raider, 1200, 640)); // the walk goes on while the camera follows\n * await cam.follow(raider, 2 * SECOND);\n * await there;\n * await cam.pan(1600, 400, 2 * SECOND);\n * await cam.shake(12);\n * }\n *\n * program(async () => {\n * const raider = first(unitsAt(locations.Base, { owner: P1, type: units.TerranMarine }));\n * if (!raider) return;\n * const skipped = await play(P1, start(intro(raider))); // Escape skips the rest of it\n * if (skipped) print(\"Skipped.\");\n * });\n *\n * Everything here is what a trigger can do, done a frame at a time: the camera is Center View on a location the library\n * keeps for itself, moved to where the camera should look; a unit walks by a Move order to another; a line is the\n * speaker's portrait talking and the words in the middle of the screen. Places are pixels (32 a tile), (0, 0) the map's\n * top left; time is frames of the game, 24 a second on Fastest (`SECOND`). The camera is the one of the player the\n * program runs as, as Center View's is.\n */\nimport { centerLocation, centerView, reserveLocation, talkingPortrait, print, sleep, frames, nextFrame, keyPressed, type Player, type Task, type Unit, type UnitType } from \"trigscript\";\nimport { easeInOutQuad, easeInQuad, easeOutQuad, easeOutBack } from \"trigscript/math\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nexport const SECOND = 24;\n\nconst VIEW = reserveLocation(\"cutscene: where the camera looks\");\nconst GOAL = reserveLocation(\"cutscene: where a unit is sent\");\n\n/** How a glide speeds up and slows down: evenly, starting slow, ending slow, both, or ending past the mark and back. */\nexport type Ease = \"linear\" | \"in\" | \"out\" | \"inOut\" | \"back\";\n\n/** How far along a glide is at `t` (0 at its start, 1 at its end), as `ease` has it. */\nfunction eased(t: fixed, ease: Ease): fixed {\n if (ease === \"in\") return easeInQuad(t);\n if (ease === \"out\") return easeOutQuad(t);\n if (ease === \"inOut\") return easeInOutQuad(t);\n if (ease === \"back\") return easeOutBack(t);\n return t;\n}\n\n/**\n * The camera of the player the program runs as: where it looks, and how it gets somewhere else. It looks at its first\n * place as soon as it is made.\n */\nexport class Camera {\n /** The point the camera is centred on, in pixels. */\n x: number;\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /** Look at a point, now. */\n look(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /**\n * Glide to a point over `time` frames, looking at each place on the way a frame at a time.\n * @param ease How it speeds up and slows down; \"inOut\" unless it says.\n */\n async pan(x: number, y: number, time: number, ease: Ease = \"inOut\") {\n const fromX = this.x;\n const fromY = this.y;\n let i = 1;\n while (i <= time) {\n const k = eased(fixed(i) / time, ease);\n this.look(fromX + Math.round((x - fromX) * k), fromY + Math.round((y - fromY) * k));\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n\n /** Keep a unit in the middle of the screen for `time` frames, or until it is gone. */\n async follow(u: Unit, time: number) {\n let i = 0;\n while (i < time && u) {\n this.look(u.x, u.y);\n await nextFrame();\n i++;\n }\n }\n\n /** Shake for `time` frames, `size` pixels each way (8 unless it says), and settle where it was. */\n async shake(time: number, size: number = 8) {\n const x = this.x;\n const y = this.y;\n let i = 0;\n while (i < time) {\n const left = (i % 4) < 2;\n const up = (i % 2) === 0;\n centerLocation(VIEW, left ? x - size : x + size, up ? y - size : y + size);\n centerView(VIEW);\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n}\n\n/**\n * Send a unit to a point by a Move order, and wait until it is there — within `near` pixels (48 unless it says) — or\n * `limit` frames have passed (30 seconds unless it says), or it is gone.\n * @returns Whether it got there.\n */\nexport async function walk(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"move\", near, limit);\n}\n\n/** The same with an Attack order: the unit fights what it meets on the way. */\nexport async function charge(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"attack\", near, limit);\n}\n\nasync function go(u: Unit, x: number, y: number, how: \"move\" | \"attack\", near: number, limit: number): Promise {\n centerLocation(GOAL, x, y);\n u.order(how, GOAL);\n let waited = 0;\n while (u && Math.abs(u.x - x) + Math.abs(u.y - y) > near && waited < limit) {\n await nextFrame();\n waited++;\n }\n return !!u && Math.abs(u.x - x) + Math.abs(u.y - y) <= near;\n}\n\n/**\n * Send every unit of a group to a point together, and wait until each is there, gone, or `limit` frames have passed.\n * @returns How many got there.\n */\nexport async function walkAll(group: Unit[], x: number, y: number, near: number = 64, limit: number = 30 * SECOND): Promise {\n centerLocation(GOAL, x, y);\n for (const u of group) if (u) u.order(\"move\", GOAL);\n let waited = 0;\n let there = 0;\n while (waited < limit) {\n there = 0;\n let moving = 0;\n for (const u of group) {\n if (!u) continue;\n if (Math.abs(u.x - x) + Math.abs(u.y - y) <= near) there++;\n else moving++;\n }\n if (moving === 0) break;\n await nextFrame();\n waited++;\n }\n return there;\n}\n\n/**\n * A line of the scene: the speaker's portrait talks and the words show in the middle of the screen, for `time` frames\n * (3 seconds unless it says), and then the scene goes on.\n */\nexport async function line(speaker: UnitType, text: string, time: number = 3 * SECOND) {\n talkingPortrait(speaker, Math.round((time * 1000) / SECOND));\n print(text, { position: \"center\" });\n await sleep(frames(time));\n}\n\n/**\n * Play a scene, started as a task (`start(intro())`), for a player who may skip it: when they press `key` (Escape unless\n * it says) the scene stops where it is. Put things where the scene would have left them when it gives true.\n * @returns Whether it was skipped.\n */\nexport async function play(player: Player, scene: Task, key: \"Escape\" | \"Space\" | \"Enter\" = \"Escape\"): Promise {\n while (scene.running) {\n if (keyPressed(player, key)) {\n scene.cancel();\n return true;\n }\n await nextFrame();\n }\n return false;\n}\n", "fog": "/**\n * Fog of war as a picture: the standard library's \"trigscript/fog\" (TrigScript 4).\n *\n * import { fog } from \"trigscript/fog\";\n *\n * const heart = fog.picture([\".##.##.\", \"#######\", \".#####.\", \"..###..\"]);\n *\n * program(async () => {\n * fog.reveal(P1); // the whole map lit once: from now on dark is fog, not black\n * while (true) {\n * fog.light(P1, 30, 20, 5); // a disc of size 5 around tile (30, 20), this frame only\n * fog.light(P1, 60, 40, heart); // a picture, its top left on tile (60, 40)\n * await nextFrame();\n * }\n * });\n *\n * The fog is a canvas that starts every frame dark: what a program lights this frame is what shows this frame, and\n * nothing else needs doing. There is no dark brush — the game's sight only ever reveals — so dark is whatever is not\n * lit; to draw dark shapes, light around them (a picture with `{ ink: \"dark\" }`). Dark is also the sharper ink: a lit\n * part is at least a brush wide (3 tiles across, 4 down), while a dark line one tile wide stays exactly that. Nothing\n * else needs doing — the library writes the game's vision countdown after every frame (memory.vision.countdown), so\n * the next frame starts from a wiped board. Watch it on the minimap. With Classic graphics (Options > Graphics) a tile\n * of the map is a pixel there, sharp; Remastered graphics blurs it a few tiles wide.\n *\n * What the board is made of decides how far apart lit and fog look. Remastered draws a tile on the minimap as the\n * average of its art and fog as 0.64 of lit, whatever the tile, so the brightest art is the best board there: plain\n * Ice snow (lit 130 against fog 82, measured 2026-10-19). Classic draws a tile as one colour of its own; Badlands\n * tile 23778 is the widest apart there, and dim and textured in Remastered. Snow played the better of the two.\n *\n * How it draws, played in StarCraft: Remastered (2026-10-17): a brush is a unit made on a tile and taken away in the\n * same trigger pass; the tiles its sight revealed stay lit through the frame. A brush's size is the unit's sight\n * range, so each size is a unit type of its own — the flying heroes below, which no ordinary map places — whose sight\n * is set every frame (Remastered takes a sight write a frame late, so one type cannot change size within a frame).\n * Coordinates are tiles, (0, 0) the map's top left. About 800 brushes a frame is the most the game makes: it keeps a\n * removed unit's place until the next frame.\n */\nimport { game, program, sleep, frames, stats, units, createUnit, removeUnit, centerLocation, reserveLocation, memory, cover, nextFrame, type Player, type UnitType, type Video } from \"trigscript\";\n\n/**\n * Each brush's shape, sizes 1 to 11: the tiles a flying unit of that sight range reveals, read out of the game.\n * \"@\" is the tile the brush is centred on. The game's air sight leaves the centre's row one short below, so every\n * shape reaches a row further up than down.\n */\nexport const SHAPES: readonly (readonly string[])[] = [\n // 1\n [\"###\", \"###\", \"#@#\", \"###\"],\n // 2\n [\".###.\", \"#####\", \"#####\", \"##@##\", \"#####\", \"#####\"],\n // 3\n [\"..###..\", \"#######\", \"#######\", \"#######\", \"###@###\", \"#######\", \"#######\", \"#######\"],\n // 4\n [\"..#####...\", \".#######..\", \"#########.\", \"##########\", \"##########\", \"####@#####\", \"##########\", \"##########\", \"#########.\", \".#######..\", \"......#...\"],\n // 5\n [\"...#####....\", \"..#######...\", \".#########..\", \"###########.\", \"############\", \"############\", \"#####@######\", \"############\", \"############\", \"###########.\", \".#########..\", \"..#######...\", \".......#....\"],\n // 6\n [\"....#####.....\", \"..#########...\", \".###########..\", \"#############.\", \"#############.\", \"##############\", \"##############\", \"######@#######\", \"##############\", \"##############\", \"#############.\", \"#############.\", \".###########..\", \"..#########...\", \"........#.....\"],\n // 7\n [\".....#####......\", \"...#########....\", \"..###########...\", \".#############..\", \"###############.\", \"###############.\", \"################\", \"################\", \"#######@########\", \"################\", \"################\", \"###############.\", \"###############.\", \".#############..\", \"..###########...\", \"...#########....\", \".........#......\"],\n // 8\n [\"......#####.......\", \"....#########.....\", \"..#############...\", \".###############..\", \".###############..\", \"#################.\", \"#################.\", \"##################\", \"##################\", \"########@#########\", \"##################\", \"##################\", \"#################.\", \"#################.\", \".###############..\", \".###############..\", \"..#############...\", \"....#########.....\", \"..........#.......\"],\n // 9\n [\"......#######.......\", \"....###########.....\", \"...#############....\", \"..###############...\", \".#################..\", \"###################.\", \"###################.\", \"####################\", \"####################\", \"####################\", \"#########@##########\", \"####################\", \"####################\", \"####################\", \"###################.\", \"###################.\", \".#################..\", \"..###############...\", \"...#############....\", \"....###########.....\", \"........#####.......\"],\n // 10\n [\".......#######........\", \".....###########......\", \"....#############.....\", \"..#################...\", \"..#################...\", \".###################..\", \"#####################.\", \"#####################.\", \"######################\", \"######################\", \"######################\", \"##########@###########\", \"######################\", \"######################\", \"######################\", \"#####################.\", \"#####################.\", \".###################..\", \"..#################...\", \"..#################...\", \"....#############.....\", \".....###########......\", \".........#####........\"],\n // 11\n [\"........#######.........\", \"......###########.......\", \"....###############.....\", \"...#################....\", \"..###################...\", \".#####################..\", \".#####################..\", \"#######################.\", \"#######################.\", \"########################\", \"########################\", \"########################\", \"###########@############\", \"########################\", \"########################\", \"########################\", \"#######################.\", \"#######################.\", \".#####################..\", \".#####################..\", \"..###################...\", \"...#################....\", \"....###############.....\", \"......###########.......\", \"..........#####.........\"],\n];\n\n/** Each size's unit, size 1 first: flying heroes without a sight upgrade. A map that places one gets odd sight from it. */\nconst BRUSHES: readonly UnitType[] = [\n units.KukulzaMutalisk, units.KukulzaGuardian, units.YggdrasillOverlord, units.MagellanScienceVessel,\n units.GantrithorCarrier, units.HyperionBattlecruiser, units.NoradIIBattlecruiser, units.TomKazanskyWraith,\n units.DanimothArbiter, units.MojoScout, units.ArtanisScout,\n];\n\n/** Where each brush is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"fog: where each brush is made\");\n\n/**\n * One disc: the tiles a brush of `size` covers (SHAPES), centred on tile (x, y). What light() does with a size. A brush\n * is a unit made where SPOT is and taken away again at once; each branch makes its own size's, so that the unit type\n * of the action is known when the script is built (one given by the program costs writing it into the action).\n */\nconst disc = game((player: Player, x: number, y: number, size: number) => {\n discPx(player, x * 32 + 16, y * 32 + 16, size);\n});\n\n/**\n * disc() in pixels, (px, py) the centre of the tile: what a caller with many brushes uses, its products by 32 worked\n * out once and the brushes' offsets added (a product by 32 of a number the game holds is a test a bit, about 0.4 µs).\n */\nconst discPx = game((player: Player, px: number, py: number, size: number) => {\n centerLocation(SPOT, px, py, 32, 32);\n switch (size) {\n case 0: case 1: createUnit(player, BRUSHES[0], 1, SPOT); removeUnit(player, BRUSHES[0]); break;\n case 2: createUnit(player, BRUSHES[1], 1, SPOT); removeUnit(player, BRUSHES[1]); break;\n case 3: createUnit(player, BRUSHES[2], 1, SPOT); removeUnit(player, BRUSHES[2]); break;\n case 4: createUnit(player, BRUSHES[3], 1, SPOT); removeUnit(player, BRUSHES[3]); break;\n case 5: createUnit(player, BRUSHES[4], 1, SPOT); removeUnit(player, BRUSHES[4]); break;\n case 6: createUnit(player, BRUSHES[5], 1, SPOT); removeUnit(player, BRUSHES[5]); break;\n case 7: createUnit(player, BRUSHES[6], 1, SPOT); removeUnit(player, BRUSHES[6]); break;\n case 8: createUnit(player, BRUSHES[7], 1, SPOT); removeUnit(player, BRUSHES[7]); break;\n case 9: createUnit(player, BRUSHES[8], 1, SPOT); removeUnit(player, BRUSHES[8]); break;\n case 10: createUnit(player, BRUSHES[9], 1, SPOT); removeUnit(player, BRUSHES[9]); break;\n default: createUnit(player, BRUSHES[10], 1, SPOT); removeUnit(player, BRUSHES[10]);\n }\n});\n\n/**\n * Light the whole map once, so that from now on a tile left dark shows as fog (grey) rather than as never seen\n * (black) — every picture then has the same two tones. Takes one frame.\n * @param player Whose fog: P1 … P8, known when the script is built.\n */\nexport const reveal = game((player: Player) => {\n const width = memory.map.width;\n const height = memory.map.height;\n // Size 11 is 23 tiles wide: a brush every 14 tiles leaves no gap, and one more past the end, kept inside, reaches the edge.\n for (let y = 2; y < height + 12; y += 14) {\n for (let x = 2; x < width + 12; x += 14) disc(player, Math.min(x, width - 3), Math.min(y, height - 3), 11);\n }\n});\n\n/**\n * Light a rectangle of tiles for this frame, worked out while the game runs: its top left on tile (x, y), `width`\n * tiles across and `height` down. Every one of the five may change from frame to frame — the walls of a raycaster, a\n * bar of a chart. It is exact from 3 × 4 up (the smallest brush); a thinner one is lit a brush wide, centred.\n *\n * fog.rect(P1, 10, 20, 3, wall); // a column 3 tiles wide, `wall` tall\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of its left edge.\n * @param y The row of its top edge.\n * @param width How many tiles across.\n * @param height How many tiles down.\n */\nexport const rect = game((player: Player, x: number, y: number, width: number, height: number) => {\n if (width < 1 || height < 1) return;\n // Size 1 is 3 tiles across and 4 down, its centre the middle column and the third row: a grid of them, the last\n // column and row moved back to end on the edge (overlapping the one before), covers the rectangle exactly.\n const right = Math.max(x + width - 2, x + 1);\n const bottom = Math.max(y + height - 2, y + 2);\n // (The brush made here, not through disc(): its unit type is then known when the script is built, which makes the\n // action a constant — a size from the program costs a branch and a written field a brush.)\n let cy = y + 2;\n while (true) {\n let cx = x + 1;\n while (true) {\n centerLocation(SPOT, cx * 32 + 16, cy * 32 + 16, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (cx >= right) break;\n cx = Math.min(cx + 3, right);\n }\n if (cy >= bottom) break;\n cy = Math.min(cy + 4, bottom);\n }\n});\n\n/** A picture for the fog, made when the script is built: its size in tiles and the brushes that draw it. */\nexport interface Picture {\n readonly width: number;\n readonly height: number;\n readonly brushes: readonly { readonly x: number; readonly y: number; readonly size: number }[];\n}\n\n/**\n * A picture from rows of text, worked out when the script is built: `#` is the ink, anything else is not.\n *\n * fog.picture([\"..##..\", \".####.\", \"######\"]) // light ink: the # tiles are lit\n * fog.picture([\"..##..\", \".####.\", \"######\"], { ink: \"dark\" }) // dark ink: the # tiles stay dark, the rest is lit\n *\n * With light ink a lit part thinner than a brush (3 tiles across, 4 down) is drawn a tile or two thicker. An image's\n * halftone (`fog.picture(photo.halftone(6))`) is drawn with the brushes it was made of, one a cell. With dark\n * ink every tile of the picture's rectangle that is not `#` is lit and the `#` tiles keep their shape exactly,\n * however thin — the ink for line art and silhouettes.\n */\nexport function picture(rows: readonly string[], options: { readonly ink?: \"light\" | \"dark\" } = {}): Picture {\n const height = rows.length;\n const width = Math.max(0, ...rows.map((r) => r.length));\n // An image's halftone (image.halftone(6)) comes with the brushes that drew it: a brush a cell, as they are.\n const drawn = (rows as { readonly brushes?: readonly { readonly x: number; readonly y: number; readonly shape: number }[] }).brushes;\n if (drawn && options.ink !== \"dark\") return Object.freeze({ width, height, brushes: Object.freeze(drawn.map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }))) });\n // Dark ink: the picture's rectangle lit but for the # tiles, so what is covered is the rest.\n const ink = options.ink === \"dark\" ? Array.from({ length: height }, (_, y) => Array.from({ length: width }, (_, x) => (rows[y][x] === \"#\" ? \".\" : \"#\")).join(\"\")) : rows;\n const brushes = cover(ink, SHAPES).map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }));\n return Object.freeze({ width, height, brushes: Object.freeze(brushes) });\n}\n\n/**\n * A video's frames as brushes, worked out when the script is built: a word a brush (x | y << 8 | size << 16), the\n * frames one after another, and where each one starts — the tables the game reads a frame from. Once a build.\n */\ninterface Film { readonly words: readonly number[]; readonly starts: readonly number[] }\nconst films = new Map();\nfunction film(video: Video): Film {\n const had = films.get(video);\n if (had) return had;\n const words: number[] = [], starts: number[] = [0];\n for (const brushes of cover(video, SHAPES)) {\n for (const b of brushes) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n starts.push(words.length);\n }\n const made = { words, starts };\n films.set(video, made);\n return made;\n}\n\n/**\n * Light the fog for this frame: a disc, a picture or a frame of a video. Tiles count from the map's top left, (0, 0).\n *\n * fog.light(P1, 30, 20, 5); // a disc of size 5 centred on tile (30, 20)\n * fog.light(P1, 60, 40, heart); // a picture (fog.picture), its top left on tile (60, 40)\n * fog.light(P1, 0, 0, badApple, f); // frame f of a video the script imports, its top left on tile (0, 0)\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The tile's column: a disc's centre, a picture's left edge.\n * @param y The tile's row: a disc's centre, a picture's top edge.\n * @param shape A size, 1 (3 tiles wide) to 11 (23 wide) — it may change while the game runs — a picture, or a video.\n * @param frame Of a video, which frame, from 0: it may change while the game runs. Past the end, nothing is lit.\n */\nexport const light = game((player: Player, x: number, y: number, shape: number | Picture | Video, frame: number = 0) => {\n if (typeof shape === \"number\") disc(player, x, y, shape);\n else {\n // The picture's corner in pixels once; each brush is its offset from there (a constant of a picture).\n const px = x * 32 + 16, py = y * 32 + 16;\n if (\"brushes\" in shape) for (const b of shape.brushes) discPx(player, px + b.x * 32, py + b.y * 32, b.size);\n else {\n const { words, starts } = film(shape);\n const end = starts[frame + 1];\n for (let i = starts[frame]; i < end; i++) {\n const w = words[i];\n // (A row's offset in pixels straight from its byte: the same as ((w >> 8) & 255) * 32, and the shift only has\n // the byte's eight bits to look at.)\n discPx(player, px + (w & 255) * 32, py + ((w & 0xff00) >> 3), w >> 16);\n }\n }\n }\n});\n\n/**\n * Play a video in the fog, a frame of it every frame of the game, from its first to its last; resolves when it ends.\n * Inside an async program: `await fog.play(P1, badApple)`. On Fastest a game frame is 42 ms, which is what Import\n * Video makes a video's frames by default; the game runs a little slower when a frame is heavy, and so does the video.\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param video A video the script imports.\n * @param x The column of its left edge, 0 by default.\n * @param y The row of its top edge, 0 by default.\n */\nexport const play = game(async (player: Player, video: Video, x: number = 0, y: number = 0) => {\n // (A while: a for over a length known when the script is built would be unrolled, a copy of the body a frame.)\n let f = 0;\n while (f < video.length) {\n light(player, x, y, video, f);\n await nextFrame();\n f++;\n }\n});\n\n/**\n * How fog.columns() lays its columns out, known when the script is built: `count` columns side by side, each `width`\n * tiles across (3, a brush's width, by default) and up to `height` tiles tall, centred on the middle row. `ink`:\n * \"light\" lights each column (the walls of a raycaster bright, on fog), \"dark\" lights all but the columns (dark walls\n * between a lit ceiling and floor); dark is cheaper when columns fill most of the board, light when they are short.\n */\nexport interface ColumnLayout {\n readonly count: number;\n readonly height: number;\n readonly width?: number;\n readonly ink?: \"light\" | \"dark\";\n /**\n * How the walls are told apart, with fog.columns()'s `faces`. \"outline\", the default: every wall drawn as its edges —\n * its top and bottom, a brush deep, and a column lit whole wherever one face meets another (on the nearer of the\n * two) — so that blocks read as boxes, the look of the raycasters of monochrome screens; with dark ink, the edges are\n * lit lines through dark walls. A few brushes a column. Chosen over the rest when played (2026-10-17).\n *\n * The others shade the faces whose number is odd (a raycaster's other side) and leave the rest whole: \"hollow\" —\n * dark, lit only along its top and bottom edges; \"ribbed\" — hollow and lit across the middle of each half; \"panelled\"\n * — hollow and lit across its quarters; \"line\" / \"lines\" — dark lines a tile thick across it at its middle or its\n * quarters (the finest, and two dozen brushes a column near the eye: for a view with room to spare).\n */\n readonly shading?: \"outline\" | \"lines\" | \"line\" | \"hollow\" | \"ribbed\" | \"panelled\";\n}\n\n/**\n * What fog.columns() reads, worked out once a layout when the script is built: for each level of the drawing that is\n * wider than a column (all the columns, a group of them, the last group) and each depth from 0 to half the height, the\n * brushes that cover a rectangle that wide and that deep exactly — the encoder's covers (cover()), a few large brushes\n * in the middle and small ones at the edges. A brush is a word, dx | dy << 8 | size << 16 from the rectangle's top\n * left; `starts` says where each (level, depth) begins.\n */\ninterface ColumnPlan { readonly words: readonly number[]; readonly starts: readonly number[]; readonly group: number; readonly half: number }\nconst columnPlans = new Map();\nconst COLUMN_GROUP = 6;\nfunction columnPlan(layout: ColumnLayout): ColumnPlan {\n const width = layout.width ?? 3, half = layout.height >> 1, group = Math.min(COLUMN_GROUP, layout.count);\n const key = `${layout.count}:${width}:${half}`;\n const had = columnPlans.get(key);\n if (had) return had;\n const words: number[] = [], starts: number[] = [];\n for (const columns of [layout.count, group, layout.count % group || group]) {\n for (let depth = 0; depth <= half; depth++) {\n starts.push(words.length);\n if (depth === 0) continue;\n // A rectangle shallower than a brush is drawn a brush deep, the rest of it on what the level before lit.\n const rows = Array.from({ length: Math.max(depth, 4) }, () => \"#\".repeat(columns * width));\n for (const b of cover(rows, SHAPES)) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n }\n }\n starts.push(words.length);\n const made = { words, starts, group, half };\n columnPlans.set(key, made);\n return made;\n}\n\n/**\n * One rectangle of fog.columns() wider than a column: the cover at `at` (a level and a depth) drawn twice, the half\n * above the middle and the half below, its top rows `top` and `bottom`, from column `x`.\n */\nconst columnRect = game((player: Player, words: readonly number[], starts: readonly number[], at: number, x: number, top: number, bottom: number) => {\n let i = starts[at];\n const end = starts[at + 1];\n // In pixels once; each brush is its offset (a few bits, a few tests) from there.\n const px = x * 32 + 16, pt = top * 32 + 16, pb = bottom * 32 + 16;\n while (i < end) {\n const w = words[i];\n const dx = (w & 255) * 32, dy = (w & 0xff00) >> 3, size = w >> 16;\n discPx(player, px + dx, pt + dy, size);\n discPx(player, px + dx, pb + dy, size);\n i++;\n }\n});\n\n/**\n * One column's part of fog.columns(), in pixels: brushes (3 × 4) a column of 4 rows apart and the last moved back to\n * end on the edge, twice — from `pt` and from `pb`, the centres of the first brush of each — down a column `k32`\n * pixels deep (32 a row; under 4 rows, a brush deep), centred on `px`. What the smallest brush covers exactly, worked out\n * here rather than read: it is the most common rectangle by far. In pixels because the caller has them, stepped: a\n * product by 32 of a number the game holds is a test a bit, about 0.4 µs, where a step is an add.\n */\nconst columnBarPx = game((player: Player, px: number, pt: number, pb: number, k32: number) => {\n // How far down the last brush is from the first.\n const end = Math.max(k32, 128) - 128;\n let r = 0;\n while (true) {\n centerLocation(SPOT, px, pt, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n centerLocation(SPOT, px, pb, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (r >= end) break;\n const step = Math.min(end - r, 128);\n r += step;\n pt += step;\n pb += step;\n }\n});\n\n/** columnBarPx() in tiles: `k` rows from row `top` down and from row `bottom` down, centred on column `x`. */\nconst columnBar = game((player: Player, x: number, top: number, bottom: number, k: number) => {\n columnBarPx(player, x * 32 + 16, top * 32 + 80, bottom * 32 + 80, k * 32);\n});\n\n/**\n * A shaded column of fog.columns() (ColumnLayout's `shading`): `a` is half its height, `lines` how many lines across\n * each half — 0 hollow, 1 at its middle, 3 at its quarters. A line is a dark row through a lit column (light ink), or\n * a lit band a brush deep through a dark one; a column too short for its lines is drawn plain.\n */\nconst columnShaded = game((player: Player, cx: number, mid: number, a: number, dark: boolean, lines: number) => {\n if (lines <= 0) {\n if (dark) { if (a >= 6) columnBar(player, cx, mid - 4, mid, 4); }\n else if (a < 8) columnBar(player, cx, mid - a, mid, a);\n else {\n // Hollow: the edges. Ribbed (-1) and panelled (-3): bands across each half too, centred on its middle or\n // quarters, where there is room for them between the edges.\n columnBar(player, cx, mid - a, mid + a - 4, 4);\n const ribs = -lines;\n if (ribs > 0 && a >= 6 * (ribs + 1)) {\n let k = 1;\n while (k <= ribs) {\n const at = (a * k) / (ribs + 1);\n columnBar(player, cx, mid - at - 2, mid + at - 2, 4);\n k++;\n }\n }\n }\n } else if (a < 5 * (lines + 1)) {\n if (!dark) columnBar(player, cx, mid - a, mid, a);\n } else {\n // From the middle out: lit up to each line, the line's row dark (light ink); or a lit band on each line (dark ink).\n let from = 0, k = 1;\n while (k <= lines + 1) {\n const to = k > lines ? a : (a * k) / (lines + 1);\n if (dark) { if (k <= lines) columnBar(player, cx, mid - to - 2, mid + to - 2, 4); }\n else columnBar(player, cx, mid - to, mid + from, to - from);\n from = to + 1;\n k++;\n }\n }\n});\n\n/**\n * Light columns for this frame — the walls of a raycaster, a bar chart — each as tall as the program says, centred on\n * the layout's middle row. The covers are worked out when the script is built (see ColumnLayout), so a frame costs a\n * brush for each part of the picture that differs from its neighbours, not one for every few tiles: a wall that fills\n * the board is a few large brushes.\n *\n * const VIEW = { count: 42, height: 96, ink: \"dark\" } as const;\n * fog.columns(P1, 1, 0, VIEW, heights); // heights: one a column, in tiles, the program's\n * fog.columns(P1, 1, 0, VIEW, heights, faces); // faces: which face of which wall each column shows\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of the layout's left edge.\n * @param y The row of its top edge.\n * @param layout How the columns are laid out: known when the script is built.\n * @param heights Each column's height in tiles (0 to the layout's height), an array of the program's.\n * @param faces Which face of which wall each column shows, a number the same for every column of one face — in a\n * raycaster, \\`(mapY * width + mapX) * 2 + side\\` — an array of the program's as long as `heights`: what the\n * layout's `shading` tells walls apart by. Optional: without it, every column is lit whole (a bar chart).\n */\nexport const columns = game((player: Player, x: number, y: number, layout: ColumnLayout, heights: readonly number[], faces?: readonly number[]) => {\n const { words, starts, half, group } = columnPlan(layout);\n const count = layout.count, width = layout.width ?? 3, dark = layout.ink === \"dark\";\n // (Dark lines through a lit column count up; lit bands through a dark one, ribbed and panelled, down.)\n // (Without faces there is nothing to tell apart, and every column is whole.)\n const outline = faces !== undefined && (layout.shading === undefined || layout.shading === \"outline\");\n const lines = layout.shading === \"lines\" ? 3 : layout.shading === \"line\" ? 1 : layout.shading === \"ribbed\" ? -1 : layout.shading === \"hollow\" ? 0 : -3;\n const span = half + 1;\n // Each column's depth from where its lit part starts: the middle row for light ink, the top and bottom for dark.\n // A shaded column of light ink is drawn on its own, after the rest: to the rest it is as if it were not there — and\n // so is every column of a light outline, which is all edges.\n const depth: number[] = new Array(count).fill(0);\n // Half of each column's height, at most half the layout's: worked out once. (Clamped before the shift, the same\n // number: the shift then has the few bits the clamp leaves, where a height from the program could have any.)\n const halves: number[] = new Array(count).fill(0);\n // And in pixels (32 a row), for the bars, which place their brushes in pixels: a small number times 32 is a few tests.\n const halves32: number[] = new Array(count).fill(0);\n let least = half, most = 0;\n // (A light outline is all edges: every depth is 0, nothing to work out.)\n const flat = !dark && outline;\n if (flat) least = 0;\n let i = 0;\n while (i < count) {\n const a = Math.min(Math.max(heights[i], 0), 2 * half + 1) >> 1;\n halves[i] = a;\n halves32[i] = a * 32;\n if (!flat) {\n let d = dark ? half - a : a;\n if (faces !== undefined && !dark && !outline && (faces[i] & 1) != 0) d = 0;\n depth[i] = d;\n if (d < least) least = d;\n if (d > most) most = d;\n }\n i++;\n }\n // A rectangle from depth p, k deep, starts on the rows above and below the middle (light) or below the top and above\n // the bottom (dark); one shallower than 4 is drawn 4 deep, reaching back over what is lit already.\n const mid = y + half;\n // Every column, from depth 0 to the least.\n if (least > 0) {\n const k = Math.max(least, 4);\n if (dark) columnRect(player, words, starts, least, x, y + least - k, y + 2 * half - least);\n else columnRect(player, words, starts, least, x, mid - least, mid + least - k);\n }\n // Each group of columns, from the least to the group's least; then each column, from there to its own. (Nothing,\n // when every column's depth is the least: a light outline's always.)\n let g = most > least ? 0 : count;\n while (g < count) {\n const last = Math.min(g + group, count);\n let gl = half;\n let j = g;\n while (j < last) { if (depth[j] < gl) gl = depth[j]; j++; }\n const level = last - g === group ? 1 : 2;\n if (gl > least) {\n const k = gl - least, kk = Math.max(k, 4);\n if (dark) columnRect(player, words, starts, level * span + k, x + g * width, y + gl - kk, y + 2 * half - gl);\n else columnRect(player, words, starts, level * span + k, x + g * width, mid - gl, mid + gl - kk);\n }\n j = g;\n while (j < last) {\n const k = depth[j] - gl;\n if (k > 0) {\n const kk = Math.max(k, 4), cx = x + j * width + 1;\n if (dark) columnBar(player, cx, y + depth[j] - kk, y + 2 * half - depth[j], k);\n else columnBar(player, cx, mid - depth[j], mid + depth[j] - kk, k);\n }\n j++;\n }\n g = last;\n }\n if (outline) {\n // Where one face meets another, the nearer (taller) of the two columns is an edge.\n const edge: number[] = new Array(count).fill(0);\n let face = faces[0], tall = heights[0];\n i = 1;\n while (i < count) {\n const f = faces[i], h = heights[i];\n if (f != face) { if (h >= tall) edge[i] = 1; else edge[i - 1] = 1; }\n face = f;\n tall = h;\n i++;\n }\n // The bars in pixels: a column's centre stepped across, the middle row's worked out once.\n const mid80 = mid * 32 + 80;\n let px = (x + 1) * 32 + 16;\n i = 0;\n while (i < count) {\n const a = halves[i], a32 = halves32[i];\n if (dark) { if (edge[i] != 0 && a >= 2) columnBarPx(player, px, mid80 - a32, mid80, a32); }\n else if (a > 0) {\n if (edge[i] != 0 || a < 8) columnBarPx(player, px, mid80 - a32, mid80, a32);\n else columnBarPx(player, px, mid80 - a32, mid80 + a32 - 128, 128);\n }\n px += width * 32;\n i++;\n }\n } else if (faces !== undefined) {\n i = 0;\n while (i < count) {\n if ((faces[i] & 1) != 0) columnShaded(player, x + i * width + 1, mid, halves[i], dark, lines);\n i++;\n }\n }\n});\n\n/**\n * Keep what was lit this frame on the board for `n` frames, and wait them out: \\`await fog.show(2)\\` in place of\n * \\`await nextFrame()\\` draws every other frame at half the cost. StarCraft: Remastered redraws the fog on the minimap\n * every other frame (measured in two played recordings, 2026-10-17), so a picture drawn every other frame looks the\n * same there as one drawn every frame. The board is wiped at the start of the frame after them, ready for the next.\n *\n * @param n How many frames, 1 to 24, known when the script is built.\n */\nexport const show = game(async (n: number) => {\n memory.vision.countdown = n;\n await sleep(frames(n));\n});\n\n/** Everything above as one name: import { fog } from \"trigscript/fog\"; fog.light(P1, x, y, 3). */\nexport const fog = { light, rect, columns, show, play, reveal, picture, SHAPES };\n\n/** The longest fog.show() keeps a picture: the countdown the game sets itself after a wipe is longer than this. */\nconst SHOW_MOST = 24;\n\n// The canvas: every brush's sight set, every frame, and the board wiped on the next — for as long as the game runs —\n// unless a program asked for the picture to stay (fog.show), when the countdown is that program's to run down.\nprogram(() => {\n while (true) {\n for (let s = 1; s <= 11; s++) stats(BRUSHES[s - 1]).sight = s;\n const left = memory.vision.countdown;\n if (left == 0 || left > SHOW_MOST) memory.vision.countdown = 1;\n sleep(frames(1));\n }\n});\n", "math": "/**\n * Numbers for motion and play: the standard library's \"trigscript/math\" (TrigScript 4).\n *\n * import { Vec, lerp, easeOutQuad, distance, angleTo, approach, wrap } from \"trigscript/math\";\n *\n * const t = fixed(frame) / 48; // 0 to 1 over two seconds\n * const x = lerp(fromX, toX, easeOutQuad(t)); // eased from one place to another\n * const v = Vec.fromAngle(angleTo(x, y, tx, ty), fixed(4));\n * pos = pos.add(v);\n *\n * Fractions are the language's fixed numbers (16.16: four decimal places or so, from about −32 768 to 32 767): a\n * number becomes one when a fraction is stored into it, or written `fixed(…)`. Angles are radians, as JavaScript's are.\n * Whole numbers stay whole where they can — `distanceSq`, `manhattan`, `wrap`, `sign` — and cost less.\n */\n\n/** π, and a whole turn. */\nexport const PI = Math.PI;\nexport const TAU = Math.PI * 2;\n\n/** From a to b by t: a at 0, b at 1, between them in between (t outside 0 … 1 goes past). */\nexport function lerp(a: fixed, b: fixed, t: fixed): fixed {\n return a + (b - a) * t;\n}\n\n/** Where v is from a to b, as lerp's t: 0 at a, 1 at b. */\nexport function inverseLerp(a: fixed, b: fixed, v: fixed): fixed {\n return b === a ? fixed(0) : (v - a) / (b - a);\n}\n\n/** v from the range a1 … b1 into a2 … b2. */\nexport function remap(v: fixed, a1: fixed, b1: fixed, a2: fixed, b2: fixed): fixed {\n return lerp(a2, b2, inverseLerp(a1, b1, v));\n}\n\n/** t kept inside 0 … 1. */\nexport function clamp01(t: fixed): fixed {\n return t < 0 ? fixed(0) : t > 1 ? fixed(1) : t;\n}\n\n/** From `current` towards `target` by at most `step`, never past it: a value that follows another at a speed. */\nexport function approach(current: number, target: number, step: number): number {\n if (current < target) return current + step > target ? target : current + step;\n return current - step < target ? target : current - step;\n}\n\n/** n into 0 … size − 1, going round: wrap(-1, 10) is 9, wrap(12, 10) is 2. */\nexport function wrap(n: number, size: number): number {\n return ((n % size) + size) % size;\n}\n\n/** −1, 0 or 1, by whether n is below, at or above zero. */\nexport function sign(n: number): number {\n return n > 0 ? 1 : n < 0 ? -1 : 0;\n}\n\n/** The distance from one point to another, as the crow flies. */\nexport function distance(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.hypot(x2 - x1, y2 - y1);\n}\n\n/** The distance squared: whole, and cheaper — compare it with a range squared. */\nexport function distanceSq(x1: number, y1: number, x2: number, y2: number): number {\n return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n}\n\n/** The distance along the axes, |dx| + |dy|: what the game's own \"nearest\" goes by. */\nexport function manhattan(x1: number, y1: number, x2: number, y2: number): number {\n return Math.abs(x2 - x1) + Math.abs(y2 - y1);\n}\n\n/** The angle from one point to another, in radians from −π to π: 0 is to the right (east), π / 2 down (south, y grows down). */\nexport function angleTo(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.atan2(y2 - y1, x2 - x1);\n}\n\n/** Degrees as radians. */\nexport function radians(degrees: fixed): fixed {\n return (degrees * PI) / 180;\n}\n\n/** Radians as degrees. */\nexport function degrees(radians: fixed): fixed {\n return (radians * 180) / PI;\n}\n\n/* Easing: t from 0 to 1, how far along a motion is at that point of its time — slow then fast, fast then slow, … */\n\n/** Slow at the start. */\nexport function easeInQuad(t: fixed): fixed {\n return t * t;\n}\n\n/** Slow at the end. */\nexport function easeOutQuad(t: fixed): fixed {\n return t * (2 - t);\n}\n\n/** Slow at both ends. */\nexport function easeInOutQuad(t: fixed): fixed {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n}\n\n/** Slower at the start than easeInQuad. */\nexport function easeInCubic(t: fixed): fixed {\n return t * t * t;\n}\n\n/** Slower at the end than easeOutQuad. */\nexport function easeOutCubic(t: fixed): fixed {\n const u = t - 1;\n return u * u * u + 1;\n}\n\n/** Goes a little past the end and comes back. */\nexport function easeOutBack(t: fixed): fixed {\n const u = t - 1;\n return 1 + 2.70158 * u * u * u + 1.70158 * u * u;\n}\n\n/** Slow at both ends, smoothly (Hermite: 3t² − 2t³). */\nexport function smoothstep(t: fixed): fixed {\n return t * t * (3 - 2 * t);\n}\n\n/**\n * A point, or a direction and a length: two fixed numbers. Each operation gives a new Vec.\n *\n * let pos = new Vec(fixed(x), fixed(y));\n * const toward = new Vec(fixed(tx), fixed(ty)).sub(pos).normalized().scale(fixed(3));\n * pos = pos.add(toward);\n */\nexport class Vec {\n x: fixed;\n y: fixed;\n\n constructor(x: fixed, y: fixed) {\n this.x = x;\n this.y = y;\n }\n\n /** A direction `length` long at `angle` radians (0 to the right, π / 2 down). */\n static fromAngle(angle: fixed, length: fixed): Vec {\n return new Vec(Math.cos(angle) * length, Math.sin(angle) * length);\n }\n\n add(o: Vec): Vec {\n return new Vec(this.x + o.x, this.y + o.y);\n }\n\n sub(o: Vec): Vec {\n return new Vec(this.x - o.x, this.y - o.y);\n }\n\n scale(k: fixed): Vec {\n return new Vec(this.x * k, this.y * k);\n }\n\n dot(o: Vec): fixed {\n return this.x * o.x + this.y * o.y;\n }\n\n /** How long it is. */\n length(): fixed {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n }\n\n /** The same direction, 1 long (or none, for none). */\n normalized(): Vec {\n const l = this.length();\n const k: fixed = l === 0 ? fixed(0) : 1 / l;\n return new Vec(this.x * k, this.y * k);\n }\n\n /** Its angle, in radians from −π to π. */\n angle(): fixed {\n return Math.atan2(this.y, this.x);\n }\n\n /** Turned by `angle` radians (clockwise on the map, where y grows down). */\n rotate(angle: fixed): Vec {\n const c = Math.cos(angle);\n const s = Math.sin(angle);\n return new Vec(this.x * c - this.y * s, this.x * s + this.y * c);\n }\n\n /** How far it is from another point. */\n distanceTo(o: Vec): fixed {\n return this.sub(o).length();\n }\n\n /** From this towards another by t (0 here, 1 there). */\n lerp(o: Vec, t: fixed): Vec {\n return new Vec(this.x + (o.x - this.x) * t, this.y + (o.y - this.y) * t);\n }\n}\n", - "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false, release = releaseOf(z);\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one — held by the\n // pedal or still dying away after it was let go (a string struck again starts again).\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) {\n const next = order[j].at;\n if (next < off) { off = next; stolen = true; release = 0.12; }\n else if (next < off + release) release = Math.max(0.1, next - off + 0.1);\n break;\n }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n // (A pedal down before 0 was put down, and comes up, in the excerpt before this one: no sound of it here.)\n if (releases) for (const [down, up] of pedal) if (down >= 0) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n};\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/**\n * The part of a performance from bar `from` up to bar `to` (not included; to its end when left out), bars as\n * `performance.bars` counts them, as a performance from 0 of its own: the notes struck in it, their times from its\n * start, and the pedal — down already when the pedal went down before it (its sound is the excerpt's before), held to\n * where it comes up. Render a long piece a section at a time, each with its room, its tail ringing on under the next\n * when the sections are added up at their `at`s: `music.render(music.excerpt(take, 44, 60), { reverb: ROOM })`.\n */\nexport function excerpt(p: Performance, from: number, to?: number): Performance & { readonly at: number } {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"excerpt() takes a performance made by music.perform.\");\n const last = p.bars.length - 1;\n if (!(Number.isInteger(from) && from >= 0 && from <= last)) throw new Error(`excerpt() starts on a bar, 0 to ${last}, not ${from}.`);\n if (to !== undefined && !(Number.isInteger(to) && to > from && to <= last)) throw new Error(`excerpt() ends on a bar after ${from}, at most ${last}, not ${to}.`);\n const a = p.bars[from], b = to === undefined ? Infinity : p.bars[to];\n const notes = p.notes.filter((n) => n.at >= a - 1e-9 && n.at < b - 1e-9).map((n) => Object.freeze({ ...n, at: n.at - a, end: n.end - a, frame: Math.round((n.at - a) / FRAME) }));\n const clip = (list: readonly (readonly [number, number])[]) => list.filter(([d, u]) => u > a && d < b).map(([d, u]) => [d - a, u - a] as [number, number]);\n const pedal = new Map();\n for (const [inst, list] of inside.pedal) pedal.set(inst, clip(list));\n const made = Object.freeze({\n kind: \"performance\" as const, at: a, notes: Object.freeze(notes), pedal: Object.freeze(clip(p.pedal).map((x) => Object.freeze(x))),\n bars: Object.freeze(p.bars.slice(from, to === undefined ? undefined : to + 1).map((t) => t - a)), parts: p.parts,\n seconds: Math.max(0, ...notes.map((n) => n.end)),\n });\n performances.set(made, { parts: inside.parts, pedal });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n for (const { part } of inside.parts) {\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) throw new Error(\"render(): the performance plays no notes.\");\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, excerpt, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", + "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false, release = releaseOf(z);\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one — held by the\n // pedal or still dying away after it was let go (a string struck again starts again).\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) {\n const next = order[j].at;\n if (next < off) { off = next; stolen = true; release = 0.12; }\n else if (next < off + release) release = Math.max(0.1, next - off + 0.1);\n break;\n }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n // (A pedal down before 0 was put down, and comes up, in the excerpt before this one: no sound of it here.)\n if (releases) for (const [down, up] of pedal) if (down >= 0) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n /**\n * A film trailer's \"braam\": five saws low and wide, the filter opening over half a second and closing slowly, driven\n * hard — the brass section's blast as a synth. Play it low (A1 … A2), with the low brass on the same notes.\n */\n braam: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 16, width: 0.6, volume: 0.22, attack: 0.04, decay: 1.2, sustain: 0.7, release: 0.9, filter: { cutoff: 160, amount: 3.4, resonance: 0.25, envelope: { attack: 0.45, decay: 1.6, sustain: 0.35, release: 0.8 } }, drive: 14, ...o }),\n /** A short synth pulse for sixteenth ostinatos: two squares, a quick filter blip. */\n pulse: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 9, width: 0.4, volume: 0.12, attack: 0.002, decay: 0.09, sustain: 0.25, release: 0.04, filter: { cutoff: 900, amount: 2.2, resonance: 0.3, envelope: { decay: 0.08, sustain: 0.1 } }, ...o }),\n /** A sub bass: a sine, soft at the start, under everything. */\n sub: (o: SynthOptions = {}) => synth({ wave: \"sine\", volume: 0.4, attack: 0.02, decay: 0.3, sustain: 0.9, release: 0.25, ...o }),\n};\n\n/**\n * An instrument of one-shots: a clip a key (\"C2\": the impact, \"D2\": a riser), each played whole whatever the note's\n * length and not moved in pitch, as loud as its velocity says — percussion and effects as parts of a performance\n * (`perform`), beside the instruments that play notes: `music.hits({ C2: music.impact(), D2: music.riser(4) })`.\n */\nexport function hits(clips: Readonly>, options: { readonly volume?: number } = {}): Instrument {\n const volume = options.volume ?? 1, byKey = new Map();\n for (const [name, clip] of Object.entries(clips)) byKey.set(noteNumber(name), clip);\n const clipOf = (name: string) => {\n const c = byKey.get(noteNumber(name));\n if (!c) throw new Error(`hits() has no clip for ${name}: it has ${Object.keys(clips).join(\", \")}.`);\n return c;\n };\n return Object.freeze({\n kind: \"notes\" as const,\n note: (name: string) => (volume === 1 ? clipOf(name) : clipOf(name).gain(volume)),\n strike: (name: string, _seconds: number, velocity: number) => clipOf(name).gain(volume * velocity),\n });\n}\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/**\n * The part of a performance from bar `from` up to bar `to` (not included; to its end when left out), bars as\n * `performance.bars` counts them, as a performance from 0 of its own: the notes struck in it, their times from its\n * start, and the pedal — down already when the pedal went down before it (its sound is the excerpt's before), held to\n * where it comes up. Render a long piece a section at a time, each with its room, its tail ringing on under the next\n * when the sections are added up at their `at`s: `music.render(music.excerpt(take, 44, 60), { reverb: ROOM })`.\n */\nexport function excerpt(p: Performance, from: number, to?: number): Performance & { readonly at: number } {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"excerpt() takes a performance made by music.perform.\");\n const last = p.bars.length - 1;\n if (!(Number.isInteger(from) && from >= 0 && from <= last)) throw new Error(`excerpt() starts on a bar, 0 to ${last}, not ${from}.`);\n if (to !== undefined && !(Number.isInteger(to) && to > from && to <= last)) throw new Error(`excerpt() ends on a bar after ${from}, at most ${last}, not ${to}.`);\n const a = p.bars[from], b = to === undefined ? Infinity : p.bars[to];\n const notes = p.notes.filter((n) => n.at >= a - 1e-9 && n.at < b - 1e-9).map((n) => Object.freeze({ ...n, at: n.at - a, end: n.end - a, frame: Math.round((n.at - a) / FRAME) }));\n const clip = (list: readonly (readonly [number, number])[]) => list.filter(([d, u]) => u > a && d < b).map(([d, u]) => [d - a, u - a] as [number, number]);\n const pedal = new Map();\n for (const [inst, list] of inside.pedal) pedal.set(inst, clip(list));\n const made = Object.freeze({\n kind: \"performance\" as const, at: a, notes: Object.freeze(notes), pedal: Object.freeze(clip(p.pedal).map((x) => Object.freeze(x))),\n bars: Object.freeze(p.bars.slice(from, to === undefined ? undefined : to + 1).map((t) => t - a)), parts: p.parts,\n seconds: Math.max(0, ...notes.map((n) => n.end)),\n });\n performances.set(made, { parts: inside.parts, pedal });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n for (const { part } of inside.parts) {\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) throw new Error(\"render(): the performance plays no notes.\");\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, excerpt, hits, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", "random": "/**\n * Chance: the standard library's \"trigscript/random\" (TrigScript 4).\n *\n * import { chance, range, pick, shuffle, weighted, Random } from \"trigscript/random\";\n *\n * if (chance(25)) dropLoot(); // one time in four\n * const lane = range(1, 3); // 1, 2 or 3\n * const boss = pick(BOSSES); // any one of a list\n * shuffle(order); // an array of the program, in place\n * const tier = weighted([70, 25, 5]); // 0 most of the time, 2 rarely\n *\n * const rng = new Random(seed); // the same numbers every time for the same seed\n * const x = rng.range(0, 63);\n *\n * The functions use the game's own random numbers, which every player's game draws alike, so nothing goes out of step\n * in a game of several players. `Random` is a generator of your own (xorshift), seeded: the same seed gives the same\n * numbers, game after game — a level made from a seed, a save code that holds one.\n */\nimport { random } from \"trigscript\";\n\n/** True `percent` times in a hundred (25: one time in four). */\nexport function chance(percent: number): boolean {\n return random(100) < percent;\n}\n\n/** A whole number from `min` to `max`, both included. */\nexport function range(min: number, max: number): number {\n return min + random(max - min + 1);\n}\n\n/** The total of `count` dice of `sides` sides each (3, 6: from 3 to 18). */\nexport function dice(count: number, sides: number): number {\n let total = 0;\n let i = 0;\n while (i < count) { total += 1 + random(sides); i++; }\n return total;\n}\n\n/** One of a list, any one alike; a list the script has, or an array of the program (the first's 0 when it is empty). */\nexport function pick(items: readonly T[]): T {\n return items[random(items.length)];\n}\n\n/** The place of one of the weights, each as likely as its share of their total: [70, 25, 5] gives 0 most of the time. */\nexport function weighted(weights: readonly number[]): number {\n let total = 0;\n for (const w of weights) total += w;\n let roll = random(total);\n let i = 0;\n while (i < weights.length) {\n if (roll < weights[i]) return i;\n roll -= weights[i];\n i++;\n }\n return weights.length - 1;\n}\n\n/** An array of the program in a random order, in place (Fisher–Yates: every order alike). */\nexport function shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = random(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n}\n\n/**\n * A generator of random numbers of your own, seeded: the same seed gives the same numbers, in the game and when the\n * script is tested. Make it in the program (`const rng = new Random(1234)`).\n */\nexport class Random {\n state: number;\n\n /** Seeded with any whole number (0 is taken as 1). */\n constructor(seed: number) {\n this.state = seed === 0 ? 1 : seed;\n }\n\n /** The next number, from 0 to 2 147 483 647. */\n next(): number {\n let x = this.state;\n x ^= x << 13;\n x ^= x >>> 17;\n x ^= x << 5;\n this.state = x;\n return x & 0x7fffffff;\n }\n\n /** A whole number from 0 to n − 1. */\n int(n: number): number {\n return this.next() % n;\n }\n\n /** A whole number from `min` to `max`, both included. */\n range(min: number, max: number): number {\n return min + this.int(max - min + 1);\n }\n\n /** True `percent` times in a hundred. */\n chance(percent: number): boolean {\n return this.int(100) < percent;\n }\n\n /** One of a list, any one alike. */\n pick(items: readonly T[]): T {\n return items[this.int(items.length)];\n }\n\n /** An array of the program in a random order, in place. */\n shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = this.int(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n }\n}\n", "screen": "/**\n * Pixel screens: the standard library's \"trigscript/screen\" (TrigScript 4).\n *\n * import { Screen, ScreenView, sprite } from \"trigscript/screen\";\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n *\n * program(async () => {\n * const screen = new Screen(4, 4, 24, 16); // 24 × 16 pixels, its corner on tile (4, 4)\n * let x = 10;\n * while (true) {\n * screen.clear();\n * screen.rect(0, 15, 24, 1, 5); // the ground, in colour 5\n * screen.blit(SHIP, x, 12);\n * screen.number(score, 1, 1, 2); // digits 3 × 5 pixels, in colour 2\n * screen.present(); // on the map, and so on the minimap (screen.reveal(P1) once first)\n * await nextFrame();\n * }\n * });\n *\n * A screen is a grid of pixels, each 0 (empty) or a colour from 1 to 7; drawing changes the grid, and `present()`\n * shows it: a pixel is a unit on the map, owned by the player whose colour it is, so the minimap shows the picture —\n * neighbouring pixels of one colour join into a solid block there. Only the pixels that changed since the last\n * `present()` are made or taken away, and only the pixels drawn since are looked at, so a still picture costs nothing to\n * show. Draw through the methods (`set`, `clear`, `rect`, …): a pixel written into `pixels` directly is not seen. The same grid can be shown in a\n * player's text lines too, as squares (`ScreenView` in a `ui.lines` view): one game, two screens, as the Tetris probe has it.\n *\n * A player sees the pixels only where they have vision: `screen.reveal(P1)` once gives them Map Revealers over it.\n *\n * Two looks (the constructor's last argument): \"dots\", Overlords, which fly — the minimap draws each as a dot with a gap\n * round it, the screen may be over Space; and \"solid\", Pylons, which the minimap draws as their whole two-tile\n * footprint, so pixels side by side are one block — on buildable ground (probes/lib/screen-map.mts --ground).\n *\n * What the map needs, found playing the unit-pixel probe in StarCraft: Remastered (2026-10-16): the owners of the\n * pixels (P3, P4, P5, P1, P6, P7, P8 below; their colours are theirs on the map, so give them the colours of TEXT_COLORS) must not\n * be computers — a computer moves its own units — and Remastered will not start a game without a computer, so one slot\n * (P2 here) is a computer that owns no pixel. A pixel is an Overlord, which sits on any ground and on nothing else; keep\n * the screen's tiles clear of buildings. A Pylon needs buildable ground, and none of the map's own units in the way. About 80 pixels made and taken away in a frame did not slow the game.\n */\nimport { centerLocation, createUnit, removeUnitAt, reserveLocation, textColors, units, P1, P3, P4, P5, P6, P7, P8, type Player } from \"trigscript\";\n\n/**\n * Whose units show colours 1 to 7 on the map, in the order of TEXT_COLORS: give each player that colour in the map\n * (cyan, yellow, purple, green, red, blue, orange). Green is P1's — your own units are green on the minimap anyway.\n * Not computers.\n */\nexport const OWNERS: readonly Player[] = [P3, P4, P5, P1, P6, P7, P8];\n/** The same colours in the text lines (`ScreenView`), 0 an empty square: cyan, yellow, purple, green, red, blue, orange. */\nexport const TEXT_COLORS: readonly number[] = [0, textColors.cyan, textColors.yellow, textColors.purple, textColors.green, textColors.red, textColors.blue, textColors.orange];\n\n/** Where each pixel's unit is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"screen: where each pixel is made\");\n\n/** A picture known when the script is built, to `blit` onto a screen: its size, and its pixels a row at a time (0 is see-through). */\nexport interface Sprite { readonly width: number; readonly height: number; readonly cells: readonly number[] }\n\n/**\n * A sprite from rows of text, when the script is built: \"1\" … \"7\" a pixel of that colour, anything else see-through.\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n */\nexport function sprite(rows: readonly string[]): Sprite {\n const width = Math.max(0, ...rows.map((r) => r.length));\n const cells: number[] = [];\n for (const row of rows) for (let x = 0; x < width; x++) { const c = Number(row[x]); cells.push(c >= 1 && c <= 7 ? c : 0); }\n return { width, height: rows.length, cells };\n}\n\n/** The digits 0 to 9, three pixels wide and five high, for `number()`: each fifteen pixels, a row at a time. */\nconst DIGITS: readonly number[] = [\n \"111101101101111\", \"010110010010111\", \"111001111100111\", \"111001111001111\", \"101101111001001\",\n \"111100111001111\", \"111100111101111\", \"111001001010010\", \"111101111101111\", \"111101111001111\",\n].flatMap((d) => d.split(\"\").map(Number));\n\n/** The most pixels a screen has: 32 × 32 at two tiles a pixel covers a 64 × 64 map, 64 × 32 half of a 128 × 128 one. */\nexport const MAX_PIXELS = 2048;\n\nexport class Screen {\n /** The picture being drawn: a colour a pixel, a row at a time (the first width × height of them). */\n pixels: number[] = new Array(MAX_PIXELS).fill(0);\n /** What the map shows now: the picture as it was at the last `present()`. */\n shown: number[] = new Array(MAX_PIXELS).fill(0);\n /** The pixels drawn a colour they were not since the last `present()`, in order: each one's place and its x and y. */\n drawnAt: number[] = new Array(MAX_PIXELS).fill(0);\n drawnX: number[] = new Array(MAX_PIXELS).fill(0);\n drawnY: number[] = new Array(MAX_PIXELS).fill(0);\n drawn = 0;\n /** More drawn than the list holds: `present()` looks at every pixel instead. */\n overflow = false;\n x: number;\n y: number;\n width: number;\n height: number;\n cell: number;\n /** The unit a pixel is: an Overlord (\"dots\"), or a Pylon (\"solid\"). */\n unit = 0;\n\n /**\n * A screen `width` × `height` pixels (MAX_PIXELS at most), its top left corner on tile (x, y) of the map, a pixel two\n * tiles across.\n * @param look \"dots\" (the default): a pixel is an Overlord, which the minimap draws as a dot, a gap round it — it flies,\n * so the screen may be over anything, Space too. \"solid\": a pixel is a Pylon, which the minimap draws as its whole\n * footprint, two tiles square, so pixels side by side are one block — it needs buildable ground under the screen,\n * and gives its owner Protoss supply. (Overlords a tile apart do not fit: the game will not place most of them.)\n */\n constructor(x: number, y: number, width: number, height: number, look: \"dots\" | \"solid\" = \"dots\") {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.cell = 64;\n this.unit = look === \"solid\" ? units.ProtossPylon : units.ZergOverlord;\n }\n\n /** Every pixel the colour (0, empty, unless it says). */\n clear(color: number = 0) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.put(i, x, y, color); i++; x++; }\n y++;\n }\n }\n\n /** One pixel; nothing happens outside the screen. */\n set(x: number, y: number, color: number) {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) this.put(y * this.width + x, x, y, color);\n }\n\n /** A pixel written, and listed for `present()` when its colour changed. */\n private put(i: number, x: number, y: number, color: number) {\n if (this.pixels[i] === color) return;\n this.pixels[i] = color;\n if (this.drawn < MAX_PIXELS) {\n this.drawnAt[this.drawn] = i;\n this.drawnX[this.drawn] = x;\n this.drawnY[this.drawn] = y;\n this.drawn++;\n } else this.overflow = true;\n }\n\n /** The colour of a pixel; 0 outside the screen. */\n get(x: number, y: number): number {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) return this.pixels[y * this.width + x];\n return 0;\n }\n\n /** A filled rectangle, its top left at (x, y); what is outside the screen is left out. */\n rect(x: number, y: number, width: number, height: number, color: number) {\n let j = 0;\n while (j < height) {\n let i = 0;\n while (i < width) { this.set(x + i, y + j, color); i++; }\n j++;\n }\n }\n\n /** A line from (x0, y0) to (x1, y1), both ends drawn. */\n line(x0: number, y0: number, x1: number, y1: number, color: number) {\n const dx = Math.abs(x1 - x0);\n const dy = -Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx + dy;\n let x = x0;\n let y = y0;\n while (true) {\n this.set(x, y, color);\n if (x === x1 && y === y1) break;\n const e2 = 2 * err;\n if (e2 >= dy) { err += dy; x += sx; }\n if (e2 <= dx) { err += dx; y += sy; }\n }\n }\n\n /** A sprite with its top left at (x, y): its see-through pixels leave what is under them. */\n blit(s: Sprite, x: number, y: number) {\n let k = 0;\n let j = 0;\n while (j < s.height) {\n let i = 0;\n while (i < s.width) {\n const c = s.cells[k];\n if (c !== 0) this.set(x + i, y + j, c);\n k++;\n i++;\n }\n j++;\n }\n }\n\n /** A whole number's digits, 3 × 5 pixels each with a pixel between, its top left at (x, y): a score on the minimap. */\n number(n: number, x: number, y: number, color: number) {\n let rest = n < 0 ? -n : n;\n let count = 1;\n let probe = rest;\n while (probe >= 10) { probe = Math.floor(probe / 10); count++; }\n let place = x + (count - 1) * 4;\n while (true) {\n const d = rest % 10;\n let k = 0;\n while (k < 15) {\n if (DIGITS[d * 15 + k] === 1) this.set(place + (k % 3), y + Math.floor(k / 3), color);\n k++;\n }\n rest = Math.floor(rest / 10);\n place -= 4;\n if (rest === 0) break;\n }\n }\n\n /**\n * Let a player see the screen: Map Revealers of theirs over it, for the rest of the game. Without them its pixels,\n * owned by other players, are hidden by the fog of war — on the map and on the minimap. Once, before the first\n * `present()`.\n * @param player Who sees it: P1 … P8, known when the script is built.\n */\n reveal(player: Player) {\n // A Map Revealer sees ten tiles round; one every six tiles leaves no gap.\n const right = this.x * 32 + this.width * this.cell;\n const bottom = this.y * 32 + this.height * this.cell;\n let py = this.y * 32 + 96;\n while (py < bottom + 96) {\n let px = this.x * 32 + 96;\n while (px < right + 96) {\n centerLocation(SPOT, px, py, 32, 32);\n createUnit(player, units.MapRevealer, 1, SPOT);\n px += 192;\n }\n py += 192;\n }\n }\n\n /**\n * The picture on the map: each pixel that changed since the last time taken away and made again in its colour. Only\n * the pixels drawn since are looked at (one drawn and drawn back is passed over), unless more were drawn than the list\n * holds.\n */\n present() {\n if (this.overflow) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.show(i, x, y); i++; x++; }\n y++;\n }\n this.overflow = false;\n } else {\n for (let k = 0; k < this.drawn; k++) this.show(this.drawnAt[k], this.drawnX[k], this.drawnY[k]);\n }\n this.drawn = 0;\n }\n\n /** One pixel on the map as it is in the picture, when it is not already. */\n private show(i: number, x: number, y: number) {\n const now = this.pixels[i];\n const was = this.shown[i];\n if (now === was) return;\n const half = this.cell >> 1;\n centerLocation(SPOT, this.x * 32 + x * this.cell + half, this.y * 32 + y * this.cell + half, 32, 32);\n OWNERS.forEach((owner, k) => { if (was === k + 1) removeUnitAt(owner, this.unit, 1, SPOT); });\n OWNERS.forEach((owner, k) => { if (now === k + 1) createUnit(owner, this.unit, 1, SPOT); });\n this.shown[i] = now;\n }\n}\n\n/**\n * A screen in the text lines, a square a pixel — filled in its colour, or empty — a line a row. For a `ui.lines` view:\n * ``, the screen's size known when the script is built. Eleven lines\n * show at once, sixty squares across.\n */\nexport function ScreenView({ screen, width, height }: { screen: Screen; width: number; height: number }) {\n return <>{UP_TO_60.map((y) => y < height && {UP_TO_60.map((x) => x < width && )})};\n}\n\n/** 0 … 59: the places a view's rows and columns are counted over, the ones past its size left out when the script is built. */\nconst UP_TO_60: readonly number[] = Array.from({ length: 60 }, (_, i) => i);\n", "signals": "/**\n * Events of your own: the standard library's \"trigscript/signals\" (TrigScript 4).\n *\n * import { Signal } from \"trigscript/signals\";\n *\n * const waveCleared = new Signal();\n *\n * program(async () => {\n * waveCleared.on((wave) => { setResources(P1, \"add\", 100 * wave, \"ore\"); }); // braces: a handler gives back no action\n * waveCleared.once((wave) => print(`First wave down!`));\n * const id = waveCleared.on((wave) => print(`Wave ${wave} cleared`));\n * …\n * waveCleared.emit(3); // every handler, in the order they were added\n * waveCleared.off(id);\n * });\n *\n * A signal lets one part of a map say that something happened without knowing who listens: the shop, the score and the\n * music each add a handler, and the wave code only emits. What it carries is one value of the type it is made with —\n * a number, a boolean, a text or a unit (`new Signal()`). Its handlers are functions kept as values: they may use\n * what the block they were written in has, and they run to their end, one after another, within the frame.\n *\n * Make a signal inside the program that uses it (`const s = new Signal()` at its top): a signal is variables\n * of a program, as anything a program writes is.\n */\n\nexport class Signal {\n /** The handlers, by the number `on` gave; one taken off is undefined, and its place is given to the next one added. */\n handlers: (((value: T) => void) | undefined)[] = [];\n /** Which handlers go once they have run once. */\n onceOnly: boolean[] = [];\n\n /**\n * Add a handler: it runs at every `emit`, handed the value.\n * @returns Its number, for `off`.\n */\n on(handler: (value: T) => void): number {\n return this.add(handler, false);\n }\n\n /** Add a handler that runs at the next `emit` only. @returns Its number, for `off` before then. */\n once(handler: (value: T) => void): number {\n return this.add(handler, true);\n }\n\n /** Take a handler off, by the number `on` or `once` gave. */\n off(id: number) {\n if (id >= 0 && id < this.handlers.length) this.handlers[id] = undefined;\n }\n\n /** Run every handler, in the order they were added, each handed `value`. */\n emit(value: T) {\n let i = 0;\n while (i < this.handlers.length) {\n const h = this.handlers[i];\n if (h) {\n if (this.onceOnly[i]) this.handlers[i] = undefined;\n h(value);\n }\n i++;\n }\n }\n\n /** How many handlers it has. */\n count(): number {\n let n = 0;\n for (const h of this.handlers) if (h) n++;\n return n;\n }\n\n /** Take every handler off. */\n clear() {\n let i = 0;\n while (i < this.handlers.length) { this.handlers[i] = undefined; i++; }\n }\n\n private add(handler: (value: T) => void, once: boolean): number {\n // A place one was taken off from, or a new one at the end.\n let i = 0;\n while (i < this.handlers.length) {\n if (!this.handlers[i]) {\n this.handlers[i] = handler;\n this.onceOnly[i] = once;\n return i;\n }\n i++;\n }\n this.handlers.push(handler);\n this.onceOnly.push(once);\n return this.handlers.length - 1;\n }\n}\n", diff --git a/ledger/sounds/music-hits.ts b/ledger/sounds/music-hits.ts new file mode 100644 index 0000000..2f48afb --- /dev/null +++ b/ledger/sounds/music-hits.ts @@ -0,0 +1,12 @@ +// ledger: step 5, takes +// One-shots as a part of a performance (`music.hits`): a clip a key, played whole and unpitched, beside a braam +// (`music.presets.braam`), rendered into one clip. +import { music } from "trigscript/music"; +const fx = music.hits({ C2: music.impact({ seconds: 1 }), D2: music.riser(1) }); +const take = music.perform({ meter: "3/8", bpm: 120 }, { + fx: { instrument: fx, notes: "D2/8 r C2@110" }, + braam: { instrument: music.presets.braam(), notes: "r/8 r A1" }, +}); +program(async () => { + playWav(music.render(take), 0); +}); diff --git a/scripts/make-samples.mts b/scripts/make-samples.mts index 4d37827..1fbf095 100644 --- a/scripts/make-samples.mts +++ b/scripts/make-samples.mts @@ -4,6 +4,7 @@ * * npx tsx scripts/make-samples.mts [options] * npx tsx scripts/make-samples.mts --names [options] + * npx tsx scripts/make-samples.mts --kit [options] * * --keys 40-90 only the zones of these keys (MIDI numbers, or names: E2-C7); the pedal's are kept * --layers 2,4,6 only these strengths of the notes, by number from the softest (1); the ones kept widen to cover the rest @@ -16,6 +17,10 @@ * each text — a drum measured by ear or by its spectrum, where --detect is unsure * --name "…" --credit "…" what the file says it is, and whom to credit * + * A kit (--kit) is percussion, a key a drum: { "root": "", "release": 2, "drums": { "C2": ["Percussion/ + * BDrumNewhit_*"], … } } — each key's recordings by pattern (* any text), unpitched, its strengths from the names + * ("v3", or ppp … fff), the rest of a name telling recordings of one strength apart (played in turn). + * * The recordings stay where they are (never in a repository: a sample library is its makers' and is large); the file * made holds what the build needs, coded without loss. */ @@ -26,8 +31,8 @@ import { writeSamples, type ZoneData } from "../compiler/samples"; const args = process.argv.slice(2); const option = (name: string) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }; const flag = (name: string) => args.includes(name); -const positional = args.filter((a, i) => !a.startsWith("--") && !(i > 0 && args[i - 1].startsWith("--") && !["--detect", "--names"].includes(args[i - 1]))); -const byNames = flag("--names"); +const positional = args.filter((a, i) => !a.startsWith("--") && !(i > 0 && args[i - 1].startsWith("--") && !["--detect", "--names", "--kit"].includes(args[i - 1]))); +const byNames = flag("--names"), byKit = flag("--kit"); const [source, out] = positional; if (!source || !out) { console.error("usage: make-samples [--keys lo-hi] [--layers 1,3,…] [--seconds s] | --names [--detect]"); process.exit(2); } @@ -186,9 +191,45 @@ function zonesFromNames(folder: string): { files: string[]; zones: ZoneData[] } return { files: recs.map((r) => r.file), zones }; } +/* ── A kit: a key a drum ── */ + +const DYNAMICS = ["ppp", "pp", "p", "mp", "mf", "f", "ff", "fff"]; +/** A recording's strength from its name: "v3", or a dynamic as a word of it; -1 when it says none. */ +function strengthOf(stem: string): number { + const v = /(?:^|[_-])v(\d+)(?=[_.-]|$)/i.exec(stem); + if (v) return Number(v[1]); + const words = stem.toLowerCase().replace(/\.wav$/, "").split(/[_\-\s]+/); + for (let k = DYNAMICS.length - 1; k >= 0; k--) if (words.includes(DYNAMICS[k])) return k + 1; + return -1; +} + +function zonesFromKit(path: string): { files: string[]; zones: ZoneData[] } { + const spec = JSON.parse(readFileSync(path, "utf8")) as { root?: string; release?: number; drums: Record }; + const root = resolve(dirname(path), spec.root ?? "."); + const files: string[] = [], zones: ZoneData[] = []; + for (const [name, patterns] of Object.entries(spec.drums)) { + const key = keyOf(name); + const found = patterns.flatMap((pat) => { + const dir = join(root, dirname(pat)), re = new RegExp(`^${basename(pat).replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`); + return readdirSync(dir).filter((f) => re.test(f) && /\.wav$/i.test(f)).sort().map((f) => join(dir, f)); + }); + if (!found.length) throw new Error(`${name}: no recording matches ${patterns.join(", ")}.`); + const strengths = [...new Set(found.map((f) => strengthOf(basename(f))))].sort((a, b) => a - b); + found.forEach((f) => { + const st = strengthOf(basename(f)), li = strengths.indexOf(st), same = found.filter((g) => strengthOf(basename(g)) === st); + files.push(f); + zones.push({ + sample: files.length - 1, key, lo: key, hi: key, vlo: li === 0 ? 1 : Math.floor((127 * li) / strengths.length) + 1, vhi: Math.floor((127 * (li + 1)) / strengths.length), + pitched: false, release: spec.release ?? 2, ...(same.length > 1 ? { turns: same.length, turn: same.indexOf(f) + 1 } : {}), + }); + }); + } + return { files, zones }; +} + /* ── Choosing, cutting, writing ── */ -let { files, zones } = byNames ? zonesFromNames(source) : zonesFromSfz(source); +let { files, zones } = byKit ? zonesFromKit(source) : byNames ? zonesFromNames(source) : zonesFromSfz(source); const keys = option("--keys"); if (keys) { const [lo, hi] = keys.split("-").map(keyOf); diff --git a/scripts/samples-tuning.mts b/scripts/samples-tuning.mts new file mode 100644 index 0000000..a1a9d2a --- /dev/null +++ b/scripts/samples-tuning.mts @@ -0,0 +1,78 @@ +/** + * Whether a sampled instrument's zones say the right key for their recordings: each pitched attack zone's recording + * measured (an FFT over 0.1 … 0.5 s of it, the peak within a semitone of the key it claims, its fundamental and its + * second harmonic) against the zone's key and tune. A zone is flagged when both are more than 25 cents off (above C6, + * 1.5 cents a semitone sharper allowed: a piano's stretch) — a wrong root makes every note the zone plays off by as + * much (the Salamander's C4 regions, 2026-11-09), and moves both. + * + * npx tsx scripts/samples-tuning.mts … [--all] + * + * Exits 1 when a zone is off. Unpitched zones (pitched: false) and release and pedal zones are not measured. + */ +import { readFileSync } from "node:fs"; +import { basename } from "node:path"; +import { readSamples } from "../compiler/samples"; +import { clipChannels } from "../compiler/sound"; + +const args = process.argv.slice(2); +const files = args.filter((a) => !a.startsWith("--")); +if (!files.length) { console.error("usage: samples-tuning … [--all]"); process.exit(2); } +const N = 32768, LIMIT = 25; + +function fft(re: Float64Array, im: Float64Array) { + const n = re.length; + for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } } + for (let len = 2; len <= n; len <<= 1) { + const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang); + for (let i = 0; i < n; i += len) { + let cr = 1, ci = 0; + for (let j = 0; j < len / 2; j++) { + const a = i + j, b = a + len / 2, vr = re[b] * cr - im[b] * ci, vi = re[b] * ci + im[b] * cr; + re[b] = re[a] - vr; im[b] = im[a] - vi; re[a] += vr; im[a] += vi; + const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; + } + } + } +} + +/** Cents of harmonic `h` of `key` in `x` (at `rate`), or NaN when there is too little of it. */ +function cents(x: Float32Array, rate: number, key: number, h: number): number { + const a = Math.round(0.1 * rate), L = Math.min(Math.round(0.4 * rate), x.length - a, N); + if (L < 2048) return NaN; + const re = new Float64Array(N), im = new Float64Array(N); + for (let i = 0; i < L; i++) re[i] = x[a + i] * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / L)); + fft(re, im); + const mag = (k: number) => Math.hypot(re[k], im[k]); + const f = 440 * 2 ** ((key - 69) / 12) * h; + if (f > rate / 2.5) return NaN; + const lo = Math.floor((f * 2 ** (-0.9 / 12) * N) / rate), hi = Math.ceil((f * 2 ** (0.9 / 12) * N) / rate); + let bk = lo; + for (let k = lo; k <= hi; k++) if (mag(k) > mag(bk)) bk = k; + const y0 = Math.log(mag(bk - 1) + 1e-12), y1 = Math.log(mag(bk) + 1e-12), y2 = Math.log(mag(bk + 1) + 1e-12); + return 1200 * Math.log2((((bk + (0.5 * (y0 - y2)) / (y0 - 2 * y1 + y2)) * rate) / N) / f); +} + +let off = 0; +for (const file of files) { + const set = readSamples(readFileSync(file, "utf8")); + const seen = new Map(); + let checked = 0, bad = 0; + for (const z of set.zones) { + if ((z.trigger ?? "attack") !== "attack" || z.pitched === false || seen.has(z.clip)) continue; + seen.set(z.clip, true); + const ch = clipChannels(z.clip), x = ch.length === 1 ? ch[0] : ch[0].map((v, i) => (v + ch[1][i]) / 2); + const actual = z.key + (z.tune ?? 0) / 100, base = Math.round(actual), shift = (actual - base) * 100; + // Off when the fundamental and the second harmonic both say so (either alone can mislead: a low fundamental is + // weak, a drum's partials are not harmonics) — a wrong root moves both; above C6 a piano is tuned sharp (stretch). + const c1 = cents(x, set.rate, base, 1) - shift, c2 = cents(x, set.rate, base, 2) - shift; + const found = [c1, c2].filter(Number.isFinite); + if (!found.length) continue; + checked++; + const stretch = Math.max(0, base - 84) * 1.5, outside = (v: number) => v > LIMIT + stretch || v < -LIMIT; + const wrong = found.every(outside), c = Math.abs(c1) <= Math.abs(c2) || !Number.isFinite(c2) ? c1 : c2; + if (wrong) { bad++; off++; } + if (wrong || args.includes("--all")) console.log(`${wrong ? "OFF " : " "}${basename(file)} key ${z.key}${z.tune ? ` ${z.tune > 0 ? "+" : ""}${z.tune}¢` : ""} v${z.vlo}-${z.vhi}: ${c.toFixed(0)} cents (fundamental ${Number.isFinite(c1) ? c1.toFixed(0) : "–"}, 2nd harmonic ${Number.isFinite(c2) ? c2.toFixed(0) : "–"})`); + } + console.log(`${basename(file)}: ${checked} recordings measured, ${bad} off by more than ${LIMIT} cents.`); +} +process.exitCode = off ? 1 : 0; diff --git a/scripts/tuning-check.mts b/scripts/tuning-check.mts new file mode 100644 index 0000000..af0c925 --- /dev/null +++ b/scripts/tuning-check.mts @@ -0,0 +1,93 @@ +/** + * Whether a render is in tune, note by note: for each pitch a timeline says is struck, the frequency of its + * fundamental and its second harmonic just after each onset (an FFT over up to 0.2 s, the peak within a semitone of + * where it should be, refined by a parabola), the median over every time it is struck, in cents against equal + * temperament at A4 = 440 — judged by the fundamental, or under 200 Hz by the second harmonic. A pitch more than 25 cents off is flagged — above C6 a piano is tuned wider (its octaves + * stretched), so there it may be sharp by 1.5 cents a semitone more. + * + * npx tsx scripts/tuning-check.mts [--offset=seconds] [--parts=0,1] [--all] + * + * The timeline is a module as probes/lib/fur-elise-timeline-gen.mts writes one: NOTES rows [at, end, pitch, velocity, + * part, …], and ROLES when it has them (parts whose role is a drum, a cymbal, an impact or a riser are not pitched and + * are left out). `--offset`: where the render begins in the timeline (a section's clip). `--parts`: only these parts. + * `--all`: print every pitch, not only the ones off. Exits 1 when a pitch is off. Needs ffmpeg. + * + * Found its first use on the straight soundtrack (2026-11-09): B3, C4 and C#4 a semitone sharp — an SFZ region with no + * pitch_keycenter taken from its lowest key (make-samples, since fixed). + */ +import { execFileSync } from "node:child_process"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +const args = process.argv.slice(2); +const flag = (n: string) => args.find((a) => a.startsWith(`--${n}=`))?.slice(n.length + 3); +const [audio, timeline] = args.filter((a) => !a.startsWith("--")); +if (!audio || !timeline) { console.error("usage: tuning-check [--offset=s] [--parts=0,1] [--all]"); process.exit(2); } +const RATE = 48000, N = 32768, LIMIT = 25; +const raw = execFileSync("ffmpeg", ["-v", "error", "-i", resolve(audio), "-ac", "1", "-ar", String(RATE), "-f", "f32le", "-"], { maxBuffer: 1 << 30 }); +const x = new Float32Array(raw.buffer, raw.byteOffset, raw.byteLength / 4); +const mod = await import(pathToFileURL(resolve(timeline)).href) as { NOTES: readonly (readonly number[])[]; PARTS?: readonly string[]; ROLES?: readonly string[] }; +const offset = Number(flag("offset") ?? 0); +const only = flag("parts")?.split(",").map(Number); +const UNPITCHED = /^(drum|cymbal|impact|riser)/; + +function fft(re: Float64Array, im: Float64Array) { + const n = re.length; + for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } } + for (let len = 2; len <= n; len <<= 1) { + const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang); + for (let i = 0; i < n; i += len) { + let cr = 1, ci = 0; + for (let j = 0; j < len / 2; j++) { + const a = i + j, b = a + len / 2, vr = re[b] * cr - im[b] * ci, vi = re[b] * ci + im[b] * cr; + re[b] = re[a] - vr; im[b] = im[a] - vi; re[a] += vr; im[a] += vi; + const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; + } + } + } +} + +const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]; +const name = (p: number) => NAMES[p % 12] + (Math.floor(p / 12) - 1); +const per = new Map(); +for (const n of mod.NOTES) { + const [at, end, pitch, , part] = n; + if (only && !only.includes(part)) continue; + if (mod.ROLES && UNPITCHED.test(mod.ROLES[part] ?? "")) continue; + const t0 = at - offset + 0.04, L = Math.round(Math.min(0.2, end - at - 0.04) * RATE), i0 = Math.round(t0 * RATE); + if (L < 4000 || i0 < 0 || i0 + L > x.length) continue; + const re = new Float64Array(N), im = new Float64Array(N); + for (let i = 0; i < L; i++) re[i] = x[i0 + i] * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / L)); + fft(re, im); + const mag = (k: number) => Math.hypot(re[k], im[k]); + const out = per.get(pitch) ?? { c: [], c2: [] }; + for (const h of [1, 2]) { + const f = 440 * 2 ** ((pitch - 69) / 12) * h; + if (f < 70 || f > 4000) continue; + const lo = Math.floor((f * 2 ** (-0.9 / 12) * N) / RATE), hi = Math.ceil((f * 2 ** (0.9 / 12) * N) / RATE); + let bk = lo; + for (let k = lo; k <= hi; k++) if (mag(k) > mag(bk)) bk = k; + const y0 = Math.log(mag(bk - 1) + 1e-12), y1 = Math.log(mag(bk) + 1e-12), y2 = Math.log(mag(bk + 1) + 1e-12); + const fm = ((bk + (0.5 * (y0 - y2)) / (y0 - 2 * y1 + y2)) * RATE) / N; + (h === 1 ? out.c : out.c2).push(1200 * Math.log2(fm / f)); + } + per.set(pitch, out); +} +const median = (xs: number[]) => { const s = xs.filter(Number.isFinite).sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : NaN; }; +let off = 0, checked = 0; +for (const p of [...per.keys()].sort((a, b) => a - b)) { + const v = per.get(p)!, c = median(v.c), c2 = median(v.c2), n = Math.max(v.c.length, v.c2.length); + // The value to judge: the fundamental — but under 200 Hz the second harmonic, since 0.2 s cannot place a low + // fundamental within 25 cents and a piano's lowest are weak (F3's read −53 where its harmonic said −2). + const low = 440 * 2 ** ((p - 69) / 12) < 200; + const cents = low && Number.isFinite(c2) ? c2 : Number.isFinite(c) ? c : c2; + if (!Number.isFinite(cents)) continue; + checked++; + // Off when the judged value is, and the other one (where there is one) agrees: a wrong note moves both. + const stretch = Math.max(0, p - 84) * 1.5, outside = (v: number) => v > LIMIT + stretch || v < -LIMIT; + const other = cents === c ? c2 : c, bad = outside(cents) && (!Number.isFinite(other) || outside(other) || !low); + if (bad) off++; + if (bad || args.includes("--all")) console.log(`${bad ? "OFF " : " "}${name(p).padEnd(4)} ${String(p).padEnd(3)} ×${String(n).padEnd(4)} fundamental ${Number.isFinite(c) ? c.toFixed(0).padStart(4) : " –"} cents, 2nd harmonic ${Number.isFinite(c2) ? c2.toFixed(0).padStart(4) : " –"}`); +} +console.log(`${checked} pitches checked, ${off} off by more than ${LIMIT} cents (above C6, ${LIMIT} plus 1.5 a semitone sharp allowed).`); +process.exitCode = off ? 1 : 0; diff --git a/stdlib/music.ts b/stdlib/music.ts index e88d3d3..e8ffed2 100644 --- a/stdlib/music.ts +++ b/stdlib/music.ts @@ -404,8 +404,37 @@ export const presets = { bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }), /** A plucked string, a little bright. */ pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }), + /** + * A film trailer's "braam": five saws low and wide, the filter opening over half a second and closing slowly, driven + * hard — the brass section's blast as a synth. Play it low (A1 … A2), with the low brass on the same notes. + */ + braam: (o: SynthOptions = {}) => synth({ wave: "saw", voices: 5, detune: 16, width: 0.6, volume: 0.22, attack: 0.04, decay: 1.2, sustain: 0.7, release: 0.9, filter: { cutoff: 160, amount: 3.4, resonance: 0.25, envelope: { attack: 0.45, decay: 1.6, sustain: 0.35, release: 0.8 } }, drive: 14, ...o }), + /** A short synth pulse for sixteenth ostinatos: two squares, a quick filter blip. */ + pulse: (o: SynthOptions = {}) => synth({ wave: "square", voices: 2, detune: 9, width: 0.4, volume: 0.12, attack: 0.002, decay: 0.09, sustain: 0.25, release: 0.04, filter: { cutoff: 900, amount: 2.2, resonance: 0.3, envelope: { decay: 0.08, sustain: 0.1 } }, ...o }), + /** A sub bass: a sine, soft at the start, under everything. */ + sub: (o: SynthOptions = {}) => synth({ wave: "sine", volume: 0.4, attack: 0.02, decay: 0.3, sustain: 0.9, release: 0.25, ...o }), }; +/** + * An instrument of one-shots: a clip a key ("C2": the impact, "D2": a riser), each played whole whatever the note's + * length and not moved in pitch, as loud as its velocity says — percussion and effects as parts of a performance + * (`perform`), beside the instruments that play notes: `music.hits({ C2: music.impact(), D2: music.riser(4) })`. + */ +export function hits(clips: Readonly>, options: { readonly volume?: number } = {}): Instrument { + const volume = options.volume ?? 1, byKey = new Map(); + for (const [name, clip] of Object.entries(clips)) byKey.set(noteNumber(name), clip); + const clipOf = (name: string) => { + const c = byKey.get(noteNumber(name)); + if (!c) throw new Error(`hits() has no clip for ${name}: it has ${Object.keys(clips).join(", ")}.`); + return c; + }; + return Object.freeze({ + kind: "notes" as const, + note: (name: string) => (volume === 1 ? clipOf(name) : clipOf(name).gain(volume)), + strike: (name: string, _seconds: number, velocity: number) => clipOf(name).gain(volume * velocity), + }); +} + /** * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1). @@ -1707,6 +1736,6 @@ export const loop = game(async (s: Song) => { /** Everything above as one name: import { music } from "trigscript/music"; music.play(song). */ export const music = { - sampler, sampled, perform, excerpt, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop, + sampler, sampled, perform, excerpt, hits, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop, part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct, }; diff --git a/tests/make-samples.test.ts b/tests/make-samples.test.ts index 2eacc6e..83c0328 100644 --- a/tests/make-samples.test.ts +++ b/tests/make-samples.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -35,3 +35,24 @@ describe("make-samples: an SFZ's root keys", () => { } }, 60_000); }); + +describe("make-samples: a kit", () => { + it("makes a key a drum, its strengths from the names (v3, or pp … fff), the rest played in turn", () => { + const dir = mkdtempSync(join(tmpdir(), "make-kit-")); + try { + mkdirSync(join(dir, "drums")); + for (const f of ["boom_v1_rr1.wav", "boom_v1_rr2.wav", "boom_v2_rr1.wav", "gong_p.wav", "gong_fff.wav", "gong_mf.wav"]) writeFileSync(join(dir, "drums", f), wav(0.1)); + writeFileSync(join(dir, "kit.json"), JSON.stringify({ release: 2, drums: { C2: ["drums/boom_*"], G3: ["drums/gong_*"] } })); + const out = join(dir, "kit.samples"); + execFileSync("npx", ["tsx", join(__dirname, "..", "scripts", "make-samples.mts"), "--kit", join(dir, "kit.json"), out], { stdio: "pipe" }); + const zones = (JSON.parse(readFileSync(out, "utf8")) as { zones: { key: number; vlo: number; vhi: number; pitched?: boolean; turn?: number; turns?: number; release?: number }[] }).zones; + expect(zones.map((z) => [z.key, z.vlo, z.vhi, z.turn ?? 0, z.turns ?? 0])).toEqual([ + [36, 1, 63, 1, 2], [36, 1, 63, 2, 2], [36, 64, 127, 0, 0], + [55, 85, 127, 0, 0], [55, 43, 84, 0, 0], [55, 1, 42, 0, 0], + ]); + expect(zones.every((z) => z.pitched === false && z.release === 2)).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); +}); diff --git a/tests/sampled.test.ts b/tests/sampled.test.ts index 9cd1aea..eabb0be 100644 --- a/tests/sampled.test.ts +++ b/tests/sampled.test.ts @@ -225,6 +225,27 @@ describe("music.excerpt", () => { }); }); +describe("music.hits and the trailer presets", () => { + it("plays each key's clip whole, unpitched, as loud as its velocity, in a performance beside a note instrument", () => { + const r = run(` + const boom = tone(50, 2, { volume: 0.5 }), tick = noise(0.05, { volume: 0.3 }); + const fx = music.hits({ C2: boom, D2: tick }); + if (fx.note("C2", 0.1) !== boom) fail("note"); + if (Math.abs(fx.strike!("C2", 0.1, 0.5).peak - boom.peak * 0.5) > 1e-6) fail("strike"); + const take = music.perform({ meter: "3/8", bpm: 120 }, { fx: { instrument: fx, notes: "C2/16@100 r D2 r/4" } }); + const mix = music.render(take, { limit: false }); + // The boom whole, two seconds, though the note is a sixteenth. + if (Math.abs(mix.seconds - 2) > 0.05) fail(\`\${mix.seconds}\`); + const both = music.render(music.perform({ meter: "3/8", bpm: 120 }, { fx: { instrument: fx, notes: "C2/16@100 r D2 r/4" }, pad: { instrument: music.presets.braam(), notes: "A1/4." } }), { limit: false }); + if (!(both.seconds >= 2)) fail(\`\${both.seconds}\`); + for (const p of [music.presets.braam(), music.presets.pulse(), music.presets.sub()]) if (!(p.note("A2", 0.5).seconds >= 0.49)) fail("preset"); + let refused = ""; + try { fx.note("E2", 1); } catch (e) { refused = String(e); } + if (!/no clip for E2/.test(refused)) fail(refused);`); + expect(errors(r)).toEqual([]); + }); +}); + describe("loudness and sympathy", () => { it("measures a full-scale 997 Hz sine at −3.01 LUFS on one side, 0 from both (as the game plays one channel), and brings a clip to a loudness", () => { const sine = tone(997, 3, { volume: 1, rate: 48000 }); From 13ce19ec0ad9f32abff8eace2e7eae2658a44a72 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 06:03:57 -0600 Subject: [PATCH 22/31] A sampled instrument's identity in every clip name made from it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A clip from a .samples file was named by its own recording's bytes, so a change elsewhere in the instrument (another recording, a zone's root or strengths) left it the same name — and in the editor withSounds keeps a file whose name the map already has. Now each recording's key carries the instrument's identity too: a hash of its rate, its zones and every recording's hash, worked out once when the file is read from the coded bytes (nothing decoded). Change anything in an instrument and every clip made from it gets a new name. ENGINE stays "sound 3": only clips made from instruments are renamed, by their keys; nothing else is made differently. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- compiler/samples.ts | 16 +++++++++++----- tests/sampled.test.ts | 12 ++++++++++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/compiler/samples.ts b/compiler/samples.ts index c0823d9..9c343f3 100644 --- a/compiler/samples.ts +++ b/compiler/samples.ts @@ -264,16 +264,22 @@ export function readSamples(text: string): Samples { checkZones(h.zones, h.samples.length); const data = fromBase64(h.data); let o = 0, seconds = 0; - const clips = h.samples.map((s) => { + // Each recording's own hash, then the instrument's: its zones and every recording's hash together. Every clip made + // from it is named by both, so an instrument changed in any way — a recording, a zone's key or strength — gives every + // clip made from it a new file name, and a map that keeps the files whose names it has (withSounds) takes the new + // ones. Cheap: the coded bytes are hashed, nothing is decoded. + const parts = h.samples.map((s) => { const bytes = data.subarray(o, o + s.bytes); o += s.bytes; if (bytes.length < s.bytes) throw new Error(`The recording ${s.name} ends too soon: the file is cut short.`); seconds += s.frames / rate; - return storedClip(`samples:${hashBytes(bytes)}:${s.channels}:${s.frames}:${rate}`, rate, s.frames, s.channels, () => { - const r = new BitReader(bytes); - return Array.from({ length: s.channels }, () => decodeChannel(r, s.frames)); - }); + return { s, bytes, hash: hashBytes(bytes) }; }); + const identity = hashBytes(new TextEncoder().encode(`${rate}|${JSON.stringify(h.zones)}|${parts.map((p) => p.hash).join(",")}`)); + const clips = parts.map(({ s, bytes, hash }) => storedClip(`samples:${identity}:${hash}:${s.channels}:${s.frames}:${rate}`, rate, s.frames, s.channels, () => { + const r = new BitReader(bytes); + return Array.from({ length: s.channels }, () => decodeChannel(r, s.frames)); + })); const zones = h.zones.map((z) => Object.freeze({ ...z, clip: clips[z.sample] })); return Object.freeze({ __trigscript: "samples" as const, name: typeof h.name === "string" ? h.name : "", credit: typeof h.credit === "string" ? h.credit : "", diff --git a/tests/sampled.test.ts b/tests/sampled.test.ts index eabb0be..e35bf38 100644 --- a/tests/sampled.test.ts +++ b/tests/sampled.test.ts @@ -93,6 +93,18 @@ describe("the .samples file", () => { expect(text.length).toBeLessThan(rec[0].length * 4 * (4 / 3) * 0.6); }); + it("names every clip made from an instrument by the instrument too: change one recording, every name changes", () => { + const one = (level: number) => writeSamples({ rate: RATE, samples: [{ name: "a", channels: ring(220, 0.5, 0.5) }, { name: "b", channels: ring(440, 0.5, level) }], zones: [ + { sample: 0, key: 57, lo: 0, hi: 62, vlo: 1, vhi: 127 }, { sample: 1, key: 69, lo: 63, hi: 127, vlo: 1, vhi: 127 }, + ] }); + // Only recording b differs; the clip played is made from recording a. + const names = (text: string) => compileScript(ts, { "main.ts": `import inst from "./inst.samples";\nprogram(async () => { playWav(inst.zones[0].clip.gain(0.5), 0); });`, "inst.samples": text }, defaultScriptNames(), { lib: LIB, sounds: false }).sounds.map((x) => x.path); + const [a, b] = [names(one(0.5)), names(one(0.4))]; + expect(a.length).toBe(1); + expect(a).not.toEqual(b); + expect(names(one(0.5))).toEqual(a); + }); + it("refuses a zone that names no recording, and says what it holds on the hover", () => { expect(() => writeSamples({ rate: RATE, samples: [], zones: [{ sample: 0, key: 60, lo: 0, hi: 127, vlo: 1, vhi: 127 }] })).toThrow(/names recording 0/); expect(describeSamples(instrument())).toMatch(/^A sampled instrument, Test: 6 recordings .* 6 zones at 22,050 Hz\. Ours \(CC0\)\.$/); From c0c350f7e937964328a21a697ca38b85831bed5d Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 06:19:17 -0600 Subject: [PATCH 23/31] =?UTF-8?q?S7:=20F=C3=BCr=20Elise,=20the=20cinematic?= =?UTF-8?q?=20arrangement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A trailer-score arrangement, 2:36.5 with the hall's tail: the theme's first phrase on the piano alone, free in time, a drone and a riser; the band in at 0:12.7 at 144 eighths a minute, felt in 6/8 (the theme, its repeat, the middle part); the F major episode as a lift and a build; the storm with everything as the climax; a breakdown over a pumping pad; the theme big; the band gone and the last bars on the piano alone. The piano is the lead throughout; around it VSCO strings, brass and timpani, a new VSCO percussion kit as taiko patterns, and synths made in the script (braam, sub, pads, pulses, supersaw, kick, impacts, risers). Rendered a section at a time in the hall, section faders, one gain to −14 LUFS, limited once: −14.0 LUFS, −1.4 dBTP decoded, the storm the loudest. probes/lib/fur-elise-cinematic-timeline.ts carries every part with its role, the sections with their frames and the big hits, for the picture; the straight timeline gained roles and hits too. The timeline generator takes --cinematic. tuning-check now calls a pitch off only when both readings agree (a chord neighbour moves one) and leaves pitches under 80 Hz unjudged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 41 + probes/fur-elise-cinematic.ts | 21 + probes/lib/fur-elise-cinematic-score.ts | 253 ++ probes/lib/fur-elise-cinematic-timeline.ts | 3836 ++++++++++++++++++++ probes/lib/fur-elise-cinematic.ts | 106 + probes/lib/fur-elise-sound-gen.mts | 6 +- probes/lib/fur-elise-timeline-gen.mts | 52 +- probes/lib/fur-elise-timeline.ts | 22 +- probes/lib/vsco-percussion.kit.json | 19 + scripts/tuning-check.mts | 14 +- 10 files changed, 4348 insertions(+), 22 deletions(-) create mode 100644 probes/fur-elise-cinematic.ts create mode 100644 probes/lib/fur-elise-cinematic-score.ts create mode 100644 probes/lib/fur-elise-cinematic-timeline.ts create mode 100644 probes/lib/fur-elise-cinematic.ts create mode 100644 probes/lib/vsco-percussion.kit.json diff --git a/docs/v4-plan.md b/docs/v4-plan.md index 898a1cf..26c9f9f 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6643,6 +6643,47 @@ After the sound probe ("sounds great") and the visualizer probe (one long clip k bars (−13.7): at the probe's −17 / −15 the climax is bigger in sound, not much in level — lower the piano to −18.5 if it should stand out more. +#### S7 the cinematic arrangement (built 2026-11-09) + +The user on the straight soundtrack: "sounds okay but it takes awhile to get going, can we do a stylistic +arrangement?" and "some of the notes sound a bit sharp" (B3/C4/C#4 a semitone sharp: an SFZ region with no root, fixed +in e67671d). Chosen: a cinematic hybrid — piano, orchestra, big percussion, synth pulses — about 2:30. + +- **The form** (`probes/lib/fur-elise-cinematic-score.ts`, the piano's notes the score's; frames at 42 ms): + intro 0:00 (frame 0) — bars 1 … 8 on the piano alone, free in time, a drone creeping in, a riser made to end on the + band's downbeat; band 0:12.7 (302) — the theme, its repeat and the middle part at 144 eighths a minute, steady, felt + in 6/8; lift 0:48.9 (1165) — the F major episode as a breath, pulses at its thirty-seconds, the E–D# made a build + (riser, tom fills, snare roll); storm 1:08.9 (1642) — the drumming A as a taiko pulse, then everything, the climax; + breakdown 1:32.1 (2192) — the arpeggios and the run over a pumping pad; final 1:38.8 (2352) — the theme big, with + its repeat and the middle part to bar 18; ending 2:13.9 (3189) — the band gone, bars 19 … 21 and the held A on the + piano alone. The whole 2:36.5 (the music 2:22, then the hall). +- **The palette:** the Salamander piano as the lead throughout (a quick compressor on it; its ff chords stood 6 dB + over everything's peaks); VSCO strings (spiccato ostinatos from each bar's chord, held strings, the probe's storm + parts), horns, trombones and tuba (braams with the synth braam on the strong bars), timpani; a new VSCO percussion kit + (gran cassa, bass drums, tenor drums, snare and roll, crash, suspended cymbal, gong) as taiko patterns over two bars; + synths made in the script: braam, sub, pad (pumping a bar), pulses, supersaw in the climax, the library's kick, + impacts, a sub drop, risers, a crash reversed. Each part's level set by measuring it alone in the storm against the + piano at −13 LUFS. +- **Mixing:** each section rendered apart in the hall (the band's through a 2:1 bus), section faders (storm +1 dB, + final −2), one gain for all (`together(…, { lufs })`), the whole limited once to 0.8. −14.0 LUFS integrated, true peak + −1.4 dBTP decoded (the band section's clip −1.0). Short-term: intro −19, band −13 … −16, lift −15, storm −11 … −12, + breakdown −16.5, final −14, ending −21. The limiter takes up to ~6 dB off the storm's biggest hits. 3.2 MB at q6. +- **Library and tools:** `music.hits` (one-shots in a performance), presets braam / pulse / sub, make-samples `--kit`, + `scripts/tuning-check.mts` (a render against its timeline) and `scripts/samples-tuning.mts` (an instrument's zones); + a sampled instrument's identity in every clip name made from it (no ENGINE bump). +- **Tuning:** the cinematic whole — 58 pitches checked, one flagged: the trombones' C#3, two notes under the storm's + braam (its A1's fifth harmonic on C#3's second); rendered alone they are −1 cents. 11 pitches under 80 Hz (the sub) + not judged. The straight soundtrack after the fix: 55 checked, none off. The instruments: the horn's G2, the tuba's + F1, timpani 5's ff off, none of them played. +- **Timeline:** `probes/lib/fur-elise-cinematic-timeline.ts` (beside the straight one, which gained ROLES and HITS): + 3,644 notes, PARTS and ROLES (lead, accomp, strings, brass, bass, synth, pad, drum-low, drum-high, cymbal, impact, + riser), SECTIONS with frames, BARS, PEDAL, HITS (100: impacts, and low drums and cymbals at velocity 110 or more, + `[at, frame, strength, part]`). The render is `probes/lib/fur-elise-cinematic.ts` (importing it starts nothing); + `probes/fur-elise-cinematic.ts` plays it. + +**Open:** the user's ears. The final statement is dense (LRA 1.0) — a wall of sound by design, maybe too much; the +storm's hits are limited hard. Previews: Maps/TrigScript/fur-elise-sound-preview/cinematic/. + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice diff --git a/probes/fur-elise-cinematic.ts b/probes/fur-elise-cinematic.ts new file mode 100644 index 0000000..120a2d7 --- /dev/null +++ b/probes/fur-elise-cinematic.ts @@ -0,0 +1,21 @@ +// Für Elise, the cinematic arrangement (S7, 2026-11-09): plays the whole piece; keys 1 … 7 play a section's clip on +// its own. The render is probes/lib/fur-elise-cinematic.ts; the timeline for a picture, probes/lib/ +// fur-elise-cinematic-timeline.ts (probes/lib/fur-elise-timeline-gen.mts --cinematic). +// +// npx tsx scripts/sound-dump.mts probes/fur-elise-cinematic.ts +import { whole, sectionClips } from "./lib/fur-elise-cinematic"; + +program(async () => { + displayText("\x04Für Elise, cinematic: the whole piece. Keys 1-7 play a section on its own."); + playWav(whole, 0); + while (true) { + if (keyPressed(P1, "1")) playWav(sectionClips[0], 0); + if (keyPressed(P1, "2")) playWav(sectionClips[1], 0); + if (keyPressed(P1, "3")) playWav(sectionClips[2], 0); + if (keyPressed(P1, "4")) playWav(sectionClips[3], 0); + if (keyPressed(P1, "5")) playWav(sectionClips[4], 0); + if (keyPressed(P1, "6")) playWav(sectionClips[5], 0); + if (keyPressed(P1, "7")) playWav(sectionClips[6], 0); + await nextFrame(); + } +}); diff --git a/probes/lib/fur-elise-cinematic-score.ts b/probes/lib/fur-elise-cinematic-score.ts new file mode 100644 index 0000000..85447a3 --- /dev/null +++ b/probes/lib/fur-elise-cinematic-score.ts @@ -0,0 +1,253 @@ +// Für Elise as a cinematic hybrid (asked 2026-11-09): piano, orchestra, big percussion and synths, a trailer score's +// shape. The piano's notes are the score's (probes/lib/fur-elise-score.ts, ours from the public-domain score); every +// other part is our arrangement, written here bar by bar from the harmony of each bar, in the notation `music.perform` +// reads. 3/8 throughout, felt as 6/8 once the band is in (a pulse every three eighths, patterns over two bars). +// +// The form, by bar of the whole: +// intro 0 … 8 the theme's first phrase on the piano alone, free in time; a low drone creeping in; a riser +// band 9 … 37 the band in on bar 1's downbeat at 144 eighths a minute: the theme, its repeat, the middle part +// lift 38 … 53 the F major episode as a breath, its thirty-seconds over pulses, the E–D# turned into a build +// storm 54 … 71 the drumming A as a taiko pulse, the storm with everything: the climax +// breakdown 72 … 76 the arpeggios and the run over a pumping pad, a riser +// final 77 … 102 the theme big, its repeat, the middle part, to bar 18 +// ending 103 … 106 the band gone: bars 19 … 21 and the last A on the piano alone, slowing, held in the pedal +import { + A_RIGHT, A_LEFT, A_TEMPO, B_RIGHT, B_LEFT, C_RIGHT, C_LEFT, P_RIGHT, P_LEFT, C_VIOLINS, C_VIOLAS, C_HORNS, C_TROMBONES, C_TUBA, C_TIMPANI, sixteenths, +} from "./fur-elise-score"; + +/** What a part is to the picture: the timeline gives each part one. */ +export type Role = "lead" | "accomp" | "strings" | "brass" | "bass" | "synth" | "pad" | "drum-low" | "drum-high" | "cymbal" | "impact" | "riser"; + +/** The parts, in the order the timeline numbers them, with their roles. */ +export const PART_ROLES = { + right: "lead", left: "accomp", + violins: "strings", violas: "strings", ostinato: "strings", celli: "strings", basses: "bass", + horns: "brass", trombones: "brass", tuba: "brass", braam: "brass", + sub: "bass", drone: "pad", pad: "pad", pulse: "synth", supersaw: "synth", + taiko: "drum-low", kick: "drum-low", timpani: "drum-low", toms: "drum-high", snare: "drum-high", + cymbals: "cymbal", impacts: "impact", risers: "riser", +} as const satisfies Record; +export type PartName = keyof typeof PART_ROLES; + +/* ── Harmony, a chord a bar ── */ + +const PC: Readonly> = { C: 0, "C#": 1, Db: 1, D: 2, "D#": 3, Eb: 3, E: 4, F: 5, "F#": 6, G: 7, "G#": 8, Ab: 8, A: 9, Bb: 10, B: 11 }; +const KINDS: Readonly> = { "": [0, 4, 7], m: [0, 3, 7], "7": [0, 4, 7, 10], dim: [0, 3, 6, 9] }; +const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "Bb", "B"]; +const nm = (n: number) => NAMES[((n % 12) + 12) % 12] + (Math.floor(n / 12) - 1); +/** A chord's notes from its root in `octave`: root, third, fifth (and seventh). */ +function chord(sym: string, octave: number): number[] { + const m = /^([A-G][#b]?)(m|7|dim)?$/.exec(sym); + if (!m) throw new Error(`no chord ${sym}`); + const root = 12 * (octave + 1) + PC[m[1]]; + return KINDS[m[2] ?? ""].map((i) => root + i); +} + +/** The harmony of the theme's bars (by the score's numbers; 8 is either ending). */ +const THEME_H: Readonly> = { + 0: "E", 1: "E", 2: "Am", 3: "E", 4: "Am", 5: "E", 6: "Am", 7: "E", 8: "Am", 9: "C", 10: "G", 11: "Am", 12: "E", 13: "E", 14: "E", + 15: "E", 16: "Am", 17: "E", 18: "Am", 19: "E", 20: "Am", 21: "E", 22: "Am", +}; +const B_H = ["Am", "F", "Bb", "C7", "F", "F", "Am", "G7", "C", "G", "C", "G", "E", "E", "E", "E"]; +const STORM_H = ["A", "A", "Dm", "E", "Am", "Dm", "D#dim", "E", "Am", "A", "Dm", "Dm", "Bb", "Eb", "Bb", "E", "Am", "E"]; +const P_H = ["Am", "Am", "Am", "E", "E"]; + +/* ── Generated parts: a bar's text from its chord ── */ + +/** Spiccato ostinato, sixteenths: root, root, fifth | root, fifth, octave — accents on the pulses. */ +const ostinatoBar = (sym: string, octave: number, v = 0) => { + const [r, , f] = chord(sym, octave); + return `${nm(r)}/16@${100 + v} ${nm(r)}@${70 + v} ${nm(f)}@${78 + v} ${nm(r)}@${96 + v} ${nm(f)}@${72 + v} ${nm(r + 12)}@${80 + v}`; +}; +/** The bass's eighths on the root, the first strong. */ +const bassBar = (sym: string, octave: number, v = 0) => { const r = nm(chord(sym, octave)[0]); return `${r}/8@${105 + v} ${r}@${80 + v} ${r}@${88 + v}`; }; +/** A chord held the bar (pads, strings, horns). */ +const heldBar = (sym: string, octave: number, v = 0, top = 3) => `${chord(sym, octave).slice(0, top).map(nm).join("+")}/4.@${90 + v}`; +/** The sub: the root, an octave under the bass, the bar. */ +const subBar = (sym: string, v = 0) => `${nm(chord(sym, 1)[0])}/4.@${95 + v}`; +/** Synth pulses: the chord's notes going up in sixteenths. */ +const pulseBar = (sym: string, octave: number, v = 0) => { + const c = chord(sym, octave), n = [c[0], c[1], c[2], c[0] + 12, c[2], c[1]]; + return n.map((x, k) => `${nm(x)}${k === 0 ? "/16" : ""}@${(k % 3 === 0 ? 96 : 76) + v}`).join(" "); +}; +/** A braam: root and fifth low, root an octave up, held `bars` bars. */ +const braam = (sym: string, bars = 1, v = 0) => { + const [r, , f] = chord(sym, 1), notes = [r, f, r + 12].map(nm).join("+"); + return bars === 1 ? [`${notes}/4.@${110 + v}`] : [`${notes}/4.@${110 + v}~`, ...Array.from({ length: bars - 1 }, (_, k) => `${notes}/4.${k < bars - 2 ? "~" : ""}`)]; +}; + +const rest = "r/4."; +const rests = (n: number) => Array.from({ length: n }, () => rest); + +/* ── The percussion, a bar of 3/8 at a time (kit keys: probes/lib/vsco-percussion.kit.json) ── */ +// Kit: C2 gran cassa, C#2 bass drum, D2 bass drum muted, E2 low tenor drum, F#2 high tenor drum, G2 snare, G#2 snare +// roll, C#3 crash, D#3 suspended cymbal, G3 gong. Hits (synth, music.hits): C2 impact, D2 sub drop, E2 kick, F2 a crash +// reversed (two bars), G2 riser (four bars), A2 riser (three bars), B2 riser (intro). +const TAIKO = { + light: ["C2/8@95 r/16 D2@60 r/8", "D2/16@80 r r D2@70 r/8"], + groove: ["C2/8@110 r/16 D2@75 E2/8@85", "D2/16@95 r E2@70 E2@60 D2/8@100"], + full: ["C2/16@122 r D2@85 E2@95 C2@112 r", "D2/16@105 E2@75 F#2@80 C2@118 E2@85 F#2@92"], + storm: ["C2/16@124 E2@75 E2@80 D2@110 E2@75 E2@85", "C#2/16@118 E2@75 E2@82 D2@110 E2@78 F#2@95"], + fill: ["E2/16@80 E2@86 F#2@92 E2@98 F#2@104 F#2@110", "E2/16@105 F#2@110 E2@114 F#2@118 E2@122 F#2@127"], + half: ["C2/8@90 r r", rest], +}; +/** Bars of a pattern of two bars, `n` bars long. */ +const pattern = (two: readonly string[], n: number) => Array.from({ length: n }, (_, k) => two[k % 2]); +/** The synth kick on each pulse (twice a bar of 6/8: on the first and fourth sixteenths of 3/8, the first only). */ +const kicks = (n: number, v = 0) => Array.from({ length: n }, () => `E2/4.@${100 + v}`); + +/* ── The whole ── */ + +export interface CinematicSection { readonly name: string; readonly from: number; readonly to: number } + +/** Strip a bar's dynamics and hairpins; `mark` before the first. */ +function marked(bars: readonly string[], mark: string, keepPedal = true): string[] { + return bars.map((b, i) => { + const words = b.split(/\s+/).filter((w) => w && !/^(ppp|pp|p|mp|mf|f|ff|fff|<|>)$/.test(w) && (keepPedal || !/^(ped|\*)$/.test(w))); + return (i === 0 ? `${mark} ` : "") + words.join(" "); + }); +} +const range = (a: number, b: number) => Array.from({ length: b - a + 1 }, (_, i) => a + i); + +export function cinematic() { + const parts: Record = Object.fromEntries(Object.keys(PART_ROLES).map((k) => [k, [] as string[]])) as Record; + const sections: CinematicSection[] = []; + let bars = 0; + /** A section: `n` bars, each part given its bars (or rests). The pickup bar is 1/8 long. */ + const add = (name: string, n: number, given: Partial>, pickup = false) => { + for (const k of Object.keys(PART_ROLES) as PartName[]) { + const list = given[k] ?? (pickup ? ["r/8", ...rests(n - 1)] : rests(n)); + if (list.length !== n) throw new Error(`${name}: ${k} has ${list.length} bars, not ${n}.`); + parts[k].push(...list); + } + sections.push({ name, from: bars, to: bars + n }); + bars += n; + }; + const harmony = (list: readonly (number | "8a" | "8b")[]) => list.map((k) => THEME_H[typeof k === "number" ? k : 8]); + const R = (k: number | "8a" | "8b") => (k === "8a" ? "A4/4 E5/16@+2 D#5@-3" : A_RIGHT[k === "8b" ? 8 : k]); + const L = (k: number | "8a" | "8b") => (k === "8a" ? "ped A2/16 E3 A3 r * r/8" : A_LEFT[k === "8b" ? 8 : k]); + + // Intro: pickup, 1 … 7, and the first ending (its A held, the pickup at the band's tempo). A drone: A1 and A2 from + // bar 3, a pad on the harmony from bar 5, both creeping up; a riser into the band and a crash reversed before it. + const introBars: (number | "8a")[] = [0, ...range(1, 7), "8a"]; + add("intro", 9, { + right: introBars.map(R), left: introBars.map(L), + sub: ["r/8", rest, rest, "pp A1/4.@40~", "A1/4.~", "A1/4.~", "A1/4.~", "A1/4.~", "A1/4.@60"], + drone: ["r/8", rest, rest, rest, rest, "pp < E3+B3/4.", "A2+E3+C4/4.", "E3+G#3+B3/4.", "mp A2+E3+C4/4."], + risers: ["r/8", rest, rest, rest, rest, rest, "B2/4.@90", rest, rest], + }, true); + + // The band: the theme (1 … 7 and the first ending; 1 … 7 and the second), then the middle part 9 … 21. Its first time + // lighter (ostinato, low drums, sub), its repeat full (strings held, kick, pad pumping); the middle part (9 … 14) + // drawn back, the theme's return (15 … 21) full again with braams. + const themeA: (number | "8a" | "8b")[] = [...range(1, 7), "8a"], themeB: (number | "8a" | "8b")[] = [...range(1, 7), "8b"], middle = range(9, 21); + const band = [...themeA, ...themeB, ...middle], bh = harmony(band); + const nB = band.length; // 29 + add("band", nB, { + right: marked(band.map(R), "f"), left: marked(band.map(L), "mf"), + ostinato: bh.map((h, k) => ostinatoBar(h, 3, k < 8 ? -10 : k >= 16 && k < 22 ? -14 : 0)), + celli: bh.map((h, k) => (k < 8 ? rest : ostinatoBar(h, 2, k >= 16 && k < 22 ? -16 : -4))), + basses: bh.map((h, k) => (k < 8 || (k >= 16 && k < 22) ? rest : bassBar(h, 1, -6))), + sub: bh.map((h, k) => subBar(h, k < 8 ? -20 : -6)), + violins: bh.map((h, k) => (k < 8 || (k >= 16 && k < 22) ? rest : heldBar(h, 4, -14))), + pad: bh.map((h, k) => (k >= 8 ? heldBar(h, 3, k >= 16 && k < 22 ? -24 : -12) : rest)), + horns: bh.map((h, k) => (k >= 22 ? heldBar(h, 3, -14, 2) : rest)), + braam: bh.map((h, k) => (k === 0 || k === 8 || k === 22 ? braam(h)[0] : rest)), + trombones: bh.map((h, k) => (k === 0 || k === 8 || k === 22 ? braam(h, 1, -10)[0] : rest)), + tuba: bh.map((h, k) => (k === 0 || k === 8 || k === 22 ? `${nm(chord(h, 1)[0])}/4.@100` : rest)), + taiko: [...pattern(TAIKO.light, 8), ...pattern(TAIKO.groove, 8), ...pattern(TAIKO.half, 6), ...pattern(TAIKO.full, 6), TAIKO.fill[1]], + kick: bh.map((_, k) => (k >= 8 && !(k >= 16 && k < 22) ? `E2/4.@${k >= 22 ? 108 : 96}` : rest)), + toms: bh.map((_, k) => (k === 15 || k === 27 ? TAIKO.fill[0] : rest)), + cymbals: bh.map((_, k) => (k === 0 || k === 8 || k === 22 ? "C#3/4.@105" : k === 16 ? "D#3/4.@70" : rest)), + impacts: bh.map((_, k) => (k === 0 ? "C2/4.@115" : k === 22 ? "C2/4.@100" : rest)), + risers: bh.map((_, k) => (k === 6 || k === 20 ? "F2/4.@85" : rest)), + }); + + // The lift: the episode as a breath — piano and held strings, the pulses joining at the thirty-seconds (B8), the + // E–D# (B12 … B15) turned into the build: a riser over four bars, the toms and the snare roll growing. + const liftH = B_H; + add("lift", 16, { + right: marked(B_RIGHT, "mf"), left: marked(B_LEFT, "mp"), + violins: liftH.map((h, k) => (k < 12 ? heldBar(h, 4, -22) : rest)), + violas: liftH.map((h, k) => (k < 12 ? heldBar(h, 3, -24) : rest)), + pad: liftH.map((h, k) => heldBar(h, 3, k < 8 ? -28 : -18)), + sub: liftH.map((h, k) => subBar(h, k < 8 ? -30 : -14)), + pulse: liftH.map((h, k) => (k >= 8 ? pulseBar(h, 4, k >= 12 ? -4 + (k - 12) * 4 : -12) : rest)), + ostinato: liftH.map((h, k) => (k >= 12 ? ostinatoBar(h, 3, -12 + (k - 12) * 5) : rest)), + taiko: liftH.map((_, k) => (k < 8 ? (k % 4 === 0 ? "C2/4.@70" : rest) : k < 12 ? TAIKO.half[k % 2] : TAIKO.groove[k % 2])), + toms: liftH.map((_, k) => (k === 14 ? TAIKO.fill[0] : k === 15 ? TAIKO.fill[1] : rest)), + snare: liftH.map((_, k) => (k >= 13 ? `G#2/4.@${70 + (k - 13) * 20}` : rest)), + cymbals: liftH.map((_, k) => (k === 0 ? "D#3/4.@60" : k === 8 ? "D#3/4.@80" : rest)), + risers: liftH.map((_, k) => (k === 12 ? "G2/4.@100" : rest)), + }); + + // The storm: the bar of drumming A as the taiko pulse alone with the piano, then everything — the probe's orchestra, + // braams on the strong bars, the supersaw doubling the right hand's chords, the pulses, the pad pumping, impacts on + // C1, C9 and the last chord, the gong on C16. + const sh = STORM_H, strong = new Set([1, 5, 9, 12, 16]); + add("storm", 18, { + right: ["A4/8@-4 r r", ...C_RIGHT], left: [`f ${sixteenths("A2")}`, ...C_LEFT.map((b, k) => (k === 0 ? b.replace(/^f /, "ff ") : b))], + violins: [rest, ...C_VIOLINS], violas: [rest, ...C_VIOLAS], horns: [rest, ...C_HORNS], trombones: [rest, ...C_TROMBONES], tuba: [rest, ...C_TUBA], timpani: [rest, ...C_TIMPANI], + ostinato: sh.map((h) => ostinatoBar(h, 3, 4)), celli: sh.map((h, k) => (k === 0 ? rest : ostinatoBar(h, 2, 2))), basses: sh.map((h, k) => (k === 0 ? rest : bassBar(h, 1, 4))), + sub: sh.map((h) => subBar(h, 0)), + pad: sh.map((h, k) => (k === 0 ? rest : heldBar(h, 3, -10))), + pulse: sh.map((h, k) => (k === 0 ? rest : pulseBar(h, 5, -8))), + supersaw: sh.map((h, k) => (k === 0 || k === 17 ? rest : heldBar(h, 4, -4))), + braam: sh.map((h, k) => (strong.has(k) ? braam(h, 1, 6)[0] : rest)), + taiko: sh.map((_, k) => (k === 17 ? "C2/8@125 r r" : TAIKO.storm[k % 2])), + kick: sh.map((_, k) => (k === 0 || k === 17 ? rest : "E2/4.@110")), + toms: sh.map((_, k) => (k === 8 || k === 15 ? TAIKO.fill[1] : rest)), + cymbals: sh.map((_, k) => (k === 1 || k === 9 ? "C#3/4.@120" : k === 16 ? "G3/4.@120" : k === 5 || k === 12 ? "C#3/4.@100" : rest)), + impacts: sh.map((_, k) => (k === 1 || k === 9 ? "C2/4.@125" : k === 16 ? "C2/4.@127" : k === 17 ? "D2/4.@110" : rest)), + risers: sh.map((_, k) => (k === 7 ? "F2/4.@90" : rest)), + }); + + // The breakdown: the arpeggios and the run over the pad, pumping, and a heartbeat; a riser over its last three bars. + add("breakdown", 5, { + right: marked(P_RIGHT, "mp"), left: marked(P_LEFT, "mp"), + pad: P_H.map((h) => heldBar(h, 3, -10)), sub: P_H.map((h) => subBar(h, -16)), + taiko: ["C2/4.@80", rest, "C2/4.@85", rest, "D2/16@90 D2@95 D2@100 D2@105 D2@112 D2@120"], + risers: [rest, rest, "A2/4.@100", rest, rest], + }); + + // The final statement, big: everything in from bar 1, the middle part (9 … 14) full but its brass out, its return to + // bar 18. Bar 18's chord the band's last. + const fin: (number | "8a" | "8b")[] = [...themeA, ...themeB, ...range(9, 18)], fh = harmony(fin), nF = fin.length; // 26 + const bigBar = (k: number) => k === 0 || k === 8 || k === 16 || k === 22; + add("final", nF, { + right: marked(fin.map(R), "ff"), left: marked(fin.map(L), "f"), + ostinato: fh.map((h) => ostinatoBar(h, 3, 2)), celli: fh.map((h) => ostinatoBar(h, 2, 0)), basses: fh.map((h) => bassBar(h, 1, 0)), + violins: fh.map((h) => heldBar(h, 4, -8)), violas: fh.map((h) => heldBar(h, 3, -14)), + horns: fh.map((h, k) => (k >= 16 && k < 22 ? rest : heldBar(h, 3, -6, 2))), + sub: fh.map((h) => subBar(h, -2)), pad: fh.map((h) => heldBar(h, 3, -10)), pulse: fh.map((h, k) => (k >= 8 ? pulseBar(h, 5, -10) : rest)), + supersaw: fh.map((h, k) => (k >= 22 ? heldBar(h, 4, -6) : rest)), + braam: fh.map((h, k) => (bigBar(k) ? braam(h, 1, 4)[0] : rest)), + trombones: fh.map((h, k) => (bigBar(k) ? braam(h, 1, -6)[0] : rest)), + tuba: fh.map((h, k) => (bigBar(k) ? `${nm(chord(h, 1)[0])}/4.@105` : rest)), + taiko: [...pattern(TAIKO.full, 8), ...pattern(TAIKO.full, 8), ...pattern(TAIKO.groove, 6), ...pattern(TAIKO.full, 3), "C2/8@127 r r"], + kick: fh.map((_, k) => (k === nF - 1 ? "E2/8@115 r r" : "E2/4.@108")), + toms: fh.map((_, k) => (k === 7 || k === 15 || k === 21 ? TAIKO.fill[1] : rest)), + timpani: fh.map((h, k) => (bigBar(k) || k === nF - 1 ? `${h.startsWith("A") ? "A2" : "E3"}/4.@115` : rest)), + cymbals: fh.map((_, k) => (bigBar(k) ? "C#3/4.@118" : k === nF - 1 ? "G3/4.@110" : rest)), + impacts: fh.map((_, k) => (k === 0 ? "C2/4.@127" : k === 16 || k === 22 ? "C2/4.@112" : k === nF - 1 ? "C2/4.@120" : rest)), + risers: fh.map((_, k) => (k === 6 || k === 14 || k === 20 ? "F2/4.@90" : rest)), + }); + + // The ending: the band gone, bars 19 … 21 and the last A on the piano alone, slowing; a low drone under the first two. + add("ending", 4, { + right: marked([A_RIGHT[19], A_RIGHT[20], A_RIGHT[21], "A4/4.@+8"], "mp").map((b, k) => (k === 3 ? `ppp ${b}` : k === 2 ? `> ${b}` : b)), + left: marked([A_LEFT[19], A_LEFT[20], A_LEFT[21], "ped A1+A2/4. | r/4. | r/4. *"], "p").map((b, k) => (k === 3 ? `ppp ${b}` : b)), + sub: ["pp A1/4.@50~", "A1/4.", rest, rest], + }); + + // The tempo: the intro free (the probe's shape for bars 1 … 8), the pickup into the band at 144, the band steady, the + // breakdown a little slower, accelerating back into the final; the ending free again. + const intro = A_TEMPO.filter(([x]) => x < 8.6); + const tempo: [number, number][] = [ + ...intro.map(([x, v]) => [x, v] as [number, number]), [8.5, 100], [8.67, 144], + [71, 144], [71.9, 120], [72, 132], [75, 132], [76.9, 144], [77, 144], + [103, 126], [104, 116], [105, 100], [105.7, 82], [106, 70], + ]; + const holds: [number, number][] = [[72, 0.5], [103, 0.45], [106, 0.3]]; + return { parts, sections, tempo, holds, bars }; +} diff --git a/probes/lib/fur-elise-cinematic-timeline.ts b/probes/lib/fur-elise-cinematic-timeline.ts new file mode 100644 index 0000000..0bef0e0 --- /dev/null +++ b/probes/lib/fur-elise-cinematic-timeline.ts @@ -0,0 +1,3836 @@ +// Generated by probes/lib/fur-elise-timeline-gen.mts --cinematic from probes/fur-elise-cinematic.ts: do not edit, make it again. +// Für Elise (the cinematic arrangement) as the soundtrack plays it (the whole piece as one clip, from 0). Seconds from its start; a frame is 42 ms +// (Fastest). The picture runs ahead of a long clip's sound by about 95 ms (the visualizer probe, 2026-11-09): the +// program shifts the picture, not these numbers. + +/** Seconds from the first note to the last let go (the held A's ring and the hall's tail come after). */ +export const SECONDS = 142.067; +/** The parts, by the number NOTES gives them. */ +export const PARTS = ["right","left","violins","violas","ostinato","celli","basses","horns","trombones","tuba","braam","sub","drone","pad","pulse","supersaw","taiko","kick","timpani","toms","snare","cymbals","impacts","risers"] as const; +/** + * Each part's role, by the same number: "lead" (the piano's right hand, the theme), "accomp" (its left hand), + * "strings", "brass", "bass", "synth", "pad", "drum-low" (taiko, kick, timpani), "drum-high" (tenor drums, snare), + * "cymbal" (crash, suspended cymbal, gong), "impact" (impacts and the sub drop), "riser" (risers, crashes reversed). + */ +export const ROLES = ["lead","accomp","strings","strings","strings","strings","bass","brass","brass","brass","brass","bass","pad","pad","synth","synth","drum-low","drum-low","drum-low","drum-high","drum-high","cymbal","impact","riser"] as const; +/** The sections, in order: the bar each begins on (BARS' numbering), and where, in seconds and frames. */ +export const SECTIONS: readonly { readonly name: string; readonly bar: number; readonly at: number; readonly frame: number }[] = [{"name":"intro","bar":0,"at":0,"frame":0},{"name":"band","bar":9,"at":12.699,"frame":302},{"name":"lift","bar":38,"at":48.949,"frame":1165},{"name":"storm","bar":54,"at":68.949,"frame":1642},{"name":"breakdown","bar":72,"at":92.072,"frame":2192},{"name":"final","bar":77,"at":98.768,"frame":2352},{"name":"ending","bar":103,"at":133.936,"frame":3189}]; +/** Seconds each bar begins: [0] the pickup's start, [k] bar k's. */ +export const BARS: readonly number[] = [0,0.527,2.015,3.478,4.966,6.54,8.04,9.54,11.15,12.699,13.949,15.199,16.449,17.699,18.949,20.199,21.449,22.699,23.949,25.199,26.449,27.699,28.949,30.199,31.449,32.699,33.949,35.199,36.449,37.699,38.949,40.199,41.449,42.699,43.949,45.199,46.449,47.699,48.949,50.199,51.449,52.699,53.949,55.199,56.449,57.699,58.949,60.199,61.449,62.699,63.949,65.199,66.449,67.699,68.949,70.199,71.449,72.699,73.949,75.199,76.449,77.699,78.949,80.199,81.449,82.699,83.949,85.199,86.449,87.699,88.949,90.199,92.072,93.436,94.799,96.163,97.495,98.768,100.021,101.28,102.545,103.817,105.094,106.378,107.669,108.965,110.269,111.578,112.895,114.218,115.548,116.885,118.228,119.579,120.937,122.302,123.674,125.053,126.44,127.834,129.235,130.645,132.061,133.936,135.425,137.094,139.495,142.067,144.638,147.21]; +/** The piano's sustain pedal: [down, up] in seconds. */ +export const PEDAL: readonly (readonly [number, number])[] = [ + [2.015,3.478], + [3.538,4.966], + [5.026,6.54], + [8.04,9.54], + [9.6,11.15], + [11.21,12.282], + [13.949,15.199], + [15.259,16.449], + [16.509,17.699], + [18.949,20.199], + [20.259,21.449], + [21.509,22.282], + [23.949,25.199], + [25.259,26.449], + [26.509,27.699], + [28.949,30.199], + [30.259,31.449], + [31.509,32.699], + [32.759,33.949], + [34.009,35.199], + [35.259,36.449], + [36.509,38.324], + [41.449,42.699], + [42.759,43.949], + [44.009,45.199], + [46.449,47.699], + [47.759,48.949], + [49.009,50.199], + [50.259,51.449], + [51.509,52.699], + [92.072,96.163], + [100.021,101.28], + [101.34,102.545], + [102.605,103.817], + [105.094,106.378], + [106.438,107.669], + [107.729,108.532], + [110.269,111.578], + [111.638,112.895], + [112.955,114.218], + [115.548,116.885], + [116.945,118.228], + [118.288,119.579], + [119.639,120.937], + [120.997,122.302], + [122.362,123.674], + [123.734,125.745], + [129.235,130.645], + [130.705,132.061], + [132.121,133.936], + [135.425,137.094], + [137.154,139.495], + [139.555,147.21], +]; +/** What NOTES' columns hold. */ +export const AT = 0, END = 1, PITCH = 2, VELOCITY = 3, PART = 4, VOICE = 5, BAR = 6, BEAT = 7, FRAME = 8; +/** + * Every note in the order struck: [at, end, pitch, velocity, part, voice, bar, beat, frame] — seconds struck and let go + * (the key; the pedal may hold it on), the key (60 is C4; for a drum, cymbal, impact or riser the kit's key, not a + * pitch), 1 … 127, PARTS' number, its place in its chord (0 the lowest), the bar, the beat in it (eighths from 0), the + * frame it is struck on. + */ +export const NOTES: readonly (readonly number[])[] = [ + [0,0.262,76,48,0,0,0,0,0], + [0.263,0.519,75,41,0,0,0,0.5,6], + [0.518,0.769,76,47,0,0,1,0,12], + [0.765,1.018,75,39,0,0,1,0.5,18], + [1.019,1.266,76,52,0,0,1,1,24], + [1.266,1.513,71,37,0,0,1,1.5,30], + [1.508,1.76,74,48,0,0,1,2,36], + [1.76,2.007,72,41,0,0,1,2.5,42], + [2.01,2.497,69,42,0,0,2,0,48], + [2.011,2.26,45,44,1,0,2,0,48], + [2.259,2.505,52,42,1,0,2,0.5,54], + [2.505,2.749,57,45,1,0,2,1,60], + [2.745,2.985,60,34,0,0,2,1.5,65], + [2.983,3.228,64,36,0,0,2,2,71], + [3.227,3.47,69,40,0,0,2,2.5,77], + [3.475,3.958,71,48,0,0,3,0,83], + [3.476,12.699,33,39,11,0,3,0,83], + [3.484,3.721,40,35,1,0,3,0,83], + [3.717,3.966,52,43,1,0,3,0.5,88], + [3.969,4.213,56,46,1,0,3,1,95], + [4.211,4.454,64,34,0,0,3,1.5,100], + [4.453,4.705,68,39,0,0,3,2,106], + [4.698,4.958,71,43,0,0,3,2.5,112], + [4.956,5.476,72,52,0,0,4,0,118], + [4.966,5.223,45,43,1,0,4,0,118], + [5.224,5.484,52,43,1,0,4,0.5,124], + [5.487,5.751,57,37,1,0,4,1,131], + [5.748,6.014,64,30,0,0,4,1.5,137], + [6.013,6.278,76,43,0,0,4,2,143], + [6.275,6.532,75,43,0,0,4,2.5,149], + [6.533,6.782,76,48,0,0,5,0,156], + [6.543,8.04,52,37,12,0,5,0,156], + [6.547,8.04,59,35,12,1,5,0,156], + [6.782,7.032,75,46,0,0,5,0.5,161], + [7.032,7.282,76,43,0,0,5,1,167], + [7.276,7.532,71,36,0,0,5,1.5,173], + [7.536,7.782,74,45,0,0,5,2,179], + [7.782,8.032,72,39,0,0,5,2.5,185], + [8.027,8.532,69,45,0,0,6,0,191], + [8.038,9.54,45,41,12,0,6,0,191], + [8.04,8.29,45,42,1,0,6,0,191], + [8.044,9.54,47,91,23,0,6,0,192], + [8.045,9.54,60,40,12,2,6,0,192], + [8.046,9.54,52,42,12,1,6,0,192], + [8.29,8.54,52,42,1,0,6,0.5,197], + [8.542,8.79,57,46,1,0,6,1,203], + [8.789,9.032,60,30,0,0,6,1.5,209], + [9.029,9.282,64,39,0,0,6,2,215], + [9.283,9.532,69,38,0,0,6,2.5,221], + [9.533,10.044,71,49,0,0,7,0,227], + [9.538,11.15,52,54,12,0,7,0,227], + [9.54,11.15,56,47,12,1,7,0,227], + [9.542,11.15,59,49,12,2,7,0,227], + [9.544,9.793,40,40,1,0,7,0,227], + [9.793,10.052,52,41,1,0,7,0.5,233], + [10.048,10.316,56,41,1,0,7,1,239], + [10.304,10.579,64,36,0,0,7,1.5,245], + [10.583,10.857,72,41,0,0,7,2,252], + [10.853,11.142,71,38,0,0,7,2.5,258], + [11.14,12.274,69,44,0,0,8,0,265], + [11.148,11.44,45,44,1,0,8,0,265], + [11.152,12.699,52,58,12,1,8,0,266], + [11.153,12.699,45,65,12,0,8,0,266], + [11.154,12.699,60,61,12,2,8,0,266], + [11.445,11.734,52,39,1,0,8,0.5,272], + [11.737,12.032,57,42,1,0,8,1,279], + [12.274,12.482,76,45,0,0,8,2,292], + [12.482,12.691,75,37,0,0,8,2.5,297], + [12.69,12.899,76,91,0,0,9,0,302], + [12.693,13.949,28,70,11,0,9,0,302], + [12.694,13.949,40,108,10,2,9,0,302], + [12.696,13.949,28,93,8,0,9,0,302], + [12.697,13.949,28,104,10,0,9,0,302], + [12.698,13.949,35,101,8,1,9,0,302], + [12.698,13.949,35,112,10,1,9,0,302], + [12.699,13.949,36,117,22,0,9,0,302], + [12.699,13.115,36,100,16,0,9,0,302], + [12.7,13.949,40,97,8,2,9,0,302], + [12.7,12.907,52,94,4,0,9,0,302], + [12.7,13.949,49,100,21,0,9,0,302], + [12.703,13.949,28,97,9,0,9,0,302], + [12.899,13.107,75,81,0,0,9,0.5,307], + [12.913,13.115,52,59,4,0,9,0.5,307], + [13.109,13.316,76,88,0,0,9,1,312], + [13.109,13.324,59,75,4,0,9,1,312], + [13.315,13.524,71,86,0,0,9,1.5,317], + [13.317,13.532,38,56,16,0,9,1.5,317], + [13.323,13.532,52,92,4,0,9,1.5,317], + [13.521,13.732,74,88,0,0,9,2,322], + [13.538,13.74,59,61,4,0,9,2,322], + [13.737,13.941,72,87,0,0,9,2.5,327], + [13.738,13.949,64,74,4,0,9,2.5,327], + [13.939,14.357,69,85,0,0,10,0,332], + [13.944,14.157,45,68,1,0,10,0,332], + [13.945,15.199,33,74,11,0,10,0,332], + [13.947,14.157,38,79,16,0,10,0,332], + [13.949,14.157,57,92,4,0,10,0,332], + [14.153,14.365,57,62,4,0,10,0.5,337], + [14.156,14.365,52,67,1,0,10,0.5,337], + [14.368,14.574,57,68,1,0,10,1,342], + [14.37,14.574,64,65,4,0,10,1,342], + [14.564,14.774,60,79,0,0,10,1.5,347], + [14.574,14.782,57,82,4,0,10,1.5,347], + [14.577,14.782,38,75,16,0,10,1.5,347], + [14.776,14.982,64,83,0,0,10,2,352], + [14.78,14.99,64,64,4,0,10,2,352], + [14.985,15.191,69,86,0,0,10,2.5,357], + [14.989,15.199,69,69,4,0,10,2.5,357], + [15.193,15.607,71,93,0,0,11,0,362], + [15.195,15.615,36,93,16,0,11,0,362], + [15.198,15.407,52,96,4,0,11,0,362], + [15.2,15.407,40,66,1,0,11,0,362], + [15.204,16.449,28,76,11,0,11,0,362], + [15.406,15.615,52,68,1,0,11,0.5,367], + [15.408,15.615,52,59,4,0,11,0.5,367], + [15.614,15.824,59,65,4,0,11,1,372], + [15.621,15.824,56,71,1,0,11,1,372], + [15.821,16.024,64,78,0,0,11,1.5,377], + [15.827,16.032,38,61,16,0,11,1.5,377], + [15.827,16.032,52,85,4,0,11,1.5,377], + [16.017,16.232,68,80,0,0,11,2,381], + [16.03,16.24,59,62,4,0,11,2,382], + [16.233,16.441,71,84,0,0,11,2.5,386], + [16.242,16.449,64,73,4,0,11,2.5,387], + [16.44,16.857,72,98,0,0,12,0,391], + [16.442,16.657,57,90,4,0,12,0,391], + [16.447,17.699,33,78,11,0,12,0,392], + [16.447,16.657,38,81,16,0,12,0,392], + [16.452,16.657,45,65,1,0,12,0,392], + [16.651,16.865,52,64,1,0,12,0.5,396], + [16.654,16.865,57,57,4,0,12,0.5,397], + [16.865,17.074,57,68,1,0,12,1,402], + [16.865,17.074,64,72,4,0,12,1,402], + [17.065,17.274,64,83,0,0,12,1.5,406], + [17.072,17.282,57,80,4,0,12,1.5,406], + [17.077,17.282,38,71,16,0,12,1.5,407], + [17.275,17.482,76,86,0,0,12,2,411], + [17.286,17.49,64,63,4,0,12,2,412], + [17.485,17.691,75,81,0,0,12,2.5,416], + [17.493,17.699,69,67,4,0,12,2.5,416], + [17.687,17.899,76,91,0,0,13,0,421], + [17.694,18.949,28,75,11,0,13,0,421], + [17.696,17.907,52,93,4,0,13,0,421], + [17.699,18.115,36,95,16,0,13,0,421], + [17.9,18.107,75,88,0,0,13,0.5,426], + [17.91,18.115,52,55,4,0,13,0.5,426], + [18.105,18.316,76,88,0,0,13,1,431], + [18.118,18.324,59,62,4,0,13,1,431], + [18.309,18.524,71,86,0,0,13,1.5,436], + [18.317,18.532,38,59,16,0,13,1.5,436], + [18.321,18.532,52,84,4,0,13,1.5,436], + [18.518,18.732,74,84,0,0,13,2,441], + [18.532,18.74,59,66,4,0,13,2,441], + [18.731,18.941,72,86,0,0,13,2.5,446], + [18.743,18.949,64,67,4,0,13,2.5,446], + [18.944,19.357,69,87,0,0,14,0,451], + [18.944,19.157,57,89,4,0,14,0,451], + [18.947,19.157,38,84,16,0,14,0,451], + [18.949,19.157,45,63,1,0,14,0,451], + [18.949,20.199,33,70,11,0,14,0,451], + [19.159,19.365,52,65,1,0,14,0.5,456], + [19.159,19.365,57,57,4,0,14,0.5,456], + [19.367,19.574,64,70,4,0,14,1,461], + [19.37,19.574,57,70,1,0,14,1,461], + [19.567,19.782,38,70,16,0,14,1.5,466], + [19.569,19.774,60,75,0,0,14,1.5,466], + [19.572,19.782,57,91,4,0,14,1.5,466], + [19.77,19.982,64,81,0,0,14,2,471], + [19.784,19.99,64,64,4,0,14,2,471], + [19.98,20.191,69,82,0,0,14,2.5,476], + [19.987,20.199,69,75,4,0,14,2.5,476], + [20.188,20.607,71,87,0,0,15,0,481], + [20.194,21.449,41,90,23,0,15,0,481], + [20.198,21.449,28,71,11,0,15,0,481], + [20.2,20.407,52,94,4,0,15,0,481], + [20.2,20.615,36,92,16,0,15,0,481], + [20.201,20.407,40,68,1,0,15,0,481], + [20.406,20.615,52,59,4,0,15,0.5,486], + [20.406,20.615,52,70,1,0,15,0.5,486], + [20.617,20.824,59,63,4,0,15,1,491], + [20.619,20.824,56,61,1,0,15,1,491], + [20.818,21.024,64,75,0,0,15,1.5,496], + [20.822,21.032,38,62,16,0,15,1.5,496], + [20.826,21.032,52,85,4,0,15,1.5,496], + [21.024,21.232,72,90,0,0,15,2,501], + [21.028,21.24,59,60,4,0,15,2,501], + [21.233,21.441,71,84,0,0,15,2.5,506], + [21.246,21.449,64,72,4,0,15,2.5,506], + [21.442,22.274,69,92,0,0,16,0,511], + [21.442,21.657,45,71,1,0,16,0,511], + [21.448,22.699,33,74,11,0,16,0,511], + [21.45,21.657,38,80,16,0,16,0,511], + [21.455,21.657,57,92,4,0,16,0,511], + [21.652,21.865,57,58,4,0,16,0.5,516], + [21.657,21.865,52,69,1,0,16,0.5,516], + [21.862,22.074,64,65,4,0,16,1,521], + [21.865,22.074,57,73,1,0,16,1,521], + [22.074,22.282,38,74,16,0,16,1.5,526], + [22.075,22.282,57,87,4,0,16,1.5,526], + [22.277,22.482,76,93,0,0,16,2,530], + [22.284,22.49,64,58,4,0,16,2,531], + [22.475,22.691,75,84,0,0,16,2.5,535], + [22.488,22.699,69,67,4,0,16,2.5,535], + [22.69,22.899,76,90,0,0,17,0,540], + [22.691,23.949,28,99,8,0,17,0,540], + [22.693,22.907,40,95,5,0,17,0,540], + [22.694,23.949,71,78,2,2,17,0,540], + [22.695,23.949,52,78,13,0,17,0,540], + [22.698,23.949,40,108,10,2,17,0,540], + [22.698,23.115,28,100,6,0,17,0,540], + [22.698,23.949,59,79,13,2,17,0,540], + [22.698,23.949,35,114,10,1,17,0,540], + [22.699,22.907,52,103,4,0,17,0,540], + [22.699,23.949,56,80,13,1,17,0,540], + [22.699,23.949,40,104,8,2,17,0,540], + [22.699,23.949,64,77,2,0,17,0,540], + [22.699,23.949,28,87,11,0,17,0,540], + [22.699,23.949,28,98,9,0,17,0,540], + [22.699,23.949,40,100,17,0,17,0,540], + [22.701,23.949,28,111,10,0,17,0,540], + [22.701,23.115,36,107,16,0,17,0,540], + [22.702,23.949,35,98,8,1,17,0,541], + [22.704,23.949,49,108,21,0,17,0,541], + [22.704,23.949,68,75,2,1,17,0,541], + [22.9,23.107,75,90,0,0,17,0.5,545], + [22.905,23.115,40,68,5,0,17,0.5,545], + [22.91,23.115,52,67,4,0,17,0.5,545], + [23.108,23.316,76,95,0,0,17,1,550], + [23.114,23.324,59,77,4,0,17,1,550], + [23.114,23.532,28,71,6,0,17,1,550], + [23.119,23.324,47,71,5,0,17,1,550], + [23.316,23.524,71,87,0,0,17,1.5,555], + [23.322,23.532,40,93,5,0,17,1.5,555], + [23.328,23.532,52,95,4,0,17,1.5,555], + [23.329,23.532,38,74,16,0,17,1.5,555], + [23.527,23.732,74,85,0,0,17,2,560], + [23.529,23.949,28,83,6,0,17,2,560], + [23.533,23.949,40,82,16,0,17,2,560], + [23.534,23.74,47,65,5,0,17,2,560], + [23.539,23.74,59,73,4,0,17,2,560], + [23.733,23.941,72,87,0,0,17,2.5,565], + [23.737,23.949,64,82,4,0,17,2.5,565], + [23.741,23.949,52,75,5,0,17,2.5,565], + [23.939,24.357,69,88,0,0,18,0,570], + [23.945,25.199,57,76,13,0,18,0,570], + [23.948,24.365,33,96,6,0,18,0,570], + [23.948,25.199,33,87,11,0,18,0,570], + [23.948,24.157,45,72,1,0,18,0,570], + [23.949,25.199,60,76,13,1,18,0,570], + [23.949,24.157,57,97,4,0,18,0,570], + [23.949,25.199,72,81,2,1,18,0,570], + [23.95,24.157,38,95,16,0,18,0,570], + [23.951,25.199,64,77,13,2,18,0,570], + [23.951,24.157,45,100,5,0,18,0,570], + [23.952,25.199,40,93,17,0,18,0,570], + [23.952,25.199,69,79,2,0,18,0,570], + [23.956,25.199,76,74,2,2,18,0,570], + [24.16,24.365,52,71,1,0,18,0.5,575], + [24.16,24.365,45,71,5,0,18,0.5,575], + [24.162,24.365,57,66,4,0,18,0.5,575], + [24.364,24.574,52,74,5,0,18,1,580], + [24.365,24.574,57,67,1,0,18,1,580], + [24.365,24.782,33,73,6,0,18,1,580], + [24.367,24.574,40,74,16,0,18,1,580], + [24.368,24.574,64,79,4,0,18,1,580], + [24.562,24.774,60,77,0,0,18,1.5,585], + [24.566,24.782,40,66,16,0,18,1.5,585], + [24.575,24.782,45,93,5,0,18,1.5,585], + [24.575,24.782,57,92,4,0,18,1.5,585], + [24.776,24.982,64,83,0,0,18,2,590], + [24.781,25.199,33,84,6,0,18,2,590], + [24.781,25.199,38,99,16,0,18,2,590], + [24.783,24.99,52,67,5,0,18,2,590], + [24.785,24.99,64,71,4,0,18,2,590], + [24.983,25.191,69,85,0,0,18,2.5,595], + [24.985,25.199,57,73,5,0,18,2.5,595], + [24.987,25.199,69,78,4,0,18,2.5,595], + [25.193,25.607,71,87,0,0,19,0,600], + [25.196,26.449,56,71,13,1,19,0,600], + [25.197,25.407,52,102,4,0,19,0,600], + [25.197,25.407,40,100,5,0,19,0,600], + [25.198,26.449,40,93,17,0,19,0,600], + [25.199,26.449,64,76,2,0,19,0,600], + [25.199,26.449,71,77,2,2,19,0,600], + [25.2,25.615,28,96,6,0,19,0,600], + [25.2,25.615,36,111,16,0,19,0,600], + [25.201,26.449,52,77,13,0,19,0,600], + [25.201,26.449,59,78,13,2,19,0,600], + [25.203,26.449,68,75,2,1,19,0,600], + [25.204,25.407,40,72,1,0,19,0,600], + [25.205,26.449,28,94,11,0,19,0,600], + [25.403,25.615,52,68,4,0,19,0.5,605], + [25.404,25.615,52,63,1,0,19,0.5,605], + [25.409,25.615,40,66,5,0,19,0.5,605], + [25.612,25.824,47,80,5,0,19,1,610], + [25.613,25.824,59,77,4,0,19,1,610], + [25.616,25.824,56,67,1,0,19,1,610], + [25.618,26.032,28,71,6,0,19,1,610], + [25.816,26.024,64,74,0,0,19,1.5,615], + [25.824,26.032,38,73,16,0,19,1.5,615], + [25.825,26.032,52,98,4,0,19,1.5,615], + [25.827,26.032,40,92,5,0,19,1.5,615], + [26.026,26.232,68,81,0,0,19,2,620], + [26.03,26.24,59,77,4,0,19,2,620], + [26.03,26.449,40,81,16,0,19,2,620], + [26.031,26.449,28,82,6,0,19,2,620], + [26.033,26.24,47,74,5,0,19,2,620], + [26.232,26.441,71,83,0,0,19,2.5,625], + [26.242,26.449,64,82,4,0,19,2.5,625], + [26.243,26.449,52,77,5,0,19,2.5,625], + [26.443,27.699,33,90,11,0,20,0,630], + [26.444,26.857,72,99,0,0,20,0,630], + [26.447,27.699,64,75,13,2,20,0,630], + [26.447,26.657,45,65,1,0,20,0,630], + [26.448,26.865,33,93,6,0,20,0,630], + [26.448,27.699,76,81,2,2,20,0,630], + [26.451,27.699,57,79,13,0,20,0,630], + [26.451,27.699,60,81,13,1,20,0,630], + [26.452,27.699,40,97,17,0,20,0,630], + [26.452,27.699,69,83,2,0,20,0,630], + [26.452,26.657,38,92,16,0,20,0,630], + [26.452,26.657,45,97,5,0,20,0,630], + [26.453,26.657,57,101,4,0,20,0,630], + [26.453,27.699,72,77,2,1,20,0,630], + [26.654,26.865,57,69,4,0,20,0.5,635], + [26.655,26.865,45,61,5,0,20,0.5,635], + [26.657,26.865,52,66,1,0,20,0.5,635], + [26.862,27.074,57,69,1,0,20,1,640], + [26.863,27.074,52,79,5,0,20,1,640], + [26.864,27.074,64,76,4,0,20,1,640], + [26.865,27.282,33,74,6,0,20,1,640], + [26.866,27.074,40,70,16,0,20,1,640], + [27.069,27.274,64,81,0,0,20,1.5,644], + [27.071,27.282,40,60,16,0,20,1.5,645], + [27.072,27.282,57,96,4,0,20,1.5,645], + [27.076,27.282,45,89,5,0,20,1.5,645], + [27.27,27.482,76,90,0,0,20,2,649], + [27.277,27.699,38,98,16,0,20,2,649], + [27.28,27.699,33,84,6,0,20,2,650], + [27.284,27.49,64,71,4,0,20,2,650], + [27.285,27.49,52,66,5,0,20,2,650], + [27.485,27.691,75,85,0,0,20,2.5,654], + [27.488,27.699,57,76,5,0,20,2.5,654], + [27.491,27.699,69,78,4,0,20,2.5,655], + [27.69,27.899,76,98,0,0,21,0,659], + [27.695,28.949,52,80,13,0,21,0,659], + [27.696,28.949,71,68,2,2,21,0,659], + [27.697,28.949,40,97,17,0,21,0,659], + [27.698,28.949,56,80,13,1,21,0,659], + [27.699,27.907,40,94,5,0,21,0,659], + [27.699,28.115,36,107,16,0,21,0,660], + [27.699,28.949,28,85,11,0,21,0,660], + [27.7,28.949,64,77,2,0,21,0,660], + [27.702,28.949,59,76,13,2,21,0,660], + [27.703,28.949,68,77,2,1,21,0,660], + [27.703,28.115,28,94,6,0,21,0,660], + [27.704,27.907,52,106,4,0,21,0,660], + [27.902,28.107,75,85,0,0,21,0.5,664], + [27.907,28.115,52,66,4,0,21,0.5,664], + [27.912,28.115,40,70,5,0,21,0.5,665], + [28.11,28.316,76,89,0,0,21,1,669], + [28.112,28.532,28,75,6,0,21,1,669], + [28.114,28.324,47,78,5,0,21,1,669], + [28.116,28.324,59,72,4,0,21,1,669], + [28.313,28.524,71,85,0,0,21,1.5,674], + [28.324,28.532,38,75,16,0,21,1.5,674], + [28.324,28.532,40,96,5,0,21,1.5,674], + [28.326,28.532,52,94,4,0,21,1.5,674], + [28.525,28.949,28,87,6,0,21,2,679], + [28.527,28.732,74,91,0,0,21,2,679], + [28.531,28.949,40,86,16,0,21,2,679], + [28.534,28.74,59,71,4,0,21,2,679], + [28.535,28.74,47,65,5,0,21,2,679], + [28.735,28.941,72,87,0,0,21,2.5,684], + [28.735,28.949,52,76,5,0,21,2.5,684], + [28.745,28.949,64,79,4,0,21,2.5,684], + [28.943,29.157,57,98,4,0,22,0,689], + [28.943,29.357,69,93,0,0,22,0,689], + [28.943,30.199,57,78,13,0,22,0,689], + [28.943,29.157,38,97,16,0,22,0,689], + [28.944,29.157,45,63,1,0,22,0,689], + [28.947,30.199,76,84,2,2,22,0,689], + [28.948,30.199,33,93,11,0,22,0,689], + [28.948,30.199,64,79,13,2,22,0,689], + [28.949,30.199,60,79,13,1,22,0,689], + [28.95,30.199,69,76,2,0,22,0,689], + [28.95,30.199,40,99,17,0,22,0,689], + [28.951,29.365,33,98,6,0,22,0,689], + [28.952,29.157,45,100,5,0,22,0,689], + [28.956,30.199,72,77,2,1,22,0,689], + [29.153,29.365,52,69,1,0,22,0.5,694], + [29.155,29.365,57,70,4,0,22,0.5,694], + [29.156,29.365,45,61,5,0,22,0.5,694], + [29.361,29.574,52,69,5,0,22,1,699], + [29.363,29.574,57,70,1,0,22,1,699], + [29.364,29.574,64,79,4,0,22,1,699], + [29.365,29.782,33,76,6,0,22,1,699], + [29.367,29.574,40,69,16,0,22,1,699], + [29.564,29.774,60,71,0,0,22,1.5,704], + [29.57,29.782,40,62,16,0,22,1.5,704], + [29.573,29.782,45,90,5,0,22,1.5,704], + [29.58,29.782,57,91,4,0,22,1.5,704], + [29.777,29.982,64,85,0,0,22,2,709], + [29.783,29.99,52,70,5,0,22,2,709], + [29.784,30.199,38,98,16,0,22,2,709], + [29.784,29.99,64,74,4,0,22,2,709], + [29.786,30.199,33,83,6,0,22,2,709], + [29.984,30.191,69,84,0,0,22,2.5,714], + [29.985,30.199,69,82,4,0,22,2.5,714], + [29.989,30.199,57,77,5,0,22,2.5,714], + [30.193,30.607,71,89,0,0,23,0,719], + [30.193,30.407,40,71,1,0,23,0,719], + [30.194,30.615,28,100,6,0,23,0,719], + [30.194,31.449,40,92,17,0,23,0,719], + [30.194,30.615,36,110,16,0,23,0,719], + [30.195,31.449,71,78,2,2,23,0,719], + [30.196,31.449,56,79,13,1,23,0,719], + [30.197,31.449,64,77,2,0,23,0,719], + [30.199,31.449,52,79,13,0,23,0,719], + [30.199,30.407,52,96,4,0,23,0,719], + [30.199,31.449,68,76,2,1,23,0,719], + [30.199,30.407,40,96,5,0,23,0,719], + [30.2,31.449,28,89,11,0,23,0,719], + [30.201,31.449,59,78,13,2,23,0,719], + [30.405,30.615,52,65,1,0,23,0.5,724], + [30.406,30.615,40,73,5,0,23,0.5,724], + [30.412,30.615,52,69,4,0,23,0.5,724], + [30.611,30.824,56,65,1,0,23,1,729], + [30.613,30.824,59,80,4,0,23,1,729], + [30.613,30.824,47,74,5,0,23,1,729], + [30.615,31.032,28,69,6,0,23,1,729], + [30.817,31.024,64,74,0,0,23,1.5,734], + [30.821,31.032,52,100,4,0,23,1.5,734], + [30.823,31.032,38,76,16,0,23,1.5,734], + [30.828,31.032,40,94,5,0,23,1.5,734], + [31.027,31.232,72,79,0,0,23,2,739], + [31.032,31.24,59,71,4,0,23,2,739], + [31.034,31.24,47,69,5,0,23,2,739], + [31.035,31.449,40,83,16,0,23,2,739], + [31.037,31.449,28,82,6,0,23,2,739], + [31.237,31.441,71,85,0,0,23,2.5,744], + [31.239,31.449,52,82,5,0,23,2.5,744], + [31.239,31.449,64,75,4,0,23,2.5,744], + [31.437,31.857,69,91,0,0,24,0,748], + [31.444,32.699,72,76,2,1,24,0,749], + [31.445,31.657,57,105,4,0,24,0,749], + [31.446,32.699,57,81,13,0,24,0,749], + [31.446,31.657,38,91,16,0,24,0,749], + [31.446,32.699,64,81,13,2,24,0,749], + [31.447,31.657,45,68,1,0,24,0,749], + [31.448,32.699,40,98,17,0,24,0,749], + [31.448,31.657,40,84,19,0,24,0,749], + [31.449,31.865,33,95,6,0,24,0,749], + [31.45,32.699,33,83,11,0,24,0,749], + [31.45,32.699,69,72,2,0,24,0,749], + [31.45,32.699,60,82,13,1,24,0,749], + [31.451,32.699,76,75,2,2,24,0,749], + [31.454,31.657,45,97,5,0,24,0,749], + [31.653,31.865,57,69,4,0,24,0.5,754], + [31.654,31.865,45,67,5,0,24,0.5,754], + [31.658,31.865,52,68,1,0,24,0.5,754], + [31.659,31.865,40,83,19,0,24,0.5,754], + [31.863,32.282,33,70,6,0,24,1,759], + [31.863,32.074,57,63,1,0,24,1,759], + [31.867,32.074,40,66,16,0,24,1,759], + [31.867,32.074,64,77,4,0,24,1,759], + [31.867,32.074,52,73,5,0,24,1,759], + [31.868,32.074,42,88,19,0,24,1,759], + [32.067,32.274,71,78,0,0,24,1.5,763], + [32.07,32.282,40,61,16,0,24,1.5,764], + [32.071,32.282,57,100,4,0,24,1.5,764], + [32.073,32.282,45,98,5,0,24,1.5,764], + [32.078,32.282,40,94,19,0,24,1.5,764], + [32.276,32.482,72,83,0,0,24,2,768], + [32.278,32.49,52,67,5,0,24,2,769], + [32.279,32.699,38,100,16,0,24,2,769], + [32.28,32.699,33,82,6,0,24,2,769], + [32.28,32.49,42,103,19,0,24,2,769], + [32.284,32.49,64,73,4,0,24,2,769], + [32.481,32.691,74,87,0,0,24,2.5,773], + [32.488,32.699,57,74,5,0,24,2.5,774], + [32.489,32.699,42,111,19,0,24,2.5,774], + [32.493,32.699,69,78,4,0,24,2.5,774], + [32.69,33.316,76,93,0,0,25,0,778], + [32.694,33.949,55,66,13,2,25,0,778], + [32.698,32.907,48,70,1,0,25,0,779], + [32.698,33.949,48,66,13,0,25,0,779], + [32.698,32.907,48,87,4,0,25,0,779], + [32.699,33.949,52,67,13,1,25,0,779], + [32.699,33.115,36,94,16,0,25,0,779], + [32.699,33.949,24,95,11,0,25,0,779], + [32.7,33.949,51,67,21,0,25,0,779], + [32.701,32.907,36,82,5,0,25,0,779], + [32.901,33.115,48,54,4,0,25,0.5,783], + [32.907,33.115,55,66,1,0,25,0.5,784], + [32.91,33.115,36,51,5,0,25,0.5,784], + [33.115,33.324,60,68,1,0,25,1,788], + [33.116,33.324,55,71,4,0,25,1,788], + [33.118,33.324,43,59,5,0,25,1,789], + [33.309,33.524,67,78,0,0,25,1.5,793], + [33.322,33.532,48,83,4,0,25,1.5,793], + [33.322,33.532,36,81,5,0,25,1.5,793], + [33.52,33.732,77,93,0,0,25,2,798], + [33.532,33.74,55,56,4,0,25,2,798], + [33.535,33.74,43,57,5,0,25,2,798], + [33.727,33.941,76,82,0,0,25,2.5,803], + [33.735,33.949,60,70,4,0,25,2.5,803], + [33.739,33.949,48,65,5,0,25,2.5,803], + [33.935,34.566,74,98,0,0,26,0,808], + [33.947,34.157,43,68,1,0,26,0,808], + [33.948,35.199,62,71,13,2,26,0,808], + [33.948,34.157,43,83,5,0,26,0,808], + [33.95,35.199,31,87,11,0,26,0,808], + [33.952,35.199,59,65,13,1,26,0,808], + [33.952,34.157,55,88,4,0,26,0,808], + [33.953,35.199,55,66,13,0,26,0,808], + [34.153,34.365,43,57,5,0,26,0.5,813], + [34.155,34.365,55,68,1,0,26,0.5,813], + [34.158,34.365,55,62,4,0,26,0.5,813], + [34.362,34.574,50,69,5,0,26,1,818], + [34.363,34.574,59,70,1,0,26,1,818], + [34.367,34.574,62,65,4,0,26,1,818], + [34.568,34.774,65,79,0,0,26,1.5,823], + [34.572,34.782,43,81,5,0,26,1.5,823], + [34.577,34.782,55,80,4,0,26,1.5,823], + [34.776,34.982,76,91,0,0,26,2,828], + [34.78,34.99,50,58,5,0,26,2,828], + [34.786,34.99,62,59,4,0,26,2,828], + [34.984,35.191,74,91,0,0,26,2.5,833], + [34.989,35.199,67,61,4,0,26,2.5,833], + [34.99,35.199,55,63,5,0,26,2.5,833], + [35.19,35.615,36,92,16,0,27,0,838], + [35.193,35.816,72,97,0,0,27,0,838], + [35.194,36.449,57,67,13,0,27,0,838], + [35.197,35.407,45,69,1,0,27,0,838], + [35.2,36.449,60,69,13,1,27,0,838], + [35.201,36.449,64,63,13,2,27,0,838], + [35.201,36.449,33,90,11,0,27,0,838], + [35.202,35.407,57,89,4,0,27,0,838], + [35.205,35.407,45,79,5,0,27,0,838], + [35.399,35.615,52,68,1,0,27,0.5,843], + [35.402,35.615,57,59,4,0,27,0.5,843], + [35.41,35.615,45,55,5,0,27,0.5,843], + [35.614,35.824,57,70,1,0,27,1,848], + [35.617,35.824,52,63,5,0,27,1,848], + [35.618,35.824,64,59,4,0,27,1,848], + [35.811,36.024,64,77,0,0,27,1.5,853], + [35.824,36.032,45,79,5,0,27,1.5,853], + [35.826,36.032,57,79,4,0,27,1.5,853], + [36.025,36.232,74,85,0,0,27,2,858], + [36.031,36.24,52,58,5,0,27,2,858], + [36.033,36.24,64,57,4,0,27,2,858], + [36.228,36.441,72,90,0,0,27,2.5,863], + [36.239,36.449,69,62,4,0,27,2.5,863], + [36.239,36.449,57,64,5,0,27,2.5,863], + [36.438,36.857,71,90,0,0,28,0,868], + [36.44,37.699,28,88,11,0,28,0,868], + [36.447,37.699,56,68,13,1,28,0,868], + [36.447,36.657,40,66,1,0,28,0,868], + [36.448,36.657,40,86,5,0,28,0,868], + [36.451,37.699,59,70,13,2,28,0,868], + [36.452,36.657,52,88,4,0,28,0,868], + [36.452,37.699,52,66,13,0,28,0,868], + [36.653,36.865,52,57,4,0,28,0.5,873], + [36.658,36.865,40,52,5,0,28,0.5,873], + [36.662,36.865,52,63,1,0,28,0.5,873], + [36.862,37.074,59,64,4,0,28,1,878], + [36.865,37.074,47,59,5,0,28,1,878], + [36.87,37.074,64,64,1,0,28,1,878], + [37.063,37.274,64,84,0,0,28,1.5,882], + [37.07,37.282,52,78,4,0,28,1.5,883], + [37.07,37.282,40,81,5,0,28,1.5,883], + [37.271,37.482,76,86,0,0,28,2,887], + [37.278,37.49,47,57,5,0,28,2,888], + [37.283,37.49,59,52,4,0,28,2,888], + [37.487,37.699,64,65,1,0,28,2.5,893], + [37.489,37.699,64,61,4,0,28,2.5,893], + [37.489,37.699,52,68,5,0,28,2.5,893], + [37.69,38.949,59,66,13,2,29,0,897], + [37.693,38.949,28,82,11,0,29,0,897], + [37.696,38.115,36,94,16,0,29,0,898], + [37.697,38.949,56,65,13,1,29,0,898], + [37.697,38.949,41,83,23,0,29,0,898], + [37.697,38.949,52,68,13,0,29,0,898], + [37.702,37.907,40,88,5,0,29,0,898], + [37.702,37.907,76,62,1,0,29,0,898], + [37.703,37.907,52,83,4,0,29,0,898], + [37.899,38.107,76,93,0,0,29,0.5,902], + [37.904,38.115,52,56,4,0,29,0.5,902], + [37.908,38.115,40,54,5,0,29,0.5,903], + [38.108,38.316,88,83,0,0,29,1,907], + [38.116,38.324,47,62,5,0,29,1,908], + [38.12,38.324,59,61,4,0,29,1,908], + [38.323,38.532,40,78,5,0,29,1.5,912], + [38.326,38.532,52,82,4,0,29,1.5,913], + [38.328,38.532,75,63,1,0,29,1.5,913], + [38.531,38.74,76,66,1,0,29,2,917], + [38.533,38.74,59,54,4,0,29,2,917], + [38.534,38.74,47,53,5,0,29,2,917], + [38.729,38.941,75,81,0,0,29,2.5,922], + [38.734,38.949,52,71,5,0,29,2.5,922], + [38.742,38.949,64,67,4,0,29,2.5,922], + [38.942,39.357,76,88,0,0,30,0,927], + [38.946,40.199,59,66,13,2,30,0,927], + [38.949,39.157,52,83,4,0,30,0,927], + [38.95,40.199,52,69,13,0,30,0,927], + [38.95,40.199,28,87,11,0,30,0,927], + [38.95,39.157,40,76,5,0,30,0,927], + [38.95,40.199,56,68,13,1,30,0,927], + [39.155,39.365,52,50,4,0,30,0.5,932], + [39.158,39.365,40,52,5,0,30,0.5,932], + [39.161,39.365,75,63,1,0,30,0.5,932], + [39.366,39.574,59,67,4,0,30,1,937], + [39.367,39.574,76,58,1,0,30,1,937], + [39.368,39.574,47,57,5,0,30,1,937], + [39.561,39.774,75,83,0,0,30,1.5,942], + [39.574,39.782,40,78,5,0,30,1.5,942], + [39.575,39.782,52,83,4,0,30,1.5,942], + [39.773,39.982,76,90,0,0,30,2,947], + [39.779,39.99,47,56,5,0,30,2,947], + [39.783,39.99,59,53,4,0,30,2,947], + [39.985,40.191,75,87,0,0,30,2.5,952], + [39.989,40.199,52,66,5,0,30,2.5,952], + [39.991,40.199,64,66,4,0,30,2.5,952], + [40.189,40.399,76,87,0,0,31,0,957], + [40.192,41.449,68,75,2,1,31,0,957], + [40.194,41.449,28,112,10,0,31,0,957], + [40.194,41.449,28,99,9,0,31,0,957], + [40.194,41.449,59,74,13,2,31,0,957], + [40.196,41.449,28,98,8,0,31,0,957], + [40.196,41.449,52,81,7,0,31,0,957], + [40.196,41.449,71,73,2,2,31,0,957], + [40.196,41.449,56,79,13,1,31,0,957], + [40.196,41.449,52,77,13,0,31,0,957], + [40.196,41.449,35,108,10,1,31,0,957], + [40.196,40.407,40,98,5,0,31,0,957], + [40.197,41.449,56,77,7,1,31,0,957], + [40.2,40.407,36,125,16,0,31,0,957], + [40.2,41.449,64,78,2,0,31,0,957], + [40.2,41.449,36,100,22,0,31,0,957], + [40.201,41.449,40,105,10,2,31,0,957], + [40.201,41.449,28,89,11,0,31,0,957], + [40.202,41.449,40,106,17,0,31,0,957], + [40.202,41.449,35,102,8,1,31,0,957], + [40.202,41.449,49,104,21,0,31,0,957], + [40.202,41.449,40,103,8,2,31,0,957], + [40.203,40.615,28,98,6,0,31,0,957], + [40.204,40.407,52,105,4,0,31,0,957], + [40.4,40.607,75,82,0,0,31,0.5,962], + [40.4,40.615,40,61,5,0,31,0.5,962], + [40.404,40.615,52,70,4,0,31,0.5,962], + [40.607,40.816,76,93,0,0,31,1,967], + [40.615,40.824,38,85,16,0,31,1,967], + [40.615,41.032,28,70,6,0,31,1,967], + [40.617,40.824,47,77,5,0,31,1,967], + [40.617,40.824,59,75,4,0,31,1,967], + [40.818,41.024,71,89,0,0,31,1.5,972], + [40.822,41.032,52,96,4,0,31,1.5,972], + [40.825,41.032,40,91,16,0,31,1.5,972], + [40.831,41.032,40,92,5,0,31,1.5,972], + [41.021,41.232,74,88,0,0,31,2,977], + [41.03,41.24,36,112,16,0,31,2,977], + [41.032,41.449,28,85,6,0,31,2,977], + [41.032,41.24,47,71,5,0,31,2,977], + [41.037,41.24,59,72,4,0,31,2,977], + [41.229,41.441,72,80,0,0,31,2.5,982], + [41.237,41.449,64,80,4,0,31,2.5,982], + [41.24,41.449,52,75,5,0,31,2.5,982], + [41.438,41.857,69,89,0,0,32,0,987], + [41.445,42.699,76,78,2,2,32,0,987], + [41.448,42.699,40,106,17,0,32,0,987], + [41.448,41.657,38,109,16,0,32,0,987], + [41.449,41.657,57,97,4,0,32,0,987], + [41.449,41.657,45,72,1,0,32,0,987], + [41.449,42.699,57,77,7,0,32,0,987], + [41.45,42.699,69,77,2,0,32,0,987], + [41.45,42.699,60,78,7,1,32,0,987], + [41.451,42.699,64,79,13,2,32,0,987], + [41.451,42.699,60,72,13,1,32,0,987], + [41.451,41.865,33,100,6,0,32,0,987], + [41.452,42.699,33,85,11,0,32,0,987], + [41.453,42.699,72,79,2,1,32,0,987], + [41.453,41.657,45,96,5,0,32,0,987], + [41.454,42.699,57,72,13,0,32,0,987], + [41.655,41.865,57,72,4,0,32,0.5,992], + [41.655,41.865,45,63,5,0,32,0.5,992], + [41.657,41.865,52,64,1,0,32,0.5,992], + [41.659,41.865,40,77,16,0,32,0.5,992], + [41.867,42.074,57,71,1,0,32,1,997], + [41.868,42.074,42,85,16,0,32,1,997], + [41.869,42.074,64,80,4,0,32,1,997], + [41.87,42.282,33,75,6,0,32,1,997], + [41.871,42.074,52,78,5,0,32,1,997], + [42.063,42.274,60,80,0,0,32,1.5,1002], + [42.071,42.282,36,119,16,0,32,1.5,1002], + [42.078,42.282,57,96,4,0,32,1.5,1002], + [42.078,42.282,45,94,5,0,32,1.5,1002], + [42.275,42.482,64,76,0,0,32,2,1007], + [42.276,42.49,64,71,4,0,32,2,1007], + [42.279,42.699,33,80,6,0,32,2,1007], + [42.28,42.49,40,82,16,0,32,2,1007], + [42.285,42.49,52,69,5,0,32,2,1007], + [42.481,42.691,69,88,0,0,32,2.5,1011], + [42.488,42.699,42,93,16,0,32,2.5,1012], + [42.489,42.699,69,82,4,0,32,2.5,1012], + [42.494,42.699,57,81,5,0,32,2.5,1012], + [42.693,43.949,68,77,2,1,33,0,1016], + [42.695,42.907,52,100,4,0,33,0,1017], + [42.695,43.949,59,79,13,2,33,0,1017], + [42.695,42.907,40,71,1,0,33,0,1017], + [42.696,43.107,71,89,0,0,33,0,1017], + [42.696,42.907,36,120,16,0,33,0,1017], + [42.697,43.949,56,72,7,1,33,0,1017], + [42.697,43.949,28,90,11,0,33,0,1017], + [42.697,43.949,64,78,2,0,33,0,1017], + [42.698,43.949,56,80,13,1,33,0,1017], + [42.698,43.949,52,77,7,0,33,0,1017], + [42.699,43.949,71,75,2,2,33,0,1017], + [42.699,42.907,40,97,5,0,33,0,1017], + [42.701,43.115,28,97,6,0,33,0,1017], + [42.701,43.949,40,109,17,0,33,0,1017], + [42.703,43.949,52,75,13,0,33,0,1017], + [42.904,43.115,52,65,1,0,33,0.5,1022], + [42.907,43.115,40,68,5,0,33,0.5,1022], + [42.907,43.115,52,69,4,0,33,0.5,1022], + [43.11,43.324,47,74,5,0,33,1,1026], + [43.112,43.324,59,83,4,0,33,1,1026], + [43.114,43.324,56,70,1,0,33,1,1027], + [43.116,43.532,28,77,6,0,33,1,1027], + [43.117,43.324,38,86,16,0,33,1,1027], + [43.311,43.524,64,78,0,0,33,1.5,1031], + [43.319,43.532,40,92,16,0,33,1.5,1031], + [43.322,43.532,52,102,4,0,33,1.5,1031], + [43.326,43.532,40,94,5,0,33,1.5,1032], + [43.526,43.732,68,83,0,0,33,2,1036], + [43.531,43.74,59,70,4,0,33,2,1036], + [43.531,43.74,47,66,5,0,33,2,1036], + [43.535,43.949,28,81,6,0,33,2,1037], + [43.537,43.74,36,107,16,0,33,2,1037], + [43.737,43.941,71,88,0,0,33,2.5,1041], + [43.74,43.949,64,80,4,0,33,2.5,1041], + [43.74,43.949,52,76,5,0,33,2.5,1041], + [43.938,44.357,72,91,0,0,34,0,1046], + [43.943,45.199,69,79,2,0,34,0,1046], + [43.944,45.199,76,75,2,2,34,0,1046], + [43.945,44.157,45,74,1,0,34,0,1046], + [43.946,45.199,60,72,7,1,34,0,1046], + [43.946,44.157,57,101,4,0,34,0,1046], + [43.946,44.157,38,110,16,0,34,0,1046], + [43.947,45.199,33,90,11,0,34,0,1046], + [43.948,45.199,72,74,2,1,34,0,1046], + [43.949,45.199,57,79,13,0,34,0,1046], + [43.95,45.199,57,73,7,0,34,0,1046], + [43.951,44.365,33,107,6,0,34,0,1046], + [43.951,44.157,45,92,5,0,34,0,1046], + [43.952,45.199,60,77,13,1,34,0,1046], + [43.952,45.199,64,81,13,2,34,0,1046], + [43.952,45.199,40,111,17,0,34,0,1046], + [44.153,44.365,40,75,16,0,34,0.5,1051], + [44.156,44.365,45,64,5,0,34,0.5,1051], + [44.158,44.365,52,66,1,0,34,0.5,1051], + [44.163,44.365,57,76,4,0,34,0.5,1052], + [44.363,44.574,64,76,4,0,34,1,1056], + [44.363,44.574,52,72,5,0,34,1,1056], + [44.363,44.574,57,73,1,0,34,1,1056], + [44.363,44.782,33,73,6,0,34,1,1056], + [44.368,44.574,42,82,16,0,34,1,1056], + [44.563,44.774,64,79,0,0,34,1.5,1061], + [44.573,44.782,36,117,16,0,34,1.5,1061], + [44.575,44.782,45,93,5,0,34,1.5,1061], + [44.575,44.782,57,97,4,0,34,1.5,1061], + [44.778,44.982,76,91,0,0,34,2,1066], + [44.78,45.199,33,84,6,0,34,2,1066], + [44.782,44.99,52,67,5,0,34,2,1066], + [44.783,44.99,64,74,4,0,34,2,1066], + [44.784,44.99,40,88,16,0,34,2,1066], + [44.982,45.191,75,83,0,0,34,2.5,1071], + [44.989,45.199,69,82,4,0,34,2.5,1071], + [44.989,45.199,42,96,16,0,34,2.5,1071], + [44.993,45.199,57,73,5,0,34,2.5,1071], + [45.193,45.399,76,89,0,0,35,0,1076], + [45.193,45.615,28,97,6,0,35,0,1076], + [45.198,46.449,52,71,7,0,35,0,1076], + [45.198,46.449,68,80,2,1,35,0,1076], + [45.198,45.407,52,97,4,0,35,0,1076], + [45.198,46.449,40,111,17,0,35,0,1076], + [45.198,46.449,71,80,2,2,35,0,1076], + [45.198,46.449,56,78,7,1,35,0,1076], + [45.199,45.407,40,94,5,0,35,0,1076], + [45.2,46.449,59,79,13,2,35,0,1076], + [45.2,45.407,36,126,16,0,35,0,1076], + [45.201,46.449,28,88,11,0,35,0,1076], + [45.201,46.449,64,80,2,0,35,0,1076], + [45.201,46.449,56,77,13,1,35,0,1076], + [45.202,46.449,52,80,13,0,35,0,1076], + [45.397,45.607,75,84,0,0,35,0.5,1081], + [45.408,45.615,52,68,4,0,35,0.5,1081], + [45.408,45.615,40,61,5,0,35,0.5,1081], + [45.605,45.816,76,86,0,0,35,1,1086], + [45.61,45.824,47,77,5,0,35,1,1086], + [45.613,45.824,59,80,4,0,35,1,1086], + [45.619,46.032,28,71,6,0,35,1,1086], + [45.62,45.824,38,87,16,0,35,1,1086], + [45.811,46.024,71,86,0,0,35,1.5,1091], + [45.819,46.032,40,94,16,0,35,1.5,1091], + [45.824,46.032,52,93,4,0,35,1.5,1091], + [45.828,46.032,40,92,5,0,35,1.5,1091], + [46.026,46.24,47,64,5,0,35,2,1096], + [46.029,46.232,74,92,0,0,35,2,1096], + [46.031,46.24,59,69,4,0,35,2,1096], + [46.032,46.24,36,110,16,0,35,2,1096], + [46.033,46.449,28,78,6,0,35,2,1096], + [46.239,46.441,72,92,0,0,35,2.5,1101], + [46.239,46.449,52,74,5,0,35,2.5,1101], + [46.239,46.449,64,82,4,0,35,2.5,1101], + [46.438,46.857,69,91,0,0,36,0,1106], + [46.446,46.657,40,81,19,0,36,0,1106], + [46.446,47.699,33,85,11,0,36,0,1106], + [46.446,47.699,57,74,13,0,36,0,1106], + [46.446,47.699,76,75,2,2,36,0,1106], + [46.446,47.699,57,78,7,0,36,0,1106], + [46.446,46.865,33,102,6,0,36,0,1106], + [46.447,47.699,64,76,13,2,36,0,1106], + [46.447,47.699,72,75,2,1,36,0,1106], + [46.448,46.657,45,68,1,0,36,0,1106], + [46.45,46.657,57,103,4,0,36,0,1106], + [46.451,47.699,69,75,2,0,36,0,1106], + [46.451,46.657,45,89,5,0,36,0,1106], + [46.451,47.699,40,112,17,0,36,0,1106], + [46.451,46.657,38,106,16,0,36,0,1106], + [46.452,47.699,60,79,13,1,36,0,1106], + [46.452,47.699,60,78,7,1,36,0,1106], + [46.657,46.865,40,83,19,0,36,0.5,1111], + [46.659,46.865,40,74,16,0,36,0.5,1111], + [46.659,46.865,57,67,4,0,36,0.5,1111], + [46.659,46.865,45,67,5,0,36,0.5,1111], + [46.66,46.865,52,68,1,0,36,0.5,1111], + [46.863,47.074,64,82,4,0,36,1,1116], + [46.863,47.074,42,93,19,0,36,1,1116], + [46.863,47.074,42,74,16,0,36,1,1116], + [46.864,47.074,57,65,1,0,36,1,1116], + [46.866,47.282,33,73,6,0,36,1,1116], + [46.867,47.074,52,75,5,0,36,1,1116], + [47.061,47.274,60,77,0,0,36,1.5,1121], + [47.072,47.282,36,119,16,0,36,1.5,1121], + [47.072,47.282,45,96,5,0,36,1.5,1121], + [47.074,47.282,40,96,19,0,36,1.5,1121], + [47.074,47.282,57,93,4,0,36,1.5,1121], + [47.275,47.482,64,80,0,0,36,2,1126], + [47.28,47.49,40,85,16,0,36,2,1126], + [47.282,47.49,42,104,19,0,36,2,1126], + [47.286,47.49,52,69,5,0,36,2,1126], + [47.287,47.49,64,64,4,0,36,2,1126], + [47.287,47.699,33,87,6,0,36,2,1126], + [47.487,47.691,69,84,0,0,36,2.5,1131], + [47.488,47.699,42,92,16,0,36,2.5,1131], + [47.49,47.699,57,77,5,0,36,2.5,1131], + [47.493,47.699,42,108,19,0,36,2.5,1131], + [47.496,47.699,69,81,4,0,36,2.5,1131], + [47.691,48.107,71,93,0,0,37,0,1136], + [47.693,47.907,40,65,1,0,37,0,1136], + [47.695,48.949,64,82,2,0,37,0,1136], + [47.696,48.949,52,81,13,0,37,0,1136], + [47.697,48.949,68,80,2,1,37,0,1136], + [47.697,48.949,40,110,17,0,37,0,1136], + [47.697,48.115,28,100,6,0,37,0,1136], + [47.698,48.949,56,78,13,1,37,0,1136], + [47.698,48.949,52,79,7,0,37,0,1136], + [47.699,48.949,71,76,2,2,37,0,1136], + [47.699,47.907,52,98,4,0,37,0,1136], + [47.699,47.907,40,106,16,0,37,0,1136], + [47.7,48.949,56,72,7,1,37,0,1136], + [47.701,47.907,40,93,5,0,37,0,1136], + [47.702,48.949,28,90,11,0,37,0,1136], + [47.702,48.949,59,75,13,2,37,0,1136], + [47.9,48.115,42,109,16,0,37,0.5,1140], + [47.909,48.115,40,68,5,0,37,0.5,1141], + [47.912,48.115,52,71,1,0,37,0.5,1141], + [47.913,48.115,52,70,4,0,37,0.5,1141], + [48.11,48.324,47,69,5,0,37,1,1145], + [48.114,48.532,28,77,6,0,37,1,1146], + [48.114,48.324,59,83,4,0,37,1,1146], + [48.114,48.324,40,116,16,0,37,1,1146], + [48.116,48.324,56,64,1,0,37,1,1146], + [48.312,48.524,64,75,0,0,37,1.5,1150], + [48.32,48.532,52,94,4,0,37,1.5,1150], + [48.326,48.532,40,88,5,0,37,1.5,1151], + [48.327,48.532,42,119,16,0,37,1.5,1151], + [48.522,48.732,72,86,0,0,37,2,1155], + [48.531,48.949,28,79,6,0,37,2,1155], + [48.532,48.74,47,69,5,0,37,2,1156], + [48.533,48.74,59,68,4,0,37,2,1156], + [48.536,48.74,40,127,16,0,37,2,1156], + [48.734,48.941,71,81,0,0,37,2.5,1160], + [48.739,48.949,52,71,5,0,37,2.5,1160], + [48.741,48.949,42,122,16,0,37,2.5,1160], + [48.741,48.949,64,76,4,0,37,2.5,1161], + [48.944,50.199,33,64,11,0,38,0,1165], + [48.944,49.157,45,45,1,0,38,0,1165], + [48.945,49.357,69,72,0,0,38,0,1165], + [48.946,50.199,64,61,13,2,38,0,1165], + [48.947,50.199,57,61,13,0,38,0,1165], + [48.947,50.199,69,68,2,0,38,0,1165], + [48.948,50.199,64,63,3,2,38,0,1165], + [48.948,50.199,60,63,13,1,38,0,1165], + [48.95,50.199,72,69,2,1,38,0,1165], + [48.951,50.199,76,73,2,2,38,0,1166], + [48.951,50.199,60,68,3,1,38,0,1166], + [48.952,50.199,36,69,16,0,38,0,1166], + [48.952,50.199,57,63,3,0,38,0,1166], + [48.953,50.199,51,63,21,0,38,0,1166], + [49.161,49.365,52,44,1,0,38,0.5,1171], + [49.364,49.574,57,48,1,0,38,1,1175], + [49.564,49.774,72,64,0,1,38,1.5,1180], + [49.567,49.774,64,66,0,0,38,1.5,1180], + [49.572,49.782,58,51,1,0,38,1.5,1180], + [49.573,49.782,60,47,1,1,38,1.5,1180], + [49.771,49.982,65,67,0,0,38,2,1185], + [49.778,49.982,72,66,0,1,38,2,1185], + [49.782,49.99,57,47,1,0,38,2,1185], + [49.785,49.99,60,45,1,1,38,2,1185], + [49.975,50.191,67,72,0,1,38,2.5,1190], + [49.976,50.191,64,70,0,0,38,2.5,1190], + [49.983,50.191,72,70,0,2,38,2.5,1190], + [49.986,50.199,60,51,1,2,38,2.5,1190], + [49.99,50.199,55,47,1,0,38,2.5,1190], + [49.99,50.199,58,54,1,1,38,2.5,1190], + [50.186,50.243,65,62,0,0,39,0,1195], + [50.195,51.449,60,67,3,2,39,0,1195], + [50.197,51.449,69,66,2,1,39,0,1195], + [50.197,51.449,60,60,13,2,39,0,1195], + [50.197,50.407,53,46,1,0,39,0,1195], + [50.198,51.449,72,66,2,2,39,0,1195], + [50.199,51.449,57,66,13,1,39,0,1195], + [50.199,51.449,65,69,2,0,39,0,1195], + [50.201,51.449,53,64,13,0,39,0,1195], + [50.201,51.449,57,65,3,1,39,0,1195], + [50.202,51.449,53,62,3,0,39,0,1195], + [50.204,51.449,29,63,11,0,39,0,1195], + [50.242,50.295,69,63,0,0,39,0.125,1196], + [50.295,51.024,72,79,0,0,39,0.25,1197], + [50.41,50.615,57,48,1,0,39,0.5,1200], + [50.611,50.824,60,43,1,0,39,1,1205], + [50.826,51.032,57,44,1,0,39,1.5,1210], + [51.022,51.336,77,83,0,0,39,2,1215], + [51.033,51.24,60,46,1,0,39,2,1215], + [51.243,51.449,57,36,1,0,39,2.5,1220], + [51.336,51.441,76,76,0,0,39,2.75,1222], + [51.443,51.857,76,77,0,0,40,0,1225], + [51.443,51.657,53,46,1,0,40,0,1225], + [51.444,52.699,58,70,3,0,40,0,1225], + [51.444,52.699,58,63,13,0,40,0,1225], + [51.447,52.699,34,67,11,0,40,0,1225], + [51.447,52.699,62,68,3,1,40,0,1225], + [51.447,52.699,65,60,3,2,40,0,1225], + [51.449,52.699,77,73,2,2,40,0,1225], + [51.45,52.699,70,69,2,0,40,0,1225], + [51.451,52.699,74,63,2,1,40,0,1225], + [51.453,52.699,65,60,13,2,40,0,1225], + [51.454,52.699,62,60,13,1,40,0,1225], + [51.661,51.865,58,41,1,0,40,0.5,1230], + [51.863,52.074,62,48,1,0,40,1,1235], + [51.864,52.274,74,70,0,0,40,1,1235], + [52.079,52.282,58,39,1,0,40,1.5,1240], + [52.276,52.586,82,81,0,0,40,2,1245], + [52.288,52.49,62,43,1,0,40,2,1245], + [52.49,52.699,58,39,1,0,40,2.5,1250], + [52.584,52.691,81,74,0,0,40,2.75,1252], + [52.693,53.949,24,67,11,0,41,0,1255], + [52.695,52.899,81,77,0,0,41,0,1255], + [52.697,53.949,55,57,13,2,41,0,1255], + [52.697,53.949,64,68,2,1,41,0,1255], + [52.697,53.949,48,68,13,0,41,0,1255], + [52.698,53.949,67,71,2,2,41,0,1255], + [52.698,52.907,53,48,1,0,41,0,1255], + [52.699,53.949,55,64,3,2,41,0,1255], + [52.699,53.949,60,68,2,0,41,0,1255], + [52.7,53.949,52,66,3,1,41,0,1255], + [52.701,53.949,52,64,13,1,41,0,1255], + [52.702,53.949,48,62,3,0,41,0,1255], + [52.904,53.107,79,76,0,0,41,0.5,1260], + [52.911,53.115,64,45,1,0,41,0.5,1260], + [53.107,53.316,77,76,0,0,41,1,1264], + [53.113,53.324,58,44,1,1,41,1,1265], + [53.12,53.324,55,49,1,0,41,1,1265], + [53.317,53.524,76,75,0,0,41,1.5,1269], + [53.322,53.532,64,43,1,0,41,1.5,1270], + [53.52,53.732,74,66,0,0,41,2,1274], + [53.532,53.74,55,43,1,0,41,2,1275], + [53.535,53.74,58,45,1,1,41,2,1275], + [53.731,53.941,72,65,0,0,41,2.5,1279], + [53.734,53.949,64,36,1,0,41,2.5,1279], + [53.942,54.357,70,75,0,0,42,0,1284], + [53.944,55.199,72,70,2,2,42,0,1284], + [53.945,55.199,36,72,16,0,42,0,1284], + [53.945,55.199,29,68,11,0,42,0,1284], + [53.946,55.199,57,65,13,1,42,0,1284], + [53.948,55.199,53,69,3,0,42,0,1284], + [53.949,55.199,53,60,13,0,42,0,1284], + [53.949,55.199,60,60,13,2,42,0,1285], + [53.95,55.199,57,67,3,1,42,0,1285], + [53.95,54.157,53,47,1,0,42,0,1285], + [53.951,55.199,65,71,2,0,42,0,1285], + [53.951,55.199,60,62,3,2,42,0,1285], + [53.952,55.199,69,64,2,1,42,0,1285], + [54.157,54.365,57,44,1,0,42,0.5,1289], + [54.358,54.722,69,75,0,0,42,1,1294], + [54.367,54.574,60,46,1,0,42,1,1294], + [54.575,54.782,57,41,1,0,42,1.5,1299], + [54.723,54.774,70,60,0,0,42,1.875,1303], + [54.775,54.878,69,71,0,0,42,2,1304], + [54.779,54.99,60,50,1,0,42,2,1304], + [54.879,54.982,67,66,0,0,42,2.25,1307], + [54.984,55.086,69,65,0,0,42,2.5,1309], + [54.985,55.199,57,42,1,0,42,2.5,1309], + [55.084,55.191,70,68,0,0,42,2.75,1312], + [55.19,56.024,72,73,0,0,43,0,1314], + [55.194,56.449,53,61,13,0,43,0,1314], + [55.197,56.449,60,65,13,2,43,0,1314], + [55.197,56.449,57,59,13,1,43,0,1314], + [55.197,56.449,69,66,2,1,43,0,1314], + [55.197,56.449,57,67,3,1,43,0,1314], + [55.197,56.449,72,65,2,2,43,0,1314], + [55.199,56.449,65,69,2,0,43,0,1314], + [55.199,55.407,53,45,1,0,43,0,1314], + [55.2,56.449,60,62,3,2,43,0,1314], + [55.2,56.449,53,68,3,0,43,0,1314], + [55.2,56.449,29,61,11,0,43,0,1314], + [55.412,55.615,57,45,1,0,43,0.5,1319], + [55.614,55.824,60,40,1,0,43,1,1324], + [55.825,56.032,57,44,1,0,43,1.5,1329], + [56.022,56.232,74,74,0,0,43,2,1334], + [56.033,56.24,60,44,1,0,43,2,1334], + [56.232,56.441,75,72,0,0,43,2.5,1339], + [56.244,56.449,57,43,1,0,43,2.5,1339], + [56.44,57.066,76,87,0,0,44,0,1344], + [56.448,57.699,57,65,13,0,44,0,1344], + [56.448,57.699,64,67,3,2,44,0,1344], + [56.449,57.699,72,74,2,1,44,0,1344], + [56.449,57.699,60,68,3,1,44,0,1344], + [56.449,57.699,69,74,2,0,44,0,1344], + [56.449,56.657,52,49,1,0,44,0,1344], + [56.451,57.699,33,68,11,0,44,0,1344], + [56.451,57.699,60,61,13,1,44,0,1344], + [56.452,57.699,76,71,2,2,44,0,1344], + [56.452,57.699,64,59,13,2,44,0,1344], + [56.453,57.699,57,68,3,0,44,0,1344], + [56.656,56.865,57,45,1,0,44,0.5,1349], + [56.869,57.074,60,40,1,0,44,1,1354], + [57.066,57.274,76,79,0,0,44,1.5,1359], + [57.077,57.282,57,46,1,0,44,1.5,1359], + [57.279,57.482,77,76,0,0,44,2,1364], + [57.281,57.49,50,49,1,0,44,2,1364], + [57.281,57.49,62,41,1,1,44,2,1364], + [57.485,57.691,69,67,0,0,44,2.5,1369], + [57.486,57.699,53,43,1,0,44,2.5,1369], + [57.69,58.524,72,83,0,0,45,0,1374], + [57.693,57.907,55,44,1,0,45,0,1374], + [57.696,58.949,62,65,3,2,45,0,1374], + [57.696,58.949,62,57,13,2,45,0,1374], + [57.697,58.949,67,69,2,0,45,0,1374], + [57.697,58.949,31,62,11,0,45,0,1374], + [57.698,58.949,55,64,13,0,45,0,1374], + [57.698,58.949,74,71,2,2,45,0,1374], + [57.699,58.949,59,65,13,1,45,0,1374], + [57.699,58.949,55,67,3,0,45,0,1374], + [57.701,58.949,59,63,3,1,45,0,1374], + [57.704,58.949,71,68,2,1,45,0,1374], + [57.906,58.115,64,43,1,0,45,0.5,1379], + [58.117,58.324,55,42,1,0,45,1,1384], + [58.319,58.532,65,43,1,0,45,1.5,1389], + [58.519,58.836,74,77,0,0,45,2,1393], + [58.533,58.74,55,49,1,0,45,2,1394], + [58.738,58.949,65,41,1,0,45,2.5,1399], + [58.836,58.941,71,68,0,0,45,2.75,1401], + [58.94,59.045,72,80,0,0,46,0,1403], + [58.946,59.365,36,87,16,0,46,0,1403], + [58.946,60.199,48,69,3,0,46,0,1403], + [58.947,60.199,55,76,13,2,46,0,1403], + [58.948,60.199,51,85,21,0,46,0,1404], + [58.948,60.199,52,67,3,1,46,0,1404], + [58.948,60.199,52,68,13,1,46,0,1404], + [58.948,59.365,60,43,1,0,46,0,1404], + [58.948,60.199,48,75,13,0,46,0,1404], + [58.948,60.199,24,76,11,0,46,0,1404], + [58.948,60.199,55,64,3,2,46,0,1404], + [58.949,59.157,60,80,14,0,46,0,1404], + [58.951,59.365,64,47,1,1,46,0,1404], + [58.952,60.199,64,67,2,1,46,0,1404], + [58.952,60.199,67,67,2,2,46,0,1404], + [58.953,60.199,60,67,2,0,46,0,1404], + [59.042,59.149,79,71,0,0,46,0.25,1406], + [59.146,59.253,67,65,0,0,46,0.5,1408], + [59.152,59.365,64,62,14,0,46,0.5,1408], + [59.246,59.357,79,69,0,0,46,0.75,1411], + [59.357,59.461,69,62,0,0,46,1,1413], + [59.365,59.574,67,61,14,0,46,1,1413], + [59.46,59.566,79,68,0,0,46,1.25,1416], + [59.563,59.67,71,65,0,0,46,1.5,1418], + [59.567,59.782,65,48,1,0,46,1.5,1418], + [59.575,59.782,67,44,1,1,46,1.5,1418], + [59.576,59.782,72,80,14,0,46,1.5,1418], + [59.671,59.774,79,66,0,0,46,1.75,1421], + [59.769,59.878,72,66,0,0,46,2,1423], + [59.776,59.99,67,44,1,1,46,2,1423], + [59.779,59.99,64,41,1,0,46,2,1423], + [59.787,59.99,67,63,14,0,46,2,1423], + [59.875,59.982,79,65,0,0,46,2.25,1426], + [59.988,60.086,74,72,0,0,46,2.5,1428], + [59.988,60.199,65,40,1,1,46,2.5,1428], + [59.989,60.199,62,43,1,0,46,2.5,1428], + [59.989,60.199,64,65,14,0,46,2.5,1428], + [59.996,60.199,67,48,1,2,46,2.5,1428], + [60.088,60.191,79,63,0,0,46,2.75,1431], + [60.192,61.449,59,71,13,1,47,0,1433], + [60.192,60.295,76,76,0,0,47,0,1433], + [60.194,61.449,74,73,2,2,47,0,1433], + [60.194,61.449,55,75,13,0,47,0,1433], + [60.195,60.615,64,48,1,1,47,0,1433], + [60.196,60.615,67,46,1,2,47,0,1433], + [60.197,60.407,67,89,14,0,47,0,1433], + [60.198,61.449,62,65,3,2,47,0,1433], + [60.198,61.449,67,69,2,0,47,0,1433], + [60.199,61.449,71,66,2,1,47,0,1433], + [60.199,61.449,59,69,3,1,47,0,1433], + [60.2,61.449,62,65,13,2,47,0,1433], + [60.2,61.449,55,64,3,0,47,0,1433], + [60.2,61.449,31,76,11,0,47,0,1433], + [60.203,60.615,60,49,1,0,47,0,1433], + [60.299,60.399,79,69,0,0,47,0.25,1436], + [60.399,60.503,84,79,0,0,47,0.5,1438], + [60.408,60.615,71,65,14,0,47,0.5,1438], + [60.503,60.607,83,73,0,0,47,0.75,1441], + [60.609,60.711,81,66,0,0,47,1,1443], + [60.612,60.824,74,63,14,0,47,1,1443], + [60.613,61.032,55,42,1,0,47,1,1443], + [60.614,61.032,59,42,1,1,47,1,1443], + [60.717,60.816,79,72,0,0,47,1.25,1446], + [60.818,60.92,77,72,0,0,47,1.5,1448], + [60.82,61.032,79,90,14,0,47,1.5,1448], + [60.917,61.024,76,72,0,0,47,1.75,1450], + [61.022,61.128,74,69,0,0,47,2,1453], + [61.026,61.449,59,40,1,1,47,2,1453], + [61.031,61.24,74,66,14,0,47,2,1453], + [61.033,61.449,55,46,1,0,47,2,1453], + [61.127,61.232,79,68,0,0,47,2.25,1455], + [61.231,61.336,77,75,0,0,47,2.5,1458], + [61.24,61.449,71,64,14,0,47,2.5,1458], + [61.34,61.441,74,68,0,0,47,2.75,1460], + [61.434,61.545,72,77,0,0,48,0,1463], + [61.444,61.865,36,93,16,0,48,0,1463], + [61.446,61.865,60,46,1,0,48,0,1463], + [61.447,62.699,24,79,11,0,48,0,1463], + [61.448,61.657,60,88,14,0,48,0,1463], + [61.448,62.699,64,66,2,1,48,0,1463], + [61.449,62.699,55,72,13,2,48,0,1463], + [61.45,62.699,52,72,13,1,48,0,1463], + [61.45,62.699,67,67,2,2,48,0,1463], + [61.45,62.699,52,70,3,1,48,0,1463], + [61.451,62.699,60,72,2,0,48,0,1463], + [61.451,61.865,64,49,1,1,48,0,1463], + [61.452,62.699,48,74,13,0,48,0,1463], + [61.453,62.699,55,67,3,2,48,0,1463], + [61.455,62.699,48,70,3,0,48,0,1463], + [61.55,61.649,79,67,0,0,48,0.25,1465], + [61.648,61.753,67,63,0,0,48,0.5,1468], + [61.656,61.865,64,60,14,0,48,0.5,1468], + [61.756,61.857,79,68,0,0,48,0.75,1470], + [61.853,61.961,69,66,0,0,48,1,1473], + [61.867,62.074,67,61,14,0,48,1,1473], + [61.959,62.066,79,68,0,0,48,1.25,1475], + [62.061,62.17,71,61,0,0,48,1.5,1478], + [62.067,62.282,65,42,1,0,48,1.5,1478], + [62.07,62.282,67,47,1,1,48,1.5,1478], + [62.077,62.282,72,88,14,0,48,1.5,1478], + [62.172,62.274,79,68,0,0,48,1.75,1480], + [62.279,62.378,72,76,0,0,48,2,1483], + [62.282,62.49,67,41,1,1,48,2,1483], + [62.282,62.49,67,62,14,0,48,2,1483], + [62.286,62.49,64,39,1,0,48,2,1483], + [62.375,62.482,79,71,0,0,48,2.25,1485], + [62.48,62.586,74,71,0,0,48,2.5,1488], + [62.487,62.699,65,45,1,1,48,2.5,1488], + [62.491,62.699,62,52,1,0,48,2.5,1488], + [62.492,62.699,64,61,14,0,48,2.5,1488], + [62.493,62.699,67,41,1,2,48,2.5,1488], + [62.585,62.691,79,74,0,0,48,2.75,1490], + [62.692,62.795,76,78,0,0,49,0,1493], + [62.694,63.115,60,53,1,0,49,0,1493], + [62.695,63.115,64,48,1,1,49,0,1493], + [62.695,63.115,67,43,1,2,49,0,1493], + [62.697,63.949,62,71,13,2,49,0,1493], + [62.697,63.949,59,73,13,1,49,0,1493], + [62.697,63.949,67,71,2,0,49,0,1493], + [62.697,63.949,74,71,2,2,49,0,1493], + [62.699,63.949,59,64,3,1,49,0,1493], + [62.699,63.949,71,71,2,1,49,0,1493], + [62.699,63.949,31,78,11,0,49,0,1493], + [62.7,63.949,62,67,3,2,49,0,1493], + [62.7,62.907,67,82,14,0,49,0,1493], + [62.701,63.949,55,74,13,0,49,0,1493], + [62.702,63.949,55,64,3,0,49,0,1493], + [62.795,62.899,79,64,0,0,49,0.25,1495], + [62.894,63.003,84,78,0,0,49,0.5,1497], + [62.909,63.115,71,67,14,0,49,0.5,1498], + [63.001,63.107,83,73,0,0,49,0.75,1500], + [63.11,63.532,55,44,1,0,49,1,1503], + [63.113,63.211,81,69,0,0,49,1,1503], + [63.114,63.324,74,66,14,0,49,1,1503], + [63.117,63.532,59,46,1,1,49,1,1503], + [63.212,63.316,79,70,0,0,49,1.25,1505], + [63.322,63.42,77,67,0,0,49,1.5,1508], + [63.326,63.532,79,84,14,0,49,1.5,1508], + [63.417,63.524,76,69,0,0,49,1.75,1510], + [63.525,63.628,74,70,0,0,49,2,1512], + [63.527,63.949,59,36,1,1,49,2,1513], + [63.529,63.74,74,69,14,0,49,2,1513], + [63.532,63.949,55,41,1,0,49,2,1513], + [63.629,63.732,79,64,0,0,49,2.25,1515], + [63.734,63.836,77,64,0,0,49,2.5,1517], + [63.739,63.949,71,64,14,0,49,2.5,1518], + [63.837,63.941,74,66,0,0,49,2.75,1520], + [63.942,64.045,76,70,0,0,50,0,1522], + [63.944,65.199,59,73,13,2,50,0,1522], + [63.944,65.199,52,69,13,0,50,0,1522], + [63.946,64.157,52,94,4,0,50,0,1523], + [63.946,64.365,59,51,1,1,50,0,1523], + [63.948,64.365,36,109,16,0,50,0,1523], + [63.948,64.157,64,90,14,0,50,0,1523], + [63.948,65.199,28,76,11,0,50,0,1523], + [63.948,65.199,56,73,13,1,50,0,1523], + [63.948,65.199,43,103,23,0,50,0,1523], + [63.949,64.365,56,49,1,0,50,0,1523], + [64.046,64.149,77,74,0,0,50,0.25,1525], + [64.143,64.253,76,73,0,0,50,0.5,1527], + [64.16,64.365,68,75,14,0,50,0.5,1528], + [64.16,64.365,52,60,4,0,50,0.5,1528], + [64.256,64.357,75,73,0,0,50,0.75,1530], + [64.354,64.461,76,71,0,0,50,1,1532], + [64.361,64.574,71,66,14,0,50,1,1532], + [64.361,64.574,59,65,4,0,50,1,1532], + [64.46,64.566,71,72,0,0,50,1.25,1535], + [64.565,64.67,76,81,0,0,50,1.5,1537], + [64.574,64.782,38,70,16,0,50,1.5,1537], + [64.575,64.782,76,92,14,0,50,1.5,1538], + [64.577,64.782,52,82,4,0,50,1.5,1538], + [64.678,64.774,75,72,0,0,50,1.75,1540], + [64.773,64.878,76,71,0,0,50,2,1542], + [64.777,64.99,59,58,4,0,50,2,1542], + [64.779,65.199,40,87,16,0,50,2,1542], + [64.779,64.99,71,68,14,0,50,2,1542], + [64.878,64.982,71,65,0,0,50,2.25,1545], + [64.986,65.086,76,77,0,0,50,2.5,1547], + [64.986,65.199,64,69,4,0,50,2.5,1547], + [64.991,65.199,68,73,14,0,50,2.5,1547], + [65.083,65.191,75,69,0,0,50,2.75,1550], + [65.188,65.816,76,72,0,0,51,0,1552], + [65.196,65.407,64,93,14,0,51,0,1552], + [65.197,66.449,56,66,13,1,51,0,1552], + [65.2,66.449,28,83,11,0,51,0,1552], + [65.201,65.407,52,97,4,0,51,0,1552], + [65.201,65.407,38,95,16,0,51,0,1552], + [65.201,66.449,52,77,13,0,51,0,1552], + [65.202,66.449,44,75,20,0,51,0,1552], + [65.203,66.449,59,72,13,2,51,0,1552], + [65.408,65.615,68,73,14,0,51,0.5,1557], + [65.409,65.615,52,68,4,0,51,0.5,1557], + [65.614,65.824,71,74,14,0,51,1,1562], + [65.616,65.824,59,73,4,0,51,1,1562], + [65.619,65.824,40,69,16,0,51,1,1562], + [65.817,65.92,71,68,0,0,51,1.5,1567], + [65.82,66.032,40,64,16,0,51,1.5,1567], + [65.821,66.032,52,90,4,0,51,1.5,1567], + [65.822,66.032,76,99,14,0,51,1.5,1567], + [65.92,66.024,76,76,0,0,51,1.75,1570], + [66.026,66.441,75,75,0,0,51,2,1572], + [66.03,66.24,71,76,14,0,51,2,1572], + [66.032,66.24,59,67,4,0,51,2,1572], + [66.036,66.449,38,100,16,0,51,2,1572], + [66.239,66.449,68,74,14,0,51,2.5,1577], + [66.241,66.449,64,73,4,0,51,2.5,1577], + [66.443,67.066,76,79,0,0,52,0,1582], + [66.444,67.699,56,72,13,1,52,0,1582], + [66.444,67.699,52,68,13,0,52,0,1582], + [66.447,66.865,36,110,16,0,52,0,1582], + [66.448,66.657,52,97,4,0,52,0,1582], + [66.449,67.699,59,73,13,2,52,0,1582], + [66.449,67.699,28,84,11,0,52,0,1582], + [66.449,67.699,44,89,20,0,52,0,1582], + [66.45,66.657,64,102,14,0,52,0,1582], + [66.45,66.657,40,80,19,0,52,0,1582], + [66.654,66.865,40,89,19,0,52,0.5,1587], + [66.655,66.865,52,66,4,0,52,0.5,1587], + [66.663,66.865,68,76,14,0,52,0.5,1587], + [66.858,67.074,42,95,19,0,52,1,1592], + [66.862,67.074,71,78,14,0,52,1,1592], + [66.864,67.074,59,72,4,0,52,1,1592], + [67.066,67.17,71,65,0,0,52,1.5,1597], + [67.071,67.282,40,96,19,0,52,1.5,1597], + [67.073,67.282,38,74,16,0,52,1.5,1597], + [67.076,67.282,52,96,4,0,52,1.5,1597], + [67.078,67.282,76,103,14,0,52,1.5,1597], + [67.169,67.274,76,76,0,0,52,1.75,1599], + [67.275,67.691,75,72,0,0,52,2,1602], + [67.281,67.49,71,84,14,0,52,2,1602], + [67.282,67.49,59,69,4,0,52,2,1602], + [67.283,67.699,40,84,16,0,52,2,1602], + [67.283,67.49,42,102,19,0,52,2,1602], + [67.487,67.699,68,83,14,0,52,2.5,1607], + [67.488,67.699,64,82,4,0,52,2.5,1607], + [67.491,67.699,42,113,19,0,52,2.5,1607], + [67.688,68.107,76,70,0,0,53,0,1612], + [67.69,67.907,52,101,4,0,53,0,1612], + [67.695,68.949,56,69,13,1,53,0,1612], + [67.696,67.907,38,98,16,0,53,0,1612], + [67.698,68.949,52,70,13,0,53,0,1612], + [67.699,67.907,40,107,19,0,53,0,1612], + [67.699,68.949,28,84,11,0,53,0,1612], + [67.701,68.949,59,70,13,2,53,0,1612], + [67.701,68.949,44,109,20,0,53,0,1612], + [67.701,67.907,64,98,14,0,53,0,1612], + [67.906,68.115,52,73,4,0,53,0.5,1617], + [67.907,68.115,68,87,14,0,53,0.5,1617], + [67.909,68.115,42,111,19,0,53,0.5,1617], + [68.107,68.211,75,70,0,0,53,1,1622], + [68.115,68.324,71,86,14,0,53,1,1622], + [68.117,68.324,40,71,16,0,53,1,1622], + [68.119,68.324,59,85,4,0,53,1,1622], + [68.12,68.324,40,112,19,0,53,1,1622], + [68.214,68.316,76,65,0,0,53,1.25,1624], + [68.32,68.42,75,64,0,0,53,1.5,1627], + [68.321,68.532,40,60,16,0,53,1.5,1627], + [68.324,68.532,76,107,14,0,53,1.5,1627], + [68.324,68.532,42,123,19,0,53,1.5,1627], + [68.326,68.532,52,102,4,0,53,1.5,1627], + [68.421,68.524,76,70,0,0,53,1.75,1629], + [68.518,68.941,75,71,0,0,53,2,1631], + [68.527,68.74,71,82,14,0,53,2,1632], + [68.53,68.949,38,102,16,0,53,2,1632], + [68.532,68.74,40,121,19,0,53,2,1632], + [68.533,68.74,59,77,4,0,53,2,1632], + [68.737,68.949,64,86,4,0,53,2.5,1637], + [68.739,68.949,42,127,19,0,53,2.5,1637], + [68.739,68.949,68,88,14,0,53,2.5,1637], + [68.937,69.357,69,71,0,0,54,0,1641], + [68.942,69.157,57,98,4,0,54,0,1641], + [68.945,70.199,33,98,11,0,54,0,1642], + [68.95,69.157,45,81,1,0,54,0,1642], + [68.951,69.157,36,123,16,0,54,0,1642], + [69.155,69.365,40,77,16,0,54,0.5,1647], + [69.16,69.365,45,82,1,0,54,0.5,1647], + [69.163,69.365,57,72,4,0,54,0.5,1647], + [69.362,69.574,40,76,16,0,54,1,1651], + [69.363,69.574,64,83,4,0,54,1,1651], + [69.366,69.574,45,78,1,0,54,1,1652], + [69.572,69.782,38,112,16,0,54,1.5,1656], + [69.574,69.782,57,100,4,0,54,1.5,1657], + [69.577,69.782,45,86,1,0,54,1.5,1657], + [69.784,69.99,64,78,4,0,54,2,1662], + [69.784,69.99,40,71,16,0,54,2,1662], + [69.785,69.99,45,83,1,0,54,2,1662], + [69.989,70.199,40,84,16,0,54,2.5,1666], + [69.989,70.199,45,81,1,0,54,2.5,1666], + [69.995,70.199,69,80,4,0,54,2.5,1667], + [70.187,71.441,73,105,0,3,55,0,1671], + [70.188,71.441,67,101,0,1,55,0,1671], + [70.191,71.441,64,109,0,0,55,0,1671], + [70.191,71.449,64,84,13,2,55,0,1671], + [70.192,71.449,40,113,10,1,55,0,1671], + [70.192,71.449,67,88,7,1,55,0,1671], + [70.193,71.449,64,87,7,0,55,0,1671], + [70.194,71.449,33,122,10,0,55,0,1671], + [70.194,70.407,45,103,5,0,55,0,1671], + [70.194,70.407,81,90,14,0,55,0,1671], + [70.195,71.449,73,95,2,0,55,0,1671], + [70.196,71.441,70,101,0,2,55,0,1671], + [70.196,71.449,36,127,22,0,55,0,1671], + [70.197,71.449,33,98,9,0,55,0,1671], + [70.198,71.449,49,107,8,0,55,0,1671], + [70.198,70.615,33,106,6,0,55,0,1671], + [70.198,71.449,49,121,21,0,55,0,1671], + [70.199,70.407,57,99,4,0,55,0,1671], + [70.199,71.449,69,86,15,0,55,0,1671], + [70.199,71.449,73,85,15,1,55,0,1671], + [70.199,71.449,33,92,11,0,55,0,1671], + [70.2,71.449,70,91,3,0,55,0,1671], + [70.2,71.449,45,110,10,2,55,0,1671], + [70.2,71.449,45,96,18,0,55,0,1671], + [70.201,71.449,40,111,17,0,55,0,1671], + [70.201,70.407,45,103,1,0,55,0,1671], + [70.201,71.449,57,78,13,0,55,0,1671], + [70.202,71.449,61,76,13,1,55,0,1671], + [70.202,71.449,55,106,8,1,55,0,1671], + [70.202,70.407,37,117,16,0,55,0,1671], + [70.202,71.449,76,80,15,2,55,0,1671], + [70.403,70.615,45,105,1,0,55,0.5,1676], + [70.406,70.615,57,70,4,0,55,0.5,1676], + [70.408,70.615,45,75,5,0,55,0.5,1676], + [70.408,70.615,85,62,14,0,55,0.5,1676], + [70.41,70.615,40,78,16,0,55,0.5,1676], + [70.612,70.824,45,99,1,0,55,1,1681], + [70.614,71.032,33,81,6,0,55,1,1681], + [70.616,70.824,40,81,16,0,55,1,1681], + [70.618,70.824,52,76,5,0,55,1,1681], + [70.62,70.824,88,73,14,0,55,1,1681], + [70.621,70.824,64,84,4,0,55,1,1681], + [70.823,71.032,93,87,14,0,55,1.5,1686], + [70.824,71.032,57,100,4,0,55,1.5,1686], + [70.825,71.032,38,115,16,0,55,1.5,1686], + [70.826,71.032,45,98,1,0,55,1.5,1686], + [70.827,71.032,45,101,5,0,55,1.5,1686], + [71.031,71.24,52,72,5,0,55,2,1691], + [71.031,71.24,45,96,1,0,55,2,1691], + [71.033,71.24,88,65,14,0,55,2,1691], + [71.034,71.24,64,76,4,0,55,2,1691], + [71.034,71.24,40,75,16,0,55,2,1691], + [71.037,71.449,33,89,6,0,55,2,1691], + [71.234,71.449,69,89,4,0,55,2.5,1696], + [71.236,71.449,42,90,16,0,55,2.5,1696], + [71.241,71.449,85,63,14,0,55,2.5,1696], + [71.243,71.449,45,96,1,0,55,2.5,1696], + [71.243,71.449,57,78,5,0,55,2.5,1696], + [71.441,72.274,69,88,0,1,56,0,1701], + [71.442,72.274,74,90,0,2,56,0,1701], + [71.442,71.657,45,97,1,0,56,0,1701], + [71.442,72.274,65,92,0,0,56,0,1701], + [71.443,72.699,53,85,8,1,56,0,1701], + [71.444,72.699,65,88,7,1,56,0,1701], + [71.445,71.657,36,118,16,0,56,0,1701], + [71.446,72.699,53,81,13,1,56,0,1701], + [71.449,71.865,45,90,18,0,56,0,1701], + [71.449,71.865,26,115,6,0,56,0,1701], + [71.449,72.282,69,93,3,0,56,0,1701], + [71.449,72.282,74,93,2,0,56,0,1701], + [71.449,72.699,62,85,15,0,56,0,1701], + [71.45,72.699,62,90,7,0,56,0,1701], + [71.45,72.699,50,89,8,0,56,0,1701], + [71.45,72.699,26,100,11,0,56,0,1701], + [71.45,71.657,50,101,4,0,56,0,1701], + [71.451,72.699,50,78,13,0,56,0,1701], + [71.451,71.657,38,98,5,0,56,0,1701], + [71.451,71.657,74,89,14,0,56,0,1701], + [71.451,72.699,40,112,17,0,56,0,1701], + [71.452,72.699,57,85,13,2,56,0,1701], + [71.452,72.699,69,83,15,2,56,0,1701], + [71.454,72.699,65,87,15,1,56,0,1701], + [71.652,71.865,40,77,16,0,56,0.5,1706], + [71.655,71.865,45,99,1,0,56,0.5,1706], + [71.656,71.865,38,70,5,0,56,0.5,1706], + [71.657,71.865,50,73,4,0,56,0.5,1706], + [71.659,71.865,77,65,14,0,56,0.5,1706], + [71.862,72.074,40,87,16,0,56,1,1711], + [71.865,72.282,26,81,6,0,56,1,1711], + [71.865,72.074,45,96,1,0,56,1,1711], + [71.866,72.074,45,81,5,0,56,1,1711], + [71.868,72.074,57,83,4,0,56,1,1711], + [71.869,72.074,81,72,14,0,56,1,1711], + [72.071,72.282,38,93,5,0,56,1.5,1716], + [72.076,72.282,45,99,1,0,56,1.5,1716], + [72.076,72.282,38,111,16,0,56,1.5,1716], + [72.077,72.282,50,104,4,0,56,1.5,1716], + [72.079,72.282,86,83,14,0,56,1.5,1716], + [72.271,72.482,76,90,0,1,56,2,1721], + [72.275,72.482,73,89,0,0,56,2,1721], + [72.277,72.49,45,102,1,0,56,2,1721], + [72.278,72.699,26,96,6,0,56,2,1721], + [72.281,72.49,76,92,2,0,56,2,1721], + [72.283,72.49,81,69,14,0,56,2,1721], + [72.284,72.49,57,73,4,0,56,2,1721], + [72.286,72.49,45,79,5,0,56,2,1721], + [72.286,72.49,73,92,3,0,56,2,1721], + [72.288,72.49,40,72,16,0,56,2,1721], + [72.48,72.691,74,88,0,0,56,2.5,1726], + [72.485,72.691,77,85,0,1,56,2.5,1726], + [72.487,72.699,77,94,2,0,56,2.5,1726], + [72.488,72.699,74,89,3,0,56,2.5,1726], + [72.49,72.699,40,86,16,0,56,2.5,1726], + [72.491,72.699,62,82,4,0,56,2.5,1726], + [72.493,72.699,77,69,14,0,56,2.5,1726], + [72.494,72.699,50,82,5,0,56,2.5,1726], + [72.495,72.699,45,99,1,0,56,2.5,1726], + [72.686,73.524,68,93,0,0,57,0,1731], + [72.689,73.524,77,95,0,2,57,0,1731], + [72.694,73.524,74,94,0,1,57,0,1731], + [72.695,73.949,33,92,9,0,57,0,1731], + [72.695,73.949,65,86,7,1,57,0,1731], + [72.697,72.907,76,84,14,0,57,0,1731], + [72.697,73.949,64,91,15,0,57,0,1731], + [72.697,73.115,28,114,6,0,57,0,1731], + [72.697,72.907,45,96,1,0,57,0,1731], + [72.698,73.949,40,106,17,0,57,0,1731], + [72.698,73.949,68,84,15,1,57,0,1731], + [72.698,73.532,74,89,3,0,57,0,1731], + [72.698,73.949,45,83,18,0,57,0,1731], + [72.699,72.907,40,105,5,0,57,0,1731], + [72.699,72.907,37,116,16,0,57,0,1731], + [72.7,72.907,52,110,4,0,57,0,1731], + [72.7,73.949,50,88,8,0,57,0,1731], + [72.7,73.949,62,88,7,0,57,0,1731], + [72.7,73.949,59,73,13,2,57,0,1731], + [72.702,73.949,56,78,13,1,57,0,1731], + [72.703,73.949,71,88,15,2,57,0,1731], + [72.704,73.532,77,95,2,0,57,0,1731], + [72.704,73.949,52,77,13,0,57,0,1731], + [72.704,73.949,28,97,11,0,57,0,1731], + [72.704,73.949,56,89,8,1,57,0,1731], + [72.903,73.115,40,76,16,0,57,0.5,1736], + [72.905,73.115,80,69,14,0,57,0.5,1736], + [72.908,73.115,45,94,1,0,57,0.5,1736], + [72.909,73.115,40,69,5,0,57,0.5,1736], + [72.91,73.115,52,77,4,0,57,0.5,1736], + [73.111,73.324,45,95,1,0,57,1,1741], + [73.114,73.324,59,83,4,0,57,1,1741], + [73.115,73.324,47,87,5,0,57,1,1741], + [73.116,73.532,28,84,6,0,57,1,1741], + [73.117,73.324,40,82,16,0,57,1,1741], + [73.117,73.324,83,72,14,0,57,1,1741], + [73.323,73.532,45,97,1,0,57,1.5,1746], + [73.323,73.532,40,105,5,0,57,1.5,1746], + [73.323,73.532,88,86,14,0,57,1.5,1746], + [73.325,73.532,52,105,4,0,57,1.5,1746], + [73.326,73.532,38,111,16,0,57,1.5,1746], + [73.519,73.941,68,87,0,0,57,2,1750], + [73.521,73.941,77,89,0,2,57,2,1750], + [73.523,73.941,74,88,0,1,57,2,1751], + [73.527,73.949,28,94,6,0,57,2,1751], + [73.529,73.74,45,97,1,0,57,2,1751], + [73.53,73.74,40,81,16,0,57,2,1751], + [73.531,73.74,47,77,5,0,57,2,1751], + [73.531,73.949,74,91,3,0,57,2,1751], + [73.532,73.949,77,94,2,0,57,2,1751], + [73.533,73.74,83,62,14,0,57,2,1751], + [73.535,73.74,59,79,4,0,57,2,1751], + [73.733,73.949,52,83,5,0,57,2.5,1756], + [73.738,73.949,42,95,16,0,57,2.5,1756], + [73.739,73.949,45,95,1,0,57,2.5,1756], + [73.742,73.949,64,87,4,0,57,2.5,1756], + [73.746,73.949,80,70,14,0,57,2.5,1756], + [73.933,75.191,72,85,0,1,58,0,1760], + [73.938,75.191,69,91,0,0,58,0,1760], + [73.941,75.191,76,85,0,2,58,0,1761], + [73.943,74.157,45,93,1,0,58,0,1761], + [73.944,75.199,72,89,15,1,58,0,1761], + [73.944,75.199,60,90,7,0,58,0,1761], + [73.944,75.199,76,91,2,0,58,0,1761], + [73.944,74.365,45,91,18,0,58,0,1761], + [73.944,75.199,60,80,13,1,58,0,1761], + [73.946,75.199,72,87,3,0,58,0,1761], + [73.946,74.157,81,87,14,0,58,0,1761], + [73.946,75.199,69,83,15,0,58,0,1761], + [73.948,74.157,45,109,5,0,58,0,1761], + [73.948,75.199,76,89,15,2,58,0,1761], + [73.95,75.199,33,101,11,0,58,0,1761], + [73.95,75.199,57,74,13,0,58,0,1761], + [73.95,75.199,52,88,8,1,58,0,1761], + [73.95,74.157,57,101,4,0,58,0,1761], + [73.951,75.199,48,92,8,0,58,0,1761], + [73.951,75.199,64,82,13,2,58,0,1761], + [73.951,74.157,36,123,16,0,58,0,1761], + [73.954,74.365,33,107,6,0,58,0,1761], + [73.954,75.199,64,90,7,1,58,0,1761], + [73.955,75.199,40,108,17,0,58,0,1761], + [74.151,74.365,40,75,16,0,58,0.5,1765], + [74.152,74.365,84,66,14,0,58,0.5,1766], + [74.156,74.365,57,71,4,0,58,0.5,1766], + [74.157,74.365,45,74,5,0,58,0.5,1766], + [74.16,74.365,45,103,1,0,58,0.5,1766], + [74.359,74.574,45,97,1,0,58,1,1770], + [74.361,74.574,52,82,5,0,58,1,1770], + [74.362,74.574,64,80,4,0,58,1,1771], + [74.362,74.574,88,65,14,0,58,1,1771], + [74.363,74.574,45,94,18,0,58,1,1771], + [74.365,74.782,33,86,6,0,58,1,1771], + [74.365,74.574,40,74,16,0,58,1,1771], + [74.572,74.782,57,102,4,0,58,1.5,1776], + [74.575,74.782,45,96,1,0,58,1.5,1776], + [74.575,74.782,45,92,18,0,58,1.5,1776], + [74.575,74.782,45,102,5,0,58,1.5,1776], + [74.577,74.782,38,113,16,0,58,1.5,1776], + [74.58,74.782,93,88,14,0,58,1.5,1776], + [74.779,74.99,40,78,16,0,58,2,1780], + [74.779,74.99,88,68,14,0,58,2,1780], + [74.782,74.99,64,77,4,0,58,2,1781], + [74.783,74.99,52,76,5,0,58,2,1781], + [74.783,75.199,45,86,18,0,58,2,1781], + [74.784,75.199,33,93,6,0,58,2,1781], + [74.784,74.99,45,98,1,0,58,2,1781], + [74.984,75.199,69,88,4,0,58,2.5,1785], + [74.989,75.199,40,85,16,0,58,2.5,1785], + [74.991,75.199,84,65,14,0,58,2.5,1785], + [74.993,75.199,57,86,5,0,58,2.5,1786], + [74.994,75.199,45,97,1,0,58,2.5,1786], + [75.189,76.024,65,71,0,0,59,0,1790], + [75.192,76.024,74,76,0,1,59,0,1790], + [75.195,75.407,38,68,1,0,59,0,1790], + [75.196,76.449,40,109,17,0,59,0,1790], + [75.196,76.449,38,68,9,0,59,0,1790], + [75.196,75.407,74,86,14,0,59,0,1790], + [75.196,76.449,65,77,7,1,59,0,1790], + [75.196,76.449,26,95,11,0,59,0,1790], + [75.197,75.407,50,102,4,0,59,0,1790], + [75.197,76.449,62,86,15,0,59,0,1790], + [75.197,75.615,26,112,6,0,59,0,1790], + [75.197,76.449,69,83,15,2,59,0,1790], + [75.197,76.449,62,78,7,0,59,0,1790], + [75.197,76.032,74,70,2,0,59,0,1790], + [75.198,76.032,65,71,3,0,59,0,1790], + [75.198,76.449,33,118,10,1,59,0,1790], + [75.198,76.449,49,103,21,0,59,0,1790], + [75.198,76.449,26,118,10,0,59,0,1790], + [75.199,76.449,53,85,13,1,59,0,1790], + [75.199,75.407,38,103,5,0,59,0,1790], + [75.2,75.407,37,115,16,0,59,0,1790], + [75.201,76.449,38,120,10,2,59,0,1790], + [75.203,76.449,50,79,13,0,59,0,1791], + [75.204,76.449,57,76,13,2,59,0,1791], + [75.205,75.407,45,74,1,1,59,0,1791], + [75.205,76.449,65,85,15,1,59,0,1791], + [75.402,75.615,50,79,4,0,59,0.5,1795], + [75.406,75.615,38,71,1,0,59,0.5,1795], + [75.407,75.615,40,78,16,0,59,0.5,1795], + [75.408,75.615,38,70,5,0,59,0.5,1795], + [75.409,75.615,77,70,14,0,59,0.5,1795], + [75.41,75.615,45,67,1,1,59,0.5,1795], + [75.613,75.824,40,84,16,0,59,1,1800], + [75.616,75.824,81,73,14,0,59,1,1800], + [75.618,75.824,45,64,1,1,59,1,1800], + [75.618,75.824,57,83,4,0,59,1,1800], + [75.618,75.824,45,78,5,0,59,1,1800], + [75.618,75.824,38,66,1,0,59,1,1800], + [75.618,76.032,26,87,6,0,59,1,1800], + [75.818,76.032,38,90,5,0,59,1.5,1805], + [75.819,76.032,50,98,4,0,59,1.5,1805], + [75.823,76.032,38,65,1,0,59,1.5,1805], + [75.824,76.032,45,67,1,1,59,1.5,1805], + [75.828,76.032,86,90,14,0,59,1.5,1805], + [75.83,76.032,38,108,16,0,59,1.5,1805], + [76.022,76.232,72,69,0,1,59,2,1810], + [76.023,76.232,64,78,0,0,59,2,1810], + [76.026,76.449,26,95,6,0,59,2,1810], + [76.027,76.24,81,69,14,0,59,2,1810], + [76.03,76.24,40,77,16,0,59,2,1810], + [76.031,76.24,72,69,2,0,59,2,1810], + [76.032,76.24,57,73,4,0,59,2,1810], + [76.032,76.24,38,63,1,0,59,2,1810], + [76.033,76.24,45,79,5,0,59,2,1810], + [76.035,76.24,45,66,1,1,59,2,1810], + [76.037,76.24,64,68,3,0,59,2,1810], + [76.225,76.441,62,75,0,0,59,2.5,1815], + [76.23,76.441,71,80,0,1,59,2.5,1815], + [76.237,76.449,62,70,3,0,59,2.5,1815], + [76.238,76.449,42,100,16,0,59,2.5,1815], + [76.238,76.449,38,68,1,0,59,2.5,1815], + [76.24,76.449,45,71,1,1,59,2.5,1815], + [76.24,76.449,71,78,2,0,59,2.5,1815], + [76.241,76.449,77,75,14,0,59,2.5,1815], + [76.242,76.449,50,80,5,0,59,2.5,1815], + [76.245,76.449,62,87,4,0,59,2.5,1815], + [76.435,77.274,69,81,0,2,60,0,1820], + [76.44,77.274,66,79,0,1,60,0,1820], + [76.443,77.699,27,98,11,0,60,0,1820], + [76.444,77.274,60,77,0,0,60,0,1820], + [76.445,77.282,69,76,2,0,60,0,1820], + [76.445,77.699,63,91,15,0,60,0,1820], + [76.446,76.657,36,125,16,0,60,0,1820], + [76.446,77.699,40,107,17,0,60,0,1820], + [76.446,77.282,66,76,3,0,60,0,1820], + [76.447,76.657,39,103,5,0,60,0,1820], + [76.447,77.699,54,85,13,1,60,0,1820], + [76.448,76.657,45,73,1,1,60,0,1820], + [76.449,77.699,66,87,15,1,60,0,1820], + [76.45,77.699,60,71,7,0,60,0,1820], + [76.45,77.699,57,85,13,2,60,0,1820], + [76.45,76.865,27,113,6,0,60,0,1820], + [76.451,76.657,39,70,1,0,60,0,1820], + [76.451,77.699,66,75,7,1,60,0,1820], + [76.451,77.699,51,83,13,0,60,0,1820], + [76.451,76.657,75,91,14,0,60,0,1820], + [76.452,77.699,39,72,9,0,60,0,1820], + [76.454,77.699,69,92,15,2,60,0,1820], + [76.454,76.657,51,103,4,0,60,0,1820], + [76.657,76.865,51,74,4,0,60,0.5,1825], + [76.657,76.865,78,68,14,0,60,0.5,1825], + [76.658,76.865,39,75,1,0,60,0.5,1825], + [76.658,76.865,39,71,5,0,60,0.5,1825], + [76.66,76.865,40,75,16,0,60,0.5,1825], + [76.66,76.865,45,67,1,1,60,0.5,1825], + [76.862,77.074,57,83,4,0,60,1,1830], + [76.862,77.282,27,82,6,0,60,1,1830], + [76.864,77.074,45,70,1,1,60,1,1830], + [76.865,77.074,39,69,1,0,60,1,1830], + [76.868,77.074,40,77,16,0,60,1,1830], + [76.869,77.074,45,82,5,0,60,1,1830], + [76.87,77.074,81,71,14,0,60,1,1830], + [77.069,77.282,45,68,1,1,60,1.5,1835], + [77.071,77.282,39,72,1,0,60,1.5,1835], + [77.072,77.282,38,112,16,0,60,1.5,1835], + [77.072,77.282,51,101,4,0,60,1.5,1835], + [77.073,77.282,87,90,14,0,60,1.5,1835], + [77.075,77.282,39,96,5,0,60,1.5,1835], + [77.275,77.691,69,74,0,1,60,2,1840], + [77.28,77.691,60,68,0,0,60,2,1840], + [77.281,77.49,39,67,1,0,60,2,1840], + [77.283,77.49,81,67,14,0,60,2,1840], + [77.284,77.49,40,75,16,0,60,2,1840], + [77.284,77.699,60,73,3,0,60,2,1840], + [77.284,77.49,45,80,5,0,60,2,1840], + [77.285,77.699,27,89,6,0,60,2,1840], + [77.285,77.49,57,76,4,0,60,2,1840], + [77.285,77.699,69,73,2,0,60,2,1840], + [77.286,77.49,45,75,1,1,60,2,1840], + [77.487,77.699,78,69,14,0,60,2.5,1845], + [77.488,77.699,63,83,4,0,60,2.5,1845], + [77.49,77.699,51,86,5,0,60,2.5,1845], + [77.49,77.699,45,66,1,1,60,2.5,1845], + [77.491,77.699,40,84,16,0,60,2.5,1845], + [77.491,77.699,39,67,1,0,60,2.5,1845], + [77.689,78.107,69,78,0,1,61,0,1850], + [77.689,78.107,60,73,0,0,61,0,1850], + [77.694,78.949,56,79,13,1,61,0,1850], + [77.696,77.907,76,94,14,0,61,0,1850], + [77.696,78.115,28,111,6,0,61,0,1850], + [77.697,78.949,28,95,11,0,61,0,1850], + [77.697,78.532,64,72,7,1,61,0,1850], + [77.697,77.907,45,70,1,1,61,0,1850], + [77.698,78.949,68,84,15,1,61,0,1850], + [77.698,77.907,52,101,4,0,61,0,1850], + [77.699,78.532,60,75,7,0,61,0,1850], + [77.699,78.949,40,116,17,0,61,0,1850], + [77.699,78.115,69,73,2,0,61,0,1850], + [77.699,77.907,37,124,16,0,61,0,1850], + [77.7,77.907,40,67,1,0,61,0,1850], + [77.7,78.949,52,82,13,0,61,0,1850], + [77.7,78.949,64,87,15,0,61,0,1850], + [77.7,78.949,40,76,9,0,61,0,1850], + [77.701,78.949,59,78,13,2,61,0,1850], + [77.701,78.949,71,90,15,2,61,0,1850], + [77.702,78.115,60,71,3,0,61,0,1850], + [77.702,78.115,52,92,18,0,61,0,1850], + [77.703,77.907,40,100,5,0,61,0,1850], + [77.705,78.949,41,92,23,0,61,0,1850], + [77.901,78.115,40,73,16,0,61,0.5,1855], + [77.905,78.115,45,64,1,1,61,0.5,1855], + [77.906,78.115,40,76,5,0,61,0.5,1855], + [77.906,78.115,52,72,4,0,61,0.5,1855], + [77.906,78.115,40,67,1,0,61,0.5,1855], + [77.911,78.115,80,70,14,0,61,0.5,1855], + [78.104,78.524,64,76,0,0,61,1,1860], + [78.106,78.524,72,78,0,1,61,1,1860], + [78.11,78.324,40,67,1,0,61,1,1860], + [78.111,78.532,72,72,2,0,61,1,1860], + [78.113,78.532,64,76,3,0,61,1,1860], + [78.114,78.532,28,82,6,0,61,1,1860], + [78.115,78.324,47,82,5,0,61,1,1860], + [78.116,78.324,59,78,4,0,61,1,1860], + [78.116,78.324,40,84,16,0,61,1,1860], + [78.119,78.324,45,66,1,1,61,1,1860], + [78.12,78.324,83,68,14,0,61,1,1860], + [78.322,78.532,40,68,1,0,61,1.5,1865], + [78.322,78.532,38,104,16,0,61,1.5,1865], + [78.322,78.532,52,99,4,0,61,1.5,1865], + [78.324,78.532,45,67,1,1,61,1.5,1865], + [78.326,78.532,40,99,5,0,61,1.5,1865], + [78.328,78.532,88,90,14,0,61,1.5,1865], + [78.521,78.941,62,79,0,0,61,2,1870], + [78.525,78.74,40,65,1,0,61,2,1870], + [78.526,78.941,71,72,0,1,61,2,1870], + [78.527,78.949,62,76,7,1,61,2,1870], + [78.528,78.74,83,66,14,0,61,2,1870], + [78.529,78.949,62,70,3,0,61,2,1870], + [78.529,78.74,44,68,1,1,61,2,1870], + [78.531,78.949,71,75,2,0,61,2,1870], + [78.531,78.949,59,72,7,0,61,2,1870], + [78.532,78.949,52,87,18,0,61,2,1870], + [78.532,78.74,59,82,4,0,61,2,1870], + [78.533,78.74,40,78,16,0,61,2,1870], + [78.534,78.949,28,89,6,0,61,2,1870], + [78.534,78.74,47,72,5,0,61,2,1870], + [78.738,78.949,42,98,16,0,61,2.5,1875], + [78.743,78.949,80,68,14,0,61,2.5,1875], + [78.744,78.949,40,68,1,0,61,2.5,1875], + [78.744,78.949,52,86,5,0,61,2.5,1875], + [78.747,78.949,64,86,4,0,61,2.5,1875], + [78.748,78.949,44,71,1,1,61,2.5,1875], + [78.939,80.191,69,76,0,1,62,0,1880], + [78.943,79.157,45,68,1,1,62,0,1880], + [78.944,80.191,60,74,0,0,62,0,1880], + [78.944,80.199,69,75,2,0,62,0,1880], + [78.945,80.199,60,81,3,0,62,0,1880], + [78.945,80.199,33,69,9,0,62,0,1880], + [78.946,79.157,57,103,4,0,62,0,1880], + [78.948,80.199,33,101,11,0,62,0,1880], + [78.948,80.199,48,76,8,0,62,0,1880], + [78.948,79.157,45,105,5,0,62,0,1880], + [78.949,80.199,40,111,17,0,62,0,1880], + [78.949,79.157,33,74,1,0,62,0,1880], + [78.949,80.199,52,72,8,1,62,0,1880], + [78.95,80.199,72,81,15,1,62,0,1880], + [78.951,80.199,57,81,13,0,62,0,1880], + [78.951,80.199,45,86,18,0,62,0,1880], + [78.951,79.365,33,111,6,0,62,0,1880], + [78.951,80.199,60,80,13,1,62,0,1880], + [78.952,80.199,60,75,7,1,62,0,1880], + [78.952,79.157,40,103,19,0,62,0,1880], + [78.952,80.199,76,80,15,2,62,0,1880], + [78.952,79.157,81,83,14,0,62,0,1880], + [78.952,80.199,64,81,13,2,62,0,1880], + [78.953,80.199,57,72,7,0,62,0,1880], + [78.953,80.199,69,78,15,0,62,0,1880], + [78.955,79.157,36,126,16,0,62,0,1880], + [79.153,79.365,84,69,14,0,62,0.5,1885], + [79.154,79.365,45,73,5,0,62,0.5,1885], + [79.154,79.365,45,71,1,0,62,0.5,1885], + [79.157,79.365,40,78,16,0,62,0.5,1885], + [79.157,79.365,42,110,19,0,62,0.5,1885], + [79.159,79.365,57,75,4,0,62,0.5,1885], + [79.359,79.574,40,78,16,0,62,1,1889], + [79.359,79.574,52,77,5,0,62,1,1890], + [79.365,79.574,45,67,1,0,62,1,1890], + [79.366,79.782,33,86,6,0,62,1,1890], + [79.367,79.574,40,110,19,0,62,1,1890], + [79.369,79.574,88,65,14,0,62,1,1890], + [79.37,79.574,64,80,4,0,62,1,1890], + [79.569,79.782,45,92,5,0,62,1.5,1895], + [79.57,79.782,57,105,4,0,62,1.5,1895], + [79.574,79.782,45,65,1,0,62,1.5,1895], + [79.575,79.782,38,110,16,0,62,1.5,1895], + [79.575,79.782,93,88,14,0,62,1.5,1895], + [79.576,79.782,42,120,19,0,62,1.5,1895], + [79.778,79.99,52,73,5,0,62,2,1899], + [79.779,79.99,88,68,14,0,62,2,1900], + [79.781,79.99,45,70,1,0,62,2,1900], + [79.781,79.99,64,73,4,0,62,2,1900], + [79.782,79.99,40,118,19,0,62,2,1900], + [79.783,80.199,33,95,6,0,62,2,1900], + [79.786,79.99,40,73,16,0,62,2,1900], + [79.984,80.199,69,85,4,0,62,2.5,1904], + [79.987,80.199,42,127,19,0,62,2.5,1904], + [79.988,80.199,57,82,5,0,62,2.5,1904], + [79.99,80.199,45,69,1,0,62,2.5,1905], + [79.991,80.199,84,76,14,0,62,2.5,1905], + [79.991,80.199,40,84,16,0,62,2.5,1905], + [80.19,81.441,67,100,0,1,63,0,1909], + [80.193,81.441,70,102,0,2,63,0,1909], + [80.193,81.449,33,90,9,0,63,0,1909], + [80.194,81.449,33,91,11,0,63,0,1909], + [80.194,81.449,73,85,15,1,63,0,1909], + [80.195,81.449,73,97,2,0,63,0,1909], + [80.195,81.449,61,82,13,1,63,0,1909], + [80.196,81.441,64,107,0,0,63,0,1909], + [80.196,81.441,73,105,0,3,63,0,1909], + [80.196,81.449,70,88,3,0,63,0,1909], + [80.197,80.407,37,119,16,0,63,0,1909], + [80.198,81.449,57,81,13,0,63,0,1909], + [80.198,81.449,40,107,17,0,63,0,1909], + [80.199,80.407,45,106,5,0,63,0,1909], + [80.199,81.449,40,114,10,1,63,0,1909], + [80.199,80.407,45,79,1,0,63,0,1910], + [80.2,81.449,49,119,21,0,63,0,1910], + [80.2,81.449,33,119,10,0,63,0,1910], + [80.2,81.449,45,111,10,2,63,0,1910], + [80.2,81.449,76,84,15,2,63,0,1910], + [80.2,81.449,49,98,8,0,63,0,1910], + [80.201,81.449,64,89,7,0,63,0,1910], + [80.201,80.407,57,104,4,0,63,0,1910], + [80.202,81.449,67,92,7,1,63,0,1910], + [80.202,81.449,69,84,15,0,63,0,1910], + [80.202,81.449,36,126,22,0,63,0,1910], + [80.202,81.449,64,78,13,2,63,0,1910], + [80.203,81.449,45,120,18,0,63,0,1910], + [80.205,80.615,33,104,6,0,63,0,1910], + [80.205,80.407,81,93,14,0,63,0,1910], + [80.206,81.449,55,96,8,1,63,0,1910], + [80.402,80.615,45,85,1,0,63,0.5,1914], + [80.405,80.615,57,78,4,0,63,0.5,1914], + [80.405,80.615,85,69,14,0,63,0.5,1914], + [80.406,80.615,45,67,5,0,63,0.5,1914], + [80.409,80.615,40,74,16,0,63,0.5,1915], + [80.612,81.032,33,85,6,0,63,1,1919], + [80.613,80.824,88,66,14,0,63,1,1919], + [80.614,80.824,64,84,4,0,63,1,1919], + [80.617,80.824,45,79,1,0,63,1,1919], + [80.618,80.824,52,76,5,0,63,1,1919], + [80.618,80.824,40,86,16,0,63,1,1919], + [80.821,81.032,38,109,16,0,63,1.5,1924], + [80.822,81.032,93,91,14,0,63,1.5,1924], + [80.823,81.032,45,97,5,0,63,1.5,1924], + [80.825,81.032,57,103,4,0,63,1.5,1924], + [80.826,81.032,45,84,1,0,63,1.5,1924], + [81.029,81.24,88,67,14,0,63,2,1929], + [81.03,81.24,45,88,1,0,63,2,1929], + [81.03,81.24,40,77,16,0,63,2,1929], + [81.031,81.24,64,72,4,0,63,2,1929], + [81.037,81.449,33,89,6,0,63,2,1929], + [81.037,81.24,52,75,5,0,63,2,1929], + [81.24,81.449,42,100,16,0,63,2.5,1934], + [81.24,81.449,45,83,1,0,63,2.5,1934], + [81.241,81.449,85,66,14,0,63,2.5,1934], + [81.243,81.449,69,83,4,0,63,2.5,1934], + [81.243,81.449,57,76,5,0,63,2.5,1934], + [81.44,82.274,65,84,0,0,64,0,1939], + [81.441,82.274,69,92,0,1,64,0,1939], + [81.444,81.865,26,112,6,0,64,0,1939], + [81.445,82.699,65,94,7,1,64,0,1939], + [81.445,82.699,50,85,8,0,64,0,1939], + [81.445,82.699,53,92,8,1,64,0,1939], + [81.446,81.657,45,86,1,0,64,0,1939], + [81.446,82.699,69,88,15,2,64,0,1939], + [81.447,82.699,40,105,17,0,64,0,1939], + [81.447,82.274,74,92,0,2,64,0,1939], + [81.447,82.282,69,86,3,0,64,0,1939], + [81.447,82.282,74,86,2,0,64,0,1939], + [81.448,82.699,62,88,15,0,64,0,1939], + [81.449,82.699,62,93,7,0,64,0,1939], + [81.45,82.699,50,77,13,0,64,0,1939], + [81.45,82.699,57,82,13,2,64,0,1939], + [81.45,81.657,36,123,16,0,64,0,1939], + [81.45,81.865,45,101,18,0,64,0,1939], + [81.451,82.699,26,95,11,0,64,0,1939], + [81.451,81.657,38,109,5,0,64,0,1939], + [81.452,81.657,50,104,4,0,64,0,1939], + [81.452,81.657,74,86,14,0,64,0,1939], + [81.453,82.699,53,83,13,1,64,0,1939], + [81.454,82.699,65,85,15,1,64,0,1939], + [81.656,81.865,40,73,16,0,64,0.5,1944], + [81.656,81.865,77,71,14,0,64,0.5,1944], + [81.657,81.865,50,77,4,0,64,0.5,1944], + [81.657,81.865,38,75,5,0,64,0.5,1944], + [81.659,81.865,45,85,1,0,64,0.5,1944], + [81.861,82.074,40,76,16,0,64,1,1949], + [81.866,82.074,45,80,5,0,64,1,1949], + [81.866,82.074,45,81,1,0,64,1,1949], + [81.866,82.074,81,67,14,0,64,1,1949], + [81.868,82.282,26,81,6,0,64,1,1949], + [81.869,82.074,57,77,4,0,64,1,1949], + [82.07,82.282,38,109,16,0,64,1.5,1954], + [82.073,82.282,45,86,1,0,64,1.5,1954], + [82.073,82.282,86,87,14,0,64,1.5,1954], + [82.074,82.282,38,92,5,0,64,1.5,1954], + [82.075,82.282,50,97,4,0,64,1.5,1954], + [82.267,82.482,76,92,0,1,64,2,1959], + [82.275,82.482,73,90,0,0,64,2,1959], + [82.28,82.49,45,84,1,0,64,2,1959], + [82.28,82.49,81,67,14,0,64,2,1959], + [82.281,82.49,40,77,16,0,64,2,1959], + [82.281,82.49,45,77,5,0,64,2,1959], + [82.283,82.49,57,79,4,0,64,2,1959], + [82.284,82.49,76,95,2,0,64,2,1959], + [82.284,82.699,26,89,6,0,64,2,1959], + [82.284,82.49,73,94,3,0,64,2,1959], + [82.482,82.691,77,95,0,1,64,2.5,1964], + [82.484,82.691,74,92,0,0,64,2.5,1964], + [82.485,82.699,45,86,1,0,64,2.5,1964], + [82.489,82.699,62,79,4,0,64,2.5,1964], + [82.49,82.699,74,94,3,0,64,2.5,1964], + [82.49,82.699,40,90,16,0,64,2.5,1964], + [82.492,82.699,77,91,2,0,64,2.5,1964], + [82.492,82.699,50,79,5,0,64,2.5,1964], + [82.493,82.699,77,70,14,0,64,2.5,1964], + [82.689,83.524,74,98,0,0,65,0,1969], + [82.69,83.524,77,99,0,1,65,0,1969], + [82.693,82.907,50,103,4,0,65,0,1969], + [82.695,82.907,45,79,1,0,65,0,1969], + [82.695,83.115,45,104,18,0,65,0,1969], + [82.696,83.949,53,81,13,1,65,0,1969], + [82.696,83.949,40,114,17,0,65,0,1969], + [82.697,83.949,57,79,13,2,65,0,1969], + [82.697,83.532,74,88,3,0,65,0,1969], + [82.697,82.907,37,121,16,0,65,0,1969], + [82.698,83.949,62,91,7,0,65,0,1969], + [82.698,83.949,65,86,7,1,65,0,1969], + [82.698,83.115,26,105,6,0,65,0,1969], + [82.699,83.949,62,87,15,0,65,0,1969], + [82.699,83.949,33,89,9,0,65,0,1969], + [82.699,82.907,38,99,5,0,65,0,1969], + [82.699,82.907,74,86,14,0,65,0,1969], + [82.7,83.949,53,89,8,1,65,0,1969], + [82.7,83.949,50,89,8,0,65,0,1969], + [82.7,83.949,26,102,11,0,65,0,1969], + [82.701,83.949,50,83,13,0,65,0,1969], + [82.701,83.949,65,88,15,1,65,0,1969], + [82.702,83.949,69,88,15,2,65,0,1969], + [82.702,83.532,77,91,2,0,65,0,1969], + [82.901,83.115,77,69,14,0,65,0.5,1974], + [82.906,83.115,50,73,4,0,65,0.5,1974], + [82.908,83.115,38,75,5,0,65,0.5,1974], + [82.91,83.115,40,78,16,0,65,0.5,1974], + [82.912,83.115,45,78,1,0,65,0.5,1974], + [83.11,83.324,45,80,5,0,65,1,1979], + [83.111,83.324,45,84,1,0,65,1,1979], + [83.113,83.324,45,113,18,0,65,1,1979], + [83.113,83.324,81,65,14,0,65,1,1979], + [83.114,83.324,57,86,4,0,65,1,1979], + [83.114,83.532,26,82,6,0,65,1,1979], + [83.117,83.324,40,83,16,0,65,1,1979], + [83.319,83.532,86,85,14,0,65,1.5,1984], + [83.324,83.532,45,83,1,0,65,1.5,1984], + [83.324,83.532,50,97,4,0,65,1.5,1984], + [83.325,83.532,38,97,5,0,65,1.5,1984], + [83.327,83.532,45,108,18,0,65,1.5,1984], + [83.33,83.532,38,113,16,0,65,1.5,1984], + [83.528,83.941,77,90,0,1,65,2,1989], + [83.529,83.74,81,69,14,0,65,2,1989], + [83.529,83.74,45,73,5,0,65,2,1989], + [83.529,83.941,74,83,0,0,65,2,1989], + [83.53,83.74,45,84,1,0,65,2,1989], + [83.531,83.949,77,89,2,0,65,2,1989], + [83.531,83.74,57,74,4,0,65,2,1989], + [83.533,83.949,26,90,6,0,65,2,1989], + [83.534,83.949,74,91,3,0,65,2,1989], + [83.535,83.74,40,81,16,0,65,2,1989], + [83.538,83.949,45,107,18,0,65,2,1989], + [83.734,83.949,45,81,1,0,65,2.5,1994], + [83.736,83.949,77,72,14,0,65,2.5,1994], + [83.737,83.949,50,79,5,0,65,2.5,1994], + [83.74,83.949,62,86,4,0,65,2.5,1994], + [83.743,83.949,42,96,16,0,65,2.5,1994], + [83.937,85.191,74,90,0,0,66,0,1998], + [83.942,85.191,77,90,0,1,66,0,1999], + [83.943,84.157,36,126,16,0,66,0,1999], + [83.943,85.199,74,91,3,0,66,0,1999], + [83.944,84.157,46,78,1,0,66,0,1999], + [83.945,85.199,46,118,10,2,66,0,1999], + [83.945,85.199,34,96,9,0,66,0,1999], + [83.947,85.199,40,111,17,0,66,0,1999], + [83.947,84.157,46,100,5,0,66,0,1999], + [83.947,84.157,82,91,14,0,66,0,1999], + [83.948,85.199,53,90,8,1,66,0,1999], + [83.949,85.199,58,81,13,0,66,0,1999], + [83.949,85.199,65,79,13,2,66,0,1999], + [83.949,85.199,62,79,13,1,66,0,1999], + [83.949,85.199,34,95,11,0,66,0,1999], + [83.95,85.199,65,98,7,1,66,0,1999], + [83.95,85.199,77,90,15,2,66,0,1999], + [83.95,85.199,62,92,7,0,66,0,1999], + [83.95,85.199,70,86,15,0,66,0,1999], + [83.951,85.199,77,86,2,0,66,0,1999], + [83.952,85.199,50,92,8,0,66,0,1999], + [83.952,84.157,58,109,4,0,66,0,1999], + [83.952,84.365,34,108,6,0,66,0,1999], + [83.953,85.199,49,100,21,0,66,0,1999], + [83.953,85.199,34,118,10,0,66,0,1999], + [83.953,85.199,74,86,15,1,66,0,1999], + [83.954,85.199,41,115,10,1,66,0,1999], + [84.153,84.365,86,63,14,0,66,0.5,2004], + [84.154,84.365,40,79,16,0,66,0.5,2004], + [84.155,84.365,58,70,4,0,66,0.5,2004], + [84.157,84.365,46,78,5,0,66,0.5,2004], + [84.163,84.365,46,82,1,0,66,0.5,2004], + [84.363,84.782,34,83,6,0,66,1,2009], + [84.364,84.574,89,66,14,0,66,1,2009], + [84.365,84.574,65,86,4,0,66,1,2009], + [84.367,84.574,53,77,5,0,66,1,2009], + [84.368,84.574,40,83,16,0,66,1,2009], + [84.371,84.574,46,84,1,0,66,1,2009], + [84.567,84.782,46,98,5,0,66,1.5,2014], + [84.568,84.782,58,101,4,0,66,1.5,2014], + [84.57,84.782,38,114,16,0,66,1.5,2014], + [84.571,84.782,94,88,14,0,66,1.5,2014], + [84.575,84.782,46,88,1,0,66,1.5,2014], + [84.776,84.99,40,81,16,0,66,2,2018], + [84.781,84.99,53,77,5,0,66,2,2019], + [84.782,84.99,46,82,1,0,66,2,2019], + [84.783,84.99,89,69,14,0,66,2,2019], + [84.784,84.99,65,76,4,0,66,2,2019], + [84.784,85.199,34,95,6,0,66,2,2019], + [84.985,85.199,40,86,16,0,66,2.5,2023], + [84.988,85.199,70,88,4,0,66,2.5,2024], + [84.988,85.199,86,65,14,0,66,2.5,2024], + [84.991,85.199,58,86,5,0,66,2.5,2024], + [84.994,85.199,46,89,1,0,66,2.5,2024], + [85.191,86.024,75,95,0,1,67,0,2028], + [85.193,86.024,67,93,0,0,67,0,2028], + [85.194,85.407,39,102,5,0,67,0,2028], + [85.194,85.407,46,88,1,0,67,0,2028], + [85.195,86.032,67,92,3,0,67,0,2028], + [85.196,86.449,67,83,15,1,67,0,2028], + [85.196,85.407,51,102,4,0,67,0,2028], + [85.197,85.407,37,117,16,0,67,0,2028], + [85.197,86.449,67,96,7,1,67,0,2029], + [85.198,85.407,75,89,14,0,67,0,2029], + [85.198,86.449,51,79,13,0,67,0,2029], + [85.198,86.032,75,94,2,0,67,0,2029], + [85.198,86.449,55,79,13,1,67,0,2029], + [85.198,86.449,55,94,8,1,67,0,2029], + [85.198,86.449,63,97,7,0,67,0,2029], + [85.198,86.449,51,100,8,0,67,0,2029], + [85.2,86.449,63,82,15,0,67,0,2029], + [85.2,86.449,40,109,17,0,67,0,2029], + [85.2,86.449,34,89,9,0,67,0,2029], + [85.201,85.615,27,105,6,0,67,0,2029], + [85.201,86.449,27,94,11,0,67,0,2029], + [85.201,86.449,70,81,15,2,67,0,2029], + [85.201,86.449,58,85,13,2,67,0,2029], + [85.405,85.615,39,69,5,0,67,0.5,2033], + [85.405,85.615,79,68,14,0,67,0.5,2033], + [85.408,85.615,40,72,16,0,67,0.5,2034], + [85.411,85.615,51,77,4,0,67,0.5,2034], + [85.412,85.615,46,87,1,0,67,0.5,2034], + [85.614,85.824,58,81,4,0,67,1,2038], + [85.616,85.824,46,88,1,0,67,1,2038], + [85.617,85.824,40,86,16,0,67,1,2039], + [85.618,85.824,46,81,5,0,67,1,2039], + [85.619,86.032,27,82,6,0,67,1,2039], + [85.623,85.824,82,69,14,0,67,1,2039], + [85.823,86.032,38,111,16,0,67,1.5,2043], + [85.823,86.032,51,95,4,0,67,1.5,2043], + [85.827,86.032,39,103,5,0,67,1.5,2043], + [85.827,86.032,87,88,14,0,67,1.5,2043], + [85.827,86.032,46,90,1,0,67,1.5,2043], + [86.019,86.232,65,95,0,0,67,2,2048], + [86.022,86.232,74,98,0,1,67,2,2048], + [86.025,86.24,74,92,2,0,67,2,2048], + [86.03,86.24,65,97,3,0,67,2,2048], + [86.032,86.24,40,85,16,0,67,2,2048], + [86.032,86.24,46,90,1,0,67,2,2048], + [86.033,86.449,27,86,6,0,67,2,2048], + [86.035,86.24,46,77,5,0,67,2,2048], + [86.036,86.24,58,78,4,0,67,2,2048], + [86.038,86.24,82,69,14,0,67,2,2049], + [86.23,86.441,63,103,0,0,67,2.5,2053], + [86.233,86.441,72,98,0,1,67,2.5,2053], + [86.237,86.449,51,87,5,0,67,2.5,2053], + [86.239,86.449,42,97,16,0,67,2.5,2053], + [86.24,86.449,63,96,3,0,67,2.5,2053], + [86.242,86.449,63,89,4,0,67,2.5,2053], + [86.243,86.449,72,98,2,0,67,2.5,2053], + [86.244,86.449,79,69,14,0,67,2.5,2053], + [86.246,86.449,46,86,1,0,67,2.5,2053], + [86.438,87.274,70,96,0,2,68,0,2058], + [86.443,87.274,62,102,0,0,68,0,2058], + [86.443,87.274,65,104,0,1,68,0,2058], + [86.444,87.699,65,101,7,1,68,0,2058], + [86.446,87.699,58,85,13,0,68,0,2058], + [86.446,87.699,74,87,15,1,68,0,2058], + [86.446,87.282,70,97,2,0,68,0,2058], + [86.446,86.657,82,87,14,0,68,0,2058], + [86.447,86.657,36,127,16,0,68,0,2058], + [86.447,87.699,50,99,8,0,68,0,2058], + [86.447,87.699,77,85,15,2,68,0,2058], + [86.447,87.699,53,100,8,1,68,0,2058], + [86.448,87.699,65,81,13,2,68,0,2058], + [86.448,86.657,46,98,5,0,68,0,2058], + [86.448,86.865,34,110,6,0,68,0,2058], + [86.448,87.699,34,98,11,0,68,0,2058], + [86.449,87.699,40,105,17,0,68,0,2058], + [86.449,87.699,62,81,13,1,68,0,2058], + [86.449,87.699,34,99,9,0,68,0,2058], + [86.449,87.282,65,100,3,0,68,0,2058], + [86.45,86.657,58,101,4,0,68,0,2058], + [86.45,87.699,70,84,15,0,68,0,2058], + [86.451,87.699,62,100,7,0,68,0,2058], + [86.454,86.657,46,93,1,0,68,0,2058], + [86.657,86.865,46,95,1,0,68,0.5,2063], + [86.657,86.865,86,69,14,0,68,0.5,2063], + [86.659,86.865,40,72,16,0,68,0.5,2063], + [86.662,86.865,46,74,5,0,68,0.5,2063], + [86.662,86.865,58,75,4,0,68,0.5,2063], + [86.86,87.074,65,80,4,0,68,1,2068], + [86.865,87.074,53,78,5,0,68,1,2068], + [86.865,87.074,40,82,16,0,68,1,2068], + [86.866,87.074,89,73,14,0,68,1,2068], + [86.867,87.074,46,95,1,0,68,1,2068], + [86.867,87.282,34,85,6,0,68,1,2068], + [87.071,87.282,38,109,16,0,68,1.5,2073], + [87.072,87.282,94,89,14,0,68,1.5,2073], + [87.073,87.282,46,99,5,0,68,1.5,2073], + [87.076,87.282,58,100,4,0,68,1.5,2073], + [87.077,87.282,46,91,1,0,68,1.5,2073], + [87.27,87.691,62,104,0,0,68,2,2078], + [87.274,87.691,69,102,0,2,68,2,2078], + [87.276,87.691,65,95,0,1,68,2,2078], + [87.28,87.49,40,75,16,0,68,2,2078], + [87.281,87.699,69,101,2,0,68,2,2078], + [87.282,87.49,46,88,1,0,68,2,2078], + [87.283,87.49,65,77,4,0,68,2,2078], + [87.283,87.699,34,93,6,0,68,2,2078], + [87.283,87.699,65,103,3,0,68,2,2078], + [87.285,87.49,89,68,14,0,68,2,2078], + [87.29,87.49,53,73,5,0,68,2,2078], + [87.485,87.699,40,85,16,0,68,2.5,2083], + [87.487,87.699,70,84,4,0,68,2.5,2083], + [87.492,87.699,58,81,5,0,68,2.5,2083], + [87.495,87.699,46,93,1,0,68,2.5,2083], + [87.496,87.699,86,68,14,0,68,2.5,2083], + [87.693,88.524,65,106,0,1,69,0,2088], + [87.695,88.524,62,103,0,0,69,0,2088], + [87.695,88.115,28,111,6,0,69,0,2088], + [87.695,88.532,65,103,3,0,69,0,2088], + [87.695,88.949,35,106,9,0,69,0,2088], + [87.696,88.949,62,104,7,0,69,0,2088], + [87.696,88.949,64,87,15,0,69,0,2088], + [87.697,87.907,37,122,16,0,69,0,2088], + [87.697,88.524,68,106,0,2,69,0,2088], + [87.697,87.907,76,84,14,0,69,0,2088], + [87.697,88.949,65,100,7,1,69,0,2088], + [87.697,87.907,40,103,19,0,69,0,2088], + [87.698,88.949,59,85,13,2,69,0,2088], + [87.698,87.907,47,95,1,0,69,0,2088], + [87.698,87.907,40,96,5,0,69,0,2088], + [87.699,88.949,68,85,15,1,69,0,2088], + [87.699,88.949,71,86,15,2,69,0,2088], + [87.699,88.949,40,107,17,0,69,0,2088], + [87.7,88.532,68,102,2,0,69,0,2088], + [87.7,88.949,53,103,8,1,69,0,2088], + [87.7,88.949,28,96,11,0,69,0,2088], + [87.7,88.115,52,106,18,0,69,0,2088], + [87.7,88.949,50,98,8,0,69,0,2088], + [87.701,87.907,52,108,4,0,69,0,2088], + [87.701,88.949,56,81,13,1,69,0,2088], + [87.703,88.949,52,78,13,0,69,0,2088], + [87.904,88.115,80,66,14,0,69,0.5,2093], + [87.905,88.115,40,76,5,0,69,0.5,2093], + [87.906,88.115,40,78,16,0,69,0.5,2093], + [87.906,88.115,52,74,4,0,69,0.5,2093], + [87.907,88.115,42,109,19,0,69,0.5,2093], + [87.913,88.115,47,95,1,0,69,0.5,2093], + [88.111,88.532,28,84,6,0,69,1,2098], + [88.113,88.324,47,78,5,0,69,1,2098], + [88.114,88.324,40,112,19,0,69,1,2098], + [88.114,88.324,40,80,16,0,69,1,2098], + [88.114,88.324,52,106,18,0,69,1,2098], + [88.117,88.324,47,91,1,0,69,1,2098], + [88.118,88.324,83,69,14,0,69,1,2098], + [88.119,88.324,59,82,4,0,69,1,2098], + [88.318,88.532,38,112,16,0,69,1.5,2103], + [88.318,88.532,88,85,14,0,69,1.5,2103], + [88.322,88.532,52,102,4,0,69,1.5,2103], + [88.324,88.532,42,117,19,0,69,1.5,2103], + [88.325,88.532,52,105,18,0,69,1.5,2103], + [88.327,88.532,40,100,5,0,69,1.5,2103], + [88.327,88.532,47,97,1,0,69,1.5,2103], + [88.52,88.941,65,107,0,1,69,2,2108], + [88.52,88.941,62,107,0,0,69,2,2108], + [88.521,88.941,68,105,0,2,69,2,2108], + [88.529,88.949,65,104,3,0,69,2,2108], + [88.529,88.949,68,103,2,0,69,2,2108], + [88.529,88.74,47,69,5,0,69,2,2108], + [88.531,88.74,47,91,1,0,69,2,2108], + [88.531,88.949,52,105,18,0,69,2,2108], + [88.534,88.74,59,75,4,0,69,2,2108], + [88.534,88.74,40,78,16,0,69,2,2108], + [88.534,88.74,40,118,19,0,69,2,2108], + [88.534,88.949,28,97,6,0,69,2,2108], + [88.536,88.74,83,70,14,0,69,2,2108], + [88.735,88.949,42,127,19,0,69,2.5,2113], + [88.736,88.949,42,96,16,0,69,2.5,2113], + [88.739,88.949,64,83,4,0,69,2.5,2113], + [88.741,88.949,52,89,5,0,69,2.5,2113], + [88.742,88.949,80,70,14,0,69,2.5,2113], + [88.743,88.949,47,101,1,0,69,2.5,2113], + [88.935,89.774,69,116,0,2,70,0,2118], + [88.942,89.782,64,104,3,0,70,0,2118], + [88.944,89.774,64,120,0,1,70,0,2118], + [88.945,89.774,60,119,0,0,70,0,2118], + [88.945,89.782,64,122,7,1,70,0,2118], + [88.945,90.199,40,115,10,1,70,0,2118], + [88.945,90.199,45,114,10,2,70,0,2118], + [88.946,89.782,48,121,8,0,70,0,2118], + [88.947,89.782,52,124,8,1,70,0,2118], + [88.947,90.199,72,84,15,1,70,0,2118], + [88.947,90.199,69,89,15,0,70,0,2118], + [88.948,89.157,81,89,14,0,70,0,2118], + [88.948,90.199,76,79,15,2,70,0,2118], + [88.948,89.782,45,121,18,0,70,0,2118], + [88.948,90.199,57,81,13,0,70,0,2118], + [88.949,89.782,69,106,2,0,70,0,2118], + [88.949,90.199,33,119,10,0,70,0,2118], + [88.949,89.782,33,116,9,0,70,0,2118], + [88.949,90.199,55,125,21,0,70,0,2118], + [88.949,89.157,36,125,16,0,70,0,2118], + [88.95,89.157,57,98,4,0,70,0,2118], + [88.95,89.157,45,99,5,0,70,0,2118], + [88.95,90.199,36,127,22,0,70,0,2118], + [88.951,89.365,33,107,6,0,70,0,2118], + [88.951,89.782,45,106,1,0,70,0,2118], + [88.952,89.782,60,121,7,0,70,0,2118], + [88.953,90.199,33,101,11,0,70,0,2118], + [88.953,90.199,40,108,17,0,70,0,2118], + [88.955,90.199,60,77,13,1,70,0,2118], + [88.956,90.199,64,81,13,2,70,0,2118], + [89.157,89.365,84,69,14,0,70,0.5,2123], + [89.158,89.365,57,76,4,0,70,0.5,2123], + [89.161,89.365,45,72,5,0,70,0.5,2123], + [89.162,89.365,40,72,16,0,70,0.5,2123], + [89.36,89.574,40,81,16,0,70,1,2128], + [89.362,89.574,64,79,4,0,70,1,2128], + [89.365,89.574,88,68,14,0,70,1,2128], + [89.367,89.574,52,80,5,0,70,1,2128], + [89.371,89.782,33,87,6,0,70,1,2128], + [89.567,89.782,45,94,5,0,70,1.5,2133], + [89.572,89.782,38,113,16,0,70,1.5,2133], + [89.574,89.782,57,104,4,0,70,1.5,2133], + [89.577,89.782,93,90,14,0,70,1.5,2133], + [89.776,89.99,52,76,5,0,70,2,2138], + [89.779,89.99,88,72,14,0,70,2,2138], + [89.78,90.199,33,90,6,0,70,2,2138], + [89.782,89.99,64,74,4,0,70,2,2138], + [89.784,89.99,40,78,16,0,70,2,2138], + [89.991,90.199,57,82,5,0,70,2.5,2143], + [89.991,90.199,40,82,16,0,70,2.5,2143], + [89.991,90.199,84,62,14,0,70,2.5,2143], + [89.994,90.199,69,80,4,0,70,2.5,2143], + [90.184,90.621,64,48,0,0,71,0,2147], + [90.193,90.621,71,40,0,1,71,0,2147], + [90.196,92.072,52,86,13,0,71,0,2148], + [90.197,90.629,52,42,1,0,71,0,2148], + [90.197,90.41,52,106,4,0,71,0,2148], + [90.197,90.41,40,96,5,0,71,0,2148], + [90.197,92.072,38,109,22,0,71,0,2148], + [90.198,90.629,28,108,6,0,71,0,2148], + [90.198,90.629,71,44,2,0,71,0,2148], + [90.198,92.072,59,74,13,2,71,0,2148], + [90.198,90.629,36,123,16,0,71,0,2148], + [90.199,90.629,52,70,18,0,71,0,2148], + [90.2,92.072,56,80,13,1,71,0,2148], + [90.2,92.072,28,99,11,0,71,0,2148], + [90.2,90.629,56,42,1,1,71,0,2148], + [90.202,90.41,76,84,14,0,71,0,2148], + [90.203,90.629,40,40,9,0,71,0,2148], + [90.204,90.629,64,42,3,0,71,0,2148], + [90.408,90.629,52,76,4,0,71,0.5,2153], + [90.409,90.629,40,75,5,0,71,0.5,2153], + [90.415,90.629,80,67,14,0,71,0.5,2153], + [90.625,90.854,83,66,14,0,71,1,2158], + [90.628,90.854,59,82,4,0,71,1,2158], + [90.628,90.854,47,75,5,0,71,1,2158], + [90.629,91.088,28,78,6,0,71,1,2158], + [90.85,91.088,88,85,14,0,71,1.5,2163], + [90.855,91.088,52,103,4,0,71,1.5,2163], + [90.856,91.088,40,100,5,0,71,1.5,2163], + [91.087,91.33,59,82,4,0,71,2,2169], + [91.088,91.33,83,67,14,0,71,2,2169], + [91.091,92.072,28,87,6,0,71,2,2169], + [91.091,91.33,47,74,5,0,71,2,2169], + [91.326,92.072,52,81,5,0,71,2.5,2174], + [91.329,92.072,80,70,14,0,71,2.5,2175], + [91.335,92.072,64,81,4,0,71,2.5,2175], + [92.058,92.216,57,48,0,0,72,0,2192], + [92.068,93.436,60,85,13,1,72,0,2192], + [92.069,93.436,57,84,13,0,72,0,2192], + [92.071,92.527,33,60,1,0,72,0,2192], + [92.071,93.436,36,77,16,0,72,0,2192], + [92.075,93.436,33,83,11,0,72,0,2192], + [92.079,93.436,64,79,13,2,72,0,2192], + [92.216,92.367,60,59,0,0,72,0.333,2196], + [92.366,92.519,64,56,0,0,72,0.667,2199], + [92.518,92.67,69,56,0,0,72,1,2203], + [92.668,92.822,72,61,0,0,72,1.333,2206], + [92.83,92.973,76,59,0,0,72,1.667,2210], + [92.971,93.125,74,57,0,0,72,2,2214], + [92.981,93.436,60,39,1,1,72,2,2214], + [92.982,93.436,57,41,1,0,72,2,2214], + [92.986,93.436,64,48,1,2,72,2,2214], + [93.124,93.276,72,64,0,0,72,2.333,2217], + [93.272,93.428,71,53,0,0,72,2.667,2221], + [93.423,93.579,69,53,0,0,73,0,2224], + [93.432,93.89,64,48,1,2,73,0,2225], + [93.432,94.799,64,81,13,2,73,0,2225], + [93.434,94.799,33,77,11,0,73,0,2225], + [93.434,94.799,57,80,13,0,73,0,2225], + [93.436,93.89,57,47,1,0,73,0,2225], + [93.437,93.89,60,42,1,1,73,0,2225], + [93.439,94.799,60,78,13,1,73,0,2225], + [93.578,93.731,72,52,0,0,73,0.333,2228], + [93.731,93.882,76,62,0,0,73,0.667,2232], + [93.884,94.034,81,54,0,0,73,1,2235], + [94.032,94.185,84,58,0,0,73,1.333,2239], + [94.189,94.337,88,66,0,0,73,1.667,2243], + [94.335,94.488,86,61,0,0,73,2,2246], + [94.34,94.799,60,43,1,1,73,2,2246], + [94.348,94.799,57,42,1,0,73,2,2246], + [94.35,94.799,64,47,1,2,73,2,2246], + [94.488,94.64,84,59,0,0,73,2.333,2250], + [94.638,94.791,83,58,0,0,73,2.667,2253], + [94.794,94.943,81,52,0,0,74,0,2257], + [94.797,96.163,36,82,16,0,74,0,2257], + [94.798,95.254,60,45,1,1,74,0,2257], + [94.799,95.254,57,49,1,0,74,0,2257], + [94.8,96.163,45,105,23,0,74,0,2257], + [94.8,96.163,57,85,13,0,74,0,2257], + [94.8,96.163,64,86,13,2,74,0,2257], + [94.802,95.254,64,47,1,2,74,0,2257], + [94.802,96.163,33,81,11,0,74,0,2257], + [94.804,96.163,60,83,13,1,74,0,2257], + [94.944,95.095,84,54,0,0,74,0.333,2261], + [95.1,95.246,88,61,0,0,74,0.667,2264], + [95.248,95.398,93,57,0,0,74,1,2268], + [95.394,95.549,96,55,0,0,74,1.333,2271], + [95.544,95.701,100,55,0,0,74,1.667,2275], + [95.705,96.163,64,42,1,2,74,2,2279], + [95.705,95.852,98,57,0,0,74,2,2279], + [95.707,96.163,60,48,1,1,74,2,2279], + [95.707,96.163,57,40,1,0,74,2,2279], + [95.853,96.004,96,52,0,0,74,2.333,2282], + [96.003,96.155,95,58,0,0,74,2.667,2286], + [96.15,96.306,94,52,0,0,75,0,2289], + [96.159,97.495,52,80,13,0,75,0,2290], + [96.161,97.495,28,79,11,0,75,0,2290], + [96.163,97.495,59,78,13,2,75,0,2290], + [96.163,96.614,64,36,1,2,75,0,2290], + [96.164,97.495,56,82,13,1,75,0,2290], + [96.165,96.614,60,37,1,1,75,0,2290], + [96.166,96.614,57,40,1,0,75,0,2290], + [96.305,96.457,93,59,0,0,75,0.333,2293], + [96.458,96.606,92,52,0,0,75,0.667,2297], + [96.608,96.755,91,58,0,0,75,1,2300], + [96.752,96.903,90,58,0,0,75,1.333,2304], + [96.908,97.05,89,50,0,0,75,1.667,2307], + [97.047,97.196,88,47,0,0,75,2,2311], + [97.196,97.342,87,52,0,0,75,2.333,2314], + [97.344,97.487,86,52,0,0,75,2.667,2318], + [97.486,97.631,85,54,0,0,76,0,2321], + [97.493,98.768,28,82,11,0,76,0,2321], + [97.496,97.711,38,94,16,0,76,0,2321], + [97.496,98.768,59,78,13,2,76,0,2321], + [97.496,98.768,52,80,13,0,76,0,2321], + [97.496,98.768,56,82,13,1,76,0,2321], + [97.636,97.775,84,52,0,0,76,0.333,2325], + [97.708,97.926,38,96,16,0,76,0.5,2326], + [97.775,97.918,83,52,0,0,76,0.667,2328], + [97.916,98.06,82,54,0,0,76,1,2331], + [97.927,98.139,38,104,16,0,76,1,2332], + [98.062,98.201,81,48,0,0,76,1.333,2335], + [98.136,98.35,38,107,16,0,76,1.5,2337], + [98.199,98.342,80,52,0,0,76,1.667,2338], + [98.341,98.482,79,47,0,0,76,2,2341], + [98.346,98.559,38,109,16,0,76,2,2342], + [98.482,98.621,78,50,0,0,76,2.333,2345], + [98.561,98.768,38,120,16,0,76,2.5,2347], + [98.621,98.76,77,46,0,0,76,2.667,2348], + [98.758,98.968,76,112,0,0,77,0,2351], + [98.764,100.021,52,111,18,0,77,0,2352], + [98.764,100.021,28,111,10,0,77,0,2352], + [98.765,100.021,28,90,11,0,77,0,2352], + [98.766,99.185,28,103,6,0,77,0,2352], + [98.766,98.976,36,121,16,0,77,0,2352], + [98.766,100.021,52,74,13,0,77,0,2352], + [98.766,100.021,35,98,8,1,77,0,2352], + [98.767,100.021,56,83,7,1,77,0,2352], + [98.767,100.021,36,127,22,0,77,0,2352], + [98.768,100.021,59,77,3,2,77,0,2352], + [98.768,100.021,40,109,17,0,77,0,2352], + [98.768,100.021,40,116,10,2,77,0,2352], + [98.769,100.021,35,118,10,1,77,0,2352], + [98.769,100.021,40,107,8,2,77,0,2352], + [98.769,100.021,28,113,9,0,77,0,2352], + [98.769,100.021,56,70,3,1,77,0,2352], + [98.769,100.021,71,86,2,2,77,0,2352], + [98.769,98.976,40,103,5,0,77,0,2352], + [98.77,100.021,68,79,2,1,77,0,2352], + [98.77,100.021,52,85,7,0,77,0,2352], + [98.77,98.976,52,102,4,0,77,0,2352], + [98.77,100.021,56,82,13,1,77,0,2352], + [98.771,100.021,64,75,2,0,77,0,2352], + [98.771,100.021,52,74,3,0,77,0,2352], + [98.771,100.021,28,104,8,0,77,0,2352], + [98.773,100.021,59,81,13,2,77,0,2352], + [98.773,100.021,49,118,21,0,77,0,2352], + [98.965,99.177,75,105,0,0,77,0.5,2356], + [98.975,99.185,40,74,5,0,77,0.5,2357], + [98.976,99.185,52,74,4,0,77,0.5,2357], + [99.18,99.386,76,105,0,0,77,1,2361], + [99.181,99.394,59,78,4,0,77,1,2361], + [99.182,99.394,47,81,5,0,77,1,2361], + [99.183,99.603,28,76,6,0,77,1,2362], + [99.184,99.394,38,87,16,0,77,1,2362], + [99.386,99.595,71,99,0,0,77,1.5,2366], + [99.397,99.603,40,96,5,0,77,1.5,2367], + [99.398,99.603,52,101,4,0,77,1.5,2367], + [99.4,99.603,40,95,16,0,77,1.5,2367], + [99.597,99.812,59,72,4,0,77,2,2371], + [99.597,99.804,74,106,0,0,77,2,2371], + [99.599,99.812,47,65,5,0,77,2,2371], + [99.602,99.812,36,113,16,0,77,2,2371], + [99.603,100.021,28,91,6,0,77,2,2371], + [99.796,100.013,72,97,0,0,77,2.5,2376], + [99.808,100.021,52,80,5,0,77,2.5,2376], + [99.816,100.021,64,82,4,0,77,2.5,2377], + [100.014,100.432,69,108,0,0,78,0,2381], + [100.018,100.44,33,107,6,0,78,0,2381], + [100.018,101.28,60,81,7,1,78,0,2381], + [100.019,100.23,57,102,4,0,78,0,2381], + [100.02,100.23,38,105,16,0,78,0,2381], + [100.02,101.28,72,84,2,1,78,0,2381], + [100.021,101.28,64,78,13,2,78,0,2381], + [100.021,101.28,64,72,3,2,78,0,2381], + [100.021,101.28,60,79,3,1,78,0,2381], + [100.022,101.28,76,86,2,2,78,0,2381], + [100.022,101.28,33,95,11,0,78,0,2381], + [100.022,100.23,45,95,5,0,78,0,2381], + [100.023,101.28,57,87,7,0,78,0,2381], + [100.023,101.28,69,78,2,0,78,0,2381], + [100.023,101.28,57,82,13,0,78,0,2382], + [100.023,100.23,45,80,1,0,78,0,2382], + [100.025,101.28,57,79,3,0,78,0,2382], + [100.025,101.28,40,108,17,0,78,0,2382], + [100.025,101.28,60,80,13,1,78,0,2382], + [100.225,100.44,57,71,4,0,78,0.5,2386], + [100.229,100.44,40,77,16,0,78,0.5,2386], + [100.233,100.44,52,84,1,0,78,0.5,2386], + [100.233,100.44,45,74,5,0,78,0.5,2387], + [100.438,100.65,52,77,5,0,78,1,2391], + [100.439,100.65,42,80,16,0,78,1,2391], + [100.442,100.65,64,77,4,0,78,1,2391], + [100.442,100.65,57,76,1,0,78,1,2391], + [100.444,100.86,33,84,6,0,78,1,2392], + [100.638,100.852,60,87,0,0,78,1.5,2396], + [100.645,100.86,57,96,4,0,78,1.5,2396], + [100.648,100.86,36,119,16,0,78,1.5,2396], + [100.649,100.86,45,99,5,0,78,1.5,2396], + [100.853,101.062,64,96,0,0,78,2,2401], + [100.858,101.07,64,76,4,0,78,2,2401], + [100.86,101.07,40,86,16,0,78,2,2401], + [100.86,101.28,33,86,6,0,78,2,2401], + [100.865,101.07,52,70,5,0,78,2,2402], + [101.062,101.272,69,101,0,0,78,2.5,2406], + [101.064,101.28,42,91,16,0,78,2.5,2406], + [101.067,101.28,69,83,4,0,78,2.5,2406], + [101.07,101.28,57,79,5,0,78,2.5,2406], + [101.269,101.693,71,102,0,0,79,0,2411], + [101.275,101.49,40,98,5,0,79,0,2411], + [101.276,102.545,28,96,11,0,79,0,2411], + [101.276,102.545,52,84,7,0,79,0,2411], + [101.278,102.545,64,85,2,0,79,0,2411], + [101.278,102.545,59,73,3,2,79,0,2411], + [101.279,102.545,68,82,2,1,79,0,2411], + [101.279,102.545,56,83,7,1,79,0,2411], + [101.279,102.545,52,80,3,0,79,0,2411], + [101.28,102.545,40,110,17,0,79,0,2411], + [101.281,102.545,56,76,13,1,79,0,2411], + [101.281,101.701,28,103,6,0,79,0,2411], + [101.281,102.545,71,84,2,2,79,0,2411], + [101.282,101.49,52,103,4,0,79,0,2411], + [101.282,102.545,59,77,13,2,79,0,2411], + [101.284,101.49,36,115,16,0,79,0,2412], + [101.285,102.545,56,80,3,1,79,0,2412], + [101.285,101.49,40,78,1,0,79,0,2412], + [101.285,102.545,52,85,13,0,79,0,2412], + [101.488,101.701,40,68,5,0,79,0.5,2416], + [101.491,101.701,52,75,4,0,79,0.5,2416], + [101.495,101.701,52,85,1,0,79,0.5,2417], + [101.694,101.912,56,88,1,0,79,1,2421], + [101.697,101.912,38,80,16,0,79,1,2421], + [101.701,101.912,47,74,5,0,79,1,2421], + [101.703,101.912,59,75,4,0,79,1,2422], + [101.704,102.123,28,76,6,0,79,1,2422], + [101.9,102.115,64,93,0,0,79,1.5,2426], + [101.907,102.123,40,91,5,0,79,1.5,2426], + [101.914,102.123,40,92,16,0,79,1.5,2427], + [101.918,102.123,52,104,4,0,79,1.5,2427], + [102.116,102.326,68,101,0,0,79,2,2431], + [102.118,102.545,28,91,6,0,79,2,2431], + [102.12,102.334,47,73,5,0,79,2,2431], + [102.122,102.334,36,110,16,0,79,2,2431], + [102.125,102.334,59,75,4,0,79,2,2432], + [102.327,102.537,71,99,0,0,79,2.5,2436], + [102.329,102.545,64,80,4,0,79,2.5,2436], + [102.332,102.545,52,82,5,0,79,2.5,2436], + [102.539,102.96,72,114,0,0,80,0,2441], + [102.54,103.817,60,76,3,1,80,0,2441], + [102.54,103.817,72,85,2,1,80,0,2441], + [102.542,103.817,57,78,13,0,80,0,2441], + [102.543,103.817,57,81,7,0,80,0,2441], + [102.543,103.817,69,87,2,0,80,0,2442], + [102.543,102.757,45,99,5,0,80,0,2442], + [102.543,103.817,60,79,13,1,80,0,2442], + [102.543,102.757,57,98,4,0,80,0,2442], + [102.544,103.817,40,108,17,0,80,0,2442], + [102.545,103.817,64,82,13,2,80,0,2442], + [102.545,102.757,45,79,1,0,80,0,2442], + [102.545,102.968,33,102,6,0,80,0,2442], + [102.546,103.817,64,75,3,2,80,0,2442], + [102.546,103.817,76,85,2,2,80,0,2442], + [102.547,103.817,57,80,3,0,80,0,2442], + [102.548,103.817,33,98,11,0,80,0,2442], + [102.55,102.757,38,102,16,0,80,0,2442], + [102.551,103.817,60,85,7,1,80,0,2442], + [102.754,102.968,45,73,5,0,80,0.5,2447], + [102.757,102.968,40,76,16,0,80,0.5,2447], + [102.758,102.968,52,86,1,0,80,0.5,2447], + [102.759,102.968,57,71,4,0,80,0.5,2447], + [102.965,103.18,64,82,4,0,80,1,2452], + [102.968,103.392,33,78,6,0,80,1,2452], + [102.971,103.18,42,77,16,0,80,1,2452], + [102.971,103.18,52,78,5,0,80,1,2452], + [102.972,103.18,57,81,1,0,80,1,2452], + [103.167,103.384,64,93,0,0,80,1.5,2456], + [103.176,103.392,57,99,4,0,80,1.5,2457], + [103.177,103.392,36,118,16,0,80,1.5,2457], + [103.181,103.392,45,101,5,0,80,1.5,2457], + [103.383,103.596,76,100,0,0,80,2,2462], + [103.388,103.604,40,86,16,0,80,2,2462], + [103.39,103.817,33,93,6,0,80,2,2462], + [103.39,103.604,64,70,4,0,80,2,2462], + [103.395,103.604,52,76,5,0,80,2,2462], + [103.598,103.809,75,105,0,0,80,2.5,2467], + [103.603,103.817,57,85,5,0,80,2.5,2467], + [103.605,103.817,42,95,16,0,80,2.5,2467], + [103.609,103.817,69,84,4,0,80,2.5,2467], + [103.811,104.021,76,110,0,0,81,0,2472], + [103.811,105.094,59,84,13,2,81,0,2472], + [103.811,104.029,36,120,16,0,81,0,2472], + [103.813,105.094,52,82,3,0,81,0,2472], + [103.814,105.094,52,85,13,0,81,0,2472], + [103.814,105.094,56,77,13,1,81,0,2472], + [103.815,105.094,56,80,7,1,81,0,2472], + [103.815,104.029,40,101,5,0,81,0,2472], + [103.815,105.094,28,98,11,0,81,0,2472], + [103.817,105.094,68,78,2,1,81,0,2472], + [103.817,105.094,59,76,3,2,81,0,2472], + [103.817,104.242,28,102,6,0,81,0,2472], + [103.818,105.094,52,82,7,0,81,0,2472], + [103.819,105.094,56,80,3,1,81,0,2472], + [103.819,105.094,64,83,2,0,81,0,2472], + [103.82,104.029,52,107,4,0,81,0,2472], + [103.82,105.094,71,82,2,2,81,0,2472], + [103.821,105.094,40,108,17,0,81,0,2472], + [104.019,104.234,75,102,0,0,81,0.5,2477], + [104.029,104.242,52,71,4,0,81,0.5,2477], + [104.033,104.242,40,72,5,0,81,0.5,2477], + [104.232,104.447,76,102,0,0,81,1,2482], + [104.236,104.455,59,84,4,0,81,1,2482], + [104.24,104.455,38,84,16,0,81,1,2482], + [104.24,104.455,47,76,5,0,81,1,2482], + [104.246,104.668,28,79,6,0,81,1,2482], + [104.449,104.66,71,100,0,0,81,1.5,2487], + [104.453,104.668,40,94,5,0,81,1.5,2487], + [104.455,104.668,52,99,4,0,81,1.5,2487], + [104.455,104.668,40,98,16,0,81,1.5,2487], + [104.657,104.873,74,110,0,0,81,2,2492], + [104.666,104.881,59,77,4,0,81,2,2492], + [104.668,104.881,47,75,5,0,81,2,2492], + [104.668,105.094,28,90,6,0,81,2,2492], + [104.671,104.881,36,112,16,0,81,2,2492], + [104.871,105.086,72,97,0,0,81,2.5,2497], + [104.88,105.094,64,86,4,0,81,2.5,2497], + [104.88,105.094,52,80,5,0,81,2.5,2497], + [105.086,105.514,69,105,0,0,82,0,2502], + [105.09,106.378,64,75,3,2,82,0,2502], + [105.09,106.378,64,78,13,2,82,0,2502], + [105.091,106.378,60,84,13,1,82,0,2502], + [105.092,106.378,33,89,11,0,82,0,2502], + [105.092,106.378,72,81,2,1,82,0,2502], + [105.092,105.308,45,98,5,0,82,0,2502], + [105.092,106.378,57,78,13,0,82,0,2502], + [105.092,106.378,60,87,7,1,82,0,2502], + [105.094,105.522,33,106,6,0,82,0,2502], + [105.094,106.378,40,108,17,0,82,0,2502], + [105.094,106.378,57,84,7,0,82,0,2502], + [105.094,105.308,45,79,1,0,82,0,2502], + [105.094,106.378,76,82,2,2,82,0,2502], + [105.095,106.378,69,87,2,0,82,0,2502], + [105.097,105.308,57,102,4,0,82,0,2502], + [105.097,105.308,38,102,16,0,82,0,2502], + [105.097,106.378,57,75,3,0,82,0,2502], + [105.1,106.378,60,77,3,1,82,0,2502], + [105.306,105.522,40,72,16,0,82,0.5,2507], + [105.306,105.522,57,76,4,0,82,0.5,2507], + [105.307,105.522,52,79,1,0,82,0.5,2507], + [105.311,105.522,45,74,5,0,82,0.5,2507], + [105.522,105.95,33,82,6,0,82,1,2512], + [105.522,105.735,57,80,1,0,82,1,2512], + [105.523,105.735,42,82,16,0,82,1,2512], + [105.525,105.735,64,78,4,0,82,1,2513], + [105.528,105.735,52,74,5,0,82,1,2513], + [105.727,105.942,60,94,0,0,82,1.5,2517], + [105.73,105.95,57,97,4,0,82,1.5,2517], + [105.735,105.95,45,93,5,0,82,1.5,2518], + [105.739,105.95,36,115,16,0,82,1.5,2518], + [105.943,106.164,52,71,5,0,82,2,2522], + [105.944,106.156,64,94,0,0,82,2,2522], + [105.948,106.164,64,76,4,0,82,2,2523], + [105.951,106.378,33,84,6,0,82,2,2523], + [105.956,106.164,40,81,16,0,82,2,2523], + [106.156,106.37,69,106,0,0,82,2.5,2528], + [106.16,106.378,69,84,4,0,82,2.5,2528], + [106.162,106.378,57,80,5,0,82,2.5,2528], + [106.169,106.378,42,90,16,0,82,2.5,2528], + [106.371,107.669,40,108,17,0,83,0,2533], + [106.372,107.669,52,75,3,0,83,0,2533], + [106.373,106.8,71,100,0,0,83,0,2533], + [106.374,107.669,59,82,13,2,83,0,2533], + [106.375,107.669,52,82,7,0,83,0,2533], + [106.375,107.669,64,80,2,0,83,0,2533], + [106.376,107.669,68,82,2,1,83,0,2533], + [106.377,107.669,56,76,3,1,83,0,2533], + [106.377,107.669,28,95,11,0,83,0,2533], + [106.377,107.669,41,89,23,0,83,0,2533], + [106.378,107.669,56,80,13,1,83,0,2533], + [106.379,106.593,40,83,1,0,83,0,2533], + [106.379,106.593,52,107,4,0,83,0,2533], + [106.379,106.593,36,119,16,0,83,0,2533], + [106.379,107.669,59,76,3,2,83,0,2533], + [106.379,106.808,28,104,6,0,83,0,2533], + [106.38,107.669,52,78,13,0,83,0,2533], + [106.381,106.593,40,103,5,0,83,0,2533], + [106.382,107.669,56,80,7,1,83,0,2533], + [106.385,107.669,71,80,2,2,83,0,2533], + [106.59,106.808,52,64,4,0,83,0.5,2538], + [106.593,106.808,52,79,1,0,83,0.5,2538], + [106.593,106.808,40,74,5,0,83,0.5,2538], + [106.802,107.023,59,79,4,0,83,1,2543], + [106.807,107.238,28,79,6,0,83,1,2543], + [106.807,107.023,47,81,5,0,83,1,2543], + [106.807,107.023,56,83,1,0,83,1,2543], + [106.809,107.023,38,89,16,0,83,1,2543], + [107.013,107.23,64,94,0,0,83,1.5,2548], + [107.02,107.238,40,99,5,0,83,1.5,2548], + [107.022,107.238,40,95,16,0,83,1.5,2548], + [107.024,107.238,52,97,4,0,83,1.5,2548], + [107.229,107.445,72,104,0,0,83,2,2553], + [107.236,107.453,59,77,4,0,83,2,2553], + [107.238,107.669,28,96,6,0,83,2,2553], + [107.239,107.453,36,111,16,0,83,2,2553], + [107.241,107.453,47,76,5,0,83,2,2553], + [107.447,107.669,52,79,5,0,83,2.5,2558], + [107.448,107.661,71,100,0,0,83,2.5,2558], + [107.449,107.669,64,89,4,0,83,2.5,2558], + [107.661,108.965,57,75,13,0,84,0,2563], + [107.662,108.524,69,109,0,0,84,0,2563], + [107.664,108.965,72,81,2,1,84,0,2563], + [107.664,108.965,57,75,3,0,84,0,2563], + [107.665,108.1,33,107,6,0,84,0,2563], + [107.665,108.965,60,74,3,1,84,0,2563], + [107.666,108.965,57,88,7,0,84,0,2563], + [107.666,108.965,40,104,17,0,84,0,2563], + [107.666,108.965,64,76,13,2,84,0,2563], + [107.667,107.884,45,99,5,0,84,0,2563], + [107.667,107.884,40,104,19,0,84,0,2564], + [107.67,108.965,76,86,2,2,84,0,2564], + [107.67,108.965,60,79,13,1,84,0,2564], + [107.67,108.965,33,96,11,0,84,0,2564], + [107.67,107.884,38,107,16,0,84,0,2564], + [107.671,108.965,69,76,2,0,84,0,2564], + [107.671,108.965,64,72,3,2,84,0,2564], + [107.671,108.965,60,85,7,1,84,0,2564], + [107.672,107.884,57,102,4,0,84,0,2564], + [107.673,107.884,45,85,1,0,84,0,2564], + [107.883,108.1,52,83,1,0,84,0.5,2569], + [107.883,108.1,45,67,5,0,84,0.5,2569], + [107.883,108.1,40,70,16,0,84,0.5,2569], + [107.889,108.1,57,67,4,0,84,0.5,2569], + [107.89,108.1,42,110,19,0,84,0.5,2569], + [108.097,108.316,42,82,16,0,84,1,2574], + [108.099,108.316,64,79,4,0,84,1,2574], + [108.1,108.532,33,81,6,0,84,1,2574], + [108.103,108.316,40,115,19,0,84,1,2574], + [108.106,108.316,52,77,5,0,84,1,2574], + [108.107,108.316,57,84,1,0,84,1,2574], + [108.311,108.532,57,98,4,0,84,1.5,2579], + [108.316,108.532,42,114,19,0,84,1.5,2579], + [108.318,108.532,36,119,16,0,84,1.5,2579], + [108.319,108.532,45,95,5,0,84,1.5,2579], + [108.523,108.741,76,104,0,0,84,2,2584], + [108.529,108.749,40,120,19,0,84,2,2584], + [108.531,108.749,52,72,5,0,84,2,2584], + [108.531,108.749,64,81,4,0,84,2,2584], + [108.533,108.965,33,86,6,0,84,2,2584], + [108.535,108.749,40,81,16,0,84,2,2584], + [108.735,108.957,75,105,0,0,84,2.5,2589], + [108.748,108.965,42,127,19,0,84,2.5,2589], + [108.749,108.965,42,90,16,0,84,2.5,2589], + [108.752,108.965,69,79,4,0,84,2.5,2589], + [108.753,108.965,57,78,5,0,84,2.5,2589], + [108.957,109.174,76,112,0,0,85,0,2594], + [108.959,110.269,28,106,8,0,85,0,2594], + [108.96,110.269,71,83,2,2,85,0,2594], + [108.96,109.399,28,104,6,0,85,0,2594], + [108.961,110.269,52,88,7,0,85,0,2594], + [108.961,110.269,56,83,7,1,85,0,2594], + [108.963,110.269,52,108,18,0,85,0,2594], + [108.963,110.269,64,85,2,0,85,0,2594], + [108.965,109.182,52,101,4,0,85,0,2594], + [108.965,109.182,76,82,14,0,85,0,2594], + [108.965,110.269,49,117,21,0,85,0,2594], + [108.965,110.269,40,106,8,2,85,0,2594], + [108.966,110.269,28,110,9,0,85,0,2594], + [108.966,110.269,35,110,10,1,85,0,2594], + [108.967,110.269,68,80,2,1,85,0,2594], + [108.967,110.269,28,92,11,0,85,0,2594], + [108.967,110.269,40,117,10,2,85,0,2594], + [108.967,110.269,35,104,8,1,85,0,2594], + [108.968,109.182,40,100,5,0,85,0,2594], + [108.968,110.269,52,75,3,0,85,0,2594], + [108.969,110.269,40,110,17,0,85,0,2594], + [108.969,109.182,36,118,16,0,85,0,2595], + [108.969,110.269,59,74,3,2,85,0,2595], + [108.97,110.269,28,111,10,0,85,0,2595], + [108.97,110.269,52,80,13,0,85,0,2595], + [108.971,110.269,56,76,13,1,85,0,2595], + [108.971,110.269,59,85,13,2,85,0,2595], + [108.972,110.269,56,77,3,1,85,0,2595], + [109.178,109.391,75,105,0,0,85,0.5,2599], + [109.182,109.399,52,71,4,0,85,0.5,2600], + [109.187,109.399,40,66,5,0,85,0.5,2600], + [109.19,109.399,80,62,14,0,85,0.5,2600], + [109.393,109.608,76,105,0,0,85,1,2605], + [109.397,109.616,38,84,16,0,85,1,2605], + [109.401,109.616,59,83,4,0,85,1,2605], + [109.402,109.616,47,78,5,0,85,1,2605], + [109.403,109.833,28,78,6,0,85,1,2605], + [109.403,109.616,83,65,14,0,85,1,2605], + [109.609,109.825,71,100,0,0,85,1.5,2610], + [109.613,109.833,52,100,4,0,85,1.5,2610], + [109.618,109.833,88,82,14,0,85,1.5,2610], + [109.619,109.833,40,94,5,0,85,1.5,2610], + [109.619,109.833,40,97,16,0,85,1.5,2610], + [109.825,110.043,74,100,0,0,85,2,2615], + [109.83,110.051,47,73,5,0,85,2,2615], + [109.834,110.051,36,109,16,0,85,2,2615], + [109.834,110.051,59,73,4,0,85,2,2615], + [109.835,110.051,83,64,14,0,85,2,2615], + [109.838,110.269,28,89,6,0,85,2,2615], + [110.045,110.269,64,81,4,0,85,2.5,2620], + [110.046,110.261,72,106,0,0,85,2.5,2620], + [110.051,110.269,52,81,5,0,85,2.5,2620], + [110.052,110.269,80,67,14,0,85,2.5,2620], + [110.257,110.696,69,108,0,0,86,0,2625], + [110.266,110.486,81,83,14,0,86,0,2625], + [110.266,111.578,60,85,7,1,86,0,2625], + [110.267,111.578,33,94,11,0,86,0,2625], + [110.267,110.486,45,84,1,0,86,0,2625], + [110.268,111.578,57,83,7,0,86,0,2625], + [110.268,111.578,60,77,13,1,86,0,2625], + [110.269,111.578,72,88,2,1,86,0,2625], + [110.269,111.578,57,75,13,0,86,0,2625], + [110.269,110.486,38,108,16,0,86,0,2625], + [110.269,111.578,69,81,2,0,86,0,2625], + [110.269,111.578,64,74,3,2,86,0,2625], + [110.27,111.578,64,78,13,2,86,0,2625], + [110.27,111.578,40,103,17,0,86,0,2625], + [110.27,111.578,57,77,3,0,86,0,2625], + [110.271,111.578,60,81,3,1,86,0,2626], + [110.272,110.486,57,101,4,0,86,0,2626], + [110.273,111.578,76,82,2,2,86,0,2626], + [110.274,110.704,33,105,6,0,86,0,2626], + [110.274,110.486,45,106,5,0,86,0,2626], + [110.483,110.704,84,65,14,0,86,0.5,2631], + [110.485,110.704,57,69,4,0,86,0.5,2631], + [110.485,110.704,45,64,5,0,86,0.5,2631], + [110.486,110.704,52,82,1,0,86,0.5,2631], + [110.493,110.704,40,75,16,0,86,0.5,2631], + [110.7,110.923,42,82,16,0,86,1,2636], + [110.703,110.923,88,64,14,0,86,1,2636], + [110.704,110.923,52,77,5,0,86,1,2636], + [110.705,110.923,57,81,1,0,86,1,2636], + [110.705,111.141,33,80,6,0,86,1,2636], + [110.706,110.923,64,78,4,0,86,1,2636], + [110.911,111.133,60,99,0,0,86,1.5,2641], + [110.919,111.141,36,122,16,0,86,1.5,2641], + [110.92,111.141,57,101,4,0,86,1.5,2641], + [110.921,111.141,93,81,14,0,86,1.5,2641], + [110.924,111.141,45,95,5,0,86,1.5,2641], + [111.134,111.352,64,99,0,0,86,2,2646], + [111.14,111.36,40,83,16,0,86,2,2646], + [111.142,111.36,64,72,4,0,86,2,2646], + [111.143,111.36,52,71,5,0,86,2,2646], + [111.144,111.36,88,67,14,0,86,2,2646], + [111.145,111.578,33,84,6,0,86,2,2646], + [111.349,111.57,69,99,0,0,86,2.5,2651], + [111.358,111.578,57,82,5,0,86,2.5,2651], + [111.358,111.578,42,93,16,0,86,2.5,2651], + [111.358,111.578,69,79,4,0,86,2.5,2651], + [111.359,111.578,84,69,14,0,86,2.5,2651], + [111.568,112.009,71,112,0,0,87,0,2656], + [111.574,111.797,52,98,4,0,87,0,2657], + [111.576,111.797,76,86,14,0,87,0,2657], + [111.576,111.797,36,119,16,0,87,0,2657], + [111.576,112.895,59,82,3,2,87,0,2657], + [111.576,112.895,52,71,3,0,87,0,2657], + [111.576,112.895,68,79,2,1,87,0,2657], + [111.577,112.895,71,82,2,2,87,0,2657], + [111.578,112.895,40,113,17,0,87,0,2657], + [111.578,112.895,56,74,3,1,87,0,2657], + [111.578,112.017,28,103,6,0,87,0,2657], + [111.578,112.895,56,79,7,1,87,0,2657], + [111.578,112.895,28,92,11,0,87,0,2657], + [111.579,111.797,40,85,1,0,87,0,2657], + [111.579,112.895,56,81,13,1,87,0,2657], + [111.58,112.895,64,86,2,0,87,0,2657], + [111.58,112.895,52,80,13,0,87,0,2657], + [111.581,112.895,59,79,13,2,87,0,2657], + [111.581,111.797,40,97,5,0,87,0,2657], + [111.583,112.895,52,88,7,0,87,0,2657], + [111.791,112.017,52,86,1,0,87,0.5,2662], + [111.796,112.017,52,65,4,0,87,0.5,2662], + [111.798,112.017,40,70,5,0,87,0.5,2662], + [111.799,112.017,80,65,14,0,87,0.5,2662], + [112.016,112.236,83,68,14,0,87,1,2667], + [112.016,112.236,47,80,5,0,87,1,2667], + [112.016,112.236,38,82,16,0,87,1,2667], + [112.017,112.455,28,76,6,0,87,1,2667], + [112.017,112.236,56,85,1,0,87,1,2667], + [112.019,112.236,59,80,4,0,87,1,2667], + [112.224,112.447,64,90,0,0,87,1.5,2672], + [112.234,112.455,40,92,16,0,87,1.5,2672], + [112.234,112.455,88,89,14,0,87,1.5,2672], + [112.238,112.455,52,98,4,0,87,1.5,2672], + [112.239,112.455,40,94,5,0,87,1.5,2672], + [112.448,112.675,59,72,4,0,87,2,2677], + [112.449,112.667,68,96,0,0,87,2,2677], + [112.45,112.675,47,75,5,0,87,2,2677], + [112.454,112.675,36,112,16,0,87,2,2677], + [112.457,112.895,28,89,6,0,87,2,2678], + [112.459,112.675,83,68,14,0,87,2,2678], + [112.665,112.887,71,105,0,0,87,2.5,2683], + [112.675,112.895,64,84,4,0,87,2.5,2683], + [112.676,112.895,80,70,14,0,87,2.5,2683], + [112.677,112.895,52,84,5,0,87,2.5,2683], + [112.89,113.327,72,113,0,0,88,0,2688], + [112.892,114.218,64,69,3,2,88,0,2688], + [112.892,114.218,57,75,13,0,88,0,2688], + [112.892,114.218,40,106,17,0,88,0,2688], + [112.893,113.115,81,84,14,0,88,0,2688], + [112.893,114.218,60,81,13,1,88,0,2688], + [112.893,114.218,60,86,7,1,88,0,2688], + [112.894,114.218,60,77,3,1,88,0,2688], + [112.894,114.218,72,76,2,1,88,0,2688], + [112.895,113.335,33,105,6,0,88,0,2688], + [112.895,113.115,38,104,16,0,88,0,2688], + [112.895,114.218,57,79,3,0,88,0,2688], + [112.896,113.115,45,79,1,0,88,0,2688], + [112.896,113.115,57,101,4,0,88,0,2688], + [112.897,113.115,45,97,5,0,88,0,2688], + [112.897,114.218,64,84,13,2,88,0,2688], + [112.898,114.218,76,86,2,2,88,0,2688], + [112.9,114.218,69,79,2,0,88,0,2688], + [112.9,114.218,33,94,11,0,88,0,2688], + [112.901,114.218,57,86,7,0,88,0,2688], + [113.113,113.335,52,86,1,0,88,0.5,2693], + [113.114,113.335,40,79,16,0,88,0.5,2693], + [113.115,113.335,84,60,14,0,88,0.5,2693], + [113.12,113.335,57,79,4,0,88,0.5,2693], + [113.121,113.335,45,73,5,0,88,0.5,2693], + [113.332,113.556,52,79,5,0,88,1,2698], + [113.337,113.556,64,81,4,0,88,1,2698], + [113.337,113.776,33,80,6,0,88,1,2698], + [113.338,113.556,57,87,1,0,88,1,2699], + [113.339,113.556,42,82,16,0,88,1,2699], + [113.339,113.556,88,65,14,0,88,1,2699], + [113.549,113.768,64,93,0,0,88,1.5,2704], + [113.554,113.776,36,114,16,0,88,1.5,2704], + [113.554,113.776,45,99,5,0,88,1.5,2704], + [113.557,113.776,93,87,14,0,88,1.5,2704], + [113.558,113.776,57,97,4,0,88,1.5,2704], + [113.764,113.989,76,101,0,0,88,2,2709], + [113.773,113.997,64,74,4,0,88,2,2709], + [113.775,113.997,40,80,16,0,88,2,2709], + [113.779,114.218,33,84,6,0,88,2,2709], + [113.78,113.997,52,71,5,0,88,2,2709], + [113.783,113.997,88,64,14,0,88,2,2709], + [113.989,114.21,75,100,0,0,88,2.5,2714], + [113.995,114.218,42,89,16,0,88,2.5,2714], + [113.996,114.218,69,84,4,0,88,2.5,2714], + [113.997,114.218,84,68,14,0,88,2.5,2714], + [114,114.218,57,82,5,0,88,2.5,2714], + [114.211,115.548,68,83,2,1,89,0,2719], + [114.212,115.548,71,78,2,2,89,0,2719], + [114.212,115.548,56,77,3,1,89,0,2719], + [114.213,115.548,56,91,7,1,89,0,2719], + [114.213,114.439,40,100,5,0,89,0,2719], + [114.214,114.431,76,105,0,0,89,0,2719], + [114.214,115.548,52,85,7,0,89,0,2719], + [114.215,114.439,76,86,14,0,89,0,2719], + [114.215,115.548,40,109,17,0,89,0,2719], + [114.216,114.439,52,98,4,0,89,0,2719], + [114.216,115.548,59,72,3,2,89,0,2719], + [114.216,114.439,36,117,16,0,89,0,2719], + [114.218,115.548,28,97,11,0,89,0,2719], + [114.219,115.548,56,77,13,1,89,0,2719], + [114.22,115.548,52,76,3,0,89,0,2720], + [114.221,114.661,28,107,6,0,89,0,2720], + [114.221,115.548,59,81,13,2,89,0,2720], + [114.221,115.548,64,87,2,0,89,0,2720], + [114.222,115.548,52,83,13,0,89,0,2720], + [114.432,114.653,75,106,0,0,89,0.5,2725], + [114.436,114.661,80,67,14,0,89,0.5,2725], + [114.443,114.661,52,72,4,0,89,0.5,2725], + [114.443,114.661,40,70,5,0,89,0.5,2725], + [114.654,114.874,76,103,0,0,89,1,2730], + [114.659,114.882,38,90,16,0,89,1,2730], + [114.66,114.882,59,84,4,0,89,1,2730], + [114.66,115.104,28,84,6,0,89,1,2730], + [114.666,114.882,83,61,14,0,89,1,2730], + [114.666,114.882,47,77,5,0,89,1,2730], + [114.875,115.096,71,102,0,0,89,1.5,2735], + [114.877,115.104,88,85,14,0,89,1.5,2735], + [114.88,115.104,40,99,5,0,89,1.5,2735], + [114.882,115.104,40,100,16,0,89,1.5,2735], + [114.883,115.104,52,101,4,0,89,1.5,2735], + [115.099,115.318,74,108,0,0,89,2,2740], + [115.103,115.326,59,73,4,0,89,2,2741], + [115.103,115.548,28,83,6,0,89,2,2741], + [115.104,115.326,47,67,5,0,89,2,2741], + [115.104,115.326,36,114,16,0,89,2,2741], + [115.107,115.326,83,70,14,0,89,2,2741], + [115.323,115.548,80,63,14,0,89,2.5,2746], + [115.326,115.54,72,109,0,0,89,2.5,2746], + [115.327,115.548,52,82,5,0,89,2.5,2746], + [115.327,115.548,64,81,4,0,89,2.5,2746], + [115.537,115.985,69,108,0,0,90,0,2751], + [115.542,115.77,38,103,16,0,90,0,2751], + [115.542,115.77,57,103,4,0,90,0,2751], + [115.545,116.885,72,80,2,1,90,0,2751], + [115.545,116.885,33,87,11,0,90,0,2751], + [115.546,116.885,60,72,3,1,90,0,2751], + [115.548,115.77,45,100,5,0,90,0,2751], + [115.548,116.885,60,78,13,1,90,0,2751], + [115.548,116.885,40,112,17,0,90,0,2751], + [115.548,116.885,76,89,2,2,90,0,2751], + [115.549,115.993,33,103,6,0,90,0,2751], + [115.549,116.885,57,86,13,0,90,0,2751], + [115.549,116.885,60,80,7,1,90,0,2751], + [115.55,115.77,45,81,1,0,90,0,2751], + [115.55,115.77,81,83,14,0,90,0,2751], + [115.55,116.885,57,86,7,0,90,0,2751], + [115.551,116.885,64,74,3,2,90,0,2751], + [115.552,116.885,57,76,3,0,90,0,2751], + [115.553,116.885,64,82,13,2,90,0,2751], + [115.554,116.885,69,82,2,0,90,0,2751], + [115.769,115.993,57,69,4,0,90,0.5,2756], + [115.769,115.993,84,66,14,0,90,0.5,2756], + [115.771,115.993,52,87,1,0,90,0.5,2756], + [115.771,115.993,40,72,16,0,90,0.5,2756], + [115.776,115.993,45,64,5,0,90,0.5,2757], + [115.988,116.438,33,76,6,0,90,1,2762], + [115.993,116.215,88,68,14,0,90,1,2762], + [115.993,116.215,52,74,5,0,90,1,2762], + [115.993,116.215,57,79,1,0,90,1,2762], + [115.994,116.215,64,79,4,0,90,1,2762], + [115.998,116.215,42,79,16,0,90,1,2762], + [116.206,116.43,60,94,0,0,90,1.5,2767], + [116.213,116.438,36,120,16,0,90,1.5,2767], + [116.215,116.438,57,97,4,0,90,1.5,2767], + [116.216,116.438,45,95,5,0,90,1.5,2767], + [116.22,116.438,93,88,14,0,90,1.5,2767], + [116.432,116.653,64,98,0,0,90,2,2772], + [116.432,116.661,64,71,4,0,90,2,2772], + [116.435,116.661,40,81,16,0,90,2,2772], + [116.437,116.661,52,74,5,0,90,2,2772], + [116.437,116.661,88,71,14,0,90,2,2772], + [116.438,116.885,33,86,6,0,90,2,2772], + [116.653,116.877,69,98,0,0,90,2.5,2777], + [116.659,116.885,57,82,5,0,90,2.5,2778], + [116.659,116.885,69,83,4,0,90,2.5,2778], + [116.661,116.885,42,92,16,0,90,2.5,2778], + [116.661,116.885,84,67,14,0,90,2.5,2778], + [116.88,117.324,71,105,0,0,91,0,2783], + [116.88,117.108,36,122,16,0,91,0,2783], + [116.88,118.228,64,81,2,0,91,0,2783], + [116.882,118.228,40,113,17,0,91,0,2783], + [116.882,117.108,52,105,4,0,91,0,2783], + [116.883,118.228,52,83,7,0,91,0,2783], + [116.883,118.228,41,95,23,0,91,0,2783], + [116.883,117.108,40,82,1,0,91,0,2783], + [116.883,117.108,76,82,14,0,91,0,2783], + [116.884,118.228,56,84,7,1,91,0,2783], + [116.884,117.332,28,102,6,0,91,0,2783], + [116.884,118.228,56,83,13,1,91,0,2783], + [116.885,117.108,40,101,5,0,91,0,2783], + [116.886,118.228,68,84,2,1,91,0,2783], + [116.886,118.228,28,93,11,0,91,0,2783], + [116.887,118.228,59,74,3,2,91,0,2783], + [116.887,118.228,71,79,2,2,91,0,2783], + [116.887,118.228,56,80,3,1,91,0,2783], + [116.888,118.228,59,79,13,2,91,0,2783], + [116.889,118.228,52,81,13,0,91,0,2783], + [116.891,118.228,52,75,3,0,91,0,2783], + [117.101,117.332,52,80,1,0,91,0.5,2788], + [117.102,117.332,52,70,4,0,91,0.5,2788], + [117.105,117.332,80,70,14,0,91,0.5,2788], + [117.106,117.332,40,74,5,0,91,0.5,2788], + [117.328,117.556,38,84,16,0,91,1,2794], + [117.331,117.78,28,86,6,0,91,1,2794], + [117.331,117.556,47,74,5,0,91,1,2794], + [117.331,117.556,56,79,1,0,91,1,2794], + [117.332,117.556,83,67,14,0,91,1,2794], + [117.333,117.556,59,78,4,0,91,1,2794], + [117.546,117.772,64,91,0,0,91,1.5,2799], + [117.55,117.78,40,96,16,0,91,1.5,2799], + [117.553,117.78,88,82,14,0,91,1.5,2799], + [117.557,117.78,52,100,4,0,91,1.5,2799], + [117.557,117.78,40,94,5,0,91,1.5,2799], + [117.774,117.996,72,100,0,0,91,2,2804], + [117.779,118.228,28,89,6,0,91,2,2804], + [117.78,118.004,59,75,4,0,91,2,2804], + [117.78,118.004,47,73,5,0,91,2,2804], + [117.783,118.004,36,112,16,0,91,2,2804], + [117.784,118.004,83,69,14,0,91,2,2804], + [117.997,118.22,71,99,0,0,91,2.5,2809], + [117.999,118.228,52,82,5,0,91,2.5,2809], + [118.007,118.228,64,82,4,0,91,2.5,2810], + [118.008,118.228,80,70,14,0,91,2.5,2810], + [118.222,118.67,69,97,0,0,92,0,2815], + [118.226,119.579,69,77,2,0,92,0,2815], + [118.227,119.579,57,75,3,0,92,0,2815], + [118.227,119.579,40,104,17,0,92,0,2815], + [118.227,119.579,57,88,7,0,92,0,2815], + [118.228,119.579,76,80,2,2,92,0,2815], + [118.228,118.453,45,94,5,0,92,0,2815], + [118.228,118.453,81,83,14,0,92,0,2815], + [118.229,118.453,45,82,1,0,92,0,2815], + [118.229,119.579,60,75,3,1,92,0,2815], + [118.23,119.579,60,82,13,1,92,0,2815], + [118.23,119.579,33,90,11,0,92,0,2815], + [118.23,118.678,33,102,6,0,92,0,2815], + [118.231,119.579,64,80,13,2,92,0,2815], + [118.231,119.579,57,80,13,0,92,0,2815], + [118.232,118.453,40,107,19,0,92,0,2815], + [118.232,119.579,64,75,3,2,92,0,2815], + [118.232,118.453,38,106,16,0,92,0,2815], + [118.233,119.579,72,79,2,1,92,0,2815], + [118.233,118.453,57,98,4,0,92,0,2815], + [118.235,119.579,60,79,7,1,92,0,2815], + [118.447,118.678,45,70,5,0,92,0.5,2820], + [118.45,118.678,52,84,1,0,92,0.5,2820], + [118.451,118.678,42,111,19,0,92,0.5,2820], + [118.454,118.678,57,68,4,0,92,0.5,2820], + [118.454,118.678,84,67,14,0,92,0.5,2820], + [118.456,118.678,40,76,16,0,92,0.5,2820], + [118.673,118.903,57,81,1,0,92,1,2826], + [118.677,118.903,64,81,4,0,92,1,2826], + [118.677,118.903,52,84,5,0,92,1,2826], + [118.679,118.903,42,85,16,0,92,1,2826], + [118.68,118.903,88,68,14,0,92,1,2826], + [118.681,118.903,40,113,19,0,92,1,2826], + [118.682,119.128,33,82,6,0,92,1,2826], + [118.897,119.12,71,103,0,0,92,1.5,2831], + [118.901,119.128,57,101,4,0,92,1.5,2831], + [118.902,119.128,42,114,19,0,92,1.5,2831], + [118.903,119.128,36,114,16,0,92,1.5,2831], + [118.904,119.128,93,84,14,0,92,1.5,2831], + [118.906,119.128,45,101,5,0,92,1.5,2831], + [119.119,119.345,72,109,0,0,92,2,2836], + [119.13,119.353,88,71,14,0,92,2,2836], + [119.13,119.353,64,73,4,0,92,2,2836], + [119.13,119.353,52,71,5,0,92,2,2836], + [119.13,119.579,33,89,6,0,92,2,2836], + [119.131,119.353,40,86,16,0,92,2,2836], + [119.133,119.353,40,121,19,0,92,2,2837], + [119.345,119.571,74,101,0,0,92,2.5,2842], + [119.348,119.579,69,79,4,0,92,2.5,2842], + [119.348,119.579,42,127,19,0,92,2.5,2842], + [119.348,119.579,57,79,5,0,92,2.5,2842], + [119.35,119.579,42,96,16,0,92,2.5,2842], + [119.351,119.579,84,60,14,0,92,2.5,2842], + [119.573,120.937,48,73,3,0,93,0,2847], + [119.576,120.937,40,106,17,0,93,0,2847], + [119.576,120.937,24,106,9,0,93,0,2847], + [119.576,120.937,36,119,22,0,93,0,2847], + [119.576,120.937,48,77,13,0,93,0,2847], + [119.576,120.249,76,106,0,0,93,0,2847], + [119.577,119.805,72,88,14,0,93,0,2847], + [119.577,120.937,55,79,13,2,93,0,2847], + [119.578,119.805,48,99,4,0,93,0,2847], + [119.579,120.937,52,75,3,1,93,0,2847], + [119.579,120.937,55,74,3,2,93,0,2847], + [119.579,119.805,48,82,1,0,93,0,2847], + [119.58,120.937,67,81,2,2,93,0,2847], + [119.58,119.805,36,97,5,0,93,0,2847], + [119.58,120.937,36,113,10,2,93,0,2847], + [119.581,120.937,36,101,8,2,93,0,2847], + [119.581,120.031,24,103,6,0,93,0,2847], + [119.581,120.937,31,101,8,1,93,0,2847], + [119.581,120.937,52,79,13,1,93,0,2847], + [119.581,120.937,52,121,18,0,93,0,2847], + [119.582,120.937,64,81,2,1,93,0,2847], + [119.582,120.031,36,111,16,0,93,0,2847], + [119.582,120.937,24,117,10,0,93,0,2847], + [119.583,120.937,24,102,8,0,93,0,2847], + [119.583,120.937,49,117,21,0,93,0,2847], + [119.583,120.937,60,80,2,0,93,0,2847], + [119.584,120.937,24,87,11,0,93,0,2847], + [119.587,120.937,31,118,10,1,93,0,2847], + [119.803,120.031,55,86,1,0,93,0.5,2852], + [119.804,120.031,36,74,5,0,93,0.5,2852], + [119.807,120.031,48,71,4,0,93,0.5,2853], + [119.808,120.031,76,65,14,0,93,0.5,2853], + [120.026,120.257,79,67,14,0,93,1,2858], + [120.027,120.257,43,76,5,0,93,1,2858], + [120.032,120.257,60,88,1,0,93,1,2858], + [120.033,120.257,55,79,4,0,93,1,2858], + [120.034,120.483,24,83,6,0,93,1,2858], + [120.247,120.475,67,92,0,0,93,1.5,2863], + [120.253,120.483,48,99,4,0,93,1.5,2863], + [120.255,120.483,84,80,14,0,93,1.5,2863], + [120.255,120.483,36,100,5,0,93,1.5,2863], + [120.261,120.483,38,71,16,0,93,1.5,2863], + [120.475,120.702,77,104,0,0,93,2,2868], + [120.482,120.937,40,83,16,0,93,2,2869], + [120.483,120.937,24,88,6,0,93,2,2869], + [120.483,120.71,79,62,14,0,93,2,2869], + [120.483,120.71,43,70,5,0,93,2,2869], + [120.487,120.71,55,74,4,0,93,2,2869], + [120.703,120.929,76,106,0,0,93,2.5,2874], + [120.71,120.937,48,79,5,0,93,2.5,2874], + [120.71,120.937,60,80,4,0,93,2.5,2874], + [120.713,120.937,76,64,14,0,93,2.5,2874], + [120.931,121.61,74,117,0,0,94,0,2879], + [120.932,122.302,55,75,13,0,94,0,2879], + [120.933,122.302,59,83,13,1,94,0,2879], + [120.934,121.164,55,104,4,0,94,0,2879], + [120.934,122.302,31,95,11,0,94,0,2879], + [120.935,122.302,67,87,2,0,94,0,2879], + [120.936,122.302,40,109,17,0,94,0,2879], + [120.936,121.391,31,105,6,0,94,0,2879], + [120.937,121.164,38,92,16,0,94,0,2879], + [120.937,121.164,79,83,14,0,94,0,2879], + [120.937,122.302,62,83,13,2,94,0,2879], + [120.938,121.164,43,104,5,0,94,0,2879], + [120.938,121.164,43,84,1,0,94,0,2879], + [120.939,122.302,55,80,3,0,94,0,2879], + [120.939,122.302,71,86,2,1,94,0,2879], + [120.939,122.302,62,76,3,2,94,0,2880], + [120.941,122.302,59,75,3,1,94,0,2880], + [120.942,122.302,74,80,2,2,94,0,2880], + [121.162,121.391,55,76,4,0,94,0.5,2885], + [121.162,121.391,55,79,1,0,94,0.5,2885], + [121.163,121.391,83,70,14,0,94,0.5,2885], + [121.164,121.391,43,74,5,0,94,0.5,2885], + [121.388,121.846,31,75,6,0,94,1,2890], + [121.389,121.618,86,68,14,0,94,1,2890], + [121.392,121.618,62,81,4,0,94,1,2890], + [121.392,121.618,50,75,5,0,94,1,2890], + [121.393,121.618,40,74,16,0,94,1,2890], + [121.396,121.618,59,80,1,0,94,1,2890], + [121.608,121.838,65,94,0,0,94,1.5,2895], + [121.614,121.846,91,85,14,0,94,1.5,2896], + [121.616,121.846,43,94,5,0,94,1.5,2896], + [121.62,121.846,40,58,16,0,94,1.5,2896], + [121.622,121.846,55,100,4,0,94,1.5,2896], + [121.836,122.066,76,106,0,0,94,2,2901], + [121.841,122.302,31,90,6,0,94,2,2901], + [121.843,122.074,50,72,5,0,94,2,2901], + [121.845,122.074,86,68,14,0,94,2,2901], + [121.846,122.074,62,78,4,0,94,2,2901], + [121.847,122.302,38,102,16,0,94,2,2901], + [122.069,122.294,74,106,0,0,94,2.5,2906], + [122.072,122.302,55,77,5,0,94,2.5,2906], + [122.072,122.302,83,68,14,0,94,2.5,2906], + [122.073,122.302,67,85,4,0,94,2.5,2907], + [122.296,122.758,33,104,6,0,95,0,2912], + [122.296,123.674,76,87,2,2,95,0,2912], + [122.297,123.674,60,78,3,1,95,0,2912], + [122.299,122.979,72,114,0,0,95,0,2912], + [122.3,123.674,57,77,13,0,95,0,2912], + [122.3,123.674,72,81,2,1,95,0,2912], + [122.301,123.674,64,76,13,2,95,0,2912], + [122.301,123.674,40,110,17,0,95,0,2912], + [122.301,123.674,57,81,3,0,95,0,2912], + [122.302,122.53,81,84,14,0,95,0,2912], + [122.302,123.674,64,79,3,2,95,0,2912], + [122.302,123.674,60,81,13,1,95,0,2912], + [122.303,123.674,69,83,2,0,95,0,2912], + [122.303,122.53,45,98,5,0,95,0,2912], + [122.304,123.674,33,93,11,0,95,0,2912], + [122.305,122.53,57,101,4,0,95,0,2912], + [122.305,122.758,36,105,16,0,95,0,2912], + [122.305,122.53,45,83,1,0,95,0,2912], + [122.526,122.758,84,71,14,0,95,0.5,2917], + [122.527,122.758,57,77,4,0,95,0.5,2917], + [122.529,122.758,45,64,5,0,95,0.5,2917], + [122.533,122.758,52,84,1,0,95,0.5,2917], + [122.754,123.215,33,78,6,0,95,1,2923], + [122.756,122.987,88,68,14,0,95,1,2923], + [122.758,122.987,57,87,1,0,95,1,2923], + [122.76,122.987,52,82,5,0,95,1,2923], + [122.761,122.987,64,86,4,0,95,1,2923], + [122.983,123.215,93,78,14,0,95,1.5,2928], + [122.984,123.215,57,101,4,0,95,1.5,2928], + [122.984,123.207,64,97,0,0,95,1.5,2928], + [122.987,123.215,45,96,5,0,95,1.5,2928], + [122.988,123.215,38,76,16,0,95,1.5,2928], + [123.203,123.436,74,102,0,0,95,2,2933], + [123.214,123.674,40,85,16,0,95,2,2934], + [123.215,123.674,33,84,6,0,95,2,2934], + [123.217,123.444,64,74,4,0,95,2,2934], + [123.218,123.444,52,70,5,0,95,2,2934], + [123.219,123.444,88,62,14,0,95,2,2934], + [123.438,123.666,72,98,0,0,95,2.5,2939], + [123.44,123.674,57,78,5,0,95,2.5,2939], + [123.447,123.674,84,69,14,0,95,2.5,2939], + [123.447,123.674,69,83,4,0,95,2.5,2939], + [123.664,124.125,71,105,0,0,96,0,2944], + [123.668,123.903,40,83,1,0,96,0,2944], + [123.668,125.053,59,75,3,2,96,0,2944], + [123.669,123.903,76,83,14,0,96,0,2944], + [123.67,125.053,71,86,2,2,96,0,2945], + [123.671,123.903,38,95,16,0,96,0,2945], + [123.672,125.053,52,77,13,0,96,0,2945], + [123.672,125.053,68,83,2,1,96,0,2945], + [123.673,125.053,59,78,13,2,96,0,2945], + [123.673,125.053,64,87,2,0,96,0,2945], + [123.674,125.053,56,76,13,1,96,0,2945], + [123.674,123.903,40,99,5,0,96,0,2945], + [123.675,123.903,52,104,4,0,96,0,2945], + [123.675,125.053,28,98,11,0,96,0,2945], + [123.675,125.053,40,110,17,0,96,0,2945], + [123.675,124.133,28,106,6,0,96,0,2945], + [123.677,125.053,56,75,3,1,96,0,2945], + [123.678,125.053,52,76,3,0,96,0,2945], + [123.899,124.133,52,82,1,0,96,0.5,2950], + [123.903,124.133,40,73,5,0,96,0.5,2950], + [123.905,124.133,80,66,14,0,96,0.5,2950], + [123.907,124.133,52,70,4,0,96,0.5,2950], + [124.129,124.362,59,82,4,0,96,1,2955], + [124.129,124.362,40,69,16,0,96,1,2955], + [124.129,124.362,83,66,14,0,96,1,2955], + [124.13,124.362,47,76,5,0,96,1,2955], + [124.131,124.362,64,84,1,0,96,1,2956], + [124.131,124.592,28,78,6,0,96,1,2956], + [124.352,124.584,64,99,0,0,96,1.5,2961], + [124.358,124.592,40,63,16,0,96,1.5,2961], + [124.362,124.592,40,101,5,0,96,1.5,2961], + [124.368,124.592,88,86,14,0,96,1.5,2961], + [124.37,124.592,52,97,4,0,96,1.5,2961], + [124.583,124.815,76,96,0,0,96,2,2966], + [124.593,124.823,59,75,4,0,96,2,2966], + [124.594,125.053,28,87,6,0,96,2,2967], + [124.594,124.823,83,66,14,0,96,2,2967], + [124.594,124.823,47,70,5,0,96,2,2967], + [124.595,125.053,38,103,16,0,96,2,2967], + [124.82,125.053,52,86,5,0,96,2.5,2972], + [124.821,125.053,64,83,4,0,96,2.5,2972], + [124.822,125.053,80,66,14,0,96,2.5,2972], + [124.823,125.053,64,78,1,0,96,2.5,2972], + [125.048,126.44,68,83,2,1,97,0,2977], + [125.049,126.44,28,95,11,0,97,0,2977], + [125.051,126.44,59,75,3,2,97,0,2977], + [125.051,126.44,59,82,13,2,97,0,2977], + [125.051,125.284,76,76,1,0,97,0,2977], + [125.052,126.44,52,75,3,0,97,0,2977], + [125.052,125.284,40,99,5,0,97,0,2977], + [125.052,125.514,28,103,6,0,97,0,2977], + [125.052,126.44,52,78,13,0,97,0,2977], + [125.053,126.44,64,83,2,0,97,0,2977], + [125.053,126.44,56,74,3,1,97,0,2977], + [125.053,126.44,41,88,23,0,97,0,2977], + [125.053,125.284,76,85,14,0,97,0,2977], + [125.053,126.44,71,85,2,2,97,0,2977], + [125.054,126.44,40,106,17,0,97,0,2977], + [125.054,125.284,52,100,4,0,97,0,2977], + [125.054,125.514,36,106,16,0,97,0,2977], + [125.056,126.44,56,81,13,1,97,0,2978], + [125.277,125.514,52,72,4,0,97,0.5,2983], + [125.277,125.506,76,105,0,0,97,0.5,2983], + [125.281,125.514,40,64,5,0,97,0.5,2983], + [125.286,125.514,80,67,14,0,97,0.5,2983], + [125.504,125.737,88,92,0,0,97,1,2988], + [125.513,125.745,59,80,4,0,97,1,2988], + [125.513,125.745,83,67,14,0,97,1,2988], + [125.514,125.977,28,82,6,0,97,1,2988], + [125.516,125.745,47,72,5,0,97,1,2988], + [125.744,125.977,88,84,14,0,97,1.5,2994], + [125.748,125.977,38,71,16,0,97,1.5,2994], + [125.749,125.977,75,77,1,0,97,1.5,2994], + [125.751,125.977,52,99,4,0,97,1.5,2994], + [125.751,125.977,40,95,5,0,97,1.5,2994], + [125.971,126.208,76,73,1,0,97,2,2999], + [125.977,126.208,83,69,14,0,97,2,2999], + [125.978,126.208,47,69,5,0,97,2,2999], + [125.98,126.44,40,85,16,0,97,2,3000], + [125.98,126.208,59,75,4,0,97,2,3000], + [125.98,126.44,28,85,6,0,97,2,3000], + [126.193,126.432,75,101,0,0,97,2.5,3005], + [126.203,126.44,80,60,14,0,97,2.5,3005], + [126.205,126.44,52,76,5,0,97,2.5,3005], + [126.207,126.44,64,84,4,0,97,2.5,3005], + [126.427,126.895,76,106,0,0,98,0,3010], + [126.435,127.834,71,81,2,2,98,0,3010], + [126.436,127.834,59,76,3,2,98,0,3010], + [126.436,127.834,52,75,13,0,98,0,3010], + [126.436,127.834,64,84,2,0,98,0,3010], + [126.437,126.903,28,100,6,0,98,0,3010], + [126.437,126.671,40,109,19,0,98,0,3010], + [126.438,127.834,28,90,11,0,98,0,3010], + [126.438,127.834,59,81,13,2,98,0,3010], + [126.439,126.671,38,95,16,0,98,0,3010], + [126.439,127.834,68,86,2,1,98,0,3010], + [126.44,127.834,40,113,17,0,98,0,3010], + [126.44,127.834,52,77,3,0,98,0,3010], + [126.442,126.671,52,107,4,0,98,0,3011], + [126.442,126.671,76,85,14,0,98,0,3011], + [126.444,127.834,56,75,3,1,98,0,3011], + [126.444,127.834,56,76,13,1,98,0,3011], + [126.445,126.671,40,98,5,0,98,0,3011], + [126.668,126.903,40,70,5,0,98,0.5,3016], + [126.669,126.903,42,109,19,0,98,0.5,3016], + [126.676,126.903,75,80,1,0,98,0.5,3016], + [126.676,126.903,80,66,14,0,98,0.5,3016], + [126.676,126.903,52,70,4,0,98,0.5,3016], + [126.901,127.136,59,81,4,0,98,1,3021], + [126.902,127.136,47,80,5,0,98,1,3021], + [126.903,127.136,40,71,16,0,98,1,3022], + [126.905,127.136,40,112,19,0,98,1,3022], + [126.906,127.368,28,84,6,0,98,1,3022], + [126.909,127.136,76,77,1,0,98,1,3022], + [126.91,127.136,83,60,14,0,98,1,3022], + [127.132,127.36,75,100,0,0,98,1.5,3027], + [127.138,127.368,40,95,5,0,98,1.5,3027], + [127.138,127.368,52,96,4,0,98,1.5,3027], + [127.138,127.368,42,117,19,0,98,1.5,3027], + [127.139,127.368,88,92,14,0,98,1.5,3027], + [127.143,127.368,40,58,16,0,98,1.5,3027], + [127.358,127.593,76,104,0,0,98,2,3032], + [127.366,127.834,38,104,16,0,98,2,3033], + [127.367,127.601,83,64,14,0,98,2,3033], + [127.367,127.601,59,73,4,0,98,2,3033], + [127.368,127.601,40,114,19,0,98,2,3033], + [127.372,127.834,28,88,6,0,98,2,3033], + [127.373,127.601,47,73,5,0,98,2,3033], + [127.597,127.834,52,81,5,0,98,2.5,3038], + [127.598,127.826,75,106,0,0,98,2.5,3038], + [127.6,127.834,42,127,19,0,98,2.5,3038], + [127.603,127.834,64,80,4,0,98,2.5,3038], + [127.604,127.834,80,62,14,0,98,2.5,3038], + [127.827,128.059,76,107,0,0,99,0,3043], + [127.827,129.235,28,103,8,0,99,0,3044], + [127.83,129.235,56,81,3,1,99,0,3044], + [127.83,129.235,40,113,17,0,99,0,3044], + [127.83,128.067,40,99,5,0,99,0,3044], + [127.83,129.235,35,115,10,1,99,0,3044], + [127.83,129.235,35,100,8,1,99,0,3044], + [127.83,129.235,52,83,13,0,99,0,3044], + [127.831,129.235,28,101,9,0,99,0,3044], + [127.831,129.235,59,73,3,2,99,0,3044], + [127.831,129.235,68,80,2,1,99,0,3044], + [127.832,129.235,28,92,11,0,99,0,3044], + [127.832,128.3,28,103,6,0,99,0,3044], + [127.832,129.235,40,115,10,2,99,0,3044], + [127.833,129.235,71,85,2,2,99,0,3044], + [127.833,129.235,68,86,15,1,99,0,3044], + [127.833,129.235,56,87,7,1,99,0,3044], + [127.833,129.235,59,81,13,2,99,0,3044], + [127.834,129.235,28,112,10,0,99,0,3044], + [127.834,129.235,56,81,13,1,99,0,3044], + [127.835,129.235,36,109,22,0,99,0,3044], + [127.835,128.067,52,109,4,0,99,0,3044], + [127.835,129.235,71,80,15,2,99,0,3044], + [127.835,129.235,49,116,21,0,99,0,3044], + [127.835,128.067,76,83,14,0,99,0,3044], + [127.836,128.067,36,119,16,0,99,0,3044], + [127.836,129.235,64,86,15,0,99,0,3044], + [127.836,129.235,52,88,7,0,99,0,3044], + [127.837,129.235,64,77,2,0,99,0,3044], + [127.838,129.235,40,99,8,2,99,0,3044], + [127.84,129.235,52,73,3,0,99,0,3044], + [127.84,129.235,52,111,18,0,99,0,3044], + [128.06,128.3,52,73,4,0,99,0.5,3049], + [128.06,128.292,75,100,0,0,99,0.5,3049], + [128.065,128.3,80,66,14,0,99,0.5,3049], + [128.07,128.3,40,67,5,0,99,0.5,3049], + [128.288,128.526,76,112,0,0,99,1,3054], + [128.296,128.534,47,78,5,0,99,1,3055], + [128.297,128.767,28,76,6,0,99,1,3055], + [128.299,128.534,38,79,16,0,99,1,3055], + [128.301,128.534,59,79,4,0,99,1,3055], + [128.305,128.534,83,59,14,0,99,1,3055], + [128.521,128.759,71,105,0,0,99,1.5,3060], + [128.528,128.767,40,93,5,0,99,1.5,3060], + [128.532,128.767,40,100,16,0,99,1.5,3060], + [128.535,128.767,88,87,14,0,99,1.5,3060], + [128.538,128.767,52,90,4,0,99,1.5,3060], + [128.757,128.993,74,105,0,0,99,2,3066], + [128.766,129.001,83,69,14,0,99,2,3066], + [128.767,129.235,28,88,6,0,99,2,3066], + [128.769,129.001,59,70,4,0,99,2,3066], + [128.769,129.001,36,109,16,0,99,2,3066], + [128.774,129.001,47,74,5,0,99,2,3066], + [128.994,129.227,72,102,0,0,99,2.5,3071], + [128.999,129.235,64,84,4,0,99,2.5,3071], + [129.002,129.235,80,61,14,0,99,2.5,3071], + [129.003,129.235,52,75,5,0,99,2.5,3071], + [129.232,130.645,60,80,3,1,100,0,3077], + [129.233,129.47,38,108,16,0,100,0,3077], + [129.233,130.645,64,81,13,2,100,0,3077], + [129.233,130.645,64,73,3,2,100,0,3077], + [129.234,129.47,81,86,14,0,100,0,3077], + [129.234,130.645,72,77,2,1,100,0,3077], + [129.234,130.645,69,85,15,0,100,0,3077], + [129.234,130.645,40,109,17,0,100,0,3077], + [129.234,130.645,57,77,13,0,100,0,3077], + [129.235,129.47,57,107,4,0,100,0,3077], + [129.235,129.696,69,109,0,0,100,0,3077], + [129.236,130.645,60,85,7,1,100,0,3077], + [129.236,130.645,57,84,7,0,100,0,3077], + [129.237,130.645,76,85,15,2,100,0,3077], + [129.237,130.645,57,73,3,0,100,0,3077], + [129.237,130.645,69,84,2,0,100,0,3077], + [129.238,130.645,33,96,11,0,100,0,3077], + [129.238,130.645,60,78,13,1,100,0,3077], + [129.238,129.704,33,106,6,0,100,0,3077], + [129.239,129.47,45,78,1,0,100,0,3077], + [129.239,129.47,45,99,5,0,100,0,3077], + [129.24,130.645,76,84,2,2,100,0,3077], + [129.241,130.645,72,87,15,1,100,0,3077], + [129.465,129.704,45,71,5,0,100,0.5,3083], + [129.467,129.704,40,72,16,0,100,0.5,3083], + [129.469,129.704,84,63,14,0,100,0.5,3083], + [129.472,129.704,52,83,1,0,100,0.5,3083], + [129.472,129.704,57,70,4,0,100,0.5,3083], + [129.701,129.939,42,80,16,0,100,1,3088], + [129.701,130.174,33,82,6,0,100,1,3088], + [129.701,129.939,57,86,1,0,100,1,3088], + [129.704,129.939,52,74,5,0,100,1,3088], + [129.704,129.939,64,77,4,0,100,1,3088], + [129.708,129.939,88,63,14,0,100,1,3088], + [129.933,130.166,60,96,0,0,100,1.5,3094], + [129.939,130.174,57,98,4,0,100,1.5,3094], + [129.94,130.174,93,82,14,0,100,1.5,3094], + [129.94,130.174,45,92,5,0,100,1.5,3094], + [129.944,130.174,36,120,16,0,100,1.5,3094], + [130.165,130.401,64,101,0,0,100,2,3099], + [130.171,130.409,64,73,4,0,100,2,3099], + [130.171,130.409,88,67,14,0,100,2,3099], + [130.174,130.409,52,66,5,0,100,2,3099], + [130.174,130.645,33,85,6,0,100,2,3099], + [130.177,130.409,40,87,16,0,100,2,3099], + [130.404,130.637,69,104,0,0,100,2.5,3105], + [130.406,130.645,69,81,4,0,100,2.5,3105], + [130.409,130.645,57,78,5,0,100,2.5,3105], + [130.41,130.645,42,90,16,0,100,2.5,3105], + [130.415,130.645,84,65,14,0,100,2.5,3105], + [130.639,132.061,56,85,7,1,101,0,3110], + [130.642,131.108,71,111,0,0,101,0,3111], + [130.642,132.061,59,78,13,2,101,0,3111], + [130.642,132.061,68,84,2,1,101,0,3111], + [130.642,132.061,56,75,3,1,101,0,3111], + [130.643,132.061,68,85,15,1,101,0,3111], + [130.643,130.88,40,103,5,0,101,0,3111], + [130.644,130.88,36,119,16,0,101,0,3111], + [130.644,132.061,59,77,3,2,101,0,3111], + [130.644,132.061,64,89,15,0,101,0,3111], + [130.645,132.061,52,77,3,0,101,0,3111], + [130.645,131.116,28,102,6,0,101,0,3111], + [130.646,132.061,28,95,11,0,101,0,3111], + [130.646,132.061,64,83,2,0,101,0,3111], + [130.646,132.061,56,81,13,1,101,0,3111], + [130.646,132.061,52,88,7,0,101,0,3111], + [130.646,132.061,40,113,17,0,101,0,3111], + [130.647,132.061,71,84,2,2,101,0,3111], + [130.647,130.88,76,88,14,0,101,0,3111], + [130.648,132.061,71,85,15,2,101,0,3111], + [130.649,132.061,52,81,13,0,101,0,3111], + [130.65,130.88,40,80,1,0,101,0,3111], + [130.652,130.88,52,100,4,0,101,0,3111], + [130.878,131.116,52,78,1,0,101,0.5,3116], + [130.88,131.116,52,70,4,0,101,0.5,3116], + [130.885,131.116,80,69,14,0,101,0.5,3116], + [130.885,131.116,40,70,5,0,101,0.5,3116], + [131.114,131.352,59,80,4,0,101,1,3122], + [131.114,131.352,83,69,14,0,101,1,3122], + [131.115,131.352,56,83,1,0,101,1,3122], + [131.116,131.588,28,81,6,0,101,1,3122], + [131.118,131.352,47,80,5,0,101,1,3122], + [131.119,131.352,38,88,16,0,101,1,3122], + [131.345,131.58,64,94,0,0,101,1.5,3127], + [131.348,131.588,88,87,14,0,101,1.5,3127], + [131.348,131.588,40,94,16,0,101,1.5,3127], + [131.352,131.588,52,98,4,0,101,1.5,3127], + [131.355,131.588,40,95,5,0,101,1.5,3127], + [131.581,131.817,68,102,0,0,101,2,3133], + [131.586,131.825,59,74,4,0,101,2,3133], + [131.588,131.825,36,115,16,0,101,2,3133], + [131.589,131.825,47,70,5,0,101,2,3133], + [131.59,131.825,83,64,14,0,101,2,3133], + [131.59,132.061,28,86,6,0,101,2,3133], + [131.819,132.053,71,105,0,0,101,2.5,3139], + [131.825,132.061,52,76,5,0,101,2.5,3139], + [131.825,132.061,80,68,14,0,101,2.5,3139], + [131.827,132.061,64,77,4,0,101,2.5,3139], + [132.054,133.936,57,80,13,0,102,0,3144], + [132.054,132.298,57,95,4,0,102,0,3144], + [132.058,132.535,33,109,6,0,102,0,3144], + [132.058,133.936,57,82,7,0,102,0,3144], + [132.058,133.936,72,86,15,1,102,0,3144], + [132.058,133.936,64,79,3,2,102,0,3144], + [132.058,133.936,72,82,2,1,102,0,3144], + [132.059,133.936,45,110,18,0,102,0,3144], + [132.059,133.936,76,87,15,2,102,0,3144], + [132.059,132.298,45,86,1,0,102,0,3144], + [132.06,132.527,72,116,0,0,102,0,3144], + [132.062,132.298,81,85,14,0,102,0,3144], + [132.062,133.936,55,109,21,0,102,0,3144], + [132.063,133.936,60,83,13,1,102,0,3144], + [132.063,133.936,69,78,2,0,102,0,3144], + [132.063,133.936,76,83,2,2,102,0,3144], + [132.063,133.936,36,119,22,0,102,0,3144], + [132.064,133.936,64,81,13,2,102,0,3144], + [132.064,132.535,36,127,16,0,102,0,3144], + [132.065,133.936,57,73,3,0,102,0,3144], + [132.066,133.936,33,90,11,0,102,0,3144], + [132.066,133.936,60,78,3,1,102,0,3144], + [132.066,133.936,69,84,15,0,102,0,3144], + [132.067,133.936,60,85,7,1,102,0,3144], + [132.068,132.535,40,113,17,0,102,0,3144], + [132.068,132.298,45,98,5,0,102,0,3144], + [132.298,132.535,45,73,5,0,102,0.5,3150], + [132.3,132.535,84,68,14,0,102,0.5,3150], + [132.301,132.535,57,69,4,0,102,0.5,3150], + [132.302,132.535,52,82,1,0,102,0.5,3150], + [132.53,132.773,88,62,14,0,102,1,3155], + [132.531,132.773,57,82,1,0,102,1,3156], + [132.532,132.773,64,78,4,0,102,1,3156], + [132.533,132.773,52,76,5,0,102,1,3156], + [132.535,133.01,33,78,6,0,102,1,3156], + [132.767,133.002,64,92,0,0,102,1.5,3161], + [132.772,133.01,45,101,5,0,102,1.5,3161], + [132.772,133.01,57,99,4,0,102,1.5,3161], + [132.773,133.01,93,83,14,0,102,1.5,3161], + [133.003,133.24,76,105,0,0,102,2,3167], + [133.008,133.936,33,85,6,0,102,2,3167], + [133.013,133.248,64,78,4,0,102,2,3167], + [133.013,133.248,52,73,5,0,102,2,3167], + [133.016,133.248,88,71,14,0,102,2,3167], + [133.239,133.928,75,97,0,0,102,2.5,3172], + [133.243,133.936,69,84,4,0,102,2.5,3172], + [133.245,133.936,84,70,14,0,102,2.5,3173], + [133.252,133.936,57,85,5,0,102,2.5,3173], + [133.932,134.168,76,54,0,0,103,0,3189], + [133.942,137.094,33,53,11,0,103,0,3189], + [134.167,134.411,75,55,0,0,103,0.5,3194], + [134.411,134.657,76,58,0,0,103,1,3200], + [134.661,134.907,71,55,0,0,103,1.5,3206], + [134.906,135.16,74,59,0,0,103,2,3212], + [135.157,135.417,72,56,0,0,103,2.5,3218], + [135.413,135.946,69,58,0,0,104,0,3224], + [135.422,135.686,45,43,1,0,104,0,3224], + [135.688,135.954,52,39,1,0,104,0.5,3231], + [135.951,136.228,57,39,1,0,104,1,3237], + [136.221,136.502,60,48,0,0,104,1.5,3243], + [136.504,136.79,64,48,0,0,104,2,3250], + [136.79,137.086,69,57,0,0,104,2.5,3257], + [137.083,137.714,71,61,0,0,105,0,3264], + [137.096,137.401,40,43,1,0,105,0,3264], + [137.401,137.722,52,39,1,0,105,0.5,3271], + [137.721,138.058,56,47,1,0,105,1,3279], + [138.048,138.403,64,22,0,0,105,1.5,3287], + [138.399,138.778,72,25,0,0,105,2,3295], + [138.776,139.487,71,20,0,0,105,2.5,3304], + [139.488,142.059,69,24,0,0,106,0,3321], + [139.494,142.067,45,22,1,1,106,0,3321], + [139.495,142.067,33,18,1,0,106,0,3321], +]; +/** + * The big hits, for flashes: [at, frame, strength, part] — every impact, and the low drums' and cymbals' strokes struck + * at velocity 110 or more (the kick left out: it is on every pulse); strength 0 … 1 (velocity / 127). + */ +export const HIT_AT = 0, HIT_FRAME = 1, HIT_STRENGTH = 2, HIT_PART = 3; +export const HITS: readonly (readonly number[])[] = [ + [12.699,302,0.92,22], + [25.2,600,0.87,16], + [30.194,719,0.87,16], + [40.2,957,0.98,16], + [40.2,957,0.79,22], + [41.03,977,0.88,16], + [42.071,1002,0.94,16], + [42.696,1017,0.94,16], + [43.946,1046,0.87,16], + [44.573,1061,0.92,16], + [45.2,1076,0.99,16], + [46.032,1096,0.87,16], + [47.072,1121,0.94,16], + [48.114,1146,0.91,16], + [48.327,1151,0.94,16], + [48.536,1156,1,16], + [48.741,1160,0.96,16], + [66.447,1582,0.87,16], + [68.951,1642,0.97,16], + [69.572,1656,0.88,16], + [70.196,1671,1,22], + [70.198,1671,0.95,21], + [70.202,1671,0.92,16], + [70.825,1686,0.91,16], + [71.445,1701,0.93,16], + [72.076,1716,0.87,16], + [72.699,1731,0.91,16], + [73.326,1746,0.87,16], + [73.951,1761,0.97,16], + [74.577,1776,0.89,16], + [75.2,1790,0.91,16], + [76.446,1820,0.98,16], + [77.072,1835,0.88,16], + [77.699,1850,0.98,16], + [78.955,1880,0.99,16], + [79.575,1895,0.87,16], + [80.197,1909,0.94,16], + [80.2,1910,0.94,21], + [80.202,1910,0.99,22], + [80.203,1910,0.94,18], + [81.45,1939,0.97,16], + [82.697,1969,0.95,16], + [83.113,1979,0.89,18], + [83.33,1984,0.89,16], + [83.943,1999,0.99,16], + [84.57,2014,0.9,16], + [85.197,2028,0.92,16], + [85.823,2043,0.87,16], + [86.447,2058,1,16], + [87.697,2088,0.96,16], + [88.318,2103,0.88,16], + [88.948,2118,0.95,18], + [88.949,2118,0.98,21], + [88.949,2118,0.98,16], + [88.95,2118,1,22], + [89.572,2133,0.89,16], + [90.197,2148,0.86,22], + [90.198,2148,0.97,16], + [98.561,2347,0.94,16], + [98.764,2352,0.87,18], + [98.766,2352,0.95,16], + [98.767,2352,1,22], + [98.773,2352,0.93,21], + [99.602,2371,0.89,16], + [100.648,2396,0.94,16], + [101.284,2412,0.91,16], + [102.122,2431,0.87,16], + [103.177,2457,0.93,16], + [103.811,2472,0.94,16], + [104.671,2492,0.88,16], + [105.739,2518,0.91,16], + [106.379,2533,0.94,16], + [107.239,2553,0.87,16], + [108.318,2579,0.94,16], + [108.965,2594,0.92,21], + [108.969,2595,0.93,16], + [110.919,2641,0.96,16], + [111.576,2657,0.94,16], + [112.454,2677,0.88,16], + [113.554,2704,0.9,16], + [114.216,2719,0.92,16], + [115.104,2741,0.9,16], + [116.213,2767,0.94,16], + [116.88,2783,0.96,16], + [117.783,2804,0.88,16], + [118.903,2831,0.9,16], + [119.576,2847,0.94,22], + [119.581,2847,0.95,18], + [119.582,2847,0.87,16], + [119.583,2847,0.92,21], + [127.835,3044,0.86,22], + [127.835,3044,0.91,21], + [127.836,3044,0.94,16], + [127.84,3044,0.87,18], + [129.944,3094,0.94,16], + [130.644,3111,0.94,16], + [131.588,3133,0.91,16], + [132.059,3144,0.87,18], + [132.063,3144,0.94,22], + [132.064,3144,1,16], +]; diff --git a/probes/lib/fur-elise-cinematic.ts b/probes/lib/fur-elise-cinematic.ts new file mode 100644 index 0000000..180a3bb --- /dev/null +++ b/probes/lib/fur-elise-cinematic.ts @@ -0,0 +1,106 @@ +// Für Elise, the cinematic arrangement, rendered when the script is built (probes/lib/fur-elise-cinematic-score.ts is +// the notes). Importing this starts nothing: probes/fur-elise-cinematic.ts plays it, and a showcase program imports +// `whole` (one clip for the whole piece: one long clip keeps time with the game) or the sections' clips (the fallback). +// +// Rendered a section at a time (`music.excerpt`), each with the hall and its tail under the next, the band's sections +// through a bus compressor; all of them turned by one gain so the whole is at −14 LUFS with the intro quiet and the +// storm the loudest, as played; the whole limited once. +// +// Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). Orchestra and percussion: VSCO 2 Community Edition +// by Versilian Studios (CC0). Synths, risers and impacts: made in the script. Instruments: probes/lib/fur-elise-sound-gen.mts. +import { music, type Instrument } from "trigscript/music"; +import piano from "../salamander-grand.samples"; +import violinsSet from "../vsco-violins.samples"; +import violasSet from "../vsco-violas.samples"; +import violasSpicSet from "../vsco-violas-spic.samples"; +import celliSpicSet from "../vsco-celli-spic.samples"; +import bassSpicSet from "../vsco-bass-spic.samples"; +import hornsSet from "../vsco-horns.samples"; +import tromboneSet from "../vsco-trombone.samples"; +import tubaSet from "../vsco-tuba.samples"; +import timpaniSet from "../vsco-timpani.samples"; +import percussionSet from "../vsco-percussion.samples"; +import { cinematic, PART_ROLES, type PartName } from "./fur-elise-cinematic-score"; + +export const LUFS = -14; +const HALL = { decay: 0.84, damping: 0.5, predelay: 0.032 }; +const MASTER = (c: Clip) => c.filter("highpass", 26); +/** The band's bus: 2:1 above −18 dB, slow enough to let the hits through, glue for the rest. */ +const BUS = (c: Clip) => MASTER(c).compress({ threshold: -18, ratio: 2, attack: 0.025, release: 0.3, knee: 6 }); +const QUALITY = 6; +/** Seconds a bar lasts at the band's 144 eighths a minute. */ +const BAR = (3 * 60) / 144; + +export const arrangement = cinematic(); +const grand = music.sampled(piano, { resonance: 0.07 }); +const percussion = music.sampled(percussionSet, { releases: false }); +/** One-shots: impacts, the sub drop, the kick, the crash reversed, risers. The intro's riser is made to its length below. */ +const kit = music.drums({ volume: 0.9 }); +const impact = music.impact({ seconds: 3, volume: 0.9 }).mix(music.impact({ seconds: 2.2, volume: 0.5 }).pitch(-5)); +const subDrop = tone([[0, 70], [1.6, 28]], 2.2, { volume: 0.9, rate: 44100 }).envelope([0, 0], [0.01, 1], [2.2, 0]); +const crashBack = (percussionSet.zones.find((z) => z.key === 49 && z.vhi === 127) ?? percussionSet.zones[0]).clip.trim(0, 2 * BAR).reverse().fade(0.6, 0.004); +const fx = (intro: number) => music.hits({ + C2: impact, D2: subDrop, E2: kit.hits.k, F2: crashBack, + G2: music.riser(4 * BAR, { volume: 0.45 }), A2: music.riser(3 * BAR, { volume: 0.4 }), B2: music.riser(intro, { volume: 0.4 }), +}); + +/** + * How each part is heard: its instrument, where, how loud, how much hall. Volumes set by measuring each alone in the + * storm (2026-11-09) against the piano's right hand at −13 LUFS: the taiko −15, the braam −17, the toms −19, the + * strings −20 … −22, the brass −22 … −24, the synths −21 … −24, the kick −20, the sub −22. + */ +function heard(fxInstrument: Instrument): Record Clip; lead?: number; velocity?: number }> { + return { + // (The piano's ff chords in the storm stood 6 dB over everything else's peaks: a quick compressor on the piano.) + right: { instrument: grand, lead: 0.008, reverb: 0.2, volume: 1.4, fx: (c) => c.compress({ threshold: -20, ratio: 3, attack: 0.002, release: 0.12, knee: 6, makeup: 3 }) }, + left: { instrument: grand, velocity: 0.92 }, + violins: { instrument: music.sampled(violinsSet), pan: -0.45, volume: 4.2, reverb: 0.35 }, + violas: { instrument: music.sampled(violasSet), pan: 0.25, volume: 1.1, reverb: 0.35 }, + ostinato: { instrument: music.sampled(violasSpicSet), pan: -0.25, volume: 2.8, reverb: 0.25 }, + celli: { instrument: music.sampled(celliSpicSet), pan: 0.35, volume: 1.45, reverb: 0.25 }, + basses: { instrument: music.sampled(bassSpicSet), pan: 0.5, volume: 2.0, reverb: 0.2 }, + horns: { instrument: music.sampled(hornsSet), pan: -0.15, volume: 1.0, reverb: 0.4 }, + trombones: { instrument: music.sampled(tromboneSet), pan: 0.2, volume: 4.0, reverb: 0.35 }, + tuba: { instrument: music.sampled(tubaSet), pan: 0.25, volume: 2.7, reverb: 0.3 }, + braam: { instrument: music.presets.braam(), volume: 0.9, reverb: 0.3 }, + sub: { instrument: music.presets.sub(), volume: 0.45 }, + drone: { instrument: music.presets.pad({ volume: 0.08 }), reverb: 0.5 }, + pad: { instrument: music.presets.pad({ volume: 0.095 }), reverb: 0.4, fx: music.pump(BAR, 0.55) }, + pulse: { instrument: music.presets.pulse(), pan: 0.3, volume: 1.4, reverb: 0.2, fx: (c) => c.delay(BAR / 3, { feedback: 0.25, mix: 0.2, pingPong: true }) }, + supersaw: { instrument: music.presets.supersaw({ volume: 0.145 }), reverb: 0.3, fx: (c) => c.chorus({ mix: 0.3 }) }, + taiko: { instrument: percussion, volume: 1.6, reverb: 0.3 }, + kick: { instrument: fxInstrument, volume: 0.42 }, + timpani: { instrument: music.sampled(timpaniSet), pan: -0.1, volume: 2.4, reverb: 0.4 }, + toms: { instrument: percussion, pan: 0.15, volume: 1.2, reverb: 0.3 }, + snare: { instrument: percussion, pan: -0.1, volume: 1.0, reverb: 0.35 }, + cymbals: { instrument: percussion, pan: 0.1, volume: 0.9, reverb: 0.35 }, + impacts: { instrument: fxInstrument, volume: 0.55, reverb: 0.3 }, + risers: { instrument: fxInstrument, volume: 0.9, reverb: 0.3 }, + }; +} + +const played = (fxInstrument: Instrument) => { + const how = heard(fxInstrument), parts: Record = {}; + for (const k of Object.keys(PART_ROLES) as PartName[]) parts[k] = { ...how[k], notes: arrangement.parts[k] }; + return music.perform({ meter: "3/8", bpm: 120, pickup: "1/8", tempo: arrangement.tempo, holds: arrangement.holds, humanize: { time: 0.003, velocity: 3, seed: 11 } }, parts as never); +}; +// Played once to learn the intro's free time, then again with the intro's riser made to end on the band's downbeat +// (the instruments do not change when a note is played). +const rehearsal = played(fx(4)); +/** The arrangement as played: every note's time in the whole. */ +export const take = played(fx(rehearsal.bars[9] - rehearsal.bars[6])); +export const sections = arrangement.sections.map((s) => ({ name: s.name, from: s.from, to: s.to, at: take.bars[s.from], frame: Math.round(take.bars[s.from] / 0.042) })); + +const raw = arrangement.sections.map((s, k) => music.render(music.excerpt(take, s.from, k + 1 < arrangement.sections.length ? s.to : undefined), { + reverb: HALL, master: s.name === "intro" || s.name === "ending" ? MASTER : BUS, limit: false, +})); +/** Each section's fader, dB: the storm the loudest; the final statement big, but under it. */ +const FADER: Readonly> = { intro: 0, band: 0, lift: 0, storm: 1, breakdown: 0, final: -2, ending: 0 }; +const faded = raw.map((c, k) => { const g = FADER[arrangement.sections[k].name] ?? 0; return g === 0 ? c : c.gain(10 ** (g / 20)); }); +// (A little over −14 before the limiter, which takes some of it back.) +const level = together(faded.map((c, k) => ({ clip: c, at: sections[k].at })), { lufs: LUFS + 0.4 }); + +/** The whole piece, one clip: the sections added up at their times, limited once. */ +export const whole = mixdown(level.map((c, k) => ({ clip: c, at: sections[k].at }))).limit({ ceiling: 0.8 }).ogg(QUALITY); +/** Each section with its tail, at the level it has in the whole: the fallback. */ +export const sectionClips = level.map((c) => c.limit({ ceiling: 0.8 }).ogg(QUALITY)); diff --git a/probes/lib/fur-elise-sound-gen.mts b/probes/lib/fur-elise-sound-gen.mts index ae13c43..bc41992 100644 --- a/probes/lib/fur-elise-sound-gen.mts +++ b/probes/lib/fur-elise-sound-gen.mts @@ -4,7 +4,8 @@ // salamander-grand-v3/ Salamander Grand Piano V3, 44.1 kHz 16-bit (Alexander Holm, CC BY 3.0), from // freepats.zenvoid.org: SalamanderGrandPianoV3+20161209_44khz16bit.tar.xz, unpacked into extracted/ // vsco2-ce/ VSCO 2 Community Edition (Versilian Studios, CC0), from github.com/sgossner/VSCO-2-CE: the -// string sections' sustains and spiccati, tenor trombone, tuba, horn, timpani +// string sections' sustains and spiccati, tenor trombone, tuba, horn, timpani; for the +// cinematic arrangement its percussion too (bass drums, tenor drums, snare, cymbals, gong) // // and one .sound: the piano's middle C at one strength, imported the old way (22 050 Hz, one channel, IMA ADPCM), for // the probe's first item. Everything lands in probes/ (ignored by git). @@ -40,6 +41,9 @@ vsco("Brass/F Horn/sus", "vsco-horns", "French horn (VSCO 2 CE)", "--octave", "1 vsco("Percussion/Timpani", "vsco-timpani", "Timpani (VSCO 2 CE)", "--pitch", "Timpani1=41.45,Timpani2=46.75,Timpani3=49.5,Timpani4=52.45,Timpani5=54.6", "--seconds", "6", "--release", "2"); vsco("Percussion/Timpani/Rolls", "vsco-timpani-rolls", "Timpani rolls (VSCO 2 CE)", "--pitch", "Timpani1=42,Timpani2=47,Timpani3=49.5,Timpani4=52.5,Timpani5=55", "--seconds", "12", "--release", "1"); +// The cinematic arrangement's percussion: a kit, a key a drum (probes/lib/vsco-percussion.kit.json). +make("--kit", join(import.meta.dirname, "vsco-percussion.kit.json"), join(out, "vsco-percussion.samples"), "--name", "Percussion (VSCO 2 CE)", "--credit", VSCO, "--seconds", "12"); + // Middle C, one strength (the 10th of 16), as Import Video… would have made it: one channel, 22 050 Hz, the first 8 s. const wav = readFileSync(join(SAL, "44.1khz16bit", "C4v10.wav")); const data = wav.indexOf("data"), n = Math.min(wav.readUInt32LE(data + 4) / 4, 8 * 44100); diff --git a/probes/lib/fur-elise-timeline-gen.mts b/probes/lib/fur-elise-timeline-gen.mts index 1c807d8..92b181f 100644 --- a/probes/lib/fur-elise-timeline-gen.mts +++ b/probes/lib/fur-elise-timeline-gen.mts @@ -3,7 +3,8 @@ // place in its chord, its bar, beat and frame — the sections with their frames, the bars, the pedal. Worked out by the // script's own build (a check: no samples made), so it is the soundtrack's timing exactly. // -// npx tsx probes/lib/fur-elise-timeline-gen.mts +// npx tsx probes/lib/fur-elise-timeline-gen.mts # the straight soundtrack: fur-elise-timeline.ts +// npx tsx probes/lib/fur-elise-timeline-gen.mts --cinematic # the cinematic arrangement: fur-elise-cinematic-timeline.ts import { writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; @@ -13,12 +14,16 @@ import { defaultLib } from "../../bundle/lib.mjs"; import { scriptFiles } from "../../scripts/script-files.mts"; const root = join(import.meta.dirname, "..", ".."); -const files = scriptFiles(join(root, "probes", "fur-elise.ts")); -// The build hands values back only in its words: the line it fails with carries them. -files["main.ts"] += ` +const cinematic = process.argv.includes("--cinematic"); +const files = scriptFiles(join(root, "probes", cinematic ? "fur-elise-cinematic.ts" : "fur-elise.ts")); +// The build hands values back only in its words: the line it fails with carries them. (Added to the module that has +// the performance, so the arrangement's roles are at hand.) +const into = cinematic ? "lib/fur-elise-cinematic.ts" : "main.ts"; +files[into] += ` const r3 = (x: number) => Math.round(x * 1000) / 1000; +const roles = ${cinematic ? "take.parts.map((p) => (PART_ROLES as Record)[p])" : "take.parts.map((p) => ({ right: \"lead\", left: \"accomp\", violins: \"strings\", violas: \"strings\", celli: \"strings\", basses: \"bass\", horns: \"brass\", trombones: \"brass\", tuba: \"brass\", timpani: \"drum-low\", roll: \"drum-low\" } as Record)[p])"}; throw new Error("TIMELINE " + JSON.stringify({ - seconds: r3(take.seconds), parts: take.parts, bars: take.bars.map(r3), pedal: take.pedal.map((p) => [r3(p[0]), r3(p[1])]), + seconds: r3(take.seconds), parts: take.parts, roles, bars: take.bars.map(r3), pedal: take.pedal.map((p) => [r3(p[0]), r3(p[1])]), sections: sections.map((s) => ({ name: s.name, bar: s.from, at: r3(s.at), frame: s.frame })), notes: take.notes.map((n) => [r3(n.at), r3(n.end), n.pitch, n.velocity, take.parts.indexOf(n.part), n.voice, n.bar, r3(n.beat), n.frame]), })); @@ -26,17 +31,28 @@ throw new Error("TIMELINE " + JSON.stringify({ const r = compileScript(ts, files, defaultScriptNames(), { lib: defaultLib(), sounds: false }); const line = r.diagnostics.map((d) => d.message).find((m) => m.includes("TIMELINE ")); if (!line) { for (const d of r.diagnostics) console.error(d.message); process.exit(1); } -const t = JSON.parse(line.slice(line.indexOf("TIMELINE ") + 9)) as { seconds: number; parts: string[]; bars: number[]; pedal: number[][]; sections: { name: string; bar: number; at: number; frame: number }[]; notes: number[][] }; +const t = JSON.parse(line.slice(line.indexOf("TIMELINE ") + 9)) as { seconds: number; parts: string[]; roles: string[]; bars: number[]; pedal: number[][]; sections: { name: string; bar: number; at: number; frame: number }[]; notes: number[][] }; const rows = (list: unknown[][]) => list.map((x) => ` ${JSON.stringify(x)},`).join("\n"); -const text = `// Generated by probes/lib/fur-elise-timeline-gen.mts from probes/fur-elise.ts: do not edit, make it again. -// Für Elise as the soundtrack plays it (the whole piece as one clip, from 0). Seconds from its start; a frame is 42 ms +// The big hits, for a picture's flashes: every impact; the taiko, timpani and gong/crash strokes struck at 110 or more. +const BIG = new Set(["impact"]), STRONG = new Set(["drum-low", "cymbal"]); +const hits = t.notes.filter((n) => BIG.has(t.roles[n[4]]) || (STRONG.has(t.roles[n[4]]) && t.parts[n[4]] !== "kick" && n[3] >= 110)) + .map((n) => [n[0], n[8], Math.round((n[3] / 127) * 100) / 100, n[4]]); +const text = `// Generated by probes/lib/fur-elise-timeline-gen.mts${cinematic ? " --cinematic" : ""} from probes/${cinematic ? "fur-elise-cinematic.ts" : "fur-elise.ts"}: do not edit, make it again. +// Für Elise ${cinematic ? "(the cinematic arrangement) " : ""}as the soundtrack plays it (the whole piece as one clip, from 0). Seconds from its start; a frame is 42 ms // (Fastest). The picture runs ahead of a long clip's sound by about 95 ms (the visualizer probe, 2026-11-09): the // program shifts the picture, not these numbers. /** Seconds from the first note to the last let go (the held A's ring and the hall's tail come after). */ export const SECONDS = ${t.seconds}; -/** The parts, by the number NOTES gives them: the hands, then the orchestra's parts (only in the storm). */ +/** The parts, by the number NOTES gives them. */ export const PARTS = ${JSON.stringify(t.parts)} as const; +/** + * Each part's role, by the same number: "lead" (the piano's right hand, the theme), "accomp" (its left hand)${cinematic ? `, + * "strings", "brass", "bass", "synth", "pad", "drum-low" (taiko, kick, timpani), "drum-high" (tenor drums, snare), + * "cymbal" (crash, suspended cymbal, gong), "impact" (impacts and the sub drop), "riser" (risers, crashes reversed)` : `, + * "strings", "bass", "brass", "drum-low" (the timpani)`}. + */ +export const ROLES = ${JSON.stringify(t.roles)} as const; /** The sections, in order: the bar each begins on (BARS' numbering), and where, in seconds and frames. */ export const SECTIONS: readonly { readonly name: string; readonly bar: number; readonly at: number; readonly frame: number }[] = ${JSON.stringify(t.sections)}; /** Seconds each bar begins: [0] the pickup's start, [k] bar k's. */ @@ -49,12 +65,22 @@ ${rows(t.pedal)} export const AT = 0, END = 1, PITCH = 2, VELOCITY = 3, PART = 4, VOICE = 5, BAR = 6, BEAT = 7, FRAME = 8; /** * Every note in the order struck: [at, end, pitch, velocity, part, voice, bar, beat, frame] — seconds struck and let go - * (the key; the pedal may hold it on), the key (60 is C4), 1 … 127, PARTS' number, its place in its chord (0 the lowest), - * the bar, the beat in it (eighths from 0), the frame it is struck on. + * (the key; the pedal may hold it on), the key (60 is C4; for a drum, cymbal, impact or riser the kit's key, not a + * pitch), 1 … 127, PARTS' number, its place in its chord (0 the lowest), the bar, the beat in it (eighths from 0), the + * frame it is struck on. */ export const NOTES: readonly (readonly number[])[] = [ ${rows(t.notes)} ]; +/** + * The big hits, for flashes: [at, frame, strength, part] — every impact, and the low drums' and cymbals' strokes struck + * at velocity 110 or more (the kick left out: it is on every pulse); strength 0 … 1 (velocity / 127). + */ +export const HIT_AT = 0, HIT_FRAME = 1, HIT_STRENGTH = 2, HIT_PART = 3; +export const HITS: readonly (readonly number[])[] = [ +${rows(hits)} +]; `; -writeFileSync(join(root, "probes", "lib", "fur-elise-timeline.ts"), text); -console.log(`probes/lib/fur-elise-timeline.ts: ${t.notes.length} notes, ${t.sections.length} sections, ${t.seconds} s`); +const out = cinematic ? "fur-elise-cinematic-timeline.ts" : "fur-elise-timeline.ts"; +writeFileSync(join(root, "probes", "lib", out), text); +console.log(`probes/lib/${out}: ${t.notes.length} notes, ${hits.length} hits, ${t.sections.length} sections, ${t.seconds} s`); diff --git a/probes/lib/fur-elise-timeline.ts b/probes/lib/fur-elise-timeline.ts index 7971efb..c6dbc2c 100644 --- a/probes/lib/fur-elise-timeline.ts +++ b/probes/lib/fur-elise-timeline.ts @@ -5,8 +5,13 @@ /** Seconds from the first note to the last let go (the held A's ring and the hall's tail come after). */ export const SECONDS = 198.988; -/** The parts, by the number NOTES gives them: the hands, then the orchestra's parts (only in the storm). */ +/** The parts, by the number NOTES gives them. */ export const PARTS = ["right","left","violins","violas","celli","basses","horns","trombones","tuba","timpani","roll"] as const; +/** + * Each part's role, by the same number: "lead" (the piano's right hand, the theme), "accomp" (its left hand), + * "strings", "bass", "brass", "drum-low" (the timpani). + */ +export const ROLES = ["lead","accomp","strings","strings","strings","bass","brass","brass","brass","drum-low","drum-low"] as const; /** The sections, in order: the bar each begins on (BARS' numbering), and where, in seconds and frames. */ export const SECTIONS: readonly { readonly name: string; readonly bar: number; readonly at: number; readonly frame: number }[] = [{"name":"A","bar":0,"at":0,"frame":0},{"name":"B","bar":44,"at":67.761,"frame":1613},{"name":"A again","bar":60,"at":94.434,"frame":2248},{"name":"storm","bar":81,"at":127.133,"frame":3027},{"name":"closing","bar":99,"at":152.906,"frame":3641}]; /** Seconds each bar begins: [0] the pickup's start, [k] bar k's. */ @@ -84,8 +89,9 @@ export const PEDAL: readonly (readonly [number, number])[] = [ export const AT = 0, END = 1, PITCH = 2, VELOCITY = 3, PART = 4, VOICE = 5, BAR = 6, BEAT = 7, FRAME = 8; /** * Every note in the order struck: [at, end, pitch, velocity, part, voice, bar, beat, frame] — seconds struck and let go - * (the key; the pedal may hold it on), the key (60 is C4), 1 … 127, PARTS' number, its place in its chord (0 the lowest), - * the bar, the beat in it (eighths from 0), the frame it is struck on. + * (the key; the pedal may hold it on), the key (60 is C4; for a drum, cymbal, impact or riser the kit's key, not a + * pitch), 1 … 127, PARTS' number, its place in its chord (0 the lowest), the bar, the beat in it (eighths from 0), the + * frame it is struck on. */ export const NOTES: readonly (readonly number[])[] = [ [0,0.264,76,45,0,0,0,0,0], @@ -1429,3 +1435,13 @@ export const NOTES: readonly (readonly number[])[] = [ [196.414,198.988,45,22,1,1,125,0,4677], [196.423,198.988,33,29,1,0,125,0,4677], ]; +/** + * The big hits, for flashes: [at, frame, strength, part] — every impact, and the low drums' and cymbals' strokes struck + * at velocity 110 or more (the kick left out: it is on every pulse); strength 0 … 1 (velocity / 127). + */ +export const HIT_AT = 0, HIT_FRAME = 1, HIT_STRENGTH = 2, HIT_PART = 3; +export const HITS: readonly (readonly number[])[] = [ + [139.362,3318,0.98,9], + [140.706,3350,0.9,9], + [148.933,3546,0.91,9], +]; diff --git a/probes/lib/vsco-percussion.kit.json b/probes/lib/vsco-percussion.kit.json new file mode 100644 index 0000000..b53a337 --- /dev/null +++ b/probes/lib/vsco-percussion.kit.json @@ -0,0 +1,19 @@ +{ + "root": "../../../samples/vsco2-ce", + "release": 3, + "drums": { + "C2": ["Percussion/BDrumNewhit_*"], + "C#2": ["VSCO 1 Percussion/drums/bass/bdrum_ppp_*", "VSCO 1 Percussion/drums/bass/bdrum_pp_*", "VSCO 1 Percussion/drums/bass/bdrum_p_*", "VSCO 1 Percussion/drums/bass/bdrum_mp_*", "VSCO 1 Percussion/drums/bass/bdrum_f_*", "VSCO 1 Percussion/drums/bass/bdrum_ff_*", "VSCO 1 Percussion/drums/bass/bdrum_fff_*"], + "D2": ["VSCO 1 Percussion/drums/bass/bdrum_muted_*"], + "E2": ["VSCO 1 Percussion/drums/tenor/tenor_lower/tenor_*"], + "F#2": ["VSCO 1 Percussion/drums/tenor/tenor_higher/tenorH_*"], + "G2": ["Percussion/Snare2-HitSN_*"], + "G#2": ["Percussion/Snare2-rollSN_*"], + "C#3": ["Percussion/cymbal-crash1_*"], + "D#3": ["Percussion/susCymb1-hit_*"], + "E3": ["Percussion/susCymb1-cresc-Short_*"], + "F3": ["Percussion/susCymb1-cresc-Median_*"], + "F#3": ["Percussion/susCymb1-cresc-Long_*"], + "G3": ["Percussion/gongHit_*"] + } +} diff --git a/scripts/tuning-check.mts b/scripts/tuning-check.mts index af0c925..0d8c132 100644 --- a/scripts/tuning-check.mts +++ b/scripts/tuning-check.mts @@ -2,7 +2,8 @@ * Whether a render is in tune, note by note: for each pitch a timeline says is struck, the frequency of its * fundamental and its second harmonic just after each onset (an FFT over up to 0.2 s, the peak within a semitone of * where it should be, refined by a parabola), the median over every time it is struck, in cents against equal - * temperament at A4 = 440 — judged by the fundamental, or under 200 Hz by the second harmonic. A pitch more than 25 cents off is flagged — above C6 a piano is tuned wider (its octaves + * temperament at A4 = 440 — judged by the fundamental, or under 200 Hz by the second harmonic, and called off only when + * both readings say so. Under 80 Hz nothing is judged. A pitch more than 25 cents off is flagged — above C6 a piano is tuned wider (its octaves * stretched), so there it may be sharp by 1.5 cents a semitone more. * * npx tsx scripts/tuning-check.mts [--offset=seconds] [--parts=0,1] [--all] @@ -74,7 +75,7 @@ for (const n of mod.NOTES) { per.set(pitch, out); } const median = (xs: number[]) => { const s = xs.filter(Number.isFinite).sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : NaN; }; -let off = 0, checked = 0; +let off = 0, checked = 0, low80 = 0; for (const p of [...per.keys()].sort((a, b) => a - b)) { const v = per.get(p)!, c = median(v.c), c2 = median(v.c2), n = Math.max(v.c.length, v.c2.length); // The value to judge: the fundamental — but under 200 Hz the second harmonic, since 0.2 s cannot place a low @@ -82,12 +83,15 @@ for (const p of [...per.keys()].sort((a, b) => a - b)) { const low = 440 * 2 ** ((p - 69) / 12) < 200; const cents = low && Number.isFinite(c2) ? c2 : Number.isFinite(c) ? c : c2; if (!Number.isFinite(cents)) continue; + // Under 80 Hz only the second harmonic is read, and 0.2 s cannot place it in a dense mix (a sine sub has none). + if (440 * 2 ** ((p - 69) / 12) < 80) { low80++; continue; } checked++; - // Off when the judged value is, and the other one (where there is one) agrees: a wrong note moves both. + // Off when the judged value is, and the other one (where there is one) agrees: a wrong note moves both, where a + // neighbour in the same chord (C#5 beside D5) moves one reading only. const stretch = Math.max(0, p - 84) * 1.5, outside = (v: number) => v > LIMIT + stretch || v < -LIMIT; - const other = cents === c ? c2 : c, bad = outside(cents) && (!Number.isFinite(other) || outside(other) || !low); + const other = cents === c ? c2 : c, bad = outside(cents) && (!Number.isFinite(other) || outside(other)); if (bad) off++; if (bad || args.includes("--all")) console.log(`${bad ? "OFF " : " "}${name(p).padEnd(4)} ${String(p).padEnd(3)} ×${String(n).padEnd(4)} fundamental ${Number.isFinite(c) ? c.toFixed(0).padStart(4) : " –"} cents, 2nd harmonic ${Number.isFinite(c2) ? c2.toFixed(0).padStart(4) : " –"}`); } -console.log(`${checked} pitches checked, ${off} off by more than ${LIMIT} cents (above C6, ${LIMIT} plus 1.5 a semitone sharp allowed).`); +console.log(`${checked} pitches checked, ${off} off by more than ${LIMIT} cents (above C6, ${LIMIT} plus 1.5 a semitone sharp allowed)${low80 ? `; ${low80} under 80 Hz not judged` : ""}.`); process.exitCode = off ? 1 : 0; From d6756801f628a7d393520367938afd4fbff9945f Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 06:41:18 -0600 Subject: [PATCH 24/31] =?UTF-8?q?F=C3=BCr=20Elise=20showcase=20on=20the=20?= =?UTF-8?q?cinematic=20arrangement,=20with=20one=20switch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit probes/lib/fur-elise-showcase-choice.ts picks the soundtrack: the cinematic arrangement by default, the straight piece with FUR_ELISE=straight under Node; the showcase plays that one clip and draws that timeline. The run reads ROLES: the piano's lead (gold) and accompaniment (cyan) on the keyboards, drums, cymbals, impacts and risers on no roll. The storm keeps the user's red chords and red flashes; in the big sections (the storm and the final) the rest of the band falls on the minimap in violet and the strongest low-drum hits pulse the minimap keyboard red; the intro and the ending show the piano alone, the main screen only the piano throughout. Explosions come from HITS: the impacts of strength 0.9 or more, 4 s apart (seven, Battlecruisers on the strongest); the straight piece, with none, keeps its accented downbeats. The run's tests cover both soundtracks. In the lifted game every frame holds the worked-out picture on both; at most 0.71 ms a frame. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- probes/answers/fur-elise-showcase.txt | 42 ++++--- probes/fur-elise-showcase.ts | 28 +++-- probes/lib/fur-elise-showcase-choice.ts | 17 +++ probes/lib/fur-elise-showcase-run.ts | 141 +++++++++++++---------- tests/fur-elise-showcase-run.test.ts | 147 ++++++++++++++---------- 5 files changed, 232 insertions(+), 143 deletions(-) create mode 100644 probes/lib/fur-elise-showcase-choice.ts diff --git a/probes/answers/fur-elise-showcase.txt b/probes/answers/fur-elise-showcase.txt index d9c812d..9560e1c 100644 --- a/probes/answers/fur-elise-showcase.txt +++ b/probes/answers/fur-elise-showcase.txt @@ -1,7 +1,8 @@ -Für Elise, the showcase build: a check play -=========================================== +Für Elise, the showcase on the cinematic arrangement: a check play +================================================================= -Map: trigscript-fur-elise.scx (lobby "Für Elise"). About 3 minutes 40 seconds, nothing to press. +Map: trigscript-fur-elise.scx (lobby "Für Elise"). About 2 minutes 40 seconds, nothing to press. +(trigscript-fur-elise-straight.scx beside it is the same showcase on the straight piece, 3:38, for comparison.) Stills of what it should look like: fur-elise-showcase-frames.png beside the map (the minimap on the left, the main screen on the right, as the build works them out — not the game's own drawing). @@ -13,21 +14,32 @@ What to record What is where ------------- -- Main screen: a keyboard of Flags, A1 to E7 (40 white keys, the black keys above them). Notes fall onto it, right hand - gold, left hand cyan; each key lights in its hand's colour while it sounds. -- Minimap: the same notes falling onto a keyboard row (white and indigo keys), the orchestra's parts in violet during - the storm. -- The storm (about 2:10 to 2:35): the right hand's chords red, the white keys flash red on each chord, explosions on - three downbeats (Wraiths at 2:12 and 2:23, three Battlecruisers on the last big chord at 2:33), with their sounds. -- Text: "Für Elise" at the start; "Für Elise — Ludwig van Beethoven" when the last note is let go (about 3:25). +- Main screen: a keyboard of Flags, A1 to E7 (40 white keys, the black keys above them). The piano's notes fall onto + it, right hand gold, left hand cyan; each key lights in its hand's colour while it sounds. Only the piano is drawn + there, all the way through. +- Minimap: the same notes falling onto a keyboard row. In the storm and the final statement the rest of the band + (strings, brass, bass, synths, pads) falls in violet too, and the keyboard's front row pulses red on the biggest + drum hits. The intro and the ending show the piano alone. +- The storm (about 1:12 to 1:36): the right hand's chords red, the white keys flash red on each chord. +- Explosions, with the game's own explosion sounds (times from the start of the game, about): + 0:16 the band comes in (its first downbeat): Wraiths over the melody + 1:14 the storm's first big hit: three Battlecruisers + 1:24 the storm, the middle: Wraiths + 1:33 the storm's last big hit: three Battlecruisers + 1:42 the final statement begins (the theme returns): three Battlecruisers + 2:03 the final, a big bar: Wraiths + 2:16 the final's last big bar: Wraiths +- Text: "Für Elise" at the start; "Für Elise — Ludwig van Beethoven" when the last note is let go (about 2:28). After that the keyboard stays and the game waits; leave when the sound has rung out. What to look at --------------- -1. Do the notes land on the keys as you hear them (not early, not late)? The clip now starts two frames before the - picture, to take up the ~95 ms the probe measured. -> +1. Do the notes land on the keys as you hear them (not early, not late)? The clip starts two frames before the + picture, to take up the ~95 ms the visualizer probe measured. -> 2. Does the main-screen keyboard fit in the view, both ends visible (A1 at the far left, E7 at the far right)? -> 3. Do the first text line and the end line show the ü and the dash (—) properly? -> -4. The storm: red chords, red flashes, the three explosions: right amount, or too much / too little? -> -5. The minimap: does the violet orchestra in the storm read well, or is it clutter? -> -6. Any stray unit, a Flag or Overlord in the wrong place, an error text, a stutter or slowdown? -> +4. The explosions: the right moments, too many, too few? Are their sounds all right over this music? -> +5. The minimap in the storm and the final: does the violet band read well, or is it clutter? Do the red pulses on the + drum hits help? -> +6. Are the intro and the ending calm enough (only the piano)? -> +7. Any stray unit, a Flag or Overlord in the wrong place, an error text, a stutter or slowdown? -> diff --git a/probes/fur-elise-showcase.ts b/probes/fur-elise-showcase.ts index 90e53c4..cb3b87c 100644 --- a/probes/fur-elise-showcase.ts +++ b/probes/fur-elise-showcase.ts @@ -1,11 +1,13 @@ -// Für Elise, TrigScript Showcase #3: the whole piece (probes/lib/fur-elise-soundtrack.ts, one clip) drawn as it plays — -// notes falling onto a keyboard on the minimap (Overlords over Space, the other parts in violet) and on the main screen -// (Flag-looking Spider Mines, a row every other frame), right hand gold, left hand cyan, a loud section's chords red -// with the white keys flashing red on each, explosions on its strongest downbeats. +// Für Elise, TrigScript Showcase #3: the whole piece as one clip — the cinematic arrangement (probes/lib/ +// fur-elise-cinematic.ts) or the straight piece (probes/lib/fur-elise-soundtrack.ts), as probes/lib/ +// fur-elise-showcase-choice.ts says (FUR_ELISE=straight when built under Node) — drawn as it plays: notes falling onto a +// keyboard on the minimap (Overlords over Space; the rest of the band in violet in the big sections) and on the main +// screen (Flag-looking Spider Mines, a row every other frame), right hand gold, left hand cyan, the storm's chords red +// with the white keys flashing red on each, explosions on the strongest moments. // // Every frame's picture is worked out when the script is built (probes/lib/fur-elise-showcase-run.ts, from the -// soundtrack's timeline, probes/lib/fur-elise-timeline.ts — made again by fur-elise-timeline-gen.mts when the soundtrack -// changes; the run takes its parts, sections, range and accents from it); the program plays the changes back. The clip starts two frames before the +// chosen soundtrack's timeline, made by probes/lib/fur-elise-timeline-gen.mts; the run takes its parts, sections, range +// and big moments from it); the program plays the changes back. The clip starts two frames before the // picture's frame 0: the visualizer probe measured the picture ~95 ms ahead of a long clip's sound. // // Host it as multiplayer, alone, with the game's music off (sound effects on). Check sheet: @@ -13,19 +15,25 @@ // // MAP_NAME="Für Elise" MAP_DESCRIPTION="…" npx tsx probes/lib/fur-elise-map.mts fixtures/eud/fur-elise-showcase-base.scx (the description: below) // MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase.scx fixtures/eud/fur-elise-showcase-base.scx +// FUR_ELISE=straight MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase-straight.scx fixtures/eud/fur-elise-showcase-base.scx // SCM_SIM_DIR=~/github/scm-sim-eud npx tsx scripts/test-game.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase-base.scx // -// The piano and orchestra .samples files must be in probes/ (made by probes/lib/fur-elise-sound-gen.mts; never committed). +// The piano, orchestra and percussion .samples files must be in probes/ (made by probes/lib/fur-elise-sound-gen.mts; never committed). // // Players: P1 you (green, owns only the placed Map Revealers), P2 the computer Remastered needs to start a game (owns // nothing: a computer moves its own units), P3 … P8 own the pixels — P3 white keys, P4 indigo black keys, P5 gold right -// hand, P6 cyan left hand, P7 red storm, P8 violet orchestra. +// hand, P6 cyan left hand, P7 red storm, P8 violet band. // probe-players: {"0":{"rgb":[16,252,24]},"1":{"rgb":[120,120,120]},"2":{"rgb":[240,240,240]},"3":{"rgb":[72,56,200]},"4":{"rgb":[255,190,0]},"5":{"rgb":[0,200,255]},"6":{"rgb":[235,20,50]},"7":{"rgb":[170,80,255]}} import { program, nextFrame, print, playWav, centerView, centerLocation, reserveLocation, createUnit, removeUnitAt, killUnitAt, giveUnits, setMemory, units, P3, P4, P5, P6, P7, P8, test, expect } from "trigscript"; -import { whole } from "./lib/fur-elise-soundtrack"; +import { whole as straightWhole } from "./lib/fur-elise-soundtrack"; +import { whole as cinematicWhole } from "./lib/fur-elise-cinematic"; +import { SOUNDTRACK } from "./lib/fur-elise-showcase-choice"; import { CAM_X, CAM_Y, CELL } from "./lib/fur-elise-layout"; import { START, TOTAL, LAST_OFF, STARTS, CX, CY, CKIND, CTO, LABEL_F, LABEL_TEXT, FX_F, FX_K, FX_X, FX_Y, OVERLORD, pictureAt, explosions } from "./lib/fur-elise-showcase-run"; +/** The piece, one clip: the soundtrack the switch picks (only the clip played goes in the map). */ +const WHOLE = SOUNDTRACK === "straight" ? straightWhole : cinematicWhole; + /** units.dat's flingy bytes of types 12 … 15 (Battlecruiser, Spider Mine, Nuclear Missile, Civilian), one dword. */ const LOOKS = 0x664504; const looks = (flingy: number) => 70 + flingy * 256 + 109 * 65536 + 71 * 16777216; @@ -68,7 +76,7 @@ program(async () => { let g = 0, i = 0, l = 0, e = 0, camera = 0; while (g < TOTAL) { // The piece, one clip, two frames before its picture begins. - if (g === START) playWav(whole, 0); + if (g === START) playWav(WHOLE, 0); while (l < LABEL_F.length && LABEL_F[l] === g) { const k = l; LABEL_TEXT.forEach((t, j) => { if (k === j) print(t); }); diff --git a/probes/lib/fur-elise-showcase-choice.ts b/probes/lib/fur-elise-showcase-choice.ts new file mode 100644 index 0000000..a17d999 --- /dev/null +++ b/probes/lib/fur-elise-showcase-choice.ts @@ -0,0 +1,17 @@ +// Which soundtrack the Für Elise showcase plays and draws (probes/fur-elise-showcase.ts): the one switch. "cinematic" +// (the arrangement, probes/lib/fur-elise-cinematic.ts, the default) or "straight" (the piece as written, +// probes/lib/fur-elise-soundtrack.ts). Built under Node, FUR_ELISE=straight picks the other without an edit: +// +// FUR_ELISE=straight MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts … +// +// (In the editor there is no environment: the constant below decides.) +import * as cinematic from "./fur-elise-cinematic-timeline"; +import * as straight from "./fur-elise-timeline"; + +/** The soundtrack when nothing says otherwise. */ +const DEFAULT: "cinematic" | "straight" = "cinematic"; +const asked = (globalThis as { process?: { env?: Record } }).process?.env?.FUR_ELISE; +export const SOUNDTRACK: "cinematic" | "straight" = asked === "straight" || asked === "cinematic" ? asked : DEFAULT; + +/** The chosen soundtrack's timeline: the same shape either way (probes/lib/fur-elise-timeline-gen.mts makes both). */ +export const TIMELINE = SOUNDTRACK === "straight" ? straight : cinematic; diff --git a/probes/lib/fur-elise-showcase-run.ts b/probes/lib/fur-elise-showcase-run.ts index 49e195d..0a1a893 100644 --- a/probes/lib/fur-elise-showcase-run.ts +++ b/probes/lib/fur-elise-showcase-run.ts @@ -1,36 +1,33 @@ // The Für Elise showcase's run (probes/fur-elise-showcase.ts), worked out when the script is built from the soundtrack's -// timeline (probes/lib/fur-elise-timeline.ts): when the one clip starts, the text, and the picture of every frame on +// timeline (the chosen one's: probes/lib/fur-elise-showcase-choice.ts): when the one clip starts, the text, and the picture of every frame on // both screens, flattened into the changes the program plays back. Plain data and functions, so the same run is what // the showcase plays, what tests/fur-elise-showcase-run.test.ts checks and what pictures of it are drawn from // (probes/lib/fur-elise-frames.mts --showcase). // -// It is generic over the timeline (the soundtrack may change: a new arrangement brings new parts, sections and range): -// the parts each screen shows, both keyboards, the loud sections and the explosions are all worked out from the data. +// It is generic over the timeline (probes/lib/fur-elise-showcase-choice.ts picks the cinematic arrangement or the +// straight piece): the parts each screen shows (by ROLES), both keyboards, the storm and the big sections, the +// explosions (from HITS) are all worked out from the data. +// // The looks are the ones the user chose after the visualizer probe (2026-11-09): notes falling onto a keyboard on both -// screens, the main screen's a row every other frame; the lead part (the right hand) gold, the other (the left) cyan; -// in a loud section the lead's chords red and the white keys flashing red on each, and explosions on its strongest -// downbeats. The probe measured the picture ~95 ms ahead of a long clip's sound: the clip starts LEAD frames early. +// screens, the main screen's a row every other frame; the lead (the right hand) gold, the accompaniment (the left) +// cyan; in the storm the lead's chords red and the white keys flashing red on each; explosions on the strongest +// moments; the rest of the band on the minimap in violet in the big sections only, so the intro and ending are calm. The probe measured the picture ~95 ms ahead of a long clip's sound: the clip starts LEAD frames early. import { FRAME, changesOver, fitKeys, isBlack, keyX, rollCells, whiteKeys, type FramedNote, type Pixel, type TimedNote } from "./note-timeline"; -import { NOTES, PARTS, SECTIONS, SECONDS, AT, END, PITCH, VELOCITY, PART, BAR, BEAT, FRAME as FRAME_COL } from "./fur-elise-timeline"; +import { TIMELINE } from "./fur-elise-showcase-choice"; +import { AT, END, PITCH, VELOCITY, PART, BAR, BEAT, FRAME as FRAME_COL, HIT_FRAME, HIT_STRENGTH, HIT_PART } from "./fur-elise-timeline"; import { CELL, VIEW_X, VIEW_Y, CAM_X, BLACK_Y, WHITE_Y, ROW_GAP, FALL_Y0, STAGE_ROWS, MAP_W } from "./fur-elise-layout"; -/* ── The parts ── */ +const { NOTES, ROLES, SECTIONS, SECONDS, HITS } = TIMELINE; -/** A part of drums: its notes are drums, not keys, and no roll shows them (they still count towards a downbeat's weight). */ -export const isDrums = (name: string) => /drum|kit|perc|kick|snare|hat|cymbal|clap/i.test(name); -const PITCHED = PARTS.map((_, k) => k).filter((k) => !isDrums(PARTS[k])); -const count = (k: number) => NOTES.filter((n) => n[PART] === k).length; -const meanPitch = (k: number) => NOTES.filter((n) => n[PART] === k).reduce((sum, n, _, all) => sum + n[PITCH] / all.length, 0); -/** - * The two parts the main screen shows as hands: "right" and "left" when the timeline has them (the piano), else the two - * pitched parts with the most notes, the higher of them the lead. The lead is gold, the other cyan. - */ -export const [LEAD_PART, OTHER_PART] = ((): [number, number] => { - const r = PARTS.indexOf("right" as never), l = PARTS.indexOf("left" as never); - if (r >= 0 && l >= 0) return [r, l]; - const [a, b] = [...PITCHED].sort((x, y) => count(y) - count(x)); - return meanPitch(a) >= meanPitch(b ?? a) ? [a, b ?? a] : [b, a]; -})(); +/* ── The parts, by their roles ── */ + +/** A part of these roles is drums, an impact or a riser: its "pitch" is a kit's key, and no roll shows it. */ +const UNPITCHED = ["drum-low", "drum-high", "cymbal", "impact", "riser"]; +const roleOf = (part: number): string => ROLES[part]; +export const isPitched = (part: number) => !UNPITCHED.includes(roleOf(part)); +/** The piano's two hands, on both keyboards: the lead (the right hand, the theme) gold, the accompaniment cyan. */ +export const LEAD_PART = ROLES.indexOf("lead" as never), OTHER_PART = ROLES.indexOf("accomp" as never); +if (LEAD_PART < 0 || OTHER_PART < 0) throw new Error("The timeline's ROLES name no lead or no accomp."); const onStage = (part: number) => part === LEAD_PART || part === OTHER_PART; /* ── The keyboards ── */ @@ -45,8 +42,11 @@ export const STAGE_LO = STAGE_KEYS.lo, STAGE_HI = STAGE_KEYS.hi; */ export const STAGE_PITCH = Math.max(16, Math.min(20, Math.floor(624 / Math.max(1, whiteKeys(STAGE_LO, STAGE_HI).length - 1)))); export const STAGE_X0 = 830 - (whiteKeys(STAGE_LO, STAGE_HI).length - 1) * STAGE_PITCH; -/** The minimap's keyboard: every pitched part's notes in the map's 64 columns of cells; outliers by octaves. (Für Elise: D2 … E7, A1 up an octave.) */ -export const ROLL_KEYS = fitKeys(NOTES.filter((n) => !isDrums(PARTS[n[PART]])).map((n) => n[PITCH]), MAP_W / 2, "keys"); +/** + * The minimap's keyboard: the piano's notes in the map's 64 columns of cells, outliers by octaves; the other parts are + * folded into it. (Für Elise: A1 … C7, E7's run an octave down.) + */ +export const ROLL_KEYS = fitKeys(NOTES.filter((n) => onStage(n[PART])).map((n) => n[PITCH]), MAP_W / 2, "keys"); export const ROLL_LO = ROLL_KEYS.lo, ROLL_HI = ROLL_KEYS.hi; export const ROLL_COL = Math.floor((MAP_W / 2 - (ROLL_HI - ROLL_LO + 1)) / 2); /** The minimap roll's keyboard rows, and rows of falling notes above them, a row every ROLL_STEP frames. */ @@ -82,22 +82,33 @@ export interface ShowNote extends FramedNote { readonly part: number; /** Each section's first bar, and the bar after the last. */ const sectionEnd = (k: number) => SECTIONS[k + 1]?.bar ?? Infinity; const meanVelocity = (ns: readonly (readonly number[])[]) => ns.reduce((sum, n) => sum + n[VELOCITY], 0) / Math.max(1, ns.length); -const pitchedNotes = NOTES.filter((n) => !isDrums(PARTS[n[PART]])); -/** The loud sections: played at a quarter or more over the piece's mean velocity (Für Elise: the storm, at 1.9 times). */ -export const LOUD = SECTIONS.filter((s, k) => meanVelocity(pitchedNotes.filter((n) => n[BAR] >= s.bar && n[BAR] < sectionEnd(k))) >= 1.25 * meanVelocity(pitchedNotes)).map((s) => s.name); -const loudBar = (bar: number) => SECTIONS.some((s, k) => LOUD.includes(s.name) && bar >= s.bar && bar < sectionEnd(k)); -/** The lead's notes struck together in a loud section (by bar and beat: the performance spreads a chord by a few ms). */ +const pitchedNotes = NOTES.filter((n) => isPitched(n[PART])); +const named = (...names: string[]) => SECTIONS.filter((s) => names.includes(s.name)).map((s) => s.name); +const byVelocity = SECTIONS.filter((s, k) => meanVelocity(pitchedNotes.filter((n) => n[BAR] >= s.bar && n[BAR] < sectionEnd(k))) >= 1.25 * meanVelocity(pitchedNotes)).map((s) => s.name); +/** + * The storm: red chords and red flashes (the user's choice). The section named "storm"; else the loud sections, played + * at a quarter or more over the piece's mean velocity. + */ +export const LOUD = named("storm").length ? named("storm") : byVelocity; +/** + * The big sections, where the rest of the band shows on the minimap in violet: the storm and the final statement (the + * cinematic arrangement); the intro, the ending and the quieter sections show the piano alone. + */ +export const BIG = [...new Set([...LOUD, ...named("final")])]; +const inSections = (names: readonly string[]) => (bar: number) => SECTIONS.some((s, k) => names.includes(s.name) && bar >= s.bar && bar < sectionEnd(k)); +const loudBar = inSections(LOUD), bigBar = inSections(BIG); +/** The lead's notes struck together in the storm (by bar and beat: the performance spreads a chord by a few ms). */ const struckWith = new Map(); for (const n of NOTES) if (n[PART] === LEAD_PART && loudBar(n[BAR])) struckWith.set(`${n[BAR]} ${n[BEAT]}`, (struckWith.get(`${n[BAR]} ${n[BEAT]}`) ?? 0) + 1); -export const notes: readonly ShowNote[] = NOTES.filter((n) => !isDrums(PARTS[n[PART]])).map((n) => { +export const notes: readonly ShowNote[] = NOTES.filter((n) => onStage(n[PART]) || (isPitched(n[PART]) && bigBar(n[BAR]))).map((n) => { // The timeline's own frame for the strike (the soundtrack's), and the frames its key is held. const on = ZERO + n[FRAME_COL], off = ZERO + Math.round(n[END] / FRAME); const source: TimedNote = { time: n[AT], seconds: n[END] - n[AT], note: n[PITCH], hand: n[PART], velocity: n[VELOCITY] }; const stormChord = n[PART] === LEAD_PART && loudBar(n[BAR]) && (struckWith.get(`${n[BAR]} ${n[BEAT]}`) ?? 0) >= 2; return { source, on, len: Math.max(2, off - on), note: n[PITCH], hand: n[PART], velocity: n[VELOCITY], chord: stormChord, part: n[PART], bar: n[BAR], beat: n[BEAT], stormChord }; }); -/** The hands, on both screens; the rest (the orchestra, …), on the minimap only. */ +/** The hands, on both screens; the rest of the band (strings, brass, bass, synths, pads), in the big sections, on the minimap only. */ export const piano = notes.filter((n) => onStage(n.part)); const orchestra = notes.filter((n) => !onStage(n.part)); @@ -112,6 +123,16 @@ export const flashes = new Set(); for (const f of first.values()) { flashes.add(f); flashes.add(f + 1); } } +/** + * The low drums' strongest strokes in the big sections (taiko, timpani: HITS of the role "drum-low", strength 0.95 or + * more): the minimap's keyboard front row pulses red for three frames on each — the beat felt on the minimap, the main + * screen left to the piano. + */ +export const pulses = new Set(); +for (const h of HITS) if (roleOf(h[HIT_PART]) === "drum-low" && h[HIT_STRENGTH] >= 0.95 && SECTIONS.some((s, k) => BIG.includes(s.name) && h[HIT_FRAME] >= s.frame && h[HIT_FRAME] < (SECTIONS[k + 1]?.frame ?? Infinity))) { + for (let d = 0; d < 3; d++) pulses.add(ZERO + h[HIT_FRAME] + d); +} + /* ── What each frame shows ── */ const colorOf = (n: ShowNote) => (!onStage(n.part) ? VIOLET : n.part === OTHER_PART ? CYAN : n.stormChord ? RED : GOLD); @@ -158,7 +179,7 @@ function draw(f: number, before: readonly Pixel[]): Pixel[] { const idle = isBlack(key) ? INDIGO : flash ? RED : WHITE; const color = keyColor(key, idle, rollKey); out.push({ x: rollX(key), y: rollY(ROLL_KEY_ROW), unit: OVERLORD, color }); - if (!isBlack(key)) out.push({ x: rollX(key), y: rollY(ROLL_KEY_ROW + 1), unit: OVERLORD, color }); + if (!isBlack(key)) out.push({ x: rollX(key), y: rollY(ROLL_KEY_ROW + 1), unit: OVERLORD, color: color === idle && pulses.has(f) ? RED : color }); } // The main screen's keyboard, from the frame after. if (f >= SETUP + 1) for (const key of STAGE_LIST) { @@ -185,39 +206,43 @@ export function pictureAt(f: number): Pixel[] { return PICTURES[f]; } -/* ── The explosions: the strongest downbeats ── */ +/* ── The explosions ── */ +/** The impacts the timeline marks (HITS of the role "impact"), as frames of the picture with their strength. */ +const IMPACTS = HITS.filter((h) => roleOf(h[HIT_PART]) === "impact").map((h) => ({ frame: ZERO + h[HIT_FRAME], strength: h[HIT_STRENGTH] })); /** - * The downbeats that get an explosion: in the loud sections (the whole piece when none is), each bar's first beat - * weighed by the velocities of every note struck on it, drums too; the three heaviest at least four bars apart. (Für - * Elise: C16, the ff chord the storm ends on, then C9 and C1 — the three bars the score marks with an accent.) + * The moments that get an explosion. With impacts in the timeline (the cinematic arrangement): those of strength 0.9 + * or more, the strongest first, at least 100 frames (4 s) apart — the band's first downbeat, the storm's three big + * bars, the final's return of the theme and its two last big bars, not every drum stroke. Without (the straight + * piece): the loud section's downbeats weighed by the velocities struck on them, the three heaviest four bars apart — + * C16, C9 and C1, the bars the score accents. */ -export const BOOM_BARS: readonly number[] = (() => { +export const BOOMS: readonly { frame: number; strength: number }[] = (() => { + const chosen: { frame: number; strength: number }[] = []; + if (IMPACTS.length) { + for (const h of [...IMPACTS].sort((x, y) => y.strength - x.strength || x.frame - y.frame)) { + if (h.strength >= 0.9 && chosen.every((c) => Math.abs(c.frame - h.frame) >= 100)) chosen.push(h); + } + return chosen.sort((x, y) => x.frame - y.frame); + } const weight = new Map(); for (const n of NOTES) if (n[BEAT] === 0 && (!LOUD.length || loudBar(n[BAR]))) weight.set(n[BAR], (weight.get(n[BAR]) ?? 0) + n[VELOCITY]); - const chosen: number[] = []; - for (const [bar] of [...weight].sort((x, y) => y[1] - x[1] || x[0] - y[0])) { - if (chosen.length < 3 && chosen.every((b) => Math.abs(b - bar) >= 4)) chosen.push(bar); - } - return chosen; + const bars: [number, number][] = []; + for (const [bar, w] of [...weight].sort((x, y) => y[1] - x[1] || x[0] - y[0])) if (bars.length < 3 && bars.every(([b]) => Math.abs(b - bar) >= 4)) bars.push([bar, w]); + const most = Math.max(...bars.map(([, w]) => w)); + for (const [bar, w] of bars) chosen.push({ frame: Math.min(...notes.filter((n) => n.bar === bar && n.beat === 0).map((n) => n.on)), strength: w === most ? 1 : 0.9 }); + return chosen.sort((x, y) => x.frame - y.frame); })(); /** - * Each explosion: a frame, a kind (1 a Wraith's, 2 a Battlecruiser's), where. The heaviest downbeat gets three - * Battlecruisers across the stage; the others a Wraith over each note the lead strikes on it (one in the middle if it - * strikes none). Their own explosion sounds are heard (the user's choice). + * Each explosion: a frame, a kind (1 a Wraith's, 2 a Battlecruiser's), where. The strongest moments (strength 1, the + * most a timeline gives) get three Battlecruisers across the stage; the others a Wraith over each note the lead strikes + * then (one in the middle if it strikes none). Their own explosion sounds are heard (the user's choice). */ -export const explosions: readonly { frame: number; kind: number; x: number; y: number }[] = (() => { - const list: { frame: number; kind: number; x: number; y: number }[] = []; - BOOM_BARS.forEach((bar, k) => { - const struck = notes.filter((n) => n.bar === bar && n.beat === 0); - const lead = struck.filter((n) => n.part === LEAD_PART); - const frame = Math.min(...struck.map((n) => n.on)); - if (k === 0) for (const dx of [-240, 0, 240]) list.push({ frame, kind: 2, x: CAM_X + 40 + dx, y: VIEW_Y + 110 }); - else if (lead.length) for (const n of lead) list.push({ frame, kind: 1, x: stageX(n.note), y: VIEW_Y + 120 }); - else list.push({ frame, kind: 1, x: CAM_X + 40, y: VIEW_Y + 120 }); - }); - return list.sort((a, b) => a.frame - b.frame); -})(); +export const explosions: readonly { frame: number; kind: number; x: number; y: number }[] = BOOMS.flatMap((b) => { + if (b.strength >= 0.995) return [-240, 0, 240].map((dx) => ({ frame: b.frame, kind: 2, x: CAM_X + 40 + dx, y: VIEW_Y + 110 })); + const lead = piano.filter((n) => n.part === LEAD_PART && Math.abs(n.on - b.frame) <= 2); + return lead.length ? lead.map((n) => ({ frame: b.frame, kind: 1, x: stageX(n.note), y: VIEW_Y + 120 })) : [{ frame: b.frame, kind: 1, x: CAM_X + 40, y: VIEW_Y + 120 }]; +}).sort((x, y) => x.frame - y.frame); /* ── The tables the program plays back ── */ diff --git a/tests/fur-elise-showcase-run.test.ts b/tests/fur-elise-showcase-run.test.ts index 8450f02..9c8f19b 100644 --- a/tests/fur-elise-showcase-run.test.ts +++ b/tests/fur-elise-showcase-run.test.ts @@ -1,70 +1,97 @@ /** - * The Für Elise showcase's run (probes/lib/fur-elise-showcase-run.ts), from the soundtrack's timeline: the keyboards - * hold every note (folded by octaves where they must), the hands and the loud section are found from the data, the - * explosions land on the strongest downbeats, the picture never asks the game for two Flags it would not make, and the - * changes the program plays back rebuild every frame's picture. + * The Für Elise showcase's run (probes/lib/fur-elise-showcase-run.ts), on each soundtrack the switch picks + * (probes/lib/fur-elise-showcase-choice.ts: the cinematic arrangement, the straight piece): the keyboards hold every + * note (folded by octaves where they must), the parts and sections are found by their roles and names, the explosions + * land on the strongest moments, the picture never asks the game for two Flags it would not make, and the changes the + * program plays back rebuild every frame's picture. */ -import { describe, expect, it } from "vitest"; +import { beforeAll, describe, expect, it, vi } from "vitest"; import { isBlack, whiteKeys, type Pixel } from "../probes/lib/note-timeline"; -import { NOTES, PARTS, SECTIONS, BAR, BEAT, VELOCITY } from "../probes/lib/fur-elise-timeline"; import { CELL, VIEW_X, VIEW_Y } from "../probes/lib/fur-elise-layout"; -import { - BOOM_BARS, CHANGES, FLAG, FX_F, LABEL_F, LAST_OFF, LEAD, LEAD_PART, LOUD, OTHER_PART, OVERLORD, ROLL_COL, ROLL_HI, ROLL_KEYS, ROLL_LO, - STAGE_HI, STAGE_KEYS, STAGE_LO, STAGE_PITCH, STAGE_X0, STARTS, START, TOTAL, ZERO, explosions, flashes, notes, piano, pictureAt, -} from "../probes/lib/fur-elise-showcase-run"; -describe("the showcase's run", () => { - it("starts the clip LEAD frames before the picture's frame 0, and runs past the last note", () => { - expect(ZERO - START).toBe(LEAD); - expect(LEAD).toBe(2); - expect(TOTAL).toBeGreaterThan(LAST_OFF); - for (const list of [LABEL_F, FX_F, STARTS]) expect(list.every((f, k) => k === 0 || list[k - 1] <= f)).toBe(true); - expect(STARTS.length).toBe(TOTAL + 1); - // Every note on the timeline's own frame, from ZERO. - expect(notes.every((n) => NOTES.some((m) => m[8] + ZERO === n.on))).toBe(true); +type Run = typeof import("../probes/lib/fur-elise-showcase-run"); +type Choice = typeof import("../probes/lib/fur-elise-showcase-choice"); + +describe.each(["cinematic", "straight"] as const)("the showcase's run on the %s soundtrack", (which) => { + let r: Run, c: Choice; + beforeAll(async () => { + process.env.FUR_ELISE = which; + vi.resetModules(); + c = await import("../probes/lib/fur-elise-showcase-choice"); + r = await import("../probes/lib/fur-elise-showcase-run"); + delete process.env.FUR_ELISE; + }); + + it("is the soundtrack the switch names, the clip LEAD frames before the picture, the run past the last note", () => { + expect(c.SOUNDTRACK).toBe(which); + expect(r.ZERO - r.START).toBe(2); + expect(r.TOTAL).toBeGreaterThan(r.LAST_OFF); + for (const list of [r.LABEL_F, r.FX_F, r.STARTS]) expect(list.every((f, k) => k === 0 || list[k - 1] <= f)).toBe(true); + expect(r.STARTS.length).toBe(r.TOTAL + 1); + const frames = new Set(c.TIMELINE.NOTES.map((m) => m[8] + r.ZERO)); + expect(r.notes.every((n) => frames.has(n.on))).toBe(true); }); - it("finds the hands and the loud section in the data", () => { - expect([PARTS[LEAD_PART], PARTS[OTHER_PART]]).toEqual(["right", "left"]); - expect(LOUD).toEqual(["storm"]); - expect(piano.every((n) => n.part === LEAD_PART || n.part === OTHER_PART)).toBe(true); + it("puts the piano on the keyboards by role, and no drum, impact or riser on a roll", () => { + const { ROLES } = c.TIMELINE; + expect([ROLES[r.LEAD_PART], ROLES[r.OTHER_PART]]).toEqual(["lead", "accomp"]); + expect(r.piano.every((n) => n.part === r.LEAD_PART || n.part === r.OTHER_PART)).toBe(true); + expect(r.notes.every((n) => !["drum-low", "drum-high", "cymbal", "impact", "riser"].includes(ROLES[n.part]))).toBe(true); + expect(r.LOUD).toEqual(["storm"]); }); - it("fits both keyboards: the main screen every key the hands play, 40 white keys 16 apart inside the view", () => { - expect([STAGE_LO, STAGE_HI]).toEqual([33, 100]); - expect(whiteKeys(STAGE_LO, STAGE_HI).length).toBe(40); - expect(STAGE_PITCH).toBe(16); - expect(STAGE_X0 + 39 * STAGE_PITCH).toBe(830); - for (const n of piano) expect(STAGE_KEYS.fold(n.note)).toBe(n.note); - // The minimap: 64 columns, every note on one of them. - expect(ROLL_HI - ROLL_LO + 1).toBeLessThanOrEqual(64); - expect(ROLL_COL).toBeGreaterThanOrEqual(0); - for (const n of notes) { const k = ROLL_KEYS.fold(n.note); expect(k >= ROLL_LO && k <= ROLL_HI && k % 12 === n.note % 12).toBe(true); } - expect(isBlack(ROLL_LO) || isBlack(ROLL_HI)).toBe(false); + it("shows the rest of the band only in the big sections: the intro and the ending are the piano alone", () => { + const { SECTIONS } = c.TIMELINE; + expect(r.BIG).toEqual(which === "cinematic" ? ["storm", "final"] : ["storm"]); + const band = r.notes.filter((n) => n.part !== r.LEAD_PART && n.part !== r.OTHER_PART); + expect(band.length).toBeGreaterThan(0); + for (const n of band) { + const s = [...SECTIONS].reverse().find((x) => x.bar <= n.bar)!; + expect(r.BIG).toContain(s.name); + } }); - it("explodes on the three strongest downbeats of the loud section, the strongest with Battlecruisers", () => { - const storm = SECTIONS.find((s) => s.name === "storm")!; - const weight = (bar: number) => NOTES.filter((n) => n[BAR] === bar && n[BEAT] === 0).reduce((s, n) => s + n[VELOCITY], 0); - expect(BOOM_BARS.length).toBe(3); - expect(BOOM_BARS.every((b) => b > storm.bar)).toBe(true); - expect(weight(BOOM_BARS[0])).toBeGreaterThanOrEqual(Math.max(weight(BOOM_BARS[1]), weight(BOOM_BARS[2]))); - // For Für Elise these are the bars the score marks with an accent: C1, C9 and C16. - expect([...BOOM_BARS].sort((a, b) => a - b)).toEqual([storm.bar + 1, storm.bar + 9, storm.bar + 16]); - expect(explosions.filter((e) => e.kind === 2).length).toBe(3); + it("fits both keyboards: the main screen every key the piano plays, 40 white keys 16 apart inside the view", () => { + expect([r.STAGE_LO, r.STAGE_HI]).toEqual([33, 100]); + expect(whiteKeys(r.STAGE_LO, r.STAGE_HI).length).toBe(40); + expect(r.STAGE_PITCH).toBe(16); + expect(r.STAGE_X0 + 39 * r.STAGE_PITCH).toBe(830); + for (const n of r.piano) expect(r.STAGE_KEYS.fold(n.note)).toBe(n.note); + expect(r.ROLL_HI - r.ROLL_LO + 1).toBeLessThanOrEqual(64); + for (const n of r.notes) { const k = r.ROLL_KEYS.fold(n.note); expect(k >= r.ROLL_LO && k <= r.ROLL_HI && k % 12 === n.note % 12).toBe(true); } + expect(isBlack(r.ROLL_LO) || isBlack(r.ROLL_HI)).toBe(false); + }); + + it("explodes on a handful of the strongest moments, Battlecruisers on the strongest", () => { + const { SECTIONS } = c.TIMELINE; + const section = (f: number) => [...SECTIONS].reverse().find((s) => s.frame <= f - r.ZERO)!.name; + if (which === "cinematic") { + // The band's first downbeat, three in the storm, the final's first downbeat and two of its last big bars. + expect(r.BOOMS.map((b) => section(b.frame))).toEqual(["band", "storm", "storm", "storm", "final", "final", "final"]); + expect(r.BOOMS[0].frame).toBe(r.ZERO + SECTIONS.find((s) => s.name === "band")!.frame); + expect(r.BOOMS[4].frame).toBe(r.ZERO + SECTIONS.find((s) => s.name === "final")!.frame); + } else { + // No impacts in the straight piece: the storm's three accented bars, C1, C9 and C16. + expect(r.BOOMS.map((b) => section(b.frame))).toEqual(["storm", "storm", "storm"]); + } + expect(r.BOOMS.every((b, k) => k === 0 || b.frame - r.BOOMS[k - 1].frame >= 100)).toBe(true); + for (const b of r.BOOMS) expect(r.explosions.filter((e) => e.frame === b.frame).every((e) => e.kind === (b.strength >= 0.995 ? 2 : 1))).toBe(true); }); - it("flashes the white keys red only in the loud section, on the lead's chords", () => { - const storm = SECTIONS.find((s) => s.name === "storm")!, closing = SECTIONS.find((s) => s.name === "closing")!; - expect(flashes.size).toBeGreaterThan(20); - for (const f of flashes) expect(f >= ZERO + storm.frame && f < ZERO + closing.frame + 2).toBe(true); + it("flashes the white keys red only in the storm, and pulses the minimap's keys only in the big sections", () => { + const { SECTIONS } = c.TIMELINE; + const at = (name: string) => r.ZERO + SECTIONS.find((s) => s.name === name)!.frame; + const after = (name: string) => { const k = SECTIONS.findIndex((s) => s.name === name); return r.ZERO + (SECTIONS[k + 1]?.frame ?? Infinity); }; + expect(r.flashes.size).toBeGreaterThan(20); + for (const f of r.flashes) expect(f >= at("storm") && f < after("storm") + 2).toBe(true); + for (const f of r.pulses) expect(r.BIG.some((name) => f >= at(name) && f < after(name) + 3)).toBe(true); }); it("never asks for a Flag overlapping another of its frame or of the frame before", () => { const close = (a: Pixel, b: Pixel) => Math.abs(a.x - b.x) < 16 && Math.abs(a.y - b.y) < 16 && (a.x !== b.x || a.y !== b.y); let before: Pixel[] = []; - for (let f = 0; f < TOTAL; f++) { - const flags = pictureAt(f).filter((p) => p.unit === FLAG); + for (let f = 0; f < r.TOTAL; f++) { + const flags = r.pictureAt(f).filter((p) => p.unit === r.FLAG); for (const p of flags) { const bad = flags.find((q) => close(p, q)) ?? before.find((q) => close(p, q)); if (bad) throw new Error(`frame ${f}: ${p.x},${p.y} beside ${bad.x},${bad.y}`); @@ -73,30 +100,30 @@ describe("the showcase's run", () => { } }); - it("plays back changes that rebuild every frame's picture, the units on the map well under the game's 1,700", () => { + it("plays back changes that rebuild every frame's picture, the units well under the game's 1,700", () => { const shown = new Map(); let most = 0; - CHANGES.forEach((cs, f) => { - for (const c of cs) { - const k = `${c.unit} ${c.x} ${c.y}`; - expect(shown.get(k) ?? 0).toBe(c.from); - if (c.to) shown.set(k, c.to); + r.CHANGES.forEach((cs, f) => { + for (const ch of cs) { + const k = `${ch.unit} ${ch.x} ${ch.y}`; + expect(shown.get(k) ?? 0).toBe(ch.from); + if (ch.to) shown.set(k, ch.to); else shown.delete(k); } if (f % 50 === 0) { - const want = pictureAt(f); + const want = r.pictureAt(f); expect(shown.size).toBe(want.length); for (const p of want) expect(shown.get(`${p.unit} ${p.x} ${p.y}`)).toBe(p.color); } most = Math.max(most, shown.size); }); - expect(most).toBeLessThan(700); + expect(most).toBeLessThan(1000); }); it("keeps the Overlords on the minimap's cells and the Flags in the view, right of the text", () => { - for (let f = 0; f < TOTAL; f += 11) { - for (const p of pictureAt(f)) { - if (p.unit === OVERLORD) expect((p.x - CELL / 2) % CELL === 0 && (p.y - CELL / 2) % CELL === 0 && p.y < 92 * 32).toBe(true); + for (let f = 0; f < r.TOTAL; f += 11) { + for (const p of r.pictureAt(f)) { + if (p.unit === r.OVERLORD) expect((p.x - CELL / 2) % CELL === 0 && (p.y - CELL / 2) % CELL === 0 && p.y < 92 * 32).toBe(true); else expect(p.x >= VIEW_X + 200 && p.x <= VIEW_X + 836 && p.y >= VIEW_Y + 16 && p.y <= VIEW_Y + 300).toBe(true); } } From 105ac0f4ecc478c6da7f22a5cd4f7b534165acfc Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 06:41:18 -0600 Subject: [PATCH 25/31] Plan: the S7 showcase on the cinematic arrangement The switch, the roles, what is bigger where the music is and what was left calm, the explosions' moments and why, the maps, the tuning and lifted-game checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index beaef5b..eade275 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6806,6 +6806,54 @@ in e67671d). Chosen: a cinematic hybrid — piano, orchestra, big percussion, sy storm's hits are limited hard. Previews: Maps/TrigScript/fur-elise-sound-preview/cinematic/. +#### S7 the showcase on the cinematic arrangement (built 2026-11-09) + +`fur-elise` merged again (the cinematic arrangement, the make-samples root-key fix). The showcase now plays the +cinematic arrangement by default; the straight piece stays buildable. + +**One switch.** `probes/lib/fur-elise-showcase-choice.ts`: `SOUNDTRACK` ("cinematic" by default) picks the timeline, +and `probes/fur-elise-showcase.ts` picks the clip by it (`lib/fur-elise-cinematic.ts`'s `whole` or +`lib/fur-elise-soundtrack.ts`'s); only the clip played goes in the map. Built under Node, `FUR_ELISE=straight` picks +the other without an edit (the module reads `globalThis.process.env`; the editor has none, so the constant decides). +Both soundtrack modules are evaluated at every compile, which takes a check from ~6 s to ~37 s. + +**By role, not by name.** The keyboards show the parts whose ROLES are "lead" (gold) and "accomp" (cyan); "drum-low", +"drum-high", "cymbal", "impact" and "riser" (a kit's key, not a note) are on no roll. Both keyboards are fitted to the +piano's notes (A1 … E7 on the main screen, 40 white keys 16 px apart; A1 … C7 on the minimap), the rest folded into +them by octaves. + +**Bigger where the music is, the user's choices kept:** +- *The storm* (the section named "storm"; else the loud sections by velocity): the lead's chords red, the white keys + flashing red for two frames on each (64 frames in all). +- *The big sections*, the storm and the final statement: the rest of the band (strings, brass, bass, synths, pads) + falls on the minimap in violet under the piano. The intro, the band's first sections, the breakdown and the ending + show the piano alone; the main screen shows only the piano throughout. +- *The low drums*: in the big sections, each taiko or timpani hit of strength 0.95 or more (HITS) turns the minimap + keyboard's front row red for three frames (17 pulses). Nothing on the main screen: that stays the piano's. +- *Explosions*, from HITS: the impacts of strength 0.9 or more, the strongest first, at least 100 frames (4 s) + apart — 7 moments, game time: 0:16.3 the band's first downbeat (Wraiths over the melody); 1:13.8 the storm's first + impact (three Battlecruisers); 1:23.8 the storm's middle (0.99: Wraiths); 1:32.6 the storm's last (Battlecruisers); + 1:42.4 the final's first downbeat, the theme returning (Battlecruisers); 2:03.2 and 2:15.7 the final's big bars + (Wraiths). Strength 1 gets Battlecruisers, the rest Wraiths. The taiko's own strokes (about 60 over 0.9) are left out: + an explosion on each would be every bar. The straight piece has no impacts, so it keeps the downbeat-weight rule + (C1, C9, C16). + +**The maps.** Cinematic: 3.46 MB, 2:36.5 of sound (one Ogg, 3.2 MB), the tables to 2:40.7, the end line at 2:27.7; +payload 2.6 MB, 141,011 changes. Straight: 4.39 MB, as before. + +**Checked.** `tests/fur-elise-showcase-run.test.ts` runs every check on both soundtracks (the switch through +`FUR_ELISE` and `vi.resetModules`). Tuning, on the maps' own Ogg (`scmjs map unpack`, then `scripts/tuning-check.mts`): +cinematic, 58 pitches, one off — the trombones' C#3 under the storm's braam, as the soundtrack's own check found; +straight, 55 pitches, none off (B3/C4 fixed). In the lifted game, "every frame of the piece shows the picture worked +out" holds on both (cinematic 3,825 frames, straight 5,180) and no explosion's unit outlives its frame. Cost +(cinematic): 9,781 conditions and actions a frame on average, 70,055 at the most (frame 1900, the storm with the +band and a flash) — 0.10 ms on average, 0.71 ms at the most of ~15 ms; straight as before, 0.55 ms. `game-check` +(cinematic): 572,099 accesses, 0 ending the game, 0 ignored, 0 never seen. + +**Maps** (Maps/TrigScript): `trigscript-fur-elise.scx` the cinematic showcase, `trigscript-fur-elise-straight.scx` the +straight one, `trigscript-fur-elise-check.txt` (the explosions' times), `fur-elise-showcase-frames.png` (22 stills: two +a section and each explosion). Not played yet. + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice From 48a00feabb72d155e742c8aec3f46339384b3b60 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 07:04:03 -0600 Subject: [PATCH 26/31] Melody first: Clip.duck, render's parts, the trance presets and music.sweep MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Clip.duck(key, { depth, threshold, attack, release })` turns a clip down by up to `depth` dB while another sounds, in proportion to the key's level (followed, its louder side): the pads and chords under a melody ducked by the melody itself, not only by the kick. `render(performance, { parts })` mixes only the parts named — stems: the lead apart from what plays under it, to key the ducking and to measure it. Presets trance (seven saws, a short glide into each note), arp (a pluck whose filter snaps shut) and stab (supersaw chord hits); `music.sweep(seconds, { down })`, white noise through a sweeping lowpass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- compiler/declarations.ts | 6 ++++++ compiler/dsp.ts | 20 ++++++++++++++++++++ compiler/generated/stdlib.ts | 2 +- compiler/sound.ts | 11 ++++++++++- ledger/sounds/music-sweep.ts | 14 ++++++++++++++ stdlib/music.ts | 33 +++++++++++++++++++++++++++++---- tests/sampled.test.ts | 29 ++++++++++++++++++++++++++++- 7 files changed, 108 insertions(+), 7 deletions(-) create mode 100644 ledger/sounds/music-sweep.ts diff --git a/compiler/declarations.ts b/compiler/declarations.ts index 9f8248b..3cfaa81 100644 --- a/compiler/declarations.ts +++ b/compiler/declarations.ts @@ -647,6 +647,12 @@ ${kw}interface Clip { compress(options?: { readonly threshold?: number; readonly ratio?: number; readonly attack?: number; readonly release?: number; readonly knee?: number; readonly makeup?: number }): Clip; /** Louder or quieter as a whole, so its loudness (\`lufs\`) is \`lufs\`: \`mix.loudness(-15).limit()\`. */ loudness(lufs: number): Clip; + /** + * Turned down while \`key\` sounds — up to \`depth\` dB (6) when the key is at \`threshold\` dB (−30) or over, less in + * proportion when it is quieter, following it over \`attack\` (0.01) and \`release\` (0.15) seconds: room made for a + * melody in what plays under it. \`pads.duck(lead, { depth: 5 })\` + */ + duck(key: Clip, options?: { readonly depth?: number; readonly threshold?: number; readonly attack?: number; readonly release?: number }): Clip; /** * What a piano's strings add while its sustain pedal is down: each string, A0 to E6, answers the partials of the * notes that fall on its own and rings on, until the pedal comes up and the dampers stop it. \`pedal\`: [down, up] diff --git a/compiler/dsp.ts b/compiler/dsp.ts index 6931951..ab79203 100644 --- a/compiler/dsp.ts +++ b/compiler/dsp.ts @@ -418,3 +418,23 @@ export function sympathetic(chans: Channels, rate: number, pedal: Points, amount } return [L, R]; } + +/** + * A ducker keyed from another sound: the channels turned down by up to `depth` dB while `key` sounds — the key's level + * (its two sides' louder, followed over `attack` and `release` seconds) against `threshold`: at or over it, all the + * depth; under it, as much less as the key is quieter, in proportion. What makes room for a melody in what plays under it. + */ +export function duck(chans: Channels, key: Channels, rate: number, depth: number, threshold: number, attack: number, release: number): Float32Array[] { + const n = chans[0].length, kn = key[0].length, floor = 10 ** (-depth / 20), thr = 10 ** (threshold / 20); + const up = 1 - Math.exp(-1 / Math.max(1, attack * rate)), down = 1 - Math.exp(-1 / Math.max(1, release * rate)); + const gain = new Float32Array(n); + let env = 0; + for (let i = 0; i < n; i++) { + let x = 0; + if (i < kn) for (const k of key) { const a = k[i] < 0 ? -k[i] : k[i]; if (a > x) x = a; } + env += (x - env) * (x > env ? up : down); + const amount = Math.min(1, env / thr); + gain[i] = 1 - (1 - floor) * amount; + } + return chans.map((c) => { const out = new Float32Array(n); for (let i = 0; i < n; i++) out[i] = c[i] * gain[i]; return out; }); +} diff --git a/compiler/generated/stdlib.ts b/compiler/generated/stdlib.ts index f78e5ab..d8d238c 100644 --- a/compiler/generated/stdlib.ts +++ b/compiler/generated/stdlib.ts @@ -3,7 +3,7 @@ export const STDLIB_SOURCES: Readonly> = { "cutscene": "/**\n * Scenes acted out in the game: the standard library's \"trigscript/cutscene\" (TrigScript 4).\n *\n * import { Camera, walk, line, play, SECOND } from \"trigscript/cutscene\";\n *\n * async function intro(raider: Unit) {\n * const cam = new Camera(raider.x, raider.y);\n * await line(units.JimRaynorMarine, \"Something's moving out there.\", 3 * SECOND);\n * const there = start(walk(raider, 1200, 640)); // the walk goes on while the camera follows\n * await cam.follow(raider, 2 * SECOND);\n * await there;\n * await cam.pan(1600, 400, 2 * SECOND);\n * await cam.shake(12);\n * }\n *\n * program(async () => {\n * const raider = first(unitsAt(locations.Base, { owner: P1, type: units.TerranMarine }));\n * if (!raider) return;\n * const skipped = await play(P1, start(intro(raider))); // Escape skips the rest of it\n * if (skipped) print(\"Skipped.\");\n * });\n *\n * Everything here is what a trigger can do, done a frame at a time: the camera is Center View on a location the library\n * keeps for itself, moved to where the camera should look; a unit walks by a Move order to another; a line is the\n * speaker's portrait talking and the words in the middle of the screen. Places are pixels (32 a tile), (0, 0) the map's\n * top left; time is frames of the game, 24 a second on Fastest (`SECOND`). The camera is the one of the player the\n * program runs as, as Center View's is.\n */\nimport { centerLocation, centerView, reserveLocation, talkingPortrait, print, sleep, frames, nextFrame, keyPressed, type Player, type Task, type Unit, type UnitType } from \"trigscript\";\nimport { easeInOutQuad, easeInQuad, easeOutQuad, easeOutBack } from \"trigscript/math\";\n\n/** Frames a second of game time on Fastest, the speed a map is played at. */\nexport const SECOND = 24;\n\nconst VIEW = reserveLocation(\"cutscene: where the camera looks\");\nconst GOAL = reserveLocation(\"cutscene: where a unit is sent\");\n\n/** How a glide speeds up and slows down: evenly, starting slow, ending slow, both, or ending past the mark and back. */\nexport type Ease = \"linear\" | \"in\" | \"out\" | \"inOut\" | \"back\";\n\n/** How far along a glide is at `t` (0 at its start, 1 at its end), as `ease` has it. */\nfunction eased(t: fixed, ease: Ease): fixed {\n if (ease === \"in\") return easeInQuad(t);\n if (ease === \"out\") return easeOutQuad(t);\n if (ease === \"inOut\") return easeInOutQuad(t);\n if (ease === \"back\") return easeOutBack(t);\n return t;\n}\n\n/**\n * The camera of the player the program runs as: where it looks, and how it gets somewhere else. It looks at its first\n * place as soon as it is made.\n */\nexport class Camera {\n /** The point the camera is centred on, in pixels. */\n x: number;\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /** Look at a point, now. */\n look(x: number, y: number) {\n this.x = x;\n this.y = y;\n centerLocation(VIEW, x, y);\n centerView(VIEW);\n }\n\n /**\n * Glide to a point over `time` frames, looking at each place on the way a frame at a time.\n * @param ease How it speeds up and slows down; \"inOut\" unless it says.\n */\n async pan(x: number, y: number, time: number, ease: Ease = \"inOut\") {\n const fromX = this.x;\n const fromY = this.y;\n let i = 1;\n while (i <= time) {\n const k = eased(fixed(i) / time, ease);\n this.look(fromX + Math.round((x - fromX) * k), fromY + Math.round((y - fromY) * k));\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n\n /** Keep a unit in the middle of the screen for `time` frames, or until it is gone. */\n async follow(u: Unit, time: number) {\n let i = 0;\n while (i < time && u) {\n this.look(u.x, u.y);\n await nextFrame();\n i++;\n }\n }\n\n /** Shake for `time` frames, `size` pixels each way (8 unless it says), and settle where it was. */\n async shake(time: number, size: number = 8) {\n const x = this.x;\n const y = this.y;\n let i = 0;\n while (i < time) {\n const left = (i % 4) < 2;\n const up = (i % 2) === 0;\n centerLocation(VIEW, left ? x - size : x + size, up ? y - size : y + size);\n centerView(VIEW);\n await nextFrame();\n i++;\n }\n this.look(x, y);\n }\n}\n\n/**\n * Send a unit to a point by a Move order, and wait until it is there — within `near` pixels (48 unless it says) — or\n * `limit` frames have passed (30 seconds unless it says), or it is gone.\n * @returns Whether it got there.\n */\nexport async function walk(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"move\", near, limit);\n}\n\n/** The same with an Attack order: the unit fights what it meets on the way. */\nexport async function charge(u: Unit, x: number, y: number, near: number = 48, limit: number = 30 * SECOND): Promise {\n return go(u, x, y, \"attack\", near, limit);\n}\n\nasync function go(u: Unit, x: number, y: number, how: \"move\" | \"attack\", near: number, limit: number): Promise {\n centerLocation(GOAL, x, y);\n u.order(how, GOAL);\n let waited = 0;\n while (u && Math.abs(u.x - x) + Math.abs(u.y - y) > near && waited < limit) {\n await nextFrame();\n waited++;\n }\n return !!u && Math.abs(u.x - x) + Math.abs(u.y - y) <= near;\n}\n\n/**\n * Send every unit of a group to a point together, and wait until each is there, gone, or `limit` frames have passed.\n * @returns How many got there.\n */\nexport async function walkAll(group: Unit[], x: number, y: number, near: number = 64, limit: number = 30 * SECOND): Promise {\n centerLocation(GOAL, x, y);\n for (const u of group) if (u) u.order(\"move\", GOAL);\n let waited = 0;\n let there = 0;\n while (waited < limit) {\n there = 0;\n let moving = 0;\n for (const u of group) {\n if (!u) continue;\n if (Math.abs(u.x - x) + Math.abs(u.y - y) <= near) there++;\n else moving++;\n }\n if (moving === 0) break;\n await nextFrame();\n waited++;\n }\n return there;\n}\n\n/**\n * A line of the scene: the speaker's portrait talks and the words show in the middle of the screen, for `time` frames\n * (3 seconds unless it says), and then the scene goes on.\n */\nexport async function line(speaker: UnitType, text: string, time: number = 3 * SECOND) {\n talkingPortrait(speaker, Math.round((time * 1000) / SECOND));\n print(text, { position: \"center\" });\n await sleep(frames(time));\n}\n\n/**\n * Play a scene, started as a task (`start(intro())`), for a player who may skip it: when they press `key` (Escape unless\n * it says) the scene stops where it is. Put things where the scene would have left them when it gives true.\n * @returns Whether it was skipped.\n */\nexport async function play(player: Player, scene: Task, key: \"Escape\" | \"Space\" | \"Enter\" = \"Escape\"): Promise {\n while (scene.running) {\n if (keyPressed(player, key)) {\n scene.cancel();\n return true;\n }\n await nextFrame();\n }\n return false;\n}\n", "fog": "/**\n * Fog of war as a picture: the standard library's \"trigscript/fog\" (TrigScript 4).\n *\n * import { fog } from \"trigscript/fog\";\n *\n * const heart = fog.picture([\".##.##.\", \"#######\", \".#####.\", \"..###..\"]);\n *\n * program(async () => {\n * fog.reveal(P1); // the whole map lit once: from now on dark is fog, not black\n * while (true) {\n * fog.light(P1, 30, 20, 5); // a disc of size 5 around tile (30, 20), this frame only\n * fog.light(P1, 60, 40, heart); // a picture, its top left on tile (60, 40)\n * await nextFrame();\n * }\n * });\n *\n * The fog is a canvas that starts every frame dark: what a program lights this frame is what shows this frame, and\n * nothing else needs doing. There is no dark brush — the game's sight only ever reveals — so dark is whatever is not\n * lit; to draw dark shapes, light around them (a picture with `{ ink: \"dark\" }`). Dark is also the sharper ink: a lit\n * part is at least a brush wide (3 tiles across, 4 down), while a dark line one tile wide stays exactly that. Nothing\n * else needs doing — the library writes the game's vision countdown after every frame (memory.vision.countdown), so\n * the next frame starts from a wiped board. Watch it on the minimap. With Classic graphics (Options > Graphics) a tile\n * of the map is a pixel there, sharp; Remastered graphics blurs it a few tiles wide.\n *\n * What the board is made of decides how far apart lit and fog look. Remastered draws a tile on the minimap as the\n * average of its art and fog as 0.64 of lit, whatever the tile, so the brightest art is the best board there: plain\n * Ice snow (lit 130 against fog 82, measured 2026-10-19). Classic draws a tile as one colour of its own; Badlands\n * tile 23778 is the widest apart there, and dim and textured in Remastered. Snow played the better of the two.\n *\n * How it draws, played in StarCraft: Remastered (2026-10-17): a brush is a unit made on a tile and taken away in the\n * same trigger pass; the tiles its sight revealed stay lit through the frame. A brush's size is the unit's sight\n * range, so each size is a unit type of its own — the flying heroes below, which no ordinary map places — whose sight\n * is set every frame (Remastered takes a sight write a frame late, so one type cannot change size within a frame).\n * Coordinates are tiles, (0, 0) the map's top left. About 800 brushes a frame is the most the game makes: it keeps a\n * removed unit's place until the next frame.\n */\nimport { game, program, sleep, frames, stats, units, createUnit, removeUnit, centerLocation, reserveLocation, memory, cover, nextFrame, type Player, type UnitType, type Video } from \"trigscript\";\n\n/**\n * Each brush's shape, sizes 1 to 11: the tiles a flying unit of that sight range reveals, read out of the game.\n * \"@\" is the tile the brush is centred on. The game's air sight leaves the centre's row one short below, so every\n * shape reaches a row further up than down.\n */\nexport const SHAPES: readonly (readonly string[])[] = [\n // 1\n [\"###\", \"###\", \"#@#\", \"###\"],\n // 2\n [\".###.\", \"#####\", \"#####\", \"##@##\", \"#####\", \"#####\"],\n // 3\n [\"..###..\", \"#######\", \"#######\", \"#######\", \"###@###\", \"#######\", \"#######\", \"#######\"],\n // 4\n [\"..#####...\", \".#######..\", \"#########.\", \"##########\", \"##########\", \"####@#####\", \"##########\", \"##########\", \"#########.\", \".#######..\", \"......#...\"],\n // 5\n [\"...#####....\", \"..#######...\", \".#########..\", \"###########.\", \"############\", \"############\", \"#####@######\", \"############\", \"############\", \"###########.\", \".#########..\", \"..#######...\", \".......#....\"],\n // 6\n [\"....#####.....\", \"..#########...\", \".###########..\", \"#############.\", \"#############.\", \"##############\", \"##############\", \"######@#######\", \"##############\", \"##############\", \"#############.\", \"#############.\", \".###########..\", \"..#########...\", \"........#.....\"],\n // 7\n [\".....#####......\", \"...#########....\", \"..###########...\", \".#############..\", \"###############.\", \"###############.\", \"################\", \"################\", \"#######@########\", \"################\", \"################\", \"###############.\", \"###############.\", \".#############..\", \"..###########...\", \"...#########....\", \".........#......\"],\n // 8\n [\"......#####.......\", \"....#########.....\", \"..#############...\", \".###############..\", \".###############..\", \"#################.\", \"#################.\", \"##################\", \"##################\", \"########@#########\", \"##################\", \"##################\", \"#################.\", \"#################.\", \".###############..\", \".###############..\", \"..#############...\", \"....#########.....\", \"..........#.......\"],\n // 9\n [\"......#######.......\", \"....###########.....\", \"...#############....\", \"..###############...\", \".#################..\", \"###################.\", \"###################.\", \"####################\", \"####################\", \"####################\", \"#########@##########\", \"####################\", \"####################\", \"####################\", \"###################.\", \"###################.\", \".#################..\", \"..###############...\", \"...#############....\", \"....###########.....\", \"........#####.......\"],\n // 10\n [\".......#######........\", \".....###########......\", \"....#############.....\", \"..#################...\", \"..#################...\", \".###################..\", \"#####################.\", \"#####################.\", \"######################\", \"######################\", \"######################\", \"##########@###########\", \"######################\", \"######################\", \"######################\", \"#####################.\", \"#####################.\", \".###################..\", \"..#################...\", \"..#################...\", \"....#############.....\", \".....###########......\", \".........#####........\"],\n // 11\n [\"........#######.........\", \"......###########.......\", \"....###############.....\", \"...#################....\", \"..###################...\", \".#####################..\", \".#####################..\", \"#######################.\", \"#######################.\", \"########################\", \"########################\", \"########################\", \"###########@############\", \"########################\", \"########################\", \"########################\", \"#######################.\", \"#######################.\", \".#####################..\", \".#####################..\", \"..###################...\", \"...#################....\", \"....###############.....\", \"......###########.......\", \"..........#####.........\"],\n];\n\n/** Each size's unit, size 1 first: flying heroes without a sight upgrade. A map that places one gets odd sight from it. */\nconst BRUSHES: readonly UnitType[] = [\n units.KukulzaMutalisk, units.KukulzaGuardian, units.YggdrasillOverlord, units.MagellanScienceVessel,\n units.GantrithorCarrier, units.HyperionBattlecruiser, units.NoradIIBattlecruiser, units.TomKazanskyWraith,\n units.DanimothArbiter, units.MojoScout, units.ArtanisScout,\n];\n\n/** Where each brush is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"fog: where each brush is made\");\n\n/**\n * One disc: the tiles a brush of `size` covers (SHAPES), centred on tile (x, y). What light() does with a size. A brush\n * is a unit made where SPOT is and taken away again at once; each branch makes its own size's, so that the unit type\n * of the action is known when the script is built (one given by the program costs writing it into the action).\n */\nconst disc = game((player: Player, x: number, y: number, size: number) => {\n discPx(player, x * 32 + 16, y * 32 + 16, size);\n});\n\n/**\n * disc() in pixels, (px, py) the centre of the tile: what a caller with many brushes uses, its products by 32 worked\n * out once and the brushes' offsets added (a product by 32 of a number the game holds is a test a bit, about 0.4 µs).\n */\nconst discPx = game((player: Player, px: number, py: number, size: number) => {\n centerLocation(SPOT, px, py, 32, 32);\n switch (size) {\n case 0: case 1: createUnit(player, BRUSHES[0], 1, SPOT); removeUnit(player, BRUSHES[0]); break;\n case 2: createUnit(player, BRUSHES[1], 1, SPOT); removeUnit(player, BRUSHES[1]); break;\n case 3: createUnit(player, BRUSHES[2], 1, SPOT); removeUnit(player, BRUSHES[2]); break;\n case 4: createUnit(player, BRUSHES[3], 1, SPOT); removeUnit(player, BRUSHES[3]); break;\n case 5: createUnit(player, BRUSHES[4], 1, SPOT); removeUnit(player, BRUSHES[4]); break;\n case 6: createUnit(player, BRUSHES[5], 1, SPOT); removeUnit(player, BRUSHES[5]); break;\n case 7: createUnit(player, BRUSHES[6], 1, SPOT); removeUnit(player, BRUSHES[6]); break;\n case 8: createUnit(player, BRUSHES[7], 1, SPOT); removeUnit(player, BRUSHES[7]); break;\n case 9: createUnit(player, BRUSHES[8], 1, SPOT); removeUnit(player, BRUSHES[8]); break;\n case 10: createUnit(player, BRUSHES[9], 1, SPOT); removeUnit(player, BRUSHES[9]); break;\n default: createUnit(player, BRUSHES[10], 1, SPOT); removeUnit(player, BRUSHES[10]);\n }\n});\n\n/**\n * Light the whole map once, so that from now on a tile left dark shows as fog (grey) rather than as never seen\n * (black) — every picture then has the same two tones. Takes one frame.\n * @param player Whose fog: P1 … P8, known when the script is built.\n */\nexport const reveal = game((player: Player) => {\n const width = memory.map.width;\n const height = memory.map.height;\n // Size 11 is 23 tiles wide: a brush every 14 tiles leaves no gap, and one more past the end, kept inside, reaches the edge.\n for (let y = 2; y < height + 12; y += 14) {\n for (let x = 2; x < width + 12; x += 14) disc(player, Math.min(x, width - 3), Math.min(y, height - 3), 11);\n }\n});\n\n/**\n * Light a rectangle of tiles for this frame, worked out while the game runs: its top left on tile (x, y), `width`\n * tiles across and `height` down. Every one of the five may change from frame to frame — the walls of a raycaster, a\n * bar of a chart. It is exact from 3 × 4 up (the smallest brush); a thinner one is lit a brush wide, centred.\n *\n * fog.rect(P1, 10, 20, 3, wall); // a column 3 tiles wide, `wall` tall\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of its left edge.\n * @param y The row of its top edge.\n * @param width How many tiles across.\n * @param height How many tiles down.\n */\nexport const rect = game((player: Player, x: number, y: number, width: number, height: number) => {\n if (width < 1 || height < 1) return;\n // Size 1 is 3 tiles across and 4 down, its centre the middle column and the third row: a grid of them, the last\n // column and row moved back to end on the edge (overlapping the one before), covers the rectangle exactly.\n const right = Math.max(x + width - 2, x + 1);\n const bottom = Math.max(y + height - 2, y + 2);\n // (The brush made here, not through disc(): its unit type is then known when the script is built, which makes the\n // action a constant — a size from the program costs a branch and a written field a brush.)\n let cy = y + 2;\n while (true) {\n let cx = x + 1;\n while (true) {\n centerLocation(SPOT, cx * 32 + 16, cy * 32 + 16, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (cx >= right) break;\n cx = Math.min(cx + 3, right);\n }\n if (cy >= bottom) break;\n cy = Math.min(cy + 4, bottom);\n }\n});\n\n/** A picture for the fog, made when the script is built: its size in tiles and the brushes that draw it. */\nexport interface Picture {\n readonly width: number;\n readonly height: number;\n readonly brushes: readonly { readonly x: number; readonly y: number; readonly size: number }[];\n}\n\n/**\n * A picture from rows of text, worked out when the script is built: `#` is the ink, anything else is not.\n *\n * fog.picture([\"..##..\", \".####.\", \"######\"]) // light ink: the # tiles are lit\n * fog.picture([\"..##..\", \".####.\", \"######\"], { ink: \"dark\" }) // dark ink: the # tiles stay dark, the rest is lit\n *\n * With light ink a lit part thinner than a brush (3 tiles across, 4 down) is drawn a tile or two thicker. An image's\n * halftone (`fog.picture(photo.halftone(6))`) is drawn with the brushes it was made of, one a cell. With dark\n * ink every tile of the picture's rectangle that is not `#` is lit and the `#` tiles keep their shape exactly,\n * however thin — the ink for line art and silhouettes.\n */\nexport function picture(rows: readonly string[], options: { readonly ink?: \"light\" | \"dark\" } = {}): Picture {\n const height = rows.length;\n const width = Math.max(0, ...rows.map((r) => r.length));\n // An image's halftone (image.halftone(6)) comes with the brushes that drew it: a brush a cell, as they are.\n const drawn = (rows as { readonly brushes?: readonly { readonly x: number; readonly y: number; readonly shape: number }[] }).brushes;\n if (drawn && options.ink !== \"dark\") return Object.freeze({ width, height, brushes: Object.freeze(drawn.map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }))) });\n // Dark ink: the picture's rectangle lit but for the # tiles, so what is covered is the rest.\n const ink = options.ink === \"dark\" ? Array.from({ length: height }, (_, y) => Array.from({ length: width }, (_, x) => (rows[y][x] === \"#\" ? \".\" : \"#\")).join(\"\")) : rows;\n const brushes = cover(ink, SHAPES).map((b) => ({ x: b.x, y: b.y, size: b.shape + 1 }));\n return Object.freeze({ width, height, brushes: Object.freeze(brushes) });\n}\n\n/**\n * A video's frames as brushes, worked out when the script is built: a word a brush (x | y << 8 | size << 16), the\n * frames one after another, and where each one starts — the tables the game reads a frame from. Once a build.\n */\ninterface Film { readonly words: readonly number[]; readonly starts: readonly number[] }\nconst films = new Map();\nfunction film(video: Video): Film {\n const had = films.get(video);\n if (had) return had;\n const words: number[] = [], starts: number[] = [0];\n for (const brushes of cover(video, SHAPES)) {\n for (const b of brushes) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n starts.push(words.length);\n }\n const made = { words, starts };\n films.set(video, made);\n return made;\n}\n\n/**\n * Light the fog for this frame: a disc, a picture or a frame of a video. Tiles count from the map's top left, (0, 0).\n *\n * fog.light(P1, 30, 20, 5); // a disc of size 5 centred on tile (30, 20)\n * fog.light(P1, 60, 40, heart); // a picture (fog.picture), its top left on tile (60, 40)\n * fog.light(P1, 0, 0, badApple, f); // frame f of a video the script imports, its top left on tile (0, 0)\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The tile's column: a disc's centre, a picture's left edge.\n * @param y The tile's row: a disc's centre, a picture's top edge.\n * @param shape A size, 1 (3 tiles wide) to 11 (23 wide) — it may change while the game runs — a picture, or a video.\n * @param frame Of a video, which frame, from 0: it may change while the game runs. Past the end, nothing is lit.\n */\nexport const light = game((player: Player, x: number, y: number, shape: number | Picture | Video, frame: number = 0) => {\n if (typeof shape === \"number\") disc(player, x, y, shape);\n else {\n // The picture's corner in pixels once; each brush is its offset from there (a constant of a picture).\n const px = x * 32 + 16, py = y * 32 + 16;\n if (\"brushes\" in shape) for (const b of shape.brushes) discPx(player, px + b.x * 32, py + b.y * 32, b.size);\n else {\n const { words, starts } = film(shape);\n const end = starts[frame + 1];\n for (let i = starts[frame]; i < end; i++) {\n const w = words[i];\n // (A row's offset in pixels straight from its byte: the same as ((w >> 8) & 255) * 32, and the shift only has\n // the byte's eight bits to look at.)\n discPx(player, px + (w & 255) * 32, py + ((w & 0xff00) >> 3), w >> 16);\n }\n }\n }\n});\n\n/**\n * Play a video in the fog, a frame of it every frame of the game, from its first to its last; resolves when it ends.\n * Inside an async program: `await fog.play(P1, badApple)`. On Fastest a game frame is 42 ms, which is what Import\n * Video makes a video's frames by default; the game runs a little slower when a frame is heavy, and so does the video.\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param video A video the script imports.\n * @param x The column of its left edge, 0 by default.\n * @param y The row of its top edge, 0 by default.\n */\nexport const play = game(async (player: Player, video: Video, x: number = 0, y: number = 0) => {\n // (A while: a for over a length known when the script is built would be unrolled, a copy of the body a frame.)\n let f = 0;\n while (f < video.length) {\n light(player, x, y, video, f);\n await nextFrame();\n f++;\n }\n});\n\n/**\n * How fog.columns() lays its columns out, known when the script is built: `count` columns side by side, each `width`\n * tiles across (3, a brush's width, by default) and up to `height` tiles tall, centred on the middle row. `ink`:\n * \"light\" lights each column (the walls of a raycaster bright, on fog), \"dark\" lights all but the columns (dark walls\n * between a lit ceiling and floor); dark is cheaper when columns fill most of the board, light when they are short.\n */\nexport interface ColumnLayout {\n readonly count: number;\n readonly height: number;\n readonly width?: number;\n readonly ink?: \"light\" | \"dark\";\n /**\n * How the walls are told apart, with fog.columns()'s `faces`. \"outline\", the default: every wall drawn as its edges —\n * its top and bottom, a brush deep, and a column lit whole wherever one face meets another (on the nearer of the\n * two) — so that blocks read as boxes, the look of the raycasters of monochrome screens; with dark ink, the edges are\n * lit lines through dark walls. A few brushes a column. Chosen over the rest when played (2026-10-17).\n *\n * The others shade the faces whose number is odd (a raycaster's other side) and leave the rest whole: \"hollow\" —\n * dark, lit only along its top and bottom edges; \"ribbed\" — hollow and lit across the middle of each half; \"panelled\"\n * — hollow and lit across its quarters; \"line\" / \"lines\" — dark lines a tile thick across it at its middle or its\n * quarters (the finest, and two dozen brushes a column near the eye: for a view with room to spare).\n */\n readonly shading?: \"outline\" | \"lines\" | \"line\" | \"hollow\" | \"ribbed\" | \"panelled\";\n}\n\n/**\n * What fog.columns() reads, worked out once a layout when the script is built: for each level of the drawing that is\n * wider than a column (all the columns, a group of them, the last group) and each depth from 0 to half the height, the\n * brushes that cover a rectangle that wide and that deep exactly — the encoder's covers (cover()), a few large brushes\n * in the middle and small ones at the edges. A brush is a word, dx | dy << 8 | size << 16 from the rectangle's top\n * left; `starts` says where each (level, depth) begins.\n */\ninterface ColumnPlan { readonly words: readonly number[]; readonly starts: readonly number[]; readonly group: number; readonly half: number }\nconst columnPlans = new Map();\nconst COLUMN_GROUP = 6;\nfunction columnPlan(layout: ColumnLayout): ColumnPlan {\n const width = layout.width ?? 3, half = layout.height >> 1, group = Math.min(COLUMN_GROUP, layout.count);\n const key = `${layout.count}:${width}:${half}`;\n const had = columnPlans.get(key);\n if (had) return had;\n const words: number[] = [], starts: number[] = [];\n for (const columns of [layout.count, group, layout.count % group || group]) {\n for (let depth = 0; depth <= half; depth++) {\n starts.push(words.length);\n if (depth === 0) continue;\n // A rectangle shallower than a brush is drawn a brush deep, the rest of it on what the level before lit.\n const rows = Array.from({ length: Math.max(depth, 4) }, () => \"#\".repeat(columns * width));\n for (const b of cover(rows, SHAPES)) words.push(b.x | (b.y << 8) | ((b.shape + 1) << 16));\n }\n }\n starts.push(words.length);\n const made = { words, starts, group, half };\n columnPlans.set(key, made);\n return made;\n}\n\n/**\n * One rectangle of fog.columns() wider than a column: the cover at `at` (a level and a depth) drawn twice, the half\n * above the middle and the half below, its top rows `top` and `bottom`, from column `x`.\n */\nconst columnRect = game((player: Player, words: readonly number[], starts: readonly number[], at: number, x: number, top: number, bottom: number) => {\n let i = starts[at];\n const end = starts[at + 1];\n // In pixels once; each brush is its offset (a few bits, a few tests) from there.\n const px = x * 32 + 16, pt = top * 32 + 16, pb = bottom * 32 + 16;\n while (i < end) {\n const w = words[i];\n const dx = (w & 255) * 32, dy = (w & 0xff00) >> 3, size = w >> 16;\n discPx(player, px + dx, pt + dy, size);\n discPx(player, px + dx, pb + dy, size);\n i++;\n }\n});\n\n/**\n * One column's part of fog.columns(), in pixels: brushes (3 × 4) a column of 4 rows apart and the last moved back to\n * end on the edge, twice — from `pt` and from `pb`, the centres of the first brush of each — down a column `k32`\n * pixels deep (32 a row; under 4 rows, a brush deep), centred on `px`. What the smallest brush covers exactly, worked out\n * here rather than read: it is the most common rectangle by far. In pixels because the caller has them, stepped: a\n * product by 32 of a number the game holds is a test a bit, about 0.4 µs, where a step is an add.\n */\nconst columnBarPx = game((player: Player, px: number, pt: number, pb: number, k32: number) => {\n // How far down the last brush is from the first.\n const end = Math.max(k32, 128) - 128;\n let r = 0;\n while (true) {\n centerLocation(SPOT, px, pt, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n centerLocation(SPOT, px, pb, 32, 32);\n createUnit(player, BRUSHES[0], 1, SPOT);\n removeUnit(player, BRUSHES[0]);\n if (r >= end) break;\n const step = Math.min(end - r, 128);\n r += step;\n pt += step;\n pb += step;\n }\n});\n\n/** columnBarPx() in tiles: `k` rows from row `top` down and from row `bottom` down, centred on column `x`. */\nconst columnBar = game((player: Player, x: number, top: number, bottom: number, k: number) => {\n columnBarPx(player, x * 32 + 16, top * 32 + 80, bottom * 32 + 80, k * 32);\n});\n\n/**\n * A shaded column of fog.columns() (ColumnLayout's `shading`): `a` is half its height, `lines` how many lines across\n * each half — 0 hollow, 1 at its middle, 3 at its quarters. A line is a dark row through a lit column (light ink), or\n * a lit band a brush deep through a dark one; a column too short for its lines is drawn plain.\n */\nconst columnShaded = game((player: Player, cx: number, mid: number, a: number, dark: boolean, lines: number) => {\n if (lines <= 0) {\n if (dark) { if (a >= 6) columnBar(player, cx, mid - 4, mid, 4); }\n else if (a < 8) columnBar(player, cx, mid - a, mid, a);\n else {\n // Hollow: the edges. Ribbed (-1) and panelled (-3): bands across each half too, centred on its middle or\n // quarters, where there is room for them between the edges.\n columnBar(player, cx, mid - a, mid + a - 4, 4);\n const ribs = -lines;\n if (ribs > 0 && a >= 6 * (ribs + 1)) {\n let k = 1;\n while (k <= ribs) {\n const at = (a * k) / (ribs + 1);\n columnBar(player, cx, mid - at - 2, mid + at - 2, 4);\n k++;\n }\n }\n }\n } else if (a < 5 * (lines + 1)) {\n if (!dark) columnBar(player, cx, mid - a, mid, a);\n } else {\n // From the middle out: lit up to each line, the line's row dark (light ink); or a lit band on each line (dark ink).\n let from = 0, k = 1;\n while (k <= lines + 1) {\n const to = k > lines ? a : (a * k) / (lines + 1);\n if (dark) { if (k <= lines) columnBar(player, cx, mid - to - 2, mid + to - 2, 4); }\n else columnBar(player, cx, mid - to, mid + from, to - from);\n from = to + 1;\n k++;\n }\n }\n});\n\n/**\n * Light columns for this frame — the walls of a raycaster, a bar chart — each as tall as the program says, centred on\n * the layout's middle row. The covers are worked out when the script is built (see ColumnLayout), so a frame costs a\n * brush for each part of the picture that differs from its neighbours, not one for every few tiles: a wall that fills\n * the board is a few large brushes.\n *\n * const VIEW = { count: 42, height: 96, ink: \"dark\" } as const;\n * fog.columns(P1, 1, 0, VIEW, heights); // heights: one a column, in tiles, the program's\n * fog.columns(P1, 1, 0, VIEW, heights, faces); // faces: which face of which wall each column shows\n *\n * @param player Whose fog: P1 … P8, known when the script is built.\n * @param x The column of the layout's left edge.\n * @param y The row of its top edge.\n * @param layout How the columns are laid out: known when the script is built.\n * @param heights Each column's height in tiles (0 to the layout's height), an array of the program's.\n * @param faces Which face of which wall each column shows, a number the same for every column of one face — in a\n * raycaster, \\`(mapY * width + mapX) * 2 + side\\` — an array of the program's as long as `heights`: what the\n * layout's `shading` tells walls apart by. Optional: without it, every column is lit whole (a bar chart).\n */\nexport const columns = game((player: Player, x: number, y: number, layout: ColumnLayout, heights: readonly number[], faces?: readonly number[]) => {\n const { words, starts, half, group } = columnPlan(layout);\n const count = layout.count, width = layout.width ?? 3, dark = layout.ink === \"dark\";\n // (Dark lines through a lit column count up; lit bands through a dark one, ribbed and panelled, down.)\n // (Without faces there is nothing to tell apart, and every column is whole.)\n const outline = faces !== undefined && (layout.shading === undefined || layout.shading === \"outline\");\n const lines = layout.shading === \"lines\" ? 3 : layout.shading === \"line\" ? 1 : layout.shading === \"ribbed\" ? -1 : layout.shading === \"hollow\" ? 0 : -3;\n const span = half + 1;\n // Each column's depth from where its lit part starts: the middle row for light ink, the top and bottom for dark.\n // A shaded column of light ink is drawn on its own, after the rest: to the rest it is as if it were not there — and\n // so is every column of a light outline, which is all edges.\n const depth: number[] = new Array(count).fill(0);\n // Half of each column's height, at most half the layout's: worked out once. (Clamped before the shift, the same\n // number: the shift then has the few bits the clamp leaves, where a height from the program could have any.)\n const halves: number[] = new Array(count).fill(0);\n // And in pixels (32 a row), for the bars, which place their brushes in pixels: a small number times 32 is a few tests.\n const halves32: number[] = new Array(count).fill(0);\n let least = half, most = 0;\n // (A light outline is all edges: every depth is 0, nothing to work out.)\n const flat = !dark && outline;\n if (flat) least = 0;\n let i = 0;\n while (i < count) {\n const a = Math.min(Math.max(heights[i], 0), 2 * half + 1) >> 1;\n halves[i] = a;\n halves32[i] = a * 32;\n if (!flat) {\n let d = dark ? half - a : a;\n if (faces !== undefined && !dark && !outline && (faces[i] & 1) != 0) d = 0;\n depth[i] = d;\n if (d < least) least = d;\n if (d > most) most = d;\n }\n i++;\n }\n // A rectangle from depth p, k deep, starts on the rows above and below the middle (light) or below the top and above\n // the bottom (dark); one shallower than 4 is drawn 4 deep, reaching back over what is lit already.\n const mid = y + half;\n // Every column, from depth 0 to the least.\n if (least > 0) {\n const k = Math.max(least, 4);\n if (dark) columnRect(player, words, starts, least, x, y + least - k, y + 2 * half - least);\n else columnRect(player, words, starts, least, x, mid - least, mid + least - k);\n }\n // Each group of columns, from the least to the group's least; then each column, from there to its own. (Nothing,\n // when every column's depth is the least: a light outline's always.)\n let g = most > least ? 0 : count;\n while (g < count) {\n const last = Math.min(g + group, count);\n let gl = half;\n let j = g;\n while (j < last) { if (depth[j] < gl) gl = depth[j]; j++; }\n const level = last - g === group ? 1 : 2;\n if (gl > least) {\n const k = gl - least, kk = Math.max(k, 4);\n if (dark) columnRect(player, words, starts, level * span + k, x + g * width, y + gl - kk, y + 2 * half - gl);\n else columnRect(player, words, starts, level * span + k, x + g * width, mid - gl, mid + gl - kk);\n }\n j = g;\n while (j < last) {\n const k = depth[j] - gl;\n if (k > 0) {\n const kk = Math.max(k, 4), cx = x + j * width + 1;\n if (dark) columnBar(player, cx, y + depth[j] - kk, y + 2 * half - depth[j], k);\n else columnBar(player, cx, mid - depth[j], mid + depth[j] - kk, k);\n }\n j++;\n }\n g = last;\n }\n if (outline) {\n // Where one face meets another, the nearer (taller) of the two columns is an edge.\n const edge: number[] = new Array(count).fill(0);\n let face = faces[0], tall = heights[0];\n i = 1;\n while (i < count) {\n const f = faces[i], h = heights[i];\n if (f != face) { if (h >= tall) edge[i] = 1; else edge[i - 1] = 1; }\n face = f;\n tall = h;\n i++;\n }\n // The bars in pixels: a column's centre stepped across, the middle row's worked out once.\n const mid80 = mid * 32 + 80;\n let px = (x + 1) * 32 + 16;\n i = 0;\n while (i < count) {\n const a = halves[i], a32 = halves32[i];\n if (dark) { if (edge[i] != 0 && a >= 2) columnBarPx(player, px, mid80 - a32, mid80, a32); }\n else if (a > 0) {\n if (edge[i] != 0 || a < 8) columnBarPx(player, px, mid80 - a32, mid80, a32);\n else columnBarPx(player, px, mid80 - a32, mid80 + a32 - 128, 128);\n }\n px += width * 32;\n i++;\n }\n } else if (faces !== undefined) {\n i = 0;\n while (i < count) {\n if ((faces[i] & 1) != 0) columnShaded(player, x + i * width + 1, mid, halves[i], dark, lines);\n i++;\n }\n }\n});\n\n/**\n * Keep what was lit this frame on the board for `n` frames, and wait them out: \\`await fog.show(2)\\` in place of\n * \\`await nextFrame()\\` draws every other frame at half the cost. StarCraft: Remastered redraws the fog on the minimap\n * every other frame (measured in two played recordings, 2026-10-17), so a picture drawn every other frame looks the\n * same there as one drawn every frame. The board is wiped at the start of the frame after them, ready for the next.\n *\n * @param n How many frames, 1 to 24, known when the script is built.\n */\nexport const show = game(async (n: number) => {\n memory.vision.countdown = n;\n await sleep(frames(n));\n});\n\n/** Everything above as one name: import { fog } from \"trigscript/fog\"; fog.light(P1, x, y, 3). */\nexport const fog = { light, rect, columns, show, play, reveal, picture, SHAPES };\n\n/** The longest fog.show() keeps a picture: the countdown the game sets itself after a wipe is longer than this. */\nconst SHOW_MOST = 24;\n\n// The canvas: every brush's sight set, every frame, and the board wiped on the next — for as long as the game runs —\n// unless a program asked for the picture to stay (fog.show), when the countdown is that program's to run down.\nprogram(() => {\n while (true) {\n for (let s = 1; s <= 11; s++) stats(BRUSHES[s - 1]).sight = s;\n const left = memory.vision.countdown;\n if (left == 0 || left > SHOW_MOST) memory.vision.countdown = 1;\n sleep(frames(1));\n }\n});\n", "math": "/**\n * Numbers for motion and play: the standard library's \"trigscript/math\" (TrigScript 4).\n *\n * import { Vec, lerp, easeOutQuad, distance, angleTo, approach, wrap } from \"trigscript/math\";\n *\n * const t = fixed(frame) / 48; // 0 to 1 over two seconds\n * const x = lerp(fromX, toX, easeOutQuad(t)); // eased from one place to another\n * const v = Vec.fromAngle(angleTo(x, y, tx, ty), fixed(4));\n * pos = pos.add(v);\n *\n * Fractions are the language's fixed numbers (16.16: four decimal places or so, from about −32 768 to 32 767): a\n * number becomes one when a fraction is stored into it, or written `fixed(…)`. Angles are radians, as JavaScript's are.\n * Whole numbers stay whole where they can — `distanceSq`, `manhattan`, `wrap`, `sign` — and cost less.\n */\n\n/** π, and a whole turn. */\nexport const PI = Math.PI;\nexport const TAU = Math.PI * 2;\n\n/** From a to b by t: a at 0, b at 1, between them in between (t outside 0 … 1 goes past). */\nexport function lerp(a: fixed, b: fixed, t: fixed): fixed {\n return a + (b - a) * t;\n}\n\n/** Where v is from a to b, as lerp's t: 0 at a, 1 at b. */\nexport function inverseLerp(a: fixed, b: fixed, v: fixed): fixed {\n return b === a ? fixed(0) : (v - a) / (b - a);\n}\n\n/** v from the range a1 … b1 into a2 … b2. */\nexport function remap(v: fixed, a1: fixed, b1: fixed, a2: fixed, b2: fixed): fixed {\n return lerp(a2, b2, inverseLerp(a1, b1, v));\n}\n\n/** t kept inside 0 … 1. */\nexport function clamp01(t: fixed): fixed {\n return t < 0 ? fixed(0) : t > 1 ? fixed(1) : t;\n}\n\n/** From `current` towards `target` by at most `step`, never past it: a value that follows another at a speed. */\nexport function approach(current: number, target: number, step: number): number {\n if (current < target) return current + step > target ? target : current + step;\n return current - step < target ? target : current - step;\n}\n\n/** n into 0 … size − 1, going round: wrap(-1, 10) is 9, wrap(12, 10) is 2. */\nexport function wrap(n: number, size: number): number {\n return ((n % size) + size) % size;\n}\n\n/** −1, 0 or 1, by whether n is below, at or above zero. */\nexport function sign(n: number): number {\n return n > 0 ? 1 : n < 0 ? -1 : 0;\n}\n\n/** The distance from one point to another, as the crow flies. */\nexport function distance(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.hypot(x2 - x1, y2 - y1);\n}\n\n/** The distance squared: whole, and cheaper — compare it with a range squared. */\nexport function distanceSq(x1: number, y1: number, x2: number, y2: number): number {\n return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n}\n\n/** The distance along the axes, |dx| + |dy|: what the game's own \"nearest\" goes by. */\nexport function manhattan(x1: number, y1: number, x2: number, y2: number): number {\n return Math.abs(x2 - x1) + Math.abs(y2 - y1);\n}\n\n/** The angle from one point to another, in radians from −π to π: 0 is to the right (east), π / 2 down (south, y grows down). */\nexport function angleTo(x1: number, y1: number, x2: number, y2: number): fixed {\n return Math.atan2(y2 - y1, x2 - x1);\n}\n\n/** Degrees as radians. */\nexport function radians(degrees: fixed): fixed {\n return (degrees * PI) / 180;\n}\n\n/** Radians as degrees. */\nexport function degrees(radians: fixed): fixed {\n return (radians * 180) / PI;\n}\n\n/* Easing: t from 0 to 1, how far along a motion is at that point of its time — slow then fast, fast then slow, … */\n\n/** Slow at the start. */\nexport function easeInQuad(t: fixed): fixed {\n return t * t;\n}\n\n/** Slow at the end. */\nexport function easeOutQuad(t: fixed): fixed {\n return t * (2 - t);\n}\n\n/** Slow at both ends. */\nexport function easeInOutQuad(t: fixed): fixed {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n}\n\n/** Slower at the start than easeInQuad. */\nexport function easeInCubic(t: fixed): fixed {\n return t * t * t;\n}\n\n/** Slower at the end than easeOutQuad. */\nexport function easeOutCubic(t: fixed): fixed {\n const u = t - 1;\n return u * u * u + 1;\n}\n\n/** Goes a little past the end and comes back. */\nexport function easeOutBack(t: fixed): fixed {\n const u = t - 1;\n return 1 + 2.70158 * u * u * u + 1.70158 * u * u;\n}\n\n/** Slow at both ends, smoothly (Hermite: 3t² − 2t³). */\nexport function smoothstep(t: fixed): fixed {\n return t * t * (3 - 2 * t);\n}\n\n/**\n * A point, or a direction and a length: two fixed numbers. Each operation gives a new Vec.\n *\n * let pos = new Vec(fixed(x), fixed(y));\n * const toward = new Vec(fixed(tx), fixed(ty)).sub(pos).normalized().scale(fixed(3));\n * pos = pos.add(toward);\n */\nexport class Vec {\n x: fixed;\n y: fixed;\n\n constructor(x: fixed, y: fixed) {\n this.x = x;\n this.y = y;\n }\n\n /** A direction `length` long at `angle` radians (0 to the right, π / 2 down). */\n static fromAngle(angle: fixed, length: fixed): Vec {\n return new Vec(Math.cos(angle) * length, Math.sin(angle) * length);\n }\n\n add(o: Vec): Vec {\n return new Vec(this.x + o.x, this.y + o.y);\n }\n\n sub(o: Vec): Vec {\n return new Vec(this.x - o.x, this.y - o.y);\n }\n\n scale(k: fixed): Vec {\n return new Vec(this.x * k, this.y * k);\n }\n\n dot(o: Vec): fixed {\n return this.x * o.x + this.y * o.y;\n }\n\n /** How long it is. */\n length(): fixed {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n }\n\n /** The same direction, 1 long (or none, for none). */\n normalized(): Vec {\n const l = this.length();\n const k: fixed = l === 0 ? fixed(0) : 1 / l;\n return new Vec(this.x * k, this.y * k);\n }\n\n /** Its angle, in radians from −π to π. */\n angle(): fixed {\n return Math.atan2(this.y, this.x);\n }\n\n /** Turned by `angle` radians (clockwise on the map, where y grows down). */\n rotate(angle: fixed): Vec {\n const c = Math.cos(angle);\n const s = Math.sin(angle);\n return new Vec(this.x * c - this.y * s, this.x * s + this.y * c);\n }\n\n /** How far it is from another point. */\n distanceTo(o: Vec): fixed {\n return this.sub(o).length();\n }\n\n /** From this towards another by t (0 here, 1 there). */\n lerp(o: Vec, t: fixed): Vec {\n return new Vec(this.x + (o.x - this.x) * t, this.y + (o.y - this.y) * t);\n }\n}\n", - "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false, release = releaseOf(z);\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one — held by the\n // pedal or still dying away after it was let go (a string struck again starts again).\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) {\n const next = order[j].at;\n if (next < off) { off = next; stolen = true; release = 0.12; }\n else if (next < off + release) release = Math.max(0.1, next - off + 0.1);\n break;\n }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n // (A pedal down before 0 was put down, and comes up, in the excerpt before this one: no sound of it here.)\n if (releases) for (const [down, up] of pedal) if (down >= 0) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n /**\n * A film trailer's \"braam\": five saws low and wide, the filter opening over half a second and closing slowly, driven\n * hard — the brass section's blast as a synth. Play it low (A1 … A2), with the low brass on the same notes.\n */\n braam: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 16, width: 0.6, volume: 0.22, attack: 0.04, decay: 1.2, sustain: 0.7, release: 0.9, filter: { cutoff: 160, amount: 3.4, resonance: 0.25, envelope: { attack: 0.45, decay: 1.6, sustain: 0.35, release: 0.8 } }, drive: 14, ...o }),\n /** A short synth pulse for sixteenth ostinatos: two squares, a quick filter blip. */\n pulse: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 9, width: 0.4, volume: 0.12, attack: 0.002, decay: 0.09, sustain: 0.25, release: 0.04, filter: { cutoff: 900, amount: 2.2, resonance: 0.3, envelope: { decay: 0.08, sustain: 0.1 } }, ...o }),\n /** A sub bass: a sine, soft at the start, under everything. */\n sub: (o: SynthOptions = {}) => synth({ wave: \"sine\", volume: 0.4, attack: 0.02, decay: 0.3, sustain: 0.9, release: 0.25, ...o }),\n};\n\n/**\n * An instrument of one-shots: a clip a key (\"C2\": the impact, \"D2\": a riser), each played whole whatever the note's\n * length and not moved in pitch, as loud as its velocity says — percussion and effects as parts of a performance\n * (`perform`), beside the instruments that play notes: `music.hits({ C2: music.impact(), D2: music.riser(4) })`.\n */\nexport function hits(clips: Readonly>, options: { readonly volume?: number } = {}): Instrument {\n const volume = options.volume ?? 1, byKey = new Map();\n for (const [name, clip] of Object.entries(clips)) byKey.set(noteNumber(name), clip);\n const clipOf = (name: string) => {\n const c = byKey.get(noteNumber(name));\n if (!c) throw new Error(`hits() has no clip for ${name}: it has ${Object.keys(clips).join(\", \")}.`);\n return c;\n };\n return Object.freeze({\n kind: \"notes\" as const,\n note: (name: string) => (volume === 1 ? clipOf(name) : clipOf(name).gain(volume)),\n strike: (name: string, _seconds: number, velocity: number) => clipOf(name).gain(volume * velocity),\n });\n}\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/**\n * The part of a performance from bar `from` up to bar `to` (not included; to its end when left out), bars as\n * `performance.bars` counts them, as a performance from 0 of its own: the notes struck in it, their times from its\n * start, and the pedal — down already when the pedal went down before it (its sound is the excerpt's before), held to\n * where it comes up. Render a long piece a section at a time, each with its room, its tail ringing on under the next\n * when the sections are added up at their `at`s: `music.render(music.excerpt(take, 44, 60), { reverb: ROOM })`.\n */\nexport function excerpt(p: Performance, from: number, to?: number): Performance & { readonly at: number } {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"excerpt() takes a performance made by music.perform.\");\n const last = p.bars.length - 1;\n if (!(Number.isInteger(from) && from >= 0 && from <= last)) throw new Error(`excerpt() starts on a bar, 0 to ${last}, not ${from}.`);\n if (to !== undefined && !(Number.isInteger(to) && to > from && to <= last)) throw new Error(`excerpt() ends on a bar after ${from}, at most ${last}, not ${to}.`);\n const a = p.bars[from], b = to === undefined ? Infinity : p.bars[to];\n const notes = p.notes.filter((n) => n.at >= a - 1e-9 && n.at < b - 1e-9).map((n) => Object.freeze({ ...n, at: n.at - a, end: n.end - a, frame: Math.round((n.at - a) / FRAME) }));\n const clip = (list: readonly (readonly [number, number])[]) => list.filter(([d, u]) => u > a && d < b).map(([d, u]) => [d - a, u - a] as [number, number]);\n const pedal = new Map();\n for (const [inst, list] of inside.pedal) pedal.set(inst, clip(list));\n const made = Object.freeze({\n kind: \"performance\" as const, at: a, notes: Object.freeze(notes), pedal: Object.freeze(clip(p.pedal).map((x) => Object.freeze(x))),\n bars: Object.freeze(p.bars.slice(from, to === undefined ? undefined : to + 1).map((t) => t - a)), parts: p.parts,\n seconds: Math.max(0, ...notes.map((n) => n.end)),\n });\n performances.set(made, { parts: inside.parts, pedal });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n for (const { part } of inside.parts) {\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) throw new Error(\"render(): the performance plays no notes.\");\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, excerpt, hits, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", + "music": "/**\n * Music in a program: the standard library's \"trigscript/music\" (TrigScript 4).\n *\n * import { music } from \"trigscript/music\";\n * import pluck from \"./pluck.sound\";\n *\n * const lead = music.synth({ wave: \"square\", volume: 0.2 });\n * const bass = music.sampler(pluck, \"A3\");\n * const drums = music.kit({ k: kick, s: snare, h: hat });\n *\n * const song = music.song({ bpm: 120 },\n * music.track(lead, \"C5 - E5 - G5 - - . | A5 - G5 - E5 - - .\"),\n * music.track(bass, \"C3 - - - - - - - | F3 - - - - - - -\"),\n * music.track(drums, \"kh h sh h kh h sh h | kh h sh h kh kh sh h\"),\n * );\n *\n * program(async () => {\n * start(music.loop(song)); // the song again and again, beside the program\n * playWav(lead.note(\"C6\", 0.1)); // an instrument's note on its own, for a sound effect\n * });\n *\n * A pattern is steps, a word each, a quarter of a beat each by default: a note's name starts it (\"C4\", \"F#5\", \"Bb2\"),\n * several with + sound together (\"C4+E4+G4\"), \"-\" holds what sounds a step longer, \".\" is a rest, \"|\" is only for the\n * eye; \"@\" after a step's notes says how loud (\"C4@0.5\"). A kit's step is its sounds' letters (\"kh\": kick and hat).\n * Everything is worked out when the script is built: each note an instrument plays becomes a clip once (`trigscript`'s\n * Clip, put in the map once however often it plays), and the song a table of which clip starts on which frame, which\n * `play` reads while the game runs.\n *\n * A longer song is written in sections — parts named once, each section saying what they play in it, a pattern played\n * again until the section is full — and chords by name, their notes drawn by a template:\n *\n * const parts = { keys: music.part(music.presets.keys()), bass: music.part(music.presets.bass()), drums: music.part(music.drums()) };\n * const verse = music.section(4, {\n * keys: music.chords(\"Am F C G\", \"1+2+3 - . 1+2+3 . . 1+2+3 -\", { octave: 4, lead: true }),\n * bass: music.chords(\"Am F C G\", \"1 - . 1 . 1 3 -\", { octave: 2 }),\n * drums: music.beat({ k: [0, 3, 4], s: [2, 6], h: [0, 1, 2, 3, 4, 5, 6, 7] }, 8),\n * });\n * const song = music.arrange({ bpm: 120, steps: 2 }, parts, intro, verse, verse.with({ keys: null }), outro);\n *\n * Music that follows the game is a song of sections cut into bars and layers, a clip each, which the program steers\n * bar by bar — which section, which layers, a stinger on the next beat:\n *\n * const cut = music.stems(song, { layers: { drums: [\"drums\"], rest: [\"keys\", \"bass\"] } });\n * program(async () => {\n * const band = new Band(); // import { music, Band } from \"trigscript/music\"\n * start(music.conduct(cut, band));\n * if (danger) band.go(cut.section(\"chorus\")); // at the next bar line\n * if (cleared) band.sting(cut.stinger(\"crash\")); // on the next beat\n * });\n *\n * What the game does with it (the sound probe, 2026-10-19): a bar is a whole number of frames (42 ms on Fastest), so\n * the tempo is the nearest that fits — `song.bpm` says which; a sound starts within 21 ms of its frame; 32 sound at\n * once, and a song that would need more is refused; notes that overlap add, with no limiter, so keep the volumes down.\n * `render` mixes a song into one clip when the script is built instead: every note exactly in time, one sound playing,\n * nothing to change while it plays. A program plays to its own player; a program for each player plays to each.\n */\nimport { game, sleep, frames, playWav, tone, noise, fm, pluck, mixdown, together, memory, type Clip, type Notes, type Samples, type SampleZone } from \"trigscript\";\n\n/** Seconds a frame lasts on Fastest, the speed a map is played at. */\nconst FRAME = 0.042;\n/** Sounds the game plays at once. */\nconst VOICES = 32;\n\n/** What plays a pattern's notes: each note a clip, made when the script is built. */\nexport interface Instrument {\n readonly kind: \"notes\";\n /**\n * Note `name` (\"C4\", \"F#5\") lasting `seconds`, release and all: a clip to play on its own, too. `rate`: samples a\n * second, for an instrument that makes its notes (render asks for 44 100).\n */\n note(name: string, seconds: number, rate?: number): Clip;\n /**\n * The note struck at `velocity` — a pattern's \"@\", 1 as written — for an instrument whose strength changes more than\n * its loudness (`sampled`: a soft note is a soft recording). Without it a note is `note` made louder or quieter.\n */\n strike?(name: string, seconds: number, velocity: number, rate?: number): Clip;\n /**\n * A performance's notes on this instrument (`perform`), each at its own time and strength, and its sustain pedal —\n * [down, up] in seconds — played as the instrument plays them together (a sampled piano's pedal, the sounds of its\n * keys let go), as one clip from 0. Without it each note is `note` (or `strike`) at its time.\n */\n together?(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip;\n}\n\n/** A note as an instrument plays it in a performance: from `at` to `end` seconds (the key let go), its key, how hard (1 … 127). */\nexport interface Struck { readonly at: number; readonly end: number; readonly pitch: number; readonly velocity: number }\n\n/** What plays a pattern's letters: a clip a letter. */\nexport interface Kit {\n readonly kind: \"kit\";\n readonly hits: Readonly>;\n}\n\nconst SEMITONE: Readonly> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };\n\n/** A note's number, 69 for A4: \"C4\" is 60, \"C#4\" 61, \"Db4\" 61. */\nfunction noteNumber(name: string): number {\n const m = /^([A-Ga-g])([#b]?)(-?\\d)$/.exec(name);\n if (!m) throw new Error(`A note is a name with its octave — \"C4\", \"F#5\", \"Bb2\" — not ${JSON.stringify(name)}.`);\n return 12 * (Number(m[3]) + 1) + SEMITONE[m[1].toLowerCase()] + (m[2] === \"#\" ? 1 : m[2] === \"b\" ? -1 : 0);\n}\n\n/** Notes kept as they are made, so a note played many times is the same clip (and the same file in the map). */\nfunction remembering(make: (name: string, seconds: number, rate?: number) => Clip): (name: string, seconds: number, rate?: number) => Clip {\n const made = new Map();\n return (name, seconds, rate) => {\n const key = `${name} ${seconds.toFixed(4)} ${rate ?? \"\"}`;\n let c = made.get(key);\n if (!c) { c = make(name, seconds, rate); made.set(key, c); }\n return c;\n };\n}\n\n/**\n * An instrument from a recording of one note, `root` (\"A3\"): every other note is it played faster or slower, as a\n * sampler does, cut to the note's length with a short release. Where the recording is shorter than a note, the note\n * is as long as the recording.\n */\nexport function sampler(clip: Clip, root: string = \"C4\", options: { readonly release?: number; readonly volume?: number } = {}): Instrument {\n const base = noteNumber(root), release = options.release ?? 0.05, volume = options.volume ?? 1;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds) => {\n const pitched = clip.pitch(noteNumber(name) - base).gain(volume);\n return pitched.trim(0, Math.min(pitched.seconds, seconds)).fade(0, Math.min(release, seconds / 2));\n }),\n });\n}\n\n/** An attack, a decay to the sustain level, and a release after the note's length, in seconds (sustain 0 … 1). */\nexport interface Shape { readonly attack?: number; readonly decay?: number; readonly sustain?: number; readonly release?: number }\n\n/** A shape's points for a note held `held` seconds, as levels 0 … 1: the attack from 0, the release to 0. */\nfunction shapePoints(shape: Required, held: number): [number, number][] {\n const { attack, decay, sustain, release } = shape;\n const h = Math.max(attack + decay, held);\n return [[0, 0], [attack, 1], [attack + decay, sustain], [h, sustain], [h + release, 0]];\n}\nconst full = (s: Shape | undefined, d: Required): Required => ({ attack: s?.attack ?? d.attack, decay: s?.decay ?? d.decay, sustain: s?.sustain ?? d.sustain, release: s?.release ?? d.release });\n\n/** A synth's filter: its type, the cutoff it rests at, its resonance, and how many octaves above it a note's envelope opens it. */\nexport interface SynthFilter {\n readonly type?: \"lowpass\" | \"highpass\" | \"bandpass\";\n readonly cutoff: number;\n readonly resonance?: number;\n /** Octaves above the cutoff at the envelope's top (0: the filter does not move). */\n readonly amount?: number;\n /** The filter's own attack, decay, sustain and release, as a note's loudness has. */\n readonly envelope?: Shape;\n}\n\nexport interface SynthOptions extends Shape {\n readonly wave?: \"sine\" | \"square\" | \"triangle\" | \"saw\";\n readonly volume?: number;\n /** Copies of each note (1 to 16), `detune` cents apart from lowest to highest, `width` 0 … 1 across left and right. */\n readonly voices?: number;\n readonly detune?: number;\n readonly width?: number;\n readonly filter?: SynthFilter;\n /** Saturation after the filter, dB of push (`Clip.drive`). */\n readonly drive?: number;\n /** Semitones each note slides up from (a negative number: from below) over `glideTime` seconds. */\n readonly glide?: number;\n readonly glideTime?: number;\n}\n\n/**\n * An instrument made of tones: `wave` (\"sine\", \"square\", \"triangle\", \"saw\") shaped by an attack, a decay to the\n * sustain level, and a release after the note's length — a stack of detuned copies with `voices`, through a filter\n * that opens and closes with each note with `filter`, saturated with `drive`.\n */\nexport function synth(options: SynthOptions = {}): Instrument {\n const wave = options.wave ?? \"square\", volume = options.volume ?? 0.2;\n const amp = full(options, { attack: 0.005, decay: 0.08, sustain: 0.7, release: 0.06 });\n const f = options.filter, fshape = full(f?.envelope, { attack: 0.005, decay: 0.25, sustain: 0.2, release: 0.2 });\n const voices = options.voices ?? 1, detune = options.detune ?? (voices > 1 ? 20 : 0), width = options.width ?? 0;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n const r = rate === undefined ? {} : { rate };\n const pitch = options.glide ? [[0, 440 * 2 ** ((noteNumber(name) + options.glide - 69) / 12)], [options.glideTime ?? 0.06, name]] as [number, number | string][] : name;\n let c = tone(pitch, length, { wave, volume, voices, detune, width, ...r });\n if (f) {\n const amount = f.amount ?? 0, base = f.cutoff;\n const cutoff = amount === 0 ? base : shapePoints(fshape, held).map(([t, level]) => [t, base * 2 ** (amount * level)] as [number, number]);\n c = c.filter(f.type ?? \"lowpass\", cutoff, { resonance: f.resonance ?? 0.1 });\n }\n if (options.drive) c = c.drive(options.drive);\n return c.envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/**\n * An FM instrument (`fm()`): `ratio` the modulator's pitch to the note's, `index` how bright a note starts, falling to\n * `index × brightness` over `bright` seconds — an electric piano (ratio 1), a bell (3.5), a bass (0.5).\n */\nexport function fmSynth(options: Shape & { readonly ratio?: number; readonly index?: number; readonly brightness?: number; readonly bright?: number; readonly feedback?: number; readonly volume?: number } = {}): Instrument {\n const amp = full(options, { attack: 0.002, decay: 1.2, sustain: 0.35, release: 0.3 });\n const ratio = options.ratio ?? 1, index = options.index ?? 3, after = index * (options.brightness ?? 0.2), bright = options.bright ?? 0.8, volume = options.volume ?? 0.25;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const held = Math.max(amp.attack + amp.decay, seconds - amp.release), length = held + amp.release;\n return fm(name, length, { ratio, index: [[0, index], [bright, after]], feedback: options.feedback ?? 0, volume, ...(rate === undefined ? {} : { rate }) }).envelope(...shapePoints(amp, held));\n }),\n });\n}\n\n/** A plucked-string instrument (`pluck()`): `brightness` 0 … 1, `decay` seconds; a note rings out its decay unless `cut`. */\nexport function strings(options: { readonly brightness?: number; readonly decay?: number; readonly volume?: number; readonly cut?: boolean } = {}): Instrument {\n const brightness = options.brightness ?? 0.55, decay = options.decay ?? 1.5, volume = options.volume ?? 0.3;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const length = options.cut ? seconds + 0.05 : Math.max(seconds + 0.05, Math.min(decay, 4));\n return pluck(name, length, { brightness, decay, volume, ...(rate === undefined ? {} : { rate }) }).fade(0, 0.05);\n }),\n });\n}\n\n/** How a sampled instrument (`sampled`) plays. */\nexport interface SampledOptions {\n /** How loud, 1 as recorded. */\n readonly volume?: number;\n /** The velocity (1 … 127) a pattern's note strikes at \"@1\", as written (100, as `midi` reads a file's). */\n readonly velocity?: number;\n /** Seconds a note takes to die away after it is let go, over the instrument's own (a piano's: 1). */\n readonly release?: number;\n /** Whether a key let go, and the pedal pressed and lifted, make their own sounds where the instrument has them (true). */\n readonly releases?: boolean;\n /**\n * How loud the strings answer while the sustain pedal is down (`Clip.resonance`): 0 none (as left out), 0.2 a piano's.\n * Only in a performance (`perform`), which has a pedal.\n */\n readonly resonance?: number;\n /** Seconds the strings ring with the pedal down (3). */\n readonly ring?: number;\n /** Semitones every note is moved by (0). */\n readonly transpose?: number;\n}\n\n/** A note's loudness by its velocity, as SFZ's amp_veltrack has it: 1 at 127, down to 1 − track at 0, by the velocity squared. */\nconst velocityGain = (velocity: number, track: number) => 1 - track + track * (velocity / 127) ** 2;\nconst dB = (x: number) => 10 ** (x / 20);\n\n/** The zones of `trigger` that play `key` at `velocity`, the nearest keys and strengths where none does. */\nfunction zonesFor(zones: readonly SampleZone[], trigger: string, key: number, velocity: number): SampleZone[] {\n const of = zones.filter((z) => (z.trigger ?? \"attack\") === trigger);\n if (of.length === 0) return [];\n // The nearest keys first: the zones that play the key, or else those whose range is closest to it.\n const keyGap = (z: SampleZone) => (key < z.lo ? z.lo - key : key > z.hi ? key - z.hi : 0);\n const near = Math.min(...of.map(keyGap));\n const keyed = of.filter((z) => keyGap(z) === near);\n const velGap = (z: SampleZone) => (velocity < z.vlo ? z.vlo - velocity : velocity > z.vhi ? velocity - z.vhi : 0);\n const best = Math.min(...keyed.map(velGap));\n return keyed.filter((z) => velGap(z) === best);\n}\n\n/** One of zones that play together in turn (`turn`) or by chance (`chance`): the `count`th time, or by `roll` (0 … 1). */\nfunction pick(list: readonly SampleZone[], count: number, roll: number): SampleZone {\n if (list.length === 1) return list[0];\n const turns = list.filter((z) => z.turns !== undefined && z.turn !== undefined);\n if (turns.length) {\n const n = turns[0].turns ?? turns.length, want = (count % n) + 1;\n return turns.find((z) => z.turn === want) ?? turns[0];\n }\n const chance = list.find((z) => z.chance !== undefined && roll >= z.chance[0] && roll < z.chance[1]);\n return chance ?? list[count % list.length];\n}\n\n/**\n * An instrument played from recordings (`import piano from \"./piano.samples\"`, made from an SFZ instrument by\n * scripts/make-samples.mts): each note from the recording made nearest its key — moved the few semitones to it, no\n * further — and among those the one made at its strength, so a soft note is a soft recording, not a loud one turned\n * down. A note held rings as recorded; let go, it dies away over its `release`, and the instrument's sound of a key let\n * go plays (a piano's damper and its strings settling). In a performance (`perform`) its sustain pedal holds what is\n * let go until it comes up, the pedal's own sound plays, a key struck again while it sounds stops the sound before,\n * and with `resonance` the strings ring in sympathy while the pedal is down. In a pattern, \"@\" chooses the strength:\n * \"@1\" is velocity 100 (`velocity`), \"@0.5\" 50.\n */\nexport function sampled(set: Samples, options: SampledOptions = {}): Instrument {\n const volume = options.volume ?? 1, base = options.velocity ?? 100, extra = options.release ?? 0, releases = options.releases ?? true;\n const resonance = options.resonance ?? 0, ring = options.ring ?? 3, transpose = options.transpose ?? 0;\n if (!(volume >= 0)) throw new Error(`A sampled instrument's volume is 0 or more, not ${volume}.`);\n if (!(base >= 1 && base <= 127)) throw new Error(`A sampled instrument's velocity is 1 to 127, not ${base}.`);\n if (!(resonance >= 0 && resonance <= 2)) throw new Error(`A sampled instrument's resonance is 0 to 2, not ${resonance}.`);\n if (set.zones.filter((z) => (z.trigger ?? \"attack\") === \"attack\").length === 0) throw new Error(`The instrument ${set.name || \"given\"} has no zone a key plays.`);\n /** A zone's recording at `key`: moved to it, its own tuning undone. */\n const pitched = (z: SampleZone, key: number) => (z.pitched === false ? 0 : key - z.key - (z.tune ?? 0) / 100);\n /**\n * A note: zone `z` at `key`, struck at `velocity`, let go after `held` seconds and dying away over `release`. The\n * recording is cut to what is heard before it is moved in pitch, so a short note of a long recording costs little.\n */\n const voice = (z: SampleZone, key: number, velocity: number, held: number, release: number, rate?: number): Clip => {\n const shift = pitched(z, key), speed = 2 ** (shift / 12);\n const heard = held + release, need = Math.min(z.clip.seconds, heard * speed + 0.01);\n let c = need < z.clip.seconds ? z.clip.trim(0, need) : z.clip;\n if (Math.abs(shift) > 1e-6) c = c.pitch(shift);\n if (held < c.seconds) {\n // Down 60 dB over the release, as the dampers do: eight straight pieces of the curve.\n const points: [number, number][] = [[0, 1], [held, 1]];\n for (let j = 1; j <= 8; j++) points.push([held + (release * j) / 8, j === 8 ? 0 : dB((-60 * j) / 8)]);\n c = c.envelope(...points);\n if (c.seconds > heard) c = c.trim(0, heard);\n }\n const g = volume * dB(z.volume ?? 0) * velocityGain(velocity, z.veltrack ?? 1);\n const made = g === 1 ? c : c.gain(g);\n return rate === undefined || rate === made.rate ? made : mixdown([{ clip: made, at: 0 }], undefined, rate);\n };\n /** The sound of a key let go after `held` seconds, if the instrument has one for it. */\n const letGo = (key: number, velocity: number, held: number, count: number): Clip | null => {\n if (!releases) return null;\n const list = zonesFor(set.zones, \"release\", key, velocity).filter((z) => key >= z.lo && key <= z.hi);\n if (list.length === 0) return null;\n // Each release zone of the key sounds: a piano's damper (one zone) and its strings settling (another).\n const groups = new Map();\n for (const z of list) { const k = `${z.volume ?? 0}|${z.decay ?? 0}|${z.pitched}`; const g = groups.get(k); if (g) g.push(z); else groups.set(k, [z]); }\n let out: Clip | null = null;\n for (const g of groups.values()) {\n const z = pick(g, count, 0), shift = pitched(z, key);\n const level = volume * dB((z.volume ?? 0) - (z.decay ?? 0) * held) * velocityGain(velocity, z.veltrack ?? 1);\n if (level < 1e-4) continue;\n const c = (Math.abs(shift) > 1e-6 ? z.clip.pitch(shift) : z.clip).gain(level);\n out = out ? out.mix(c) : c;\n }\n return out;\n };\n const releaseOf = (z: SampleZone) => (z.release ?? 0.3) + extra;\n const midiOf = (name: string) => noteNumber(name) + transpose;\n return Object.freeze({\n kind: \"notes\" as const,\n note: remembering((name, seconds, rate) => {\n const key = midiOf(name), z = pick(zonesFor(set.zones, \"attack\", key, base), 0, 0);\n return voice(z, key, base, seconds, releaseOf(z), rate);\n }),\n strike(name: string, seconds: number, velocity: number, rate?: number): Clip {\n const key = midiOf(name), v = Math.max(1, Math.min(127, Math.round(velocity * base))), z = pick(zonesFor(set.zones, \"attack\", key, v), 0, 0);\n return voice(z, key, v, seconds, releaseOf(z), rate);\n },\n together(notes: readonly Struck[], pedal: readonly (readonly [number, number])[], rate: number): Clip {\n const order = [...notes].sort((a, b) => a.at - b.at);\n const parts: { clip: Clip; at: number }[] = [];\n const counts = new Map();\n let roll = 0x2545f491;\n const random = () => { roll ^= roll << 13; roll ^= roll >>> 17; roll ^= roll << 5; return (roll >>> 0) / 4294967296; };\n // When a note is let go for good: the key up, or the pedal up after it if the pedal was down then.\n const damped = (t: number) => { for (const [down, up] of pedal) if (t >= down && t < up) return up; return t; };\n order.forEach((n, k) => {\n const key = n.pitch + transpose, v = Math.max(1, Math.min(127, Math.round(n.velocity)));\n const count = counts.get(key) ?? 0;\n counts.set(key, count + 1);\n const z = pick(zonesFor(set.zones, \"attack\", key, v), count, random());\n let off = damped(n.end), stolen = false, release = releaseOf(z);\n // The same key struck again while it sounds: the sound before stops, quickly, under the new one — held by the\n // pedal or still dying away after it was let go (a string struck again starts again).\n for (let j = k + 1; j < order.length; j++) if (order[j].pitch === n.pitch && order[j].at > n.at) {\n const next = order[j].at;\n if (next < off) { off = next; stolen = true; release = 0.12; }\n else if (next < off + release) release = Math.max(0.1, next - off + 0.1);\n break;\n }\n const held = Math.max(0.005, off - n.at);\n parts.push({ clip: voice(z, key, v, held, release, rate), at: n.at });\n if (!stolen) { const r = letGo(key, v, held, count); if (r) parts.push({ clip: r, at: off }); }\n });\n // (A pedal down before 0 was put down, and comes up, in the excerpt before this one: no sound of it here.)\n if (releases) for (const [down, up] of pedal) if (down >= 0) {\n for (const [trigger, at] of [[\"pedal-down\", down], [\"pedal-up\", up]] as const) {\n const list = set.zones.filter((z) => z.trigger === trigger);\n if (list.length === 0) continue;\n const z = pick(list, 0, random());\n parts.push({ clip: z.clip.gain(volume * dB(z.volume ?? 0)), at });\n }\n }\n if (parts.length === 0) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], undefined, rate);\n const mixed = mixdown(parts, undefined, rate);\n return resonance > 0 && pedal.length > 0 ? mixed.resonance({ pedal, amount: resonance, decay: ring }) : mixed;\n },\n });\n}\n\n/**\n * Instruments to start from, each a function that takes the same options as the instrument it is made with, over its\n * own: `music.presets.supersaw({ volume: 0.1 })`.\n */\nexport const presets = {\n /** Seven detuned saws through a filter that opens on each note: a trance lead, big chords. */\n supersaw: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 28, width: 0.7, volume: 0.16, attack: 0.005, decay: 0.25, sustain: 0.8, release: 0.18, filter: { cutoff: 1800, amount: 2, resonance: 0.15, envelope: { decay: 0.35, sustain: 0.35 } }, ...o }),\n /** A slow, wide pad: five saws, the filter low and slowly opening. Give its track a chorus and the reverb. */\n pad: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 18, width: 1, volume: 0.1, attack: 0.35, decay: 0.6, sustain: 0.85, release: 0.8, filter: { cutoff: 700, amount: 1.3, resonance: 0.1, envelope: { attack: 0.6, decay: 1.2, sustain: 0.5, release: 0.8 } }, ...o }),\n /** A round, punchy bass: two saws, the filter snapping shut after each note, a little drive. */\n bass: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 8, volume: 0.32, attack: 0.002, decay: 0.12, sustain: 0.9, release: 0.04, filter: { cutoff: 180, amount: 2.6, resonance: 0.25, envelope: { decay: 0.18, sustain: 0.15, release: 0.05 } }, drive: 6, ...o }),\n /** A squelchy, resonant line (a 303's): one saw, the filter wide open on each note and shutting fast. */\n acid: (o: SynthOptions = {}) => synth({ wave: \"saw\", volume: 0.22, attack: 0.002, decay: 0.1, sustain: 0.8, release: 0.05, filter: { cutoff: 260, amount: 3.6, resonance: 0.82, envelope: { decay: 0.16, sustain: 0 } }, drive: 10, ...o }),\n /** A warm lead: two square waves a little apart, softened by a filter. */\n lead: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 12, width: 0.3, volume: 0.15, attack: 0.004, decay: 0.15, sustain: 0.7, release: 0.12, filter: { cutoff: 2200, amount: 1.2, resonance: 0.2, envelope: { decay: 0.25, sustain: 0.4 } }, ...o }),\n /** The old consoles' lead: a bare square wave. */\n chip: (o: SynthOptions = {}) => synth({ wave: \"square\", volume: 0.14, attack: 0.002, decay: 0.05, sustain: 0.8, release: 0.03, ...o }),\n /** An electric piano: FM at ratio 1, bright on the strike and mellowing. */\n keys: (o: Parameters[0] = {}) => fmSynth({ ratio: 1, index: 2.6, brightness: 0.25, bright: 0.6, volume: 0.22, decay: 1.4, sustain: 0.3, release: 0.35, ...o }),\n /** A bell: FM at ratio 3.5, long and shimmering. */\n bell: (o: Parameters[0] = {}) => fmSynth({ ratio: 3.5, index: 5, brightness: 0.08, bright: 1.6, volume: 0.16, decay: 2.5, sustain: 0, release: 1.2, ...o }),\n /** A plucked string, a little bright. */\n pluck: (o: Parameters[0] = {}) => strings({ brightness: 0.6, decay: 1.4, ...o }),\n /**\n * A film trailer's \"braam\": five saws low and wide, the filter opening over half a second and closing slowly, driven\n * hard — the brass section's blast as a synth. Play it low (A1 … A2), with the low brass on the same notes.\n */\n braam: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 5, detune: 16, width: 0.6, volume: 0.22, attack: 0.04, decay: 1.2, sustain: 0.7, release: 0.9, filter: { cutoff: 160, amount: 3.4, resonance: 0.25, envelope: { attack: 0.45, decay: 1.6, sustain: 0.35, release: 0.8 } }, drive: 14, ...o }),\n /** A short synth pulse for sixteenth ostinatos: two squares, a quick filter blip. */\n pulse: (o: SynthOptions = {}) => synth({ wave: \"square\", voices: 2, detune: 9, width: 0.4, volume: 0.12, attack: 0.002, decay: 0.09, sustain: 0.25, release: 0.04, filter: { cutoff: 900, amount: 2.2, resonance: 0.3, envelope: { decay: 0.08, sustain: 0.1 } }, ...o }),\n /** A trance lead: seven saws a little apart, bright, a quick glide into each note — the melody on top of a drop. */\n trance: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 18, width: 0.5, volume: 0.13, attack: 0.004, decay: 0.3, sustain: 0.85, release: 0.15, glide: -0.6, glideTime: 0.03, filter: { cutoff: 2600, amount: 1.4, resonance: 0.15, envelope: { decay: 0.3, sustain: 0.55 } }, ...o }),\n /** A plucked synth for arpeggios: a saw whose filter snaps shut, a short tail. */\n arp: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 2, detune: 10, width: 0.4, volume: 0.13, attack: 0.002, decay: 0.16, sustain: 0.08, release: 0.12, filter: { cutoff: 500, amount: 3.2, resonance: 0.25, envelope: { decay: 0.14, sustain: 0 } }, ...o }),\n /** Supersaw chord stabs: wide, short, the filter open on the hit. */\n stab: (o: SynthOptions = {}) => synth({ wave: \"saw\", voices: 7, detune: 26, width: 0.8, volume: 0.11, attack: 0.003, decay: 0.22, sustain: 0.35, release: 0.15, filter: { cutoff: 1500, amount: 2.2, resonance: 0.12, envelope: { decay: 0.25, sustain: 0.3 } }, ...o }),\n /** A sub bass: a sine, soft at the start, under everything. */\n sub: (o: SynthOptions = {}) => synth({ wave: \"sine\", volume: 0.4, attack: 0.02, decay: 0.3, sustain: 0.9, release: 0.25, ...o }),\n};\n\n/**\n * An instrument of one-shots: a clip a key (\"C2\": the impact, \"D2\": a riser), each played whole whatever the note's\n * length and not moved in pitch, as loud as its velocity says — percussion and effects as parts of a performance\n * (`perform`), beside the instruments that play notes: `music.hits({ C2: music.impact(), D2: music.riser(4) })`.\n */\nexport function hits(clips: Readonly>, options: { readonly volume?: number } = {}): Instrument {\n const volume = options.volume ?? 1, byKey = new Map();\n for (const [name, clip] of Object.entries(clips)) byKey.set(noteNumber(name), clip);\n const clipOf = (name: string) => {\n const c = byKey.get(noteNumber(name));\n if (!c) throw new Error(`hits() has no clip for ${name}: it has ${Object.keys(clips).join(\", \")}.`);\n return c;\n };\n return Object.freeze({\n kind: \"notes\" as const,\n note: (name: string) => (volume === 1 ? clipOf(name) : clipOf(name).gain(volume)),\n strike: (name: string, _seconds: number, velocity: number) => clipOf(name).gain(volume * velocity),\n });\n}\n\n/**\n * A drum kit made from nothing, a letter a drum: k kick, s snare, c clap, h closed hat, o open hat, t tom, r rim, x crash. At\n * 44 100 Hz (`rate`), so the hats keep their top; `volume` 0 … 1 over the whole kit (1).\n */\nexport function drums(options: { readonly rate?: number; readonly volume?: number } = {}): Kit {\n const rate = options.rate ?? 44100, v = options.volume ?? 1;\n const metal = (seconds: number) => [263, 400, 421, 474, 587, 845].map((hz) => tone(hz * 2.6, seconds, { wave: \"square\", volume: 0.16, rate })).reduce((a, b) => a.mix(b));\n const kick = tone([[0, 170], [0.025, 85], [0.3, 46]], 0.42, { volume: 0.95, rate }).envelope([0, 1], [0.08, 0.85], [0.42, 0])\n .mix(noise(0.006, { volume: 0.35, rate }).filter(\"highpass\", 3000)).drive(5);\n const snare = tone([[0, 260], [0.04, 185]], 0.18, { wave: \"triangle\", volume: 0.6, rate }).envelope([0, 1], [0.15, 0])\n .mix(noise(0.28, { volume: 0.6, rate }).filter(\"highpass\", 1400).filter(\"peak\", 5000, { gain: 4 }).envelope([0, 1], [0.03, 0.55], [0.26, 0])).drive(4);\n const burst = (at: number) => ({ clip: noise(0.012, { volume: 0.6, rate }).envelope([0, 1], [0.012, 0.2]), at });\n const clap = mixdown([burst(0), burst(0.011), burst(0.023), { clip: noise(0.22, { volume: 0.5, rate }).envelope([0, 1], [0.22, 0]), at: 0.03 }], undefined, rate)\n .filter(\"bandpass\", 1300, { resonance: 0.35 }).gain(1.6);\n const hat = (seconds: number) => metal(seconds).mix(noise(seconds, { volume: 0.4, rate })).filter(\"highpass\", 7200).filter(\"highshelf\", 10000, { gain: 3 }).envelope([0, 1], [seconds * 0.25, 0.4], [seconds, 0]);\n const tom = tone([[0, 190], [0.2, 120]], 0.4, { volume: 0.8, rate }).envelope([0, 1], [0.4, 0]).mix(noise(0.01, { volume: 0.2, rate }).filter(\"bandpass\", 2500));\n const rim = tone(1700, 0.025, { wave: \"triangle\", volume: 0.5, rate }).mix(noise(0.012, { volume: 0.3, rate }).filter(\"highpass\", 4000)).envelope([0, 1], [0.025, 0]);\n const crash = metal(2).mix(noise(2, { volume: 0.5, rate })).filter(\"highpass\", 4500).filter(\"peak\", 7500, { gain: 3 }).envelope([0, 1], [0.08, 0.5], [2, 0]);\n return kit({ k: kick.gain(v), s: snare.gain(v), c: clap.gain(v), h: hat(0.07).gain(0.55 * v), o: hat(0.4).gain(0.5 * v), t: tom.gain(v), r: rim.gain(v), x: crash.gain(0.45 * v) });\n}\n\n/** A kit: a clip a letter, played by a pattern's letters (\"kh\" plays k and h together). */\nexport function kit(hits: Readonly>): Kit {\n for (const k of Object.keys(hits)) if (k.length !== 1 || k === \".\" || k === \"-\" || k === \"|\") throw new Error(`A kit's sounds are named by one letter each, not ${JSON.stringify(k)}.`);\n return Object.freeze({ kind: \"kit\" as const, hits: Object.freeze({ ...hits }) });\n}\n\n/* ── Patterns: what is written, and what writes it ── */\n\n/** A pattern: steps a word each, as one text or a text a bar. */\nexport type Pattern = string | readonly string[];\n\n/** A pattern's steps, the \"|\" left out. */\nconst wordsOf = (p: Pattern): string[] => (typeof p === \"string\" ? p : p.join(\" \")).split(/\\s+/).filter((w) => w !== \"\" && w !== \"|\");\n\n/** A step's sounds and how loud: \"C4+E4@0.6\" is C4 and E4 at 0.6; \"kh\" k and h at 1. */\nfunction velocityOf(word: string, step: number): { body: string; velocity: number } {\n const at = word.indexOf(\"@\");\n if (at < 0) return { body: word, velocity: 1 };\n const body = word.slice(0, at), v = Number(word.slice(at + 1));\n if (body === \"\" || body === \"-\" || body === \".\" || !(v >= 0 && v <= 4)) throw new Error(`Step ${step + 1}: \"@\" follows a note, a chord or a kit's letters, with how loud they play, 0 to 4 (1 as written): \"C4@0.6\", \"kh@1.3\" — not ${JSON.stringify(word)}.`);\n return { body, velocity: v };\n}\n\nconst NAMES = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n/** A note's name from its number: 60 is \"C4\". Sharps, not flats. */\nfunction nameOf(n: number): string {\n const octave = Math.floor(n / 12) - 1;\n if (octave < -1 || octave > 9) throw new Error(`A note goes from C-1 to B9: this one would be ${NAMES[((n % 12) + 12) % 12]}${octave}.`);\n return NAMES[((n % 12) + 12) % 12] + octave;\n}\n\n/** Each note of a step moved by a function of its number; holds, rests, kit letters and \"@\" kept. */\nconst eachNote = (p: Pattern, move: (n: number) => number): string[] => wordsOf(p).map((w) => w.replace(/[A-Ga-g][#b]?-?\\d/g, (name) => nameOf(move(noteNumber(name)))));\n\n/** A pattern `semitones` up (or down: a negative number): `transpose(tune, 12)` is the tune an octave up. A text a bar stays a text a bar. */\nexport function transpose(p: Pattern, semitones: number): Pattern {\n if (!Number.isInteger(semitones)) throw new Error(`transpose() moves by whole semitones, not ${semitones}.`);\n if (semitones === 0) return p;\n return typeof p === \"string\" ? eachNote(p, (n) => n + semitones).join(\" \") : p.map((bar) => eachNote(bar, (n) => n + semitones).join(\" \"));\n}\n\n/** A pattern with each step `by` steps long — eighths written as sixteenths with `stretch(p, 2)`. A text a bar stays a text a bar. */\nexport function stretch(p: Pattern, by: number): Pattern {\n if (!Number.isInteger(by) || by < 1) throw new Error(`stretch() makes each step a whole number of steps long, 1 or more — not ${by}.`);\n const one = (text: string) => wordsOf(text).map((w) => [w, ...Array.from({ length: by - 1 }, () => (w.startsWith(\".\") ? \".\" : \"-\"))].join(\" \")).join(\" \");\n return typeof p === \"string\" ? one(p) : p.map(one);\n}\n\n/** A pattern `n` times over, as one text. */\nexport function repeat(p: Pattern, n: number): string {\n if (!Number.isInteger(n) || n < 1) throw new Error(`repeat() plays a pattern a whole number of times, 1 or more — not ${n}.`);\n return Array.from({ length: n }, () => wordsOf(p).join(\" \")).join(\" \");\n}\n\n/** A kit's bar: the steps (from 0) each letter plays on, `steps` steps long — `beat({ k: [0, 8], s: [4, 12] })`. */\nexport function beat(hits: Readonly>, steps: number = 16): string {\n for (const [k, at] of Object.entries(hits)) for (const s of at) if (!Number.isInteger(s) || s < 0 || s >= steps) throw new Error(`beat(): ${k} on step ${s}, of steps 0 to ${steps - 1}.`);\n return Array.from({ length: steps }, (_, i) => Object.keys(hits).filter((k) => hits[k].includes(i)).join(\"\") || \".\").join(\" \");\n}\n\n/** A chord's notes above its root, by what follows the root's name. */\nconst QUALITIES: Readonly> = {\n \"\": [0, 4, 7], m: [0, 3, 7], dim: [0, 3, 6], aug: [0, 4, 8], \"+\": [0, 4, 8], sus2: [0, 2, 7], sus4: [0, 5, 7], sus: [0, 5, 7], \"5\": [0, 7],\n \"6\": [0, 4, 7, 9], m6: [0, 3, 7, 9], \"7\": [0, 4, 7, 10], maj7: [0, 4, 7, 11], M7: [0, 4, 7, 11], m7: [0, 3, 7, 10], dim7: [0, 3, 6, 9],\n m7b5: [0, 3, 6, 10], \"7sus4\": [0, 5, 7, 10], \"9\": [0, 4, 7, 10, 14], maj9: [0, 4, 7, 11, 14], m9: [0, 3, 7, 10, 14], add9: [0, 4, 7, 14], madd9: [0, 3, 7, 14],\n};\n\n/** A chord's notes as numbers, lowest first. */\nfunction chordNumbers(symbol: string, octave: number, inversion: number): number[] {\n const m = /^([A-G][#b]?)([^/]*)(?:\\/([A-G][#b]?))?$/.exec(symbol);\n const steps = m ? QUALITIES[m[2]] : undefined;\n if (!m || !steps) throw new Error(`A chord is a root and what kind — \"Am\", \"C\", \"G7\", \"Fmaj7\", \"Dm7\", \"Esus4\", \"Bdim\", \"C/E\" — not ${JSON.stringify(symbol)}. The kinds: ${Object.keys(QUALITIES).map((q) => `\"${q}\"`).join(\", \")}.`);\n if (!Number.isInteger(inversion) || inversion < 0 || inversion >= steps.length) throw new Error(`${symbol} has ${steps.length} notes: its inversion is 0 to ${steps.length - 1}, not ${inversion}.`);\n const root = noteNumber(m[1] + octave);\n const notes = steps.map((s) => root + s);\n for (let k = 0; k < inversion; k++) notes.push(notes.shift()! + 12);\n if (m[3]) {\n // Over another bass: that note, below the rest.\n let bass = noteNumber(m[3] + octave);\n while (bass >= notes[0]) bass -= 12;\n notes.unshift(bass);\n }\n return notes;\n}\n\n/**\n * A chord's notes, as a step plays them: `chord(\"Am\")` is \"A4+C5+E5\", its root in octave 4 (`octave`); `inversion`\n * moves its lowest notes up an octave, one each — `chord(\"E\", 3, 1)` is \"G#3+B3+E4\". \"C/E\" is C over an E below it.\n */\nexport function chord(symbol: string, octave: number = 4, inversion: number = 0): string {\n return chordNumbers(symbol, octave, inversion).map(nameOf).join(\"+\");\n}\n\n/** Each chord's notes as numbers, lowest first: the ones written, or the symbol's at `octave`. */\nconst notesOf = (c: string, octave: number): number[] => (/\\d/.test(c) ? c.split(\"+\").map(noteNumber).sort((a, b) => a - b) : chordNumbers(c, octave, 0));\n\n/**\n * A chord played as `template` says: its steps name the chord's notes by number, 1 the lowest — \"1 3 2 3\", \"1+2+3 - - -\"\n * — past the last, round again an octave up (in a three-note chord, 4 is 1 an octave up); each ^ after a number takes it\n * an octave higher, each _ an octave lower (\"1__\" the root two octaves down, for a bass). \"-\", \".\" and \"@\" as in any\n * pattern. `notes` is a chord's notes (\"A3+C4+E4\") or its name (\"Am\", with its root in octave `octave`).\n */\nexport function over(notes: string, template: Pattern, octave: number = 4): string {\n const n = notesOf(notes, octave);\n return wordsOf(template).map((w, s) => {\n const { body, velocity } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return w;\n const named = body.split(\"+\").map((d) => {\n const m = /^(\\d+)([\\^_]*)$/.exec(d);\n if (!m || Number(m[1]) < 1) throw new Error(`Step ${s + 1} of a chord's template: its notes are numbers from 1, the lowest, with ^ or _ for an octave up or down — \"1\", \"3^\", \"1__\" — not ${JSON.stringify(d)}.`);\n const k = Number(m[1]) - 1, up = Math.floor(k / n.length) + (m[2].match(/\\^/g)?.length ?? 0) - (m[2].match(/_/g)?.length ?? 0);\n return nameOf(n[k % n.length] + 12 * up);\n });\n return named.join(\"+\") + (velocity === 1 ? \"\" : `@${velocity}`);\n }).join(\" \");\n}\n\n/**\n * A progression played as `template` says, a template a chord: `chords(\"Am Am E Am Dm C E Am\", \"1_ 1 2 3\")` — as\n * `over` plays one chord. Each chord's root in octave `octave` (4); `lead: true` turns each chord after the first to\n * the inversion nearest the one before (its notes move least), as a player's hands do. A text a chord.\n */\nexport function chords(progression: string | readonly string[], template: Pattern, options: { readonly octave?: number; readonly lead?: boolean } = {}): string[] {\n const octave = options.octave ?? 4, list = wordsOf(progression);\n let before: number[] | null = null;\n return list.map((c) => {\n let n = notesOf(c, octave);\n if (options.lead && before && !/\\d/.test(c)) {\n // Each inversion, an octave either side: the one whose notes are nearest those before.\n const prev: number[] = before, mean = prev.reduce((a, b) => a + b, 0) / prev.length;\n let best = n, cost = Infinity;\n for (let inv = 0; inv < n.length; inv++) for (const shift of [-12, 0, 12]) {\n const cand = chordNumbers(c, octave, inv).map((x) => x + shift);\n const d = cand.length === prev.length ? cand.reduce((s, x, i) => s + Math.abs(x - prev[i]), 0) : Math.abs(cand.reduce((a, b) => a + b, 0) / cand.length - mean) * cand.length;\n if (d < cost) { cost = d; best = cand; }\n }\n n = best;\n }\n before = n;\n return over(n.map(nameOf).join(\"+\"), template);\n });\n}\n\n/** Seconds `n` bars last at `bpm` as a song plays it (its bar a whole number of frames): how long to make a riser. */\nexport function bars(bpm: number, n: number = 1, beats: number = 4): number {\n return n * Math.max(1, Math.round((60 / bpm) * beats / FRAME)) * FRAME;\n}\n\n/**\n * What makes a part breathe with the beat, as a mix does under a kick: down to `1 − depth` on each beat (`beat`\n * seconds apart, from the clip's start) and back over `release` of a beat — a part's fx, or a section's:\n * `{ fx: music.pump(music.bars(143) / 4) }`.\n */\nexport function pump(beat: number, depth: number = 0.45, release: number = 0.55): (clip: Clip) => Clip {\n if (!(beat > 0) || !(depth >= 0 && depth <= 1) || !(release > 0 && release <= 1)) throw new Error(\"pump() takes seconds a beat, how deep (0 … 1) and how long it takes to come back, as a part of a beat (0 … 1).\");\n return (c) => {\n const points: [number, number][] = [];\n for (let t = 0; t < c.seconds; t += beat) points.push([t, 1 - depth], [Math.min(c.seconds, t + release * beat), 1], [Math.min(c.seconds, t + beat - 0.004), 1]);\n points.push([c.seconds, 1]);\n return c.envelope(...points);\n };\n}\n\n/* ── Sounds between sections ── */\n\n/** Noise rising for `seconds` through a filter opening, loudest at the end: what leads into a drop. */\nexport function riser(seconds: number, options: { readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.5, s = seconds;\n const swept = noise(s, { volume: v, rate }).filter(\"bandpass\", [[0, 350], [s * 0.6, 1800], [s, 9000]], { resonance: 0.55 });\n const lift = tone([[0, 220], [s, 880]], s, { wave: \"saw\", voices: 3, detune: 25, width: 0.8, volume: v * 0.25, rate }).filter(\"lowpass\", [[0, 500], [s, 6000]]);\n return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01);\n}\n\n/**\n * White noise through a filter sweeping over `seconds`: up (as left out) from a low rumble to bright hiss, growing\n * louder, as a drop is built to; `down: true` the other way, falling and fading after it.\n */\nexport function sweep(seconds: number, options: { readonly down?: boolean; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.4, s = seconds, down = options.down === true;\n const points: [number, number][] = down ? [[0, 12000], [s, 150]] : [[0, 150], [s * 0.7, 2500], [s, 14000]];\n const shape: [number, number][] = down ? [[0, 1], [s, 0]] : [[0, 0], [s * 0.6, 0.35], [s, 1]];\n return noise(s, { volume: v, rate }).filter(\"lowpass\", points, { resonance: 0.3 }).envelope(...shape).fade(0.005, 0.01);\n}\n\n/** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */\nexport function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip {\n const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5;\n return tone([[0, 90], [0.4, 38], [s, 30]], s, { volume: v, rate }).envelope([0, 1], [0.15, 0.7], [s, 0])\n .mix(noise(s, { volume: v * 0.5, rate }).filter(\"lowpass\", [[0, 6000], [s, 300]]).envelope([0, 1], [0.05, 0.4], [s, 0])).drive(3);\n}\n\n/** How a track or a part is heard. */\nexport interface PartOptions {\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan?: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume?: number;\n /** What it goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb?: number;\n}\n\n/** What an instrument plays, step by step. */\nexport interface Track {\n readonly instrument: Instrument | Kit;\n readonly steps: readonly string[];\n /** Where it is heard, −1 left to 1 right; 0, the middle, when left out. */\n readonly pan: number;\n /** How loud, 1 as the instrument plays. */\n readonly volume: number;\n /** What the track goes through: its whole part in `render`, each note on its own in `play`. */\n readonly fx?: (clip: Clip) => Clip;\n /** How much of it goes to the song's reverb in `render`, 0 … 1 (0). */\n readonly reverb: number;\n}\n\n/** A part's options checked, and its defaults filled in. */\nfunction heard(options: PartOptions, what: string): { pan: number; volume: number; reverb: number; fx?: (clip: Clip) => Clip } {\n const pan = options.pan ?? 0, volume = options.volume ?? 1, reverb = options.reverb ?? 0;\n if (!(pan >= -1 && pan <= 1)) throw new Error(`A ${what}'s pan is −1 (left) to 1 (right), not ${pan}.`);\n if (!(volume >= 0)) throw new Error(`A ${what}'s volume is 0 or more, not ${volume}.`);\n if (!(reverb >= 0 && reverb <= 1)) throw new Error(`A ${what}'s reverb is 0 to 1, not ${reverb}.`);\n return { pan, volume, reverb, ...(options.fx ? { fx: options.fx } : {}) };\n}\n\n/**\n * A pattern for an instrument: steps a word each — a note or notes joined by +, \"-\" to hold, \".\" to rest, \"|\" for the\n * eye; \"@\" after a step's notes says how loud, \"C4@0.6\". `pan`: where it is heard, −1 left to 1 right (a panned track's\n * notes have two channels); `volume`: 1 as the instrument plays; `fx`: what the track goes through —\n * `(c) => c.delay(0.21).chorus()` — its whole part when the song is rendered (as a mixer's insert), each note on its own\n * when it is played note by note; `reverb`: how much goes to the song's reverb when it is rendered, 0 … 1.\n */\nexport function track(instrument: Instrument | Kit, pattern: Pattern, options: PartOptions = {}): Track {\n return Object.freeze({ instrument, steps: Object.freeze(wordsOf(pattern)), ...heard(options, \"track\") });\n}\n\n/** An instrument and how it is heard, which a song's sections give its notes: `arrange`. */\nexport interface Part extends Omit { readonly kind: \"part\" }\n\n/** An instrument as a part of a song made of sections (`arrange`), heard as `track` says. */\nexport function part(instrument: Instrument | Kit, options: PartOptions = {}): Part {\n return Object.freeze({ kind: \"part\" as const, instrument, ...heard(options, \"part\") });\n}\n\n/** How long a section lasts, as its effects need it for their points: seconds, its bars, and seconds a bar. */\nexport interface SectionTime { readonly seconds: number; readonly bars: number; readonly bar: number }\n\n/** What a section is and does, besides its notes. */\nexport interface SectionOptions {\n /** What `song.sections` calls it. */\n readonly name?: string;\n /**\n * What a part goes through in this section only, given how long the section is — a filter opening over a build:\n * `{ pad: (c, t) => c.filter(\"lowpass\", [[0, 400], [t.seconds, 8000]]) }`. Its notes from this section, tails and\n * all, before the part's own `fx`. Mixed by `render` only: a song with one is not played note by note.\n */\n readonly fx?: Readonly Clip>>;\n /** How loud a part is in this section only, 1 as it is. */\n readonly volume?: Readonly>;\n}\n\n/** Bars of a song: what each part plays in them. */\nexport interface Section {\n readonly kind: \"section\";\n readonly name: string;\n readonly bars: number;\n readonly parts: Readonly>;\n readonly fx: Readonly Clip>>;\n readonly volume: Readonly>;\n /** This section with some parts written again — null: that part rests — and these options over its own. */\n with(parts: Readonly>, options?: SectionOptions): Section;\n}\n\n/**\n * `bars` bars of a song (`arrange`), and what each part plays in them, by the part's name: `{ lead: tune, drums: beat }`.\n * A pattern shorter than the section plays again until it is filled, so a bar of drums fills eight; a part not named\n * rests. `options`: its name, a part's effects or volume for this section only.\n */\nexport function section(bars: number, parts: Readonly>, options: SectionOptions = {}): Section {\n if (!Number.isInteger(bars) || bars < 1) throw new Error(`A section is a whole number of bars, 1 or more — not ${bars}.`);\n for (const [k, v] of Object.entries(options.volume ?? {})) if (!(v >= 0)) throw new Error(`A section's volume for ${k} is 0 or more, not ${v}.`);\n const made: Section = Object.freeze({\n kind: \"section\" as const, name: options.name ?? \"\", bars,\n parts: Object.freeze({ ...parts }), fx: Object.freeze({ ...(options.fx ?? {}) }), volume: Object.freeze({ ...(options.volume ?? {}) }),\n with(changes: Readonly>, more: SectionOptions = {}): Section {\n const next: Record = { ...parts };\n for (const [k, p] of Object.entries(changes)) { if (p === null) delete next[k]; else next[k] = p; }\n return section(bars, next, { name: more.name ?? made.name, fx: { ...made.fx, ...(more.fx ?? {}) }, volume: { ...made.volume, ...(more.volume ?? {}) } });\n },\n });\n return made;\n}\n\n/** A song's tempo and grid. */\nexport interface SongOptions {\n readonly bpm: number;\n /** Steps a beat (4: sixteenths). */\n readonly steps?: number;\n /** Beats a bar (4). */\n readonly beats?: number;\n /** How late every second step starts, as a part of a step: 0 straight (as it is when left out), 1/3 a triplet's lilt. */\n readonly swing?: number;\n}\n\n/** Where a song's section is: from bar `bar` (0 the first) for `bars`, from frame `frame`. */\nexport interface SongSection { readonly name: string; readonly bar: number; readonly bars: number; readonly frame: number }\n\n/** Steps of a track that belong to one section, and what that section does to them. */\ninterface Piece { readonly from: number; readonly to: number; readonly volume: number; readonly fx?: (clip: Clip, time: SectionTime) => Clip; readonly time: SectionTime }\nconst piecesOf = new WeakMap();\n/** A song of sections' parts, by name, and the track each became: what `stems` cuts. */\nconst partsOf = new WeakMap();\n\n/**\n * A song made of sections, one after another: `parts` names each instrument and how it is heard; each section says\n * what the parts play in it. A section can be written once and played again — `arrange(o, parts, intro, verse, verse,\n * chorus)` — or played again changed: `verse.with({ lead: transpose(tune, 12) })`.\n */\nexport function arrange(options: SongOptions, parts: Readonly>, ...sections: readonly Section[]): Song {\n const { perBar, barFrames } = grid(options);\n if (sections.length === 0) throw new Error(\"arrange() takes the song's sections, one at least.\");\n const names = Object.keys(parts);\n for (const s of sections) for (const k of [...Object.keys(s.parts), ...Object.keys(s.fx), ...Object.keys(s.volume)]) {\n if (!(k in parts)) throw new Error(`A section${s.name ? ` (${s.name})` : \"\"} names ${JSON.stringify(k)}, which is no part of the song: its parts are ${names.join(\", \")}.`);\n }\n const tracks = names.map((k) => {\n const steps: string[] = [], pieces: Piece[] = [];\n for (const s of sections) {\n const length = s.bars * perBar, from = steps.length, p = s.parts[k];\n if (p === undefined) for (let i = 0; i < length; i++) steps.push(\".\");\n else {\n const words = wordsOf(p);\n if (words.length === 0 || length % words.length !== 0) throw new Error(`${k}${s.name ? ` in ${s.name}` : \"\"}: a pattern of ${words.length} steps does not fill ${s.bars} bar${s.bars === 1 ? \"\" : \"s\"} of ${perBar} steps evenly.`);\n for (let i = 0; i < length; i++) steps.push(words[i % words.length]);\n }\n const fx = k in s.fx ? s.fx[k] : undefined, volume = s.volume[k] ?? 1;\n if (fx || volume !== 1) pieces.push({ from, to: from + length, volume, ...(fx ? { fx } : {}), time: { seconds: s.bars * barFrames * FRAME, bars: s.bars, bar: barFrames * FRAME } });\n }\n const t = track(parts[k].instrument, steps, parts[k]);\n if (pieces.length) piecesOf.set(t, pieces);\n return t;\n });\n let bar = 0;\n const placedSections = sections.map((s) => { const at = { name: s.name, bar, bars: s.bars, frame: bar * barFrames }; bar += s.bars; return Object.freeze(at); });\n const made = compose(options, tracks, placedSections);\n partsOf.set(made, names.map((k, i) => ({ name: k, track: tracks[i] })));\n return made;\n}\n\n/** A clip as a track plays it note by note: through its fx, at its volume and its pan, made once a clip a track. */\nfunction placed(t: Track, made: Map, c: Clip): Clip {\n if (t.pan === 0 && t.volume === 1 && !t.fx) return c;\n let p = made.get(c);\n if (!p) {\n p = t.fx ? t.fx(c) : c;\n if (t.volume !== 1) p = p.gain(t.volume);\n if (t.pan !== 0) p = p.pan(t.pan);\n made.set(c, p);\n }\n return p;\n}\n\n/**\n * A note of a song as it sounds, at `rate` (the instrument's own when left out): a kit's letter or an instrument's note,\n * struck at its velocity where the instrument knows how (`strike`), else made louder or quieter by it.\n */\nfunction sounded(t: Track, n: Score, rate?: number): Clip {\n if (n.hit) return n.velocity === 1 ? n.hit : n.hit.gain(n.velocity);\n const inst = t.instrument as Instrument;\n if (inst.strike) return inst.strike(n.name!, n.seconds!, n.velocity, rate);\n const c = inst.note(n.name!, n.seconds!, rate);\n return n.velocity === 1 ? c : c.gain(n.velocity);\n}\n\n/** What a song's notes are, kept for render, which makes them again at its own rate; `piece`, the section whose effects it goes through. */\ninterface Score { readonly at: number; readonly track: Track; readonly made: Map; readonly velocity: number; readonly piece?: Piece; readonly name?: string; readonly seconds?: number; readonly hit?: Clip }\nconst scores = new WeakMap();\n\n/** A song, when the script is built: the tables `play` reads, and what it takes. */\nexport interface Song {\n /**\n * Frames a step lasts: a bar is a whole number of frames, a step need not be (2.5 for sixteenths at 143 beats a\n * minute). Played note by note, a note starts on the frame nearest its time — within the 21 ms the game's own\n * mixer starts a sound in anyway; rendered, exactly on it.\n */\n readonly stepFrames: number;\n /** Frames a bar lasts, a whole number. */\n readonly barFrames: number;\n /** Beats a bar. */\n readonly beats: number;\n /** The tempo it plays at: the nearest to the one asked for whose bar is a whole number of frames. */\n readonly bpm: number;\n /** Steps, the longest track's. */\n readonly steps: number;\n /** Its sections, made by `arrange`, in the order they play (none for a song of tracks). */\n readonly sections: readonly SongSection[];\n /** Frames it lasts, its last note's release included. */\n readonly frames: number;\n readonly seconds: number;\n /** Each clip the song plays, once. */\n readonly clips: readonly Clip[];\n /** Each note in the order they start: the frame it starts on, from 0, and which of `clips` it is. */\n readonly at: readonly number[];\n readonly which: readonly number[];\n /** The most notes sounding at once: `play` refuses a song of more than 32 (`render` has no limit). */\n readonly voices: number;\n}\n\n/** A song's grid: steps a bar, and frames a bar and a step. */\nfunction grid(options: SongOptions): { perBar: number; barFrames: number; stepFrames: number } {\n const perBeat = options.steps ?? 4, beats = options.beats ?? 4, swing = options.swing ?? 0;\n if (!(options.bpm > 0) || !(perBeat > 0) || !(beats > 0)) throw new Error(\"A song takes a tempo, { bpm: 120 }, steps a beat (4 by default) and beats a bar (4).\");\n if (!(swing >= 0 && swing < 1)) throw new Error(`A song's swing is 0 (straight) to under 1 (a step late), not ${swing}.`);\n const barFrames = Math.max(1, Math.round((60 / options.bpm) * beats / FRAME));\n return { perBar: perBeat * beats, barFrames, stepFrames: barFrames / (beats * perBeat) };\n}\n\n/**\n * Tracks played together from their first step: `bpm` beats a minute, `steps` steps a beat (4 by default), `swing`\n * every second step late. Played note by note (`play`), a song is refused when more than 32 notes would sound at once;\n * rendered, it has no limit. A song of sections: `arrange`.\n */\nexport function song(options: SongOptions, ...tracks: readonly Track[]): Song {\n return compose(options, tracks, []);\n}\n\nfunction compose(options: SongOptions, tracks: readonly Track[], sections: readonly SongSection[]): Song {\n const { barFrames, stepFrames } = grid(options), beats = options.beats ?? 4, swing = options.swing ?? 0;\n const stepSeconds = stepFrames * FRAME;\n // Where step s starts, in frames: every second step `swing` of a step late.\n const time = (s: number) => (s + (s % 2 === 1 ? swing : 0)) * stepFrames;\n const score: Score[] = [];\n let steps = 0, effects = false;\n for (const t of tracks) {\n const ws = t.steps, made = new Map(), pieces = piecesOf.get(t) ?? [];\n if (pieces.some((p) => p.fx)) effects = true;\n steps = Math.max(steps, ws.length);\n let k = 0;\n ws.forEach((w, s) => {\n while (k < pieces.length && pieces[k].to <= s) k++;\n const piece = k < pieces.length && pieces[k].from <= s ? pieces[k] : undefined;\n const { body, velocity: v } = velocityOf(w, s);\n if (body === \"-\" || body === \".\") return;\n const velocity = v * (piece?.volume ?? 1), into = piece ? { piece } : {};\n if (t.instrument.kind === \"kit\") {\n for (const letter of body) {\n const hit = t.instrument.hits[letter];\n if (!hit) throw new Error(`Step ${s + 1}: the kit has no ${JSON.stringify(letter)} (it has ${Object.keys(t.instrument.hits).join(\", \")}).`);\n score.push({ at: time(s), track: t, made, velocity, ...into, hit });\n }\n return;\n }\n // A note lasts its step and every \"-\" after it.\n let length = 1;\n while (s + length < ws.length && ws[s + length] === \"-\") length++;\n const seconds = swing === 0 ? length * stepSeconds : (time(s + length) - time(s)) * FRAME;\n for (const name of body.split(\"+\")) {\n noteNumber(name);\n score.push({ at: time(s), track: t, made, velocity, ...into, name, seconds });\n }\n });\n }\n score.sort((a, b) => a.at - b.at);\n // The tables `play` reads, made when they are first read: a song only rendered never makes its notes for the game.\n let table: { clips: readonly Clip[]; at: readonly number[]; which: readonly number[]; voices: number; peakStep: number; frames: number } | null = null;\n const tables = () => {\n if (table) return table;\n const notes = score.map((n) => ({ at: Math.round(n.at), clip: placed(n.track, n.made, sounded(n.track, n)) }));\n // How many sound at once: at each note's start, those started before it and not yet over.\n let voices = 0, peakStep = 0;\n notes.forEach((n, k) => {\n let sounding = 0;\n for (let j = 0; j <= k; j++) if (notes[j].at + notes[j].clip.seconds / FRAME > n.at) sounding++;\n if (sounding > voices) { voices = sounding; peakStep = Math.round(n.at / stepFrames) + 1; }\n });\n const clips: Clip[] = [];\n const which = notes.map((n) => { let k = clips.indexOf(n.clip); if (k < 0) { clips.push(n.clip); k = clips.length - 1; } return k; });\n const frames = Math.max(Math.round(steps * stepFrames), ...notes.map((n) => n.at + Math.ceil(n.clip.seconds / FRAME)));\n table = { clips: Object.freeze(clips), at: Object.freeze(notes.map((n) => n.at)), which: Object.freeze(which), voices, peakStep, frames };\n return table;\n };\n // What the game plays note by note: refused, when it is read, if more than 32 would sound at once (render has no limit).\n const playable = () => {\n if (effects) throw new Error(\"A section of this song puts a part through effects of its own, which only music.render mixes: render the song, or give the part those effects for the whole song.\");\n const t = tables();\n if (t.voices > VOICES) throw new Error(`At step ${t.peakStep}, ${t.voices} notes would sound at once; the game plays ${VOICES} note by note. Shorten notes or thin the chords — or music.render the song, one sound however many it mixes.`);\n return t;\n };\n const made: Song = Object.freeze({\n stepFrames, barFrames, beats, bpm: (60 * beats) / (barFrames * FRAME), steps, sections: Object.freeze([...sections]),\n get frames() { return tables().frames; },\n get seconds() { return tables().frames * FRAME; },\n get clips() { return playable().clips; },\n get at() { return playable().at; },\n get which() { return playable().which; },\n get voices() { return tables().voices; },\n });\n scores.set(made, score);\n return made;\n}\n\n/** The General MIDI drums, by number, as `drums()` has them: kicks k, snares s, the clap c, hats h and o, toms t, the rim r, crashes x. */\nconst GM_DRUMS: Readonly> = {\n 35: \"k\", 36: \"k\", 37: \"r\", 38: \"s\", 40: \"s\", 39: \"c\", 42: \"h\", 44: \"h\", 51: \"h\", 53: \"h\", 59: \"h\", 46: \"o\",\n 41: \"t\", 43: \"t\", 45: \"t\", 47: \"t\", 48: \"t\", 50: \"t\", 49: \"x\", 52: \"x\", 55: \"x\", 57: \"x\",\n};\n\n/** How imported notes are made a song: its grid, and which kit letter a drum's number plays. */\nexport interface MidiOptions extends Omit {\n /** Beats a minute: the file's own when left out. */\n readonly bpm?: number;\n /** A drum's MIDI number to a kit's letter, over General MIDI's (36 \"k\", 38 \"s\", 42 \"h\", 46 \"o\", 49 \"x\", …). */\n readonly drums?: Readonly>;\n}\n\n/**\n * A song of imported notes (`import tune from \"./tune.notes\"`): each track `parts` names — by its name, or its place\n * in `tune.tracks` from 0 — played by an instrument, a kit (the drums by their General MIDI numbers) or a `part`;\n * the tracks not named are left out. Each note starts on the step nearest its time and lasts the steps nearest its\n * length (`steps` a beat, 4: sixteenths); how hard it was struck is how loud it plays, 100 as written. A track whose\n * notes overlap becomes several, so the song can hold them. At the file's first tempo unless `bpm` says.\n */\nexport function midi(notes: Notes, parts: Readonly>, options: MidiOptions = {}): Song {\n const perBeat = options.steps ?? 4, map = { ...GM_DRUMS, ...(options.drums ?? {}) };\n const names = notes.tracks.map((t) => t.name);\n const tracks: Track[] = [];\n for (const [key, given] of Object.entries(parts)) {\n const index = names.indexOf(key) >= 0 ? names.indexOf(key) : /^\\d+$/.test(key) ? Number(key) : -1;\n const source = notes.tracks[index];\n if (!source) throw new Error(`The notes have no track ${JSON.stringify(key)}: their tracks are ${names.map((n) => JSON.stringify(n)).join(\", \")} (or 0 to ${names.length - 1}).`);\n const instrument = given.kind === \"part\" ? given.instrument : given, how = given.kind === \"part\" ? given : {};\n const kit = instrument.kind === \"kit\" ? instrument : null;\n // Voices: steps that each hold one chord at a time; a note joins a chord struck with it, or the first voice free.\n type Word = { sounds: string[]; velocity: number; length: number };\n const voices: { words: Map; end: number; last: number }[] = [];\n const placed = source.notes.map((n) => {\n const from = Math.round(n.at * perBeat);\n return { from, length: kit ? 1 : Math.max(1, Math.round((n.at + n.beats) * perBeat) - from), sound: kit ? map[n.pitch] : nameOf(n.pitch), velocity: Math.max(0.05, Math.round((n.velocity / 100) * 20) / 20) };\n }).filter((n) => n.sound !== undefined && (!kit || n.sound in kit.hits)).sort((a, b) => a.from - b.from || b.length - a.length);\n for (const n of placed) {\n let voice = voices.find((v) => { const w = v.words.get(v.last); return v.last === n.from && w !== undefined && w.length === n.length && w.velocity === n.velocity; });\n if (voice) { const w = voice.words.get(n.from)!; if (!w.sounds.includes(n.sound)) w.sounds.push(n.sound); continue; }\n voice = voices.find((v) => v.end <= n.from);\n if (!voice) { voice = { words: new Map(), end: 0, last: -1 }; voices.push(voice); }\n voice.words.set(n.from, { sounds: [n.sound], velocity: n.velocity, length: n.length });\n voice.end = n.from + n.length;\n voice.last = n.from;\n }\n for (const v of voices) {\n const steps: string[] = Array.from({ length: v.end }, () => \".\");\n for (const [at, w] of v.words) {\n steps[at] = (kit ? w.sounds.join(\"\") : w.sounds.join(\"+\")) + (w.velocity === 1 ? \"\" : `@${w.velocity}`);\n if (!kit) for (let k = 1; k < w.length; k++) steps[at + k] = \"-\";\n }\n tracks.push(track(instrument, steps, how));\n }\n }\n return compose({ ...options, bpm: options.bpm ?? notes.bpm, beats: options.beats ?? notes.beats }, tracks, []);\n}\n\n/* ── A performance: notes at their own times, not on a grid ── */\n\n/** A note of a performance, as it was played: what a picture that follows the music needs. */\nexport interface PerformedNote {\n /** Seconds from the start it is struck, and let go (the key up; the pedal may hold it on). */\n readonly at: number;\n readonly end: number;\n /** Its key (60 is C4), and its name (\"C4\", sharps). */\n readonly pitch: number;\n readonly note: string;\n /** How hard, 1 … 127. */\n readonly velocity: number;\n /** The part that plays it (\"right\", \"left\": what `perform` named it), and its place in its chord, 0 the lowest. */\n readonly part: string;\n readonly voice: number;\n /** The bar it is in (1 the first whole bar, 0 a pickup before it), and where in the bar, in beats of the meter from 0. */\n readonly bar: number;\n readonly beat: number;\n /** The game's frame it is struck on (42 ms on Fastest), from the start. */\n readonly frame: number;\n}\n\n/** Music played, not on a grid: made by `perform`, mixed by `render`. */\nexport interface Performance {\n readonly kind: \"performance\";\n /** Every note in the order they are struck. */\n readonly notes: readonly PerformedNote[];\n /** The sustain pedal: [down, up] in seconds, each part's that writes it. */\n readonly pedal: readonly (readonly [number, number])[];\n /** Seconds each bar begins: [0] the pickup's start (0), [1] bar 1's. */\n readonly bars: readonly number[];\n /** The parts, in the order given. */\n readonly parts: readonly string[];\n /** Seconds from the first note to the last let go (the pedal's and the notes' rings come after). */\n readonly seconds: number;\n}\n\n/** A part of a performance: who plays it, what, and how it is heard (as a track is, `PartOptions`). */\nexport interface PerformPart extends PartOptions {\n readonly instrument: Instrument;\n /** What it plays, written as `perform` reads it: one text, or a text a bar. */\n readonly notes: Pattern;\n /** Seconds it plays ahead of the beat (a melody a little before its accompaniment, as pianists play): 0.01. A negative number: behind. */\n readonly lead?: number;\n /** Its velocities times this (1). */\n readonly velocity?: number;\n}\n\n/** A performance's meter, tempo and feel. */\nexport interface PerformOptions {\n /** The bar: \"3/8\", \"4/4\" (as left out), \"6/8\". The tempo counts its beats: 3/8 counts eighths. */\n readonly meter?: string;\n /** Beats a minute: what the meter counts. */\n readonly bpm: number;\n /** How long a pickup before bar 1 lasts: \"1/8\", \"3/16\". */\n readonly pickup?: string;\n /**\n * The tempo through the piece: [bar, bpm] points, the bar from 1 (8.5 halfway through bar 8; 0.5 inside the pickup);\n * between two points it changes evenly, before the first and after the last it stays. Two points at one bar: a step.\n * A phrase that slows into its end: [[1, 132], [7, 132], [8.5, 108], [9, 132]].\n */\n readonly tempo?: readonly (readonly [number, number])[];\n /** Pauses: [bar, seconds] — a breath before a phrase, a fermata. Everything from that point on comes that much later. */\n readonly holds?: readonly (readonly [number, number])[];\n /** A player's unevenness, the same on every build: `time` seconds either way (about), `velocity` (about), `seed`. */\n readonly humanize?: { readonly time?: number; readonly velocity?: number; readonly seed?: number };\n}\n\n/** Ticks a whole note: room for halves, thirds, fifths down to a sixty-fourth. */\nconst WHOLE = 1920;\nconst DYNAMICS: Readonly> = { ppp: 20, pp: 32, p: 46, mp: 60, mf: 74, f: 90, ff: 106, fff: 120 };\n\n/** A length as written after \"/\": \"8\" an eighth, \"8.\" dotted, \"16t\" a sixteenth of a triplet. In ticks. */\nfunction lengthOf(text: string, where: string): number {\n const m = /^(1|2|4|8|16|32|64)(t?)(\\.{0,2})$/.exec(text);\n if (!m) throw new Error(`${where}: a length is 1, 2, 4, 8, 16, 32 or 64, then t for a triplet's, then a dot or two — \"8\", \"8.\", \"16t\" — not ${JSON.stringify(text)}.`);\n let t = WHOLE / Number(m[1]);\n if (m[2]) t = (t * 2) / 3;\n if (m[3].length === 1) t *= 1.5;\n if (m[3].length === 2) t *= 1.75;\n return t;\n}\n\n/** One part's text, read: its notes in ticks, its pedal in ticks, its dynamics. */\ninterface ReadNote { readonly tick: number; readonly length: number; readonly pitch: number; readonly velocity: number; readonly voice: number; readonly staccato: boolean }\nfunction readPart(name: string, text: Pattern, barTicks: number, pickup: number, meter: string): { notes: ReadNote[]; pedal: [number, number | null][] } {\n const words = typeof text === \"string\" ? wordsOf2(text) : text.flatMap((bar, k) => (k === 0 ? wordsOf2(bar) : [\"|\", ...wordsOf2(bar)]));\n const notes: { tick: number; length: number; pitch: number; at: number | null; rel: number; accent: boolean; voice: number; staccato: boolean; tie: boolean }[] = [];\n const marks: { tick: number; level: number }[] = [], hairpins: number[] = [];\n const pedal: [number, number | null][] = [];\n let tick = 0, length = WHOLE / 4, level = DYNAMICS.mf, bar = pickup > 0 ? 0 : 1, line = 0;\n const open = new Map();\n const where = () => `${name}, ${bar === 0 ? \"the pickup\" : `bar ${bar}`}`;\n marks.push({ tick: 0, level });\n for (const w of words) {\n if (w === \"|\") {\n // The first bar line ends the pickup, when there is one; every other, a bar.\n const first = bar === 0, want = first ? pickup : barTicks, sixteenth = WHOLE / 16;\n if (tick - line !== want) throw new Error(`${where()} is ${(tick - line) / sixteenth} sixteenths long; ${first ? \"the pickup is\" : `a bar of ${meter} is`} ${want / sixteenth}.`);\n line = tick;\n bar = bar + 1;\n continue;\n }\n if (w in DYNAMICS) { level = DYNAMICS[w]; marks.push({ tick, level }); continue; }\n if (w === \"<\" || w === \">\") { hairpins.push(tick); continue; }\n if (w === \"ped\") {\n const last = pedal[pedal.length - 1];\n if (last && last[1] === null) last[1] = tick;\n pedal.push([tick, null]);\n continue;\n }\n if (w === \"*\") {\n const last = pedal[pedal.length - 1];\n if (!last || last[1] !== null) throw new Error(`${where()}: \"*\" lifts the pedal, which is not down (\"ped\" puts it down).`);\n last[1] = tick;\n continue;\n }\n const m = /^(r|[A-Ga-g][#b]?-?\\d(?:\\+[A-Ga-g][#b]?-?\\d)*)(?:\\/([0-9]+t?\\.{0,2}))?(?:@([+-]?\\d+))?(['!~]*)$/.exec(w);\n if (!m) throw new Error(`${where()}: ${JSON.stringify(w)} is no note — a note is a name and octave, \"E5\", chords joined by +, \"A3+C4\"; then /8 for its length (as the last when left out), @90 or @+10 for how hard, ' for staccato, ! for an accent, ~ to tie it to the next; \"r\" a rest; \"pp\" … \"ff\" the dynamics, \"<\" and \">\" towards the next; \"ped\" and \"*\" the pedal; \"|\" a bar line.`);\n if (m[2] !== undefined) length = lengthOf(m[2], where());\n if (m[1] !== \"r\") {\n const pitches = m[1].split(\"+\").map(noteNumber).sort((a, b) => a - b);\n const flags = m[4] ?? \"\";\n pitches.forEach((pitch, voice) => {\n // A note tied from the one before is not struck again: the one before lasts longer.\n const tied = open.get(pitch);\n if (tied !== undefined && notes[tied].tick + notes[tied].length === tick) {\n notes[tied].length += length;\n if (!flags.includes(\"~\")) open.delete(pitch);\n return;\n }\n const rel = m[3] === undefined ? 0 : Number(m[3]), absolute = m[3] !== undefined && !/^[+-]/.test(m[3]);\n notes.push({ tick, length, pitch, at: absolute ? rel : null, rel: absolute ? 0 : rel, accent: flags.includes(\"!\"), voice, staccato: flags.includes(\"'\"), tie: flags.includes(\"~\") });\n if (flags.includes(\"~\")) open.set(pitch, notes.length - 1);\n });\n }\n tick += length;\n }\n // The level at a tick: the last mark's, or on its way from it to the next mark where a hairpin starts between them.\n const levelAt = (t: number) => {\n let k = 0;\n while (k + 1 < marks.length && marks[k + 1].tick <= t) k++;\n const from = marks[k], to = marks[k + 1];\n const pin = hairpins.find((h) => h >= from.tick && (!to || h < to.tick));\n if (!to || pin === undefined || t < pin) return from.level;\n return from.level + ((to.level - from.level) * (t - pin)) / Math.max(1, to.tick - pin);\n };\n return {\n notes: notes.map((n) => {\n const v = n.at !== null ? n.at : levelAt(n.tick) + n.rel + (n.accent ? 12 : 0);\n return { tick: n.tick, length: n.length, pitch: n.pitch, velocity: Math.max(1, Math.min(127, v)), voice: n.voice, staccato: n.staccato };\n }),\n pedal,\n };\n}\n/** A text's words, \"|\" kept (a bar line is checked in a performance). */\nconst wordsOf2 = (t: string): string[] => t.split(/\\s+/).filter((w) => w !== \"\");\n\n/**\n * Music played as a person plays it, not on a grid: each part's notes written as a score has them — their own lengths,\n * dynamics, the pedal — and played at a tempo that moves (`tempo`, `holds`), each note at its own time and strength.\n *\n * const take = music.perform({ meter: \"3/8\", bpm: 132, pickup: \"1/8\", tempo: [[1, 132], [7, 132], [8, 112]] }, {\n * right: { instrument: piano, notes: [\"pp E5/16 D#5\", \"E5 D#5 E5 B4 D5 C5\", \"A4/8 r/16 C4 E4 A4\"] },\n * left: { instrument: piano, notes: [\"r/8\", \"r/4.\", \"ped A2/16 E3 A3 r/16 r/8 *\"] },\n * });\n * playWav(music.render(take, { reverb: { decay: 0.85 } }));\n *\n * A note is its name and octave (\"E5\", \"F#4\", \"Bb2\"; a chord \"A3+C4+E4\"), then its length after \"/\" — 1, 2, 4, 8, 16,\n * 32 or 64, \"t\" for a triplet's, a dot or two (\"8.\" a dotted eighth) — the last one's when left out; \"@90\" how hard\n * (1 … 127), \"@+10\" or \"@-10\" against the dynamic; then ' to play it short, ! to accent it, ~ to tie it to the same note\n * next. \"r\" is a rest. \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\" (and ppp, fff) set how hard what follows is struck, \"<\" and \">\"\n * move there evenly from where they stand to the next mark. \"ped\" puts the sustain pedal down (again, while it is down:\n * lifts it and puts it down at once), \"*\" lifts it: an instrument holds every note let go while it is down, and a\n * performance's parts on the same instrument share it. \"|\" is a bar line, checked: a part whose bar is too long or\n * short is refused, by its bar. A text a bar puts the bar lines between the texts.\n *\n * What comes back says when each note is struck, how hard and by which part (`notes`), where each bar begins and where\n * the pedal is — for a picture that follows the music — and `render` mixes it into one clip.\n */\nexport function perform(options: PerformOptions, parts: Readonly>): Performance {\n const meter = options.meter ?? \"4/4\", mm = /^(\\d+)\\/(1|2|4|8|16)$/.exec(meter);\n if (!mm || Number(mm[1]) < 1) throw new Error(`A meter is beats over the note that counts them, \"3/8\", \"4/4\", \"6/8\" — not ${JSON.stringify(meter)}.`);\n const beatTicks = WHOLE / Number(mm[2]), barTicks = Number(mm[1]) * beatTicks;\n if (!(options.bpm > 0)) throw new Error(`perform() takes a tempo, { bpm: 120 }: beats a minute, the meter's (3/8 counts eighths) — not ${options.bpm}.`);\n const pickup = options.pickup ? (() => { const p = /^1\\/(\\d+)$/.exec(options.pickup!) ?? /^(\\d+)\\/(\\d+)$/.exec(options.pickup!); if (!p) throw new Error(`A pickup is a length, \"1/8\", \"3/16\" — not ${JSON.stringify(options.pickup)}.`); return p.length === 2 ? WHOLE / Number(p[1]) : (WHOLE * Number(p[1])) / Number(p[2]); })() : 0;\n const names = Object.keys(parts);\n if (names.length === 0) throw new Error(\"perform() takes its parts, one at least: { right: { instrument: piano, notes: \\\"…\\\" } }.\");\n const read = names.map((k) => ({ name: k, part: parts[k], ...readPart(k, parts[k].notes, barTicks, pickup, meter) }));\n const lastTick = Math.max(barTicks, ...read.flatMap((r) => [...r.notes.map((n) => n.tick + n.length), ...r.pedal.map(([a, b]) => Math.max(a, b ?? a))])) + barTicks;\n // Ticks to seconds: the tempo at each tick, added up; the holds where they fall.\n const barTick = (b: number) => (b <= 1 ? pickup * b : pickup + (b - 1) * barTicks);\n const points = (options.tempo ?? []).map(([b, bpm]) => {\n if (!(bpm > 0)) throw new Error(`A tempo point is [bar, beats a minute], the tempo more than 0 — not ${bpm}.`);\n return [barTick(b), bpm] as const;\n }).sort((a, b) => a[0] - b[0]);\n const bpmAt = (t: number) => {\n if (points.length === 0) return options.bpm;\n if (t <= points[0][0]) return points[0][1];\n for (let k = 1; k < points.length; k++) if (t < points[k][0]) { const [t0, v0] = points[k - 1], [t1, v1] = points[k]; return v0 + ((v1 - v0) * (t - t0)) / (t1 - t0); }\n return points[points.length - 1][1];\n };\n const holds = (options.holds ?? []).map(([b, sec]) => { if (!(sec >= 0)) throw new Error(`A hold is [bar, seconds], 0 or more — not ${sec}.`); return [barTick(b), sec] as const; });\n const secs: number[] = [0];\n for (let t = 0; t < lastTick; t++) {\n let next = secs[t] + 60 / (bpmAt(t + 0.5) * beatTicks);\n for (const [ht, sec] of holds) if (Math.floor(ht) === t + 1) next += sec;\n secs.push(next);\n }\n const timeOf = (tick: number) => { const t = Math.max(0, Math.min(lastTick, tick)), k = Math.floor(t); return k >= lastTick ? secs[lastTick] : secs[k] + (secs[k + 1] - secs[k]) * (t - k); };\n // A player's unevenness: the same numbers every build.\n const h = options.humanize ?? {}, spread = h.time ?? 0, vspread = h.velocity ?? 0;\n let seed = (h.seed ?? 1) * 2654435761 >>> 0 || 1;\n const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return (seed >>> 0) / 4294967296; };\n const wobble = () => (random() + random() + random() - 1.5) / 0.5;\n const out: PerformedNote[] = [], pedalOf = new Map(), allPedal: [number, number][] = [];\n let first = Infinity;\n for (const r of read) {\n const lead = r.part.lead ?? 0, scale = r.part.velocity ?? 1;\n for (const n of r.notes) {\n const at = timeOf(n.tick) - lead + spread * wobble(), end = timeOf(n.tick + (n.staccato ? n.length / 2 : n.length)) - lead;\n const v = Math.max(1, Math.min(127, Math.round(n.velocity * scale + vspread * wobble())));\n const bar = n.tick < pickup ? 0 : Math.floor((n.tick - pickup) / barTicks) + 1;\n const beat = (n.tick - (bar === 0 ? 0 : barTick(bar))) / beatTicks;\n out.push({ at, end: Math.max(end, at + 0.02), pitch: n.pitch, note: nameOf(n.pitch), velocity: v, part: r.name, voice: n.voice, bar, beat, frame: 0 });\n first = Math.min(first, at);\n }\n const list = pedalOf.get(r.part.instrument) ?? [];\n for (const [down, up] of r.pedal) {\n // A \"ped\" while the pedal is down: lifted and put down again 60 ms later, as a foot changes it.\n const a = timeOf(down), b = up === null ? null : timeOf(up);\n const changed = list.length > 0 && Math.abs(list[list.length - 1][1] - a) < 1e-9;\n list.push([changed ? a + 0.06 : a, b ?? Infinity]);\n }\n pedalOf.set(r.part.instrument, list);\n }\n // Nothing before 0: a lead or a wobble at the very start moves everything a little later.\n const shift = first < 0 ? -first : 0;\n const notes = out.map((n) => Object.freeze({ ...n, at: n.at + shift, end: n.end + shift, frame: Math.round((n.at + shift) / FRAME) })).sort((a, b) => a.at - b.at || a.pitch - b.pitch);\n const seconds = Math.max(0, ...notes.map((n) => n.end));\n for (const [inst, list] of pedalOf) {\n // A pedal never lifted comes up three seconds after the last note is let go: the end rings.\n const fixed = list.map(([a, b]) => [a + shift, Number.isFinite(b) ? b + shift : seconds + 3] as [number, number]);\n pedalOf.set(inst, fixed);\n allPedal.push(...fixed);\n }\n const bars = [0, ...Array.from({ length: Math.ceil((lastTick - pickup) / barTicks) }, (_, k) => timeOf(pickup + k * barTicks) + shift)];\n const made: Performance = Object.freeze({\n kind: \"performance\" as const, notes: Object.freeze(notes), pedal: Object.freeze(allPedal.sort((a, b) => a[0] - b[0]).map((p) => Object.freeze(p))),\n bars: Object.freeze(bars), parts: Object.freeze(names), seconds,\n });\n performances.set(made, { parts: read.map((r) => ({ name: r.name, part: r.part })), pedal: pedalOf });\n return made;\n}\n\n/**\n * The part of a performance from bar `from` up to bar `to` (not included; to its end when left out), bars as\n * `performance.bars` counts them, as a performance from 0 of its own: the notes struck in it, their times from its\n * start, and the pedal — down already when the pedal went down before it (its sound is the excerpt's before), held to\n * where it comes up. Render a long piece a section at a time, each with its room, its tail ringing on under the next\n * when the sections are added up at their `at`s: `music.render(music.excerpt(take, 44, 60), { reverb: ROOM })`.\n */\nexport function excerpt(p: Performance, from: number, to?: number): Performance & { readonly at: number } {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"excerpt() takes a performance made by music.perform.\");\n const last = p.bars.length - 1;\n if (!(Number.isInteger(from) && from >= 0 && from <= last)) throw new Error(`excerpt() starts on a bar, 0 to ${last}, not ${from}.`);\n if (to !== undefined && !(Number.isInteger(to) && to > from && to <= last)) throw new Error(`excerpt() ends on a bar after ${from}, at most ${last}, not ${to}.`);\n const a = p.bars[from], b = to === undefined ? Infinity : p.bars[to];\n const notes = p.notes.filter((n) => n.at >= a - 1e-9 && n.at < b - 1e-9).map((n) => Object.freeze({ ...n, at: n.at - a, end: n.end - a, frame: Math.round((n.at - a) / FRAME) }));\n const clip = (list: readonly (readonly [number, number])[]) => list.filter(([d, u]) => u > a && d < b).map(([d, u]) => [d - a, u - a] as [number, number]);\n const pedal = new Map();\n for (const [inst, list] of inside.pedal) pedal.set(inst, clip(list));\n const made = Object.freeze({\n kind: \"performance\" as const, at: a, notes: Object.freeze(notes), pedal: Object.freeze(clip(p.pedal).map((x) => Object.freeze(x))),\n bars: Object.freeze(p.bars.slice(from, to === undefined ? undefined : to + 1).map((t) => t - a)), parts: p.parts,\n seconds: Math.max(0, ...notes.map((n) => n.end)),\n });\n performances.set(made, { parts: inside.parts, pedal });\n return made;\n}\n\n/** What `render` needs of a performance besides what it shows: its parts as given, and each instrument's pedal. */\nconst performances = new WeakMap }>();\n\n/** The song's reverb in `render`, as `Clip.reverb` takes it, the dry part left out. */\nexport interface ReverbOptions { readonly decay?: number; readonly damping?: number; readonly predelay?: number; readonly width?: number }\n\n/**\n * A song mixed into one clip when the script is built: every note exactly in time, one sound playing. Mixed as a\n * mixing desk does: each track's notes made again at `rate` (44 100 when left out: what the ear hears up to 20 kHz; a\n * note played in the game note by note is made at 22 050, to keep the map small) into its own part, through a\n * section's effects where it has them, then its `fx`, at its volume, to its side; what each track sends (its `reverb`)\n * into one reverb shared by them all (`reverb`, its room); the whole through `master` —\n * `(mix) => mix.compress({ threshold: -14, ratio: 2 })` — and last a limiter (`Clip.limit`) so it never goes over\n * −1.5 dB however the parts add, between the samples too: `limit: false` leaves it as mixed, `{ ceiling, release }` sets it. A long clip a\n * program plays goes in the map as Ogg Vorbis, two channels when it has two.\n */\nexport function render(s: Song | Performance, options: RenderOptions = {}): Clip {\n const rate = options.rate ?? 44100;\n let mixed: Clip;\n if (\"kind\" in s && s.kind === \"performance\") mixed = mixPerformance(s, rate, options);\n else mixed = mixSong(s as Song, rate, options);\n if (options.master) mixed = options.master(mixed);\n if (options.loudness !== undefined) mixed = mixed.loudness(options.loudness);\n const limit = options.limit ?? true;\n return limit === false ? mixed : mixed.limit(limit === true ? {} : limit);\n}\n\n/** How `render` mixes. */\nexport interface RenderOptions {\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The limiter last (true), its ceiling and release, or false for none. */\n readonly limit?: boolean | { readonly ceiling?: number; readonly release?: number };\n /** The room the parts' `reverb` sends go to. */\n readonly reverb?: ReverbOptions;\n /** What the whole mix goes through before the limiter. */\n readonly master?: (mix: Clip) => Clip;\n /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */\n readonly loudness?: number;\n /** A performance's parts to mix, by name — the rest left out: stems, a melody apart from what is under it. */\n readonly parts?: readonly string[];\n}\n\n/** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */\nfunction withReverb(parts: { clip: Clip; at: number }[], sends: { clip: Clip; at: number }[], least: number, rate: number, room: ReverbOptions | undefined): Clip {\n if (sends.length) {\n const r = room ?? {};\n parts.push({ clip: mixdown(sends, least, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n }\n return mixdown(parts, least, rate);\n}\n\n/**\n * A performance mixed: the notes of the parts that share an instrument played by it together — both hands on one\n * piano, one pedal, a key struck by either hand — and heard as the first of those parts says; then as a song's parts are.\n */\nfunction mixPerformance(p: Performance, rate: number, options: RenderOptions): Clip {\n const inside = performances.get(p);\n if (!inside) throw new Error(\"render() takes a performance made by music.perform.\");\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const done = new Set();\n const only = options.parts;\n if (only) for (const k of only) if (!inside.parts.some((x) => x.name === k)) throw new Error(`render(): the performance has no part ${JSON.stringify(k)}: its parts are ${inside.parts.map((x) => x.name).join(\", \")}.`);\n for (const { name: first, part } of inside.parts) {\n if (only && !only.includes(first)) continue;\n const inst = part.instrument;\n if (done.has(inst)) continue;\n done.add(inst);\n const names = inside.parts.filter((x) => x.part.instrument === inst && (!only || only.includes(x.name))).map((x) => x.name);\n const own = p.notes.filter((n) => names.includes(n.part));\n if (own.length === 0) continue;\n const pedal = inside.pedal.get(inst) ?? [];\n let clip: Clip;\n if (inst.together) clip = inst.together(own.map((n) => ({ at: n.at, end: n.end, pitch: n.pitch, velocity: n.velocity })), pedal, rate);\n else {\n // An instrument that plays note by note: each held as long as the key, or the pedal, holds it.\n const held = (n: PerformedNote) => { let off = n.end; for (const [down, up] of pedal) if (off >= down && off < up) off = up; return off - n.at; };\n clip = mixdown(own.map((n) => ({ clip: (inst.strike ? inst.strike(n.note, held(n), n.velocity / 100, rate) : inst.note(n.note, held(n), rate).gain(n.velocity / 100)), at: n.at })), undefined, rate);\n }\n if (part.fx) clip = part.fx(clip);\n if ((part.volume ?? 1) !== 1) clip = clip.gain(part.volume ?? 1);\n if ((part.pan ?? 0) !== 0) clip = clip.pan(part.pan ?? 0);\n parts.push({ clip, at: 0 });\n if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 });\n }\n if (parts.length === 0) {\n if (only) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], p.seconds || 0.01, rate);\n throw new Error(\"render(): the performance plays no notes.\");\n }\n return withReverb(parts, sends, p.seconds, rate, options.reverb);\n}\n\n/** A song mixed, as a mixing desk does. */\nfunction mixSong(s: Song, rate: number, options: RenderOptions): Clip {\n const score = scores.get(s), least = s.steps * s.stepFrames * FRAME;\n let mixed: Clip;\n if (!score) {\n // (A song from elsewhere, without its score: its own clips, at their rate.)\n mixed = mixdown(s.at.map((at, k) => ({ clip: s.clips[s.which[k]], at: at * FRAME })), s.seconds, rate);\n } else {\n const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n const byTrack = new Map();\n for (const n of score) { const list = byTrack.get(n.track); if (list) list.push(n); else byTrack.set(n.track, [n]); }\n for (const [t, notes] of byTrack) {\n const clipOf = (n: Score) => sounded(t, n, rate);\n // The notes as they are, and each section's that has effects of its own mixed apart and through them.\n const entries: { clip: Clip; at: number }[] = [], apart = new Map();\n for (const n of notes) {\n if (n.piece?.fx) { const list = apart.get(n.piece); if (list) list.push(n); else apart.set(n.piece, [n]); }\n else entries.push({ clip: clipOf(n), at: n.at * FRAME });\n }\n for (const [p, list] of apart) {\n const from = p.from * s.stepFrames;\n const sub = mixdown(list.map((n) => ({ clip: clipOf(n), at: (n.at - from) * FRAME })), p.time.seconds, rate);\n entries.push({ clip: p.fx!(sub, p.time), at: from * FRAME });\n }\n let part = mixdown(entries, least, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n parts.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n mixed = withReverb(parts, sends, least, rate, options.reverb);\n }\n return mixed;\n}\n\n/* ── Music that follows the game: a song cut into pieces, played piece by piece ── */\n\n/** How a song of sections is cut for the game to play piece by piece (`stems`). */\nexport interface StemsOptions {\n /**\n * Which parts each layer holds, by name — `{ drums: [\"kit\", \"hats\"], bass: [\"bass\"], melody: [\"lead\", \"saw\"] }` — a\n * layer the game can turn on and off where a piece begins. A part in no layer is left out.\n */\n readonly layers: Readonly>;\n /**\n * Beats a piece: where the game can go to another section or turn a layer on or off (a bar's beats when left out).\n * Two in a bar of four halves the wait for a change, for about half as much map again and more sounds at once.\n */\n readonly every?: number;\n /** Samples a second (44 100). */\n readonly rate?: number;\n /** The reverb's room, as `render` takes it. */\n readonly reverb?: ReverbOptions;\n /** What each piece's clip goes through last — an EQ, not a compressor: each is on its own, the game adds them up. */\n readonly master?: (clip: Clip) => Clip;\n /** The loudest the pieces may add up to as the song plays through, every layer on (0.84, −1.5 dB). */\n readonly peak?: number;\n /**\n * Seconds a piece's clip rings on after its notes end (2), its echoes and reverb faded out over the last of them: the\n * pieces after it cover the rest, and a shorter clip is a smaller map. A layer's last piece keeps all of its tail.\n */\n readonly tail?: number;\n /** The Ogg Vorbis quality of the pieces' clips (4: a little smaller than a song's 5, as many play at once). */\n readonly quality?: number;\n /**\n * Sounds to play on the next beat when the game asks (`band.sting`): a crash for a cleared line, a hit for a boss.\n * Turned down with the pieces, which leave room for one on any beat.\n */\n readonly stingers?: Readonly>;\n}\n\n/** A song cut into pieces for the game to play piece by piece, with `conduct` and a `Band`: made when the script is built. */\nexport interface Stems {\n readonly kind: \"stems\";\n /** Frames a bar lasts. */\n readonly barFrames: number;\n readonly bpm: number;\n /** Beats a bar, and beats a piece. */\n readonly beats: number;\n readonly every: number;\n /** Frames each beat of a piece lasts, whole frames (beats of a bar not a whole number of frames take turns). */\n readonly waits: readonly number[];\n /** The layers' names, in the order `band.on` has them. */\n readonly layers: readonly string[];\n /** The sections, in the order the song plays them: their names and how many bars. */\n readonly sections: readonly SongSection[];\n /**\n * Section `s`'s piece `p` in layer `l`: its notes, their tails and echoes and reverb with them, or null where it plays\n * none. A section of `bars` bars has bars × beats / every pieces.\n */\n readonly pieces: readonly (readonly (readonly (Clip | null)[])[])[];\n readonly stingers: readonly Clip[];\n /** A section's place in `sections`, by its name: `band.go(stems.section(\"drop\"))`. */\n section(name: string): number;\n /** A layer's place in `layers`, by its name: `band.mute(stems.layer(\"drums\"))`. */\n layer(name: string): number;\n /** A stinger's place, by its name: `band.sting(stems.stinger(\"crash\"))`. */\n stinger(name: string): number;\n /** The most clips sounding at once as the song plays through, every layer on: of the game's 32, what is left for the rest. */\n readonly voices: number;\n /** The pieces added up as the game plays the song through, every layer on, each on its frame: to hear it, or compare. */\n readonly playthrough: Clip;\n}\n\n/**\n * A song of sections (`arrange`) cut into pieces — a bar each, or `every` beats — a clip each piece of each layer, for\n * music that follows the game: where each piece begins the program says which section plays and which layers (`Band`,\n * `conduct`), and a stinger plays on the next beat. A piece's clip holds the notes that start in it, with their tails,\n * echoes and reverb, so it overlaps the next and nothing is cut off, whichever comes after it; a piece the same as\n * another is the same clip, one file in the map. Each layer is mixed as `render` mixes the song, but with no master\n * and no limiter between the parts — the game adds the clips up — so all of them are turned down together until the\n * song played through stays under `peak`.\n */\nexport function stems(s: Song, options: StemsOptions): Stems {\n const parts = partsOf.get(s), score = scores.get(s);\n if (!parts || !score) throw new Error(\"stems() cuts a song made of sections, by music.arrange.\");\n const rate = options.rate ?? 44100, layers = Object.keys(options.layers), r = options.reverb ?? {}, tail = options.tail ?? 2;\n if (!(tail > 0)) throw new Error(`stems()' tail is seconds after a piece, more than 0, not ${tail}.`);\n if (layers.length === 0 || layers.length > 8) throw new Error(`stems() takes one to eight layers, not ${layers.length}.`);\n const beats = s.beats, every = options.every ?? beats, piece = (s.barFrames * every) / beats;\n if (!Number.isInteger(every) || every < 1 || every > beats || beats % every !== 0) throw new Error(`stems() cuts every few beats of a bar's ${beats}, a number that divides it — not every ${every}.`);\n if (!Number.isInteger(piece)) throw new Error(`A piece of ${every} beats would be ${piece.toFixed(2)} frames: the game plays a sound on a frame. Make it a bar (every: ${beats}), or a tempo whose bar divides into whole frames.`);\n const perBar = beats / every;\n const layerOf = new Map();\n layers.forEach((name, l) => {\n for (const p of options.layers[name]) {\n const found = parts.find((x) => x.name === p);\n if (!found) throw new Error(`The layer ${name} names ${JSON.stringify(p)}, which is no part of the song: its parts are ${parts.map((x) => x.name).join(\", \")}.`);\n if (layerOf.has(found.track)) throw new Error(`${p} is in two layers: a part is in one at most.`);\n layerOf.set(found.track, l);\n }\n });\n const pieceSeconds = piece * FRAME, total = s.sections.reduce((n, x) => n + x.bars, 0) * perBar;\n // The notes of each piece of each layer, by part.\n const cells: Map[][] = Array.from({ length: total }, () => layers.map(() => new Map()));\n for (const n of score) {\n const l = layerOf.get(n.track);\n if (l === undefined) continue;\n const g = Math.min(total - 1, Math.floor((n.at + 1e-6) / piece));\n const m = cells[g][l], list = m.get(n.track);\n if (list) list.push(n); else m.set(n.track, [n]);\n }\n const clipOf = (t: Track, n: Score) => sounded(t, n, rate);\n // Each layer's last piece with notes: it rings out whole, as the song ends.\n const last = layers.map((_, l) => { let g = total - 1; while (g > 0 && cells[g][l].size === 0) g--; return g; });\n // A piece of a layer, mixed: each part's notes from where it begins, through what the part goes through, and the reverb.\n const raw: (Clip | null)[][] = cells.map((byLayer, g) => byLayer.map((m, l) => {\n const out: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = [];\n // Where the piece's last note ends, its release and all: a riser four bars long is kept whole.\n let end = pieceSeconds;\n for (const [t, notes] of m) for (const n of notes) end = Math.max(end, (n.at - g * piece) * FRAME + clipOf(t, n).seconds);\n for (const [t, notes] of m) {\n const plain = notes.filter((n) => !n.piece?.fx), apart = notes.filter((n) => n.piece?.fx);\n const entries: { clip: Clip; at: number }[] = plain.map((n) => ({ clip: clipOf(t, n), at: (n.at - g * piece) * FRAME }));\n if (apart.length) {\n // A section's effects take the whole section: this piece's notes where they fall in it, then the piece cut out.\n const p = apart[0].piece!, from = p.from * s.stepFrames, into = (g * piece - from) * FRAME;\n const whole = p.fx!(mixdown(apart.map((n) => ({ clip: clipOf(t, n), at: (n.at - from) * FRAME })), undefined, rate), p.time);\n entries.push({ clip: whole.trim(into, whole.seconds), at: 0 });\n }\n let part = mixdown(entries, undefined, rate);\n if (t.fx) part = t.fx(part);\n if (t.volume !== 1) part = part.gain(t.volume);\n if (t.pan !== 0) part = part.pan(t.pan);\n out.push({ clip: part, at: 0 });\n if (t.reverb > 0) sends.push({ clip: part.gain(t.reverb), at: 0 });\n }\n if (out.length === 0) return null;\n if (sends.length) out.push({ clip: mixdown(sends, undefined, rate).reverb({ decay: r.decay ?? 0.7, damping: r.damping ?? 0.45, predelay: r.predelay ?? 0.02, width: r.width ?? 1, mix: 1, dry: 0 }), at: 0 });\n let mixed = mixdown(out, undefined, rate);\n if (options.master) mixed = options.master(mixed);\n // What rings on after the piece's notes, kept for `tail` seconds and faded over the last of them — the pieces\n // after cover the rest — but all of it after the layer's last piece.\n const keep = end + tail;\n return g < last[l] && mixed.seconds > keep ? mixed.trim(0, keep).fade(0, Math.min(1, tail / 2)) : mixed;\n }));\n // All of them turned down together, as the song plays through.\n const placed: { clip: Clip; at: number; g: number; l: number }[] = [];\n raw.forEach((byLayer, g) => byLayer.forEach((c, l) => { if (c) placed.push({ clip: c, at: g * pieceSeconds, g, l }); }));\n if (placed.length === 0) throw new Error(\"stems(): the layers play no notes.\");\n // The stingers may play on any beat: turned down with the pieces, and room left for them over the loudest.\n const waits = Array.from({ length: every }, (_, j) => Math.round(((j + 1) * piece) / every) - Math.round((j * piece) / every));\n const stingerNames = Object.keys(options.stingers ?? {});\n const lines: number[] = [];\n for (let g = 0; g < total; g++) { let at = g * piece; for (const w of waits) { lines.push(at * FRAME); at += w; } }\n const fitted = together(placed, { peak: options.peak ?? 0.84, over: stingerNames.map((k) => ({ clip: options.stingers![k], at: lines })) });\n const grid: (Clip | null)[][] = raw.map((byLayer) => byLayer.map(() => null));\n const quality = options.quality ?? 4;\n placed.forEach((p, k) => { grid[p.g][p.l] = fitted[k].ogg(quality); });\n const stingers = stingerNames.map((_, k) => fitted[placed.length + k]);\n let start = 0;\n const pieces = s.sections.map((sec) => { const n = sec.bars * perBar, rows = grid.slice(start, start + n).map((row) => Object.freeze(row)); start += n; return Object.freeze(rows); });\n const lookup = (what: string, list: readonly string[], name: string) => {\n const k = list.indexOf(name);\n if (k < 0) throw new Error(`There is no ${what} ${JSON.stringify(name)}: there are ${list.map((x) => JSON.stringify(x)).join(\", \") || \"none\"}.`);\n return k;\n };\n let voices = -1;\n return Object.freeze({\n kind: \"stems\" as const, barFrames: s.barFrames, bpm: s.bpm, beats, every, waits: Object.freeze(waits),\n layers: Object.freeze(layers), sections: s.sections, pieces: Object.freeze(pieces), stingers: Object.freeze(stingers),\n section: (name: string) => lookup(\"section\", s.sections.map((x) => x.name), name),\n layer: (name: string) => lookup(\"layer\", layers, name),\n stinger: (name: string) => lookup(\"stinger\", stingerNames, name),\n get playthrough() {\n return mixdown(placed.map((p) => ({ clip: grid[p.g][p.l]!, at: p.at })));\n },\n get voices() {\n if (voices < 0) {\n voices = 0;\n for (const p of placed) { let n = 0; for (const q of placed) if (q.at <= p.at && q.at + q.clip.seconds > p.at) n++; voices = Math.max(voices, n); }\n }\n return voices;\n },\n });\n}\n\n/**\n * The music as the game steers it: which section plays, which piece of it, which layers. Make one inside the program\n * that steers the music and hand it to `conduct`, which plays a piece where each begins as it says:\n *\n * import { music, Band } from \"trigscript/music\";\n * const band = new Band();\n * start(music.conduct(stems, band));\n * band.go(stems.section(\"drop\")); // where the next piece begins\n * band.mute(stems.layer(\"drums\"));\n * band.sting(stems.stinger(\"crash\")); // on the next beat\n *\n * With nothing said, the song plays through its sections in order and starts again.\n */\nexport class Band {\n /** The section playing, its place in `stems.sections`; the piece of it (a bar, unless `stems.every` says), from 0; the beat of the piece. */\n section = 0;\n piece = 0;\n beat = 0;\n /** Pieces played since it started. */\n count = 0;\n /** The game's frame the beat playing began on: how far into the beat it is, for what moves with the music. */\n at = 0;\n /** The section to go to, and whether where the next piece begins (`go`) or when this section ends (`queue`); −1 for none. */\n next = -1;\n now = false;\n /** Whether a section plays again when it ends, instead of going on to the next. */\n loop = false;\n /** Which layers play, by their place in `stems.layers`. */\n on = [true, true, true, true, true, true, true, true];\n /** A stinger to play on the next beat, by its place; −1 for none. */\n stung = -1;\n /** Whether it plays: false stops it where the next piece would begin (what sounds rings out). */\n playing = true;\n\n /** Go to a section where the next piece begins, from its first piece. */\n go(section: number) {\n this.next = section;\n this.now = true;\n }\n /** Go to a section when the one playing ends. */\n queue(section: number) {\n this.next = section;\n this.now = false;\n }\n /** Turn a layer off, or on, from where the next piece begins. */\n mute(layer: number) {\n this.on[layer] = false;\n }\n unmute(layer: number) {\n this.on[layer] = true;\n }\n /** Play a stinger on the next beat. */\n sting(stinger: number) {\n this.stung = stinger;\n }\n /** Stop where the next piece would begin. */\n stop() {\n this.playing = false;\n }\n}\n\n/** Play `stems` as `band` says, beat by beat, until it stops: `start(music.conduct(stems, band))` beside the program. */\nexport const conduct = game(async (s: Stems, band: Band) => {\n band.playing = true;\n band.beat = 0;\n while (band.playing || band.beat > 0) {\n band.at = memory.game.frame;\n if (band.beat === 0) {\n // Where a piece begins: where to be, then the piece's clip of each layer that is on. (Which clip, by test: a\n // clip is no value a program holds.)\n if (band.next >= 0 && (band.now || band.piece === 0)) {\n band.section = band.next;\n band.piece = 0;\n band.next = -1;\n }\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) {\n for (let p = 0; p < s.pieces[k].length; p++) if (band.piece === p) {\n for (let l = 0; l < s.layers.length; l++) if (s.pieces[k][p][l]) if (band.on[l]) playWav(s.pieces[k][p][l]!, 0);\n }\n }\n }\n for (let j = 0; j < s.stingers.length; j++) if (band.stung === j) playWav(s.stingers[j], 0);\n band.stung = -1;\n for (let j = 0; j < s.every; j++) if (band.beat === j) await sleep(frames(s.waits[j]));\n band.beat++;\n if (band.beat >= s.every) {\n band.beat = 0;\n band.count++;\n band.piece++;\n // A section ended: again, or on to the next (after the last, the first).\n for (let k = 0; k < s.sections.length; k++) if (band.section === k) if (band.piece >= s.pieces[k].length) {\n band.piece = 0;\n if (!band.loop) band.section = k + 1 < s.sections.length ? k + 1 : 0;\n }\n if (!band.playing) band.beat = 0;\n }\n }\n});\n\n/**\n * Play a song, note by note, inside an async program: \\`await music.play(song)\\` resolves at its end, or\n * \\`start(music.play(song))\\` plays it beside the program.\n */\nexport const play = game(async (s: Song) => {\n const at = s.at;\n const which = s.which;\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n // Which clip, by its number: a test a clip (a loop over a length known when the script is built is unrolled, and\n // the clips stay the song's, known when it is built — a clip is no value a program holds).\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n if (s.frames > now) await sleep(frames(s.frames - now));\n});\n\n/** Play a song again and again; start it beside a program: \\`start(music.loop(song))\\`. */\nexport const loop = game(async (s: Song) => {\n // (\\`play\\` written out again, so that the wait at the end of each turn is where the loop shows it — at least a frame,\n // so that a song with nothing left at its end does not turn round within one frame for ever.)\n const at = s.at;\n const which = s.which;\n while (true) {\n let i = 0;\n let now = 0;\n while (i < at.length) {\n if (at[i] > now) {\n await sleep(frames(at[i] - now));\n now = at[i];\n }\n const k = which[i];\n for (let j = 0; j < s.clips.length; j++) if (k === j) playWav(s.clips[j], 0);\n i++;\n }\n await sleep(frames(Math.max(s.frames - now, 1)));\n }\n});\n\n/** Everything above as one name: import { music } from \"trigscript/music\"; music.play(song). */\nexport const music = {\n sampler, sampled, perform, excerpt, hits, sweep, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop,\n part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct,\n};\n", "random": "/**\n * Chance: the standard library's \"trigscript/random\" (TrigScript 4).\n *\n * import { chance, range, pick, shuffle, weighted, Random } from \"trigscript/random\";\n *\n * if (chance(25)) dropLoot(); // one time in four\n * const lane = range(1, 3); // 1, 2 or 3\n * const boss = pick(BOSSES); // any one of a list\n * shuffle(order); // an array of the program, in place\n * const tier = weighted([70, 25, 5]); // 0 most of the time, 2 rarely\n *\n * const rng = new Random(seed); // the same numbers every time for the same seed\n * const x = rng.range(0, 63);\n *\n * The functions use the game's own random numbers, which every player's game draws alike, so nothing goes out of step\n * in a game of several players. `Random` is a generator of your own (xorshift), seeded: the same seed gives the same\n * numbers, game after game — a level made from a seed, a save code that holds one.\n */\nimport { random } from \"trigscript\";\n\n/** True `percent` times in a hundred (25: one time in four). */\nexport function chance(percent: number): boolean {\n return random(100) < percent;\n}\n\n/** A whole number from `min` to `max`, both included. */\nexport function range(min: number, max: number): number {\n return min + random(max - min + 1);\n}\n\n/** The total of `count` dice of `sides` sides each (3, 6: from 3 to 18). */\nexport function dice(count: number, sides: number): number {\n let total = 0;\n let i = 0;\n while (i < count) { total += 1 + random(sides); i++; }\n return total;\n}\n\n/** One of a list, any one alike; a list the script has, or an array of the program (the first's 0 when it is empty). */\nexport function pick(items: readonly T[]): T {\n return items[random(items.length)];\n}\n\n/** The place of one of the weights, each as likely as its share of their total: [70, 25, 5] gives 0 most of the time. */\nexport function weighted(weights: readonly number[]): number {\n let total = 0;\n for (const w of weights) total += w;\n let roll = random(total);\n let i = 0;\n while (i < weights.length) {\n if (roll < weights[i]) return i;\n roll -= weights[i];\n i++;\n }\n return weights.length - 1;\n}\n\n/** An array of the program in a random order, in place (Fisher–Yates: every order alike). */\nexport function shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = random(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n}\n\n/**\n * A generator of random numbers of your own, seeded: the same seed gives the same numbers, in the game and when the\n * script is tested. Make it in the program (`const rng = new Random(1234)`).\n */\nexport class Random {\n state: number;\n\n /** Seeded with any whole number (0 is taken as 1). */\n constructor(seed: number) {\n this.state = seed === 0 ? 1 : seed;\n }\n\n /** The next number, from 0 to 2 147 483 647. */\n next(): number {\n let x = this.state;\n x ^= x << 13;\n x ^= x >>> 17;\n x ^= x << 5;\n this.state = x;\n return x & 0x7fffffff;\n }\n\n /** A whole number from 0 to n − 1. */\n int(n: number): number {\n return this.next() % n;\n }\n\n /** A whole number from `min` to `max`, both included. */\n range(min: number, max: number): number {\n return min + this.int(max - min + 1);\n }\n\n /** True `percent` times in a hundred. */\n chance(percent: number): boolean {\n return this.int(100) < percent;\n }\n\n /** One of a list, any one alike. */\n pick(items: readonly T[]): T {\n return items[this.int(items.length)];\n }\n\n /** An array of the program in a random order, in place. */\n shuffle(items: T[]) {\n let i = items.length - 1;\n while (i > 0) {\n const j = this.int(i + 1);\n const held = items[i];\n items[i] = items[j];\n items[j] = held;\n i--;\n }\n }\n}\n", "screen": "/**\n * Pixel screens: the standard library's \"trigscript/screen\" (TrigScript 4).\n *\n * import { Screen, ScreenView, sprite } from \"trigscript/screen\";\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n *\n * program(async () => {\n * const screen = new Screen(4, 4, 24, 16); // 24 × 16 pixels, its corner on tile (4, 4)\n * let x = 10;\n * while (true) {\n * screen.clear();\n * screen.rect(0, 15, 24, 1, 5); // the ground, in colour 5\n * screen.blit(SHIP, x, 12);\n * screen.number(score, 1, 1, 2); // digits 3 × 5 pixels, in colour 2\n * screen.present(); // on the map, and so on the minimap (screen.reveal(P1) once first)\n * await nextFrame();\n * }\n * });\n *\n * A screen is a grid of pixels, each 0 (empty) or a colour from 1 to 7; drawing changes the grid, and `present()`\n * shows it: a pixel is a unit on the map, owned by the player whose colour it is, so the minimap shows the picture —\n * neighbouring pixels of one colour join into a solid block there. Only the pixels that changed since the last\n * `present()` are made or taken away, and only the pixels drawn since are looked at, so a still picture costs nothing to\n * show. Draw through the methods (`set`, `clear`, `rect`, …): a pixel written into `pixels` directly is not seen. The same grid can be shown in a\n * player's text lines too, as squares (`ScreenView` in a `ui.lines` view): one game, two screens, as the Tetris probe has it.\n *\n * A player sees the pixels only where they have vision: `screen.reveal(P1)` once gives them Map Revealers over it.\n *\n * Two looks (the constructor's last argument): \"dots\", Overlords, which fly — the minimap draws each as a dot with a gap\n * round it, the screen may be over Space; and \"solid\", Pylons, which the minimap draws as their whole two-tile\n * footprint, so pixels side by side are one block — on buildable ground (probes/lib/screen-map.mts --ground).\n *\n * What the map needs, found playing the unit-pixel probe in StarCraft: Remastered (2026-10-16): the owners of the\n * pixels (P3, P4, P5, P1, P6, P7, P8 below; their colours are theirs on the map, so give them the colours of TEXT_COLORS) must not\n * be computers — a computer moves its own units — and Remastered will not start a game without a computer, so one slot\n * (P2 here) is a computer that owns no pixel. A pixel is an Overlord, which sits on any ground and on nothing else; keep\n * the screen's tiles clear of buildings. A Pylon needs buildable ground, and none of the map's own units in the way. About 80 pixels made and taken away in a frame did not slow the game.\n */\nimport { centerLocation, createUnit, removeUnitAt, reserveLocation, textColors, units, P1, P3, P4, P5, P6, P7, P8, type Player } from \"trigscript\";\n\n/**\n * Whose units show colours 1 to 7 on the map, in the order of TEXT_COLORS: give each player that colour in the map\n * (cyan, yellow, purple, green, red, blue, orange). Green is P1's — your own units are green on the minimap anyway.\n * Not computers.\n */\nexport const OWNERS: readonly Player[] = [P3, P4, P5, P1, P6, P7, P8];\n/** The same colours in the text lines (`ScreenView`), 0 an empty square: cyan, yellow, purple, green, red, blue, orange. */\nexport const TEXT_COLORS: readonly number[] = [0, textColors.cyan, textColors.yellow, textColors.purple, textColors.green, textColors.red, textColors.blue, textColors.orange];\n\n/** Where each pixel's unit is made: a location the map does not use, taken when the script is built. */\nconst SPOT = reserveLocation(\"screen: where each pixel is made\");\n\n/** A picture known when the script is built, to `blit` onto a screen: its size, and its pixels a row at a time (0 is see-through). */\nexport interface Sprite { readonly width: number; readonly height: number; readonly cells: readonly number[] }\n\n/**\n * A sprite from rows of text, when the script is built: \"1\" … \"7\" a pixel of that colour, anything else see-through.\n *\n * const SHIP = sprite([\".1.\", \"111\", \"1.1\"]);\n */\nexport function sprite(rows: readonly string[]): Sprite {\n const width = Math.max(0, ...rows.map((r) => r.length));\n const cells: number[] = [];\n for (const row of rows) for (let x = 0; x < width; x++) { const c = Number(row[x]); cells.push(c >= 1 && c <= 7 ? c : 0); }\n return { width, height: rows.length, cells };\n}\n\n/** The digits 0 to 9, three pixels wide and five high, for `number()`: each fifteen pixels, a row at a time. */\nconst DIGITS: readonly number[] = [\n \"111101101101111\", \"010110010010111\", \"111001111100111\", \"111001111001111\", \"101101111001001\",\n \"111100111001111\", \"111100111101111\", \"111001001010010\", \"111101111101111\", \"111101111001111\",\n].flatMap((d) => d.split(\"\").map(Number));\n\n/** The most pixels a screen has: 32 × 32 at two tiles a pixel covers a 64 × 64 map, 64 × 32 half of a 128 × 128 one. */\nexport const MAX_PIXELS = 2048;\n\nexport class Screen {\n /** The picture being drawn: a colour a pixel, a row at a time (the first width × height of them). */\n pixels: number[] = new Array(MAX_PIXELS).fill(0);\n /** What the map shows now: the picture as it was at the last `present()`. */\n shown: number[] = new Array(MAX_PIXELS).fill(0);\n /** The pixels drawn a colour they were not since the last `present()`, in order: each one's place and its x and y. */\n drawnAt: number[] = new Array(MAX_PIXELS).fill(0);\n drawnX: number[] = new Array(MAX_PIXELS).fill(0);\n drawnY: number[] = new Array(MAX_PIXELS).fill(0);\n drawn = 0;\n /** More drawn than the list holds: `present()` looks at every pixel instead. */\n overflow = false;\n x: number;\n y: number;\n width: number;\n height: number;\n cell: number;\n /** The unit a pixel is: an Overlord (\"dots\"), or a Pylon (\"solid\"). */\n unit = 0;\n\n /**\n * A screen `width` × `height` pixels (MAX_PIXELS at most), its top left corner on tile (x, y) of the map, a pixel two\n * tiles across.\n * @param look \"dots\" (the default): a pixel is an Overlord, which the minimap draws as a dot, a gap round it — it flies,\n * so the screen may be over anything, Space too. \"solid\": a pixel is a Pylon, which the minimap draws as its whole\n * footprint, two tiles square, so pixels side by side are one block — it needs buildable ground under the screen,\n * and gives its owner Protoss supply. (Overlords a tile apart do not fit: the game will not place most of them.)\n */\n constructor(x: number, y: number, width: number, height: number, look: \"dots\" | \"solid\" = \"dots\") {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.cell = 64;\n this.unit = look === \"solid\" ? units.ProtossPylon : units.ZergOverlord;\n }\n\n /** Every pixel the colour (0, empty, unless it says). */\n clear(color: number = 0) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.put(i, x, y, color); i++; x++; }\n y++;\n }\n }\n\n /** One pixel; nothing happens outside the screen. */\n set(x: number, y: number, color: number) {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) this.put(y * this.width + x, x, y, color);\n }\n\n /** A pixel written, and listed for `present()` when its colour changed. */\n private put(i: number, x: number, y: number, color: number) {\n if (this.pixels[i] === color) return;\n this.pixels[i] = color;\n if (this.drawn < MAX_PIXELS) {\n this.drawnAt[this.drawn] = i;\n this.drawnX[this.drawn] = x;\n this.drawnY[this.drawn] = y;\n this.drawn++;\n } else this.overflow = true;\n }\n\n /** The colour of a pixel; 0 outside the screen. */\n get(x: number, y: number): number {\n if (x >= 0 && y >= 0 && x < this.width && y < this.height) return this.pixels[y * this.width + x];\n return 0;\n }\n\n /** A filled rectangle, its top left at (x, y); what is outside the screen is left out. */\n rect(x: number, y: number, width: number, height: number, color: number) {\n let j = 0;\n while (j < height) {\n let i = 0;\n while (i < width) { this.set(x + i, y + j, color); i++; }\n j++;\n }\n }\n\n /** A line from (x0, y0) to (x1, y1), both ends drawn. */\n line(x0: number, y0: number, x1: number, y1: number, color: number) {\n const dx = Math.abs(x1 - x0);\n const dy = -Math.abs(y1 - y0);\n const sx = x0 < x1 ? 1 : -1;\n const sy = y0 < y1 ? 1 : -1;\n let err = dx + dy;\n let x = x0;\n let y = y0;\n while (true) {\n this.set(x, y, color);\n if (x === x1 && y === y1) break;\n const e2 = 2 * err;\n if (e2 >= dy) { err += dy; x += sx; }\n if (e2 <= dx) { err += dx; y += sy; }\n }\n }\n\n /** A sprite with its top left at (x, y): its see-through pixels leave what is under them. */\n blit(s: Sprite, x: number, y: number) {\n let k = 0;\n let j = 0;\n while (j < s.height) {\n let i = 0;\n while (i < s.width) {\n const c = s.cells[k];\n if (c !== 0) this.set(x + i, y + j, c);\n k++;\n i++;\n }\n j++;\n }\n }\n\n /** A whole number's digits, 3 × 5 pixels each with a pixel between, its top left at (x, y): a score on the minimap. */\n number(n: number, x: number, y: number, color: number) {\n let rest = n < 0 ? -n : n;\n let count = 1;\n let probe = rest;\n while (probe >= 10) { probe = Math.floor(probe / 10); count++; }\n let place = x + (count - 1) * 4;\n while (true) {\n const d = rest % 10;\n let k = 0;\n while (k < 15) {\n if (DIGITS[d * 15 + k] === 1) this.set(place + (k % 3), y + Math.floor(k / 3), color);\n k++;\n }\n rest = Math.floor(rest / 10);\n place -= 4;\n if (rest === 0) break;\n }\n }\n\n /**\n * Let a player see the screen: Map Revealers of theirs over it, for the rest of the game. Without them its pixels,\n * owned by other players, are hidden by the fog of war — on the map and on the minimap. Once, before the first\n * `present()`.\n * @param player Who sees it: P1 … P8, known when the script is built.\n */\n reveal(player: Player) {\n // A Map Revealer sees ten tiles round; one every six tiles leaves no gap.\n const right = this.x * 32 + this.width * this.cell;\n const bottom = this.y * 32 + this.height * this.cell;\n let py = this.y * 32 + 96;\n while (py < bottom + 96) {\n let px = this.x * 32 + 96;\n while (px < right + 96) {\n centerLocation(SPOT, px, py, 32, 32);\n createUnit(player, units.MapRevealer, 1, SPOT);\n px += 192;\n }\n py += 192;\n }\n }\n\n /**\n * The picture on the map: each pixel that changed since the last time taken away and made again in its colour. Only\n * the pixels drawn since are looked at (one drawn and drawn back is passed over), unless more were drawn than the list\n * holds.\n */\n present() {\n if (this.overflow) {\n let i = 0;\n let y = 0;\n while (y < this.height) {\n let x = 0;\n while (x < this.width) { this.show(i, x, y); i++; x++; }\n y++;\n }\n this.overflow = false;\n } else {\n for (let k = 0; k < this.drawn; k++) this.show(this.drawnAt[k], this.drawnX[k], this.drawnY[k]);\n }\n this.drawn = 0;\n }\n\n /** One pixel on the map as it is in the picture, when it is not already. */\n private show(i: number, x: number, y: number) {\n const now = this.pixels[i];\n const was = this.shown[i];\n if (now === was) return;\n const half = this.cell >> 1;\n centerLocation(SPOT, this.x * 32 + x * this.cell + half, this.y * 32 + y * this.cell + half, 32, 32);\n OWNERS.forEach((owner, k) => { if (was === k + 1) removeUnitAt(owner, this.unit, 1, SPOT); });\n OWNERS.forEach((owner, k) => { if (now === k + 1) createUnit(owner, this.unit, 1, SPOT); });\n this.shown[i] = now;\n }\n}\n\n/**\n * A screen in the text lines, a square a pixel — filled in its colour, or empty — a line a row. For a `ui.lines` view:\n * ``, the screen's size known when the script is built. Eleven lines\n * show at once, sixty squares across.\n */\nexport function ScreenView({ screen, width, height }: { screen: Screen; width: number; height: number }) {\n return <>{UP_TO_60.map((y) => y < height && {UP_TO_60.map((x) => x < width && )})};\n}\n\n/** 0 … 59: the places a view's rows and columns are counted over, the ones past its size left out when the script is built. */\nconst UP_TO_60: readonly number[] = Array.from({ length: 60 }, (_, i) => i);\n", "signals": "/**\n * Events of your own: the standard library's \"trigscript/signals\" (TrigScript 4).\n *\n * import { Signal } from \"trigscript/signals\";\n *\n * const waveCleared = new Signal();\n *\n * program(async () => {\n * waveCleared.on((wave) => { setResources(P1, \"add\", 100 * wave, \"ore\"); }); // braces: a handler gives back no action\n * waveCleared.once((wave) => print(`First wave down!`));\n * const id = waveCleared.on((wave) => print(`Wave ${wave} cleared`));\n * …\n * waveCleared.emit(3); // every handler, in the order they were added\n * waveCleared.off(id);\n * });\n *\n * A signal lets one part of a map say that something happened without knowing who listens: the shop, the score and the\n * music each add a handler, and the wave code only emits. What it carries is one value of the type it is made with —\n * a number, a boolean, a text or a unit (`new Signal()`). Its handlers are functions kept as values: they may use\n * what the block they were written in has, and they run to their end, one after another, within the frame.\n *\n * Make a signal inside the program that uses it (`const s = new Signal()` at its top): a signal is variables\n * of a program, as anything a program writes is.\n */\n\nexport class Signal {\n /** The handlers, by the number `on` gave; one taken off is undefined, and its place is given to the next one added. */\n handlers: (((value: T) => void) | undefined)[] = [];\n /** Which handlers go once they have run once. */\n onceOnly: boolean[] = [];\n\n /**\n * Add a handler: it runs at every `emit`, handed the value.\n * @returns Its number, for `off`.\n */\n on(handler: (value: T) => void): number {\n return this.add(handler, false);\n }\n\n /** Add a handler that runs at the next `emit` only. @returns Its number, for `off` before then. */\n once(handler: (value: T) => void): number {\n return this.add(handler, true);\n }\n\n /** Take a handler off, by the number `on` or `once` gave. */\n off(id: number) {\n if (id >= 0 && id < this.handlers.length) this.handlers[id] = undefined;\n }\n\n /** Run every handler, in the order they were added, each handed `value`. */\n emit(value: T) {\n let i = 0;\n while (i < this.handlers.length) {\n const h = this.handlers[i];\n if (h) {\n if (this.onceOnly[i]) this.handlers[i] = undefined;\n h(value);\n }\n i++;\n }\n }\n\n /** How many handlers it has. */\n count(): number {\n let n = 0;\n for (const h of this.handlers) if (h) n++;\n return n;\n }\n\n /** Take every handler off. */\n clear() {\n let i = 0;\n while (i < this.handlers.length) { this.handlers[i] = undefined; i++; }\n }\n\n private add(handler: (value: T) => void, once: boolean): number {\n // A place one was taken off from, or a new one at the end.\n let i = 0;\n while (i < this.handlers.length) {\n if (!this.handlers[i]) {\n this.handlers[i] = handler;\n this.onceOnly[i] = once;\n return i;\n }\n i++;\n }\n this.handlers.push(handler);\n this.onceOnly.push(once);\n return this.handlers.length - 1;\n }\n}\n", diff --git a/compiler/sound.ts b/compiler/sound.ts index 0e97531..668d933 100644 --- a/compiler/sound.ts +++ b/compiler/sound.ts @@ -19,7 +19,7 @@ * written. IMA ADPCM, PCM and Ogg Vorbis play; Ogg Opus does not. */ import { fromBase64, toBase64 } from "./rangeCoder"; -import { chorus, compressor, curve, echo, echoTail, eq, fmVoice, loudness, plate, plateTail, pluckVoice, saturate, seeded, svf, sympathetic, type FilterType, type Points } from "./dsp"; +import { chorus, compressor, curve, duck, echo, echoTail, eq, fmVoice, loudness, plate, plateTail, pluckVoice, saturate, seeded, svf, sympathetic, type FilterType, type Points } from "./dsp"; /** The extension of a sound among a script's files. */ export const SOUND_EXTENSION = ".sound"; @@ -246,6 +246,7 @@ export interface Clip { chorus(options?: { readonly speed?: number; readonly depth?: number; readonly mix?: number }): Clip; compress(options?: { readonly threshold?: number; readonly ratio?: number; readonly attack?: number; readonly release?: number; readonly knee?: number; readonly makeup?: number }): Clip; loudness(lufs: number): Clip; + duck(key: Clip, options?: { readonly depth?: number; readonly threshold?: number; readonly attack?: number; readonly release?: number }): Clip; resonance(options: { readonly pedal: readonly (readonly [number, number])[]; readonly amount?: number; readonly decay?: number }): Clip; } @@ -596,6 +597,14 @@ function lazyClip(rate: number, frames: number, channels: 1 | 2, compute: () => if (!(num(target, "loudness()") >= -70 && target <= 0)) throw new RangeError(`loudness() is LUFS, −70 to 0 (−16 for music heard on its own, −23 for broadcast), not ${target}.`); return same("loudness", [target], (cs) => { const now = clip.lufs; return Number.isFinite(now) ? cs.map((s) => scale(s, 10 ** ((target - now) / 20))) : cs; }); }, + duck(key, options = {}) { + if (!isClip(key)) throw new Error("duck() takes the clip it ducks under: pads.duck(lead)."); + const o = { depth: options.depth ?? 6, threshold: options.threshold ?? -30, attack: options.attack ?? 0.01, release: options.release ?? 0.15 }; + if (!(num(o.depth, "duck()'s depth") >= 0 && o.depth <= 40)) throw new RangeError(`duck()'s depth is 0 to 40 dB, not ${o.depth}.`); + if (!(num(o.threshold, "duck()'s threshold") <= 0 && o.threshold >= -80)) throw new RangeError(`duck()'s threshold is −80 to 0 dB, not ${o.threshold}.`); + if (!(num(o.attack, "duck()'s attack") >= 0) || !(num(o.release, "duck()'s release") >= 0)) throw new RangeError("duck()'s attack and release are seconds, 0 or more."); + return derive("duck", [key, o], frames, channels, (cs) => duck(cs, channelsAt(key, rate, key.channels), rate, o.depth, o.threshold, o.attack, o.release)); + }, resonance(options) { const pedal = options?.pedal, amount = options?.amount ?? 0.25, decay = options?.decay ?? 3; if (!Array.isArray(pedal)) throw new Error("resonance() takes the pedal: { pedal: [[down, up], …] } in seconds."); diff --git a/ledger/sounds/music-sweep.ts b/ledger/sounds/music-sweep.ts new file mode 100644 index 0000000..c3f3b29 --- /dev/null +++ b/ledger/sounds/music-sweep.ts @@ -0,0 +1,14 @@ +// ledger: step 5, takes +// A noise sweep into a drop (`music.sweep`), a lead on the trance preset, and the pad under it ducked by the lead +// (`Clip.duck`), the two rendered apart (`render`'s `parts`). +import { music } from "trigscript/music"; +const take = music.perform({ meter: "4/4", bpm: 128 }, { + lead: { instrument: music.presets.trance(), notes: "E5/8 D#5 E5 D#5 E5 B4 D5 C5" }, + pad: { instrument: music.presets.pad(), notes: "A3+C4+E4/1" }, +}); +const lead = music.render(take, { parts: ["lead"], limit: false }); +const under = music.render(take, { parts: ["pad"], limit: false }).duck(lead, { depth: 5 }); +const drop = music.sweep(2).then(mixdown([{ clip: lead, at: 0 }, { clip: under, at: 0 }]).limit()); +program(async () => { + playWav(drop, 0); +}); diff --git a/stdlib/music.ts b/stdlib/music.ts index e8ffed2..b5c2b1a 100644 --- a/stdlib/music.ts +++ b/stdlib/music.ts @@ -411,6 +411,12 @@ export const presets = { braam: (o: SynthOptions = {}) => synth({ wave: "saw", voices: 5, detune: 16, width: 0.6, volume: 0.22, attack: 0.04, decay: 1.2, sustain: 0.7, release: 0.9, filter: { cutoff: 160, amount: 3.4, resonance: 0.25, envelope: { attack: 0.45, decay: 1.6, sustain: 0.35, release: 0.8 } }, drive: 14, ...o }), /** A short synth pulse for sixteenth ostinatos: two squares, a quick filter blip. */ pulse: (o: SynthOptions = {}) => synth({ wave: "square", voices: 2, detune: 9, width: 0.4, volume: 0.12, attack: 0.002, decay: 0.09, sustain: 0.25, release: 0.04, filter: { cutoff: 900, amount: 2.2, resonance: 0.3, envelope: { decay: 0.08, sustain: 0.1 } }, ...o }), + /** A trance lead: seven saws a little apart, bright, a quick glide into each note — the melody on top of a drop. */ + trance: (o: SynthOptions = {}) => synth({ wave: "saw", voices: 7, detune: 18, width: 0.5, volume: 0.13, attack: 0.004, decay: 0.3, sustain: 0.85, release: 0.15, glide: -0.6, glideTime: 0.03, filter: { cutoff: 2600, amount: 1.4, resonance: 0.15, envelope: { decay: 0.3, sustain: 0.55 } }, ...o }), + /** A plucked synth for arpeggios: a saw whose filter snaps shut, a short tail. */ + arp: (o: SynthOptions = {}) => synth({ wave: "saw", voices: 2, detune: 10, width: 0.4, volume: 0.13, attack: 0.002, decay: 0.16, sustain: 0.08, release: 0.12, filter: { cutoff: 500, amount: 3.2, resonance: 0.25, envelope: { decay: 0.14, sustain: 0 } }, ...o }), + /** Supersaw chord stabs: wide, short, the filter open on the hit. */ + stab: (o: SynthOptions = {}) => synth({ wave: "saw", voices: 7, detune: 26, width: 0.8, volume: 0.11, attack: 0.003, decay: 0.22, sustain: 0.35, release: 0.15, filter: { cutoff: 1500, amount: 2.2, resonance: 0.12, envelope: { decay: 0.25, sustain: 0.3 } }, ...o }), /** A sub bass: a sine, soft at the start, under everything. */ sub: (o: SynthOptions = {}) => synth({ wave: "sine", volume: 0.4, attack: 0.02, decay: 0.3, sustain: 0.9, release: 0.25, ...o }), }; @@ -629,6 +635,17 @@ export function riser(seconds: number, options: { readonly volume?: number; read return swept.mix(lift).envelope([0, 0], [s * 0.5, 0.25], [s * 0.9, 0.85], [s, 1]).fade(0, 0.01); } +/** + * White noise through a filter sweeping over `seconds`: up (as left out) from a low rumble to bright hiss, growing + * louder, as a drop is built to; `down: true` the other way, falling and fading after it. + */ +export function sweep(seconds: number, options: { readonly down?: boolean; readonly volume?: number; readonly rate?: number } = {}): Clip { + const rate = options.rate ?? 44100, v = options.volume ?? 0.4, s = seconds, down = options.down === true; + const points: [number, number][] = down ? [[0, 12000], [s, 150]] : [[0, 150], [s * 0.7, 2500], [s, 14000]]; + const shape: [number, number][] = down ? [[0, 1], [s, 0]] : [[0, 0], [s * 0.6, 0.35], [s, 1]]; + return noise(s, { volume: v, rate }).filter("lowpass", points, { resonance: 0.3 }).envelope(...shape).fade(0.005, 0.01); +} + /** A boom to land on: a falling sine under a burst of noise, ringing `seconds` (1.5). */ export function impact(options: { readonly seconds?: number; readonly volume?: number; readonly rate?: number } = {}): Clip { const rate = options.rate ?? 44100, v = options.volume ?? 0.8, s = options.seconds ?? 1.5; @@ -1327,6 +1344,8 @@ export interface RenderOptions { readonly master?: (mix: Clip) => Clip; /** LUFS the mix is brought to before the limiter (`Clip.loudness`): −16 for a piano on its own, −14 a band. */ readonly loudness?: number; + /** A performance's parts to mix, by name — the rest left out: stems, a melody apart from what is under it. */ + readonly parts?: readonly string[]; } /** The parts of a mix as `render` adds them up: each part, and what it sends to the shared reverb. */ @@ -1347,11 +1366,14 @@ function mixPerformance(p: Performance, rate: number, options: RenderOptions): C if (!inside) throw new Error("render() takes a performance made by music.perform."); const parts: { clip: Clip; at: number }[] = [], sends: { clip: Clip; at: number }[] = []; const done = new Set(); - for (const { part } of inside.parts) { + const only = options.parts; + if (only) for (const k of only) if (!inside.parts.some((x) => x.name === k)) throw new Error(`render(): the performance has no part ${JSON.stringify(k)}: its parts are ${inside.parts.map((x) => x.name).join(", ")}.`); + for (const { name: first, part } of inside.parts) { + if (only && !only.includes(first)) continue; const inst = part.instrument; if (done.has(inst)) continue; done.add(inst); - const names = inside.parts.filter((x) => x.part.instrument === inst).map((x) => x.name); + const names = inside.parts.filter((x) => x.part.instrument === inst && (!only || only.includes(x.name))).map((x) => x.name); const own = p.notes.filter((n) => names.includes(n.part)); if (own.length === 0) continue; const pedal = inside.pedal.get(inst) ?? []; @@ -1368,7 +1390,10 @@ function mixPerformance(p: Performance, rate: number, options: RenderOptions): C parts.push({ clip, at: 0 }); if ((part.reverb ?? 0) > 0) sends.push({ clip: clip.gain(part.reverb ?? 0), at: 0 }); } - if (parts.length === 0) throw new Error("render(): the performance plays no notes."); + if (parts.length === 0) { + if (only) return mixdown([{ clip: noise(0.01, { volume: 0, rate }), at: 0 }], p.seconds || 0.01, rate); + throw new Error("render(): the performance plays no notes."); + } return withReverb(parts, sends, p.seconds, rate, options.reverb); } @@ -1736,6 +1761,6 @@ export const loop = game(async (s: Song) => { /** Everything above as one name: import { music } from "trigscript/music"; music.play(song). */ export const music = { - sampler, sampled, perform, excerpt, hits, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop, + sampler, sampled, perform, excerpt, hits, sweep, synth, fmSynth, strings, presets, drums, kit, track, song, render, play, loop, part, section, arrange, transpose, stretch, repeat, beat, chord, over, chords, bars, pump, riser, impact, midi, stems, conduct, }; diff --git a/tests/sampled.test.ts b/tests/sampled.test.ts index e35bf38..3b60e0f 100644 --- a/tests/sampled.test.ts +++ b/tests/sampled.test.ts @@ -9,7 +9,7 @@ import { describe, expect, it } from "vitest"; import { compileScript, type CompileResult } from "../compiler/compiler"; import { defaultScriptNames } from "../compiler/names"; import { defaultLib } from "../bundle/lib.mjs"; -import { clipChannels, decodeAdpcm, makeClip, tone } from "../compiler/sound"; +import { clipChannels, decodeAdpcm, makeClip, silence, tone } from "../compiler/sound"; import { describeSamples, readSamples, writeSamples, type ZoneData } from "../compiler/samples"; const LIB = defaultLib(); @@ -258,6 +258,33 @@ describe("music.hits and the trailer presets", () => { }); }); +describe("melody first: ducking, stems, the trance presets", () => { + it("ducks a pad by the lead's own envelope: down while the lead sounds, back when it stops", () => { + const rate = 22050, pad = tone(220, 3, { volume: 0.5, rate }), lead = tone(880, 1, { volume: 0.5, rate }); + const ducked = clipChannels(pad.duck(lead.then(silence(2, { rate })), { depth: 6, threshold: -30 }))[0]; + const during = rms(ducked, 0.4, 0.8, rate), after = rms(ducked, 2.0, 2.5, rate); + expect(20 * Math.log10(during / after)).toBeCloseTo(-6, 0); + }); + + it("renders only the parts asked for, and a sweep and the trance presets are clips of their lengths", () => { + const r = run(` + const take = music.perform({ meter: "4/4", bpm: 120 }, { + lead: { instrument: music.presets.trance(), notes: "E5/4 D#5 E5 B4" }, + arp: { instrument: music.presets.arp(), notes: "A3/16 C4 E4 A4 r/4. r/2" }, + stab: { instrument: music.presets.stab(), notes: "A3+C4+E4/8 r/4. r/2" }, + }); + const lead = music.render(take, { parts: ["lead"], limit: false }), rest = music.render(take, { parts: ["arp", "stab"], limit: false }); + const all = music.render(take, { limit: false }); + if (Math.abs(mixdown([{ clip: lead, at: 0 }, { clip: rest, at: 0 }]).lufs - all.lufs) > 0.2) fail(\`\${lead.lufs} \${rest.lufs} \${all.lufs}\`); + const s = music.sweep(2), d = music.sweep(1, { down: true }); + if (Math.abs(s.seconds - 2) > 0.01 || Math.abs(d.seconds - 1) > 0.01) fail("sweep"); + let refused = ""; + try { music.render(take, { parts: ["bass"] }); } catch (e) { refused = String(e); } + if (!/no part "bass"/.test(refused)) fail(refused);`); + expect(errors(r)).toEqual([]); + }); +}); + describe("loudness and sympathy", () => { it("measures a full-scale 997 Hz sine at −3.01 LUFS on one side, 0 from both (as the game plays one channel), and brings a clip to a loudness", () => { const sine = tone(997, 3, { volume: 1, rate: 48000 }); From c61523d8419fa8ea9c10c7742267f9c2a7903fc3 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 07:22:15 -0600 Subject: [PATCH 27/31] scripts/lead-check.mts: does the melody stand out, bar by bar The melody and everything else rendered apart, the same mix at the same places, and for each bar where the melody plays (parts whose role is lead or lead-synth, from the timeline), how much louder it is than the rest in its own range: from 0.85 of its median note's fundamental to 5 kHz, energy over the bar in Hann-windowed FFT frames. Prints each section's lowest and median and the bars under --want (6 dB); exits 1 when a bar is under it. Made to hold the trance remix to "the melody first". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- scripts/lead-check.mts | 75 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 scripts/lead-check.mts diff --git a/scripts/lead-check.mts b/scripts/lead-check.mts new file mode 100644 index 0000000..4d0fcd4 --- /dev/null +++ b/scripts/lead-check.mts @@ -0,0 +1,75 @@ +/** + * Whether a melody stands out: the melody and everything else rendered apart (the same mix, the same places), and for + * each bar where the melody plays, how much louder it is than the rest in its own range — from just under the + * melody's fundamental (its median note's, at 0.85) to 5 kHz, where its notes and their presence are. The energy of + * each over the bar (Hann-windowed FFT frames of 4096, half overlapping), as a ratio in dB. + * + * npx tsx scripts/lead-check.mts [--want=6] [--floor=4] [--all] + * + * The timeline is a module as probes/lib/fur-elise-timeline-gen.mts writes one: NOTES, ROLES (the melody's parts + * are "lead" and "lead-synth"), BARS and SECTIONS. Prints each section's lowest and median ratio and every bar under + * `want`; exits 1 when a bar is under `want` (6 dB) or any is under `floor` (4). Needs ffmpeg. + */ +import { execFileSync } from "node:child_process"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +const args = process.argv.slice(2); +const flag = (n: string) => args.find((a) => a.startsWith(`--${n}=`))?.slice(n.length + 3); +const [melodyFile, restFile, timeline] = args.filter((a) => !a.startsWith("--")); +if (!melodyFile || !restFile || !timeline) { console.error("usage: lead-check [--want=6] [--floor=4] [--all]"); process.exit(2); } +const WANT = Number(flag("want") ?? 6), FLOOR = Number(flag("floor") ?? 4), RATE = 48000, N = 4096, TOP = 5000; +const read = (f: string) => { const b = execFileSync("ffmpeg", ["-v", "error", "-i", resolve(f), "-ac", "1", "-ar", String(RATE), "-f", "f32le", "-"], { maxBuffer: 1 << 30 }); return new Float32Array(b.buffer, b.byteOffset, b.byteLength / 4); }; +const melody = read(melodyFile), rest = read(restFile); +const t = await import(pathToFileURL(resolve(timeline)).href) as { NOTES: readonly (readonly number[])[]; ROLES: readonly string[]; BARS: readonly number[]; SECTIONS: readonly { name: string; bar: number }[] }; +const isMelody = (part: number) => t.ROLES[part] === "lead" || t.ROLES[part] === "lead-synth"; + +function fft(re: Float64Array, im: Float64Array) { + const n = re.length; + for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } } + for (let len = 2; len <= n; len <<= 1) { + const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang); + for (let i = 0; i < n; i += len) { + let cr = 1, ci = 0; + for (let j = 0; j < len / 2; j++) { + const a = i + j, b = a + len / 2, vr = re[b] * cr - im[b] * ci, vi = re[b] * ci + im[b] * cr; + re[b] = re[a] - vr; im[b] = im[a] - vi; re[a] += vr; im[a] += vi; + const q = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = q; + } + } + } +} +/** Energy of `x` between `lo` and `hi` Hz over [a, b) seconds. */ +function band(x: Float32Array, a: number, b: number, lo: number, hi: number): number { + const kl = Math.max(1, Math.floor((lo * N) / RATE)), kh = Math.min(N / 2, Math.ceil((hi * N) / RATE)); + let e = 0; + for (let s = Math.round(a * RATE); s + N <= Math.round(b * RATE) && s + N <= x.length; s += N / 2) { + const re = new Float64Array(N), im = new Float64Array(N); + for (let i = 0; i < N; i++) re[i] = x[s + i] * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N)); + fft(re, im); + for (let k = kl; k <= kh; k++) e += re[k] * re[k] + im[k] * im[k]; + } + return e; +} + +const sectionOf = (bar: number) => { let s = t.SECTIONS[0]; for (const x of t.SECTIONS) if (x.bar <= bar) s = x; return s.name; }; +const rows: { bar: number; section: string; db: number; lo: number }[] = []; +for (let bar = 0; bar + 1 < t.BARS.length; bar++) { + const a = t.BARS[bar], b = t.BARS[bar + 1]; + const notes = t.NOTES.filter((n) => isMelody(n[4]) && n[0] < b && n[1] > a); + if (!notes.length || b - a < (N / RATE) * 1.5) continue; + const f0 = notes.map((n) => 440 * 2 ** ((n[2] - 69) / 12)).sort((x, y) => x - y), lo = 0.85 * f0[Math.floor(f0.length / 2)]; + const em = band(melody, a, b, lo, TOP), er = band(rest, a, b, lo, TOP); + rows.push({ bar, section: sectionOf(bar), db: 10 * Math.log10((em + 1e-12) / (er + 1e-12)), lo }); +} +const median = (xs: number[]) => { const s = [...xs].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; }; +let fails = 0; +for (const name of [...new Set(rows.map((r) => r.section))]) { + const r = rows.filter((x) => x.section === name), dbs = r.map((x) => x.db), under = r.filter((x) => x.db < WANT); + fails += under.length; + console.log(`${name.padEnd(12)} ${String(r.length).padStart(3)} bars: lowest ${Math.min(...dbs).toFixed(1).padStart(5)} dB, median ${median(dbs).toFixed(1).padStart(5)} dB${under.length ? `, under ${WANT}: ${under.map((x) => `bar ${x.bar} ${x.db.toFixed(1)}`).join(", ")}` : ""}`); + if (args.includes("--all")) for (const x of r) console.log(` bar ${x.bar}: ${x.db.toFixed(1)} dB (from ${x.lo.toFixed(0)} Hz)`); +} +const all = rows.map((r) => r.db); +console.log(`${rows.length} bars with the melody: lowest ${Math.min(...all).toFixed(1)} dB, median ${median(all).toFixed(1)} dB; ${fails} under ${WANT} dB, ${rows.filter((r) => r.db < FLOOR).length} under ${FLOOR}.`); +process.exitCode = fails ? 1 : 0; From 7afff896654ccc352e31bf51c2730362d6113ed2 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 07:22:15 -0600 Subject: [PATCH 28/31] =?UTF-8?q?S7:=20F=C3=BCr=20Elise,=20the=20trance=20?= =?UTF-8?q?remix=20=E2=80=94=20the=20piano=20into=20a=20synth=20remix,=20t?= =?UTF-8?q?he=20melody=20first?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The piano alone in 3/8 (bars 1 … 8, free), a sweep and a crash reversed, then a remix in 4/4 at 128: the theme reshaped as dance covers do (each 3/8 bar half a bar of 4/4, the turn as running sixteenths) on a trance lead over the piano; the F major episode as a breakdown; a build; the storm as the biggest drop (the drumming A as the bass, the diminished chords as stabs); the arpeggios and the run; the theme in full; then the last bars and the held A on the piano alone. 2:34.8. The melody first, measured: each section mixed as melody, harmony (dipped where the melody sits, ducked 6 dB by its envelope), effects (dipped, ducked) and rhythm, the ducking keyed from the whole melody so tails go down too. lead-check: all 75 bars with the melody at 6.9 dB or more over the rest in its range, medians 14 … 18 dB. −11.8 LUFS integrated, drops −10.8 … −11.1, the piano's ends −20; −1.3 dBTP decoded; the limiter at most 3.8 dB. Tuning: 41 pitches, none off. probes/lib/fur-elise-remix-timeline.ts puts the three performances together with roles, sections with a kind, DROPS and HITS; the timeline generator takes --remix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 42 + probes/fur-elise-remix.ts | 25 + probes/lib/fur-elise-remix-score.ts | 287 ++ probes/lib/fur-elise-remix-timeline.ts | 4878 ++++++++++++++++++++++++ probes/lib/fur-elise-remix.ts | 144 + probes/lib/fur-elise-timeline-gen.mts | 53 +- 6 files changed, 5415 insertions(+), 14 deletions(-) create mode 100644 probes/fur-elise-remix.ts create mode 100644 probes/lib/fur-elise-remix-score.ts create mode 100644 probes/lib/fur-elise-remix-timeline.ts create mode 100644 probes/lib/fur-elise-remix.ts diff --git a/docs/v4-plan.md b/docs/v4-plan.md index 26c9f9f..1912a87 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6684,6 +6684,48 @@ in e67671d). Chosen: a cinematic hybrid — piano, orchestra, big percussion, sy **Open:** the user's ears. The final statement is dense (LRA 1.0) — a wall of sound by design, maybe too much; the storm's hits are limited hard. Previews: Maps/TrigScript/fur-elise-sound-preview/cinematic/. +#### S7 the synth remix (built 2026-11-09) + +The user on the cinematic version: "the background is overshadowing the melody … having it start with the piano and +going into a louder synth remix would be cool" — trance, 4/4. The diagnosis held: the piano shared its range with the +ostinatos, the supersaw doubling and the pads, and nothing made room for it. So the melody first, as a measured +requirement. + +- **The form** (`probes/lib/fur-elise-remix-score.ts`; frames at 42 ms): intro 0:00 (0) — the piano alone, bars 1 … 8 + in 3/8, free, a quiet pad, a noise sweep and a crash reversed into …; drop 1 0:13.1 (312) — 128 a minute, 4/4: the + theme reshaped as dance covers do (each 3/8 bar half a bar, the turn's pickup folded in: E D# E D# E B D C), twice, + the middle part, the theme again; breakdown 1 0:41.2 (981) — the F major episode's tune on the piano over pads; + build 1 0:48.7 (1160) — the E–D# over E, a snare roll, a riser, the suck-in; drop 2 0:56.2 (1338) — the storm: the + drumming A as a sixteenth bass, its diminished chords as stabs, its line on the lead; breakdown 2 1:26.2 (2053) — the + arpeggios on the piano; build 2 1:33.7 (2231) — the chromatic run, the E–D#; drop 3 1:41.2 (2410) — the theme in + full; ending 2:12.4 (3153) — after a breath, bars 19 … 21 and the held A on the piano alone. 2:34.8 with the tail. +- **The palette:** the trance lead (seven saws, a glide, a dotted-eighth ping-pong) an octave over the piano, which + doubles it as written, and a square lead an octave down in drops 2 and 3; plucked arpeggios and supersaw stabs, + pads, rolling bass (lowpassed at 700 Hz) and sub, all pumped by the beat; the library's kick, clap, hats and snare; + a VSCO crash, violas swelling into the drops, timpani in the storm; impacts, risers, sweeps. +- **Melody first:** each section mixed as four stems — the melody (lead, its lower octave, piano), the harmony (pads, + stabs, arpeggios, strings, the piano's left hand: dipped −5 dB at 1.8 kHz and −3 at 3.5, ducked 6 dB by the melody's + own envelope), the effects (crash, impacts, risers, clap, snare, open hats: dipped, ducked 6), the rhythm. The + ducking keyed from the whole melody, so a section's tail goes down under the next one's melody too; sweeps and the + suck-in high-passed above the melody's range. `scripts/lead-check.mts` (new) measures the melody against the rest in + its range bar by bar: every one of 75 bars ≥ 6.9 dB; lowest / median per section — intro 7.7 / 14.1, drop 1 15.5 / + 18.3, breakdown 1 9.1 / 14.3, build 1 7.9 / 17.7, drop 2 10.3 / 16.2, breakdown 2 10.8 / 14.4, build 2 13.7 / 15.2, + drop 3 10.4 / 15.5, ending 6.9 / 16.9. (Before: 17 bars under 6, the worst −11.8 — the suck-in, the tails, the crash.) +- **Loudness:** each section to its target, the whole limited once (to 0.8): −11.8 LUFS integrated; drops −11.1, + −10.8, −11.0 (short-term −10.5 … −11); breakdowns −15, builds −13, intro and ending −20; true peak −1.3 dBTP decoded. + The limiter takes at most 3.8 dB (drop 2), after the kick, the timpani and the storm bass's accents came down (5.4 + before). 3.5 MB at q6. +- **Library:** `Clip.duck(key)`, `render(…, { parts })`, presets trance / arp / stab, `music.sweep`. +- **Tuning:** 41 pitches checked, none off; 8 under 80 Hz not judged. +- **Timeline:** `probes/lib/fur-elise-remix-timeline.ts` — the three performances put together: PARTS, ROLES ("lead" + for the piano's right hand and the lead synth, "lead-synth" its lower octave, "accomp" the left hand, "arp", "synth", + "pad", "strings", "bass", drums, "cymbal", "impact", "riser"), SECTIONS with a kind (intro, drop, breakdown, build, + ending), DROPS, HITS (drops' downbeats at strength 1), BARS (3/8 bars, then 4/4, then 3/8: BEAT is in each one's own + beats). `probes/lib/fur-elise-remix.ts` renders, `probes/fur-elise-remix.ts` plays (M and R the stems). + +**Open:** the user's ears: whether the lead is too far on top now (medians 15 … 18 dB in the drops), whether the 4/4 +reshaping still reads as Für Elise, the drops' level. + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice diff --git a/probes/fur-elise-remix.ts b/probes/fur-elise-remix.ts new file mode 100644 index 0000000..fe48941 --- /dev/null +++ b/probes/fur-elise-remix.ts @@ -0,0 +1,25 @@ +// Für Elise, the trance remix (S7, 2026-11-09): plays the whole piece; keys 1 … 9 play a section's clip on its own; +// M and R the melody and the rest apart (what scripts/lead-check.mts measures). The render is probes/lib/ +// fur-elise-remix.ts; the timeline, probes/lib/fur-elise-remix-timeline.ts (probes/lib/fur-elise-timeline-gen.mts --remix). +// +// npx tsx scripts/sound-dump.mts probes/fur-elise-remix.ts +import { whole, sectionClips, melodyStem, restStem } from "./lib/fur-elise-remix"; + +program(async () => { + displayText("\x04Für Elise, the remix: the whole piece. Keys 1-9 play a section on its own."); + playWav(whole, 0); + while (true) { + if (keyPressed(P1, "1")) playWav(sectionClips[0], 0); + if (keyPressed(P1, "2")) playWav(sectionClips[1], 0); + if (keyPressed(P1, "3")) playWav(sectionClips[2], 0); + if (keyPressed(P1, "4")) playWav(sectionClips[3], 0); + if (keyPressed(P1, "5")) playWav(sectionClips[4], 0); + if (keyPressed(P1, "6")) playWav(sectionClips[5], 0); + if (keyPressed(P1, "7")) playWav(sectionClips[6], 0); + if (keyPressed(P1, "8")) playWav(sectionClips[7], 0); + if (keyPressed(P1, "9")) playWav(sectionClips[8], 0); + if (keyPressed(P1, "M")) playWav(melodyStem, 0); + if (keyPressed(P1, "R")) playWav(restStem, 0); + await nextFrame(); + } +}); diff --git a/probes/lib/fur-elise-remix-score.ts b/probes/lib/fur-elise-remix-score.ts new file mode 100644 index 0000000..b20bec1 --- /dev/null +++ b/probes/lib/fur-elise-remix-score.ts @@ -0,0 +1,287 @@ +// Für Elise as a trance remix (asked 2026-11-09): the theme's first phrase on the piano alone (3/8, free in time), then +// a remix in 4/4 at 128 beats a minute, then the last bars on the piano alone again. The theme reshaped into 4/4 as +// dance covers do — each 3/8 bar of the score half a bar of 4/4: the E–D# turn as running sixteenths (its pickup folded +// in: E D# E D# E B D C), the long notes longer — so it sits on 4- and 8-bar phrases. Every note from the public-domain +// score (probes/lib/fur-elise-score.ts); the reshaping and every other part ours. +// +// The remix, by bar (4/4): +// drop 1 0 … 15 the theme on the lead, the piano with it: twice, the middle part, the theme again +// breakdown 1 16 … 19 the F major episode's tune on the piano over pads +// build 1 20 … 23 the E–D# over E, a snare roll, a riser and a sweep, a bar's silence before … +// drop 2 24 … 39 the storm: the drumming A as the bass, its diminished chords as stabs, its line on the lead +// breakdown 2 40 … 43 the arpeggios on the piano over a pad +// build 2 44 … 47 the chromatic run, the E–D# again, a riser +// drop 3 48 … 63 the theme in full, its last bar the band's last hit +// Written as steps, a sixteenth each: a note ("E5", a chord "A3+C4+E4", "@96" its velocity), "-" holds it, "." rests. +import { A_RIGHT, A_LEFT, A_TEMPO } from "./fur-elise-score"; + +export type Role = "lead" | "lead-synth" | "accomp" | "arp" | "pluck" | "strings" | "brass" | "bass" | "synth" | "pad" | "drum-low" | "drum-high" | "cymbal" | "impact" | "riser"; + +/** The remix's parts and their roles; the melody's parts ("lead") are what the rest makes room for. */ +export const REMIX_ROLES = { + piano: "lead", pianoLH: "accomp", lead: "lead", leadLow: "lead-synth", + arp: "arp", stabs: "synth", pad: "pad", strings: "strings", bass: "bass", sub: "bass", + kick: "drum-low", timpani: "drum-low", clap: "drum-high", hats: "drum-high", snare: "drum-high", openHats: "cymbal", crash: "cymbal", + impacts: "impact", risers: "riser", +} as const satisfies Record; +export type RemixPart = keyof typeof REMIX_ROLES; +/** What the melody is: the parts mixed apart, ducking the rest. */ +export const MELODY: readonly RemixPart[] = ["piano", "lead", "leadLow"]; +/** What is harmony under it: ducked by it, its range dipped. */ +export const HARMONY: readonly RemixPart[] = ["pianoLH", "arp", "stabs", "pad", "strings"]; +/** The effects and the drums in its range (crash, impacts, risers, clap, snare, open hats): ducked a little, dipped. */ +export const EFFECTS: readonly RemixPart[] = ["crash", "impacts", "risers", "clap", "snare", "openHats"]; + +/* ── Steps to the notation `perform` reads ── */ + +const LENGTHS: readonly [number, string][] = [[16, "1"], [12, "2."], [8, "2"], [6, "4."], [4, "4"], [3, "8."], [2, "8"], [1, "16"]]; +/** A run of `n` sixteenths as lengths, longest first. */ +const pieces = (n: number) => { const out: string[] = []; for (const [k, l] of LENGTHS) while (n >= k) { out.push(l); n -= k; } return out; }; +const NOTE = /^([A-G][#b]?-?\d)$/; +const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "Bb", "B"]; +const SEMI: Readonly> = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 }; +const num = (n: string) => { const m = /^([A-G])([#b]?)(-?\d)$/.exec(n)!; return 12 * (Number(m[3]) + 1) + SEMI[m[1]] + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0); }; +const nm = (k: number) => NAMES[((k % 12) + 12) % 12] + (Math.floor(k / 12) - 1); +/** A bar of steps (16, a sixteenth each) as notation, every pitch moved `by` semitones; a held note tied across lengths. */ +export function steps(bar: string, by = 0): string { + // A dynamic before the first step passes through as it is. + const all = bar.split(/\s+/).filter((w) => w && w !== "|"), mark = /^(ppp|pp|p|mp|mf|f|ff|fff)$/.test(all[0]) ? `${all.shift()} ` : ""; + const words = all; + if (words.length !== 16) throw new Error(`a bar of 4/4 is 16 steps, not ${words.length}: ${bar}`); + const out: string[] = []; + for (let i = 0; i < 16;) { + const w = words[i]; + let n = 1; + while (i + n < 16 && words[i + n] === "-") n++; + if (w === "." || w === "-") { + let r = n; // a rest (or a hold with nothing before it in the bar: a rest too) + while (i + r < 16 && words[i + r] === ".") r++; + for (const l of pieces(r)) out.push(`r/${l}`); + i += r; + continue; + } + const [body, vel] = w.split("@"); + const notes = body.split("+").map((x) => { if (!NOTE.test(x)) throw new Error(`no note ${x} in ${bar}`); return nm(num(x) + by); }).join("+"); + pieces(n).forEach((l, k, all) => out.push(`${notes}/${l}${k === 0 && vel ? `@${vel}` : ""}${k < all.length - 1 ? "~" : ""}`)); + i += n; + } + return mark + out.join(" "); +} + +/* ── Harmony ── */ + +const PC: Readonly> = { C: 0, "C#": 1, D: 2, "D#": 3, Eb: 3, E: 4, F: 5, "F#": 6, G: 7, "G#": 8, A: 9, Bb: 10, B: 11 }; +const KINDS: Readonly> = { "": [0, 4, 7], m: [0, 3, 7], "7": [0, 4, 7, 10], dim: [0, 3, 6, 9] }; +function chord(sym: string, octave: number): number[] { + const m = /^([A-G][#b]?)(m|7|dim)?$/.exec(sym); + if (!m) throw new Error(`no chord ${sym}`); + const root = 12 * (octave + 1) + PC[m[1]]; + return KINDS[m[2] ?? ""].map((i) => root + i); +} + +/* ── The theme in 4/4 ── */ + +const T1 = "E5 D#5 E5 D#5 E5 B4 D5 C5 A4 - - C4 E4 A4 - -"; +const T2 = "B4 - - E4 G#4 B4 - - C5 - - E4 E5 - - -"; +const T4A = "B4 - - E4 C5 B4 - - A4 - - - - - - -"; +const T4B = "B4 - - E4 C5 B4 - - A4 - - B4 C5 D5 - -"; +const M5 = "E5 - - G4 F5 E5 - - D5 - - F4 E5 D5 - -"; +const M6 = "C5 - - E4 D5 C5 - - B4 - - E4 E5 - E5 E6"; +const M7 = "E6 - - - D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5 -"; +const T_H: readonly (readonly [string, string])[] = [["E", "Am"], ["E", "Am"], ["E", "Am"], ["E", "Am"]]; +/** The drop's sixteen bars of melody and their chords, a chord a half bar; the last bar left for a fill. */ +const DROP = [T1, T2, T1, T4A, T1, T2, T1, T4B, M5, M6, M7, T1, T2, T1, T4A, "A4 - - - - - - - . . . . . . . ."]; +const DROP_H: readonly (readonly [string, string])[] = [...T_H, ...T_H, ["C", "G"], ["Am", "E"], ["E", "E"], ...T_H, ["Am", "Am"]]; + +/** The episode's tune (B1 … B7) in 4/4, and its chords. */ +const EPISODE = [ + "C5 - - - F5 - E5 - E5 - D5 - Bb5 - A5 -", + "A5 G5 F5 E5 D5 C5 - - Bb4 - A4 - A4 G4 A4 Bb4", + "C5 - - - D5 - D#5 - E5 - - E5 F5 - A4 -", + "C5 - - - D5 - B4 - C5 - - - - - - -", +]; +const EPISODE_H: readonly (readonly [string, string])[] = [["F", "Bb"], ["C7", "F"], ["F", "Am"], ["G7", "C"]]; +/** The build: the E–D# over E, the last bar silence before the drop. */ +const BUILD = [ + "E5 F5 E5 D#5 E5 B4 E5 D#5 E5 B4 E5 D#5 E5 F5 E5 D#5", + "E5 F5 E5 D#5 E5 B4 E5 D#5 E5 B4 E5 D#5 E5 F5 E5 D#5", + "E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5", + "E5 - - - . . . . . . . . . . . .", +]; +/** The storm in 4/4: a chord a bar (C1 … C16), its line for the lead, its bass. */ +const STORM_H = ["A", "Dm", "E", "Am", "Dm", "D#dim", "E", "Am", "A", "Dm", "Dm", "Bb", "Eb", "Bb", "E", "Am"]; +const STORM_CHORDS = ["E4+G4+Bb4+C#5", "F4+A4+D5", "G#4+D5+F5", "A4+C5+E5", "F4+D5", "C4+F#4+A4", "C4+E4+A4", "C4+A4", "E4+G4+Bb4+C#5", "F4+A4+D5", "D5+F5", "D5+F5", "G4+Eb5", "D4+F4+Bb4", "D4+F4+G#4", "C4+E4+A4"]; +const STORM_LINE = [ + "C#5 - - - - - - - - - - - - - - -", "D5 - - - - - - - - - - - E5 - F5 -", "F5 - - - - - - - F5 - - - - - - -", "E5 - - - - - - - - - - - - - - -", + "D5 - - - - - - - - - - - C5 - B4 -", "A4 - - - - - - - A4 - - - - - - -", "A4 - - - - C5 - - - - B4 - - - - -", "A4 - - - - - - - - - - - - - - -", + "C#5 - - - - - - - - - - - - - - -", "D5 - - - - - - - - - - - E5 - F5 -", "F5 - - - - - - - F5 - - - - - - -", "F5 - - - - - - - - - - - - - - -", + "Eb5 - - - - - - - - - - - D5 - C5 -", "Bb4 - - - - - - - A4 - - - - - - -", "G#4 - - - - - - - G#4 - - - - - - -", "A4 - - - - - - - - - - - - - - -", +]; +const STORM_BASS = ["A1", "A1", "A1", "A1", "D2", "D#2", "E2", "A1", "A1", "A1", "A1", "Bb1", "Bb1", "Bb1", "B1", "A1"]; +/** The arpeggios (P1 … P3) in 4/4 sixteenths, then the run down and the E–D# into the final drop. */ +const ARPS = [ + "A3 C4 E4 A4 C5 E5 A5 E5 C5 A4 E4 C4 A3 C4 E4 A4", + "A4 C5 E5 A5 C6 E6 A6 E6 C6 A5 E5 C5 A4 C5 E5 A5", + "F3 A3 C4 F4 A4 C5 F5 C5 A4 F4 C4 A3 F3 A3 C4 F4", + "E3 G#3 B3 E4 G#4 B4 E5 B4 G#4 E4 B3 G#3 E3 G#3 B3 E4", +]; +const ARPS_H: readonly (readonly [string, string])[] = [["Am", "Am"], ["Am", "Am"], ["F", "F"], ["E", "E"]]; +const RUN = [ + "Bb5 A5 G#5 G5 F#5 F5 E5 D#5 D5 C#5 C5 B4 Bb4 A4 G#4 G4", + "F#4 F4 E4 F4 F#4 G4 G#4 A4 Bb4 B4 C5 C#5 D5 D#5 E5 F5", + "E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5 E5 D#5", + "E5 - - - . . . . . . . . . . . .", +]; + +/* ── Generated parts, a bar of 16 steps from a bar's two chords ── */ + +const v = (x: number) => `@${Math.max(1, Math.min(127, Math.round(x)))}`; +/** Rolling bass: off the beat, three sixteenths of each beat on the root (the kick takes the first). */ +const rolling = ([a, b]: readonly [string, string], loud = 0) => { + const r = (s: string) => nm(chord(s, 2)[0]); + return [a, a, b, b].map((c) => `. ${r(c)}${v(96 + loud)} ${r(c)}${v(82 + loud)} ${r(c)}${v(88 + loud)}`).join(" "); +}; +/** The plucked arpeggio: up and down the chord in sixteenths, octave 4 and 5 — under the lead, a register it leaves room in. */ +const arpBar = ([a, b]: readonly [string, string], loud = 0) => [a, b].map((c) => { + const n = chord(c, 3), up = [n[0], n[1], n[2], n[0] + 12, n[1] + 12, n[2] + 12, n[0] + 12, n[2]]; + return up.map((x, k) => `${nm(x)}${v((k % 4 === 0 ? 92 : 72) + loud)}`).join(" "); +}).join(" "); +/** Chords held a half bar each (pads), or struck on the dance's 3-3-2 (stabs). */ +const padBar = ([a, b]: readonly [string, string], octave = 3, loud = 0) => [a, b].map((c) => `${chord(c, octave).slice(0, 3).map(nm).join("+")}${v(86 + loud)} - - - - - - -`).join(" "); +const stabBar = ([a, b]: readonly [string, string], loud = 0) => [a, b].map((c) => { const n = chord(c, 3).slice(0, 3).map(nm).join("+"); return `${n}${v(100 + loud)} - . ${n}${v(84 + loud)} - . ${n}${v(92 + loud)} -`; }).join(" "); +const subBar = ([a, b]: readonly [string, string]) => [a, b].map((c) => `${nm(chord(c, 1)[0])}@90 - - - - - - -`).join(" "); +const REST = ". . . . . . . . . . . . . . . ."; + +/* ── The dance kit (hits: C2 kick, D2 snare, D#2 clap, F#2 closed hat, A#2 open hat), and the crash (VSCO C#3) ── */ +const KICKS = "C2@112 . . . C2@108 . . . C2@110 . . . C2@108 . . ."; +const KICKS_HALF = "C2@105 . . . . . . . C2@100 . . . . . . ."; +const CLAPS = ". . . . D#2@100 . . . . . . . D#2@104 . . ."; +const OPEN = ". . A#2@88 . . . A#2@84 . . . A#2@88 . . . A#2@84 ."; +const HATS = "F#2@70 F#2@40 . F#2@48 F#2@64 F#2@40 . F#2@46 F#2@70 F#2@40 . F#2@48 F#2@64 F#2@40 . F#2@52"; +const FILL = "D2@70 D2@74 D2@78 D2@82 D2@86 D2@90 D2@94 D2@98 D2@102 D2@106 D2@110 D2@114 D2@118 D2@122 D2@124 D2@127"; +/** A snare roll over four bars, quarters to sixteenths, louder bar by bar. */ +const ROLL = [ + "D2@60 . . . D2@64 . . . D2@68 . . . D2@72 . . .", + "D2@74 . D2@76 . D2@78 . D2@80 . D2@82 . D2@84 . D2@86 . D2@88 .", + "D2@88 D2@90 D2@92 D2@94 D2@96 D2@98 D2@100 D2@102 D2@104 D2@106 D2@108 D2@110 D2@112 D2@114 D2@116 D2@118", + ". . . . . . . . . . . . . . . .", +]; + +export interface RemixSection { readonly name: string; readonly from: number; readonly to: number } + +export function remix() { + const parts = Object.fromEntries(Object.keys(REMIX_ROLES).map((k) => [k, [] as string[]])) as Record; + const sections: RemixSection[] = []; + let bars = 0; + const add = (name: string, n: number, given: Partial>) => { + for (const k of Object.keys(REMIX_ROLES) as RemixPart[]) { + const list = given[k] ?? Array.from({ length: n }, () => REST); + if (list.length !== n) throw new Error(`${name}: ${k} has ${list.length} bars, not ${n}.`); + parts[k].push(...list.map((b) => steps(b, k === "lead" ? 12 : 0))); + } + sections.push({ name, from: bars, to: bars + n }); + bars += n; + }; + const each = (h: readonly (readonly [string, string])[], f: (c: readonly [string, string], k: number) => string) => h.map((c, k) => f(c, k)); + const bar1 = (n: number, f: (k: number) => string) => Array.from({ length: n }, (_, k) => f(k)); + const phraseCrash = (n: number, at: readonly number[]) => bar1(n, (k) => (at.includes(k) ? "C#3@115 . . . . . . . . . . . . . . ." : REST)); + + // Drop 1: the theme on the lead (an octave up) and the piano (as written), the full groove; the middle part (bars + // 8 … 10) with the stabs out; bar 15 a fill and a sweep down. + add("drop 1", 16, { + piano: DROP.map((b, k) => (k === 0 ? `f ${b}` : b)), + lead: DROP.map((b, k) => (k === 0 ? `f ${b}` : b)), + arp: each(DROP_H, (c, k) => (k === 15 ? REST : arpBar(c, k >= 8 && k < 11 ? -10 : 0))), + stabs: each(DROP_H, (c, k) => (k >= 8 && k < 11 || k === 15 ? REST : stabBar(c))), + pad: each(DROP_H, (c) => padBar(c)), + bass: each(DROP_H, (c, k) => (k === 15 ? REST : rolling(c))), + sub: each(DROP_H, (c) => subBar(c)), + kick: bar1(16, (k) => (k === 15 ? KICKS_HALF : KICKS)), clap: bar1(16, (k) => (k === 15 ? REST : CLAPS)), + openHats: bar1(16, (k) => (k === 15 ? REST : OPEN)), hats: bar1(16, (k) => (k < 8 ? REST : HATS)), + snare: bar1(16, (k) => (k === 15 ? FILL : REST)), + crash: phraseCrash(16, [0, 8, 11]), + impacts: bar1(16, (k) => (k === 0 ? "C2@127 . . . . . . . . . . . . . . ." : REST)), + risers: bar1(16, (k) => (k === 15 ? "E2@100 . . . . . . . . . . . . . . ." : REST)), + }); + // Breakdown: the episode's tune on the piano, the left hand's chords, pads; no drums. + add("breakdown 1", 4, { + piano: EPISODE.map((b, k) => (k === 0 ? `mf ${b}` : b)), + pianoLH: each(EPISODE_H, ([a, b]) => [a, b].map((c) => { const n = chord(c, 3); return `${nm(n[0] - 12)}@64 ${nm(n[0])}@52 ${nm(n[1])}@50 ${nm(n[2])}@52 ${nm(n[1])}@48 ${nm(n[2])}@50 ${nm(n[0] + 12)}@52 ${nm(n[2])}@48`; }).join(" ")), + pad: each(EPISODE_H, (c) => padBar(c, 3, -8)), sub: each(EPISODE_H, (c) => subBar(c)), + crash: ["C#3@80 . . . . . . . . . . . . . . .", REST, REST, REST], + }); + // Build: the E–D# on the lead over E, a snare roll, the kick doubling up, a riser and a sweep; the last bar silent + // but for the riser's top and a crash reversed (the suck-in) into the drop. + const E: readonly [string, string] = ["E", "E"]; + add("build 1", 4, { + lead: BUILD.map((b, k) => (k === 0 ? `mf ${b}` : k === 2 ? `f ${b}` : b)), piano: BUILD.map((b, k) => (k === 0 ? `mf ${b}` : k === 2 ? `f ${b}` : b)), + arp: [arpBar(E, -14), arpBar(E, -8), arpBar(E, -2), REST], pad: [padBar(E, 3, -6), padBar(E, 3, -2), padBar(E, 3, 2), REST], + strings: [REST, "E3+B3+E4@60 - - - - - - - - - - - - - - -", "E3+G#3+B3+E4@90 - - - - - - - - - - - - - - -", REST], + bass: [rolling(E, -14), rolling(E, -8), REST, REST], sub: [subBar(E), subBar(E), subBar(E), REST], + kick: [KICKS_HALF, KICKS, "C2@110 . C2@100 . C2@110 . C2@100 . C2@112 . C2@104 . C2@115 . C2@108 .", REST], + snare: ROLL, + risers: ["G2@100 . . . . . . . . . . . . . . .", REST, REST, "F2@110 . . . . . . . . . . . . . . ."], + }); + // Drop 2, the storm, the biggest: the drumming A as a sixteenth bass, the diminished chords as stabs, its line on + // the lead and the piano, timpani on its strong bars. + const SH = STORM_H.map((c) => [c, c] as const); + add("drop 2", 16, { + lead: STORM_LINE.map((b, k) => (k === 0 ? `ff ${b}` : b)), piano: STORM_LINE.map((b, k) => (k === 0 ? `mf ${b}` : b)), + leadLow: STORM_LINE.map((b, k) => (k === 8 ? `f ${b}` : k > 8 ? b : REST)), + stabs: STORM_CHORDS.map((n) => `${n}@96 - . ${n}@80 - . ${n}@88 - ${n}@94 - . ${n}@80 - . ${n}@88 -`), + pad: each(SH, (c) => padBar(c, 3, -6)), + bass: STORM_BASS.map((r) => { const hi = nm(num(r) + 12); return Array.from({ length: 16 }, (_, k) => `${k % 2 ? hi : r}${v(k % 4 === 2 ? 96 : k % 4 === 0 ? 70 : 84)}`).join(" "); }), + sub: STORM_BASS.map((r) => `${nm(num(r) - 12 + 12)}@95 - - - - - - - - - - - - - - -`), + kick: bar1(16, () => KICKS), clap: bar1(16, () => CLAPS), openHats: bar1(16, () => OPEN), hats: bar1(16, () => HATS), + snare: bar1(16, (k) => (k === 7 || k === 15 ? FILL : REST)), + timpani: bar1(16, (k) => (k === 0 || k === 8 ? "A2@118 . . . . . . . . . . . . . . ." : k === 15 ? "E3@110 . . . . . . . A2@120 . . . . . . ." : REST)), + crash: phraseCrash(16, [0, 4, 8, 12]), + impacts: bar1(16, (k) => (k === 0 ? "C2@127 . . . . . . . . . . . . . . ." : k === 8 ? "C2@115 . . . . . . . . . . . . . . ." : REST)), + risers: bar1(16, (k) => (k === 15 ? "E2@100 . . . . . . . . . . . . . . ." : REST)), + }); + // Breakdown 2: the arpeggios on the piano over a pumping pad and a half-time kick. + add("breakdown 2", 4, { + piano: ARPS.map((b, k) => (k === 0 ? `mp ${b}` : b)), + pad: each(ARPS_H, (c) => padBar(c, 3, -6)), sub: each(ARPS_H, (c) => subBar(c)), + kick: bar1(4, () => KICKS_HALF), crash: ["C#3@70 . . . . . . . . . . . . . . .", REST, REST, REST], + }); + // Build 2: the run down and up on the lead and the piano, then the E–D#; the roll, a riser, the suck-in. + add("build 2", 4, { + lead: RUN.map((b, k) => (k === 0 ? `mf ${b}` : k === 2 ? `f ${b}` : b)), piano: RUN.map((b, k) => (k === 0 ? `mf ${b}` : k === 2 ? `f ${b}` : b)), + arp: [arpBar(E, -10), arpBar(E, -6), arpBar(E, -2), REST], pad: [padBar(["Am", "Am"], 3, -6), padBar(E, 3, -2), padBar(E, 3, 2), REST], + strings: ["A3+C4+E4@50 - - - - - - - - - - - - - - -", "E3+B3+E4@70 - - - - - - - - - - - - - - -", "E3+G#3+B3+E4@95 - - - - - - - - - - - - - - -", REST], + bass: [rolling(["Am", "Am"], -10), rolling(E, -6), REST, REST], sub: [subBar(["Am", "Am"]), subBar(E), subBar(E), REST], + kick: [KICKS_HALF, KICKS, "C2@110 . C2@100 . C2@110 . C2@100 . C2@112 . C2@104 . C2@115 . C2@108 .", REST], + snare: ROLL, + risers: ["G2@100 . . . . . . . . . . . . . . .", REST, REST, "F2@110 . . . . . . . . . . . . . . ."], + }); + // The final drop: the theme in full — the lead doubled an octave down from its middle part on — its last bar the + // band's last hit. + const FINAL = [...DROP.slice(0, 15), "A4@110 - - - . . . . . . . . . . . ."]; + add("drop 3", 16, { + piano: FINAL.map((b, k) => (k === 0 ? `f ${b}` : b)), lead: FINAL.map((b, k) => (k === 0 ? `ff ${b}` : b)), leadLow: FINAL.map((b, k) => (k === 8 ? `f ${b}` : k > 8 ? b : REST)), + arp: each(DROP_H, (c, k) => (k === 15 ? REST : arpBar(c, 2))), + stabs: each(DROP_H, (c, k) => (k === 15 ? `${chord("Am", 3).slice(0, 3).map(nm).join("+")}@115 - - - . . . . . . . . . . . .` : stabBar(c, 4))), + pad: each(DROP_H, (c, k) => (k === 15 ? REST : padBar(c))), strings: each(DROP_H, (c, k) => (k >= 8 && k < 15 ? padBar(c, 3, -10) : REST)), + bass: each(DROP_H, (c, k) => (k === 15 ? "A1@115 - - - . . . . . . . . . . . ." : rolling(c, 4))), + sub: each(DROP_H, (c, k) => (k === 15 ? "A1@100 - - - - - - - . . . . . . . ." : subBar(c))), + kick: bar1(16, (k) => (k === 15 ? "C2@120 . . . . . . . . . . . . . . ." : KICKS)), clap: bar1(16, (k) => (k === 15 ? REST : CLAPS)), + openHats: bar1(16, (k) => (k === 15 ? REST : OPEN)), hats: bar1(16, (k) => (k === 15 ? REST : HATS)), + snare: bar1(16, (k) => (k === 7 || k === 14 ? FILL : REST)), + timpani: bar1(16, (k) => (k === 15 ? "A2@120 . . . . . . . . . . . . . . ." : REST)), + crash: phraseCrash(16, [0, 8, 11]), + impacts: bar1(16, (k) => (k === 0 || k === 15 ? "C2@125 . . . . . . . . . . . . . . ." : REST)), + }); + return { parts, sections, bars, bpm: 128 }; +} + +/* ── The piano alone, before and after (3/8) ── */ + +/** The intro: the pickup and bars 1 … 7, then the A held (no second pickup: the drop's first bar is the turn). */ +export const INTRO_RIGHT = [...A_RIGHT.slice(0, 8), "A4/4.@+10"]; +export const INTRO_LEFT = [...A_LEFT.slice(0, 8), "ped A2/16@-10 E3@-14 A3@-14 r r/8"]; +export const INTRO_TEMPO: readonly (readonly [number, number])[] = [...A_TEMPO.filter(([x]) => x < 8), [8, 100], [8.67, 92]]; +/** The ending: bars 19 … 21 and the last A, held in the pedal, slowing. */ +export const OUTRO_RIGHT = ["mp " + A_RIGHT[19], A_RIGHT[20], "> " + A_RIGHT[21].replace(/^> /, ""), "ppp A4/4.@+8"]; +export const OUTRO_LEFT = ["p " + A_LEFT[19], A_LEFT[20], A_LEFT[21].replace(/^> /, ""), "ppp ped A1+A2/4. | r/4. | r/4. *"]; +export const OUTRO_TEMPO: readonly (readonly [number, number])[] = [[1, 120], [2, 112], [3, 98], [3.7, 80], [4, 70]]; diff --git a/probes/lib/fur-elise-remix-timeline.ts b/probes/lib/fur-elise-remix-timeline.ts new file mode 100644 index 0000000..6cb0cc8 --- /dev/null +++ b/probes/lib/fur-elise-remix-timeline.ts @@ -0,0 +1,4878 @@ +// Generated by probes/lib/fur-elise-timeline-gen.mts --remix from probes/fur-elise-remix.ts: do not edit, make it again. +// Für Elise (the trance remix: the piano's intro in 3/8, the remix in 4/4 at 128, the piano's ending in 3/8) as the soundtrack plays it (the whole piece as one clip, from 0). Seconds from its start; a frame is 42 ms +// (Fastest). The picture runs ahead of a long clip's sound by about 95 ms (the visualizer probe, 2026-11-09): the +// program shifts the picture, not these numbers. + +/** Seconds from the first note to the last let go (the held A's ring and the hall's tail come after). */ +export const SECONDS = 140.41; +/** The parts, by the number NOTES gives them. */ +export const PARTS = ["piano","pianoLH","lead","leadLow","arp","stabs","pad","strings","bass","sub","kick","timpani","clap","hats","snare","openHats","crash","impacts","risers"] as const; +/** + * Each part's role, by the same number: "lead" (the melody: the piano's right hand, the lead synth), "accomp" (the piano's left hand), + * "lead-synth" (the lead's octave below, doubling the melody), "arp" (the plucked arpeggios), "synth" (stabs), "pad", + * "strings", "bass" (rolling bass, sub), "drum-low" (kick, timpani), "drum-high" (clap, hats, snare), "cymbal" (open + * hats, crash), "impact", "riser" (risers, sweeps, crashes reversed). + */ +export const ROLES = ["lead","accomp","lead","lead-synth","arp","synth","pad","strings","bass","bass","drum-low","drum-low","drum-high","drum-high","drum-high","cymbal","cymbal","impact","riser"] as const; +/** The sections, in order — kind 'intro', 'drop', 'breakdown', 'build' or 'ending': the bar each begins on (BARS' numbering), and where, in seconds and frames. */ +export const SECTIONS: readonly { readonly name: string; readonly kind: string; readonly bar: number; readonly at: number; readonly frame: number }[] = [{"name":"intro","kind":"intro","bar":0,"at":0,"frame":0},{"name":"drop 1","kind":"drop","bar":9,"at":13.086,"frame":312},{"name":"breakdown 1","kind":"breakdown","bar":25,"at":41.215,"frame":981},{"name":"build 1","kind":"build","bar":29,"at":48.715,"frame":1160},{"name":"drop 2","kind":"drop","bar":33,"at":56.215,"frame":1338},{"name":"breakdown 2","kind":"breakdown","bar":49,"at":86.215,"frame":2053},{"name":"build 2","kind":"build","bar":53,"at":93.715,"frame":2231},{"name":"drop 3","kind":"drop","bar":57,"at":101.215,"frame":2410},{"name":"ending","kind":"ending","bar":73,"at":132.415,"frame":3153}]; +/** The drops' downbeats, [at, frame]: the biggest moments (strength 1 in HITS too). */ +export const DROPS: readonly (readonly [number, number])[] = [[13.086,312],[56.215,1338],[101.215,2410]]; +/** Seconds each bar begins: [0] the pickup's start, [k] bar k's. */ +export const BARS: readonly number[] = [0,0.53,2.017,3.481,4.969,6.543,8.043,9.543,11.184,13.086,13.09,14.965,16.84,18.715,20.59,22.465,24.34,26.215,28.09,29.965,31.84,33.715,35.59,37.465,39.34,41.215,43.09,44.965,46.84,48.715,50.59,52.465,54.34,56.215,58.09,59.965,61.84,63.715,65.59,67.465,69.34,71.215,73.09,74.965,76.84,78.715,80.59,82.465,84.34,86.215,88.09,89.965,91.84,93.715,95.59,97.465,99.34,101.215,103.09,104.965,106.84,108.715,110.59,112.465,114.34,116.215,118.09,119.965,121.84,123.715,125.59,127.465,129.34,132.415,132.428,133.981,135.697,137.839]; +/** The piano's sustain pedal: [down, up] in seconds. */ +export const PEDAL: readonly (readonly [number, number])[] = [ + [2.017,3.481], + [3.541,4.969], + [5.029,6.543], + [8.043,9.543], + [9.603,11.184], + [11.244,16.086], + [133.981,135.697], + [135.757,137.839], + [137.899,145.553], +]; +/** What NOTES' columns hold. */ +export const AT = 0, END = 1, PITCH = 2, VELOCITY = 3, PART = 4, VOICE = 5, BAR = 6, BEAT = 7, FRAME = 8; +/** + * Every note in the order struck: [at, end, pitch, velocity, part, voice, bar, beat, frame] — seconds struck and let go + * (the key; the pedal may hold it on), the key (60 is C4; for a drum, cymbal, impact or riser the kit's key, not a + * pitch), 1 … 127, PARTS' number, its place in its chord (0 the lowest), the bar, the beat in it (eighths from 0), the + * frame it is struck on. + */ +export const NOTES: readonly (readonly number[])[] = [ + [0,0.264,76,45,0,0,0,0,0], + [0.264,0.522,75,40,0,0,0,0.5,6], + [0.522,0.771,76,47,0,0,1,0,12], + [0.776,1.02,75,40,0,0,1,0.5,18], + [1.027,1.269,76,44,0,0,1,1,24], + [1.267,1.516,71,47,0,0,1,1.5,30], + [1.517,1.763,74,39,0,0,1,2,36], + [1.766,2.009,72,50,0,0,1,2.5,42], + [2.004,2.5,69,53,0,0,2,0,48], + [2.014,2.263,45,36,1,0,2,0,48], + [2.261,2.508,52,42,1,0,2,0.5,54], + [2.504,2.752,57,40,1,0,2,1,60], + [2.747,2.988,60,32,0,0,2,1.5,65], + [2.983,3.231,64,37,0,0,2,2,71], + [3.237,3.473,69,45,0,0,2,2.5,77], + [3.471,3.961,71,50,0,0,3,0,83], + [3.48,3.724,40,32,1,0,3,0,83], + [3.726,3.969,52,43,1,0,3,0.5,89], + [3.961,4.216,56,39,1,0,3,1,94], + [4.205,4.456,64,32,0,0,3,1.5,100], + [4.459,4.708,68,39,0,0,3,2,106], + [4.702,4.961,71,41,0,0,3,2.5,112], + [4.958,5.479,72,53,0,0,4,0,118], + [4.959,5.225,45,36,1,0,4,0,118], + [5.229,5.487,52,40,1,0,4,0.5,125], + [5.485,5.754,57,38,1,0,4,1,131], + [5.741,6.017,64,34,0,0,4,1.5,137], + [6.021,6.28,76,47,0,0,4,2,143], + [6.278,6.535,75,37,0,0,4,2.5,149], + [6.539,9.543,45,33,6,0,5,0,156], + [6.543,6.785,76,50,0,0,5,0,156], + [6.545,9.543,52,31,6,1,5,0,156], + [6.782,7.035,75,44,0,0,5,0.5,161], + [7.032,7.285,76,41,0,0,5,1,167], + [7.287,7.535,71,42,0,0,5,1.5,174], + [7.533,7.785,74,43,0,0,5,2,179], + [7.794,8.035,72,45,0,0,5,2.5,186], + [8.031,8.535,69,47,0,0,6,0,191], + [8.038,9.543,36,69,18,0,6,0,191], + [8.042,8.293,45,39,1,0,6,0,191], + [8.296,8.543,52,40,1,0,6,0.5,198], + [8.543,8.793,57,43,1,0,6,1,203], + [8.787,9.035,60,29,0,0,6,1.5,209], + [9.035,9.285,64,37,0,0,6,2,215], + [9.285,9.535,69,42,0,0,6,2.5,221], + [9.532,10.049,71,45,0,0,7,0,227], + [9.544,9.796,40,38,1,0,7,0,227], + [9.791,10.057,52,36,1,0,7,0.5,233], + [10.054,10.326,56,39,1,0,7,1,239], + [10.315,10.595,64,34,0,0,7,1.5,246], + [10.595,10.881,72,43,0,0,7,2,252], + [10.883,11.176,71,39,0,0,7,2.5,259], + [11.178,13.086,38,78,18,0,8,0,266], + [11.182,13.078,69,55,0,0,8,0,266], + [11.184,11.487,45,33,1,0,8,0,266], + [11.186,13.086,56,31,6,1,8,0,266], + [11.186,13.086,52,29,6,0,8,0,266], + [11.189,13.086,59,31,6,2,8,0,266], + [11.488,11.796,52,27,1,0,8,0.5,274], + [11.795,12.112,57,27,1,0,8,1,281], + [13.086,13.325,56,101,5,1,10,0,312], + [13.087,14.028,28,90,9,0,10,0,312], + [13.088,13.207,36,110,10,0,10,0,312], + [13.089,14.028,52,87,6,0,10,0,312], + [13.089,13.325,59,98,5,2,10,0,312], + [13.089,13.207,52,90,4,0,10,0,312], + [13.089,14.028,59,85,6,2,10,0,312], + [13.089,13.207,88,92,2,0,10,0,312], + [13.089,13.325,52,100,5,0,10,0,312], + [13.09,14.028,56,84,6,1,10,0,312], + [13.091,13.207,36,127,17,0,10,0,312], + [13.093,13.207,76,88,0,0,10,0,312], + [13.094,13.207,49,110,16,0,10,0,312], + [13.203,13.325,56,73,4,0,10,0.25,314], + [13.206,13.325,87,90,2,0,10,0.25,314], + [13.208,13.325,40,98,8,0,10,0.25,314], + [13.21,13.325,75,93,0,0,10,0.25,315], + [13.323,13.442,59,71,4,0,10,0.5,317], + [13.324,13.442,76,89,0,0,10,0.5,317], + [13.325,13.442,46,88,15,0,10,0.5,317], + [13.325,13.442,88,93,2,0,10,0.5,317], + [13.326,13.442,40,78,8,0,10,0.5,317], + [13.439,13.559,64,71,4,0,10,0.75,320], + [13.439,13.676,52,84,5,0,10,0.75,320], + [13.441,13.559,87,92,2,0,10,0.75,320], + [13.441,13.559,75,90,0,0,10,0.75,320], + [13.442,13.676,59,88,5,2,10,0.75,320], + [13.443,13.676,56,85,5,1,10,0.75,320], + [13.444,13.559,40,87,8,0,10,0.75,320], + [13.557,13.676,39,103,12,0,10,1,323], + [13.559,13.676,88,88,2,0,10,1,323], + [13.559,13.676,36,107,10,0,10,1,323], + [13.56,13.676,76,88,0,0,10,1,323], + [13.563,13.676,68,91,4,0,10,1,323], + [13.675,13.793,83,95,2,0,10,1.25,326], + [13.675,13.793,71,93,0,0,10,1.25,326], + [13.677,13.793,71,70,4,0,10,1.25,326], + [13.679,13.793,40,94,8,0,10,1.25,326], + [13.791,13.911,40,82,8,0,10,1.5,328], + [13.792,13.911,74,87,0,0,10,1.5,328], + [13.792,13.911,64,72,4,0,10,1.5,328], + [13.792,14.028,52,92,5,0,10,1.5,328], + [13.793,13.911,86,89,2,0,10,1.5,328], + [13.795,13.911,46,87,15,0,10,1.5,328], + [13.795,14.028,56,95,5,1,10,1.5,328], + [13.798,14.028,59,88,5,2,10,1.5,329], + [13.908,14.028,72,87,0,0,10,1.75,331], + [13.911,14.028,84,91,2,0,10,1.75,331], + [13.913,14.028,40,87,8,0,10,1.75,331], + [13.914,14.028,59,71,4,0,10,1.75,331], + [14.026,14.145,57,89,4,0,10,2,334], + [14.026,14.965,64,87,6,2,10,2,334], + [14.026,14.262,60,103,5,1,10,2,334], + [14.026,14.262,64,100,5,2,10,2,334], + [14.027,14.145,36,111,10,0,10,2,334], + [14.028,14.965,60,87,6,1,10,2,334], + [14.028,14.379,81,93,2,0,10,2,334], + [14.029,14.262,57,102,5,0,10,2,334], + [14.03,14.965,57,89,6,0,10,2,334], + [14.03,14.965,33,89,9,0,10,2,334], + [14.032,14.379,69,93,0,0,10,2,334], + [14.145,14.262,45,96,8,0,10,2.25,337], + [14.147,14.262,60,74,4,0,10,2.25,337], + [14.263,14.379,64,72,4,0,10,2.5,340], + [14.264,14.379,46,89,15,0,10,2.5,340], + [14.265,14.379,45,83,8,0,10,2.5,340], + [14.378,14.614,57,87,5,0,10,2.75,342], + [14.379,14.496,72,89,2,0,10,2.75,342], + [14.38,14.614,64,84,5,2,10,2.75,342], + [14.381,14.496,45,90,8,0,10,2.75,342], + [14.381,14.496,69,70,4,0,10,2.75,342], + [14.381,14.614,60,86,5,1,10,2.75,342], + [14.383,14.496,60,90,0,0,10,2.75,342], + [14.494,14.614,64,89,0,0,10,3,345], + [14.494,14.614,39,102,12,0,10,3,345], + [14.496,14.614,72,94,4,0,10,3,345], + [14.501,14.614,36,107,10,0,10,3,345], + [14.501,14.614,76,93,2,0,10,3,345], + [14.612,14.731,45,96,8,0,10,3.25,348], + [14.612,14.965,81,94,2,0,10,3.25,348], + [14.614,14.965,69,87,0,0,10,3.25,348], + [14.614,14.731,76,72,4,0,10,3.25,348], + [14.728,14.848,46,87,15,0,10,3.5,351], + [14.731,14.848,69,73,4,0,10,3.5,351], + [14.732,14.965,64,92,5,2,10,3.5,351], + [14.733,14.965,57,89,5,0,10,3.5,351], + [14.734,14.848,45,81,8,0,10,3.5,351], + [14.734,14.965,60,94,5,1,10,3.5,351], + [14.847,14.965,64,73,4,0,10,3.75,353], + [14.848,14.965,45,86,8,0,10,3.75,354], + [14.96,15.2,56,102,5,1,11,0,356], + [14.963,15.903,59,85,6,2,11,0,356], + [14.963,15.903,28,85,9,0,11,0,356], + [14.964,15.903,52,86,6,0,11,0,356], + [14.965,15.082,52,89,4,0,11,0,356], + [14.966,15.2,52,99,5,0,11,0,356], + [14.966,15.2,59,102,5,2,11,0,356], + [14.966,15.317,71,91,0,0,11,0,356], + [14.967,15.082,36,112,10,0,11,0,356], + [14.967,15.317,83,91,2,0,11,0,356], + [14.968,15.903,56,89,6,1,11,0,356], + [15.083,15.2,40,97,8,0,11,0.25,359], + [15.088,15.2,56,74,4,0,11,0.25,359], + [15.199,15.317,40,82,8,0,11,0.5,362], + [15.199,15.317,46,89,15,0,11,0.5,362], + [15.201,15.317,59,73,4,0,11,0.5,362], + [15.315,15.551,52,82,5,0,11,0.75,365], + [15.315,15.551,56,82,5,1,11,0.75,365], + [15.316,15.434,76,88,2,0,11,0.75,365], + [15.317,15.434,64,73,4,0,11,0.75,365], + [15.317,15.434,64,93,0,0,11,0.75,365], + [15.318,15.551,59,86,5,2,11,0.75,365], + [15.318,15.434,40,88,8,0,11,0.75,365], + [15.431,15.551,68,94,4,0,11,1,367], + [15.434,15.551,36,110,10,0,11,1,367], + [15.435,15.551,68,88,0,0,11,1,367], + [15.435,15.551,80,89,2,0,11,1,368], + [15.436,15.551,39,103,12,0,11,1,368], + [15.549,15.903,71,95,0,0,11,1.25,370], + [15.55,15.668,40,98,8,0,11,1.25,370], + [15.554,15.903,83,90,2,0,11,1.25,370], + [15.554,15.668,71,71,4,0,11,1.25,370], + [15.666,15.903,52,93,5,0,11,1.5,373], + [15.666,15.786,64,72,4,0,11,1.5,373], + [15.667,15.786,40,82,8,0,11,1.5,373], + [15.667,15.903,56,90,5,1,11,1.5,373], + [15.669,15.786,46,83,15,0,11,1.5,373], + [15.671,15.903,59,93,5,2,11,1.5,373], + [15.785,15.903,40,85,8,0,11,1.75,376], + [15.789,15.903,59,74,4,0,11,1.75,376], + [15.9,16.137,64,104,5,2,11,2,379], + [15.9,16.02,57,88,4,0,11,2,379], + [15.902,16.137,57,98,5,0,11,2,379], + [15.903,16.84,60,85,6,1,11,2,379], + [15.903,16.84,64,88,6,2,11,2,379], + [15.903,16.137,60,103,5,1,11,2,379], + [15.903,16.254,72,90,0,0,11,2,379], + [15.904,16.84,33,91,9,0,11,2,379], + [15.904,16.02,36,111,10,0,11,2,379], + [15.905,16.254,84,95,2,0,11,2,379], + [15.906,16.84,57,85,6,0,11,2,379], + [16.018,16.137,45,98,8,0,11,2.25,381], + [16.022,16.137,60,72,4,0,11,2.25,381], + [16.133,16.254,45,82,8,0,11,2.5,384], + [16.136,16.254,46,87,15,0,11,2.5,384], + [16.141,16.254,64,71,4,0,11,2.5,384], + [16.251,16.489,57,85,5,0,11,2.75,387], + [16.252,16.371,76,90,2,0,11,2.75,387], + [16.252,16.371,64,88,0,0,11,2.75,387], + [16.253,16.371,69,70,4,0,11,2.75,387], + [16.254,16.371,45,86,8,0,11,2.75,387], + [16.255,16.489,60,84,5,1,11,2.75,387], + [16.255,16.489,64,83,5,2,11,2.75,387], + [16.369,16.489,39,106,12,0,11,3,390], + [16.371,16.489,72,94,4,0,11,3,390], + [16.372,16.84,76,87,0,0,11,3,390], + [16.375,16.84,88,92,2,0,11,3,390], + [16.375,16.489,36,106,10,0,11,3,390], + [16.49,16.606,76,73,4,0,11,3.25,393], + [16.49,16.606,45,96,8,0,11,3.25,393], + [16.603,16.723,69,69,4,0,11,3.5,395], + [16.606,16.84,57,93,5,0,11,3.5,395], + [16.606,16.723,45,81,8,0,11,3.5,395], + [16.606,16.723,46,81,15,0,11,3.5,395], + [16.607,16.84,60,94,5,1,11,3.5,395], + [16.608,16.84,64,93,5,2,11,3.5,395], + [16.722,16.84,64,70,4,0,11,3.75,398], + [16.723,16.84,45,86,8,0,11,3.75,398], + [16.837,16.957,52,91,4,0,12,0,401], + [16.838,17.778,56,86,6,1,12,0,401], + [16.838,17.075,52,101,5,0,12,0,401], + [16.838,17.778,52,88,6,0,12,0,401], + [16.839,16.957,88,89,2,0,12,0,401], + [16.839,17.778,59,87,6,2,12,0,401], + [16.84,17.075,56,99,5,1,12,0,401], + [16.84,16.957,76,89,0,0,12,0,401], + [16.84,17.778,28,90,9,0,12,0,401], + [16.841,17.075,59,97,5,2,12,0,401], + [16.842,16.957,36,112,10,0,12,0,401], + [16.955,17.075,40,97,8,0,12,0.25,404], + [16.956,17.075,75,91,0,0,12,0.25,404], + [16.958,17.075,56,73,4,0,12,0.25,404], + [16.96,17.075,87,93,2,0,12,0.25,404], + [17.07,17.192,40,85,8,0,12,0.5,406], + [17.072,17.192,46,91,15,0,12,0.5,406], + [17.075,17.192,76,88,0,0,12,0.5,407], + [17.075,17.192,88,89,2,0,12,0.5,407], + [17.075,17.192,59,75,4,0,12,0.5,407], + [17.191,17.309,87,87,2,0,12,0.75,409], + [17.191,17.426,59,87,5,2,12,0.75,409], + [17.192,17.309,40,91,8,0,12,0.75,409], + [17.194,17.426,52,85,5,0,12,0.75,409], + [17.194,17.309,64,75,4,0,12,0.75,409], + [17.194,17.309,75,88,0,0,12,0.75,409], + [17.197,17.426,56,82,5,1,12,0.75,409], + [17.305,17.426,68,90,4,0,12,1,412], + [17.306,17.426,88,93,2,0,12,1,412], + [17.309,17.426,39,99,12,0,12,1,412], + [17.309,17.426,76,92,0,0,12,1,412], + [17.31,17.426,36,107,10,0,12,1,412], + [17.422,17.543,83,91,2,0,12,1.25,415], + [17.425,17.543,40,96,8,0,12,1.25,415], + [17.425,17.543,71,70,4,0,12,1.25,415], + [17.429,17.543,71,91,0,0,12,1.25,415], + [17.54,17.661,74,92,0,0,12,1.5,418], + [17.541,17.661,86,89,2,0,12,1.5,418], + [17.542,17.661,64,71,4,0,12,1.5,418], + [17.542,17.661,46,83,15,0,12,1.5,418], + [17.542,17.778,56,92,5,1,12,1.5,418], + [17.543,17.778,52,93,5,0,12,1.5,418], + [17.543,17.778,59,94,5,2,12,1.5,418], + [17.545,17.661,40,81,8,0,12,1.5,418], + [17.662,17.778,40,86,8,0,12,1.75,421], + [17.664,17.778,59,73,4,0,12,1.75,421], + [17.665,17.778,72,89,0,0,12,1.75,421], + [17.665,17.778,84,92,2,0,12,1.75,421], + [17.774,18.715,60,85,6,1,12,2,423], + [17.775,18.715,33,89,9,0,12,2,423], + [17.775,17.895,36,108,10,0,12,2,423], + [17.776,18.012,64,99,5,2,12,2,423], + [17.776,18.129,81,90,2,0,12,2,423], + [17.777,18.715,57,87,6,0,12,2,423], + [17.777,18.129,69,91,0,0,12,2,423], + [17.778,18.012,57,97,5,0,12,2,423], + [17.778,18.715,64,83,6,2,12,2,423], + [17.779,17.895,57,93,4,0,12,2,423], + [17.782,18.012,60,99,5,1,12,2,423], + [17.894,18.012,60,72,4,0,12,2.25,426], + [17.895,18.012,45,99,8,0,12,2.25,426], + [18.011,18.129,46,88,15,0,12,2.5,429], + [18.012,18.129,45,83,8,0,12,2.5,429], + [18.017,18.129,64,72,4,0,12,2.5,429], + [18.127,18.364,60,83,5,1,12,2.75,432], + [18.127,18.246,60,90,0,0,12,2.75,432], + [18.128,18.246,69,72,4,0,12,2.75,432], + [18.129,18.364,57,83,5,0,12,2.75,432], + [18.13,18.364,64,86,5,2,12,2.75,432], + [18.13,18.246,72,90,2,0,12,2.75,432], + [18.132,18.246,45,85,8,0,12,2.75,432], + [18.243,18.364,36,109,10,0,12,3,434], + [18.246,18.364,76,93,2,0,12,3,434], + [18.248,18.364,39,103,12,0,12,3,434], + [18.249,18.364,72,90,4,0,12,3,434], + [18.25,18.364,64,90,0,0,12,3,435], + [18.361,18.715,69,88,0,0,12,3.25,437], + [18.364,18.481,76,70,4,0,12,3.25,437], + [18.364,18.481,45,94,8,0,12,3.25,437], + [18.365,18.715,81,89,2,0,12,3.25,437], + [18.477,18.598,45,80,8,0,12,3.5,440], + [18.48,18.598,46,86,15,0,12,3.5,440], + [18.481,18.598,69,69,4,0,12,3.5,440], + [18.481,18.715,57,93,5,0,12,3.5,440], + [18.482,18.715,64,94,5,2,12,3.5,440], + [18.483,18.715,60,94,5,1,12,3.5,440], + [18.599,18.715,45,86,8,0,12,3.75,443], + [18.601,18.715,64,69,4,0,12,3.75,443], + [18.713,19.653,28,90,9,0,13,0,446], + [18.713,18.832,36,115,10,0,13,0,446], + [18.713,19.067,83,93,2,0,13,0,446], + [18.714,18.95,56,100,5,1,13,0,446], + [18.714,18.832,52,90,4,0,13,0,446], + [18.715,19.653,59,86,6,2,13,0,446], + [18.715,19.653,56,84,6,1,13,0,446], + [18.716,18.95,52,101,5,0,13,0,446], + [18.716,19.067,71,94,0,0,13,0,446], + [18.716,18.95,59,102,5,2,13,0,446], + [18.716,19.653,52,87,6,0,13,0,446], + [18.833,18.95,56,73,4,0,13,0.25,448], + [18.835,18.95,40,99,8,0,13,0.25,448], + [18.947,19.067,59,71,4,0,13,0.5,451], + [18.948,19.067,46,84,15,0,13,0.5,451], + [18.951,19.067,40,82,8,0,13,0.5,451], + [19.064,19.301,56,87,5,1,13,0.75,454], + [19.066,19.184,40,87,8,0,13,0.75,454], + [19.067,19.184,64,90,0,0,13,0.75,454], + [19.068,19.301,59,85,5,2,13,0.75,454], + [19.068,19.301,52,87,5,0,13,0.75,454], + [19.069,19.184,76,91,2,0,13,0.75,454], + [19.069,19.184,64,70,4,0,13,0.75,454], + [19.182,19.301,84,91,2,0,13,1,457], + [19.183,19.301,36,108,10,0,13,1,457], + [19.183,19.301,72,88,0,0,13,1,457], + [19.185,19.301,68,91,4,0,13,1,457], + [19.185,19.301,39,98,12,0,13,1,457], + [19.298,19.418,40,95,8,0,13,1.25,459], + [19.3,19.653,83,89,2,0,13,1.25,460], + [19.3,19.653,71,88,0,0,13,1.25,460], + [19.302,19.418,71,71,4,0,13,1.25,460], + [19.418,19.536,46,83,15,0,13,1.5,462], + [19.418,19.536,64,73,4,0,13,1.5,462], + [19.419,19.536,40,85,8,0,13,1.5,462], + [19.42,19.653,59,92,5,2,13,1.5,462], + [19.422,19.653,56,94,5,1,13,1.5,462], + [19.422,19.653,52,91,5,0,13,1.5,462], + [19.536,19.653,59,73,4,0,13,1.75,465], + [19.538,19.653,40,91,8,0,13,1.75,465], + [19.649,19.887,64,98,5,2,13,2,468], + [19.651,20.59,64,84,6,2,13,2,468], + [19.651,20.59,69,89,0,0,13,2,468], + [19.651,20.59,60,85,6,1,13,2,468], + [19.651,19.887,60,100,5,1,13,2,468], + [19.652,20.59,81,90,2,0,13,2,468], + [19.653,19.887,57,101,5,0,13,2,468], + [19.653,20.59,33,90,9,0,13,2,468], + [19.654,19.77,36,110,10,0,13,2,468], + [19.655,20.59,57,84,6,0,13,2,468], + [19.655,19.77,57,91,4,0,13,2,468], + [19.767,19.887,45,101,8,0,13,2.25,471], + [19.771,19.887,60,73,4,0,13,2.25,471], + [19.884,20.004,45,83,8,0,13,2.5,473], + [19.886,20.004,46,87,15,0,13,2.5,473], + [19.889,20.004,64,70,4,0,13,2.5,474], + [20.001,20.121,69,70,4,0,13,2.75,476], + [20.002,20.121,45,89,8,0,13,2.75,476], + [20.003,20.239,60,87,5,1,13,2.75,476], + [20.004,20.239,57,86,5,0,13,2.75,476], + [20.006,20.239,64,84,5,2,13,2.75,476], + [20.12,20.239,39,106,12,0,13,3,479], + [20.12,20.239,72,92,4,0,13,3,479], + [20.124,20.239,36,110,10,0,13,3,479], + [20.236,20.356,76,72,4,0,13,3.25,482], + [20.24,20.356,45,97,8,0,13,3.25,482], + [20.354,20.59,64,90,5,2,13,3.5,485], + [20.355,20.59,60,92,5,1,13,3.5,485], + [20.356,20.473,45,82,8,0,13,3.5,485], + [20.356,20.473,69,68,4,0,13,3.5,485], + [20.357,20.473,46,85,15,0,13,3.5,485], + [20.357,20.59,57,92,5,0,13,3.5,485], + [20.47,20.59,45,88,8,0,13,3.75,487], + [20.474,20.59,64,73,4,0,13,3.75,487], + [20.587,20.825,52,99,5,0,14,0,490], + [20.587,20.707,76,94,0,0,14,0,490], + [20.589,21.528,28,89,9,0,14,0,490], + [20.589,21.528,59,88,6,2,14,0,490], + [20.59,20.707,88,88,2,0,14,0,490], + [20.59,20.825,56,97,5,1,14,0,490], + [20.591,20.707,52,93,4,0,14,0,490], + [20.591,21.528,56,90,6,1,14,0,490], + [20.591,21.528,52,86,6,0,14,0,490], + [20.592,20.707,36,112,10,0,14,0,490], + [20.595,20.825,59,96,5,2,14,0,490], + [20.706,20.825,87,89,2,0,14,0.25,493], + [20.706,20.825,40,94,8,0,14,0.25,493], + [20.707,20.825,75,91,0,0,14,0.25,493], + [20.709,20.825,56,73,4,0,14,0.25,493], + [20.823,20.942,40,83,8,0,14,0.5,496], + [20.824,20.942,76,91,0,0,14,0.5,496], + [20.826,20.942,46,88,15,0,14,0.5,496], + [20.826,20.942,59,72,4,0,14,0.5,496], + [20.826,20.942,88,90,2,0,14,0.5,496], + [20.937,21.176,52,84,5,0,14,0.75,499], + [20.938,21.059,64,73,4,0,14,0.75,499], + [20.94,21.176,59,85,5,2,14,0.75,499], + [20.94,21.059,40,89,8,0,14,0.75,499], + [20.941,21.059,75,91,0,0,14,0.75,499], + [20.942,21.176,56,83,5,1,14,0.75,499], + [20.944,21.059,87,91,2,0,14,0.75,499], + [21.058,21.176,76,95,0,0,14,1,501], + [21.058,21.176,36,106,10,0,14,1,501], + [21.059,21.176,88,90,2,0,14,1,501], + [21.061,21.176,39,101,12,0,14,1,501], + [21.063,21.176,68,90,4,0,14,1,501], + [21.174,21.293,71,72,4,0,14,1.25,504], + [21.177,21.293,83,89,2,0,14,1.25,504], + [21.178,21.293,71,86,0,0,14,1.25,504], + [21.178,21.293,40,98,8,0,14,1.25,504], + [21.291,21.528,59,95,5,2,14,1.5,507], + [21.293,21.528,52,93,5,0,14,1.5,507], + [21.294,21.411,86,91,2,0,14,1.5,507], + [21.294,21.411,74,90,0,0,14,1.5,507], + [21.294,21.411,40,82,8,0,14,1.5,507], + [21.294,21.528,56,90,5,1,14,1.5,507], + [21.294,21.411,64,70,4,0,14,1.5,507], + [21.295,21.411,46,83,15,0,14,1.5,507], + [21.408,21.528,40,86,8,0,14,1.75,510], + [21.409,21.528,59,72,4,0,14,1.75,510], + [21.413,21.528,84,89,2,0,14,1.75,510], + [21.413,21.528,72,88,0,0,14,1.75,510], + [21.523,22.465,60,87,6,1,14,2,512], + [21.524,21.645,36,109,10,0,14,2,512], + [21.526,22.465,57,88,6,0,14,2,513], + [21.526,22.465,33,87,9,0,14,2,513], + [21.526,21.762,57,98,5,0,14,2,513], + [21.528,21.645,57,91,4,0,14,2,513], + [21.529,22.465,64,87,6,2,14,2,513], + [21.529,21.879,81,93,2,0,14,2,513], + [21.529,21.762,60,98,5,1,14,2,513], + [21.53,21.879,69,90,0,0,14,2,513], + [21.531,21.762,64,101,5,2,14,2,513], + [21.644,21.762,45,94,8,0,14,2.25,515], + [21.647,21.762,60,72,4,0,14,2.25,515], + [21.761,21.879,64,74,4,0,14,2.5,518], + [21.763,21.879,45,82,8,0,14,2.5,518], + [21.764,21.879,46,88,15,0,14,2.5,518], + [21.878,22.114,64,84,5,2,14,2.75,521], + [21.879,22.114,57,79,5,0,14,2.75,521], + [21.879,21.996,69,71,4,0,14,2.75,521], + [21.879,22.114,60,83,5,1,14,2.75,521], + [21.88,21.996,45,91,8,0,14,2.75,521], + [21.88,21.996,72,89,2,0,14,2.75,521], + [21.881,21.996,60,91,0,0,14,2.75,521], + [21.996,22.114,36,108,10,0,14,3,524], + [21.996,22.114,72,93,4,0,14,3,524], + [21.996,22.114,76,92,2,0,14,3,524], + [21.997,22.114,64,87,0,0,14,3,524], + [21.998,22.114,39,104,12,0,14,3,524], + [22.113,22.465,81,91,2,0,14,3.25,526], + [22.113,22.465,69,87,0,0,14,3.25,527], + [22.114,22.231,76,70,4,0,14,3.25,527], + [22.116,22.231,45,96,8,0,14,3.25,527], + [22.229,22.465,60,92,5,1,14,3.5,529], + [22.229,22.348,69,71,4,0,14,3.5,529], + [22.23,22.348,45,78,8,0,14,3.5,529], + [22.23,22.465,64,90,5,2,14,3.5,529], + [22.23,22.465,57,94,5,0,14,3.5,529], + [22.234,22.348,46,80,15,0,14,3.5,529], + [22.346,22.465,64,69,4,0,14,3.75,532], + [22.347,22.465,45,88,8,0,14,3.75,532], + [22.462,22.7,59,99,5,2,15,0,535], + [22.463,22.7,56,98,5,1,15,0,535], + [22.463,23.403,28,91,9,0,15,0,535], + [22.464,22.582,36,114,10,0,15,0,535], + [22.465,22.817,83,87,2,0,15,0,535], + [22.465,22.7,52,104,5,0,15,0,535], + [22.466,23.403,59,85,6,2,15,0,535], + [22.466,23.403,52,84,6,0,15,0,535], + [22.466,23.403,56,85,6,1,15,0,535], + [22.466,22.817,71,91,0,0,15,0,535], + [22.467,22.582,52,93,4,0,15,0,535], + [22.579,22.7,56,73,4,0,15,0.25,538], + [22.583,22.7,40,96,8,0,15,0.25,538], + [22.698,22.817,59,72,4,0,15,0.5,540], + [22.699,22.817,46,87,15,0,15,0.5,540], + [22.7,22.817,40,79,8,0,15,0.5,540], + [22.815,22.934,40,92,8,0,15,0.75,543], + [22.816,22.934,64,89,0,0,15,0.75,543], + [22.816,22.934,76,91,2,0,15,0.75,543], + [22.816,22.934,64,72,4,0,15,0.75,543], + [22.817,23.051,56,87,5,1,15,0.75,543], + [22.818,23.051,59,86,5,2,15,0.75,543], + [22.818,23.051,52,84,5,0,15,0.75,543], + [22.93,23.051,80,89,2,0,15,1,546], + [22.931,23.051,36,107,10,0,15,1,546], + [22.933,23.051,39,100,12,0,15,1,546], + [22.934,23.051,68,89,0,0,15,1,546], + [22.935,23.051,68,92,4,0,15,1,546], + [23.05,23.403,71,88,0,0,15,1.25,549], + [23.051,23.168,71,74,4,0,15,1.25,549], + [23.051,23.403,83,90,2,0,15,1.25,549], + [23.055,23.168,40,94,8,0,15,1.25,549], + [23.165,23.286,46,86,15,0,15,1.5,552], + [23.168,23.403,59,92,5,2,15,1.5,552], + [23.169,23.403,56,92,5,1,15,1.5,552], + [23.169,23.286,64,75,4,0,15,1.5,552], + [23.171,23.286,40,83,8,0,15,1.5,552], + [23.172,23.403,52,90,5,0,15,1.5,552], + [23.283,23.403,40,90,8,0,15,1.75,554], + [23.286,23.403,59,70,4,0,15,1.75,554], + [23.4,23.754,84,91,2,0,15,2,557], + [23.4,23.637,60,103,5,1,15,2,557], + [23.401,23.52,57,92,4,0,15,2,557], + [23.401,23.754,72,91,0,0,15,2,557], + [23.402,24.34,57,86,6,0,15,2,557], + [23.404,24.34,33,91,9,0,15,2,557], + [23.404,24.34,60,86,6,1,15,2,557], + [23.404,23.52,36,111,10,0,15,2,557], + [23.404,23.637,64,100,5,2,15,2,557], + [23.404,24.34,64,84,6,2,15,2,557], + [23.404,23.637,57,100,5,0,15,2,557], + [23.519,23.637,60,74,4,0,15,2.25,560], + [23.519,23.637,45,97,8,0,15,2.25,560], + [23.633,23.754,45,81,8,0,15,2.5,563], + [23.638,23.754,64,68,4,0,15,2.5,563], + [23.64,23.754,46,92,15,0,15,2.5,563], + [23.752,23.871,76,92,2,0,15,2.75,566], + [23.754,23.871,45,91,8,0,15,2.75,566], + [23.754,23.989,60,83,5,1,15,2.75,566], + [23.755,23.871,69,72,4,0,15,2.75,566], + [23.756,23.871,64,89,0,0,15,2.75,566], + [23.756,23.989,57,83,5,0,15,2.75,566], + [23.757,23.989,64,87,5,2,15,2.75,566], + [23.869,24.34,76,86,0,0,15,3,568], + [23.871,23.989,36,105,10,0,15,3,568], + [23.871,23.989,72,96,4,0,15,3,568], + [23.872,24.34,88,92,2,0,15,3,568], + [23.872,23.989,39,106,12,0,15,3,568], + [23.987,24.106,76,75,4,0,15,3.25,571], + [23.988,24.106,45,95,8,0,15,3.25,571], + [24.106,24.223,69,75,4,0,15,3.5,574], + [24.106,24.223,46,85,15,0,15,3.5,574], + [24.106,24.34,57,93,5,0,15,3.5,574], + [24.107,24.34,64,91,5,2,15,3.5,574], + [24.108,24.34,60,89,5,1,15,3.5,574], + [24.109,24.223,45,77,8,0,15,3.5,574], + [24.224,24.34,45,85,8,0,15,3.75,577], + [24.225,24.34,64,73,4,0,15,3.75,577], + [24.337,24.575,52,102,5,0,16,0,579], + [24.337,25.278,56,89,6,1,16,0,579], + [24.339,25.278,28,88,9,0,16,0,579], + [24.339,24.457,76,91,0,0,16,0,580], + [24.34,24.575,56,98,5,1,16,0,580], + [24.34,24.575,59,96,5,2,16,0,580], + [24.34,24.457,36,109,10,0,16,0,580], + [24.341,24.457,88,90,2,0,16,0,580], + [24.342,24.457,52,93,4,0,16,0,580], + [24.342,25.278,59,84,6,2,16,0,580], + [24.345,25.278,52,85,6,0,16,0,580], + [24.456,24.575,56,72,4,0,16,0.25,582], + [24.458,24.575,40,97,8,0,16,0.25,582], + [24.458,24.575,87,89,2,0,16,0.25,582], + [24.459,24.575,75,89,0,0,16,0.25,582], + [24.569,24.692,59,72,4,0,16,0.5,585], + [24.571,24.692,46,86,15,0,16,0.5,585], + [24.575,24.692,40,80,8,0,16,0.5,585], + [24.577,24.692,88,91,2,0,16,0.5,585], + [24.577,24.692,76,90,0,0,16,0.5,585], + [24.689,24.926,56,82,5,1,16,0.75,588], + [24.69,24.809,40,91,8,0,16,0.75,588], + [24.691,24.809,64,75,4,0,16,0.75,588], + [24.693,24.926,52,82,5,0,16,0.75,588], + [24.694,24.809,75,92,0,0,16,0.75,588], + [24.694,24.809,87,90,2,0,16,0.75,588], + [24.696,24.926,59,84,5,2,16,0.75,588], + [24.807,24.926,68,91,4,0,16,1,591], + [24.81,24.926,36,108,10,0,16,1,591], + [24.811,24.926,88,91,2,0,16,1,591], + [24.812,24.926,39,97,12,0,16,1,591], + [24.812,24.926,76,92,0,0,16,1,591], + [24.924,25.043,83,91,2,0,16,1.25,593], + [24.925,25.043,71,88,0,0,16,1.25,593], + [24.927,25.043,71,71,4,0,16,1.25,593], + [24.929,25.043,40,95,8,0,16,1.25,594], + [25.04,25.278,59,91,5,2,16,1.5,596], + [25.041,25.161,74,91,0,0,16,1.5,596], + [25.043,25.161,40,83,8,0,16,1.5,596], + [25.044,25.161,86,91,2,0,16,1.5,596], + [25.045,25.161,46,83,15,0,16,1.5,596], + [25.045,25.161,64,75,4,0,16,1.5,596], + [25.046,25.278,52,90,5,0,16,1.5,596], + [25.046,25.278,56,92,5,1,16,1.5,596], + [25.158,25.278,59,68,4,0,16,1.75,599], + [25.159,25.278,40,87,8,0,16,1.75,599], + [25.162,25.278,84,92,2,0,16,1.75,599], + [25.164,25.278,72,89,0,0,16,1.75,599], + [25.273,26.215,57,87,6,0,16,2,602], + [25.275,25.629,81,91,2,0,16,2,602], + [25.275,25.395,57,95,4,0,16,2,602], + [25.276,25.395,36,108,10,0,16,2,602], + [25.277,26.215,33,90,9,0,16,2,602], + [25.278,25.629,69,92,0,0,16,2,602], + [25.279,25.512,60,99,5,1,16,2,602], + [25.279,26.215,64,89,6,2,16,2,602], + [25.281,26.215,60,83,6,1,16,2,602], + [25.281,25.512,64,98,5,2,16,2,602], + [25.281,25.512,57,99,5,0,16,2,602], + [25.392,25.512,45,99,8,0,16,2.25,605], + [25.393,25.512,60,70,4,0,16,2.25,605], + [25.51,25.629,46,88,15,0,16,2.5,607], + [25.514,25.629,64,74,4,0,16,2.5,607], + [25.515,25.629,45,79,8,0,16,2.5,607], + [25.625,25.864,57,82,5,0,16,2.75,610], + [25.628,25.746,72,91,2,0,16,2.75,610], + [25.628,25.746,60,88,0,0,16,2.75,610], + [25.628,25.864,64,83,5,2,16,2.75,610], + [25.629,25.746,45,86,8,0,16,2.75,610], + [25.63,25.864,60,83,5,1,16,2.75,610], + [25.634,25.746,69,72,4,0,16,2.75,610], + [25.743,25.864,36,108,10,0,16,3,613], + [25.744,25.864,72,91,4,0,16,3,613], + [25.745,25.864,39,103,12,0,16,3,613], + [25.746,25.864,64,88,0,0,16,3,613], + [25.748,25.864,76,89,2,0,16,3,613], + [25.863,25.981,76,72,4,0,16,3.25,616], + [25.864,26.215,69,90,0,0,16,3.25,616], + [25.866,25.981,45,96,8,0,16,3.25,616], + [25.867,26.215,81,91,2,0,16,3.25,616], + [25.98,26.098,69,68,4,0,16,3.5,619], + [25.981,26.215,57,95,5,0,16,3.5,619], + [25.982,26.215,64,92,5,2,16,3.5,619], + [25.982,26.098,45,81,8,0,16,3.5,619], + [25.983,26.098,46,83,15,0,16,3.5,619], + [25.985,26.215,60,88,5,1,16,3.5,619], + [26.098,26.215,64,70,4,0,16,3.75,621], + [26.1,26.215,45,87,8,0,16,3.75,621], + [26.212,26.45,59,100,5,2,17,0,624], + [26.212,26.45,52,96,5,0,17,0,624], + [26.214,27.153,28,90,9,0,17,0,624], + [26.214,27.153,56,86,6,1,17,0,624], + [26.214,26.45,56,102,5,1,17,0,624], + [26.214,26.332,36,113,10,0,17,0,624], + [26.214,27.153,59,88,6,2,17,0,624], + [26.214,27.153,52,86,6,0,17,0,624], + [26.215,26.567,83,93,2,0,17,0,624], + [26.216,26.567,71,90,0,0,17,0,624], + [26.217,26.332,52,92,4,0,17,0,624], + [26.332,26.45,56,72,4,0,17,0.25,627], + [26.332,26.45,40,96,8,0,17,0.25,627], + [26.449,26.567,59,76,4,0,17,0.5,630], + [26.452,26.567,46,89,15,0,17,0.5,630], + [26.452,26.567,40,79,8,0,17,0.5,630], + [26.564,26.684,64,68,4,0,17,0.75,632], + [26.564,26.801,52,84,5,0,17,0.75,632], + [26.566,26.801,59,82,5,2,17,0.75,633], + [26.567,26.684,76,88,2,0,17,0.75,633], + [26.568,26.801,56,83,5,1,17,0.75,633], + [26.568,26.684,64,90,0,0,17,0.75,633], + [26.571,26.684,40,89,8,0,17,0.75,633], + [26.682,26.801,39,97,12,0,17,1,635], + [26.682,26.801,36,110,10,0,17,1,635], + [26.685,26.801,72,90,0,0,17,1,635], + [26.685,26.801,68,89,4,0,17,1,635], + [26.689,26.801,84,91,2,0,17,1,635], + [26.802,26.918,40,94,8,0,17,1.25,638], + [26.802,27.153,83,92,2,0,17,1.25,638], + [26.804,26.918,71,71,4,0,17,1.25,638], + [26.804,27.153,71,89,0,0,17,1.25,638], + [26.914,27.153,59,93,5,2,17,1.5,641], + [26.918,27.036,40,81,8,0,17,1.5,641], + [26.918,27.036,46,86,15,0,17,1.5,641], + [26.919,27.153,52,90,5,0,17,1.5,641], + [26.92,27.153,56,96,5,1,17,1.5,641], + [26.921,27.036,64,73,4,0,17,1.5,641], + [27.033,27.153,40,89,8,0,17,1.75,644], + [27.034,27.153,59,77,4,0,17,1.75,644], + [27.15,28.09,33,90,9,0,17,2,646], + [27.15,28.09,64,87,6,2,17,2,646], + [27.15,27.387,60,99,5,1,17,2,646], + [27.151,27.504,69,89,0,0,17,2,646], + [27.153,28.09,60,87,6,1,17,2,646], + [27.153,28.09,57,86,6,0,17,2,646], + [27.154,27.387,64,99,5,2,17,2,647], + [27.154,27.504,81,88,2,0,17,2,647], + [27.155,27.27,36,109,10,0,17,2,647], + [27.156,27.387,57,99,5,0,17,2,647], + [27.157,27.27,57,92,4,0,17,2,647], + [27.268,27.387,45,98,8,0,17,2.25,649], + [27.268,27.387,60,74,4,0,17,2.25,649], + [27.386,27.504,64,73,4,0,17,2.5,652], + [27.39,27.504,46,88,15,0,17,2.5,652], + [27.392,27.504,45,82,8,0,17,2.5,652], + [27.503,27.739,64,84,5,2,17,2.75,655], + [27.503,27.739,57,85,5,0,17,2.75,655], + [27.503,27.621,71,87,0,0,17,2.75,655], + [27.504,27.621,83,91,2,0,17,2.75,655], + [27.504,27.621,69,72,4,0,17,2.75,655], + [27.504,27.621,45,89,8,0,17,2.75,655], + [27.506,27.739,60,85,5,1,17,2.75,655], + [27.619,27.739,72,96,4,0,17,3,658], + [27.62,27.739,39,101,12,0,17,3,658], + [27.623,27.739,72,90,0,0,17,3,658], + [27.623,27.739,36,107,10,0,17,3,658], + [27.624,27.739,84,90,2,0,17,3,658], + [27.737,27.856,45,95,8,0,17,3.25,660], + [27.738,28.09,86,92,2,0,17,3.25,660], + [27.739,27.856,76,71,4,0,17,3.25,660], + [27.74,28.09,74,89,0,0,17,3.25,660], + [27.853,27.973,45,83,8,0,17,3.5,663], + [27.854,27.973,46,89,15,0,17,3.5,663], + [27.856,28.09,57,88,5,0,17,3.5,663], + [27.858,27.973,69,69,4,0,17,3.5,663], + [27.859,28.09,60,92,5,1,17,3.5,663], + [27.859,28.09,64,88,5,2,17,3.5,663], + [27.969,28.09,45,90,8,0,17,3.75,666], + [27.973,28.09,64,74,4,0,17,3.75,666], + [28.085,28.207,49,114,16,0,18,0,669], + [28.085,28.207,36,109,10,0,18,0,669], + [28.086,28.207,48,82,4,0,18,0,669], + [28.087,29.028,55,86,6,2,18,0,669], + [28.087,28.442,76,90,0,0,18,0,669], + [28.088,29.028,52,85,6,1,18,0,669], + [28.088,29.028,24,91,9,0,18,0,669], + [28.088,28.442,88,92,2,0,18,0,669], + [28.089,29.028,48,82,6,0,18,0,669], + [28.092,28.207,42,66,13,0,18,0,669], + [28.207,28.325,52,60,4,0,18,0.25,672], + [28.207,28.325,36,95,8,0,18,0.25,672], + [28.209,28.325,42,40,13,0,18,0.25,672], + [28.325,28.442,46,90,15,0,18,0.5,674], + [28.326,28.442,55,59,4,0,18,0.5,674], + [28.328,28.442,36,82,8,0,18,0.5,674], + [28.44,28.559,60,64,4,0,18,0.75,677], + [28.441,28.559,36,86,8,0,18,0.75,677], + [28.444,28.559,79,88,2,0,18,0.75,677], + [28.444,28.559,67,92,0,0,18,0.75,677], + [28.445,28.559,42,51,13,0,18,0.75,677], + [28.556,28.676,77,91,0,0,18,1,680], + [28.557,28.676,36,109,10,0,18,1,680], + [28.558,28.676,39,102,12,0,18,1,680], + [28.558,28.676,89,92,2,0,18,1,680], + [28.561,28.676,42,68,13,0,18,1,680], + [28.563,28.676,64,83,4,0,18,1,680], + [28.674,29.028,88,91,2,0,18,1.25,683], + [28.674,28.793,36,96,8,0,18,1.25,683], + [28.675,28.793,42,43,13,0,18,1.25,683], + [28.676,28.793,67,63,4,0,18,1.25,683], + [28.677,29.028,76,88,0,0,18,1.25,683], + [28.791,28.911,60,62,4,0,18,1.5,685], + [28.793,28.911,46,83,15,0,18,1.5,686], + [28.797,28.911,36,81,8,0,18,1.5,686], + [28.908,29.028,36,89,8,0,18,1.75,688], + [28.913,29.028,42,47,13,0,18,1.75,688], + [28.915,29.028,55,64,4,0,18,1.75,688], + [29.024,29.379,86,91,2,0,18,2,691], + [29.024,29.965,62,82,6,2,18,2,691], + [29.029,29.965,55,85,6,0,18,2,691], + [29.029,29.145,42,73,13,0,18,2,691], + [29.029,29.379,74,87,0,0,18,2,691], + [29.03,29.965,59,87,6,1,18,2,691], + [29.03,29.145,55,81,4,0,18,2,691], + [29.03,29.965,31,91,9,0,18,2,691], + [29.031,29.145,36,107,10,0,18,2,691], + [29.144,29.262,42,40,13,0,18,2.25,694], + [29.144,29.262,59,61,4,0,18,2.25,694], + [29.149,29.262,43,97,8,0,18,2.25,694], + [29.259,29.379,43,79,8,0,18,2.5,697], + [29.263,29.379,62,64,4,0,18,2.5,697], + [29.266,29.379,46,87,15,0,18,2.5,697], + [29.377,29.496,43,88,8,0,18,2.75,699], + [29.381,29.496,42,49,13,0,18,2.75,700], + [29.381,29.496,67,62,4,0,18,2.75,700], + [29.383,29.496,65,90,0,0,18,2.75,700], + [29.383,29.496,77,87,2,0,18,2.75,700], + [29.496,29.614,88,88,2,0,18,3,702], + [29.498,29.614,36,108,10,0,18,3,702], + [29.498,29.614,76,90,0,0,18,3,702], + [29.498,29.614,42,65,13,0,18,3,702], + [29.499,29.614,71,84,4,0,18,3,702], + [29.5,29.614,39,101,12,0,18,3,702], + [29.611,29.965,74,93,0,0,18,3.25,705], + [29.611,29.731,74,61,4,0,18,3.25,705], + [29.612,29.965,86,91,2,0,18,3.25,705], + [29.613,29.731,42,41,13,0,18,3.25,705], + [29.614,29.731,43,96,8,0,18,3.25,705], + [29.731,29.848,67,62,4,0,18,3.5,708], + [29.732,29.848,43,77,8,0,18,3.5,708], + [29.733,29.848,46,84,15,0,18,3.5,708], + [29.847,29.965,42,50,13,0,18,3.75,711], + [29.848,29.965,62,60,4,0,18,3.75,711], + [29.851,29.965,43,87,8,0,18,3.75,711], + [29.963,30.903,33,87,9,0,19,0,713], + [29.964,30.082,36,112,10,0,19,0,713], + [29.964,30.903,60,88,6,1,19,0,713], + [29.966,30.317,84,90,2,0,19,0,713], + [29.966,30.082,42,68,13,0,19,0,713], + [29.967,30.903,64,82,6,2,19,0,713], + [29.967,30.903,57,87,6,0,19,0,714], + [29.967,30.082,57,79,4,0,19,0,714], + [29.968,30.317,72,86,0,0,19,0,714], + [30.083,30.2,42,40,13,0,19,0.25,716], + [30.085,30.2,60,59,4,0,19,0.25,716], + [30.087,30.2,45,95,8,0,19,0.25,716], + [30.196,30.317,64,64,4,0,19,0.5,719], + [30.197,30.317,45,83,8,0,19,0.5,719], + [30.198,30.317,46,88,15,0,19,0.5,719], + [30.314,30.434,42,43,13,0,19,0.75,722], + [30.316,30.434,64,91,0,0,19,0.75,722], + [30.318,30.434,69,63,4,0,19,0.75,722], + [30.318,30.434,45,90,8,0,19,0.75,722], + [30.319,30.434,76,88,2,0,19,0.75,722], + [30.429,30.551,72,81,4,0,19,1,725], + [30.43,30.551,86,91,2,0,19,1,725], + [30.433,30.551,36,109,10,0,19,1,725], + [30.434,30.551,39,97,12,0,19,1,725], + [30.435,30.551,42,64,13,0,19,1,725], + [30.436,30.551,74,90,0,0,19,1,725], + [30.549,30.668,42,40,13,0,19,1.25,727], + [30.55,30.668,45,95,8,0,19,1.25,727], + [30.55,30.903,84,92,2,0,19,1.25,727], + [30.551,30.903,72,87,0,0,19,1.25,727], + [30.552,30.668,76,63,4,0,19,1.25,727], + [30.667,30.786,46,87,15,0,19,1.5,730], + [30.667,30.786,69,61,4,0,19,1.5,730], + [30.669,30.786,45,80,8,0,19,1.5,730], + [30.785,30.903,45,89,8,0,19,1.75,733], + [30.785,30.903,42,46,13,0,19,1.75,733], + [30.785,30.903,64,61,4,0,19,1.75,733], + [30.901,31.84,56,87,6,1,19,2,736], + [30.902,31.84,28,91,9,0,19,2,736], + [30.902,31.84,59,86,6,2,19,2,736], + [30.902,31.02,52,83,4,0,19,2,736], + [30.902,31.02,36,111,10,0,19,2,736], + [30.903,31.84,52,86,6,0,19,2,736], + [30.904,31.254,71,88,0,0,19,2,736], + [30.904,31.254,83,92,2,0,19,2,736], + [30.906,31.02,42,70,13,0,19,2,736], + [31.02,31.137,56,61,4,0,19,2.25,739], + [31.02,31.137,42,41,13,0,19,2.25,739], + [31.022,31.137,40,97,8,0,19,2.25,739], + [31.136,31.254,46,89,15,0,19,2.5,741], + [31.137,31.254,40,79,8,0,19,2.5,741], + [31.14,31.254,59,59,4,0,19,2.5,741], + [31.251,31.371,64,60,4,0,19,2.75,744], + [31.252,31.371,42,47,13,0,19,2.75,744], + [31.255,31.371,76,93,2,0,19,2.75,744], + [31.256,31.371,40,86,8,0,19,2.75,744], + [31.259,31.371,64,91,0,0,19,2.75,744], + [31.369,31.606,76,93,0,0,19,3,747], + [31.37,31.489,36,107,10,0,19,3,747], + [31.371,31.489,42,67,13,0,19,3,747], + [31.372,31.489,39,104,12,0,19,3,747], + [31.373,31.489,68,83,4,0,19,3,747], + [31.374,31.606,88,90,2,0,19,3,747], + [31.488,31.606,40,97,8,0,19,3.25,750], + [31.489,31.606,42,42,13,0,19,3.25,750], + [31.491,31.606,71,65,4,0,19,3.25,750], + [31.602,31.723,40,82,8,0,19,3.5,752], + [31.604,31.723,76,89,0,0,19,3.5,752], + [31.605,31.723,46,84,15,0,19,3.5,753], + [31.606,31.723,88,88,2,0,19,3.5,753], + [31.608,31.723,64,64,4,0,19,3.5,753], + [31.718,31.84,100,93,2,0,19,3.75,755], + [31.721,31.84,42,49,13,0,19,3.75,755], + [31.721,31.84,88,91,0,0,19,3.75,755], + [31.722,31.84,40,86,8,0,19,3.75,755], + [31.723,31.84,59,64,4,0,19,3.75,755], + [31.838,32.778,56,84,6,1,20,0,758], + [31.839,32.309,88,89,0,0,20,0,758], + [31.84,32.778,59,90,6,2,20,0,758], + [31.84,31.957,52,80,4,0,20,0,758], + [31.84,31.957,36,112,10,0,20,0,758], + [31.841,32.778,52,85,6,0,20,0,758], + [31.841,32.778,28,91,9,0,20,0,758], + [31.841,32.309,100,89,2,0,20,0,758], + [31.843,31.957,42,69,13,0,20,0,758], + [31.955,32.075,40,96,8,0,20,0.25,761], + [31.956,32.075,42,40,13,0,20,0.25,761], + [31.957,32.075,56,60,4,0,20,0.25,761], + [32.071,32.192,40,85,8,0,20,0.5,764], + [32.074,32.192,46,92,15,0,20,0.5,764], + [32.076,32.192,59,66,4,0,20,0.5,764], + [32.19,32.309,40,88,8,0,20,0.75,766], + [32.193,32.309,42,50,13,0,20,0.75,767], + [32.197,32.309,64,62,4,0,20,0.75,767], + [32.305,32.426,36,109,10,0,20,1,769], + [32.307,32.426,75,89,0,0,20,1,769], + [32.308,32.426,39,98,12,0,20,1,769], + [32.308,32.426,87,91,2,0,20,1,769], + [32.309,32.426,68,83,4,0,20,1,769], + [32.311,32.426,42,65,13,0,20,1,769], + [32.422,32.543,88,92,2,0,20,1.25,772], + [32.424,32.543,40,97,8,0,20,1.25,772], + [32.426,32.543,76,92,0,0,20,1.25,772], + [32.427,32.543,42,38,13,0,20,1.25,772], + [32.429,32.543,71,64,4,0,20,1.25,772], + [32.54,32.661,40,80,8,0,20,1.5,775], + [32.541,32.661,64,63,4,0,20,1.5,775], + [32.543,32.661,46,84,15,0,20,1.5,775], + [32.543,32.661,75,92,0,0,20,1.5,775], + [32.544,32.661,87,91,2,0,20,1.5,775], + [32.659,32.778,59,65,4,0,20,1.75,778], + [32.659,32.778,88,90,2,0,20,1.75,778], + [32.659,32.778,40,86,8,0,20,1.75,778], + [32.66,32.778,42,48,13,0,20,1.75,778], + [32.661,32.778,76,89,0,0,20,1.75,778], + [32.773,32.895,36,112,10,0,20,2,780], + [32.777,33.715,59,87,6,2,20,2,780], + [32.777,32.895,42,67,13,0,20,2,780], + [32.777,33.715,52,87,6,0,20,2,780], + [32.778,32.895,87,92,2,0,20,2,780], + [32.778,32.895,52,80,4,0,20,2,780], + [32.778,32.895,75,86,0,0,20,2,780], + [32.779,33.715,28,89,9,0,20,2,780], + [32.779,33.715,56,85,6,1,20,2,780], + [32.891,33.012,40,95,8,0,20,2.25,783], + [32.894,33.012,76,92,0,0,20,2.25,783], + [32.897,33.012,88,88,2,0,20,2.25,783], + [32.897,33.012,56,62,4,0,20,2.25,783], + [32.898,33.012,42,41,13,0,20,2.25,783], + [33.009,33.129,87,88,2,0,20,2.5,786], + [33.011,33.129,59,58,4,0,20,2.5,786], + [33.011,33.129,40,82,8,0,20,2.5,786], + [33.012,33.129,75,93,0,0,20,2.5,786], + [33.015,33.129,46,87,15,0,20,2.5,786], + [33.128,33.246,88,89,2,0,20,2.75,789], + [33.129,33.246,64,59,4,0,20,2.75,789], + [33.13,33.246,40,85,8,0,20,2.75,789], + [33.131,33.246,42,50,13,0,20,2.75,789], + [33.132,33.246,76,89,0,0,20,2.75,789], + [33.246,33.364,42,60,13,0,20,3,792], + [33.246,33.364,87,92,2,0,20,3,792], + [33.247,33.364,39,108,12,0,20,3,792], + [33.248,33.364,68,80,4,0,20,3,792], + [33.249,33.364,36,103,10,0,20,3,792], + [33.25,33.364,75,88,0,0,20,3,792], + [33.36,33.481,40,92,8,0,20,3.25,794], + [33.362,33.481,88,91,2,0,20,3.25,794], + [33.364,33.481,71,64,4,0,20,3.25,794], + [33.364,33.481,42,38,13,0,20,3.25,794], + [33.365,33.481,76,86,0,0,20,3.25,794], + [33.478,33.715,87,88,2,0,20,3.5,797], + [33.478,33.598,64,66,4,0,20,3.5,797], + [33.481,33.598,46,85,15,0,20,3.5,797], + [33.481,33.598,40,81,8,0,20,3.5,797], + [33.483,33.715,75,86,0,0,20,3.5,797], + [33.593,33.715,42,53,13,0,20,3.75,800], + [33.594,33.715,59,67,4,0,20,3.75,800], + [33.598,33.715,40,88,8,0,20,3.75,800], + [33.711,34.653,28,91,9,0,21,0,803], + [33.711,33.95,52,105,5,0,21,0,803], + [33.713,33.832,42,70,13,0,21,0,803], + [33.713,34.653,52,86,6,0,21,0,803], + [33.713,33.832,52,90,4,0,21,0,803], + [33.714,34.653,59,89,6,2,21,0,803], + [33.715,33.95,56,101,5,1,21,0,803], + [33.716,34.653,56,85,6,1,21,0,803], + [33.716,33.832,49,111,16,0,21,0,803], + [33.716,33.832,88,91,2,0,21,0,803], + [33.717,33.832,76,88,0,0,21,0,803], + [33.718,33.832,36,114,10,0,21,0,803], + [33.718,33.95,59,102,5,2,21,0,803], + [33.83,33.95,87,90,2,0,21,0.25,805], + [33.832,33.95,56,72,4,0,21,0.25,806], + [33.832,33.95,42,39,13,0,21,0.25,806], + [33.832,33.95,40,94,8,0,21,0.25,806], + [33.832,33.95,75,92,0,0,21,0.25,806], + [33.948,34.067,59,74,4,0,21,0.5,808], + [33.949,34.067,88,90,2,0,21,0.5,808], + [33.95,34.067,40,78,8,0,21,0.5,808], + [33.95,34.067,46,93,15,0,21,0.5,808], + [33.953,34.067,76,89,0,0,21,0.5,808], + [34.065,34.301,52,83,5,0,21,0.75,811], + [34.066,34.184,42,48,13,0,21,0.75,811], + [34.067,34.184,64,72,4,0,21,0.75,811], + [34.067,34.301,56,84,5,1,21,0.75,811], + [34.069,34.301,59,85,5,2,21,0.75,811], + [34.069,34.184,75,88,0,0,21,0.75,811], + [34.069,34.184,87,89,2,0,21,0.75,811], + [34.071,34.184,40,90,8,0,21,0.75,811], + [34.181,34.301,42,62,13,0,21,1,814], + [34.183,34.301,39,97,12,0,21,1,814], + [34.184,34.301,36,105,10,0,21,1,814], + [34.186,34.301,76,90,0,0,21,1,814], + [34.187,34.301,68,93,4,0,21,1,814], + [34.187,34.301,88,93,2,0,21,1,814], + [34.296,34.418,42,39,13,0,21,1.25,817], + [34.299,34.418,40,94,8,0,21,1.25,817], + [34.3,34.418,83,89,2,0,21,1.25,817], + [34.301,34.418,71,90,0,0,21,1.25,817], + [34.302,34.418,71,73,4,0,21,1.25,817], + [34.416,34.653,52,94,5,0,21,1.5,819], + [34.417,34.536,46,81,15,0,21,1.5,819], + [34.417,34.536,86,91,2,0,21,1.5,819], + [34.417,34.653,56,90,5,1,21,1.5,819], + [34.417,34.536,40,81,8,0,21,1.5,819], + [34.418,34.536,74,88,0,0,21,1.5,819], + [34.421,34.653,59,91,5,2,21,1.5,820], + [34.421,34.536,64,69,4,0,21,1.5,820], + [34.535,34.653,40,88,8,0,21,1.75,822], + [34.536,34.653,72,90,0,0,21,1.75,822], + [34.536,34.653,42,43,13,0,21,1.75,822], + [34.537,34.653,59,72,4,0,21,1.75,822], + [34.539,34.653,84,88,2,0,21,1.75,822], + [34.65,35.004,69,88,0,0,21,2,825], + [34.65,34.887,57,97,5,0,21,2,825], + [34.651,34.77,42,73,13,0,21,2,825], + [34.651,35.59,64,85,6,2,21,2,825], + [34.652,34.887,64,101,5,2,21,2,825], + [34.652,34.887,60,100,5,1,21,2,825], + [34.653,35.59,57,83,6,0,21,2,825], + [34.653,35.59,60,87,6,1,21,2,825], + [34.654,34.77,57,93,4,0,21,2,825], + [34.654,35.59,33,90,9,0,21,2,825], + [34.654,34.77,36,113,10,0,21,2,825], + [34.657,35.004,81,94,2,0,21,2,825], + [34.769,34.887,60,73,4,0,21,2.25,828], + [34.769,34.887,45,94,8,0,21,2.25,828], + [34.771,34.887,42,37,13,0,21,2.25,828], + [34.884,35.004,45,81,8,0,21,2.5,831], + [34.884,35.004,64,72,4,0,21,2.5,831], + [34.89,35.004,46,87,15,0,21,2.5,831], + [35,35.121,72,92,2,0,21,2.75,833], + [35.002,35.121,42,49,13,0,21,2.75,833], + [35.005,35.121,45,87,8,0,21,2.75,833], + [35.005,35.239,57,86,5,0,21,2.75,833], + [35.005,35.239,64,86,5,2,21,2.75,833], + [35.006,35.121,69,73,4,0,21,2.75,833], + [35.006,35.121,60,90,0,0,21,2.75,833], + [35.007,35.239,60,81,5,1,21,2.75,833], + [35.118,35.239,39,101,12,0,21,3,836], + [35.119,35.239,36,107,10,0,21,3,836], + [35.119,35.239,72,91,4,0,21,3,836], + [35.12,35.239,42,67,13,0,21,3,836], + [35.123,35.239,76,89,2,0,21,3,836], + [35.124,35.239,64,89,0,0,21,3,836], + [35.237,35.59,69,90,0,0,21,3.25,839], + [35.238,35.356,76,69,4,0,21,3.25,839], + [35.238,35.356,42,41,13,0,21,3.25,839], + [35.239,35.59,81,92,2,0,21,3.25,839], + [35.24,35.356,45,96,8,0,21,3.25,839], + [35.352,35.473,45,81,8,0,21,3.5,842], + [35.355,35.473,46,82,15,0,21,3.5,842], + [35.356,35.473,69,70,4,0,21,3.5,842], + [35.357,35.59,60,89,5,1,21,3.5,842], + [35.357,35.59,57,94,5,0,21,3.5,842], + [35.359,35.59,64,93,5,2,21,3.5,842], + [35.471,35.59,64,71,4,0,21,3.75,845], + [35.474,35.59,45,91,8,0,21,3.75,845], + [35.476,35.59,42,54,13,0,21,3.75,845], + [35.588,36.528,59,85,6,2,22,0,847], + [35.589,35.707,36,110,10,0,22,0,847], + [35.59,35.707,42,69,13,0,22,0,847], + [35.59,35.942,83,90,2,0,22,0,847], + [35.59,35.825,52,100,5,0,22,0,847], + [35.59,36.528,28,88,9,0,22,0,847], + [35.59,35.825,59,99,5,2,22,0,847], + [35.59,36.528,56,87,6,1,22,0,847], + [35.591,35.825,56,99,5,1,22,0,847], + [35.591,36.528,52,89,6,0,22,0,847], + [35.592,35.707,52,94,4,0,22,0,847], + [35.592,35.942,71,93,0,0,22,0,847], + [35.708,35.825,40,95,8,0,22,0.25,850], + [35.709,35.825,42,40,13,0,22,0.25,850], + [35.712,35.825,56,76,4,0,22,0.25,850], + [35.821,35.942,46,87,15,0,22,0.5,853], + [35.821,35.942,59,72,4,0,22,0.5,853], + [35.823,35.942,40,82,8,0,22,0.5,853], + [35.939,36.176,59,80,5,2,22,0.75,856], + [35.94,36.059,42,50,13,0,22,0.75,856], + [35.94,36.176,52,81,5,0,22,0.75,856], + [35.943,36.059,64,75,4,0,22,0.75,856], + [35.944,36.176,56,83,5,1,22,0.75,856], + [35.944,36.059,64,89,0,0,22,0.75,856], + [35.946,36.059,40,88,8,0,22,0.75,856], + [35.947,36.059,76,90,2,0,22,0.75,856], + [36.057,36.176,36,109,10,0,22,1,859], + [36.057,36.176,39,101,12,0,22,1,859], + [36.058,36.176,68,89,4,0,22,1,859], + [36.058,36.176,42,63,13,0,22,1,859], + [36.058,36.176,80,90,2,0,22,1,859], + [36.059,36.176,68,91,0,0,22,1,859], + [36.174,36.528,83,87,2,0,22,1.25,861], + [36.175,36.293,42,36,13,0,22,1.25,861], + [36.176,36.293,40,96,8,0,22,1.25,861], + [36.177,36.528,71,90,0,0,22,1.25,861], + [36.18,36.293,71,72,4,0,22,1.25,861], + [36.292,36.528,56,94,5,1,22,1.5,864], + [36.293,36.411,64,70,4,0,22,1.5,864], + [36.294,36.528,59,90,5,2,22,1.5,864], + [36.295,36.411,40,83,8,0,22,1.5,864], + [36.296,36.528,52,93,5,0,22,1.5,864], + [36.296,36.411,46,84,15,0,22,1.5,864], + [36.409,36.528,40,89,8,0,22,1.75,867], + [36.414,36.528,59,74,4,0,22,1.75,867], + [36.414,36.528,42,46,13,0,22,1.75,867], + [36.525,36.762,64,101,5,2,22,2,870], + [36.525,36.645,42,68,13,0,22,2,870], + [36.526,37.465,33,87,9,0,22,2,870], + [36.527,36.762,57,104,5,0,22,2,870], + [36.527,36.879,72,89,0,0,22,2,870], + [36.528,36.879,84,90,2,0,22,2,870], + [36.528,37.465,64,85,6,2,22,2,870], + [36.528,36.762,60,101,5,1,22,2,870], + [36.529,36.645,36,113,10,0,22,2,870], + [36.53,37.465,60,85,6,1,22,2,870], + [36.531,36.645,57,93,4,0,22,2,870], + [36.533,37.465,57,86,6,0,22,2,870], + [36.646,36.762,60,71,4,0,22,2.25,873], + [36.647,36.762,45,98,8,0,22,2.25,873], + [36.648,36.762,42,41,13,0,22,2.25,873], + [36.76,36.879,45,81,8,0,22,2.5,875], + [36.763,36.879,46,87,15,0,22,2.5,875], + [36.766,36.879,64,72,4,0,22,2.5,875], + [36.875,37.114,60,86,5,1,22,2.75,878], + [36.878,36.996,76,90,2,0,22,2.75,878], + [36.879,37.114,64,84,5,2,22,2.75,878], + [36.879,36.996,64,90,0,0,22,2.75,878], + [36.88,36.996,69,73,4,0,22,2.75,878], + [36.881,37.114,57,82,5,0,22,2.75,878], + [36.881,36.996,45,91,8,0,22,2.75,878], + [36.882,36.996,42,50,13,0,22,2.75,878], + [36.994,37.114,39,104,12,0,22,3,881], + [36.994,37.114,36,107,10,0,22,3,881], + [36.995,37.114,42,65,13,0,22,3,881], + [36.996,37.114,72,90,4,0,22,3,881], + [36.998,37.465,76,91,0,0,22,3,881], + [36.999,37.465,88,90,2,0,22,3,881], + [37.111,37.231,42,39,13,0,22,3.25,884], + [37.113,37.231,45,96,8,0,22,3.25,884], + [37.116,37.231,76,71,4,0,22,3.25,884], + [37.228,37.348,45,84,8,0,22,3.5,886], + [37.23,37.348,69,72,4,0,22,3.5,886], + [37.23,37.465,64,93,5,2,22,3.5,886], + [37.231,37.348,46,86,15,0,22,3.5,886], + [37.233,37.465,60,90,5,1,22,3.5,887], + [37.234,37.465,57,96,5,0,22,3.5,887], + [37.348,37.465,64,71,4,0,22,3.75,889], + [37.348,37.465,42,51,13,0,22,3.75,889], + [37.35,37.465,45,84,8,0,22,3.75,889], + [37.461,37.7,56,100,5,1,23,0,892], + [37.463,38.403,28,90,9,0,23,0,892], + [37.463,37.582,88,91,2,0,23,0,892], + [37.463,37.7,52,98,5,0,23,0,892], + [37.464,37.582,36,113,10,0,23,0,892], + [37.464,37.7,59,104,5,2,23,0,892], + [37.464,38.403,56,86,6,1,23,0,892], + [37.465,37.582,52,91,4,0,23,0,892], + [37.465,38.403,59,86,6,2,23,0,892], + [37.465,38.403,52,84,6,0,23,0,892], + [37.467,37.582,42,69,13,0,23,0,892], + [37.467,37.582,76,89,0,0,23,0,892], + [37.579,37.7,42,36,13,0,23,0.25,895], + [37.58,37.7,87,90,2,0,23,0.25,895], + [37.581,37.7,40,94,8,0,23,0.25,895], + [37.583,37.7,56,72,4,0,23,0.25,895], + [37.583,37.7,75,90,0,0,23,0.25,895], + [37.697,37.817,46,90,15,0,23,0.5,898], + [37.698,37.817,88,89,2,0,23,0.5,898], + [37.698,37.817,40,83,8,0,23,0.5,898], + [37.7,37.817,59,71,4,0,23,0.5,898], + [37.704,37.817,76,86,0,0,23,0.5,898], + [37.815,37.934,64,68,4,0,23,0.75,900], + [37.815,37.934,42,47,13,0,23,0.75,900], + [37.815,37.934,40,91,8,0,23,0.75,900], + [37.817,38.051,52,82,5,0,23,0.75,900], + [37.817,38.051,56,82,5,1,23,0.75,900], + [37.817,38.051,59,82,5,2,23,0.75,900], + [37.818,37.934,87,87,2,0,23,0.75,900], + [37.82,37.934,75,87,0,0,23,0.75,900], + [37.932,38.051,42,62,13,0,23,1,903], + [37.933,38.051,88,87,2,0,23,1,903], + [37.934,38.051,76,90,0,0,23,1,903], + [37.935,38.051,36,109,10,0,23,1,903], + [37.936,38.051,68,91,4,0,23,1,903], + [37.936,38.051,39,98,12,0,23,1,903], + [38.046,38.168,42,40,13,0,23,1.25,906], + [38.049,38.168,71,71,4,0,23,1.25,906], + [38.049,38.168,71,89,0,0,23,1.25,906], + [38.049,38.168,40,97,8,0,23,1.25,906], + [38.053,38.168,83,90,2,0,23,1.25,906], + [38.165,38.286,46,80,15,0,23,1.5,909], + [38.167,38.403,56,95,5,1,23,1.5,909], + [38.167,38.286,74,90,0,0,23,1.5,909], + [38.168,38.403,59,92,5,2,23,1.5,909], + [38.168,38.403,52,93,5,0,23,1.5,909], + [38.169,38.286,64,73,4,0,23,1.5,909], + [38.17,38.286,86,86,2,0,23,1.5,909], + [38.171,38.286,40,81,8,0,23,1.5,909], + [38.284,38.403,84,88,2,0,23,1.75,912], + [38.284,38.403,40,86,8,0,23,1.75,912], + [38.285,38.403,72,91,0,0,23,1.75,912], + [38.288,38.403,59,72,4,0,23,1.75,912], + [38.289,38.403,42,44,13,0,23,1.75,912], + [38.399,38.52,57,95,4,0,23,2,914], + [38.401,38.637,57,98,5,0,23,2,914], + [38.401,38.754,69,89,0,0,23,2,914], + [38.401,38.754,81,89,2,0,23,2,914], + [38.401,38.637,64,104,5,2,23,2,914], + [38.403,39.34,64,87,6,2,23,2,914], + [38.404,38.52,36,107,10,0,23,2,914], + [38.404,38.637,60,103,5,1,23,2,914], + [38.404,39.34,57,85,6,0,23,2,914], + [38.405,38.52,42,68,13,0,23,2,914], + [38.406,39.34,33,87,9,0,23,2,914], + [38.406,39.34,60,89,6,1,23,2,914], + [38.518,38.637,42,36,13,0,23,2.25,917], + [38.518,38.637,45,97,8,0,23,2.25,917], + [38.519,38.637,60,76,4,0,23,2.25,917], + [38.634,38.754,64,75,4,0,23,2.5,920], + [38.637,38.754,46,88,15,0,23,2.5,920], + [38.641,38.754,45,84,8,0,23,2.5,920], + [38.752,38.871,69,74,4,0,23,2.75,923], + [38.753,38.989,60,85,5,1,23,2.75,923], + [38.753,38.871,72,91,2,0,23,2.75,923], + [38.753,38.989,64,87,5,2,23,2.75,923], + [38.754,38.989,57,81,5,0,23,2.75,923], + [38.755,38.871,45,88,8,0,23,2.75,923], + [38.755,38.871,60,90,0,0,23,2.75,923], + [38.757,38.871,42,48,13,0,23,2.75,923], + [38.868,38.989,42,64,13,0,23,3,925], + [38.87,38.989,64,89,0,0,23,3,925], + [38.873,38.989,76,91,2,0,23,3,926], + [38.874,38.989,39,106,12,0,23,3,926], + [38.874,38.989,36,108,10,0,23,3,926], + [38.876,38.989,72,94,4,0,23,3,926], + [38.987,39.106,76,75,4,0,23,3.25,928], + [38.988,39.34,81,89,2,0,23,3.25,928], + [38.988,39.34,69,87,0,0,23,3.25,928], + [38.988,39.106,45,98,8,0,23,3.25,928], + [38.99,39.106,42,41,13,0,23,3.25,928], + [39.104,39.34,57,90,5,0,23,3.5,931], + [39.105,39.223,45,81,8,0,23,3.5,931], + [39.106,39.34,64,90,5,2,23,3.5,931], + [39.106,39.223,69,71,4,0,23,3.5,931], + [39.106,39.223,46,84,15,0,23,3.5,931], + [39.11,39.34,60,95,5,1,23,3.5,931], + [39.222,39.34,64,74,4,0,23,3.75,934], + [39.223,39.34,42,51,13,0,23,3.75,934], + [39.224,39.34,45,90,8,0,23,3.75,934], + [39.338,40.278,59,85,6,2,24,0,937], + [39.339,39.457,36,113,10,0,24,0,937], + [39.339,39.575,56,99,5,1,24,0,937], + [39.339,40.278,56,84,6,1,24,0,937], + [39.339,40.278,28,90,9,0,24,0,937], + [39.341,39.457,42,70,13,0,24,0,937], + [39.341,39.692,71,92,0,0,24,0,937], + [39.341,39.692,83,87,2,0,24,0,937], + [39.341,39.575,59,97,5,2,24,0,937], + [39.342,39.575,52,97,5,0,24,0,937], + [39.342,39.457,52,90,4,0,24,0,937], + [39.343,40.278,52,82,6,0,24,0,937], + [39.453,39.575,42,41,13,0,24,0.25,939], + [39.457,39.575,40,93,8,0,24,0.25,939], + [39.46,39.575,56,71,4,0,24,0.25,940], + [39.571,39.692,40,81,8,0,24,0.5,942], + [39.572,39.692,59,71,4,0,24,0.5,942], + [39.573,39.692,46,89,15,0,24,0.5,942], + [39.688,39.809,42,51,13,0,24,0.75,945], + [39.689,39.809,64,89,0,0,24,0.75,945], + [39.69,39.926,52,85,5,0,24,0.75,945], + [39.69,39.809,76,89,2,0,24,0.75,945], + [39.692,39.809,64,71,4,0,24,0.75,945], + [39.693,39.926,59,84,5,2,24,0.75,945], + [39.694,39.809,40,86,8,0,24,0.75,945], + [39.695,39.926,56,81,5,1,24,0.75,945], + [39.808,39.926,36,107,10,0,24,1,948], + [39.808,39.926,68,93,4,0,24,1,948], + [39.808,39.926,42,62,13,0,24,1,948], + [39.81,39.926,72,91,0,0,24,1,948], + [39.81,39.926,39,99,12,0,24,1,948], + [39.811,39.926,84,87,2,0,24,1,948], + [39.925,40.278,71,92,0,0,24,1.25,951], + [39.926,40.043,42,40,13,0,24,1.25,951], + [39.927,40.278,83,89,2,0,24,1.25,951], + [39.927,40.043,71,71,4,0,24,1.25,951], + [39.928,40.043,40,95,8,0,24,1.25,951], + [40.041,40.161,46,86,15,0,24,1.5,953], + [40.043,40.161,64,75,4,0,24,1.5,953], + [40.044,40.161,40,81,8,0,24,1.5,953], + [40.046,40.278,52,88,5,0,24,1.5,953], + [40.046,40.278,59,92,5,2,24,1.5,953], + [40.047,40.278,56,92,5,1,24,1.5,954], + [40.159,40.278,42,47,13,0,24,1.75,956], + [40.161,40.278,40,84,8,0,24,1.75,956], + [40.162,40.278,59,73,4,0,24,1.75,956], + [40.273,40.395,36,110,10,0,24,2,959], + [40.275,41.215,57,85,6,0,24,2,959], + [40.275,40.512,60,96,5,1,24,2,959], + [40.276,40.512,64,105,5,2,24,2,959], + [40.276,40.395,57,91,4,0,24,2,959], + [40.277,40.512,57,102,5,0,24,2,959], + [40.278,41.215,64,85,6,2,24,2,959], + [40.278,41.215,69,89,0,0,24,2,959], + [40.279,41.215,33,91,9,0,24,2,959], + [40.279,40.395,42,69,13,0,24,2,959], + [40.279,41.215,81,88,2,0,24,2,959], + [40.28,41.215,60,84,6,1,24,2,959], + [40.393,40.512,45,92,8,0,24,2.25,962], + [40.397,40.512,42,40,13,0,24,2.25,962], + [40.4,40.512,60,71,4,0,24,2.25,962], + [40.511,40.629,46,92,15,0,24,2.5,965], + [40.511,40.629,45,81,8,0,24,2.5,965], + [40.514,40.629,64,71,4,0,24,2.5,965], + [40.627,40.864,60,84,5,1,24,2.75,967], + [40.628,40.746,45,88,8,0,24,2.75,967], + [40.631,40.746,42,47,13,0,24,2.75,967], + [40.631,40.864,64,84,5,2,24,2.75,967], + [40.632,40.746,69,73,4,0,24,2.75,967], + [40.633,40.864,57,87,5,0,24,2.75,967], + [40.746,40.864,42,63,13,0,24,3,970], + [40.748,40.864,36,104,10,0,24,3,970], + [40.748,40.864,39,105,12,0,24,3,970], + [40.749,40.864,72,91,4,0,24,3,970], + [40.865,40.981,45,97,8,0,24,3.25,973], + [40.867,40.981,42,42,13,0,24,3.25,973], + [40.867,40.981,76,73,4,0,24,3.25,973], + [40.976,41.098,45,84,8,0,24,3.5,976], + [40.98,41.098,46,87,15,0,24,3.5,976], + [40.98,41.215,57,93,5,0,24,3.5,976], + [40.98,41.215,64,91,5,2,24,3.5,976], + [40.982,41.098,69,71,4,0,24,3.5,976], + [40.983,41.215,60,89,5,1,24,3.5,976], + [41.096,41.215,64,71,4,0,24,3.75,978], + [41.097,41.215,42,54,13,0,24,3.75,978], + [41.098,41.215,45,89,8,0,24,3.75,979], + [41.21,41.332,42,69,13,0,25,0,981], + [41.215,41.332,36,106,10,0,25,0,981], + [41.215,42.153,64,87,6,2,25,0,981], + [41.215,42.153,69,89,0,0,25,0,981], + [41.215,42.153,57,86,6,0,25,0,981], + [41.216,41.332,40,100,18,0,25,0,981], + [41.216,41.332,38,71,14,0,25,0,981], + [41.217,42.153,33,88,9,0,25,0,981], + [41.217,42.153,81,86,2,0,25,0,981], + [41.219,42.153,60,82,6,1,25,0,981], + [41.331,41.45,42,40,13,0,25,0.25,984], + [41.335,41.45,38,76,14,0,25,0.25,984], + [41.447,41.567,38,79,14,0,25,0.5,987], + [41.564,41.684,38,81,14,0,25,0.75,990], + [41.566,41.684,42,50,13,0,25,0.75,990], + [41.683,41.801,42,65,13,0,25,1,992], + [41.684,41.801,38,88,14,0,25,1,992], + [41.8,41.918,42,41,13,0,25,1.25,995], + [41.8,41.918,38,88,14,0,25,1.25,995], + [41.918,42.036,38,96,14,0,25,1.5,998], + [42.033,42.153,42,49,13,0,25,1.75,1001], + [42.036,42.153,38,96,14,0,25,1.75,1001], + [42.15,43.09,33,91,9,0,25,2,1004], + [42.15,42.27,42,72,13,0,25,2,1004], + [42.151,43.09,60,87,6,1,25,2,1004], + [42.152,42.27,36,95,10,0,25,2,1004], + [42.153,43.09,57,87,6,0,25,2,1004], + [42.153,42.27,38,99,14,0,25,2,1004], + [42.155,43.09,64,86,6,2,25,2,1004], + [42.271,42.387,38,107,14,0,25,2.25,1006], + [42.271,42.387,42,41,13,0,25,2.25,1006], + [42.386,42.504,38,109,14,0,25,2.5,1009], + [42.501,42.621,38,113,14,0,25,2.75,1012], + [42.506,42.621,42,51,13,0,25,2.75,1012], + [42.621,42.739,38,118,14,0,25,3,1015], + [42.623,42.739,42,64,13,0,25,3,1015], + [42.738,42.856,42,38,13,0,25,3.25,1018], + [42.739,42.856,38,124,14,0,25,3.25,1018], + [42.858,42.973,38,126,14,0,25,3.5,1020], + [42.97,43.09,38,126,14,0,25,3.75,1023], + [42.976,43.09,42,50,13,0,25,3.75,1023], + [43.088,44.028,57,79,6,1,26,0,1026], + [43.088,44.028,29,90,9,0,26,0,1026], + [43.089,43.559,72,74,0,0,26,0,1026], + [43.09,44.028,60,80,6,2,26,0,1026], + [43.091,44.028,53,77,6,0,26,0,1026], + [43.091,43.207,49,82,16,0,26,0,1026], + [43.093,43.207,41,63,1,0,26,0,1026], + [43.209,43.325,53,54,1,0,26,0.25,1029], + [43.325,43.442,57,49,1,0,26,0.5,1032], + [43.442,43.559,60,49,1,0,26,0.75,1034], + [43.56,43.676,57,52,1,0,26,1,1037], + [43.562,43.793,77,71,0,0,26,1,1037], + [43.678,43.793,60,53,1,0,26,1.25,1040], + [43.795,44.028,76,71,0,0,26,1.5,1043], + [43.796,43.911,65,49,1,0,26,1.5,1043], + [43.911,44.028,60,46,1,0,26,1.75,1045], + [44.023,44.965,58,77,6,0,26,2,1048], + [44.024,44.965,65,78,6,2,26,2,1048], + [44.026,44.145,46,63,1,0,26,2,1048], + [44.027,44.262,76,69,0,0,26,2,1048], + [44.027,44.965,62,77,6,1,26,2,1048], + [44.031,44.965,34,95,9,0,26,2,1048], + [44.142,44.262,58,50,1,0,26,2.25,1051], + [44.26,44.379,62,48,1,0,26,2.5,1054], + [44.264,44.496,74,75,0,0,26,2.5,1054], + [44.377,44.496,65,50,1,0,26,2.75,1057], + [44.497,44.731,82,72,0,0,26,3,1059], + [44.499,44.614,62,45,1,0,26,3,1059], + [44.612,44.731,65,50,1,0,26,3.25,1062], + [44.73,44.965,81,71,0,0,26,3.5,1065], + [44.732,44.848,70,52,1,0,26,3.5,1065], + [44.849,44.965,65,48,1,0,26,3.75,1068], + [44.96,45.903,48,75,6,0,27,0,1070], + [44.962,45.903,52,79,6,1,27,0,1071], + [44.965,45.903,55,80,6,2,27,0,1071], + [44.967,45.082,81,74,0,0,27,0,1071], + [44.968,45.082,36,63,1,0,27,0,1071], + [44.971,45.903,24,93,9,0,27,0,1071], + [45.082,45.2,48,54,1,0,27,0.25,1073], + [45.082,45.2,79,75,0,0,27,0.25,1073], + [45.197,45.317,52,50,1,0,27,0.5,1076], + [45.197,45.317,77,71,0,0,27,0.5,1076], + [45.316,45.434,55,50,1,0,27,0.75,1079], + [45.316,45.434,76,71,0,0,27,0.75,1079], + [45.434,45.551,74,75,0,0,27,1,1082], + [45.435,45.551,52,50,1,0,27,1,1082], + [45.55,45.668,55,50,1,0,27,1.25,1085], + [45.554,45.903,72,77,0,0,27,1.25,1085], + [45.666,45.786,60,51,1,0,27,1.5,1087], + [45.787,45.903,55,51,1,0,27,1.75,1090], + [45.901,46.02,41,63,1,0,27,2,1093], + [45.901,46.137,70,75,0,0,27,2,1093], + [45.902,46.84,60,77,6,2,27,2,1093], + [45.902,46.84,29,90,9,0,27,2,1093], + [45.904,46.84,57,76,6,1,27,2,1093], + [45.906,46.84,53,77,6,0,27,2,1093], + [46.02,46.137,53,51,1,0,27,2.25,1096], + [46.136,46.371,69,73,0,0,27,2.5,1098], + [46.14,46.254,57,50,1,0,27,2.5,1099], + [46.255,46.371,60,50,1,0,27,2.75,1101], + [46.368,46.489,57,50,1,0,27,3,1104], + [46.372,46.489,69,73,0,0,27,3,1104], + [46.487,46.606,67,73,0,0,27,3.25,1107], + [46.491,46.606,60,52,1,0,27,3.25,1107], + [46.602,46.723,69,73,0,0,27,3.5,1110], + [46.604,46.723,65,56,1,0,27,3.5,1110], + [46.722,46.84,70,76,0,0,27,3.75,1112], + [46.727,46.84,60,48,1,0,27,3.75,1113], + [46.839,47.309,72,75,0,0,28,0,1115], + [46.84,47.778,53,81,6,0,28,0,1115], + [46.841,47.778,57,81,6,1,28,0,1115], + [46.842,46.957,41,62,1,0,28,0,1115], + [46.842,47.778,60,77,6,2,28,0,1115], + [46.842,47.778,29,90,9,0,28,0,1115], + [46.958,47.075,53,53,1,0,28,0.25,1118], + [47.071,47.192,57,48,1,0,28,0.5,1121], + [47.189,47.309,60,51,1,0,28,0.75,1124], + [47.307,47.426,57,47,1,0,28,1,1126], + [47.307,47.543,74,71,0,0,28,1,1126], + [47.427,47.543,60,49,1,0,28,1.25,1129], + [47.541,47.778,75,73,0,0,28,1.5,1132], + [47.548,47.661,65,50,1,0,28,1.5,1132], + [47.656,47.778,60,50,1,0,28,1.75,1135], + [47.775,48.715,64,75,6,2,28,2,1137], + [47.776,48.715,33,92,9,0,28,2,1138], + [47.776,48.129,76,77,0,0,28,2,1138], + [47.778,48.715,60,74,6,1,28,2,1138], + [47.78,48.715,57,80,6,0,28,2,1138], + [47.78,47.895,45,67,1,0,28,2,1138], + [47.89,48.012,57,55,1,0,28,2.25,1140], + [48.012,48.129,60,50,1,0,28,2.5,1143], + [48.127,48.246,76,69,0,0,28,2.75,1146], + [48.13,48.246,64,52,1,0,28,2.75,1146], + [48.246,48.481,77,72,0,0,28,3,1149], + [48.247,48.364,60,46,1,0,28,3,1149], + [48.364,48.481,64,52,1,0,28,3.25,1152], + [48.482,48.598,69,55,1,0,28,3.5,1154], + [48.483,48.715,69,77,0,0,28,3.5,1154], + [48.599,48.715,64,44,1,0,28,3.75,1157], + [48.712,49.653,59,78,6,1,29,0,1160], + [48.714,49.653,31,90,9,0,29,0,1160], + [48.714,49.653,62,81,6,2,29,0,1160], + [48.715,49.184,72,72,0,0,29,0,1160], + [48.715,49.653,55,77,6,0,29,0,1160], + [48.717,48.832,43,65,1,0,29,0,1160], + [48.831,48.95,55,50,1,0,29,0.25,1163], + [48.95,49.067,59,50,1,0,29,0.5,1165], + [49.068,49.184,62,53,1,0,29,0.75,1168], + [49.18,49.301,59,49,1,0,29,1,1171], + [49.186,49.418,74,74,0,0,29,1,1171], + [49.302,49.418,62,47,1,0,29,1.25,1174], + [49.418,49.536,67,51,1,0,29,1.5,1177], + [49.419,49.653,71,74,0,0,29,1.5,1177], + [49.533,49.653,62,46,1,0,29,1.75,1179], + [49.648,50.59,52,78,6,1,29,2,1182], + [49.652,50.59,72,72,0,0,29,2,1182], + [49.652,50.59,24,86,9,0,29,2,1182], + [49.654,50.59,55,78,6,2,29,2,1182], + [49.655,49.77,36,66,1,0,29,2,1182], + [49.656,50.59,48,79,6,0,29,2,1182], + [49.772,49.887,48,51,1,0,29,2.25,1185], + [49.887,50.004,52,48,1,0,29,2.5,1188], + [50.005,50.121,55,52,1,0,29,2.75,1191], + [50.123,50.239,52,47,1,0,29,3,1193], + [50.237,50.356,55,52,1,0,29,3.25,1196], + [50.354,50.473,60,49,1,0,29,3.5,1199], + [50.474,50.59,55,49,1,0,29,3.75,1202], + [50.588,50.707,88,76,2,0,30,0,1204], + [50.588,51.528,59,85,6,2,30,0,1204], + [50.59,50.707,36,106,10,0,30,0,1205], + [50.59,51.528,52,79,6,0,30,0,1205], + [50.591,51.528,28,92,9,0,30,0,1205], + [50.591,50.707,76,72,0,0,30,0,1205], + [50.592,50.707,43,101,18,0,30,0,1205], + [50.592,51.528,56,77,6,1,30,0,1205], + [50.593,50.707,38,59,14,0,30,0,1205], + [50.594,50.707,52,82,4,0,30,0,1205], + [50.705,50.825,40,85,8,0,30,0.25,1207], + [50.706,50.825,89,76,2,0,30,0.25,1207], + [50.709,50.825,56,57,4,0,30,0.25,1207], + [50.711,50.825,77,74,0,0,30,0.25,1207], + [50.821,50.942,76,72,0,0,30,0.5,1210], + [50.823,50.942,88,73,2,0,30,0.5,1210], + [50.824,50.942,59,57,4,0,30,0.5,1210], + [50.827,50.942,40,68,8,0,30,0.5,1210], + [50.94,51.059,87,75,2,0,30,0.75,1213], + [50.94,51.059,64,61,4,0,30,0.75,1213], + [50.941,51.059,75,75,0,0,30,0.75,1213], + [50.941,51.059,40,75,8,0,30,0.75,1213], + [51.057,51.176,38,61,14,0,30,1,1216], + [51.057,51.176,76,74,0,0,30,1,1216], + [51.058,51.176,88,70,2,0,30,1,1216], + [51.061,51.176,68,80,4,0,30,1,1216], + [51.173,51.293,71,72,0,0,30,1.25,1218], + [51.174,51.293,40,80,8,0,30,1.25,1218], + [51.177,51.293,83,74,2,0,30,1.25,1219], + [51.18,51.293,71,59,4,0,30,1.25,1219], + [51.292,51.411,76,78,0,0,30,1.5,1221], + [51.292,51.411,88,73,2,0,30,1.5,1221], + [51.293,51.411,64,60,4,0,30,1.5,1221], + [51.294,51.411,40,67,8,0,30,1.5,1221], + [51.408,51.528,40,71,8,0,30,1.75,1224], + [51.409,51.528,75,75,0,0,30,1.75,1224], + [51.41,51.528,59,56,4,0,30,1.75,1224], + [51.41,51.528,87,75,2,0,30,1.75,1224], + [51.526,52.465,59,78,6,2,30,2,1227], + [51.526,52.465,28,91,9,0,30,2,1227], + [51.526,51.645,88,75,2,0,30,2,1227], + [51.526,52.465,56,78,6,1,30,2,1227], + [51.527,51.645,38,65,14,0,30,2,1227], + [51.528,51.645,76,75,0,0,30,2,1227], + [51.528,51.645,36,103,10,0,30,2,1227], + [51.529,51.645,52,77,4,0,30,2,1227], + [51.529,52.465,52,81,6,0,30,2,1227], + [51.641,51.762,40,80,8,0,30,2.25,1230], + [51.643,51.762,56,55,4,0,30,2.25,1230], + [51.645,51.762,71,73,0,0,30,2.25,1230], + [51.649,51.762,83,74,2,0,30,2.25,1230], + [51.76,51.879,88,72,2,0,30,2.5,1232], + [51.763,51.879,76,72,0,0,30,2.5,1232], + [51.763,51.879,40,68,8,0,30,2.5,1232], + [51.763,51.879,59,59,4,0,30,2.5,1232], + [51.876,51.996,87,71,2,0,30,2.75,1235], + [51.876,51.996,75,74,0,0,30,2.75,1235], + [51.876,51.996,64,59,4,0,30,2.75,1235], + [51.88,51.996,40,73,8,0,30,2.75,1235], + [51.995,52.114,38,68,14,0,30,3,1238], + [51.995,52.114,68,80,4,0,30,3,1238], + [51.996,52.114,76,77,0,0,30,3,1238], + [52,52.114,88,74,2,0,30,3,1238], + [52.111,52.231,40,81,8,0,30,3.25,1241], + [52.112,52.231,77,74,0,0,30,3.25,1241], + [52.114,52.231,71,59,4,0,30,3.25,1241], + [52.115,52.231,89,76,2,0,30,3.25,1241], + [52.229,52.348,64,58,4,0,30,3.5,1244], + [52.231,52.348,88,73,2,0,30,3.5,1244], + [52.233,52.348,76,71,0,0,30,3.5,1244], + [52.234,52.348,40,67,8,0,30,3.5,1244], + [52.348,52.465,87,77,2,0,30,3.75,1246], + [52.349,52.465,75,76,0,0,30,3.75,1246], + [52.349,52.465,59,57,4,0,30,3.75,1246], + [52.35,52.465,40,76,8,0,30,3.75,1246], + [52.461,53.403,59,86,6,2,31,0,1249], + [52.461,54.34,64,61,7,2,31,0,1249], + [52.462,53.403,56,85,6,1,31,0,1249], + [52.462,54.34,59,61,7,1,31,0,1249], + [52.462,53.403,52,82,6,0,31,0,1249], + [52.462,52.582,38,72,14,0,31,0,1249], + [52.463,52.582,76,72,0,0,31,0,1249], + [52.463,53.403,28,90,9,0,31,0,1249], + [52.463,52.582,36,111,10,0,31,0,1249], + [52.463,52.582,52,84,4,0,31,0,1249], + [52.465,54.34,52,64,7,0,31,0,1249], + [52.467,52.582,88,74,2,0,31,0,1249], + [52.581,52.7,40,87,8,0,31,0.25,1252], + [52.583,52.7,56,60,4,0,31,0.25,1252], + [52.583,52.7,89,76,2,0,31,0.25,1252], + [52.583,52.7,77,78,0,0,31,0.25,1252], + [52.698,52.817,76,75,0,0,31,0.5,1255], + [52.699,52.817,38,75,14,0,31,0.5,1255], + [52.702,52.817,59,66,4,0,31,0.5,1255], + [52.702,52.817,40,78,8,0,31,0.5,1255], + [52.702,52.817,88,73,2,0,31,0.5,1255], + [52.814,52.934,40,79,8,0,31,0.75,1257], + [52.815,52.934,64,64,4,0,31,0.75,1257], + [52.816,52.934,75,71,0,0,31,0.75,1258], + [52.817,52.934,87,77,2,0,31,0.75,1258], + [52.931,53.051,38,79,14,0,31,1,1260], + [52.933,53.051,36,109,10,0,31,1,1260], + [52.933,53.051,88,74,2,0,31,1,1260], + [52.934,53.051,68,83,4,0,31,1,1260], + [52.934,53.051,76,73,0,0,31,1,1260], + [53.047,53.168,71,72,0,0,31,1.25,1263], + [53.049,53.168,71,63,4,0,31,1.25,1263], + [53.052,53.168,40,86,8,0,31,1.25,1263], + [53.053,53.168,83,76,2,0,31,1.25,1263], + [53.168,53.286,38,82,14,0,31,1.5,1266], + [53.168,53.286,64,65,4,0,31,1.5,1266], + [53.169,53.286,88,74,2,0,31,1.5,1266], + [53.169,53.286,40,73,8,0,31,1.5,1266], + [53.171,53.286,76,73,0,0,31,1.5,1266], + [53.283,53.403,40,81,8,0,31,1.75,1269], + [53.286,53.403,87,75,2,0,31,1.75,1269], + [53.286,53.403,75,71,0,0,31,1.75,1269], + [53.289,53.403,59,65,4,0,31,1.75,1269], + [53.401,53.52,88,71,2,0,31,2,1271], + [53.401,54.34,56,86,6,1,31,2,1271], + [53.401,53.52,38,80,14,0,31,2,1271], + [53.402,54.34,28,91,9,0,31,2,1271], + [53.402,54.34,59,84,6,2,31,2,1271], + [53.402,53.52,76,75,0,0,31,2,1271], + [53.404,53.52,36,108,10,0,31,2,1272], + [53.404,53.52,52,83,4,0,31,2,1272], + [53.405,54.34,52,83,6,0,31,2,1272], + [53.516,53.637,40,86,8,0,31,2.25,1274], + [53.52,53.637,56,65,4,0,31,2.25,1274], + [53.52,53.637,71,76,0,0,31,2.25,1274], + [53.521,53.637,83,70,2,0,31,2.25,1274], + [53.633,53.754,88,74,2,0,31,2.5,1277], + [53.635,53.754,76,73,0,0,31,2.5,1277], + [53.637,53.754,59,65,4,0,31,2.5,1277], + [53.638,53.754,40,75,8,0,31,2.5,1277], + [53.639,53.754,38,83,14,0,31,2.5,1277], + [53.751,53.871,75,74,0,0,31,2.75,1280], + [53.752,53.871,40,80,8,0,31,2.75,1280], + [53.753,53.871,64,65,4,0,31,2.75,1280], + [53.757,53.871,87,73,2,0,31,2.75,1280], + [53.869,53.989,68,86,4,0,31,3,1283], + [53.87,53.989,76,76,0,0,31,3,1283], + [53.871,53.989,88,77,2,0,31,3,1283], + [53.871,53.989,38,85,14,0,31,3,1283], + [53.873,53.989,36,112,10,0,31,3,1283], + [53.987,54.106,77,72,0,0,31,3.25,1285], + [53.988,54.106,40,92,8,0,31,3.25,1285], + [53.989,54.106,89,75,2,0,31,3.25,1285], + [53.991,54.106,71,65,4,0,31,3.25,1285], + [54.103,54.223,40,74,8,0,31,3.5,1288], + [54.104,54.223,76,75,0,0,31,3.5,1288], + [54.105,54.223,64,64,4,0,31,3.5,1288], + [54.107,54.223,88,78,2,0,31,3.5,1288], + [54.107,54.223,38,88,14,0,31,3.5,1288], + [54.221,54.34,40,83,8,0,31,3.75,1291], + [54.222,54.34,87,73,2,0,31,3.75,1291], + [54.225,54.34,59,67,4,0,31,3.75,1291], + [54.226,54.34,75,74,0,0,31,3.75,1291], + [54.337,54.457,76,93,0,0,32,0,1294], + [54.337,54.457,38,90,14,0,32,0,1294], + [54.339,54.457,36,108,10,0,32,0,1294], + [54.34,56.215,64,89,7,3,32,0,1294], + [54.34,54.457,52,92,4,0,32,0,1294], + [54.34,56.215,59,89,7,2,32,0,1294], + [54.341,56.215,52,89,7,0,32,0,1294], + [54.341,54.457,88,89,2,0,32,0,1294], + [54.341,56.215,56,90,7,1,32,0,1294], + [54.342,55.278,56,84,6,1,32,0,1294], + [54.342,55.278,52,88,6,0,32,0,1294], + [54.342,55.278,28,86,9,0,32,0,1294], + [54.342,55.278,59,85,6,2,32,0,1294], + [54.455,54.575,38,89,14,0,32,0.25,1297], + [54.455,54.575,87,94,2,0,32,0.25,1297], + [54.456,54.575,75,91,0,0,32,0.25,1297], + [54.457,54.575,56,68,4,0,32,0.25,1297], + [54.573,54.692,36,101,10,0,32,0.5,1299], + [54.573,54.692,59,67,4,0,32,0.5,1299], + [54.574,54.692,38,91,14,0,32,0.5,1299], + [54.575,54.692,76,90,0,0,32,0.5,1299], + [54.577,54.692,88,91,2,0,32,0.5,1299], + [54.689,54.809,75,90,0,0,32,0.75,1302], + [54.689,54.809,87,87,2,0,32,0.75,1302], + [54.691,54.809,38,97,14,0,32,0.75,1302], + [54.692,54.809,64,69,4,0,32,0.75,1302], + [54.807,54.926,36,107,10,0,32,1,1305], + [54.81,54.926,38,98,14,0,32,1,1305], + [54.81,54.926,76,93,0,0,32,1,1305], + [54.811,54.926,68,95,4,0,32,1,1305], + [54.813,54.926,88,88,2,0,32,1,1305], + [54.926,55.043,38,93,14,0,32,1.25,1308], + [54.926,55.043,87,92,2,0,32,1.25,1308], + [54.928,55.043,75,88,0,0,32,1.25,1308], + [54.928,55.043,71,72,4,0,32,1.25,1308], + [55.043,55.161,36,99,10,0,32,1.5,1311], + [55.044,55.161,64,70,4,0,32,1.5,1311], + [55.046,55.161,88,91,2,0,32,1.5,1311], + [55.046,55.161,76,86,0,0,32,1.5,1311], + [55.047,55.161,38,101,14,0,32,1.5,1311], + [55.159,55.278,38,102,14,0,32,1.75,1313], + [55.161,55.278,59,70,4,0,32,1.75,1313], + [55.162,55.278,75,95,0,0,32,1.75,1313], + [55.163,55.278,87,89,2,0,32,1.75,1313], + [55.273,56.215,59,87,6,2,32,2,1316], + [55.276,56.215,56,86,6,1,32,2,1316], + [55.277,55.395,36,111,10,0,32,2,1316], + [55.277,55.395,76,89,0,0,32,2,1316], + [55.278,56.215,28,90,9,0,32,2,1316], + [55.278,55.395,52,87,4,0,32,2,1316], + [55.279,55.395,38,104,14,0,32,2,1316], + [55.28,55.395,88,92,2,0,32,2,1316], + [55.28,56.215,52,90,6,0,32,2,1316], + [55.396,55.512,75,92,0,0,32,2.25,1319], + [55.398,55.512,56,74,4,0,32,2.25,1319], + [55.399,55.512,87,92,2,0,32,2.25,1319], + [55.399,55.512,38,106,14,0,32,2.25,1319], + [55.507,55.629,59,66,4,0,32,2.5,1322], + [55.512,55.629,76,86,0,0,32,2.5,1322], + [55.513,55.629,36,104,10,0,32,2.5,1322], + [55.514,55.629,88,92,2,0,32,2.5,1322], + [55.515,55.629,38,109,14,0,32,2.5,1322], + [55.629,55.746,38,112,14,0,32,2.75,1325], + [55.63,55.746,64,70,4,0,32,2.75,1325], + [55.63,55.746,87,90,2,0,32,2.75,1325], + [55.632,55.746,75,90,0,0,32,2.75,1325], + [55.744,55.864,88,92,2,0,32,3,1327], + [55.745,55.864,38,111,14,0,32,3,1327], + [55.746,55.864,68,88,4,0,32,3,1327], + [55.747,55.864,36,114,10,0,32,3,1327], + [55.747,55.864,76,91,0,0,32,3,1327], + [55.86,55.981,38,114,14,0,32,3.25,1330], + [55.86,55.981,71,66,4,0,32,3.25,1330], + [55.863,55.981,87,90,2,0,32,3.25,1330], + [55.865,55.981,75,86,0,0,32,3.25,1330], + [55.976,56.098,76,89,0,0,32,3.5,1333], + [55.979,56.098,36,107,10,0,32,3.5,1333], + [55.98,56.098,38,114,14,0,32,3.5,1333], + [55.982,56.098,64,70,4,0,32,3.5,1333], + [55.983,56.098,88,89,2,0,32,3.5,1333], + [56.097,56.215,59,72,4,0,32,3.75,1336], + [56.097,56.215,75,86,0,0,32,3.75,1336], + [56.097,56.215,38,115,14,0,32,3.75,1336], + [56.101,56.215,87,90,2,0,32,3.75,1336], + [56.211,56.684,76,91,0,0,33,0,1338], + [56.215,56.332,41,107,18,0,33,0,1338], + [56.216,56.684,88,90,2,0,33,0,1338], + [58.086,59.028,61,79,6,1,34,0,1383], + [58.087,59.028,57,81,6,0,34,0,1383], + [58.087,59.965,85,109,2,0,34,0,1383], + [58.089,58.207,36,127,17,0,34,0,1383], + [58.089,58.207,49,115,16,0,34,0,1383], + [58.089,59.965,33,91,9,0,34,0,1383], + [58.09,58.207,33,74,8,0,34,0,1383], + [58.09,59.028,64,82,6,2,34,0,1383], + [58.09,58.325,64,97,5,0,34,0,1383], + [58.09,58.325,73,97,5,3,34,0,1383], + [58.091,58.207,45,119,11,0,34,0,1383], + [58.091,58.325,70,98,5,2,34,0,1383], + [58.092,58.207,42,68,13,0,34,0,1383], + [58.093,58.207,36,113,10,0,34,0,1383], + [58.093,59.965,73,73,0,0,34,0,1383], + [58.093,58.325,67,95,5,1,34,0,1383], + [58.206,58.325,45,86,8,0,34,0.25,1386], + [58.209,58.325,42,41,13,0,34,0.25,1386], + [58.322,58.442,46,87,15,0,34,0.5,1389], + [58.323,58.442,33,95,8,0,34,0.5,1389], + [58.44,58.676,70,81,5,2,34,0.75,1391], + [58.441,58.676,64,79,5,0,34,0.75,1391], + [58.444,58.559,42,47,13,0,34,0.75,1392], + [58.444,58.559,45,86,8,0,34,0.75,1392], + [58.445,58.676,67,76,5,1,34,0.75,1392], + [58.447,58.676,73,79,5,3,34,0.75,1392], + [58.558,58.676,42,68,13,0,34,1,1394], + [58.56,58.676,36,107,10,0,34,1,1394], + [58.562,58.676,39,101,12,0,34,1,1394], + [58.564,58.676,33,68,8,0,34,1,1394], + [58.674,58.793,42,39,13,0,34,1.25,1397], + [58.676,58.793,45,87,8,0,34,1.25,1397], + [58.789,58.911,46,84,15,0,34,1.5,1400], + [58.793,59.028,64,88,5,0,34,1.5,1400], + [58.793,59.028,73,87,5,3,34,1.5,1400], + [58.794,58.911,33,98,8,0,34,1.5,1400], + [58.796,59.028,67,88,5,1,34,1.5,1400], + [58.797,59.028,70,89,5,2,34,1.5,1400], + [58.91,59.028,45,87,8,0,34,1.75,1403], + [58.91,59.028,42,48,13,0,34,1.75,1403], + [59.025,59.262,73,93,5,3,34,2,1405], + [59.027,59.145,33,73,8,0,34,2,1405], + [59.028,59.965,61,80,6,1,34,2,1405], + [59.028,59.262,64,97,5,0,34,2,1405], + [59.028,59.262,67,94,5,1,34,2,1405], + [59.029,59.262,70,94,5,2,34,2,1405], + [59.029,59.145,42,71,13,0,34,2,1405], + [59.031,59.145,36,111,10,0,34,2,1405], + [59.031,59.965,64,83,6,2,34,2,1406], + [59.033,59.965,57,81,6,0,34,2,1406], + [59.141,59.262,42,42,13,0,34,2.25,1408], + [59.145,59.262,45,82,8,0,34,2.25,1408], + [59.264,59.379,33,98,8,0,34,2.5,1411], + [59.267,59.379,46,88,15,0,34,2.5,1411], + [59.376,59.614,73,80,5,3,34,2.75,1414], + [59.377,59.614,64,79,5,0,34,2.75,1414], + [59.378,59.496,45,85,8,0,34,2.75,1414], + [59.379,59.614,67,82,5,1,34,2.75,1414], + [59.38,59.614,70,81,5,2,34,2.75,1414], + [59.38,59.496,42,53,13,0,34,2.75,1414], + [59.495,59.614,42,60,13,0,34,3,1417], + [59.496,59.614,39,106,12,0,34,3,1417], + [59.498,59.614,36,110,10,0,34,3,1417], + [59.499,59.614,33,70,8,0,34,3,1417], + [59.613,59.731,45,83,8,0,34,3.25,1419], + [59.616,59.731,42,36,13,0,34,3.25,1419], + [59.728,59.965,67,84,5,1,34,3.5,1422], + [59.73,59.965,73,86,5,3,34,3.5,1422], + [59.73,59.848,33,96,8,0,34,3.5,1422], + [59.73,59.965,70,89,5,2,34,3.5,1422], + [59.733,59.848,46,84,15,0,34,3.5,1422], + [59.735,59.965,64,86,5,0,34,3.5,1422], + [59.848,59.965,42,52,13,0,34,3.75,1425], + [59.849,59.965,45,86,8,0,34,3.75,1425], + [59.961,61.371,74,74,0,0,35,0,1428], + [59.961,61.84,33,94,9,0,35,0,1428], + [59.963,60.082,36,112,10,0,35,0,1428], + [59.964,60.903,57,79,6,2,35,0,1428], + [59.964,60.903,50,81,6,0,35,0,1428], + [59.966,60.2,69,93,5,1,35,0,1428], + [59.966,60.2,74,94,5,2,35,0,1428], + [59.966,60.903,53,79,6,1,35,0,1428], + [59.966,60.2,65,96,5,0,35,0,1428], + [59.966,60.082,42,69,13,0,35,0,1428], + [59.966,61.371,86,111,2,0,35,0,1428], + [59.968,60.082,33,71,8,0,35,0,1428], + [60.083,60.2,42,39,13,0,35,0.25,1431], + [60.083,60.2,45,83,8,0,35,0.25,1431], + [60.199,60.317,33,96,8,0,35,0.5,1433], + [60.204,60.317,46,90,15,0,35,0.5,1433], + [60.314,60.551,74,81,5,2,35,0.75,1436], + [60.315,60.551,69,79,5,1,35,0.75,1436], + [60.316,60.551,65,81,5,0,35,0.75,1436], + [60.319,60.434,42,50,13,0,35,0.75,1436], + [60.319,60.434,45,86,8,0,35,0.75,1436], + [60.431,60.551,33,71,8,0,35,1,1439], + [60.432,60.551,42,61,13,0,35,1,1439], + [60.433,60.551,39,99,12,0,35,1,1439], + [60.434,60.551,36,109,10,0,35,1,1439], + [60.552,60.668,45,85,8,0,35,1.25,1442], + [60.554,60.668,42,41,13,0,35,1.25,1442], + [60.665,60.903,74,86,5,2,35,1.5,1444], + [60.666,60.786,46,88,15,0,35,1.5,1444], + [60.669,60.903,69,91,5,1,35,1.5,1445], + [60.67,60.903,65,88,5,0,35,1.5,1445], + [60.672,60.786,33,99,8,0,35,1.5,1445], + [60.782,60.903,45,83,8,0,35,1.75,1447], + [60.787,60.903,42,46,13,0,35,1.75,1447], + [60.9,61.84,57,79,6,2,35,2,1450], + [60.902,61.84,50,81,6,0,35,2,1450], + [60.902,61.137,74,96,5,2,35,2,1450], + [60.902,61.02,36,113,10,0,35,2,1450], + [60.903,61.02,33,71,8,0,35,2,1450], + [60.904,61.137,65,97,5,0,35,2,1450], + [60.904,61.02,42,68,13,0,35,2,1450], + [60.904,61.84,53,78,6,1,35,2,1450], + [60.905,61.137,69,94,5,1,35,2,1450], + [61.018,61.137,42,39,13,0,35,2.25,1453], + [61.021,61.137,45,85,8,0,35,2.25,1453], + [61.136,61.254,33,94,8,0,35,2.5,1456], + [61.137,61.254,46,87,15,0,35,2.5,1456], + [61.249,61.371,45,84,8,0,35,2.75,1458], + [61.253,61.489,65,79,5,0,35,2.75,1458], + [61.253,61.489,69,79,5,1,35,2.75,1458], + [61.257,61.489,74,81,5,2,35,2.75,1459], + [61.258,61.371,42,47,13,0,35,2.75,1459], + [61.37,61.489,42,62,13,0,35,3,1461], + [61.372,61.489,36,106,10,0,35,3,1461], + [61.373,61.606,88,103,2,0,35,3,1461], + [61.374,61.606,76,69,0,0,35,3,1461], + [61.374,61.489,39,103,12,0,35,3,1461], + [61.374,61.489,33,70,8,0,35,3,1461], + [61.49,61.606,45,84,8,0,35,3.25,1464], + [61.49,61.606,42,39,13,0,35,3.25,1464], + [61.603,61.84,74,92,5,2,35,3.5,1467], + [61.604,61.84,89,103,2,0,35,3.5,1467], + [61.604,61.84,77,78,0,0,35,3.5,1467], + [61.604,61.84,65,90,5,0,35,3.5,1467], + [61.606,61.84,69,89,5,1,35,3.5,1467], + [61.606,61.723,46,82,15,0,35,3.5,1467], + [61.607,61.723,33,96,8,0,35,3.5,1467], + [61.723,61.84,42,51,13,0,35,3.75,1470], + [61.726,61.84,45,83,8,0,35,3.75,1470], + [61.837,62.778,59,81,6,2,36,0,1472], + [61.837,62.778,56,81,6,1,36,0,1472], + [61.839,62.075,77,96,5,2,36,0,1472], + [61.839,62.778,89,107,2,0,36,0,1472], + [61.84,62.075,74,98,5,1,36,0,1472], + [61.841,63.715,33,98,9,0,36,0,1472], + [61.841,61.957,36,111,10,0,36,0,1472], + [61.841,61.957,33,69,8,0,36,0,1472], + [61.842,62.075,68,95,5,0,36,0,1472], + [61.843,62.778,52,82,6,0,36,0,1472], + [61.844,61.957,42,66,13,0,36,0,1472], + [61.844,62.778,77,76,0,0,36,0,1472], + [61.955,62.075,42,38,13,0,36,0.25,1475], + [61.956,62.075,45,87,8,0,36,0.25,1475], + [62.074,62.192,46,88,15,0,36,0.5,1478], + [62.077,62.192,33,95,8,0,36,0.5,1478], + [62.189,62.309,42,48,13,0,36,0.75,1481], + [62.191,62.426,74,81,5,1,36,0.75,1481], + [62.192,62.426,77,83,5,2,36,0.75,1481], + [62.192,62.309,45,89,8,0,36,0.75,1481], + [62.194,62.426,68,79,5,0,36,0.75,1481], + [62.305,62.426,39,96,12,0,36,1,1483], + [62.309,62.426,42,61,13,0,36,1,1484], + [62.31,62.426,33,73,8,0,36,1,1484], + [62.311,62.426,36,106,10,0,36,1,1484], + [62.425,62.543,45,87,8,0,36,1.25,1486], + [62.427,62.543,42,40,13,0,36,1.25,1486], + [62.542,62.661,33,99,8,0,36,1.5,1489], + [62.543,62.778,74,88,5,1,36,1.5,1489], + [62.544,62.778,77,90,5,2,36,1.5,1489], + [62.544,62.661,46,83,15,0,36,1.5,1489], + [62.545,62.778,68,85,5,0,36,1.5,1489], + [62.663,62.778,42,47,13,0,36,1.75,1492], + [62.663,62.778,45,85,8,0,36,1.75,1492], + [62.774,62.895,36,112,10,0,36,2,1495], + [62.775,63.012,74,93,5,1,36,2,1495], + [62.775,63.715,77,76,0,0,36,2,1495], + [62.775,63.715,52,81,6,0,36,2,1495], + [62.778,63.715,89,106,2,0,36,2,1495], + [62.778,63.715,59,82,6,2,36,2,1495], + [62.78,62.895,42,69,13,0,36,2,1495], + [62.78,62.895,33,72,8,0,36,2,1495], + [62.781,63.012,68,92,5,0,36,2,1495], + [62.781,63.012,77,91,5,2,36,2,1495], + [62.781,63.715,56,84,6,1,36,2,1495], + [62.892,63.012,45,82,8,0,36,2.25,1497], + [62.894,63.012,42,40,13,0,36,2.25,1497], + [63.009,63.129,46,86,15,0,36,2.5,1500], + [63.013,63.129,33,95,8,0,36,2.5,1500], + [63.126,63.364,77,80,5,2,36,2.75,1503], + [63.126,63.364,68,78,5,0,36,2.75,1503], + [63.129,63.364,74,79,5,1,36,2.75,1503], + [63.129,63.246,42,43,13,0,36,2.75,1503], + [63.129,63.246,45,83,8,0,36,2.75,1503], + [63.247,63.364,39,104,12,0,36,3,1506], + [63.247,63.364,33,71,8,0,36,3,1506], + [63.248,63.364,42,60,13,0,36,3,1506], + [63.249,63.364,36,105,10,0,36,3,1506], + [63.36,63.481,45,82,8,0,36,3.25,1509], + [63.365,63.481,42,41,13,0,36,3.25,1509], + [63.48,63.715,68,91,5,0,36,3.5,1511], + [63.481,63.715,74,91,5,1,36,3.5,1511], + [63.481,63.598,33,101,8,0,36,3.5,1511], + [63.482,63.598,46,82,15,0,36,3.5,1511], + [63.486,63.715,77,87,5,2,36,3.5,1512], + [63.598,63.715,45,83,8,0,36,3.75,1514], + [63.598,63.715,42,52,13,0,36,3.75,1514], + [63.712,63.832,33,68,8,0,37,0,1517], + [63.713,63.832,36,110,10,0,37,0,1517], + [63.713,64.653,60,78,6,1,37,0,1517], + [63.713,65.59,33,92,9,0,37,0,1517], + [63.714,64.653,57,79,6,0,37,0,1517], + [63.714,63.95,72,99,5,1,37,0,1517], + [63.714,65.59,76,73,0,0,37,0,1517], + [63.715,65.59,88,102,2,0,37,0,1517], + [63.715,64.653,64,79,6,2,37,0,1517], + [63.716,63.95,69,97,5,0,37,0,1517], + [63.718,63.832,42,71,13,0,37,0,1517], + [63.718,63.95,76,93,5,2,37,0,1517], + [63.833,63.95,45,85,8,0,37,0.25,1520], + [63.835,63.95,42,41,13,0,37,0.25,1520], + [63.95,64.067,33,96,8,0,37,0.5,1523], + [63.951,64.067,46,87,15,0,37,0.5,1523], + [64.066,64.301,69,80,5,0,37,0.75,1525], + [64.067,64.184,45,89,8,0,37,0.75,1525], + [64.068,64.301,76,81,5,2,37,0.75,1525], + [64.069,64.301,72,81,5,1,37,0.75,1525], + [64.07,64.184,42,48,13,0,37,0.75,1525], + [64.183,64.301,42,65,13,0,37,1,1528], + [64.184,64.301,39,100,12,0,37,1,1528], + [64.185,64.301,36,105,10,0,37,1,1528], + [64.186,64.301,33,69,8,0,37,1,1528], + [64.301,64.418,45,80,8,0,37,1.25,1531], + [64.303,64.418,42,39,13,0,37,1.25,1531], + [64.414,64.653,72,88,5,1,37,1.5,1534], + [64.414,64.653,69,87,5,0,37,1.5,1534], + [64.417,64.536,33,99,8,0,37,1.5,1534], + [64.418,64.653,76,92,5,2,37,1.5,1534], + [64.42,64.536,46,83,15,0,37,1.5,1534], + [64.532,64.653,45,84,8,0,37,1.75,1536], + [64.537,64.653,42,46,13,0,37,1.75,1537], + [64.648,65.59,60,77,6,1,37,2,1539], + [64.649,65.59,64,79,6,2,37,2,1539], + [64.651,65.59,57,80,6,0,37,2,1539], + [64.652,64.887,69,96,5,0,37,2,1539], + [64.653,64.77,36,109,10,0,37,2,1539], + [64.654,64.77,33,73,8,0,37,2,1539], + [64.654,64.887,76,93,5,2,37,2,1539], + [64.655,64.887,72,96,5,1,37,2,1539], + [64.657,64.77,42,68,13,0,37,2,1539], + [64.771,64.887,45,82,8,0,37,2.25,1542], + [64.771,64.887,42,40,13,0,37,2.25,1542], + [64.886,65.004,33,96,8,0,37,2.5,1545], + [64.888,65.004,46,92,15,0,37,2.5,1545], + [65.002,65.121,45,86,8,0,37,2.75,1548], + [65.003,65.239,69,78,5,0,37,2.75,1548], + [65.004,65.239,76,82,5,2,37,2.75,1548], + [65.005,65.239,72,78,5,1,37,2.75,1548], + [65.005,65.121,42,46,13,0,37,2.75,1548], + [65.118,65.239,33,67,8,0,37,3,1550], + [65.119,65.239,39,103,12,0,37,3,1550], + [65.119,65.239,36,106,10,0,37,3,1550], + [65.122,65.239,42,62,13,0,37,3,1551], + [65.238,65.356,45,83,8,0,37,3.25,1553], + [65.238,65.356,42,42,13,0,37,3.25,1553], + [65.352,65.59,72,87,5,1,37,3.5,1556], + [65.355,65.473,46,85,15,0,37,3.5,1556], + [65.355,65.59,69,84,5,0,37,3.5,1556], + [65.359,65.59,76,86,5,2,37,3.5,1556], + [65.36,65.473,33,93,8,0,37,3.5,1556], + [65.472,65.59,45,85,8,0,37,3.75,1559], + [65.473,65.59,42,48,13,0,37,3.75,1559], + [65.589,65.707,42,72,13,0,38,0,1562], + [65.589,66.528,57,82,6,2,38,0,1562], + [65.589,66.996,86,106,2,0,38,0,1562], + [65.589,65.825,65,96,5,0,38,0,1562], + [65.59,67.465,38,94,9,0,38,0,1562], + [65.59,65.707,36,109,10,0,38,0,1562], + [65.591,66.996,74,74,0,0,38,0,1562], + [65.592,66.528,50,79,6,0,38,0,1562], + [65.592,66.528,53,83,6,1,38,0,1562], + [65.593,65.707,38,69,8,0,38,0,1562], + [65.593,65.707,49,114,16,0,38,0,1562], + [65.594,65.825,74,98,5,1,38,0,1562], + [65.706,65.825,42,38,13,0,38,0.25,1564], + [65.708,65.825,50,86,8,0,38,0.25,1564], + [65.819,65.942,46,87,15,0,38,0.5,1567], + [65.823,65.942,38,96,8,0,38,0.5,1567], + [65.939,66.059,50,86,8,0,38,0.75,1570], + [65.939,66.176,65,79,5,0,38,0.75,1570], + [65.941,66.059,42,48,13,0,38,0.75,1570], + [65.943,66.176,74,82,5,1,38,0.75,1570], + [66.056,66.176,38,72,8,0,38,1,1573], + [66.056,66.176,42,65,13,0,38,1,1573], + [66.057,66.176,39,101,12,0,38,1,1573], + [66.059,66.176,36,109,10,0,38,1,1573], + [66.173,66.293,50,81,8,0,38,1.25,1576], + [66.173,66.293,42,38,13,0,38,1.25,1576], + [66.292,66.528,74,89,5,1,38,1.5,1578], + [66.292,66.411,46,84,15,0,38,1.5,1578], + [66.293,66.411,38,97,8,0,38,1.5,1578], + [66.296,66.528,65,90,5,0,38,1.5,1578], + [66.409,66.528,42,44,13,0,38,1.75,1581], + [66.41,66.528,50,83,8,0,38,1.75,1581], + [66.526,67.465,57,80,6,2,38,2,1584], + [66.527,66.762,74,94,5,1,38,2,1584], + [66.529,67.465,53,77,6,1,38,2,1584], + [66.529,66.762,65,93,5,0,38,2,1584], + [66.53,67.465,50,81,6,0,38,2,1584], + [66.53,66.645,42,70,13,0,38,2,1584], + [66.531,66.645,38,67,8,0,38,2,1584], + [66.531,66.645,36,107,10,0,38,2,1584], + [66.645,66.762,42,37,13,0,38,2.25,1587], + [66.649,66.762,50,86,8,0,38,2.25,1587], + [66.76,66.879,46,87,15,0,38,2.5,1590], + [66.761,66.879,38,96,8,0,38,2.5,1590], + [66.876,66.996,42,51,13,0,38,2.75,1592], + [66.878,67.114,74,82,5,1,38,2.75,1592], + [66.878,67.114,65,77,5,0,38,2.75,1592], + [66.882,66.996,50,85,8,0,38,2.75,1592], + [66.992,67.114,36,109,10,0,38,3,1595], + [66.995,67.114,38,66,8,0,38,3,1595], + [66.995,67.114,39,104,12,0,38,3,1595], + [66.996,67.114,42,62,13,0,38,3,1595], + [66.998,67.231,72,73,0,0,38,3,1595], + [66.998,67.231,84,107,2,0,38,3,1595], + [67.113,67.231,50,79,8,0,38,3.25,1598], + [67.117,67.231,42,38,13,0,38,3.25,1598], + [67.23,67.465,71,72,0,0,38,3.5,1601], + [67.232,67.348,38,100,8,0,38,3.5,1601], + [67.232,67.465,83,105,2,0,38,3.5,1601], + [67.232,67.465,65,87,5,0,38,3.5,1601], + [67.233,67.348,46,85,15,0,38,3.5,1601], + [67.236,67.465,74,89,5,1,38,3.5,1601], + [67.347,67.465,42,54,13,0,38,3.75,1603], + [67.348,67.465,50,85,8,0,38,3.75,1604], + [67.463,67.7,66,96,5,1,39,0,1606], + [67.463,68.403,57,81,6,2,39,0,1606], + [67.464,67.7,69,95,5,2,39,0,1606], + [67.465,67.582,39,68,8,0,39,0,1606], + [67.465,68.403,51,80,6,0,39,0,1606], + [67.465,68.403,81,105,2,0,39,0,1606], + [67.465,67.7,60,97,5,0,39,0,1606], + [67.466,68.403,54,79,6,1,39,0,1606], + [67.466,67.582,42,70,13,0,39,0,1606], + [67.467,69.34,39,100,9,0,39,0,1606], + [67.467,67.582,36,114,10,0,39,0,1606], + [67.468,68.403,69,75,0,0,39,0,1606], + [67.583,67.7,51,86,8,0,39,0.25,1609], + [67.584,67.7,42,39,13,0,39,0.25,1609], + [67.699,67.817,46,93,15,0,39,0.5,1612], + [67.704,67.817,39,94,8,0,39,0.5,1612], + [67.814,67.934,42,50,13,0,39,0.75,1615], + [67.818,68.051,69,75,5,2,39,0.75,1615], + [67.818,68.051,60,82,5,0,39,0.75,1615], + [67.818,68.051,66,80,5,1,39,0.75,1615], + [67.821,67.934,51,83,8,0,39,0.75,1615], + [67.932,68.051,36,109,10,0,39,1,1617], + [67.932,68.051,39,100,12,0,39,1,1617], + [67.936,68.051,42,62,13,0,39,1,1618], + [67.937,68.051,39,69,8,0,39,1,1618], + [68.046,68.168,51,84,8,0,39,1.25,1620], + [68.053,68.168,42,36,13,0,39,1.25,1620], + [68.166,68.403,60,91,5,0,39,1.5,1623], + [68.166,68.286,39,93,8,0,39,1.5,1623], + [68.168,68.403,69,89,5,2,39,1.5,1623], + [68.169,68.286,46,83,15,0,39,1.5,1623], + [68.172,68.403,66,88,5,1,39,1.5,1623], + [68.284,68.403,42,46,13,0,39,1.75,1626], + [68.284,68.403,51,86,8,0,39,1.75,1626], + [68.401,68.52,39,70,8,0,39,2,1629], + [68.401,68.637,60,94,5,0,39,2,1629], + [68.402,69.34,54,79,6,1,39,2,1629], + [68.402,69.34,69,73,0,0,39,2,1629], + [68.403,68.637,66,93,5,1,39,2,1629], + [68.403,68.52,36,111,10,0,39,2,1629], + [68.403,68.637,69,97,5,2,39,2,1629], + [68.403,68.52,42,72,13,0,39,2,1629], + [68.403,69.34,81,108,2,0,39,2,1629], + [68.405,69.34,51,78,6,0,39,2,1629], + [68.405,69.34,57,78,6,2,39,2,1629], + [68.52,68.637,51,83,8,0,39,2.25,1631], + [68.522,68.637,42,43,13,0,39,2.25,1631], + [68.637,68.754,39,96,8,0,39,2.5,1634], + [68.638,68.754,46,88,15,0,39,2.5,1634], + [68.751,68.989,60,78,5,0,39,2.75,1637], + [68.753,68.871,51,84,8,0,39,2.75,1637], + [68.754,68.989,66,78,5,1,39,2.75,1637], + [68.755,68.989,69,81,5,2,39,2.75,1637], + [68.755,68.871,42,50,13,0,39,2.75,1637], + [68.867,68.989,39,72,8,0,39,3,1640], + [68.869,68.989,36,106,10,0,39,3,1640], + [68.87,68.989,39,103,12,0,39,3,1640], + [68.875,68.989,42,63,13,0,39,3,1640], + [68.987,69.106,51,83,8,0,39,3.25,1643], + [68.99,69.106,42,40,13,0,39,3.25,1643], + [69.103,69.223,46,85,15,0,39,3.5,1645], + [69.103,69.34,60,89,5,0,39,3.5,1645], + [69.105,69.34,66,90,5,1,39,3.5,1645], + [69.105,69.223,39,99,8,0,39,3.5,1645], + [69.107,69.34,69,83,5,2,39,3.5,1645], + [69.221,69.34,51,83,8,0,39,3.75,1648], + [69.221,69.34,42,49,13,0,39,3.75,1648], + [69.337,69.457,40,70,8,0,40,0,1651], + [69.337,69.575,69,96,5,2,40,0,1651], + [69.337,69.457,36,113,10,0,40,0,1651], + [69.338,70.278,59,78,6,2,40,0,1651], + [69.338,69.926,69,76,0,0,40,0,1651], + [69.338,69.575,64,93,5,1,40,0,1651], + [69.339,70.278,52,79,6,0,40,0,1651], + [69.34,71.215,40,95,9,0,40,0,1651], + [69.34,70.278,56,81,6,1,40,0,1651], + [69.341,69.457,42,72,13,0,40,0,1651], + [69.341,69.926,81,106,2,0,40,0,1651], + [69.343,69.575,60,96,5,0,40,0,1651], + [69.46,69.575,42,40,13,0,40,0.25,1654], + [69.46,69.575,52,82,8,0,40,0.25,1654], + [69.573,69.692,40,95,8,0,40,0.5,1657], + [69.578,69.692,46,91,15,0,40,0.5,1657], + [69.688,69.926,69,83,5,2,40,0.75,1659], + [69.692,69.809,42,50,13,0,40,0.75,1659], + [69.692,69.926,60,80,5,0,40,0.75,1659], + [69.692,69.809,52,85,8,0,40,0.75,1659], + [69.694,69.926,64,82,5,1,40,0.75,1659], + [69.807,69.926,40,70,8,0,40,1,1662], + [69.807,69.926,36,109,10,0,40,1,1662], + [69.81,69.926,39,100,12,0,40,1,1662], + [69.81,69.926,42,61,13,0,40,1,1662], + [69.926,70.512,72,74,0,0,40,1.25,1665], + [69.928,70.512,84,108,2,0,40,1.25,1665], + [69.929,70.043,42,43,13,0,40,1.25,1665], + [69.929,70.043,52,84,8,0,40,1.25,1665], + [70.04,70.161,46,85,15,0,40,1.5,1668], + [70.042,70.278,64,88,5,1,40,1.5,1668], + [70.043,70.278,69,84,5,2,40,1.5,1668], + [70.044,70.278,60,85,5,0,40,1.5,1668], + [70.046,70.161,40,95,8,0,40,1.5,1668], + [70.161,70.278,52,87,8,0,40,1.75,1671], + [70.163,70.278,42,43,13,0,40,1.75,1671], + [70.276,70.512,60,95,5,0,40,2,1673], + [70.277,70.395,42,69,13,0,40,2,1673], + [70.278,71.215,56,79,6,1,40,2,1673], + [70.278,70.395,40,71,8,0,40,2,1673], + [70.279,71.215,52,81,6,0,40,2,1673], + [70.279,70.512,64,92,5,1,40,2,1673], + [70.279,70.395,36,109,10,0,40,2,1673], + [70.279,70.512,69,96,5,2,40,2,1673], + [70.281,71.215,59,82,6,2,40,2,1673], + [70.39,70.512,52,85,8,0,40,2.25,1676], + [70.392,70.512,42,41,13,0,40,2.25,1676], + [70.51,71.215,83,107,2,0,40,2.5,1679], + [70.511,71.215,71,74,0,0,40,2.5,1679], + [70.513,70.629,46,88,15,0,40,2.5,1679], + [70.514,70.629,40,95,8,0,40,2.5,1679], + [70.624,70.864,69,81,5,2,40,2.75,1682], + [70.626,70.746,42,48,13,0,40,2.75,1682], + [70.629,70.864,60,80,5,0,40,2.75,1682], + [70.63,70.746,52,87,8,0,40,2.75,1682], + [70.631,70.864,64,79,5,1,40,2.75,1682], + [70.745,70.864,36,109,10,0,40,3,1684], + [70.747,70.864,42,64,13,0,40,3,1684], + [70.749,70.864,39,105,12,0,40,3,1685], + [70.751,70.864,40,68,8,0,40,3,1685], + [70.866,70.981,42,42,13,0,40,3.25,1687], + [70.866,70.981,52,86,8,0,40,3.25,1687], + [70.977,71.215,64,90,5,1,40,3.5,1690], + [70.978,71.215,69,89,5,2,40,3.5,1690], + [70.979,71.098,40,96,8,0,40,3.5,1690], + [70.982,71.215,60,89,5,0,40,3.5,1690], + [70.983,71.098,46,82,15,0,40,3.5,1690], + [71.095,71.215,52,84,8,0,40,3.75,1693], + [71.099,71.215,42,54,13,0,40,3.75,1693], + [71.212,71.45,60,96,5,0,41,0,1696], + [71.213,71.332,38,69,14,0,41,0,1696], + [71.214,71.332,36,113,10,0,41,0,1696], + [71.215,71.332,33,68,8,0,41,0,1696], + [71.215,73.09,81,104,2,0,41,0,1696], + [71.215,73.09,69,75,0,0,41,0,1696], + [71.215,73.09,33,95,9,0,41,0,1696], + [71.215,72.153,64,79,6,2,41,0,1696], + [71.217,72.153,60,79,6,1,41,0,1696], + [71.217,71.332,42,68,13,0,41,0,1696], + [71.217,72.153,57,80,6,0,41,0,1696], + [71.219,71.45,69,94,5,1,41,0,1696], + [71.332,71.45,45,84,8,0,41,0.25,1698], + [71.332,71.45,38,73,14,0,41,0.25,1698], + [71.336,71.45,42,41,13,0,41,0.25,1698], + [71.447,71.567,33,99,8,0,41,0.5,1701], + [71.45,71.567,46,86,15,0,41,0.5,1701], + [71.452,71.567,38,80,14,0,41,0.5,1701], + [71.565,71.684,42,46,13,0,41,0.75,1704], + [71.565,71.684,38,83,14,0,41,0.75,1704], + [71.568,71.801,60,78,5,0,41,0.75,1704], + [71.568,71.801,69,84,5,1,41,0.75,1704], + [71.571,71.684,45,87,8,0,41,0.75,1704], + [71.683,71.801,36,111,10,0,41,1,1707], + [71.684,71.801,42,64,13,0,41,1,1707], + [71.684,71.801,39,103,12,0,41,1,1707], + [71.685,71.801,33,73,8,0,41,1,1707], + [71.687,71.801,38,87,14,0,41,1,1707], + [71.798,71.918,45,85,8,0,41,1.25,1709], + [71.799,71.918,42,42,13,0,41,1.25,1710], + [71.803,71.918,38,91,14,0,41,1.25,1710], + [71.917,72.153,69,87,5,1,41,1.5,1712], + [71.919,72.036,38,94,14,0,41,1.5,1712], + [71.92,72.153,60,86,5,0,41,1.5,1712], + [71.92,72.036,33,98,8,0,41,1.5,1712], + [71.923,72.036,46,80,15,0,41,1.5,1712], + [72.033,72.153,45,85,8,0,41,1.75,1715], + [72.034,72.153,38,97,14,0,41,1.75,1715], + [72.038,72.153,42,43,13,0,41,1.75,1715], + [72.148,73.09,57,82,6,0,41,2,1718], + [72.15,72.27,42,72,13,0,41,2,1718], + [72.15,72.387,60,95,5,0,41,2,1718], + [72.15,72.27,38,103,14,0,41,2,1718], + [72.152,73.09,64,79,6,2,41,2,1718], + [72.153,72.27,36,109,10,0,41,2,1718], + [72.154,72.27,33,68,8,0,41,2,1718], + [72.155,72.387,69,94,5,1,41,2,1718], + [72.156,73.09,60,78,6,1,41,2,1718], + [72.269,72.387,38,108,14,0,41,2.25,1721], + [72.27,72.387,42,40,13,0,41,2.25,1721], + [72.271,72.387,45,80,8,0,41,2.25,1721], + [72.386,72.504,33,96,8,0,41,2.5,1723], + [72.387,72.504,38,113,14,0,41,2.5,1723], + [72.388,72.504,46,87,15,0,41,2.5,1724], + [72.503,72.739,60,79,5,0,41,2.75,1726], + [72.503,72.621,42,46,13,0,41,2.75,1726], + [72.505,72.621,38,117,14,0,41,2.75,1726], + [72.505,72.739,69,81,5,1,41,2.75,1726], + [72.506,72.621,45,84,8,0,41,2.75,1726], + [72.617,72.739,42,63,13,0,41,3,1729], + [72.62,72.739,36,105,10,0,41,3,1729], + [72.622,72.739,39,103,12,0,41,3,1729], + [72.623,72.739,33,72,8,0,41,3,1729], + [72.624,72.739,38,123,14,0,41,3,1729], + [72.734,72.856,42,41,13,0,41,3.25,1732], + [72.743,72.856,38,122,14,0,41,3.25,1732], + [72.744,72.856,45,86,8,0,41,3.25,1732], + [72.852,72.973,46,87,15,0,41,3.5,1735], + [72.853,73.09,69,87,5,1,41,3.5,1735], + [72.854,72.973,38,124,14,0,41,3.5,1735], + [72.855,73.09,60,87,5,0,41,3.5,1735], + [72.857,72.973,33,96,8,0,41,3.5,1735], + [72.969,73.09,42,54,13,0,41,3.75,1737], + [72.97,73.09,45,84,8,0,41,3.75,1737], + [72.971,73.09,38,124,14,0,41,3.75,1737], + [73.087,73.207,42,72,13,0,42,0,1740], + [73.088,74.965,85,105,2,0,42,0,1740], + [73.088,73.207,49,114,16,0,42,0,1740], + [73.089,73.207,36,115,17,0,42,0,1740], + [73.089,73.325,70,96,5,2,42,0,1740], + [73.089,73.207,33,67,8,0,42,0,1740], + [73.089,73.207,36,109,10,0,42,0,1740], + [73.09,74.965,73,89,3,0,42,0,1740], + [73.09,74.028,57,80,6,0,42,0,1740], + [73.091,74.028,64,79,6,2,42,0,1740], + [73.091,73.325,67,95,5,1,42,0,1740], + [73.091,74.965,33,93,9,0,42,0,1740], + [73.092,73.325,64,95,5,0,42,0,1740], + [73.092,74.028,61,77,6,1,42,0,1740], + [73.092,73.325,73,98,5,3,42,0,1740], + [73.093,74.965,73,73,0,0,42,0,1740], + [73.094,73.207,45,118,11,0,42,0,1740], + [73.207,73.325,45,85,8,0,42,0.25,1743], + [73.209,73.325,42,42,13,0,42,0.25,1743], + [73.325,73.442,46,86,15,0,42,0.5,1746], + [73.325,73.442,33,97,8,0,42,0.5,1746], + [73.438,73.676,67,80,5,1,42,0.75,1749], + [73.438,73.676,70,80,5,2,42,0.75,1749], + [73.441,73.676,73,77,5,3,42,0.75,1749], + [73.442,73.559,42,49,13,0,42,0.75,1749], + [73.444,73.676,64,79,5,0,42,0.75,1749], + [73.445,73.559,45,86,8,0,42,0.75,1749], + [73.557,73.676,39,99,12,0,42,1,1751], + [73.558,73.676,42,64,13,0,42,1,1751], + [73.559,73.676,33,72,8,0,42,1,1751], + [73.563,73.676,36,108,10,0,42,1,1751], + [73.675,73.793,45,83,8,0,42,1.25,1754], + [73.677,73.793,42,38,13,0,42,1.25,1754], + [73.79,73.911,33,98,8,0,42,1.5,1757], + [73.793,74.028,67,87,5,1,42,1.5,1757], + [73.793,74.028,64,85,5,0,42,1.5,1757], + [73.793,74.028,73,91,5,3,42,1.5,1757], + [73.793,74.028,70,87,5,2,42,1.5,1757], + [73.795,73.911,46,84,15,0,42,1.5,1757], + [73.91,74.028,42,45,13,0,42,1.75,1760], + [73.91,74.028,45,87,8,0,42,1.75,1760], + [74.026,74.965,57,77,6,0,42,2,1763], + [74.027,74.965,64,83,6,2,42,2,1763], + [74.027,74.145,36,112,10,0,42,2,1763], + [74.028,74.262,70,93,5,2,42,2,1763], + [74.028,74.262,67,95,5,1,42,2,1763], + [74.028,74.262,73,92,5,3,42,2,1763], + [74.029,74.145,42,68,13,0,42,2,1763], + [74.029,74.145,33,71,8,0,42,2,1763], + [74.029,74.262,64,96,5,0,42,2,1763], + [74.032,74.965,61,77,6,1,42,2,1763], + [74.143,74.262,42,37,13,0,42,2.25,1765], + [74.144,74.262,45,80,8,0,42,2.25,1765], + [74.26,74.379,46,90,15,0,42,2.5,1768], + [74.264,74.379,33,96,8,0,42,2.5,1768], + [74.375,74.496,45,87,8,0,42,2.75,1771], + [74.377,74.614,70,81,5,2,42,2.75,1771], + [74.377,74.614,73,79,5,3,42,2.75,1771], + [74.38,74.614,67,79,5,1,42,2.75,1771], + [74.38,74.496,42,49,13,0,42,2.75,1771], + [74.381,74.614,64,80,5,0,42,2.75,1771], + [74.495,74.614,42,63,13,0,42,3,1774], + [74.496,74.614,39,105,12,0,42,3,1774], + [74.498,74.614,36,108,10,0,42,3,1774], + [74.498,74.614,33,71,8,0,42,3,1774], + [74.615,74.731,45,85,8,0,42,3.25,1777], + [74.616,74.731,42,37,13,0,42,3.25,1777], + [74.729,74.965,64,89,5,0,42,3.5,1779], + [74.73,74.848,46,83,15,0,42,3.5,1779], + [74.731,74.965,73,87,5,3,42,3.5,1779], + [74.731,74.965,70,88,5,2,42,3.5,1779], + [74.732,74.965,67,87,5,1,42,3.5,1779], + [74.732,74.848,33,92,8,0,42,3.5,1779], + [74.847,74.965,45,86,8,0,42,3.75,1782], + [74.849,74.965,42,49,13,0,42,3.75,1782], + [74.962,75.903,53,78,6,1,43,0,1785], + [74.962,76.371,74,91,3,0,43,0,1785], + [74.963,75.082,33,67,8,0,43,0,1785], + [74.964,75.2,65,99,5,0,43,0,1785], + [74.964,75.903,57,80,6,2,43,0,1785], + [74.965,76.371,74,74,0,0,43,0,1785], + [74.965,75.082,36,113,10,0,43,0,1785], + [74.965,75.903,50,77,6,0,43,0,1785], + [74.966,75.082,42,73,13,0,43,0,1785], + [74.966,75.2,74,97,5,2,43,0,1785], + [74.967,76.371,86,107,2,0,43,0,1785], + [74.968,75.2,69,98,5,1,43,0,1785], + [74.97,76.84,33,96,9,0,43,0,1785], + [75.081,75.2,42,40,13,0,43,0.25,1788], + [75.087,75.2,45,86,8,0,43,0.25,1788], + [75.198,75.317,46,89,15,0,43,0.5,1790], + [75.203,75.317,33,96,8,0,43,0.5,1791], + [75.315,75.551,74,77,5,2,43,0.75,1793], + [75.318,75.434,42,50,13,0,43,0.75,1793], + [75.318,75.434,45,86,8,0,43,0.75,1793], + [75.318,75.551,69,80,5,1,43,0.75,1793], + [75.318,75.551,65,77,5,0,43,0.75,1793], + [75.431,75.551,42,64,13,0,43,1,1796], + [75.433,75.551,39,102,12,0,43,1,1796], + [75.435,75.551,36,107,10,0,43,1,1796], + [75.437,75.551,33,70,8,0,43,1,1796], + [75.55,75.668,45,81,8,0,43,1.25,1799], + [75.554,75.668,42,38,13,0,43,1.25,1799], + [75.666,75.903,65,89,5,0,43,1.5,1802], + [75.666,75.786,33,93,8,0,43,1.5,1802], + [75.667,75.903,69,91,5,1,43,1.5,1802], + [75.671,75.786,46,82,15,0,43,1.5,1802], + [75.671,75.903,74,88,5,2,43,1.5,1802], + [75.783,75.903,42,50,13,0,43,1.75,1804], + [75.785,75.903,45,82,8,0,43,1.75,1804], + [75.901,76.02,36,111,10,0,43,2,1807], + [75.901,76.137,74,95,5,2,43,2,1807], + [75.903,76.137,65,90,5,0,43,2,1807], + [75.903,76.84,57,77,6,2,43,2,1807], + [75.903,76.84,50,75,6,0,43,2,1807], + [75.904,76.137,69,96,5,1,43,2,1807], + [75.905,76.02,33,71,8,0,43,2,1807], + [75.905,76.02,42,69,13,0,43,2,1807], + [75.905,76.84,53,80,6,1,43,2,1807], + [76.019,76.137,45,85,8,0,43,2.25,1810], + [76.019,76.137,42,39,13,0,43,2.25,1810], + [76.134,76.254,46,88,15,0,43,2.5,1813], + [76.141,76.254,33,94,8,0,43,2.5,1813], + [76.251,76.489,74,82,5,2,43,2.75,1815], + [76.251,76.371,45,84,8,0,43,2.75,1816], + [76.252,76.489,65,77,5,0,43,2.75,1816], + [76.253,76.489,69,81,5,1,43,2.75,1816], + [76.257,76.371,42,45,13,0,43,2.75,1816], + [76.367,76.606,76,74,0,0,43,3,1818], + [76.368,76.606,76,87,3,0,43,3,1818], + [76.37,76.489,36,111,10,0,43,3,1818], + [76.371,76.489,33,68,8,0,43,3,1818], + [76.373,76.489,39,101,12,0,43,3,1818], + [76.373,76.489,42,62,13,0,43,3,1818], + [76.376,76.606,88,106,2,0,43,3,1818], + [76.487,76.606,45,84,8,0,43,3.25,1821], + [76.492,76.606,42,42,13,0,43,3.25,1821], + [76.602,76.84,77,88,3,0,43,3.5,1824], + [76.605,76.84,77,74,0,0,43,3.5,1824], + [76.605,76.723,33,97,8,0,43,3.5,1824], + [76.606,76.84,74,88,5,2,43,3.5,1824], + [76.606,76.84,89,105,2,0,43,3.5,1824], + [76.608,76.84,65,86,5,0,43,3.5,1824], + [76.609,76.84,69,89,5,1,43,3.5,1824], + [76.609,76.723,46,84,15,0,43,3.5,1824], + [76.724,76.84,42,53,13,0,43,3.75,1827], + [76.726,76.84,45,83,8,0,43,3.75,1827], + [76.835,76.957,36,114,10,0,44,0,1829], + [76.838,76.957,33,74,8,0,44,0,1829], + [76.838,76.957,42,71,13,0,44,0,1829], + [76.839,77.778,77,90,3,0,44,0,1829], + [76.839,78.715,33,95,9,0,44,0,1830], + [76.84,77.075,74,96,5,0,44,0,1830], + [76.84,77.778,77,71,0,0,44,0,1830], + [76.841,77.778,57,77,6,2,44,0,1830], + [76.841,77.075,77,95,5,1,44,0,1830], + [76.841,77.778,53,79,6,1,44,0,1830], + [76.841,77.778,89,107,2,0,44,0,1830], + [76.843,77.778,50,78,6,0,44,0,1830], + [76.955,77.075,45,83,8,0,44,0.25,1832], + [76.955,77.075,42,39,13,0,44,0.25,1832], + [77.073,77.192,46,85,15,0,44,0.5,1835], + [77.075,77.192,33,100,8,0,44,0.5,1835], + [77.191,77.309,42,47,13,0,44,0.75,1838], + [77.193,77.309,45,86,8,0,44,0.75,1838], + [77.193,77.426,74,82,5,0,44,0.75,1838], + [77.196,77.426,77,81,5,1,44,0.75,1838], + [77.306,77.426,33,69,8,0,44,1,1841], + [77.31,77.426,36,107,10,0,44,1,1841], + [77.31,77.426,42,61,13,0,44,1,1841], + [77.31,77.426,39,96,12,0,44,1,1841], + [77.424,77.543,42,40,13,0,44,1.25,1843], + [77.427,77.543,45,84,8,0,44,1.25,1844], + [77.541,77.661,46,84,15,0,44,1.5,1846], + [77.545,77.778,74,86,5,0,44,1.5,1846], + [77.545,77.661,33,96,8,0,44,1.5,1846], + [77.546,77.778,77,85,5,1,44,1.5,1846], + [77.661,77.778,42,46,13,0,44,1.75,1849], + [77.662,77.778,45,81,8,0,44,1.75,1849], + [77.775,78.715,57,75,6,2,44,2,1852], + [77.775,78.012,77,95,5,1,44,2,1852], + [77.776,77.895,36,110,10,0,44,2,1852], + [77.776,78.715,50,80,6,0,44,2,1852], + [77.776,77.895,42,69,13,0,44,2,1852], + [77.776,78.715,53,81,6,1,44,2,1852], + [77.778,78.715,89,105,2,0,44,2,1852], + [77.779,78.715,77,75,0,0,44,2,1852], + [77.779,78.715,77,89,3,0,44,2,1852], + [77.779,77.895,33,71,8,0,44,2,1852], + [77.782,78.012,74,91,5,0,44,2,1852], + [77.892,78.012,42,44,13,0,44,2.25,1855], + [77.895,78.012,45,87,8,0,44,2.25,1855], + [78.01,78.129,33,98,8,0,44,2.5,1857], + [78.013,78.129,46,91,15,0,44,2.5,1857], + [78.128,78.364,77,83,5,1,44,2.75,1860], + [78.128,78.246,45,83,8,0,44,2.75,1860], + [78.13,78.246,42,49,13,0,44,2.75,1860], + [78.13,78.364,74,75,5,0,44,2.75,1860], + [78.242,78.364,36,105,10,0,44,3,1863], + [78.245,78.364,42,61,13,0,44,3,1863], + [78.247,78.364,39,107,12,0,44,3,1863], + [78.25,78.364,33,68,8,0,44,3,1863], + [78.361,78.481,45,83,8,0,44,3.25,1866], + [78.367,78.481,42,39,13,0,44,3.25,1866], + [78.479,78.598,46,87,15,0,44,3.5,1869], + [78.481,78.715,74,86,5,0,44,3.5,1869], + [78.483,78.715,77,88,5,1,44,3.5,1869], + [78.483,78.598,33,95,8,0,44,3.5,1869], + [78.597,78.715,45,80,8,0,44,3.75,1871], + [78.598,78.715,42,54,13,0,44,3.75,1871], + [78.712,80.59,77,77,0,0,45,0,1874], + [78.713,80.59,89,105,2,0,45,0,1874], + [78.714,78.95,74,94,5,0,45,0,1874], + [78.715,80.59,77,94,3,0,45,0,1874], + [78.715,79.653,62,79,6,1,45,0,1874], + [78.715,78.832,34,70,8,0,45,0,1874], + [78.716,78.95,77,96,5,1,45,0,1874], + [78.716,80.59,34,97,9,0,45,0,1874], + [78.716,78.832,42,68,13,0,45,0,1874], + [78.717,79.653,65,79,6,2,45,0,1874], + [78.717,79.653,58,81,6,0,45,0,1874], + [78.717,78.832,36,114,10,0,45,0,1874], + [78.832,78.95,46,81,8,0,45,0.25,1877], + [78.834,78.95,42,42,13,0,45,0.25,1877], + [78.948,79.067,46,88,15,0,45,0.5,1880], + [78.952,79.067,34,94,8,0,45,0.5,1880], + [79.066,79.301,74,83,5,0,45,0.75,1883], + [79.067,79.301,77,85,5,1,45,0.75,1883], + [79.067,79.184,42,47,13,0,45,0.75,1883], + [79.067,79.184,46,87,8,0,45,0.75,1883], + [79.183,79.301,36,109,10,0,45,1,1885], + [79.183,79.301,42,66,13,0,45,1,1885], + [79.185,79.301,34,70,8,0,45,1,1885], + [79.186,79.301,39,99,12,0,45,1,1885], + [79.302,79.418,46,84,8,0,45,1.25,1888], + [79.302,79.418,42,40,13,0,45,1.25,1888], + [79.414,79.536,46,83,15,0,45,1.5,1891], + [79.415,79.653,74,89,5,0,45,1.5,1891], + [79.417,79.653,77,89,5,1,45,1.5,1891], + [79.421,79.536,34,99,8,0,45,1.5,1891], + [79.535,79.653,46,85,8,0,45,1.75,1894], + [79.535,79.653,42,46,13,0,45,1.75,1894], + [79.649,79.77,34,67,8,0,45,2,1896], + [79.651,80.59,65,81,6,2,45,2,1896], + [79.651,79.887,74,93,5,0,45,2,1896], + [79.652,79.77,36,110,10,0,45,2,1896], + [79.653,80.59,58,81,6,0,45,2,1896], + [79.654,80.59,62,79,6,1,45,2,1897], + [79.654,79.887,77,95,5,1,45,2,1897], + [79.657,79.77,42,70,13,0,45,2,1897], + [79.768,79.887,42,37,13,0,45,2.25,1899], + [79.772,79.887,46,86,8,0,45,2.25,1899], + [79.887,80.004,34,95,8,0,45,2.5,1902], + [79.889,80.004,46,88,15,0,45,2.5,1902], + [80.003,80.121,42,48,13,0,45,2.75,1905], + [80.004,80.239,77,78,5,1,45,2.75,1905], + [80.006,80.121,46,83,8,0,45,2.75,1905], + [80.008,80.239,74,79,5,0,45,2.75,1905], + [80.119,80.239,39,103,12,0,45,3,1908], + [80.121,80.239,34,69,8,0,45,3,1908], + [80.122,80.239,36,110,10,0,45,3,1908], + [80.124,80.239,42,68,13,0,45,3,1908], + [80.237,80.356,46,82,8,0,45,3.25,1910], + [80.239,80.356,42,42,13,0,45,3.25,1910], + [80.354,80.59,74,84,5,0,45,3.5,1913], + [80.356,80.473,34,98,8,0,45,3.5,1913], + [80.358,80.59,77,88,5,1,45,3.5,1913], + [80.359,80.473,46,83,15,0,45,3.5,1913], + [80.473,80.59,42,51,13,0,45,3.75,1916], + [80.474,80.59,46,83,8,0,45,3.75,1916], + [80.589,80.825,75,97,5,1,46,0,1919], + [80.589,81.996,75,69,0,0,46,0,1919], + [80.589,82.465,34,94,9,0,46,0,1919], + [80.59,80.825,67,97,5,0,46,0,1919], + [80.59,81.528,51,81,6,0,46,0,1919], + [80.59,80.707,42,68,13,0,46,0,1919], + [80.591,81.996,75,87,3,0,46,0,1919], + [80.591,81.528,58,82,6,2,46,0,1919], + [80.591,80.707,36,114,10,0,46,0,1919], + [80.591,80.707,49,119,16,0,46,0,1919], + [80.592,81.996,87,105,2,0,46,0,1919], + [80.592,80.707,34,68,8,0,46,0,1919], + [80.595,81.528,55,81,6,1,46,0,1919], + [80.707,80.825,46,82,8,0,46,0.25,1922], + [80.709,80.825,42,42,13,0,46,0.25,1922], + [80.825,80.942,34,97,8,0,46,0.5,1924], + [80.827,80.942,46,86,15,0,46,0.5,1924], + [80.942,81.059,46,81,8,0,46,0.75,1927], + [80.943,81.176,67,81,5,0,46,0.75,1927], + [80.943,81.176,75,79,5,1,46,0.75,1927], + [80.946,81.059,42,49,13,0,46,0.75,1927], + [81.058,81.176,39,97,12,0,46,1,1930], + [81.06,81.176,34,67,8,0,46,1,1930], + [81.061,81.176,42,69,13,0,46,1,1930], + [81.062,81.176,36,108,10,0,46,1,1930], + [81.176,81.293,46,82,8,0,46,1.25,1933], + [81.177,81.293,42,40,13,0,46,1.25,1933], + [81.291,81.411,34,98,8,0,46,1.5,1935], + [81.292,81.528,67,83,5,0,46,1.5,1936], + [81.292,81.528,75,86,5,1,46,1.5,1936], + [81.294,81.411,46,83,15,0,46,1.5,1936], + [81.407,81.528,46,83,8,0,46,1.75,1938], + [81.411,81.528,42,48,13,0,46,1.75,1938], + [81.523,81.645,36,108,10,0,46,2,1941], + [81.527,81.762,67,91,5,0,46,2,1941], + [81.527,82.465,58,79,6,2,46,2,1941], + [81.528,82.465,51,77,6,0,46,2,1941], + [81.528,81.645,42,72,13,0,46,2,1941], + [81.528,81.762,75,97,5,1,46,2,1941], + [81.528,81.645,34,68,8,0,46,2,1941], + [81.528,82.465,55,80,6,1,46,2,1941], + [81.642,81.762,42,38,13,0,46,2.25,1944], + [81.644,81.762,46,81,8,0,46,2.25,1944], + [81.762,81.879,46,88,15,0,46,2.5,1947], + [81.763,81.879,34,95,8,0,46,2.5,1947], + [81.878,82.114,75,80,5,1,46,2.75,1949], + [81.879,81.996,42,47,13,0,46,2.75,1949], + [81.879,82.114,67,78,5,0,46,2.75,1949], + [81.883,81.996,46,84,8,0,46,2.75,1950], + [81.992,82.231,74,71,0,0,46,3,1952], + [81.992,82.114,36,104,10,0,46,3,1952], + [81.993,82.231,74,91,3,0,46,3,1952], + [81.997,82.114,34,74,8,0,46,3,1952], + [81.997,82.114,39,104,12,0,46,3,1952], + [81.997,82.114,42,64,13,0,46,3,1952], + [81.999,82.231,86,104,2,0,46,3,1952], + [82.112,82.231,42,38,13,0,46,3.25,1955], + [82.117,82.231,46,86,8,0,46,3.25,1955], + [82.227,82.465,75,88,5,1,46,3.5,1958], + [82.228,82.348,46,84,15,0,46,3.5,1958], + [82.228,82.348,34,96,8,0,46,3.5,1958], + [82.23,82.465,67,85,5,0,46,3.5,1958], + [82.23,82.465,84,106,2,0,46,3.5,1958], + [82.231,82.465,72,73,0,0,46,3.5,1958], + [82.232,82.465,72,92,3,0,46,3.5,1958], + [82.35,82.465,46,88,8,0,46,3.75,1961], + [82.352,82.465,42,54,13,0,46,3.75,1961], + [82.461,82.582,36,115,10,0,47,0,1963], + [82.464,83.403,65,78,6,2,47,0,1963], + [82.464,82.582,34,72,8,0,47,0,1963], + [82.464,82.582,42,70,13,0,47,0,1963], + [82.465,83.403,82,110,2,0,47,0,1963], + [82.465,84.34,34,97,9,0,47,0,1963], + [82.465,83.403,58,83,6,0,47,0,1963], + [82.466,82.7,70,96,5,2,47,0,1963], + [82.467,83.403,70,74,0,0,47,0,1964], + [82.468,83.403,70,88,3,0,47,0,1964], + [82.468,82.7,62,97,5,0,47,0,1964], + [82.469,82.7,65,97,5,1,47,0,1964], + [82.471,83.403,62,79,6,1,47,0,1964], + [82.58,82.7,46,83,8,0,47,0.25,1966], + [82.583,82.7,42,42,13,0,47,0.25,1966], + [82.699,82.817,46,87,15,0,47,0.5,1969], + [82.7,82.817,34,94,8,0,47,0.5,1969], + [82.812,82.934,46,83,8,0,47,0.75,1972], + [82.812,82.934,42,49,13,0,47,0.75,1972], + [82.816,83.051,62,80,5,0,47,0.75,1972], + [82.816,83.051,70,82,5,2,47,0.75,1972], + [82.819,83.051,65,79,5,1,47,0.75,1972], + [82.932,83.051,34,72,8,0,47,1,1975], + [82.934,83.051,39,103,12,0,47,1,1975], + [82.934,83.051,36,107,10,0,47,1,1975], + [82.935,83.051,42,66,13,0,47,1,1975], + [83.05,83.168,42,43,13,0,47,1.25,1977], + [83.053,83.168,46,86,8,0,47,1.25,1977], + [83.166,83.403,70,90,5,2,47,1.5,1980], + [83.166,83.286,46,84,15,0,47,1.5,1980], + [83.166,83.403,62,87,5,0,47,1.5,1980], + [83.168,83.286,34,99,8,0,47,1.5,1980], + [83.168,83.403,65,87,5,1,47,1.5,1980], + [83.287,83.403,46,83,8,0,47,1.75,1983], + [83.288,83.403,42,44,13,0,47,1.75,1983], + [83.4,83.637,65,94,5,1,47,2,1986], + [83.4,84.34,58,77,6,0,47,2,1986], + [83.401,83.52,36,110,10,0,47,2,1986], + [83.401,84.34,65,80,6,2,47,2,1986], + [83.401,83.637,70,96,5,2,47,2,1986], + [83.402,84.34,81,102,2,0,47,2,1986], + [83.402,84.34,69,89,3,0,47,2,1986], + [83.403,84.34,69,73,0,0,47,2,1986], + [83.403,83.52,34,68,8,0,47,2,1986], + [83.404,83.52,42,68,13,0,47,2,1986], + [83.405,83.637,62,93,5,0,47,2,1986], + [83.406,84.34,62,84,6,1,47,2,1986], + [83.518,83.637,46,84,8,0,47,2.25,1989], + [83.523,83.637,42,38,13,0,47,2.25,1989], + [83.637,83.754,46,84,15,0,47,2.5,1991], + [83.638,83.754,34,95,8,0,47,2.5,1991], + [83.751,83.989,70,81,5,2,47,2.75,1994], + [83.753,83.989,62,80,5,0,47,2.75,1994], + [83.755,83.871,42,44,13,0,47,2.75,1994], + [83.757,83.871,46,83,8,0,47,2.75,1994], + [83.758,83.989,65,81,5,1,47,2.75,1994], + [83.871,83.989,36,110,10,0,47,3,1997], + [83.872,83.989,34,71,8,0,47,3,1997], + [83.873,83.989,39,106,12,0,47,3,1997], + [83.876,83.989,42,64,13,0,47,3,1997], + [83.989,84.106,46,85,8,0,47,3.25,2000], + [83.991,84.106,42,41,13,0,47,3.25,2000], + [84.103,84.34,62,88,5,0,47,3.5,2002], + [84.104,84.223,34,95,8,0,47,3.5,2002], + [84.104,84.34,70,89,5,2,47,3.5,2002], + [84.104,84.223,46,80,15,0,47,3.5,2002], + [84.108,84.34,65,87,5,1,47,3.5,2003], + [84.222,84.34,46,82,8,0,47,3.75,2005], + [84.226,84.34,42,47,13,0,47,3.75,2005], + [84.336,84.575,65,99,5,1,48,0,2008], + [84.337,85.278,68,73,0,0,48,0,2008], + [84.339,85.278,59,80,6,2,48,0,2008], + [84.339,85.278,80,105,2,0,48,0,2008], + [84.339,86.215,35,96,9,0,48,0,2008], + [84.34,84.457,36,110,10,0,48,0,2008], + [84.34,84.457,42,68,13,0,48,0,2008], + [84.341,84.575,68,93,5,2,48,0,2008], + [84.342,85.278,52,79,6,0,48,0,2008], + [84.342,84.457,35,69,8,0,48,0,2008], + [84.343,85.278,56,79,6,1,48,0,2008], + [84.343,85.278,68,88,3,0,48,0,2008], + [84.345,84.575,62,97,5,0,48,0,2008], + [84.453,84.575,42,37,13,0,48,0.25,2011], + [84.459,84.575,47,84,8,0,48,0.25,2011], + [84.577,84.692,35,97,8,0,48,0.5,2014], + [84.578,84.692,46,86,15,0,48,0.5,2014], + [84.687,84.926,65,83,5,1,48,0.75,2016], + [84.689,84.809,42,49,13,0,48,0.75,2016], + [84.69,84.809,47,83,8,0,48,0.75,2016], + [84.693,84.926,68,78,5,2,48,0.75,2016], + [84.694,84.926,62,79,5,0,48,0.75,2017], + [84.806,84.926,35,68,8,0,48,1,2019], + [84.81,84.926,39,101,12,0,48,1,2019], + [84.81,84.926,42,65,13,0,48,1,2019], + [84.81,84.926,36,111,10,0,48,1,2019], + [84.927,85.043,42,41,13,0,48,1.25,2022], + [84.929,85.043,47,84,8,0,48,1.25,2022], + [85.043,85.278,68,89,5,2,48,1.5,2025], + [85.043,85.161,35,96,8,0,48,1.5,2025], + [85.044,85.161,46,81,15,0,48,1.5,2025], + [85.045,85.278,62,87,5,0,48,1.5,2025], + [85.045,85.278,65,87,5,1,48,1.5,2025], + [85.161,85.278,47,86,8,0,48,1.75,2028], + [85.162,85.278,42,45,13,0,48,1.75,2028], + [85.273,86.215,68,75,0,0,48,2,2030], + [85.274,85.395,42,72,13,0,48,2,2030], + [85.275,86.215,52,82,6,0,48,2,2030], + [85.276,85.512,68,97,5,2,48,2,2030], + [85.276,85.512,62,95,5,0,48,2,2030], + [85.276,86.215,56,80,6,1,48,2,2030], + [85.277,85.395,35,69,8,0,48,2,2030], + [85.277,85.512,65,99,5,1,48,2,2030], + [85.278,86.215,59,79,6,2,48,2,2030], + [85.279,86.215,80,108,2,0,48,2,2030], + [85.28,86.215,68,91,3,0,48,2,2030], + [85.28,85.395,36,112,10,0,48,2,2030], + [85.393,85.512,47,81,8,0,48,2.25,2033], + [85.394,85.512,42,42,13,0,48,2.25,2033], + [85.515,85.629,46,85,15,0,48,2.5,2036], + [85.515,85.629,35,97,8,0,48,2.5,2036], + [85.627,85.864,62,79,5,0,48,2.75,2039], + [85.629,85.746,42,48,13,0,48,2.75,2039], + [85.629,85.864,68,82,5,2,48,2.75,2039], + [85.629,85.864,65,80,5,1,48,2.75,2039], + [85.633,85.746,47,84,8,0,48,2.75,2039], + [85.744,85.864,39,107,12,0,48,3,2042], + [85.744,85.864,36,110,10,0,48,3,2042], + [85.745,85.864,42,67,13,0,48,3,2042], + [85.75,85.864,35,72,8,0,48,3,2042], + [85.862,85.981,42,41,13,0,48,3.25,2044], + [85.865,85.981,47,86,8,0,48,3.25,2044], + [85.978,86.215,65,89,5,1,48,3.5,2047], + [85.979,86.215,68,91,5,2,48,3.5,2047], + [85.979,86.098,46,85,15,0,48,3.5,2047], + [85.98,86.215,62,88,5,0,48,3.5,2047], + [85.981,86.098,35,95,8,0,48,3.5,2047], + [86.097,86.215,42,55,13,0,48,3.75,2050], + [86.099,86.215,47,85,8,0,48,3.75,2050], + [86.213,87.153,57,83,6,0,49,0,2053], + [86.214,88.09,69,89,3,0,49,0,2053], + [86.214,86.332,52,108,11,0,49,0,2053], + [86.215,86.45,69,96,5,2,49,0,2053], + [86.215,86.45,60,92,5,0,49,0,2053], + [86.215,86.332,38,71,14,0,49,0,2053], + [86.215,87.153,60,83,6,1,49,0,2053], + [86.215,86.45,64,98,5,1,49,0,2053], + [86.215,88.09,81,106,2,0,49,0,2053], + [86.215,86.332,42,73,13,0,49,0,2053], + [86.216,87.153,64,82,6,2,49,0,2053], + [86.216,86.332,33,70,8,0,49,0,2053], + [86.217,88.09,69,72,0,0,49,0,2053], + [86.217,86.332,40,100,18,0,49,0,2053], + [86.217,86.332,36,114,10,0,49,0,2053], + [86.219,88.09,33,96,9,0,49,0,2053], + [86.328,86.45,38,71,14,0,49,0.25,2055], + [86.331,86.45,42,41,13,0,49,0.25,2055], + [86.332,86.45,45,88,8,0,49,0.25,2056], + [86.45,86.567,33,92,8,0,49,0.5,2058], + [86.451,86.567,46,89,15,0,49,0.5,2058], + [86.451,86.567,38,82,14,0,49,0.5,2058], + [86.564,86.801,69,80,5,2,49,0.75,2061], + [86.567,86.684,38,82,14,0,49,0.75,2061], + [86.568,86.684,42,46,13,0,49,0.75,2061], + [86.568,86.684,45,84,8,0,49,0.75,2061], + [86.568,86.801,60,77,5,0,49,0.75,2061], + [86.569,86.801,64,79,5,1,49,0.75,2061], + [86.683,86.801,36,108,10,0,49,1,2064], + [86.684,86.801,33,70,8,0,49,1,2064], + [86.684,86.801,42,65,13,0,49,1,2064], + [86.686,86.801,39,99,12,0,49,1,2064], + [86.686,86.801,38,87,14,0,49,1,2064], + [86.801,86.918,42,37,13,0,49,1.25,2067], + [86.802,86.918,45,83,8,0,49,1.25,2067], + [86.803,86.918,38,87,14,0,49,1.25,2067], + [86.915,87.153,60,88,5,0,49,1.5,2069], + [86.916,87.153,69,88,5,2,49,1.5,2069], + [86.917,87.036,38,92,14,0,49,1.5,2069], + [86.918,87.036,33,98,8,0,49,1.5,2069], + [86.918,87.153,64,86,5,1,49,1.5,2069], + [86.92,87.036,46,83,15,0,49,1.5,2070], + [87.033,87.153,42,44,13,0,49,1.75,2072], + [87.038,87.153,45,84,8,0,49,1.75,2072], + [87.039,87.153,38,99,14,0,49,1.75,2072], + [87.15,88.09,64,76,6,2,49,2,2075], + [87.15,87.387,69,97,5,2,49,2,2075], + [87.151,87.387,64,93,5,1,49,2,2075], + [87.151,87.27,45,118,11,0,49,2,2075], + [87.151,88.09,57,79,6,0,49,2,2075], + [87.152,87.27,42,66,13,0,49,2,2075], + [87.153,87.27,38,102,14,0,49,2,2075], + [87.153,87.27,36,109,10,0,49,2,2075], + [87.154,87.27,33,69,8,0,49,2,2075], + [87.154,87.387,60,97,5,0,49,2,2075], + [87.156,88.09,60,81,6,1,49,2,2075], + [87.264,87.387,42,42,13,0,49,2.25,2078], + [87.271,87.387,45,81,8,0,49,2.25,2078], + [87.272,87.387,38,107,14,0,49,2.25,2078], + [87.387,87.504,33,98,8,0,49,2.5,2081], + [87.389,87.504,46,89,15,0,49,2.5,2081], + [87.39,87.504,38,110,14,0,49,2.5,2081], + [87.5,87.621,45,84,8,0,49,2.75,2083], + [87.501,87.739,69,81,5,2,49,2.75,2083], + [87.502,87.739,60,80,5,0,49,2.75,2083], + [87.502,87.621,38,113,14,0,49,2.75,2083], + [87.503,87.621,42,47,13,0,49,2.75,2083], + [87.505,87.739,64,84,5,1,49,2.75,2083], + [87.619,87.739,38,117,14,0,49,3,2086], + [87.619,87.739,33,70,8,0,49,3,2086], + [87.622,87.739,39,103,12,0,49,3,2086], + [87.623,87.739,36,104,10,0,49,3,2086], + [87.623,87.739,42,64,13,0,49,3,2086], + [87.734,87.856,38,121,14,0,49,3.25,2089], + [87.739,87.856,42,35,13,0,49,3.25,2089], + [87.739,87.856,45,82,8,0,49,3.25,2089], + [87.854,88.09,69,89,5,2,49,3.5,2092], + [87.855,88.09,60,91,5,0,49,3.5,2092], + [87.856,87.973,38,122,14,0,49,3.5,2092], + [87.856,87.973,33,97,8,0,49,3.5,2092], + [87.857,87.973,46,84,15,0,49,3.5,2092], + [87.858,88.09,64,87,5,1,49,3.5,2092], + [87.972,88.09,42,54,13,0,49,3.75,2095], + [87.975,88.09,38,127,14,0,49,3.75,2095], + [87.976,88.09,45,80,8,0,49,3.75,2095], + [88.088,88.207,36,107,10,0,50,0,2097], + [88.088,88.207,49,68,16,0,50,0,2097], + [88.088,89.028,60,76,6,1,50,0,2097], + [88.089,88.207,57,58,0,0,50,0,2097], + [88.091,89.028,57,80,6,0,50,0,2097], + [88.091,89.028,33,90,9,0,50,0,2097], + [88.093,89.028,64,84,6,2,50,0,2097], + [88.209,88.325,60,57,0,0,50,0.25,2100], + [88.324,88.442,64,59,0,0,50,0.5,2103], + [88.443,88.559,69,59,0,0,50,0.75,2106], + [88.559,88.676,72,60,0,0,50,1,2109], + [88.675,88.793,76,57,0,0,50,1.25,2111], + [88.792,88.911,81,57,0,0,50,1.5,2114], + [88.911,89.028,76,61,0,0,50,1.75,2117], + [89.024,89.965,57,80,6,0,50,2,2120], + [89.026,89.145,36,100,10,0,50,2,2120], + [89.027,89.965,64,83,6,2,50,2,2120], + [89.028,89.965,33,85,9,0,50,2,2120], + [89.028,89.965,60,82,6,1,50,2,2120], + [89.03,89.145,72,62,0,0,50,2,2120], + [89.144,89.262,69,56,0,0,50,2.25,2122], + [89.261,89.379,64,57,0,0,50,2.5,2125], + [89.376,89.496,60,59,0,0,50,2.75,2128], + [89.496,89.614,57,61,0,0,50,3,2131], + [89.616,89.731,60,59,0,0,50,3.25,2134], + [89.731,89.848,64,58,0,0,50,3.5,2136], + [89.846,89.965,69,59,0,0,50,3.75,2139], + [89.963,90.903,33,88,9,0,51,0,2142], + [89.964,90.903,64,82,6,2,51,0,2142], + [89.964,90.903,60,80,6,1,51,0,2142], + [89.965,90.082,69,58,0,0,51,0,2142], + [89.965,90.903,57,80,6,0,51,0,2142], + [89.965,90.082,36,103,10,0,51,0,2142], + [90.081,90.2,72,59,0,0,51,0.25,2145], + [90.2,90.317,76,58,0,0,51,0.5,2148], + [90.319,90.434,81,61,0,0,51,0.75,2150], + [90.437,90.551,84,59,0,0,51,1,2153], + [90.554,90.668,88,58,0,0,51,1.25,2156], + [90.666,90.786,93,63,0,0,51,1.5,2159], + [90.785,90.903,88,59,0,0,51,1.75,2162], + [90.899,91.02,84,61,0,0,51,2,2164], + [90.9,91.84,57,82,6,0,51,2,2164], + [90.902,91.84,64,79,6,2,51,2,2164], + [90.904,91.02,36,99,10,0,51,2,2164], + [90.904,91.84,60,82,6,1,51,2,2164], + [90.905,91.84,33,89,9,0,51,2,2164], + [91.021,91.137,81,60,0,0,51,2.25,2167], + [91.135,91.254,76,63,0,0,51,2.5,2170], + [91.25,91.371,72,61,0,0,51,2.75,2173], + [91.373,91.489,69,56,0,0,51,3,2176], + [91.491,91.606,72,57,0,0,51,3.25,2178], + [91.607,91.723,76,61,0,0,51,3.5,2181], + [91.723,91.84,81,58,0,0,51,3.75,2184], + [91.838,92.778,53,84,6,0,52,0,2187], + [91.838,92.778,57,83,6,1,52,0,2187], + [91.84,91.957,53,63,0,0,52,0,2187], + [91.84,91.957,36,104,10,0,52,0,2187], + [91.843,92.778,60,79,6,2,52,0,2187], + [91.843,92.778,29,91,9,0,52,0,2187], + [91.955,92.075,57,58,0,0,52,0.25,2189], + [92.075,92.192,60,59,0,0,52,0.5,2192], + [92.19,92.309,65,62,0,0,52,0.75,2195], + [92.31,92.426,69,60,0,0,52,1,2198], + [92.423,92.543,72,61,0,0,52,1.25,2201], + [92.543,92.661,77,58,0,0,52,1.5,2203], + [92.664,92.778,72,60,0,0,52,1.75,2206], + [92.776,93.715,29,86,9,0,52,2,2209], + [92.777,93.715,53,82,6,0,52,2,2209], + [92.777,93.715,60,83,6,2,52,2,2209], + [92.778,92.895,69,57,0,0,52,2,2209], + [92.779,92.895,36,99,10,0,52,2,2209], + [92.781,93.715,57,77,6,1,52,2,2209], + [92.895,93.012,65,61,0,0,52,2.25,2212], + [93.013,93.129,60,62,0,0,52,2.5,2215], + [93.127,93.246,57,58,0,0,52,2.75,2217], + [93.248,93.364,53,58,0,0,52,3,2220], + [93.365,93.481,57,56,0,0,52,3.25,2223], + [93.482,93.598,60,61,0,0,52,3.5,2226], + [93.599,93.715,65,62,0,0,52,3.75,2229], + [93.712,94.653,59,80,6,2,53,0,2231], + [93.717,93.832,52,63,0,0,53,0,2231], + [93.717,94.653,52,77,6,0,53,0,2231], + [93.717,94.653,56,78,6,1,53,0,2231], + [93.718,93.832,36,105,10,0,53,0,2231], + [93.719,94.653,28,93,9,0,53,0,2231], + [93.832,93.95,56,61,0,0,53,0.25,2234], + [93.95,94.067,59,60,0,0,53,0.5,2237], + [94.07,94.184,64,57,0,0,53,0.75,2240], + [94.182,94.301,68,57,0,0,53,1,2242], + [94.304,94.418,71,58,0,0,53,1.25,2245], + [94.421,94.536,76,58,0,0,53,1.5,2248], + [94.531,94.653,71,58,0,0,53,1.75,2251], + [94.651,95.59,59,79,6,2,53,2,2254], + [94.652,94.77,68,58,0,0,53,2,2254], + [94.652,94.77,36,101,10,0,53,2,2254], + [94.652,95.59,52,82,6,0,53,2,2254], + [94.652,95.59,28,87,9,0,53,2,2254], + [94.657,95.59,56,77,6,1,53,2,2254], + [94.768,94.887,64,61,0,0,53,2.25,2256], + [94.886,95.004,59,58,0,0,53,2.5,2259], + [95.006,95.121,56,58,0,0,53,2.75,2262], + [95.119,95.239,52,60,0,0,53,3,2265], + [95.239,95.356,56,57,0,0,53,3.25,2268], + [95.354,95.473,59,60,0,0,53,3.5,2270], + [95.476,95.59,64,63,0,0,53,3.75,2273], + [95.586,95.707,94,74,2,0,54,0,2276], + [95.586,97.465,64,49,7,2,54,0,2276], + [95.589,95.707,82,75,0,0,54,0,2276], + [95.589,96.528,60,81,6,1,54,0,2276], + [95.589,95.707,36,106,10,0,54,0,2276], + [95.59,95.707,52,87,4,0,54,0,2276], + [95.59,95.707,38,56,14,0,54,0,2276], + [95.59,97.465,57,50,7,0,54,0,2276], + [95.59,96.528,33,91,9,0,54,0,2276], + [95.591,97.465,60,50,7,1,54,0,2276], + [95.591,96.528,57,82,6,0,54,0,2276], + [95.592,96.528,64,79,6,2,54,0,2276], + [95.593,95.707,43,98,18,0,54,0,2276], + [95.705,95.825,93,72,2,0,54,0.25,2279], + [95.706,95.825,45,86,8,0,54,0.25,2279], + [95.708,95.825,56,64,4,0,54,0.25,2279], + [95.709,95.825,81,74,0,0,54,0.25,2279], + [95.823,95.942,45,72,8,0,54,0.5,2282], + [95.824,95.942,59,62,4,0,54,0.5,2282], + [95.825,95.942,80,75,0,0,54,0.5,2282], + [95.828,95.942,92,74,2,0,54,0.5,2282], + [95.939,96.059,91,74,2,0,54,0.75,2284], + [95.942,96.059,45,82,8,0,54,0.75,2284], + [95.942,96.059,64,63,4,0,54,0.75,2284], + [95.944,96.059,79,74,0,0,54,0.75,2284], + [96.056,96.176,38,62,14,0,54,1,2287], + [96.057,96.176,68,79,4,0,54,1,2287], + [96.061,96.176,78,73,0,0,54,1,2287], + [96.062,96.176,90,72,2,0,54,1,2287], + [96.173,96.293,77,77,0,0,54,1.25,2290], + [96.175,96.293,45,86,8,0,54,1.25,2290], + [96.176,96.293,71,63,4,0,54,1.25,2290], + [96.176,96.293,89,76,2,0,54,1.25,2290], + [96.29,96.411,64,61,4,0,54,1.5,2293], + [96.294,96.411,88,77,2,0,54,1.5,2293], + [96.294,96.411,45,72,8,0,54,1.5,2293], + [96.296,96.411,76,72,0,0,54,1.5,2293], + [96.412,96.528,45,79,8,0,54,1.75,2296], + [96.412,96.528,87,76,2,0,54,1.75,2296], + [96.413,96.528,59,61,4,0,54,1.75,2296], + [96.413,96.528,75,74,0,0,54,1.75,2296], + [96.524,97.465,33,91,9,0,54,2,2298], + [96.526,97.465,60,83,6,1,54,2,2298], + [96.527,96.645,74,74,0,0,54,2,2298], + [96.527,96.645,38,65,14,0,54,2,2298], + [96.527,96.645,36,97,10,0,54,2,2298], + [96.529,96.645,86,71,2,0,54,2,2298], + [96.529,97.465,57,81,6,0,54,2,2298], + [96.53,96.645,52,80,4,0,54,2,2298], + [96.531,97.465,64,82,6,2,54,2,2298], + [96.644,96.762,56,61,4,0,54,2.25,2301], + [96.646,96.762,73,74,0,0,54,2.25,2301], + [96.646,96.762,85,73,2,0,54,2.25,2301], + [96.648,96.762,45,88,8,0,54,2.25,2301], + [96.759,96.879,59,63,4,0,54,2.5,2304], + [96.76,96.879,45,72,8,0,54,2.5,2304], + [96.761,96.879,84,76,2,0,54,2.5,2304], + [96.765,96.879,72,75,0,0,54,2.5,2304], + [96.878,96.996,64,64,4,0,54,2.75,2307], + [96.88,96.996,71,73,0,0,54,2.75,2307], + [96.881,96.996,45,79,8,0,54,2.75,2307], + [96.885,96.996,83,76,2,0,54,2.75,2307], + [96.995,97.114,70,76,0,0,54,3,2309], + [96.995,97.114,82,73,2,0,54,3,2309], + [96.995,97.114,38,70,14,0,54,3,2309], + [96.997,97.114,68,82,4,0,54,3,2309], + [97.112,97.231,45,82,8,0,54,3.25,2312], + [97.113,97.231,69,76,0,0,54,3.25,2312], + [97.113,97.231,81,73,2,0,54,3.25,2312], + [97.116,97.231,71,62,4,0,54,3.25,2312], + [97.228,97.348,45,72,8,0,54,3.5,2315], + [97.23,97.348,80,75,2,0,54,3.5,2315], + [97.23,97.348,64,62,4,0,54,3.5,2315], + [97.232,97.348,68,75,0,0,54,3.5,2315], + [97.345,97.465,67,76,0,0,54,3.75,2318], + [97.347,97.465,45,78,8,0,54,3.75,2318], + [97.349,97.465,59,65,4,0,54,3.75,2318], + [97.352,97.465,79,72,2,0,54,3.75,2318], + [97.462,99.34,64,73,7,2,55,0,2321], + [97.463,99.34,59,67,7,1,55,0,2321], + [97.463,98.403,59,84,6,2,55,0,2321], + [97.465,98.403,28,87,9,0,55,0,2321], + [97.465,99.34,52,68,7,0,55,0,2321], + [97.465,97.582,78,73,2,0,55,0,2321], + [97.466,97.582,66,73,0,0,55,0,2321], + [97.467,97.582,38,73,14,0,55,0,2321], + [97.467,97.582,36,111,10,0,55,0,2321], + [97.467,98.403,52,84,6,0,55,0,2321], + [97.467,97.582,52,84,4,0,55,0,2321], + [97.467,98.403,56,86,6,1,55,0,2321], + [97.581,97.7,65,75,0,0,55,0.25,2323], + [97.583,97.7,77,72,2,0,55,0.25,2323], + [97.583,97.7,56,67,4,0,55,0.25,2323], + [97.584,97.7,40,93,8,0,55,0.25,2323], + [97.698,97.817,38,75,14,0,55,0.5,2326], + [97.699,97.817,59,66,4,0,55,0.5,2326], + [97.699,97.817,40,75,8,0,55,0.5,2326], + [97.699,97.817,76,76,2,0,55,0.5,2326], + [97.702,97.817,64,74,0,0,55,0.5,2326], + [97.814,97.934,40,80,8,0,55,0.75,2329], + [97.815,97.934,65,71,0,0,55,0.75,2329], + [97.816,97.934,77,74,2,0,55,0.75,2329], + [97.816,97.934,64,63,4,0,55,0.75,2329], + [97.933,98.051,38,77,14,0,55,1,2332], + [97.934,98.051,66,73,0,0,55,1,2332], + [97.934,98.051,36,110,10,0,55,1,2332], + [97.935,98.051,68,83,4,0,55,1,2332], + [97.936,98.051,78,76,2,0,55,1,2332], + [98.047,98.168,67,73,0,0,55,1.25,2334], + [98.05,98.168,79,75,2,0,55,1.25,2335], + [98.051,98.168,40,88,8,0,55,1.25,2335], + [98.052,98.168,71,62,4,0,55,1.25,2335], + [98.167,98.286,40,80,8,0,55,1.5,2337], + [98.168,98.286,80,75,2,0,55,1.5,2337], + [98.17,98.286,68,76,0,0,55,1.5,2337], + [98.171,98.286,38,79,14,0,55,1.5,2337], + [98.172,98.286,64,66,4,0,55,1.5,2337], + [98.286,98.403,69,75,0,0,55,1.75,2340], + [98.286,98.403,40,85,8,0,55,1.75,2340], + [98.286,98.403,81,77,2,0,55,1.75,2340], + [98.29,98.403,59,69,4,0,55,1.75,2340], + [98.398,98.52,38,81,14,0,55,2,2343], + [98.401,98.52,52,81,4,0,55,2,2343], + [98.402,99.34,52,84,6,0,55,2,2343], + [98.402,99.34,59,84,6,2,55,2,2343], + [98.402,99.34,28,91,9,0,55,2,2343], + [98.402,99.34,56,87,6,1,55,2,2343], + [98.404,98.52,82,74,2,0,55,2,2343], + [98.404,98.52,70,71,0,0,55,2,2343], + [98.405,98.52,36,104,10,0,55,2,2343], + [98.52,98.637,56,65,4,0,55,2.25,2346], + [98.52,98.637,40,90,8,0,55,2.25,2346], + [98.521,98.637,71,72,0,0,55,2.25,2346], + [98.523,98.637,83,74,2,0,55,2.25,2346], + [98.632,98.754,84,74,2,0,55,2.5,2348], + [98.634,98.754,72,74,0,0,55,2.5,2348], + [98.635,98.754,38,85,14,0,55,2.5,2348], + [98.635,98.754,40,74,8,0,55,2.5,2348], + [98.639,98.754,59,64,4,0,55,2.5,2349], + [98.753,98.871,64,66,4,0,55,2.75,2351], + [98.754,98.871,85,72,2,0,55,2.75,2351], + [98.755,98.871,40,84,8,0,55,2.75,2351], + [98.758,98.871,73,69,0,0,55,2.75,2351], + [98.868,98.989,74,75,0,0,55,3,2354], + [98.87,98.989,68,90,4,0,55,3,2354], + [98.871,98.989,86,73,2,0,55,3,2354], + [98.873,98.989,38,88,14,0,55,3,2354], + [98.874,98.989,36,106,10,0,55,3,2354], + [98.988,99.106,40,90,8,0,55,3.25,2357], + [98.988,99.106,71,64,4,0,55,3.25,2357], + [98.99,99.106,87,75,2,0,55,3.25,2357], + [98.991,99.106,75,75,0,0,55,3.25,2357], + [99.102,99.223,76,75,0,0,55,3.5,2360], + [99.103,99.223,40,74,8,0,55,3.5,2360], + [99.106,99.223,64,63,4,0,55,3.5,2360], + [99.107,99.223,88,72,2,0,55,3.5,2360], + [99.109,99.223,38,89,14,0,55,3.5,2360], + [99.221,99.34,59,67,4,0,55,3.75,2362], + [99.222,99.34,40,83,8,0,55,3.75,2362], + [99.225,99.34,89,78,2,0,55,3.75,2363], + [99.226,99.34,77,72,0,0,55,3.75,2363], + [99.336,99.457,36,108,10,0,56,0,2365], + [99.338,99.457,76,92,0,0,56,0,2365], + [99.338,99.457,38,90,14,0,56,0,2365], + [99.339,101.215,52,96,7,0,56,0,2365], + [99.339,99.457,88,91,2,0,56,0,2365], + [99.339,100.278,52,87,6,0,56,0,2365], + [99.339,99.457,52,89,4,0,56,0,2365], + [99.34,101.215,59,90,7,2,56,0,2365], + [99.341,101.215,64,92,7,3,56,0,2365], + [99.341,100.278,56,88,6,1,56,0,2365], + [99.341,100.278,59,87,6,2,56,0,2365], + [99.341,101.215,56,94,7,1,56,0,2365], + [99.342,100.278,28,87,9,0,56,0,2365], + [99.455,99.575,75,90,0,0,56,0.25,2368], + [99.455,99.575,38,88,14,0,56,0.25,2368], + [99.456,99.575,56,69,4,0,56,0.25,2368], + [99.46,99.575,87,92,2,0,56,0.25,2368], + [99.572,99.692,38,93,14,0,56,0.5,2371], + [99.573,99.692,59,72,4,0,56,0.5,2371], + [99.575,99.692,76,91,0,0,56,0.5,2371], + [99.575,99.692,36,99,10,0,56,0.5,2371], + [99.576,99.692,88,91,2,0,56,0.5,2371], + [99.689,99.809,38,94,14,0,56,0.75,2374], + [99.693,99.809,87,91,2,0,56,0.75,2374], + [99.694,99.809,75,92,0,0,56,0.75,2374], + [99.695,99.809,64,74,4,0,56,0.75,2374], + [99.806,99.926,68,88,4,0,56,1,2376], + [99.807,99.926,38,96,14,0,56,1,2376], + [99.807,99.926,76,89,0,0,56,1,2376], + [99.807,99.926,88,92,2,0,56,1,2376], + [99.813,99.926,36,112,10,0,56,1,2377], + [99.925,100.043,71,69,4,0,56,1.25,2379], + [99.926,100.043,75,89,0,0,56,1.25,2379], + [99.927,100.043,87,92,2,0,56,1.25,2379], + [99.93,100.043,38,94,14,0,56,1.25,2379], + [100.041,100.161,88,89,2,0,56,1.5,2382], + [100.043,100.161,38,100,14,0,56,1.5,2382], + [100.045,100.161,76,91,0,0,56,1.5,2382], + [100.046,100.161,64,70,4,0,56,1.5,2382], + [100.047,100.161,36,98,10,0,56,1.5,2382], + [100.158,100.278,75,87,0,0,56,1.75,2385], + [100.158,100.278,38,102,14,0,56,1.75,2385], + [100.16,100.278,59,70,4,0,56,1.75,2385], + [100.161,100.278,87,93,2,0,56,1.75,2385], + [100.276,100.395,36,113,10,0,56,2,2388], + [100.276,100.395,52,92,4,0,56,2,2388], + [100.276,101.215,59,89,6,2,56,2,2388], + [100.277,100.395,88,89,2,0,56,2,2388], + [100.279,101.215,56,89,6,1,56,2,2388], + [100.279,100.395,76,87,0,0,56,2,2388], + [100.279,101.215,52,90,6,0,56,2,2388], + [100.279,101.215,28,91,9,0,56,2,2388], + [100.279,100.395,38,102,14,0,56,2,2388], + [100.393,100.512,56,72,4,0,56,2.25,2390], + [100.396,100.512,38,105,14,0,56,2.25,2390], + [100.396,100.512,87,92,2,0,56,2.25,2390], + [100.398,100.512,75,90,0,0,56,2.25,2390], + [100.508,100.629,59,68,4,0,56,2.5,2393], + [100.51,100.629,38,106,14,0,56,2.5,2393], + [100.511,100.629,36,104,10,0,56,2.5,2393], + [100.511,100.629,76,90,0,0,56,2.5,2393], + [100.516,100.629,88,90,2,0,56,2.5,2393], + [100.625,100.746,75,86,0,0,56,2.75,2396], + [100.627,100.746,64,71,4,0,56,2.75,2396], + [100.627,100.746,38,109,14,0,56,2.75,2396], + [100.628,100.746,87,89,2,0,56,2.75,2396], + [100.745,100.864,88,94,2,0,56,3,2399], + [100.746,100.864,76,91,0,0,56,3,2399], + [100.747,100.864,36,112,10,0,56,3,2399], + [100.747,100.864,68,88,4,0,56,3,2399], + [100.749,100.864,38,111,14,0,56,3,2399], + [100.863,100.981,87,94,2,0,56,3.25,2402], + [100.864,100.981,38,115,14,0,56,3.25,2402], + [100.864,100.981,75,87,0,0,56,3.25,2402], + [100.866,100.981,71,68,4,0,56,3.25,2402], + [100.979,101.098,76,86,0,0,56,3.5,2404], + [100.98,101.098,36,105,10,0,56,3.5,2404], + [100.981,101.098,88,87,2,0,56,3.5,2404], + [100.982,101.098,64,71,4,0,56,3.5,2404], + [100.983,101.098,38,115,14,0,56,3.5,2404], + [101.097,101.215,87,86,2,0,56,3.75,2407], + [101.097,101.215,75,90,0,0,56,3.75,2407], + [101.097,101.215,59,70,4,0,56,3.75,2407], + [101.1,101.215,38,120,14,0,56,3.75,2407], + [101.213,101.684,88,91,2,0,57,0,2410], + [101.215,101.684,76,88,0,0,57,0,2410], + [101.216,101.332,41,112,18,0,57,0,2410], + [103.088,103.207,76,92,0,0,58,0,2454], + [103.089,103.207,52,93,4,0,58,0,2454], + [103.089,104.028,56,89,6,1,58,0,2454], + [103.089,103.207,36,127,17,0,58,0,2454], + [103.09,103.325,52,100,5,0,58,0,2455], + [103.09,103.325,59,104,5,2,58,0,2455], + [103.09,103.207,36,111,10,0,58,0,2455], + [103.09,103.207,42,71,13,0,58,0,2455], + [103.09,104.028,28,93,9,0,58,0,2455], + [103.093,104.028,59,85,6,2,58,0,2455], + [103.093,103.207,49,119,16,0,58,0,2455], + [103.094,104.028,52,84,6,0,58,0,2455], + [103.094,103.207,88,105,2,0,58,0,2455], + [103.094,103.325,56,103,5,1,58,0,2455], + [103.203,103.325,56,76,4,0,58,0.25,2457], + [103.206,103.325,75,89,0,0,58,0.25,2457], + [103.206,103.325,40,101,8,0,58,0.25,2457], + [103.209,103.325,87,107,2,0,58,0.25,2457], + [103.209,103.325,42,39,13,0,58,0.25,2457], + [103.319,103.442,76,89,0,0,58,0.5,2460], + [103.322,103.442,88,105,2,0,58,0.5,2460], + [103.324,103.442,40,84,8,0,58,0.5,2460], + [103.324,103.442,46,88,15,0,58,0.5,2460], + [103.324,103.442,59,73,4,0,58,0.5,2460], + [103.438,103.559,75,87,0,0,58,0.75,2463], + [103.439,103.676,52,90,5,0,58,0.75,2463], + [103.44,103.559,42,44,13,0,58,0.75,2463], + [103.442,103.559,64,74,4,0,58,0.75,2463], + [103.442,103.559,87,107,2,0,58,0.75,2463], + [103.443,103.559,40,93,8,0,58,0.75,2463], + [103.445,103.676,56,89,5,1,58,0.75,2463], + [103.445,103.676,59,85,5,2,58,0.75,2463], + [103.557,103.676,42,65,13,0,58,1,2466], + [103.558,103.676,36,107,10,0,58,1,2466], + [103.558,103.676,88,108,2,0,58,1,2466], + [103.559,103.676,76,92,0,0,58,1,2466], + [103.562,103.676,68,94,4,0,58,1,2466], + [103.562,103.676,39,101,12,0,58,1,2466], + [103.675,103.793,83,105,2,0,58,1.25,2468], + [103.676,103.793,71,92,0,0,58,1.25,2468], + [103.676,103.793,40,98,8,0,58,1.25,2468], + [103.679,103.793,42,39,13,0,58,1.25,2469], + [103.68,103.793,71,77,4,0,58,1.25,2469], + [103.792,103.911,64,71,4,0,58,1.5,2471], + [103.792,103.911,40,84,8,0,58,1.5,2471], + [103.792,103.911,86,104,2,0,58,1.5,2471], + [103.794,103.911,74,90,0,0,58,1.5,2471], + [103.795,103.911,46,84,15,0,58,1.5,2471], + [103.795,104.028,52,93,5,0,58,1.5,2471], + [103.796,104.028,59,95,5,2,58,1.5,2471], + [103.797,104.028,56,96,5,1,58,1.5,2471], + [103.908,104.028,59,74,4,0,58,1.75,2474], + [103.909,104.028,40,92,8,0,58,1.75,2474], + [103.909,104.028,72,91,0,0,58,1.75,2474], + [103.911,104.028,42,48,13,0,58,1.75,2474], + [103.914,104.028,84,109,2,0,58,1.75,2474], + [104.023,104.965,57,86,6,0,58,2,2477], + [104.024,104.145,57,95,4,0,58,2,2477], + [104.025,104.379,69,87,0,0,58,2,2477], + [104.025,104.145,42,68,13,0,58,2,2477], + [104.026,104.262,64,103,5,2,58,2,2477], + [104.027,104.965,60,90,6,1,58,2,2477], + [104.027,104.965,33,88,9,0,58,2,2477], + [104.028,104.379,81,105,2,0,58,2,2477], + [104.028,104.965,64,83,6,2,58,2,2477], + [104.029,104.262,57,102,5,0,58,2,2477], + [104.029,104.262,60,104,5,1,58,2,2477], + [104.03,104.145,36,110,10,0,58,2,2477], + [104.142,104.262,60,75,4,0,58,2.25,2480], + [104.142,104.262,45,99,8,0,58,2.25,2480], + [104.143,104.262,42,37,13,0,58,2.25,2480], + [104.261,104.379,64,73,4,0,58,2.5,2482], + [104.262,104.379,45,84,8,0,58,2.5,2482], + [104.263,104.379,46,90,15,0,58,2.5,2482], + [104.378,104.496,69,77,4,0,58,2.75,2485], + [104.378,104.614,64,90,5,2,58,2.75,2485], + [104.378,104.614,60,87,5,1,58,2.75,2485], + [104.379,104.496,60,88,0,0,58,2.75,2485], + [104.381,104.496,72,104,2,0,58,2.75,2485], + [104.381,104.496,42,50,13,0,58,2.75,2485], + [104.382,104.496,45,93,8,0,58,2.75,2485], + [104.382,104.614,57,88,5,0,58,2.75,2485], + [104.494,104.614,39,101,12,0,58,3,2488], + [104.495,104.614,64,88,0,0,58,3,2488], + [104.496,104.614,76,106,2,0,58,3,2488], + [104.497,104.614,72,93,4,0,58,3,2488], + [104.498,104.614,42,68,13,0,58,3,2488], + [104.5,104.614,36,111,10,0,58,3,2488], + [104.612,104.731,45,96,8,0,58,3.25,2491], + [104.613,104.965,81,107,2,0,58,3.25,2491], + [104.615,104.731,76,73,4,0,58,3.25,2491], + [104.615,104.731,42,41,13,0,58,3.25,2491], + [104.616,104.965,69,92,0,0,58,3.25,2491], + [104.727,104.965,57,95,5,0,58,3.5,2493], + [104.729,104.848,45,90,8,0,58,3.5,2494], + [104.729,104.965,60,96,5,1,58,3.5,2494], + [104.731,104.848,69,73,4,0,58,3.5,2494], + [104.731,104.848,46,84,15,0,58,3.5,2494], + [104.732,104.965,64,99,5,2,58,3.5,2494], + [104.844,104.965,45,91,8,0,58,3.75,2496], + [104.847,104.965,42,53,13,0,58,3.75,2496], + [104.849,104.965,64,73,4,0,58,3.75,2496], + [104.962,105.2,56,103,5,1,59,0,2499], + [104.962,105.903,59,86,6,2,59,0,2499], + [104.963,105.903,52,84,6,0,59,0,2499], + [104.964,105.903,28,95,9,0,59,0,2499], + [104.964,105.903,56,86,6,1,59,0,2499], + [104.964,105.082,52,97,4,0,59,0,2499], + [104.964,105.317,83,107,2,0,59,0,2499], + [104.965,105.082,36,112,10,0,59,0,2499], + [104.965,105.2,59,106,5,2,59,0,2499], + [104.966,105.2,52,100,5,0,59,0,2499], + [104.966,105.317,71,91,0,0,59,0,2499], + [104.966,105.082,42,67,13,0,59,0,2499], + [105.081,105.2,56,71,4,0,59,0.25,2502], + [105.082,105.2,40,100,8,0,59,0.25,2502], + [105.083,105.2,42,42,13,0,59,0.25,2502], + [105.198,105.317,59,78,4,0,59,0.5,2505], + [105.2,105.317,40,84,8,0,59,0.5,2505], + [105.2,105.317,46,91,15,0,59,0.5,2505], + [105.313,105.434,64,75,4,0,59,0.75,2507], + [105.314,105.434,42,47,13,0,59,0.75,2507], + [105.314,105.551,52,89,5,0,59,0.75,2507], + [105.317,105.434,76,107,2,0,59,0.75,2508], + [105.317,105.434,40,89,8,0,59,0.75,2508], + [105.317,105.434,64,92,0,0,59,0.75,2508], + [105.318,105.551,59,89,5,2,59,0.75,2508], + [105.32,105.551,56,86,5,1,59,0.75,2508], + [105.431,105.551,39,100,12,0,59,1,2510], + [105.432,105.551,80,103,2,0,59,1,2510], + [105.432,105.551,68,92,4,0,59,1,2510], + [105.436,105.551,36,110,10,0,59,1,2510], + [105.436,105.551,68,89,0,0,59,1,2510], + [105.437,105.551,42,65,13,0,59,1,2510], + [105.549,105.668,40,97,8,0,59,1.25,2513], + [105.549,105.668,42,42,13,0,59,1.25,2513], + [105.551,105.903,83,108,2,0,59,1.25,2513], + [105.552,105.668,71,74,4,0,59,1.25,2513], + [105.554,105.903,71,86,0,0,59,1.25,2513], + [105.663,105.903,59,94,5,2,59,1.5,2516], + [105.666,105.786,46,81,15,0,59,1.5,2516], + [105.667,105.786,64,76,4,0,59,1.5,2516], + [105.668,105.786,40,84,8,0,59,1.5,2516], + [105.671,105.903,56,97,5,1,59,1.5,2516], + [105.672,105.903,52,96,5,0,59,1.5,2516], + [105.782,105.903,40,93,8,0,59,1.75,2519], + [105.784,105.903,59,75,4,0,59,1.75,2519], + [105.788,105.903,42,45,13,0,59,1.75,2519], + [105.9,106.84,33,90,9,0,59,2,2521], + [105.901,106.84,57,86,6,0,59,2,2521], + [105.901,106.84,60,85,6,1,59,2,2521], + [105.903,106.137,60,107,5,1,59,2,2521], + [105.903,106.137,57,103,5,0,59,2,2521], + [105.903,106.254,72,89,0,0,59,2,2521], + [105.903,106.254,84,105,2,0,59,2,2522], + [105.904,106.137,64,107,5,2,59,2,2522], + [105.904,106.02,36,112,10,0,59,2,2522], + [105.905,106.02,42,70,13,0,59,2,2522], + [105.905,106.02,57,93,4,0,59,2,2522], + [105.906,106.84,64,88,6,2,59,2,2522], + [106.016,106.137,45,101,8,0,59,2.25,2524], + [106.016,106.137,60,73,4,0,59,2.25,2524], + [106.019,106.137,42,44,13,0,59,2.25,2524], + [106.134,106.254,45,84,8,0,59,2.5,2527], + [106.138,106.254,64,73,4,0,59,2.5,2527], + [106.138,106.254,46,84,15,0,59,2.5,2527], + [106.25,106.371,76,108,2,0,59,2.75,2530], + [106.251,106.489,60,90,5,1,59,2.75,2530], + [106.253,106.371,45,94,8,0,59,2.75,2530], + [106.254,106.371,42,48,13,0,59,2.75,2530], + [106.254,106.371,69,73,4,0,59,2.75,2530], + [106.256,106.371,64,94,0,0,59,2.75,2530], + [106.256,106.489,64,90,5,2,59,2.75,2530], + [106.256,106.489,57,87,5,0,59,2.75,2530], + [106.367,106.84,88,105,2,0,59,3,2533], + [106.37,106.489,36,110,10,0,59,3,2533], + [106.37,106.489,42,63,13,0,59,3,2533], + [106.371,106.84,76,90,0,0,59,3,2533], + [106.371,106.489,39,102,12,0,59,3,2533], + [106.371,106.489,72,95,4,0,59,3,2533], + [106.486,106.606,76,76,4,0,59,3.25,2535], + [106.488,106.606,45,101,8,0,59,3.25,2535], + [106.489,106.606,42,37,13,0,59,3.25,2535], + [106.604,106.723,69,77,4,0,59,3.5,2538], + [106.605,106.723,45,86,8,0,59,3.5,2538], + [106.605,106.84,57,95,5,0,59,3.5,2538], + [106.607,106.84,64,97,5,2,59,3.5,2538], + [106.607,106.723,46,86,15,0,59,3.5,2538], + [106.609,106.84,60,93,5,1,59,3.5,2538], + [106.719,106.84,42,54,13,0,59,3.75,2541], + [106.723,106.84,64,73,4,0,59,3.75,2541], + [106.726,106.84,45,95,8,0,59,3.75,2541], + [106.837,106.957,88,104,2,0,60,0,2544], + [106.838,106.957,52,95,4,0,60,0,2544], + [106.839,106.957,76,90,0,0,60,0,2544], + [106.84,107.778,56,90,6,1,60,0,2544], + [106.84,106.957,36,111,10,0,60,0,2544], + [106.841,107.778,52,87,6,0,60,0,2544], + [106.841,107.075,59,106,5,2,60,0,2544], + [106.841,107.778,59,87,6,2,60,0,2544], + [106.842,107.075,52,105,5,0,60,0,2544], + [106.842,107.778,28,91,9,0,60,0,2544], + [106.843,107.075,56,105,5,1,60,0,2544], + [106.843,106.957,42,71,13,0,60,0,2544], + [106.955,107.075,56,71,4,0,60,0.25,2547], + [106.956,107.075,75,87,0,0,60,0.25,2547], + [106.957,107.075,42,44,13,0,60,0.25,2547], + [106.959,107.075,87,105,2,0,60,0.25,2547], + [106.959,107.075,40,102,8,0,60,0.25,2547], + [107.071,107.192,40,84,8,0,60,0.5,2549], + [107.073,107.192,46,86,15,0,60,0.5,2549], + [107.073,107.192,76,92,0,0,60,0.5,2549], + [107.074,107.192,88,108,2,0,60,0.5,2549], + [107.075,107.192,59,77,4,0,60,0.5,2549], + [107.188,107.426,59,88,5,2,60,0.75,2552], + [107.19,107.309,42,43,13,0,60,0.75,2552], + [107.191,107.309,87,107,2,0,60,0.75,2552], + [107.191,107.309,40,92,8,0,60,0.75,2552], + [107.192,107.426,52,88,5,0,60,0.75,2552], + [107.193,107.309,75,90,0,0,60,0.75,2552], + [107.194,107.426,56,89,5,1,60,0.75,2552], + [107.195,107.309,64,77,4,0,60,0.75,2552], + [107.306,107.426,42,65,13,0,60,1,2555], + [107.306,107.426,36,107,10,0,60,1,2555], + [107.308,107.426,39,100,12,0,60,1,2555], + [107.308,107.426,68,92,4,0,60,1,2555], + [107.31,107.426,76,91,0,0,60,1,2555], + [107.312,107.426,88,106,2,0,60,1,2555], + [107.425,107.543,42,37,13,0,60,1.25,2558], + [107.425,107.543,71,91,0,0,60,1.25,2558], + [107.427,107.543,40,102,8,0,60,1.25,2558], + [107.428,107.543,71,76,4,0,60,1.25,2558], + [107.429,107.543,83,103,2,0,60,1.25,2558], + [107.539,107.661,40,85,8,0,60,1.5,2560], + [107.541,107.778,56,96,5,1,60,1.5,2561], + [107.542,107.661,86,107,2,0,60,1.5,2561], + [107.542,107.778,52,93,5,0,60,1.5,2561], + [107.543,107.661,64,75,4,0,60,1.5,2561], + [107.543,107.661,74,88,0,0,60,1.5,2561], + [107.544,107.778,59,93,5,2,60,1.5,2561], + [107.547,107.661,46,82,15,0,60,1.5,2561], + [107.659,107.778,59,77,4,0,60,1.75,2563], + [107.659,107.778,42,45,13,0,60,1.75,2563], + [107.66,107.778,84,109,2,0,60,1.75,2563], + [107.66,107.778,72,90,0,0,60,1.75,2563], + [107.665,107.778,40,92,8,0,60,1.75,2563], + [107.773,108.715,57,84,6,0,60,2,2566], + [107.775,108.715,33,91,9,0,60,2,2566], + [107.775,107.895,36,113,10,0,60,2,2566], + [107.776,108.129,81,107,2,0,60,2,2566], + [107.776,108.715,60,85,6,1,60,2,2566], + [107.776,108.129,69,90,0,0,60,2,2566], + [107.776,108.012,57,106,5,0,60,2,2566], + [107.777,107.895,57,97,4,0,60,2,2566], + [107.777,108.715,64,89,6,2,60,2,2566], + [107.781,107.895,42,71,13,0,60,2,2566], + [107.781,108.012,64,101,5,2,60,2,2566], + [107.781,108.012,60,102,5,1,60,2,2566], + [107.892,108.012,60,72,4,0,60,2.25,2569], + [107.896,108.012,42,39,13,0,60,2.25,2569], + [107.897,108.012,45,100,8,0,60,2.25,2569], + [108.009,108.129,46,86,15,0,60,2.5,2572], + [108.011,108.129,64,74,4,0,60,2.5,2572], + [108.013,108.129,45,84,8,0,60,2.5,2572], + [108.127,108.246,60,89,0,0,60,2.75,2574], + [108.128,108.364,57,89,5,0,60,2.75,2574], + [108.129,108.246,45,91,8,0,60,2.75,2575], + [108.13,108.364,64,84,5,2,60,2.75,2575], + [108.131,108.246,72,104,2,0,60,2.75,2575], + [108.131,108.246,42,47,13,0,60,2.75,2575], + [108.131,108.246,69,76,4,0,60,2.75,2575], + [108.131,108.364,60,90,5,1,60,2.75,2575], + [108.244,108.364,72,97,4,0,60,3,2577], + [108.245,108.364,42,61,13,0,60,3,2577], + [108.247,108.364,76,107,2,0,60,3,2577], + [108.247,108.364,39,104,12,0,60,3,2577], + [108.249,108.364,64,88,0,0,60,3,2577], + [108.249,108.364,36,106,10,0,60,3,2577], + [108.36,108.715,81,106,2,0,60,3.25,2580], + [108.361,108.481,42,42,13,0,60,3.25,2580], + [108.362,108.715,69,91,0,0,60,3.25,2580], + [108.365,108.481,76,78,4,0,60,3.25,2580], + [108.368,108.481,45,100,8,0,60,3.25,2580], + [108.477,108.598,46,84,15,0,60,3.5,2583], + [108.479,108.715,57,95,5,0,60,3.5,2583], + [108.481,108.715,60,97,5,1,60,3.5,2583], + [108.482,108.598,69,76,4,0,60,3.5,2583], + [108.482,108.715,64,100,5,2,60,3.5,2583], + [108.483,108.598,45,87,8,0,60,3.5,2583], + [108.595,108.715,42,51,13,0,60,3.75,2586], + [108.597,108.715,45,91,8,0,60,3.75,2586], + [108.6,108.715,64,76,4,0,60,3.75,2586], + [108.711,108.832,36,110,10,0,61,0,2588], + [108.711,108.95,52,104,5,0,61,0,2588], + [108.713,108.832,42,73,13,0,61,0,2588], + [108.714,109.067,83,107,2,0,61,0,2588], + [108.715,108.95,56,104,5,1,61,0,2588], + [108.715,109.653,52,84,6,0,61,0,2588], + [108.715,109.653,59,87,6,2,61,0,2588], + [108.716,109.653,28,93,9,0,61,0,2588], + [108.717,109.653,56,86,6,1,61,0,2589], + [108.718,108.95,59,106,5,2,61,0,2589], + [108.718,109.067,71,94,0,0,61,0,2589], + [108.72,108.832,52,97,4,0,61,0,2589], + [108.834,108.95,40,101,8,0,61,0.25,2591], + [108.834,108.95,42,43,13,0,61,0.25,2591], + [108.834,108.95,56,72,4,0,61,0.25,2591], + [108.948,109.067,46,90,15,0,61,0.5,2594], + [108.951,109.067,40,86,8,0,61,0.5,2594], + [108.951,109.067,59,71,4,0,61,0.5,2594], + [109.062,109.184,64,91,0,0,61,0.75,2597], + [109.062,109.184,42,49,13,0,61,0.75,2597], + [109.064,109.184,76,107,2,0,61,0.75,2597], + [109.065,109.184,40,92,8,0,61,0.75,2597], + [109.067,109.184,64,71,4,0,61,0.75,2597], + [109.068,109.301,56,87,5,1,61,0.75,2597], + [109.069,109.301,52,88,5,0,61,0.75,2597], + [109.07,109.301,59,88,5,2,61,0.75,2597], + [109.18,109.301,36,108,10,0,61,1,2600], + [109.182,109.301,42,61,13,0,61,1,2600], + [109.182,109.301,68,89,4,0,61,1,2600], + [109.183,109.301,72,89,0,0,61,1,2600], + [109.184,109.301,84,104,2,0,61,1,2600], + [109.184,109.301,39,97,12,0,61,1,2600], + [109.298,109.418,40,102,8,0,61,1.25,2602], + [109.301,109.418,71,75,4,0,61,1.25,2602], + [109.301,109.653,71,92,0,0,61,1.25,2602], + [109.302,109.418,42,43,13,0,61,1.25,2602], + [109.303,109.653,83,109,2,0,61,1.25,2602], + [109.418,109.536,40,84,8,0,61,1.5,2605], + [109.419,109.653,52,94,5,0,61,1.5,2605], + [109.419,109.536,64,72,4,0,61,1.5,2605], + [109.42,109.653,56,98,5,1,61,1.5,2605], + [109.421,109.536,46,82,15,0,61,1.5,2605], + [109.422,109.653,59,96,5,2,61,1.5,2605], + [109.537,109.653,40,91,8,0,61,1.75,2608], + [109.537,109.653,42,46,13,0,61,1.75,2608], + [109.538,109.653,59,75,4,0,61,1.75,2608], + [109.649,110.59,57,87,6,0,61,2,2611], + [109.65,109.887,57,104,5,0,61,2,2611], + [109.65,109.887,60,106,5,1,61,2,2611], + [109.651,109.77,42,69,13,0,61,2,2611], + [109.651,110.59,64,87,6,2,61,2,2611], + [109.652,110.59,60,86,6,1,61,2,2611], + [109.652,110.59,33,91,9,0,61,2,2611], + [109.653,110.59,81,105,2,0,61,2,2611], + [109.654,109.77,57,96,4,0,61,2,2611], + [109.654,109.887,64,103,5,2,61,2,2611], + [109.656,109.77,36,110,10,0,61,2,2611], + [109.656,110.59,69,90,0,0,61,2,2611], + [109.767,109.887,42,41,13,0,61,2.25,2613], + [109.768,109.887,45,100,8,0,61,2.25,2614], + [109.77,109.887,60,78,4,0,61,2.25,2614], + [109.885,110.004,46,87,15,0,61,2.5,2616], + [109.886,110.004,64,76,4,0,61,2.5,2616], + [109.887,110.004,45,88,8,0,61,2.5,2616], + [110.002,110.239,60,88,5,1,61,2.75,2619], + [110.003,110.239,57,85,5,0,61,2.75,2619], + [110.003,110.239,64,88,5,2,61,2.75,2619], + [110.005,110.121,45,91,8,0,61,2.75,2619], + [110.006,110.121,42,48,13,0,61,2.75,2619], + [110.006,110.121,69,75,4,0,61,2.75,2619], + [110.12,110.239,39,101,12,0,61,3,2622], + [110.121,110.239,42,65,13,0,61,3,2622], + [110.121,110.239,72,91,4,0,61,3,2622], + [110.125,110.239,36,109,10,0,61,3,2622], + [110.234,110.356,45,100,8,0,61,3.25,2625], + [110.237,110.356,42,42,13,0,61,3.25,2625], + [110.239,110.356,76,75,4,0,61,3.25,2625], + [110.352,110.473,46,84,15,0,61,3.5,2627], + [110.354,110.473,69,74,4,0,61,3.5,2627], + [110.357,110.59,60,98,5,1,61,3.5,2628], + [110.357,110.473,45,84,8,0,61,3.5,2628], + [110.357,110.59,57,95,5,0,61,3.5,2628], + [110.358,110.59,64,92,5,2,61,3.5,2628], + [110.472,110.59,64,74,4,0,61,3.75,2630], + [110.472,110.59,42,53,13,0,61,3.75,2630], + [110.474,110.59,45,90,8,0,61,3.75,2630], + [110.586,110.825,52,104,5,0,62,0,2633], + [110.588,110.825,56,104,5,1,62,0,2633], + [110.588,110.707,36,113,10,0,62,0,2633], + [110.59,110.707,52,90,4,0,62,0,2633], + [110.59,110.707,42,67,13,0,62,0,2633], + [110.591,111.528,52,84,6,0,62,0,2633], + [110.591,110.825,59,103,5,2,62,0,2633], + [110.591,110.707,88,104,2,0,62,0,2633], + [110.591,110.707,76,89,0,0,62,0,2633], + [110.591,111.528,59,88,6,2,62,0,2633], + [110.592,111.528,56,86,6,1,62,0,2633], + [110.594,111.528,28,92,9,0,62,0,2633], + [110.704,110.825,87,103,2,0,62,0.25,2636], + [110.705,110.825,75,90,0,0,62,0.25,2636], + [110.706,110.825,42,39,13,0,62,0.25,2636], + [110.709,110.825,56,74,4,0,62,0.25,2636], + [110.711,110.825,40,99,8,0,62,0.25,2636], + [110.825,110.942,40,86,8,0,62,0.5,2639], + [110.825,110.942,76,92,0,0,62,0.5,2639], + [110.826,110.942,59,74,4,0,62,0.5,2639], + [110.826,110.942,46,89,15,0,62,0.5,2639], + [110.827,110.942,88,106,2,0,62,0.5,2639], + [110.94,111.176,56,90,5,1,62,0.75,2641], + [110.941,111.059,64,72,4,0,62,0.75,2641], + [110.941,111.059,40,94,8,0,62,0.75,2641], + [110.942,111.059,87,104,2,0,62,0.75,2641], + [110.942,111.176,52,90,5,0,62,0.75,2641], + [110.944,111.176,59,88,5,2,62,0.75,2642], + [110.945,111.059,42,47,13,0,62,0.75,2642], + [110.946,111.059,75,90,0,0,62,0.75,2642], + [111.056,111.176,88,102,2,0,62,1,2644], + [111.056,111.176,76,89,0,0,62,1,2644], + [111.059,111.176,42,61,13,0,62,1,2644], + [111.059,111.176,68,98,4,0,62,1,2644], + [111.06,111.176,39,99,12,0,62,1,2644], + [111.06,111.176,36,107,10,0,62,1,2644], + [111.173,111.293,71,92,0,0,62,1.25,2647], + [111.174,111.293,40,103,8,0,62,1.25,2647], + [111.175,111.293,42,40,13,0,62,1.25,2647], + [111.175,111.293,71,75,4,0,62,1.25,2647], + [111.179,111.293,83,106,2,0,62,1.25,2647], + [111.29,111.411,64,73,4,0,62,1.5,2650], + [111.291,111.528,52,94,5,0,62,1.5,2650], + [111.291,111.411,74,93,0,0,62,1.5,2650], + [111.292,111.528,56,100,5,1,62,1.5,2650], + [111.293,111.528,59,93,5,2,62,1.5,2650], + [111.294,111.411,46,83,15,0,62,1.5,2650], + [111.295,111.411,86,104,2,0,62,1.5,2650], + [111.295,111.411,40,88,8,0,62,1.5,2650], + [111.408,111.528,40,94,8,0,62,1.75,2653], + [111.409,111.528,84,106,2,0,62,1.75,2653], + [111.409,111.528,59,74,4,0,62,1.75,2653], + [111.41,111.528,72,90,0,0,62,1.75,2653], + [111.413,111.528,42,48,13,0,62,1.75,2653], + [111.525,111.645,36,111,10,0,62,2,2655], + [111.526,111.762,64,103,5,2,62,2,2655], + [111.527,111.762,60,102,5,1,62,2,2655], + [111.527,111.762,57,102,5,0,62,2,2655], + [111.528,112.465,60,86,6,1,62,2,2655], + [111.528,111.645,42,70,13,0,62,2,2655], + [111.528,112.465,57,85,6,0,62,2,2655], + [111.529,111.879,69,87,0,0,62,2,2655], + [111.529,111.879,81,107,2,0,62,2,2655], + [111.53,112.465,64,86,6,2,62,2,2655], + [111.532,111.645,57,96,4,0,62,2,2656], + [111.532,112.465,33,90,9,0,62,2,2656], + [111.644,111.762,42,40,13,0,62,2.25,2658], + [111.644,111.762,45,97,8,0,62,2.25,2658], + [111.645,111.762,60,77,4,0,62,2.25,2658], + [111.761,111.879,46,88,15,0,62,2.5,2661], + [111.761,111.879,45,87,8,0,62,2.5,2661], + [111.762,111.879,64,72,4,0,62,2.5,2661], + [111.877,112.114,60,87,5,1,62,2.75,2664], + [111.877,111.996,45,88,8,0,62,2.75,2664], + [111.878,112.114,57,86,5,0,62,2.75,2664], + [111.879,111.996,42,44,13,0,62,2.75,2664], + [111.881,111.996,72,104,2,0,62,2.75,2664], + [111.881,111.996,60,91,0,0,62,2.75,2664], + [111.881,112.114,64,88,5,2,62,2.75,2664], + [111.882,111.996,69,74,4,0,62,2.75,2664], + [111.995,112.114,76,107,2,0,62,3,2667], + [111.996,112.114,39,102,12,0,62,3,2667], + [111.997,112.114,72,94,4,0,62,3,2667], + [111.998,112.114,64,92,0,0,62,3,2667], + [111.998,112.114,42,60,13,0,62,3,2667], + [111.999,112.114,36,106,10,0,62,3,2667], + [112.111,112.465,81,104,2,0,62,3.25,2669], + [112.112,112.231,76,73,4,0,62,3.25,2669], + [112.115,112.231,42,37,13,0,62,3.25,2669], + [112.116,112.231,45,98,8,0,62,3.25,2669], + [112.117,112.465,69,91,0,0,62,3.25,2669], + [112.228,112.465,60,96,5,1,62,3.5,2672], + [112.229,112.348,46,81,15,0,62,3.5,2672], + [112.23,112.348,45,84,8,0,62,3.5,2672], + [112.23,112.465,57,100,5,0,62,3.5,2672], + [112.231,112.348,69,72,4,0,62,3.5,2672], + [112.232,112.465,64,93,5,2,62,3.5,2672], + [112.346,112.465,64,76,4,0,62,3.75,2675], + [112.347,112.465,42,51,13,0,62,3.75,2675], + [112.349,112.465,45,96,8,0,62,3.75,2675], + [112.462,112.582,42,74,13,0,63,0,2678], + [112.463,113.403,52,88,6,0,63,0,2678], + [112.464,112.7,52,105,5,0,63,0,2678], + [112.465,112.582,52,93,4,0,63,0,2678], + [112.465,113.403,59,89,6,2,63,0,2678], + [112.466,112.582,36,111,10,0,63,0,2678], + [112.466,113.403,28,87,9,0,63,0,2678], + [112.467,112.7,59,108,5,2,63,0,2678], + [112.467,112.817,71,89,0,0,63,0,2678], + [112.467,112.7,56,106,5,1,63,0,2678], + [112.468,112.817,83,108,2,0,63,0,2678], + [112.468,113.403,56,88,6,1,63,0,2678], + [112.58,112.7,56,76,4,0,63,0.25,2680], + [112.58,112.7,42,41,13,0,63,0.25,2680], + [112.582,112.7,40,98,8,0,63,0.25,2681], + [112.698,112.817,59,76,4,0,63,0.5,2683], + [112.699,112.817,46,85,15,0,63,0.5,2683], + [112.699,112.817,40,87,8,0,63,0.5,2683], + [112.813,112.934,64,74,4,0,63,0.75,2686], + [112.814,112.934,42,50,13,0,63,0.75,2686], + [112.814,113.051,59,88,5,2,63,0.75,2686], + [112.816,112.934,40,94,8,0,63,0.75,2686], + [112.816,113.051,52,88,5,0,63,0.75,2686], + [112.817,113.051,56,90,5,1,63,0.75,2686], + [112.821,112.934,64,90,0,0,63,0.75,2686], + [112.822,112.934,76,107,2,0,63,0.75,2686], + [112.931,113.051,68,97,4,0,63,1,2689], + [112.931,113.051,80,103,2,0,63,1,2689], + [112.932,113.051,68,88,0,0,63,1,2689], + [112.933,113.051,42,60,13,0,63,1,2689], + [112.933,113.051,39,102,12,0,63,1,2689], + [112.937,113.051,36,107,10,0,63,1,2689], + [113.049,113.168,40,96,8,0,63,1.25,2692], + [113.053,113.168,71,73,4,0,63,1.25,2692], + [113.053,113.168,42,44,13,0,63,1.25,2692], + [113.054,113.403,71,87,0,0,63,1.25,2692], + [113.055,113.403,83,108,2,0,63,1.25,2692], + [113.164,113.286,64,77,4,0,63,1.5,2694], + [113.166,113.403,56,96,5,1,63,1.5,2694], + [113.167,113.286,46,82,15,0,63,1.5,2694], + [113.168,113.403,59,98,5,2,63,1.5,2694], + [113.169,113.403,52,96,5,0,63,1.5,2694], + [113.17,113.286,40,84,8,0,63,1.5,2695], + [113.284,113.403,59,73,4,0,63,1.75,2697], + [113.284,113.403,42,47,13,0,63,1.75,2697], + [113.286,113.403,40,94,8,0,63,1.75,2697], + [113.398,113.52,36,115,10,0,63,2,2700], + [113.401,113.637,57,104,5,0,63,2,2700], + [113.401,113.52,57,91,4,0,63,2,2700], + [113.401,113.637,64,101,5,2,63,2,2700], + [113.402,114.34,60,86,6,1,63,2,2700], + [113.402,114.34,57,86,6,0,63,2,2700], + [113.403,113.637,60,105,5,1,63,2,2700], + [113.404,113.754,84,107,2,0,63,2,2700], + [113.404,113.754,72,89,0,0,63,2,2700], + [113.404,113.52,42,66,13,0,63,2,2700], + [113.405,114.34,64,87,6,2,63,2,2700], + [113.406,114.34,33,92,9,0,63,2,2700], + [113.519,113.637,45,101,8,0,63,2.25,2703], + [113.52,113.637,42,42,13,0,63,2.25,2703], + [113.523,113.637,60,72,4,0,63,2.25,2703], + [113.635,113.754,64,72,4,0,63,2.5,2706], + [113.635,113.754,46,89,15,0,63,2.5,2706], + [113.636,113.754,45,83,8,0,63,2.5,2706], + [113.753,113.989,60,91,5,1,63,2.75,2708], + [113.754,113.871,45,92,8,0,63,2.75,2708], + [113.754,113.871,76,103,2,0,63,2.75,2708], + [113.754,113.871,42,52,13,0,63,2.75,2708], + [113.755,113.989,64,88,5,2,63,2.75,2708], + [113.755,113.989,57,91,5,0,63,2.75,2708], + [113.756,113.871,64,91,0,0,63,2.75,2708], + [113.756,113.871,69,74,4,0,63,2.75,2708], + [113.868,113.989,36,106,10,0,63,3,2711], + [113.87,114.34,76,92,0,0,63,3,2711], + [113.87,113.989,42,64,13,0,63,3,2711], + [113.872,113.989,72,97,4,0,63,3,2711], + [113.872,113.989,39,103,12,0,63,3,2711], + [113.873,114.34,88,107,2,0,63,3,2711], + [113.988,114.106,76,75,4,0,63,3.25,2714], + [113.99,114.106,42,43,13,0,63,3.25,2714], + [113.99,114.106,45,101,8,0,63,3.25,2714], + [114.103,114.34,64,97,5,2,63,3.5,2717], + [114.105,114.223,46,81,15,0,63,3.5,2717], + [114.107,114.34,60,95,5,1,63,3.5,2717], + [114.108,114.223,69,78,4,0,63,3.5,2717], + [114.108,114.34,57,96,5,0,63,3.5,2717], + [114.109,114.223,45,87,8,0,63,3.5,2717], + [114.22,114.34,42,52,13,0,63,3.75,2720], + [114.222,114.34,45,96,8,0,63,3.75,2720], + [114.222,114.34,64,75,4,0,63,3.75,2720], + [114.337,115.278,52,86,6,0,64,0,2722], + [114.337,114.575,56,104,5,1,64,0,2722], + [114.337,114.457,36,112,10,0,64,0,2722], + [114.338,114.457,42,68,13,0,64,0,2722], + [114.338,114.457,88,106,2,0,64,0,2722], + [114.339,114.575,52,105,5,0,64,0,2722], + [114.34,115.278,59,84,6,2,64,0,2722], + [114.34,115.278,28,89,9,0,64,0,2722], + [114.341,115.278,56,83,6,1,64,0,2722], + [114.342,114.457,52,92,4,0,64,0,2722], + [114.343,114.575,59,103,5,2,64,0,2722], + [114.344,114.457,76,93,0,0,64,0,2722], + [114.456,114.575,42,40,13,0,64,0.25,2725], + [114.456,114.575,87,105,2,0,64,0.25,2725], + [114.457,114.575,75,87,0,0,64,0.25,2725], + [114.457,114.575,40,102,8,0,64,0.25,2725], + [114.461,114.575,56,79,4,0,64,0.25,2725], + [114.571,114.692,59,73,4,0,64,0.5,2728], + [114.573,114.692,40,87,8,0,64,0.5,2728], + [114.574,114.692,46,88,15,0,64,0.5,2728], + [114.575,114.692,88,106,2,0,64,0.5,2728], + [114.576,114.692,76,92,0,0,64,0.5,2728], + [114.69,114.926,52,90,5,0,64,0.75,2731], + [114.691,114.809,40,95,8,0,64,0.75,2731], + [114.692,114.926,56,87,5,1,64,0.75,2731], + [114.693,114.809,42,46,13,0,64,0.75,2731], + [114.693,114.809,64,74,4,0,64,0.75,2731], + [114.694,114.926,59,86,5,2,64,0.75,2731], + [114.694,114.809,87,107,2,0,64,0.75,2731], + [114.695,114.809,75,89,0,0,64,0.75,2731], + [114.808,114.926,39,100,12,0,64,1,2734], + [114.808,114.926,68,94,4,0,64,1,2734], + [114.809,114.926,88,102,2,0,64,1,2734], + [114.81,114.926,76,94,0,0,64,1,2734], + [114.81,114.926,36,109,10,0,64,1,2734], + [114.811,114.926,42,63,13,0,64,1,2734], + [114.923,115.043,40,100,8,0,64,1.25,2736], + [114.925,115.043,71,92,0,0,64,1.25,2736], + [114.926,115.043,71,78,4,0,64,1.25,2736], + [114.927,115.043,42,42,13,0,64,1.25,2736], + [114.928,115.043,83,106,2,0,64,1.25,2736], + [115.041,115.278,52,94,5,0,64,1.5,2739], + [115.042,115.161,74,92,0,0,64,1.5,2739], + [115.042,115.161,40,85,8,0,64,1.5,2739], + [115.042,115.161,64,73,4,0,64,1.5,2739], + [115.042,115.161,46,83,15,0,64,1.5,2739], + [115.044,115.278,59,97,5,2,64,1.5,2739], + [115.045,115.161,86,106,2,0,64,1.5,2739], + [115.047,115.278,56,95,5,1,64,1.5,2739], + [115.16,115.278,59,75,4,0,64,1.75,2742], + [115.16,115.278,42,46,13,0,64,1.75,2742], + [115.162,115.278,84,105,2,0,64,1.75,2742], + [115.162,115.278,72,92,0,0,64,1.75,2742], + [115.163,115.278,40,93,8,0,64,1.75,2742], + [115.275,116.215,57,84,6,0,64,2,2745], + [115.276,115.395,36,111,10,0,64,2,2745], + [115.276,115.629,81,102,2,0,64,2,2745], + [115.276,115.512,60,106,5,1,64,2,2745], + [115.276,115.395,57,89,4,0,64,2,2745], + [115.277,116.215,33,91,9,0,64,2,2745], + [115.277,115.629,69,91,0,0,64,2,2745], + [115.277,115.512,64,104,5,2,64,2,2745], + [115.279,116.215,60,84,6,1,64,2,2745], + [115.279,115.395,42,67,13,0,64,2,2745], + [115.279,115.512,57,105,5,0,64,2,2745], + [115.281,116.215,64,85,6,2,64,2,2745], + [115.393,115.512,42,39,13,0,64,2.25,2747], + [115.393,115.512,60,73,4,0,64,2.25,2747], + [115.394,115.512,45,98,8,0,64,2.25,2747], + [115.511,115.629,46,92,15,0,64,2.5,2750], + [115.513,115.629,64,73,4,0,64,2.5,2750], + [115.514,115.629,45,86,8,0,64,2.5,2750], + [115.626,115.864,64,86,5,2,64,2.75,2753], + [115.626,115.864,60,90,5,1,64,2.75,2753], + [115.627,115.746,42,51,13,0,64,2.75,2753], + [115.627,115.864,57,90,5,0,64,2.75,2753], + [115.627,115.746,60,93,0,0,64,2.75,2753], + [115.628,115.746,69,72,4,0,64,2.75,2753], + [115.629,115.746,72,109,2,0,64,2.75,2753], + [115.631,115.746,45,93,8,0,64,2.75,2753], + [115.744,115.864,42,60,13,0,64,3,2756], + [115.746,115.864,76,106,2,0,64,3,2756], + [115.747,115.864,72,91,4,0,64,3,2756], + [115.747,115.864,36,105,10,0,64,3,2756], + [115.748,115.864,39,106,12,0,64,3,2756], + [115.75,115.864,64,88,0,0,64,3,2756], + [115.863,116.215,69,91,0,0,64,3.25,2759], + [115.863,116.215,81,105,2,0,64,3.25,2759], + [115.864,115.981,42,41,13,0,64,3.25,2759], + [115.864,115.981,45,100,8,0,64,3.25,2759], + [115.865,115.981,76,76,4,0,64,3.25,2759], + [115.978,116.098,45,88,8,0,64,3.5,2761], + [115.979,116.215,57,96,5,0,64,3.5,2761], + [115.98,116.098,69,76,4,0,64,3.5,2761], + [115.982,116.215,60,96,5,1,64,3.5,2761], + [115.983,116.215,64,96,5,2,64,3.5,2761], + [115.983,116.098,46,81,15,0,64,3.5,2762], + [116.095,116.215,64,73,4,0,64,3.75,2764], + [116.098,116.215,42,51,13,0,64,3.75,2764], + [116.099,116.215,45,93,8,0,64,3.75,2764], + [116.213,117.153,28,92,9,0,65,0,2767], + [116.213,116.45,56,105,5,1,65,0,2767], + [116.213,116.332,52,92,4,0,65,0,2767], + [116.214,116.45,59,105,5,2,65,0,2767], + [116.214,117.153,52,84,6,0,65,0,2767], + [116.214,116.45,52,102,5,0,65,0,2767], + [116.215,117.153,59,88,6,2,65,0,2767], + [116.215,117.153,56,85,6,1,65,0,2767], + [116.216,116.332,36,113,10,0,65,0,2767], + [116.216,116.567,71,91,0,0,65,0,2767], + [116.217,116.332,38,72,14,0,65,0,2767], + [116.218,116.567,83,101,2,0,65,0,2767], + [116.218,116.332,42,70,13,0,65,0,2767], + [116.33,116.45,40,100,8,0,65,0.25,2770], + [116.332,116.45,42,39,13,0,65,0.25,2770], + [116.333,116.45,56,73,4,0,65,0.25,2770], + [116.336,116.45,38,74,14,0,65,0.25,2770], + [116.448,116.567,59,78,4,0,65,0.5,2773], + [116.451,116.567,40,85,8,0,65,0.5,2773], + [116.452,116.567,38,77,14,0,65,0.5,2773], + [116.452,116.567,46,88,15,0,65,0.5,2773], + [116.562,116.684,64,72,4,0,65,0.75,2775], + [116.564,116.801,52,87,5,0,65,0.75,2775], + [116.564,116.684,42,50,13,0,65,0.75,2775], + [116.564,116.684,76,109,2,0,65,0.75,2775], + [116.565,116.801,59,90,5,2,65,0.75,2775], + [116.566,116.684,40,93,8,0,65,0.75,2775], + [116.568,116.684,64,92,0,0,65,0.75,2775], + [116.57,116.801,56,85,5,1,65,0.75,2775], + [116.57,116.684,38,80,14,0,65,0.75,2775], + [116.682,116.801,36,111,10,0,65,1,2778], + [116.683,116.801,39,98,12,0,65,1,2778], + [116.684,116.801,72,93,0,0,65,1,2778], + [116.684,116.801,42,65,13,0,65,1,2778], + [116.685,116.801,84,105,2,0,65,1,2778], + [116.685,116.801,38,85,14,0,65,1,2778], + [116.685,116.801,68,95,4,0,65,1,2778], + [116.799,117.153,83,108,2,0,65,1.25,2781], + [116.8,116.918,40,103,8,0,65,1.25,2781], + [116.8,116.918,71,78,4,0,65,1.25,2781], + [116.801,116.918,38,90,14,0,65,1.25,2781], + [116.801,117.153,71,85,0,0,65,1.25,2781], + [116.803,116.918,42,41,13,0,65,1.25,2781], + [116.917,117.153,59,94,5,2,65,1.5,2784], + [116.917,117.036,46,83,15,0,65,1.5,2784], + [116.918,117.036,38,95,14,0,65,1.5,2784], + [116.919,117.153,56,97,5,1,65,1.5,2784], + [116.92,117.036,64,69,4,0,65,1.5,2784], + [116.92,117.153,52,94,5,0,65,1.5,2784], + [116.921,117.036,40,89,8,0,65,1.5,2784], + [117.032,117.153,42,44,13,0,65,1.75,2786], + [117.035,117.153,59,71,4,0,65,1.75,2787], + [117.035,117.153,40,93,8,0,65,1.75,2787], + [117.039,117.153,38,94,14,0,65,1.75,2787], + [117.148,117.27,42,74,13,0,65,2,2789], + [117.15,117.387,57,106,5,0,65,2,2789], + [117.15,117.27,36,106,10,0,65,2,2789], + [117.151,117.27,57,96,4,0,65,2,2789], + [117.151,117.387,64,103,5,2,65,2,2789], + [117.151,117.504,69,93,0,0,65,2,2789], + [117.151,117.27,38,104,14,0,65,2,2789], + [117.151,118.09,60,87,6,1,65,2,2789], + [117.151,118.09,64,85,6,2,65,2,2789], + [117.152,117.387,60,100,5,1,65,2,2789], + [117.152,117.504,81,107,2,0,65,2,2789], + [117.153,118.09,57,86,6,0,65,2,2789], + [117.153,118.09,33,93,9,0,65,2,2789], + [117.269,117.387,60,73,4,0,65,2.25,2792], + [117.271,117.387,38,105,14,0,65,2.25,2792], + [117.273,117.387,42,41,13,0,65,2.25,2792], + [117.273,117.387,45,99,8,0,65,2.25,2792], + [117.384,117.504,64,71,4,0,65,2.5,2795], + [117.385,117.504,46,83,15,0,65,2.5,2795], + [117.386,117.504,38,112,14,0,65,2.5,2795], + [117.389,117.504,45,87,8,0,65,2.5,2795], + [117.499,117.621,42,46,13,0,65,2.75,2798], + [117.501,117.621,83,105,2,0,65,2.75,2798], + [117.504,117.621,38,113,14,0,65,2.75,2798], + [117.504,117.739,57,89,5,0,65,2.75,2798], + [117.504,117.739,60,85,5,1,65,2.75,2798], + [117.505,117.621,69,76,4,0,65,2.75,2798], + [117.505,117.621,71,90,0,0,65,2.75,2798], + [117.505,117.621,45,91,8,0,65,2.75,2798], + [117.505,117.739,64,85,5,2,65,2.75,2798], + [117.617,117.739,72,92,4,0,65,3,2800], + [117.619,117.739,36,109,10,0,65,3,2800], + [117.62,117.739,42,62,13,0,65,3,2800], + [117.62,117.739,38,117,14,0,65,3,2800], + [117.623,117.739,72,93,0,0,65,3,2801], + [117.624,117.739,84,104,2,0,65,3,2801], + [117.624,117.739,39,106,12,0,65,3,2801], + [117.735,117.856,38,123,14,0,65,3.25,2803], + [117.737,117.856,45,103,8,0,65,3.25,2803], + [117.74,118.09,74,91,0,0,65,3.25,2803], + [117.742,117.856,42,40,13,0,65,3.25,2803], + [117.742,118.09,86,105,2,0,65,3.25,2803], + [117.743,117.856,76,73,4,0,65,3.25,2803], + [117.854,117.973,46,82,15,0,65,3.5,2806], + [117.854,117.973,38,122,14,0,65,3.5,2806], + [117.855,118.09,57,96,5,0,65,3.5,2806], + [117.855,118.09,64,96,5,2,65,3.5,2806], + [117.857,117.973,69,76,4,0,65,3.5,2806], + [117.858,118.09,60,97,5,1,65,3.5,2806], + [117.859,117.973,45,87,8,0,65,3.5,2806], + [117.971,118.09,38,126,14,0,65,3.75,2809], + [117.972,118.09,42,51,13,0,65,3.75,2809], + [117.975,118.09,64,72,4,0,65,3.75,2809], + [117.976,118.09,45,94,8,0,65,3.75,2809], + [118.087,118.207,42,68,13,0,66,0,2812], + [118.088,119.028,52,85,6,1,66,0,2812], + [118.088,118.442,76,91,0,0,66,0,2812], + [118.088,119.028,48,76,7,0,66,0,2812], + [118.089,118.325,48,104,5,0,66,0,2812], + [118.089,119.028,24,87,9,0,66,0,2812], + [118.089,119.028,55,83,6,2,66,0,2812], + [118.09,118.207,49,111,16,0,66,0,2812], + [118.09,119.028,52,75,7,1,66,0,2812], + [118.09,118.442,88,108,2,0,66,0,2812], + [118.09,118.442,76,93,3,0,66,0,2812], + [118.091,118.207,48,93,4,0,66,0,2812], + [118.091,118.207,36,110,10,0,66,0,2812], + [118.092,118.325,52,102,5,1,66,0,2812], + [118.093,119.028,48,86,6,0,66,0,2812], + [118.094,118.325,55,106,5,2,66,0,2812], + [118.095,119.028,55,73,7,2,66,0,2812], + [118.203,118.325,36,98,8,0,66,0.25,2814], + [118.207,118.325,52,74,4,0,66,0.25,2814], + [118.208,118.325,42,42,13,0,66,0.25,2814], + [118.323,118.442,55,74,4,0,66,0.5,2817], + [118.326,118.442,46,91,15,0,66,0.5,2817], + [118.326,118.442,36,87,8,0,66,0.5,2817], + [118.439,118.559,67,85,3,0,66,0.75,2820], + [118.44,118.676,48,89,5,0,66,0.75,2820], + [118.442,118.559,60,74,4,0,66,0.75,2820], + [118.442,118.676,52,87,5,1,66,0.75,2820], + [118.443,118.559,42,50,13,0,66,0.75,2820], + [118.443,118.559,67,91,0,0,66,0.75,2820], + [118.443,118.559,36,95,8,0,66,0.75,2820], + [118.444,118.676,55,86,5,2,66,0.75,2820], + [118.444,118.559,79,103,2,0,66,0.75,2820], + [118.558,118.676,39,98,12,0,66,1,2823], + [118.559,118.676,77,88,0,0,66,1,2823], + [118.559,118.676,64,96,4,0,66,1,2823], + [118.559,118.676,77,90,3,0,66,1,2823], + [118.56,118.676,36,112,10,0,66,1,2823], + [118.561,118.676,42,62,13,0,66,1,2823], + [118.561,118.676,89,104,2,0,66,1,2823], + [118.674,118.793,42,39,13,0,66,1.25,2826], + [118.675,119.028,76,89,0,0,66,1.25,2826], + [118.677,118.793,67,76,4,0,66,1.25,2826], + [118.678,119.028,76,87,3,0,66,1.25,2826], + [118.679,118.793,36,95,8,0,66,1.25,2826], + [118.68,119.028,88,107,2,0,66,1.25,2826], + [118.789,119.028,52,95,5,1,66,1.5,2828], + [118.791,118.911,60,72,4,0,66,1.5,2828], + [118.792,119.028,55,95,5,2,66,1.5,2828], + [118.793,118.911,46,84,15,0,66,1.5,2828], + [118.797,119.028,48,98,5,0,66,1.5,2828], + [118.797,118.911,36,86,8,0,66,1.5,2828], + [118.907,119.028,55,76,4,0,66,1.75,2831], + [118.908,119.028,42,46,13,0,66,1.75,2831], + [118.909,119.028,36,95,8,0,66,1.75,2831], + [119.025,119.145,42,69,13,0,66,2,2834], + [119.026,119.145,36,110,10,0,66,2,2834], + [119.027,119.262,62,103,5,2,66,2,2834], + [119.027,119.965,62,78,7,2,66,2,2834], + [119.027,119.965,59,75,7,1,66,2,2834], + [119.028,119.262,59,102,5,1,66,2,2834], + [119.028,119.379,86,106,2,0,66,2,2834], + [119.028,119.965,31,89,9,0,66,2,2834], + [119.028,119.965,62,82,6,2,66,2,2834], + [119.028,119.262,55,108,5,0,66,2,2834], + [119.029,119.965,55,76,7,0,66,2,2834], + [119.029,119.379,74,90,3,0,66,2,2834], + [119.029,119.965,55,86,6,0,66,2,2834], + [119.03,119.379,74,92,0,0,66,2,2834], + [119.031,119.145,55,93,4,0,66,2,2834], + [119.032,119.965,59,84,6,1,66,2,2834], + [119.142,119.262,42,40,13,0,66,2.25,2837], + [119.143,119.262,59,77,4,0,66,2.25,2837], + [119.145,119.262,43,99,8,0,66,2.25,2837], + [119.26,119.379,43,85,8,0,66,2.5,2840], + [119.261,119.379,62,75,4,0,66,2.5,2840], + [119.263,119.379,46,86,15,0,66,2.5,2840], + [119.376,119.614,62,88,5,2,66,2.75,2842], + [119.377,119.496,65,91,3,0,66,2.75,2842], + [119.377,119.496,67,77,4,0,66,2.75,2842], + [119.378,119.496,77,106,2,0,66,2.75,2842], + [119.378,119.496,65,93,0,0,66,2.75,2842], + [119.378,119.496,42,48,13,0,66,2.75,2842], + [119.378,119.614,59,84,5,1,66,2.75,2842], + [119.38,119.496,43,91,8,0,66,2.75,2842], + [119.381,119.614,55,92,5,0,66,2.75,2842], + [119.496,119.614,42,67,13,0,66,3,2845], + [119.498,119.614,36,106,10,0,66,3,2845], + [119.498,119.614,76,87,0,0,66,3,2845], + [119.498,119.614,88,107,2,0,66,3,2845], + [119.499,119.614,71,95,4,0,66,3,2845], + [119.5,119.614,76,90,3,0,66,3,2845], + [119.5,119.614,39,104,12,0,66,3,2845], + [119.612,119.731,42,41,13,0,66,3.25,2848], + [119.612,119.965,74,92,3,0,66,3.25,2848], + [119.613,119.731,43,100,8,0,66,3.25,2848], + [119.615,119.965,86,108,2,0,66,3.25,2848], + [119.615,119.965,74,88,0,0,66,3.25,2848], + [119.615,119.731,74,72,4,0,66,3.25,2848], + [119.729,119.848,43,84,8,0,66,3.5,2851], + [119.729,119.965,59,95,5,1,66,3.5,2851], + [119.729,119.965,55,93,5,0,66,3.5,2851], + [119.73,119.848,67,73,4,0,66,3.5,2851], + [119.731,119.848,46,84,15,0,66,3.5,2851], + [119.734,119.965,62,96,5,2,66,3.5,2851], + [119.846,119.965,62,72,4,0,66,3.75,2853], + [119.847,119.965,43,89,8,0,66,3.75,2853], + [119.847,119.965,42,53,13,0,66,3.75,2854], + [119.962,120.2,64,103,5,2,67,0,2856], + [119.963,120.317,84,107,2,0,67,0,2856], + [119.963,120.082,42,68,13,0,67,0,2856], + [119.964,120.903,60,84,6,1,67,0,2856], + [119.964,120.903,60,77,7,1,67,0,2856], + [119.964,120.317,72,90,0,0,67,0,2856], + [119.964,120.2,60,104,5,1,67,0,2856], + [119.964,120.903,57,85,6,0,67,0,2856], + [119.965,120.903,64,85,6,2,67,0,2856], + [119.966,120.317,72,91,3,0,67,0,2856], + [119.967,120.082,36,112,10,0,67,0,2856], + [119.967,120.903,64,75,7,2,67,0,2856], + [119.967,120.2,57,103,5,0,67,0,2856], + [119.967,120.903,57,76,7,0,67,0,2856], + [119.968,120.903,33,89,9,0,67,0,2856], + [119.968,120.082,57,95,4,0,67,0,2856], + [120.083,120.2,60,73,4,0,67,0.25,2859], + [120.084,120.2,45,100,8,0,67,0.25,2859], + [120.086,120.2,42,39,13,0,67,0.25,2859], + [120.197,120.317,46,89,15,0,67,0.5,2862], + [120.197,120.317,64,76,4,0,67,0.5,2862], + [120.199,120.317,45,87,8,0,67,0.5,2862], + [120.315,120.434,45,90,8,0,67,0.75,2865], + [120.315,120.551,60,85,5,1,67,0.75,2865], + [120.316,120.434,69,75,4,0,67,0.75,2865], + [120.317,120.434,76,105,2,0,67,0.75,2865], + [120.317,120.434,42,48,13,0,67,0.75,2865], + [120.318,120.551,64,86,5,2,67,0.75,2865], + [120.318,120.551,57,90,5,0,67,0.75,2865], + [120.32,120.434,64,87,3,0,67,0.75,2865], + [120.321,120.434,64,93,0,0,67,0.75,2865], + [120.432,120.551,72,98,4,0,67,1,2867], + [120.432,120.551,39,103,12,0,67,1,2867], + [120.433,120.551,42,66,13,0,67,1,2867], + [120.433,120.551,36,108,10,0,67,1,2867], + [120.434,120.551,86,105,2,0,67,1,2867], + [120.435,120.551,74,89,3,0,67,1,2868], + [120.436,120.551,74,91,0,0,67,1,2868], + [120.55,120.903,72,90,3,0,67,1.25,2870], + [120.552,120.668,76,73,4,0,67,1.25,2870], + [120.552,120.668,42,38,13,0,67,1.25,2870], + [120.552,120.903,84,103,2,0,67,1.25,2870], + [120.552,120.668,45,99,8,0,67,1.25,2870], + [120.553,120.903,72,89,0,0,67,1.25,2870], + [120.665,120.903,60,93,5,1,67,1.5,2873], + [120.668,120.786,46,85,15,0,67,1.5,2873], + [120.668,120.786,69,72,4,0,67,1.5,2873], + [120.669,120.786,45,85,8,0,67,1.5,2873], + [120.669,120.903,64,96,5,2,67,1.5,2873], + [120.672,120.903,57,97,5,0,67,1.5,2873], + [120.786,120.903,42,43,13,0,67,1.75,2876], + [120.787,120.903,64,72,4,0,67,1.75,2876], + [120.791,120.903,45,92,8,0,67,1.75,2876], + [120.9,121.84,59,88,6,2,67,2,2879], + [120.9,121.02,42,70,13,0,67,2,2879], + [120.901,121.02,36,109,10,0,67,2,2879], + [120.901,121.84,28,91,9,0,67,2,2879], + [120.901,121.254,83,106,2,0,67,2,2879], + [120.901,121.84,52,77,7,0,67,2,2879], + [120.902,121.84,52,89,6,0,67,2,2879], + [120.902,121.254,71,91,3,0,67,2,2879], + [120.903,121.137,56,106,5,1,67,2,2879], + [120.903,121.254,71,89,0,0,67,2,2879], + [120.903,121.02,52,94,4,0,67,2,2879], + [120.903,121.84,56,83,6,1,67,2,2879], + [120.903,121.84,59,77,7,2,67,2,2879], + [120.903,121.137,59,105,5,2,67,2,2879], + [120.903,121.137,52,105,5,0,67,2,2879], + [120.906,121.84,56,75,7,1,67,2,2879], + [121.016,121.137,56,74,4,0,67,2.25,2881], + [121.018,121.137,40,97,8,0,67,2.25,2881], + [121.019,121.137,42,39,13,0,67,2.25,2881], + [121.135,121.254,46,90,15,0,67,2.5,2884], + [121.137,121.254,40,89,8,0,67,2.5,2884], + [121.138,121.254,59,74,4,0,67,2.5,2884], + [121.252,121.371,64,91,0,0,67,2.75,2887], + [121.254,121.371,42,47,13,0,67,2.75,2887], + [121.255,121.489,56,85,5,1,67,2.75,2887], + [121.255,121.371,40,90,8,0,67,2.75,2887], + [121.256,121.371,64,89,3,0,67,2.75,2887], + [121.257,121.371,76,105,2,0,67,2.75,2887], + [121.257,121.489,59,88,5,2,67,2.75,2887], + [121.257,121.371,64,74,4,0,67,2.75,2887], + [121.258,121.489,52,88,5,0,67,2.75,2887], + [121.37,121.489,39,106,12,0,67,3,2890], + [121.372,121.489,42,65,13,0,67,3,2890], + [121.372,121.489,68,90,4,0,67,3,2890], + [121.373,121.606,76,90,3,0,67,3,2890], + [121.374,121.606,88,107,2,0,67,3,2890], + [121.374,121.606,76,90,0,0,67,3,2890], + [121.377,121.489,36,110,10,0,67,3,2890], + [121.487,121.606,42,37,13,0,67,3.25,2893], + [121.488,121.606,71,72,4,0,67,3.25,2893], + [121.488,121.606,40,98,8,0,67,3.25,2893], + [121.603,121.84,56,96,5,1,67,3.5,2895], + [121.603,121.723,64,72,4,0,67,3.5,2895], + [121.603,121.84,59,95,5,2,67,3.5,2895], + [121.604,121.84,52,92,5,0,67,3.5,2895], + [121.605,121.723,76,90,3,0,67,3.5,2895], + [121.607,121.723,40,82,8,0,67,3.5,2895], + [121.607,121.723,46,86,15,0,67,3.5,2895], + [121.607,121.723,76,93,0,0,67,3.5,2895], + [121.608,121.723,88,106,2,0,67,3.5,2895], + [121.721,121.84,59,71,4,0,67,3.75,2898], + [121.721,121.84,88,91,0,0,67,3.75,2898], + [121.722,121.84,88,91,3,0,67,3.75,2898], + [121.722,121.84,42,52,13,0,67,3.75,2898], + [121.722,121.84,40,89,8,0,67,3.75,2898], + [121.727,121.84,100,105,2,0,67,3.75,2898], + [121.837,122.778,56,85,6,1,68,0,2901], + [121.839,122.778,28,94,9,0,68,0,2901], + [121.839,122.778,52,73,7,0,68,0,2901], + [121.84,121.957,52,93,4,0,68,0,2901], + [121.84,122.309,88,89,0,0,68,0,2901], + [121.84,122.778,59,75,7,2,68,0,2901], + [121.841,122.778,52,88,6,0,68,0,2901], + [121.841,122.075,59,104,5,2,68,0,2901], + [121.842,122.309,100,104,2,0,68,0,2901], + [121.842,122.778,56,74,7,1,68,0,2901], + [121.842,122.075,52,104,5,0,68,0,2901], + [121.842,122.309,88,88,3,0,68,0,2901], + [121.843,122.778,59,85,6,2,68,0,2901], + [121.843,121.957,36,115,10,0,68,0,2901], + [121.843,121.957,42,71,13,0,68,0,2901], + [121.844,122.075,56,106,5,1,68,0,2901], + [121.958,122.075,42,41,13,0,68,0.25,2904], + [121.959,122.075,56,78,4,0,68,0.25,2904], + [121.962,122.075,40,99,8,0,68,0.25,2904], + [122.072,122.192,59,74,4,0,68,0.5,2906], + [122.075,122.192,40,84,8,0,68,0.5,2907], + [122.076,122.192,46,88,15,0,68,0.5,2907], + [122.189,122.426,52,88,5,0,68,0.75,2909], + [122.19,122.426,59,90,5,2,68,0.75,2909], + [122.19,122.309,64,75,4,0,68,0.75,2909], + [122.191,122.309,40,93,8,0,68,0.75,2909], + [122.193,122.426,56,88,5,1,68,0.75,2909], + [122.194,122.309,42,49,13,0,68,0.75,2909], + [122.306,122.426,42,63,13,0,68,1,2912], + [122.306,122.426,36,109,10,0,68,1,2912], + [122.308,122.426,39,103,12,0,68,1,2912], + [122.308,122.426,87,108,2,0,68,1,2912], + [122.308,122.426,75,90,3,0,68,1,2912], + [122.309,122.426,68,94,4,0,68,1,2912], + [122.312,122.426,75,95,0,0,68,1,2912], + [122.423,122.543,88,106,2,0,68,1.25,2915], + [122.424,122.543,76,89,0,0,68,1.25,2915], + [122.425,122.543,42,40,13,0,68,1.25,2915], + [122.427,122.543,76,89,3,0,68,1.25,2915], + [122.428,122.543,71,74,4,0,68,1.25,2915], + [122.428,122.543,40,99,8,0,68,1.25,2915], + [122.539,122.778,56,98,5,1,68,1.5,2918], + [122.54,122.661,75,89,3,0,68,1.5,2918], + [122.542,122.661,64,72,4,0,68,1.5,2918], + [122.544,122.661,40,84,8,0,68,1.5,2918], + [122.544,122.661,87,106,2,0,68,1.5,2918], + [122.544,122.661,46,81,15,0,68,1.5,2918], + [122.544,122.661,75,90,0,0,68,1.5,2918], + [122.545,122.778,59,95,5,2,68,1.5,2918], + [122.546,122.778,52,98,5,0,68,1.5,2918], + [122.658,122.778,76,93,0,0,68,1.75,2920], + [122.66,122.778,76,92,3,0,68,1.75,2920], + [122.66,122.778,88,107,2,0,68,1.75,2920], + [122.661,122.778,42,49,13,0,68,1.75,2920], + [122.661,122.778,40,92,8,0,68,1.75,2920], + [122.662,122.778,59,75,4,0,68,1.75,2921], + [122.774,123.715,59,88,6,2,68,2,2923], + [122.775,123.715,52,89,6,0,68,2,2923], + [122.775,122.895,52,94,4,0,68,2,2923], + [122.776,122.895,36,111,10,0,68,2,2923], + [122.776,123.715,52,75,7,0,68,2,2923], + [122.776,123.012,59,105,5,2,68,2,2923], + [122.776,123.715,28,92,9,0,68,2,2923], + [122.777,122.895,75,90,0,0,68,2,2923], + [122.777,123.715,56,78,7,1,68,2,2923], + [122.778,123.715,56,87,6,1,68,2,2923], + [122.778,122.895,87,106,2,0,68,2,2923], + [122.778,122.895,75,90,3,0,68,2,2923], + [122.779,123.012,52,99,5,0,68,2,2923], + [122.779,122.895,42,70,13,0,68,2,2923], + [122.779,123.715,59,77,7,2,68,2,2923], + [122.779,123.012,56,104,5,1,68,2,2923], + [122.892,123.012,76,88,3,0,68,2.25,2926], + [122.893,123.012,88,105,2,0,68,2.25,2926], + [122.893,123.012,56,75,4,0,68,2.25,2926], + [122.894,123.012,76,90,0,0,68,2.25,2926], + [122.894,123.012,40,101,8,0,68,2.25,2926], + [122.894,123.012,42,37,13,0,68,2.25,2926], + [123.009,123.129,87,110,2,0,68,2.5,2929], + [123.01,123.129,75,86,0,0,68,2.5,2929], + [123.01,123.129,59,71,4,0,68,2.5,2929], + [123.011,123.129,75,90,3,0,68,2.5,2929], + [123.013,123.129,46,88,15,0,68,2.5,2929], + [123.013,123.129,40,85,8,0,68,2.5,2929], + [123.127,123.246,64,73,4,0,68,2.75,2932], + [123.128,123.246,76,92,3,0,68,2.75,2932], + [123.128,123.246,76,88,0,0,68,2.75,2932], + [123.128,123.246,42,50,13,0,68,2.75,2932], + [123.129,123.246,40,95,8,0,68,2.75,2932], + [123.129,123.246,88,106,2,0,68,2.75,2932], + [123.131,123.364,52,86,5,0,68,2.75,2932], + [123.131,123.364,56,91,5,1,68,2.75,2932], + [123.132,123.364,59,85,5,2,68,2.75,2932], + [123.244,123.364,87,102,2,0,68,3,2934], + [123.244,123.364,36,109,10,0,68,3,2934], + [123.245,123.364,75,91,3,0,68,3,2934], + [123.246,123.364,75,89,0,0,68,3,2934], + [123.248,123.364,42,64,13,0,68,3,2934], + [123.248,123.364,39,102,12,0,68,3,2934], + [123.251,123.364,68,92,4,0,68,3,2935], + [123.361,123.481,40,99,8,0,68,3.25,2937], + [123.361,123.481,42,42,13,0,68,3.25,2937], + [123.364,123.481,76,87,3,0,68,3.25,2937], + [123.364,123.481,76,89,0,0,68,3.25,2937], + [123.364,123.481,88,104,2,0,68,3.25,2937], + [123.365,123.481,71,72,4,0,68,3.25,2937], + [123.477,123.598,64,74,4,0,68,3.5,2940], + [123.478,123.715,59,96,5,2,68,3.5,2940], + [123.478,123.715,75,90,3,0,68,3.5,2940], + [123.478,123.715,56,98,5,1,68,3.5,2940], + [123.479,123.598,46,86,15,0,68,3.5,2940], + [123.479,123.715,52,96,5,0,68,3.5,2940], + [123.48,123.715,87,106,2,0,68,3.5,2940], + [123.481,123.715,75,87,0,0,68,3.5,2940], + [123.484,123.598,40,85,8,0,68,3.5,2940], + [123.596,123.715,40,91,8,0,68,3.75,2943], + [123.597,123.715,59,76,4,0,68,3.75,2943], + [123.597,123.715,42,50,13,0,68,3.75,2943], + [123.712,123.832,42,70,13,0,69,0,2946], + [123.712,124.653,52,89,6,0,69,0,2946], + [123.712,123.95,56,104,5,1,69,0,2946], + [123.713,124.653,56,75,7,1,69,0,2946], + [123.714,124.653,52,78,7,0,69,0,2946], + [123.714,123.832,52,91,4,0,69,0,2946], + [123.715,124.653,59,78,7,2,69,0,2946], + [123.715,123.832,88,104,2,0,69,0,2946], + [123.715,124.653,28,89,9,0,69,0,2946], + [123.716,124.653,59,85,6,2,69,0,2946], + [123.716,123.832,49,115,16,0,69,0,2946], + [123.716,123.832,36,112,10,0,69,0,2946], + [123.717,123.95,52,103,5,0,69,0,2946], + [123.717,123.95,59,104,5,2,69,0,2946], + [123.718,123.832,76,88,0,0,69,0,2946], + [123.718,123.832,76,87,3,0,69,0,2946], + [123.718,124.653,56,88,6,1,69,0,2946], + [123.829,123.95,42,36,13,0,69,0.25,2948], + [123.831,123.95,40,101,8,0,69,0.25,2948], + [123.831,123.95,87,107,2,0,69,0.25,2948], + [123.832,123.95,75,94,0,0,69,0.25,2948], + [123.832,123.95,75,89,3,0,69,0.25,2948], + [123.833,123.95,56,73,4,0,69,0.25,2948], + [123.945,124.067,40,87,8,0,69,0.5,2951], + [123.947,124.067,76,93,0,0,69,0.5,2951], + [123.947,124.067,88,108,2,0,69,0.5,2951], + [123.948,124.067,59,77,4,0,69,0.5,2951], + [123.949,124.067,46,82,15,0,69,0.5,2951], + [123.949,124.067,76,93,3,0,69,0.5,2951], + [124.065,124.184,64,75,4,0,69,0.75,2954], + [124.066,124.184,75,89,0,0,69,0.75,2954], + [124.066,124.184,40,92,8,0,69,0.75,2954], + [124.067,124.184,75,88,3,0,69,0.75,2954], + [124.067,124.301,59,84,5,2,69,0.75,2954], + [124.068,124.301,56,87,5,1,69,0.75,2954], + [124.069,124.184,87,108,2,0,69,0.75,2954], + [124.069,124.184,42,49,13,0,69,0.75,2954], + [124.069,124.301,52,88,5,0,69,0.75,2954], + [124.182,124.301,88,103,2,0,69,1,2957], + [124.182,124.301,76,92,0,0,69,1,2957], + [124.183,124.301,76,89,3,0,69,1,2957], + [124.184,124.301,42,68,13,0,69,1,2957], + [124.184,124.301,68,94,4,0,69,1,2957], + [124.185,124.301,36,108,10,0,69,1,2957], + [124.189,124.301,39,99,12,0,69,1,2957], + [124.299,124.418,40,102,8,0,69,1.25,2959], + [124.3,124.418,83,102,2,0,69,1.25,2960], + [124.3,124.418,71,89,3,0,69,1.25,2960], + [124.301,124.418,71,93,0,0,69,1.25,2960], + [124.301,124.418,42,40,13,0,69,1.25,2960], + [124.302,124.418,71,78,4,0,69,1.25,2960], + [124.415,124.536,46,82,15,0,69,1.5,2962], + [124.416,124.536,74,87,3,0,69,1.5,2962], + [124.418,124.653,59,95,5,2,69,1.5,2962], + [124.418,124.536,64,73,4,0,69,1.5,2962], + [124.418,124.653,52,93,5,0,69,1.5,2962], + [124.419,124.536,74,91,0,0,69,1.5,2962], + [124.42,124.536,40,87,8,0,69,1.5,2962], + [124.42,124.653,56,96,5,1,69,1.5,2962], + [124.423,124.536,86,106,2,0,69,1.5,2962], + [124.532,124.653,84,103,2,0,69,1.75,2965], + [124.534,124.653,40,91,8,0,69,1.75,2965], + [124.534,124.653,42,43,13,0,69,1.75,2965], + [124.534,124.653,59,77,4,0,69,1.75,2965], + [124.535,124.653,72,89,3,0,69,1.75,2965], + [124.537,124.653,72,91,0,0,69,1.75,2965], + [124.649,125.004,81,109,2,0,69,2,2968], + [124.651,125.004,69,93,0,0,69,2,2968], + [124.651,124.77,36,108,10,0,69,2,2968], + [124.652,125.59,60,85,6,1,69,2,2968], + [124.653,125.59,64,87,6,2,69,2,2968], + [124.653,125.59,60,78,7,1,69,2,2968], + [124.653,125.59,64,75,7,2,69,2,2968], + [124.653,124.887,60,101,5,1,69,2,2968], + [124.653,125.59,57,84,6,0,69,2,2968], + [124.654,125.59,57,74,7,0,69,2,2968], + [124.654,125.59,33,88,9,0,69,2,2968], + [124.654,124.77,57,92,4,0,69,2,2968], + [124.655,124.887,64,102,5,2,69,2,2968], + [124.655,124.887,57,101,5,0,69,2,2968], + [124.655,124.77,42,68,13,0,69,2,2968], + [124.655,125.004,69,88,3,0,69,2,2968], + [124.767,124.887,60,72,4,0,69,2.25,2971], + [124.77,124.887,42,37,13,0,69,2.25,2971], + [124.771,124.887,45,103,8,0,69,2.25,2971], + [124.883,125.004,46,89,15,0,69,2.5,2973], + [124.887,125.004,64,74,4,0,69,2.5,2974], + [124.888,125.004,45,91,8,0,69,2.5,2974], + [125,125.239,64,89,5,2,69,2.75,2976], + [125.001,125.121,72,106,2,0,69,2.75,2976], + [125.002,125.121,60,90,3,0,69,2.75,2976], + [125.003,125.239,60,92,5,1,69,2.75,2976], + [125.004,125.121,45,95,8,0,69,2.75,2976], + [125.004,125.121,42,44,13,0,69,2.75,2976], + [125.006,125.121,69,73,4,0,69,2.75,2976], + [125.006,125.121,60,92,0,0,69,2.75,2976], + [125.008,125.239,57,90,5,0,69,2.75,2976], + [125.119,125.239,64,93,0,0,69,3,2979], + [125.12,125.239,64,88,3,0,69,3,2979], + [125.12,125.239,42,67,13,0,69,3,2979], + [125.122,125.239,39,107,12,0,69,3,2979], + [125.123,125.239,76,102,2,0,69,3,2979], + [125.124,125.239,72,91,4,0,69,3,2979], + [125.124,125.239,36,110,10,0,69,3,2979], + [125.237,125.356,76,72,4,0,69,3.25,2982], + [125.237,125.59,69,92,0,0,69,3.25,2982], + [125.237,125.356,42,39,13,0,69,3.25,2982], + [125.239,125.356,45,97,8,0,69,3.25,2982], + [125.239,125.59,69,87,3,0,69,3.25,2982], + [125.241,125.59,81,109,2,0,69,3.25,2982], + [125.351,125.59,57,99,5,0,69,3.5,2985], + [125.353,125.473,46,84,15,0,69,3.5,2985], + [125.356,125.59,60,97,5,1,69,3.5,2985], + [125.358,125.59,64,98,5,2,69,3.5,2985], + [125.359,125.473,69,73,4,0,69,3.5,2985], + [125.36,125.473,45,84,8,0,69,3.5,2985], + [125.471,125.59,42,55,13,0,69,3.75,2987], + [125.474,125.59,45,91,8,0,69,3.75,2987], + [125.474,125.59,64,77,4,0,69,3.75,2987], + [125.587,125.942,83,106,2,0,70,0,2990], + [125.587,125.942,71,91,3,0,70,0,2990], + [125.588,126.528,28,86,9,0,70,0,2990], + [125.589,126.528,56,86,6,1,70,0,2990], + [125.589,125.707,42,69,13,0,70,0,2990], + [125.59,126.528,56,79,7,1,70,0,2990], + [125.59,126.528,52,75,7,0,70,0,2990], + [125.59,126.528,52,89,6,0,70,0,2990], + [125.591,125.825,52,105,5,0,70,0,2990], + [125.591,125.825,59,104,5,2,70,0,2990], + [125.592,125.707,52,93,4,0,70,0,2990], + [125.592,126.528,59,85,6,2,70,0,2990], + [125.592,126.528,59,78,7,2,70,0,2990], + [125.593,125.942,71,90,0,0,70,0,2990], + [125.593,125.707,36,113,10,0,70,0,2990], + [125.595,125.825,56,103,5,1,70,0,2990], + [125.706,125.825,56,77,4,0,70,0.25,2993], + [125.71,125.825,42,39,13,0,70,0.25,2993], + [125.71,125.825,40,103,8,0,70,0.25,2993], + [125.823,125.942,46,89,15,0,70,0.5,2996], + [125.825,125.942,59,73,4,0,70,0.5,2996], + [125.827,125.942,40,87,8,0,70,0.5,2996], + [125.937,126.059,64,72,4,0,70,0.75,2999], + [125.94,126.176,56,88,5,1,70,0.75,2999], + [125.94,126.176,59,85,5,2,70,0.75,2999], + [125.942,126.059,76,106,2,0,70,0.75,2999], + [125.943,126.059,64,90,0,0,70,0.75,2999], + [125.944,126.176,52,90,5,0,70,0.75,2999], + [125.945,126.059,42,45,13,0,70,0.75,2999], + [125.946,126.059,40,95,8,0,70,0.75,2999], + [125.946,126.059,64,92,3,0,70,0.75,2999], + [126.055,126.176,39,98,12,0,70,1,3001], + [126.058,126.176,42,64,13,0,70,1,3001], + [126.058,126.176,68,90,3,0,70,1,3001], + [126.06,126.176,68,91,4,0,70,1,3001], + [126.061,126.176,36,108,10,0,70,1,3001], + [126.062,126.176,80,106,2,0,70,1,3001], + [126.064,126.176,68,89,0,0,70,1,3002], + [126.172,126.293,40,100,8,0,70,1.25,3004], + [126.172,126.293,42,38,13,0,70,1.25,3004], + [126.175,126.293,71,75,4,0,70,1.25,3004], + [126.177,126.528,83,109,2,0,70,1.25,3004], + [126.178,126.528,71,89,3,0,70,1.25,3004], + [126.179,126.528,71,89,0,0,70,1.25,3004], + [126.29,126.411,40,89,8,0,70,1.5,3007], + [126.29,126.528,56,92,5,1,70,1.5,3007], + [126.29,126.411,46,82,15,0,70,1.5,3007], + [126.292,126.528,52,96,5,0,70,1.5,3007], + [126.293,126.411,64,70,4,0,70,1.5,3007], + [126.295,126.528,59,97,5,2,70,1.5,3007], + [126.408,126.528,59,74,4,0,70,1.75,3010], + [126.409,126.528,42,49,13,0,70,1.75,3010], + [126.415,126.528,40,90,8,0,70,1.75,3010], + [126.524,127.465,60,80,7,1,70,2,3012], + [126.525,127.465,60,90,6,1,70,2,3012], + [126.525,127.465,57,83,6,0,70,2,3013], + [126.525,126.879,72,93,0,0,70,2,3013], + [126.526,126.762,57,103,5,0,70,2,3013], + [126.526,126.645,57,94,4,0,70,2,3013], + [126.526,126.645,42,70,13,0,70,2,3013], + [126.527,126.879,84,105,2,0,70,2,3013], + [126.527,126.762,60,103,5,1,70,2,3013], + [126.528,126.645,36,111,10,0,70,2,3013], + [126.528,126.879,72,89,3,0,70,2,3013], + [126.529,127.465,64,75,7,2,70,2,3013], + [126.529,127.465,64,86,6,2,70,2,3013], + [126.53,126.762,64,104,5,2,70,2,3013], + [126.53,127.465,57,75,7,0,70,2,3013], + [126.53,127.465,33,92,9,0,70,2,3013], + [126.643,126.762,42,40,13,0,70,2.25,3015], + [126.647,126.762,60,74,4,0,70,2.25,3015], + [126.647,126.762,45,97,8,0,70,2.25,3015], + [126.761,126.879,46,86,15,0,70,2.5,3018], + [126.763,126.879,64,72,4,0,70,2.5,3018], + [126.765,126.879,45,83,8,0,70,2.5,3018], + [126.876,126.996,42,48,13,0,70,2.75,3021], + [126.877,126.996,64,87,3,0,70,2.75,3021], + [126.877,127.114,57,91,5,0,70,2.75,3021], + [126.877,126.996,45,91,8,0,70,2.75,3021], + [126.877,126.996,69,75,4,0,70,2.75,3021], + [126.878,126.996,76,104,2,0,70,2.75,3021], + [126.879,127.114,64,88,5,2,70,2.75,3021], + [126.88,127.114,60,87,5,1,70,2.75,3021], + [126.882,126.996,64,88,0,0,70,2.75,3021], + [126.994,127.114,36,109,10,0,70,3,3024], + [126.994,127.465,88,106,2,0,70,3,3024], + [126.994,127.114,39,105,12,0,70,3,3024], + [126.996,127.114,42,63,13,0,70,3,3024], + [126.997,127.465,76,88,0,0,70,3,3024], + [126.998,127.465,76,91,3,0,70,3,3024], + [126.998,127.114,72,95,4,0,70,3,3024], + [127.112,127.231,76,74,4,0,70,3.25,3026], + [127.113,127.231,42,43,13,0,70,3.25,3027], + [127.115,127.231,45,101,8,0,70,3.25,3027], + [127.23,127.465,60,95,5,1,70,3.5,3029], + [127.23,127.465,64,98,5,2,70,3.5,3029], + [127.23,127.348,46,84,15,0,70,3.5,3029], + [127.231,127.348,69,76,4,0,70,3.5,3029], + [127.231,127.348,45,84,8,0,70,3.5,3029], + [127.232,127.465,57,93,5,0,70,3.5,3029], + [127.347,127.465,42,52,13,0,70,3.75,3032], + [127.347,127.465,45,90,8,0,70,3.75,3032], + [127.349,127.465,64,76,4,0,70,3.75,3032], + [127.462,127.7,56,99,5,1,71,0,3035], + [127.462,127.582,52,95,4,0,71,0,3035], + [127.463,127.582,88,106,2,0,71,0,3035], + [127.464,128.403,52,86,6,0,71,0,3035], + [127.464,128.403,56,87,6,1,71,0,3035], + [127.465,127.582,36,113,10,0,71,0,3035], + [127.465,128.403,28,93,9,0,71,0,3035], + [127.465,127.582,76,93,0,0,71,0,3035], + [127.465,127.582,76,89,3,0,71,0,3035], + [127.465,127.582,42,65,13,0,71,0,3035], + [127.466,128.403,52,72,7,0,71,0,3035], + [127.467,128.403,56,79,7,1,71,0,3035], + [127.467,127.7,52,105,5,0,71,0,3035], + [127.468,128.403,59,77,7,2,71,0,3035], + [127.468,128.403,59,84,6,2,71,0,3035], + [127.468,127.7,59,103,5,2,71,0,3035], + [127.581,127.7,56,73,4,0,71,0.25,3038], + [127.582,127.7,87,109,2,0,71,0.25,3038], + [127.583,127.7,42,39,13,0,71,0.25,3038], + [127.583,127.7,75,91,0,0,71,0.25,3038], + [127.584,127.7,40,101,8,0,71,0.25,3038], + [127.585,127.7,75,91,3,0,71,0.25,3038], + [127.697,127.817,59,72,4,0,71,0.5,3040], + [127.698,127.817,40,82,8,0,71,0.5,3040], + [127.7,127.817,76,92,3,0,71,0.5,3040], + [127.7,127.817,76,91,0,0,71,0.5,3040], + [127.701,127.817,46,88,15,0,71,0.5,3040], + [127.701,127.817,88,108,2,0,71,0.5,3041], + [127.816,128.051,52,86,5,0,71,0.75,3043], + [127.817,128.051,56,86,5,1,71,0.75,3043], + [127.817,127.934,75,93,3,0,71,0.75,3043], + [127.817,127.934,75,91,0,0,71,0.75,3043], + [127.818,127.934,42,49,13,0,71,0.75,3043], + [127.818,127.934,87,105,2,0,71,0.75,3043], + [127.818,127.934,64,74,4,0,71,0.75,3043], + [127.818,127.934,40,93,8,0,71,0.75,3043], + [127.819,128.051,59,87,5,2,71,0.75,3043], + [127.93,128.051,39,99,12,0,71,1,3046], + [127.932,128.051,68,94,4,0,71,1,3046], + [127.934,128.051,76,89,3,0,71,1,3046], + [127.934,128.051,88,107,2,0,71,1,3046], + [127.935,128.051,42,62,13,0,71,1,3046], + [127.935,128.051,36,110,10,0,71,1,3046], + [127.937,128.051,76,94,0,0,71,1,3046], + [128.047,128.168,71,88,0,0,71,1.25,3049], + [128.049,128.168,71,72,4,0,71,1.25,3049], + [128.05,128.168,40,97,8,0,71,1.25,3049], + [128.052,128.168,83,108,2,0,71,1.25,3049], + [128.052,128.168,42,39,13,0,71,1.25,3049], + [128.053,128.168,71,92,3,0,71,1.25,3049], + [128.167,128.286,40,87,8,0,71,1.5,3052], + [128.168,128.403,59,96,5,2,71,1.5,3052], + [128.169,128.286,86,106,2,0,71,1.5,3052], + [128.169,128.403,56,98,5,1,71,1.5,3052], + [128.17,128.286,64,78,4,0,71,1.5,3052], + [128.17,128.286,74,93,0,0,71,1.5,3052], + [128.17,128.286,74,89,3,0,71,1.5,3052], + [128.171,128.403,52,96,5,0,71,1.5,3052], + [128.171,128.286,46,83,15,0,71,1.5,3052], + [128.283,128.403,72,89,0,0,71,1.75,3054], + [128.285,128.403,42,48,13,0,71,1.75,3054], + [128.287,128.403,72,91,3,0,71,1.75,3054], + [128.287,128.403,84,103,2,0,71,1.75,3054], + [128.287,128.403,59,73,4,0,71,1.75,3054], + [128.287,128.403,40,90,8,0,71,1.75,3054], + [128.398,128.637,64,104,5,2,71,2,3057], + [128.398,129.34,57,84,6,0,71,2,3057], + [128.4,128.637,57,101,5,0,71,2,3057], + [128.401,129.34,64,87,6,2,71,2,3057], + [128.401,129.34,60,84,6,1,71,2,3057], + [128.401,128.52,42,68,13,0,71,2,3057], + [128.401,129.34,33,87,9,0,71,2,3057], + [128.402,128.637,60,106,5,1,71,2,3057], + [128.402,128.52,57,91,4,0,71,2,3057], + [128.402,129.34,60,77,7,1,71,2,3057], + [128.402,129.34,64,76,7,2,71,2,3057], + [128.403,128.754,81,106,2,0,71,2,3057], + [128.403,128.754,69,88,0,0,71,2,3057], + [128.403,128.52,36,107,10,0,71,2,3057], + [128.403,129.34,57,72,7,0,71,2,3057], + [128.405,128.754,69,90,3,0,71,2,3057], + [128.518,128.637,45,102,8,0,71,2.25,3060], + [128.518,128.637,60,74,4,0,71,2.25,3060], + [128.519,128.637,42,39,13,0,71,2.25,3060], + [128.634,128.754,46,84,15,0,71,2.5,3063], + [128.636,128.754,45,85,8,0,71,2.5,3063], + [128.639,128.754,64,75,4,0,71,2.5,3063], + [128.754,128.871,60,90,0,0,71,2.75,3066], + [128.755,128.989,60,86,5,1,71,2.75,3066], + [128.755,128.871,45,91,8,0,71,2.75,3066], + [128.755,128.989,57,84,5,0,71,2.75,3066], + [128.755,128.989,64,86,5,2,71,2.75,3066], + [128.756,128.871,60,90,3,0,71,2.75,3066], + [128.757,128.871,69,73,4,0,71,2.75,3066], + [128.757,128.871,72,110,2,0,71,2.75,3066], + [128.758,128.871,42,49,13,0,71,2.75,3066], + [128.868,128.989,64,89,0,0,71,3,3068], + [128.869,128.989,72,94,4,0,71,3,3068], + [128.87,128.989,36,106,10,0,71,3,3068], + [128.871,128.989,42,62,13,0,71,3,3068], + [128.871,128.989,39,102,12,0,71,3,3068], + [128.872,128.989,64,92,3,0,71,3,3068], + [128.874,128.989,76,109,2,0,71,3,3068], + [128.987,129.34,69,92,0,0,71,3.25,3071], + [128.988,129.106,76,73,4,0,71,3.25,3071], + [128.989,129.34,81,105,2,0,71,3.25,3071], + [128.989,129.106,45,99,8,0,71,3.25,3071], + [128.991,129.106,42,37,13,0,71,3.25,3071], + [128.992,129.34,69,89,3,0,71,3.25,3071], + [129.102,129.34,60,93,5,1,71,3.5,3074], + [129.103,129.223,69,72,4,0,71,3.5,3074], + [129.104,129.34,64,96,5,2,71,3.5,3074], + [129.105,129.223,45,84,8,0,71,3.5,3074], + [129.107,129.223,46,83,15,0,71,3.5,3074], + [129.109,129.34,57,96,5,0,71,3.5,3074], + [129.221,129.34,64,74,4,0,71,3.75,3077], + [129.221,129.34,45,88,8,0,71,3.75,3077], + [129.223,129.34,42,53,13,0,71,3.75,3077], + [129.337,129.692,83,107,2,0,72,0,3079], + [129.338,130.278,52,90,6,0,72,0,3079], + [129.338,129.457,52,94,4,0,72,0,3079], + [129.338,129.457,36,111,10,0,72,0,3079], + [129.339,129.575,52,104,5,0,72,0,3080], + [129.339,130.278,56,88,6,1,72,0,3080], + [129.34,130.278,56,76,7,1,72,0,3080], + [129.34,130.278,59,77,7,2,72,0,3080], + [129.34,130.278,28,90,9,0,72,0,3080], + [129.34,129.575,59,102,5,2,72,0,3080], + [129.34,130.278,52,76,7,0,72,0,3080], + [129.342,129.457,42,71,13,0,72,0,3080], + [129.342,129.692,71,92,3,0,72,0,3080], + [129.342,129.457,38,70,14,0,72,0,3080], + [129.342,130.278,59,84,6,2,72,0,3080], + [129.343,129.692,71,88,0,0,72,0,3080], + [129.346,129.575,56,102,5,1,72,0,3080], + [129.456,129.575,40,99,8,0,72,0.25,3082], + [129.459,129.575,38,74,14,0,72,0.25,3082], + [129.459,129.575,42,40,13,0,72,0.25,3082], + [129.46,129.575,56,78,4,0,72,0.25,3082], + [129.573,129.692,59,75,4,0,72,0.5,3085], + [129.576,129.692,46,87,15,0,72,0.5,3085], + [129.576,129.692,40,84,8,0,72,0.5,3085], + [129.577,129.692,38,80,14,0,72,0.5,3085], + [129.688,129.926,56,87,5,1,72,0.75,3088], + [129.689,129.926,52,89,5,0,72,0.75,3088], + [129.69,129.809,64,72,4,0,72,0.75,3088], + [129.69,129.809,76,109,2,0,72,0.75,3088], + [129.691,129.809,42,52,13,0,72,0.75,3088], + [129.691,129.809,64,88,3,0,72,0.75,3088], + [129.693,129.809,40,93,8,0,72,0.75,3088], + [129.694,129.926,59,91,5,2,72,0.75,3088], + [129.694,129.809,64,90,0,0,72,0.75,3088], + [129.695,129.809,38,83,14,0,72,0.75,3088], + [129.807,129.926,84,102,2,0,72,1,3091], + [129.808,129.926,42,68,13,0,72,1,3091], + [129.808,129.926,72,94,3,0,72,1,3091], + [129.808,129.926,38,85,14,0,72,1,3091], + [129.808,129.926,68,93,4,0,72,1,3091], + [129.809,129.926,36,108,10,0,72,1,3091], + [129.809,129.926,72,88,0,0,72,1,3091], + [129.811,129.926,39,101,12,0,72,1,3091], + [129.924,130.278,71,90,3,0,72,1.25,3093], + [129.925,130.278,71,89,0,0,72,1.25,3093], + [129.925,130.278,83,103,2,0,72,1.25,3093], + [129.926,130.043,40,104,8,0,72,1.25,3093], + [129.927,130.043,71,71,4,0,72,1.25,3093], + [129.927,130.043,38,92,14,0,72,1.25,3093], + [129.927,130.043,42,42,13,0,72,1.25,3094], + [130.041,130.278,59,94,5,2,72,1.5,3096], + [130.041,130.161,64,76,4,0,72,1.5,3096], + [130.042,130.161,46,87,15,0,72,1.5,3096], + [130.042,130.278,52,99,5,0,72,1.5,3096], + [130.043,130.161,40,82,8,0,72,1.5,3096], + [130.043,130.278,56,98,5,1,72,1.5,3096], + [130.046,130.161,38,98,14,0,72,1.5,3096], + [130.161,130.278,42,47,13,0,72,1.75,3099], + [130.161,130.278,38,99,14,0,72,1.75,3099], + [130.162,130.278,40,95,8,0,72,1.75,3099], + [130.163,130.278,59,72,4,0,72,1.75,3099], + [130.274,131.215,60,86,6,1,72,2,3102], + [130.274,130.512,60,103,5,1,72,2,3102], + [130.275,131.215,33,91,9,0,72,2,3102], + [130.275,131.215,69,92,3,0,72,2,3102], + [130.276,130.512,57,101,5,0,72,2,3102], + [130.277,131.215,60,78,7,1,72,2,3102], + [130.277,131.215,64,76,7,2,72,2,3102], + [130.277,130.395,42,73,13,0,72,2,3102], + [130.278,131.215,57,85,6,0,72,2,3102], + [130.278,130.395,38,103,14,0,72,2,3102], + [130.278,130.512,64,103,5,2,72,2,3102], + [130.278,130.395,57,96,4,0,72,2,3102], + [130.278,130.395,36,113,10,0,72,2,3102], + [130.279,131.215,64,90,6,2,72,2,3102], + [130.279,131.215,69,93,0,0,72,2,3102], + [130.28,131.215,57,77,7,0,72,2,3102], + [130.28,131.215,81,105,2,0,72,2,3102], + [130.392,130.512,45,102,8,0,72,2.25,3105], + [130.393,130.512,38,105,14,0,72,2.25,3105], + [130.395,130.512,60,77,4,0,72,2.25,3105], + [130.396,130.512,42,42,13,0,72,2.25,3105], + [130.51,130.629,64,72,4,0,72,2.5,3107], + [130.511,130.629,38,108,14,0,72,2.5,3107], + [130.512,130.629,46,89,15,0,72,2.5,3107], + [130.517,130.629,45,87,8,0,72,2.5,3108], + [130.627,130.746,69,72,4,0,72,2.75,3110], + [130.627,130.864,60,87,5,1,72,2.75,3110], + [130.627,130.746,38,110,14,0,72,2.75,3110], + [130.628,130.864,64,85,5,2,72,2.75,3110], + [130.628,130.746,42,47,13,0,72,2.75,3110], + [130.63,130.746,45,90,8,0,72,2.75,3110], + [130.631,130.864,57,91,5,0,72,2.75,3110], + [130.744,130.864,36,106,10,0,72,3,3113], + [130.745,130.864,72,96,4,0,72,3,3113], + [130.745,130.864,42,65,13,0,72,3,3113], + [130.746,130.864,38,116,14,0,72,3,3113], + [130.746,130.864,39,104,12,0,72,3,3113], + [130.86,130.981,42,44,13,0,72,3.25,3116], + [130.862,130.981,76,77,4,0,72,3.25,3116], + [130.863,130.981,45,102,8,0,72,3.25,3116], + [130.865,130.981,38,124,14,0,72,3.25,3116], + [130.977,131.215,60,94,5,1,72,3.5,3119], + [130.979,131.215,57,98,5,0,72,3.5,3119], + [130.98,131.215,64,98,5,2,72,3.5,3119], + [130.981,131.098,38,123,14,0,72,3.5,3119], + [130.982,131.098,45,89,8,0,72,3.5,3119], + [130.983,131.098,46,82,15,0,72,3.5,3119], + [130.985,131.098,69,75,4,0,72,3.5,3119], + [131.094,131.215,42,51,13,0,72,3.75,3121], + [131.097,131.215,45,91,8,0,72,3.75,3121], + [131.101,131.215,64,76,4,0,72,3.75,3121], + [131.101,131.215,38,127,14,0,72,3.75,3121], + [131.213,131.684,81,112,2,0,73,0,3124], + [131.214,131.332,36,124,17,0,73,0,3124], + [131.214,131.684,60,119,5,1,73,0,3124], + [131.214,131.684,64,115,5,2,73,0,3124], + [131.215,131.684,33,114,8,0,73,0,3124], + [131.216,131.684,69,114,3,0,73,0,3124], + [131.216,131.332,45,119,11,0,73,0,3124], + [131.216,132.153,33,98,9,0,73,0,3124], + [131.217,131.332,36,118,10,0,73,0,3124], + [131.217,131.684,69,112,0,0,73,0,3124], + [131.218,131.684,57,115,5,0,73,0,3124], + [132.415,132.672,76,64,0,0,74,0,3153], + [132.671,132.926,75,56,0,0,74,0.5,3159], + [132.921,133.183,76,62,0,0,74,1,3165], + [133.189,133.443,71,61,0,0,74,1.5,3171], + [133.445,133.706,74,55,0,0,74,2,3177], + [133.707,133.973,72,56,0,0,74,2.5,3184], + [133.976,134.52,69,58,0,0,75,0,3190], + [133.984,134.251,45,43,1,0,75,0,3190], + [134.253,134.528,52,43,1,0,75,0.5,3196], + [134.53,134.81,57,43,1,0,75,1,3203], + [134.801,135.091,60,44,0,0,75,1.5,3210], + [135.089,135.387,64,53,0,0,75,2,3216], + [135.386,135.689,69,57,0,0,75,2.5,3223], + [135.693,136.33,71,59,0,0,76,0,3231], + [135.693,136.01,40,42,1,0,76,0,3231], + [136.018,136.338,52,40,1,0,76,0.5,3239], + [136.344,136.682,56,44,1,0,76,1,3246], + [136.671,137.035,64,25,0,0,76,1.5,3254], + [137.033,137.419,72,29,0,0,76,2,3263], + [137.416,137.831,71,18,0,0,76,2.5,3272], + [137.835,140.41,45,23,1,1,77,0,3282], + [137.836,140.402,69,27,0,0,77,0,3282], + [137.843,140.41,33,20,1,0,77,0,3282], +]; +/** + * The big hits, for flashes: [at, frame, strength, part] — every impact, and the low drums' and cymbals' strokes struck + * at velocity 110 or more (the kick left out: it is on every pulse, but for its downbeat on each drop); strength 0 … 1 (velocity / 127), 1 on a drop's downbeat. + */ +export const HIT_AT = 0, HIT_FRAME = 1, HIT_STRENGTH = 2, HIT_PART = 3; +export const HITS: readonly (readonly number[])[] = [ + [13.088,312,1,10], + [13.091,312,1,17], + [13.094,312,1,16], + [28.085,669,0.9,16], + [33.716,803,0.87,16], + [58.089,1383,1,17], + [58.089,1383,0.91,16], + [58.091,1383,0.94,11], + [65.593,1562,0.9,16], + [73.088,1740,0.9,16], + [73.089,1740,0.91,17], + [73.094,1740,0.93,11], + [80.591,1919,0.94,16], + [87.151,2075,0.93,11], + [103.089,2454,1,17], + [103.093,2455,0.94,16], + [118.09,2812,0.87,16], + [123.716,2946,0.91,16], + [131.214,3124,0.98,17], + [131.216,3124,0.94,11], +]; diff --git a/probes/lib/fur-elise-remix.ts b/probes/lib/fur-elise-remix.ts new file mode 100644 index 0000000..8636013 --- /dev/null +++ b/probes/lib/fur-elise-remix.ts @@ -0,0 +1,144 @@ +// Für Elise, the trance remix, rendered when the script is built (probes/lib/fur-elise-remix-score.ts is the notes). +// Importing this starts nothing: probes/fur-elise-remix.ts plays it; a showcase program imports `whole`. +// +// Three performances end to end: the piano's intro (3/8, free in time), the remix (4/4, 128 a minute), the piano's +// ending (3/8). The melody first, by construction and by measurement (scripts/lead-check.mts): each remix section +// mixed as three stems — the melody (the lead synth, its lower octave, the piano), the harmony under it (pads, stabs, +// arpeggios, strings, the piano's left hand) ducked by the melody's own envelope and dipped where the melody sits, and +// the rhythm (bass, sub, drums, effects) — then through a bus, each section to its loudness, the whole limited once. +// +// Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). Strings, crash, timpani: VSCO 2 Community Edition by +// Versilian Studios (CC0). Everything else made in the script. +import { music, type Instrument } from "trigscript/music"; +import piano from "../salamander-grand.samples"; +import violasSet from "../vsco-violas.samples"; +import timpaniSet from "../vsco-timpani.samples"; +import percussionSet from "../vsco-percussion.samples"; +import { remix, REMIX_ROLES, MELODY, HARMONY, EFFECTS, INTRO_RIGHT, INTRO_LEFT, INTRO_TEMPO, OUTRO_RIGHT, OUTRO_LEFT, OUTRO_TEMPO, type RemixPart } from "./fur-elise-remix-score"; + +const BPM = 128, BEAT = 60 / BPM, BAR = 4 * BEAT; +const ROOM = { decay: 0.78, damping: 0.5, predelay: 0.02 }; +const HALL = { decay: 0.84, damping: 0.5, predelay: 0.032 }; +const MASTER = (c: Clip) => c.filter("highpass", 28); +const BUS = (c: Clip) => MASTER(c).compress({ threshold: -16, ratio: 2, attack: 0.02, release: 0.2, knee: 6 }); +const QUALITY = 6; +/** + * How far the harmony goes down under the melody, and the effects; where the melody's range is dipped in both. Set by + * scripts/lead-check.mts until the melody stands 6 dB over the rest in its range in every bar it plays. + */ +const DUCK = { depth: 6, threshold: -30, attack: 0.006, release: 0.2 }; +const DUCK_FX = { depth: 6, threshold: -30, attack: 0.006, release: 0.2 }; +const DIP = (c: Clip) => c.filter("peak", 1800, { gain: -5, q: 0.5 }).filter("peak", 3500, { gain: -3, q: 0.8 }); +/** Each section's loudness: the drops loud, the storm's the loudest, the piano's ends quiet. */ +const TARGET: Readonly> = { + intro: -20, "drop 1": -10.8, "breakdown 1": -15, "build 1": -13, "drop 2": -10.4, "breakdown 2": -15, "build 2": -13, "drop 3": -10.5, ending: -20, +}; + +export const arrangement = remix(); +const grand = music.sampled(piano, { resonance: 0.07 }); +const kit = music.drums({ volume: 0.9 }); +const dance = music.hits({ C2: kit.hits.k, D2: kit.hits.s, "D#2": kit.hits.c, "F#2": kit.hits.h, "A#2": kit.hits.o }); +const crashBack = (seconds: number) => (percussionSet.zones.find((z) => z.key === 49 && z.vhi === 127) ?? percussionSet.zones[0]).clip.trim(0, seconds).reverse().fade(Math.min(0.5, seconds / 2), 0.004); +const fx = music.hits({ + C2: music.impact({ seconds: 2.5, volume: 0.9 }).mix(tone([[0, 70], [1.4, 30]], 1.8, { volume: 0.8, rate: 44100 }).envelope([0, 0], [0.01, 1], [1.8, 0])), + // (The sweeps and the crash reversed above the melody's range: they are air, not notes.) + E2: music.sweep(BAR, { down: true, volume: 0.3 }).filter("highpass", 3500), F2: crashBack(BAR).filter("highpass", 4500), + G2: music.riser(3 * BAR, { volume: 0.4 }).filter("highpass", 900).mix(music.sweep(3 * BAR, { volume: 0.25 }).filter("highpass", 2500)), +}); + +/** How each part of the remix is heard. Volumes balanced by measuring (see the plan's S7 remix section). */ +const PUMP = music.pump(BEAT, 0.6, 0.6); +const heard: Record Clip; velocity?: number }> = { + piano: { instrument: grand, volume: 1.2, reverb: 0.2 }, + pianoLH: { instrument: grand }, + lead: { instrument: music.presets.trance(), volume: 1.0, reverb: 0.25, fx: (c) => c.delay(BEAT * 0.75, { feedback: 0.3, mix: 0.18, pingPong: true, tone: 4500 }) }, + leadLow: { instrument: music.presets.lead({ volume: 0.12 }), volume: 0.8, reverb: 0.2 }, + arp: { instrument: music.presets.arp(), pan: 0.25, volume: 0.8, reverb: 0.2, fx: (c) => PUMP(c.delay(BEAT * 0.75, { feedback: 0.25, mix: 0.2, pingPong: true })) }, + stabs: { instrument: music.presets.stab(), volume: 0.9, reverb: 0.25, fx: PUMP }, + pad: { instrument: music.presets.pad({ volume: 0.07 }), reverb: 0.4, fx: PUMP }, + strings: { instrument: music.sampled(violasSet), volume: 1.4, reverb: 0.4 }, + bass: { instrument: music.presets.bass({ volume: 0.3 }), volume: 0.9, fx: (c) => PUMP(c.filter("lowpass", 700)) }, + sub: { instrument: music.presets.sub(), volume: 0.35, fx: PUMP }, + kick: { instrument: dance, volume: 0.7 }, + timpani: { instrument: music.sampled(timpaniSet), volume: 0.8, reverb: 0.4 }, + clap: { instrument: dance, volume: 0.55, reverb: 0.25 }, + hats: { instrument: dance, pan: 0.2, volume: 0.35 }, + snare: { instrument: dance, volume: 0.55, reverb: 0.2 }, + openHats: { instrument: dance, pan: -0.15, volume: 0.4 }, + crash: { instrument: music.sampled(percussionSet, { releases: false }), volume: 0.55, reverb: 0.3 }, + impacts: { instrument: fx, volume: 0.42, reverb: 0.3 }, + risers: { instrument: fx, volume: 0.7, reverb: 0.3 }, +}; +const parts: Record = {}; +for (const k of Object.keys(REMIX_ROLES) as RemixPart[]) parts[k] = { ...heard[k], notes: arrangement.parts[k] }; +/** The remix as played, from its first drop's downbeat. */ +export const take = music.perform({ meter: "4/4", bpm: BPM, humanize: { time: 0.002, velocity: 2, seed: 3 } }, parts as never); + +/** The piano's intro, played once to learn its free time, then with its sweep and suck-in made to end on the drop. */ +const introOf = (sweepSeconds: number, suck: number) => music.perform({ meter: "3/8", bpm: 120, pickup: "1/8", tempo: INTRO_TEMPO, humanize: { time: 0.004, velocity: 3, seed: 7 } }, { + piano: { instrument: grand, notes: INTRO_RIGHT, lead: 0.008, reverb: 0.24 }, + pianoLH: { instrument: grand, notes: INTRO_LEFT, velocity: 0.82 }, + pad: { instrument: music.presets.pad({ volume: 0.035 }), reverb: 0.5, notes: ["r/8", "r/4.", "r/4.", "r/4.", "r/4.", "pp < A2+E3/4.~", "A2+E3/4.", "r/4.", "pp E3+G#3+B3/4."] }, + risers: { instrument: music.hits({ C2: music.sweep(sweepSeconds, { volume: 0.32 }).filter("highpass", 5000), D2: crashBack(suck).filter("highpass", 5500) }), volume: 0.8, notes: ["r/8", "r/4.", "r/4.", "r/4.", "r/4.", "r/4.", "C2/4.", "r/4.", "D2/4."] }, +}); +const rehearsal = introOf(4, 1); +export const intro = introOf(rehearsal.bars[9] - rehearsal.bars[6], rehearsal.bars[9] - rehearsal.bars[8]); +export const outro = music.perform({ meter: "3/8", bpm: 120, tempo: OUTRO_TEMPO, humanize: { time: 0.004, velocity: 3, seed: 9 } }, { + piano: { instrument: grand, notes: OUTRO_RIGHT, lead: 0.008, reverb: 0.24 }, + pianoLH: { instrument: grand, notes: OUTRO_LEFT, velocity: 0.92 }, +}); + +/** Where each performance begins in the whole: the drop on the intro's last bar line; the ending on the remix's. */ +export const DROP_AT = intro.bars[9]; +/** (A breath before the ending: the last hit's tail under way before the piano comes back alone.) */ +export const OUTRO_AT = DROP_AT + take.bars[arrangement.bars] + 1.2; +/** The sections, in the whole: name, kind, where in seconds and frames, and the bar numbers of the whole they span. */ +export const sections = [ + { name: "intro", kind: "intro", at: 0, from: 0, to: 9 }, + ...arrangement.sections.map((s) => ({ name: s.name, kind: s.name.split(" ")[0], at: DROP_AT + take.bars[s.from], from: 9 + s.from, to: 9 + s.to })), + { name: "ending", kind: "ending", at: OUTRO_AT, from: 9 + arrangement.bars, to: 9 + arrangement.bars + 4 }, +].map((s) => ({ ...s, frame: Math.round(s.at / 0.042) })); + +/* ── Mixed: the melody, the harmony under it, the rhythm ── */ + +const ALL = Object.keys(REMIX_ROLES) as RemixPart[]; +const RHYTHM = ALL.filter((k) => !MELODY.includes(k) && !HARMONY.includes(k) && !EFFECTS.includes(k)); +type Stems = { melody: Clip; harmony: Clip; effects: Clip; rhythm: Clip }; +type Raw = { melody: Clip; harmony: Clip; effects: Clip; rhythm: Clip; at: number }; +function rawOf(p: typeof take, room: typeof ROOM, has: readonly string[], at: number): Raw { + const pick = (list: readonly RemixPart[]) => list.filter((k) => has.includes(k)); + return { + melody: music.render(p, { parts: pick(MELODY), reverb: room, limit: false }), + harmony: DIP(music.render(p, { parts: pick(HARMONY), reverb: room, limit: false })), + effects: DIP(music.render(p, { parts: pick(EFFECTS), reverb: room, limit: false })), + rhythm: music.render(p, { parts: pick(RHYTHM), reverb: room, limit: false }), at, + }; +} +const raws: Raw[] = [ + rawOf(intro, HALL, ["piano", "pianoLH", "pad", "risers"], 0), + ...arrangement.sections.map((s, k) => rawOf(music.excerpt(take, s.from, k + 1 < arrangement.sections.length ? s.to : undefined), ROOM, ALL, sections[k + 1].at)), + rawOf(outro, HALL, ["piano", "pianoLH"], OUTRO_AT), +]; +// The harmony and the effects ducked by the whole melody, not only their own section's: a section's tail rings under +// the next section's melody, and goes down for it too. +const melodyAll = mixdown(raws.map((r) => ({ clip: r.melody, at: r.at }))); +const keyFrom = (at: number, seconds: number) => melodyAll.trim(Math.min(at, melodyAll.seconds - 0.01), Math.min(melodyAll.seconds, at + seconds)); +const allStems: Stems[] = raws.map((r) => ({ + melody: r.melody, rhythm: r.rhythm, + harmony: r.harmony.duck(keyFrom(r.at, r.harmony.seconds), DUCK), + effects: r.effects.duck(keyFrom(r.at, r.effects.seconds), DUCK_FX), +})); + +const mixes = allStems.map((st, k) => { + const sum = mixdown([{ clip: st.melody, at: 0 }, { clip: st.harmony, at: 0 }, { clip: st.effects, at: 0 }, { clip: st.rhythm, at: 0 }]); + const kind = sections[k].kind; + return (kind === "intro" || kind === "ending" ? MASTER(sum) : BUS(sum)).loudness(TARGET[sections[k].name]); +}); + +/** The whole piece, one clip, limited once. */ +export const whole = mixdown(mixes.map((c, k) => ({ clip: c, at: sections[k].at }))).limit({ ceiling: 0.8 }).ogg(QUALITY); +/** Each section with its tail, at its level: the fallback. */ +export const sectionClips = mixes.map((c) => c.limit({ ceiling: 0.8 }).ogg(QUALITY)); +/** The melody and everything else, apart, at the same places (before the sections' levels: the ratio is what counts). */ +export const melodyStem = mixdown(allStems.map((st, k) => ({ clip: st.melody, at: sections[k].at }))).ogg(8); +export const restStem = mixdown(allStems.map((st, k) => ({ clip: mixdown([{ clip: st.harmony, at: 0 }, { clip: st.effects, at: 0 }, { clip: st.rhythm, at: 0 }]), at: sections[k].at }))).ogg(8); diff --git a/probes/lib/fur-elise-timeline-gen.mts b/probes/lib/fur-elise-timeline-gen.mts index 92b181f..41a8944 100644 --- a/probes/lib/fur-elise-timeline-gen.mts +++ b/probes/lib/fur-elise-timeline-gen.mts @@ -5,6 +5,7 @@ // // npx tsx probes/lib/fur-elise-timeline-gen.mts # the straight soundtrack: fur-elise-timeline.ts // npx tsx probes/lib/fur-elise-timeline-gen.mts --cinematic # the cinematic arrangement: fur-elise-cinematic-timeline.ts +// npx tsx probes/lib/fur-elise-timeline-gen.mts --remix # the trance remix: fur-elise-remix-timeline.ts import { writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; @@ -14,12 +15,27 @@ import { defaultLib } from "../../bundle/lib.mjs"; import { scriptFiles } from "../../scripts/script-files.mts"; const root = join(import.meta.dirname, "..", ".."); -const cinematic = process.argv.includes("--cinematic"); -const files = scriptFiles(join(root, "probes", cinematic ? "fur-elise-cinematic.ts" : "fur-elise.ts")); +const cinematic = process.argv.includes("--cinematic"), remixed = process.argv.includes("--remix"); +const files = scriptFiles(join(root, "probes", remixed ? "fur-elise-remix.ts" : cinematic ? "fur-elise-cinematic.ts" : "fur-elise.ts")); // The build hands values back only in its words: the line it fails with carries them. (Added to the module that has // the performance, so the arrangement's roles are at hand.) -const into = cinematic ? "lib/fur-elise-cinematic.ts" : "main.ts"; -files[into] += ` +const into = remixed ? "lib/fur-elise-remix.ts" : cinematic ? "lib/fur-elise-cinematic.ts" : "main.ts"; +// The remix is three performances end to end (the piano's intro, the remix, its ending): put together here, each +// note's time and bar moved to where its performance begins in the whole. +if (remixed) files[into] += ` +const r3 = (x: number) => Math.round(x * 1000) / 1000; +const names = Object.keys(REMIX_ROLES); +const placed = [[intro, 0, 0], [take, DROP_AT, 9], [outro, OUTRO_AT, 9 + arrangement.bars]] as const; +const notes = placed.flatMap(([p, at, bar]) => p.notes.map((n) => [r3(n.at + at), r3(n.end + at), n.pitch, n.velocity, names.indexOf(n.part), n.voice, n.bar + bar, r3(n.beat), Math.round((n.at + at) / 0.042)])).sort((a, b) => a[0] - b[0]); +const bars = [...intro.bars.slice(0, 9), ...take.bars.slice(0, arrangement.bars).map((b) => b + DROP_AT), ...outro.bars.slice(0, 5).map((b) => b + OUTRO_AT)].map(r3); +throw new Error("TIMELINE " + JSON.stringify({ + seconds: r3(OUTRO_AT + outro.seconds), parts: names, roles: names.map((k) => (REMIX_ROLES as Record)[k]), bars, + pedal: [...intro.pedal.map((p) => [r3(p[0]), r3(p[1])]), ...outro.pedal.map((p) => [r3(p[0] + OUTRO_AT), r3(p[1] + OUTRO_AT)])], + sections: sections.map((s) => ({ name: s.name, kind: s.kind, bar: s.from, at: r3(s.at), frame: s.frame })), + notes, +})); +`; +else files[into] += ` const r3 = (x: number) => Math.round(x * 1000) / 1000; const roles = ${cinematic ? "take.parts.map((p) => (PART_ROLES as Record)[p])" : "take.parts.map((p) => ({ right: \"lead\", left: \"accomp\", violins: \"strings\", violas: \"strings\", celli: \"strings\", basses: \"bass\", horns: \"brass\", trombones: \"brass\", tuba: \"brass\", timpani: \"drum-low\", roll: \"drum-low\" } as Record)[p])"}; throw new Error("TIMELINE " + JSON.stringify({ @@ -31,14 +47,18 @@ throw new Error("TIMELINE " + JSON.stringify({ const r = compileScript(ts, files, defaultScriptNames(), { lib: defaultLib(), sounds: false }); const line = r.diagnostics.map((d) => d.message).find((m) => m.includes("TIMELINE ")); if (!line) { for (const d of r.diagnostics) console.error(d.message); process.exit(1); } -const t = JSON.parse(line.slice(line.indexOf("TIMELINE ") + 9)) as { seconds: number; parts: string[]; roles: string[]; bars: number[]; pedal: number[][]; sections: { name: string; bar: number; at: number; frame: number }[]; notes: number[][] }; +const t = JSON.parse(line.slice(line.indexOf("TIMELINE ") + 9)) as { seconds: number; parts: string[]; roles: string[]; bars: number[]; pedal: number[][]; sections: { name: string; kind?: string; bar: number; at: number; frame: number }[]; notes: number[][] }; const rows = (list: unknown[][]) => list.map((x) => ` ${JSON.stringify(x)},`).join("\n"); // The big hits, for a picture's flashes: every impact; the taiko, timpani and gong/crash strokes struck at 110 or more. const BIG = new Set(["impact"]), STRONG = new Set(["drum-low", "cymbal"]); -const hits = t.notes.filter((n) => BIG.has(t.roles[n[4]]) || (STRONG.has(t.roles[n[4]]) && t.parts[n[4]] !== "kick" && n[3] >= 110)) - .map((n) => [n[0], n[8], Math.round((n[3] / 127) * 100) / 100, n[4]]); -const text = `// Generated by probes/lib/fur-elise-timeline-gen.mts${cinematic ? " --cinematic" : ""} from probes/${cinematic ? "fur-elise-cinematic.ts" : "fur-elise.ts"}: do not edit, make it again. -// Für Elise ${cinematic ? "(the cinematic arrangement) " : ""}as the soundtrack plays it (the whole piece as one clip, from 0). Seconds from its start; a frame is 42 ms +const drops = t.sections.filter((x) => x.kind === "drop"); +const hits = t.notes.filter((n) => BIG.has(t.roles[n[4]]) || (STRONG.has(t.roles[n[4]]) && t.parts[n[4]] !== "kick" && n[3] >= 110) + // (In the remix the kick is every beat: its downbeats on a drop are the big ones.) + || (t.parts[n[4]] === "kick" && drops.some((d) => Math.abs(d.at - n[0]) < 0.05))) + .map((n) => [n[0], n[8], drops.some((d) => Math.abs(d.at - n[0]) < 0.05) ? 1 : Math.round((n[3] / 127) * 100) / 100, n[4]]); +const flagName = remixed ? " --remix" : cinematic ? " --cinematic" : "", source = remixed ? "fur-elise-remix.ts" : cinematic ? "fur-elise-cinematic.ts" : "fur-elise.ts"; +const text = `// Generated by probes/lib/fur-elise-timeline-gen.mts${flagName} from probes/${source}: do not edit, make it again. +// Für Elise ${remixed ? "(the trance remix: the piano's intro in 3/8, the remix in 4/4 at 128, the piano's ending in 3/8) " : cinematic ? "(the cinematic arrangement) " : ""}as the soundtrack plays it (the whole piece as one clip, from 0). Seconds from its start; a frame is 42 ms // (Fastest). The picture runs ahead of a long clip's sound by about 95 ms (the visualizer probe, 2026-11-09): the // program shifts the picture, not these numbers. @@ -47,14 +67,19 @@ export const SECONDS = ${t.seconds}; /** The parts, by the number NOTES gives them. */ export const PARTS = ${JSON.stringify(t.parts)} as const; /** - * Each part's role, by the same number: "lead" (the piano's right hand, the theme), "accomp" (its left hand)${cinematic ? `, + * Each part's role, by the same number: "lead" (the melody: the piano's right hand${remixed ? ", the lead synth" : ""}), "accomp" (the piano's left hand)${remixed ? `, + * "lead-synth" (the lead's octave below, doubling the melody), "arp" (the plucked arpeggios), "synth" (stabs), "pad", + * "strings", "bass" (rolling bass, sub), "drum-low" (kick, timpani), "drum-high" (clap, hats, snare), "cymbal" (open + * hats, crash), "impact", "riser" (risers, sweeps, crashes reversed)` : cinematic ? `, * "strings", "brass", "bass", "synth", "pad", "drum-low" (taiko, kick, timpani), "drum-high" (tenor drums, snare), * "cymbal" (crash, suspended cymbal, gong), "impact" (impacts and the sub drop), "riser" (risers, crashes reversed)` : `, * "strings", "bass", "brass", "drum-low" (the timpani)`}. */ export const ROLES = ${JSON.stringify(t.roles)} as const; -/** The sections, in order: the bar each begins on (BARS' numbering), and where, in seconds and frames. */ -export const SECTIONS: readonly { readonly name: string; readonly bar: number; readonly at: number; readonly frame: number }[] = ${JSON.stringify(t.sections)}; +/** The sections, in order${remixed ? " — kind 'intro', 'drop', 'breakdown', 'build' or 'ending'" : ""}: the bar each begins on (BARS' numbering), and where, in seconds and frames. */ +export const SECTIONS: readonly { readonly name: string;${remixed ? " readonly kind: string;" : ""} readonly bar: number; readonly at: number; readonly frame: number }[] = ${JSON.stringify(t.sections)};${remixed ? ` +/** The drops' downbeats, [at, frame]: the biggest moments (strength 1 in HITS too). */ +export const DROPS: readonly (readonly [number, number])[] = ${JSON.stringify(drops.map((d) => [d.at, d.frame]))};` : ""} /** Seconds each bar begins: [0] the pickup's start, [k] bar k's. */ export const BARS: readonly number[] = ${JSON.stringify(t.bars)}; /** The piano's sustain pedal: [down, up] in seconds. */ @@ -74,13 +99,13 @@ ${rows(t.notes)} ]; /** * The big hits, for flashes: [at, frame, strength, part] — every impact, and the low drums' and cymbals' strokes struck - * at velocity 110 or more (the kick left out: it is on every pulse); strength 0 … 1 (velocity / 127). + * at velocity 110 or more (the kick left out: it is on every pulse${remixed ? ", but for its downbeat on each drop" : ""}); strength 0 … 1 (velocity / 127)${remixed ? ", 1 on a drop's downbeat" : ""}. */ export const HIT_AT = 0, HIT_FRAME = 1, HIT_STRENGTH = 2, HIT_PART = 3; export const HITS: readonly (readonly number[])[] = [ ${rows(hits)} ]; `; -const out = cinematic ? "fur-elise-cinematic-timeline.ts" : "fur-elise-timeline.ts"; +const out = remixed ? "fur-elise-remix-timeline.ts" : cinematic ? "fur-elise-cinematic-timeline.ts" : "fur-elise-timeline.ts"; writeFileSync(join(root, "probes", "lib", out), text); console.log(`probes/lib/${out}: ${t.notes.length} notes, ${hits.length} hits, ${t.sections.length} sections, ${t.seconds} s`); From 9c4c42efa9aa2e8e42fb7de94aec66a624c5e791 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 12:38:46 -0600 Subject: [PATCH 29/31] =?UTF-8?q?F=C3=BCr=20Elise=20showcase=20on=20the=20?= =?UTF-8?q?trance=20remix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The switch has a third soundtrack, the remix, now the default (FUR_ELISE=cinematic or straight builds the others). A small LOOK per soundtrack says what the timeline does not: the storm section (the remix's drop 2), the big sections (its drops and builds) and the roles the main screen shows besides the piano (its stabs). Every "lead" part (the piano's right hand and the trance lead) is gold and drawn on top on both screens, the left hand cyan; in the drops and builds the stabs fall on the main screen in violet and the band on the minimap; the intro, breakdowns and ending show the piano alone. The storm's stab chords are red with the white keys flashing on each; the drops' downbeats and big impacts flash too and get the explosions, five Battlecruisers on the storm's. The cinematic and straight runs are unchanged. In the lifted game every frame of the remix holds the worked-out picture; 0.79 ms a frame at most. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- probes/answers/fur-elise-showcase.txt | 64 ++++++------ probes/fur-elise-showcase.ts | 18 ++-- probes/lib/fur-elise-showcase-choice.ts | 30 ++++-- probes/lib/fur-elise-showcase-run.ts | 128 ++++++++++++++---------- tests/fur-elise-showcase-run.test.ts | 31 ++++-- 5 files changed, 161 insertions(+), 110 deletions(-) diff --git a/probes/answers/fur-elise-showcase.txt b/probes/answers/fur-elise-showcase.txt index 9560e1c..18a6a36 100644 --- a/probes/answers/fur-elise-showcase.txt +++ b/probes/answers/fur-elise-showcase.txt @@ -1,10 +1,15 @@ -Für Elise, the showcase on the cinematic arrangement: a check play -================================================================= +Für Elise, the showcase on the trance remix: a check play +======================================================== Map: trigscript-fur-elise.scx (lobby "Für Elise"). About 2 minutes 40 seconds, nothing to press. -(trigscript-fur-elise-straight.scx beside it is the same showcase on the straight piece, 3:38, for comparison.) -Stills of what it should look like: fur-elise-showcase-frames.png beside the map (the minimap on the left, the main -screen on the right, as the build works them out — not the game's own drawing). +Beside it, for comparison: trigscript-fur-elise-cinematic.scx (the cinematic arrangement) and +trigscript-fur-elise-straight.scx (the piece as written). +Stills of what it should look like: fur-elise-showcase-frames.png (the minimap on the left, the main screen on the +right, as the build works them out — not the game's own drawing). + +Music: Für Elise by Ludwig van Beethoven (public domain); our transcription from the Breitkopf & Härtel edition of +1888, and our remix. Piano: Salamander Grand Piano V3 by Alexander Holm (CC BY 3.0). Orchestral and percussion +samples: VSCO 2 Community Edition by Versilian Studios (CC0). Made with TrigScript (scmjs.dev). What to record -------------- @@ -12,34 +17,27 @@ What to record - Options: game MUSIC OFF, sound effects ON (the piece plays as a sound effect). - Record the whole run, from the lobby to the end text and a few seconds after. Don't move the camera or click. -What is where -------------- -- Main screen: a keyboard of Flags, A1 to E7 (40 white keys, the black keys above them). The piano's notes fall onto - it, right hand gold, left hand cyan; each key lights in its hand's colour while it sounds. Only the piano is drawn - there, all the way through. -- Minimap: the same notes falling onto a keyboard row. In the storm and the final statement the rest of the band - (strings, brass, bass, synths, pads) falls in violet too, and the keyboard's front row pulses red on the biggest - drum hits. The intro and the ending show the piano alone. -- The storm (about 1:12 to 1:36): the right hand's chords red, the white keys flash red on each chord. -- Explosions, with the game's own explosion sounds (times from the start of the game, about): - 0:16 the band comes in (its first downbeat): Wraiths over the melody - 1:14 the storm's first big hit: three Battlecruisers - 1:24 the storm, the middle: Wraiths - 1:33 the storm's last big hit: three Battlecruisers - 1:42 the final statement begins (the theme returns): three Battlecruisers - 2:03 the final, a big bar: Wraiths - 2:16 the final's last big bar: Wraiths -- Text: "Für Elise" at the start; "Für Elise — Ludwig van Beethoven" when the last note is let go (about 2:28). - After that the keyboard stays and the game waits; leave when the sound has rung out. +What is where (times from the start of the game, about) +------------------------------------------------------ +- Main screen: a keyboard of Flags, A1 to E7 (40 white keys, the black keys above them). Notes fall onto it at half + speed: the melody gold (drawn on top), the piano's left hand cyan; in the drops the synth stabs too, violet. +- Minimap: the same, plus the rest of the band (arps, pads, strings, bass) in violet during the drops and builds. +- 0:00 the piano intro: calm, the piano alone. +- 0:17 drop 1: the band comes in. White keys flash red, three Battlecruisers explode. +- 0:45 breakdown 1 (calm), 0:52 build 1. +- 1:00 drop 2, the storm, the biggest: the stab chords red, the white keys flashing red on each chord, five + Battlecruisers on its downbeat; an impact with Wraiths at 1:17. +- 1:29 breakdown 2 (calm), 1:37 build 2. +- 1:45 drop 3: red flash, three Battlecruisers; Wraiths at 2:15. +- 2:16 the ending: the piano alone again, calm. +- 2:26 "Für Elise — Ludwig van Beethoven". The keyboard stays and the game waits; leave when the sound has rung out. +The explosions play the game's own explosion sounds over the music. What to look at --------------- -1. Do the notes land on the keys as you hear them (not early, not late)? The clip starts two frames before the - picture, to take up the ~95 ms the visualizer probe measured. -> -2. Does the main-screen keyboard fit in the view, both ends visible (A1 at the far left, E7 at the far right)? -> -3. Do the first text line and the end line show the ü and the dash (—) properly? -> -4. The explosions: the right moments, too many, too few? Are their sounds all right over this music? -> -5. The minimap in the storm and the final: does the violet band read well, or is it clutter? Do the red pulses on the - drum hits help? -> -6. Are the intro and the ending calm enough (only the piano)? -> -7. Any stray unit, a Flag or Overlord in the wrong place, an error text, a stutter or slowdown? -> +1. Do the notes land on the keys as you hear them, in the drops too (not early, not late)? -> +2. Is the melody (gold) easy to follow in the drops, over the violet stabs? -> +3. The storm (drop 2): red chords, red flashes, five Battlecruisers: right amount, too much, too little? -> +4. Are the intro, the breakdowns and the ending calm enough (the piano alone)? -> +5. The minimap in the drops: does the violet band read well, or is it clutter? -> +6. Any stray unit, a Flag or Overlord in the wrong place, an error text, a stutter or slowdown? -> diff --git a/probes/fur-elise-showcase.ts b/probes/fur-elise-showcase.ts index cb3b87c..0c57e2b 100644 --- a/probes/fur-elise-showcase.ts +++ b/probes/fur-elise-showcase.ts @@ -1,9 +1,9 @@ -// Für Elise, TrigScript Showcase #3: the whole piece as one clip — the cinematic arrangement (probes/lib/ -// fur-elise-cinematic.ts) or the straight piece (probes/lib/fur-elise-soundtrack.ts), as probes/lib/ -// fur-elise-showcase-choice.ts says (FUR_ELISE=straight when built under Node) — drawn as it plays: notes falling onto a -// keyboard on the minimap (Overlords over Space; the rest of the band in violet in the big sections) and on the main -// screen (Flag-looking Spider Mines, a row every other frame), right hand gold, left hand cyan, the storm's chords red -// with the white keys flashing red on each, explosions on the strongest moments. +// Für Elise, TrigScript Showcase #3: the whole piece as one clip — the trance remix (probes/lib/fur-elise-remix.ts), +// the cinematic arrangement (probes/lib/fur-elise-cinematic.ts) or the straight piece (probes/lib/fur-elise-soundtrack.ts), +// as probes/lib/fur-elise-showcase-choice.ts says (FUR_ELISE=cinematic or straight when built under Node) — drawn as it +// plays: notes falling onto a keyboard on the minimap (Overlords over Space; the rest of the band in violet in the big +// sections) and on the main screen (Flag-looking Spider Mines, a row every other frame), the melody gold on top, the +// left hand cyan, the storm's chords red with the white keys flashing red on each, explosions on the biggest moments. // // Every frame's picture is worked out when the script is built (probes/lib/fur-elise-showcase-run.ts, from the // chosen soundtrack's timeline, made by probes/lib/fur-elise-timeline-gen.mts; the run takes its parts, sections, range @@ -14,7 +14,8 @@ // probes/answers/fur-elise-showcase.txt. // // MAP_NAME="Für Elise" MAP_DESCRIPTION="…" npx tsx probes/lib/fur-elise-map.mts fixtures/eud/fur-elise-showcase-base.scx (the description: below) -// MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase.scx fixtures/eud/fur-elise-showcase-base.scx +// MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase-remix.scx fixtures/eud/fur-elise-showcase-base.scx +// FUR_ELISE=cinematic MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase-cinematic.scx fixtures/eud/fur-elise-showcase-base.scx // FUR_ELISE=straight MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase-straight.scx fixtures/eud/fur-elise-showcase-base.scx // SCM_SIM_DIR=~/github/scm-sim-eud npx tsx scripts/test-game.mts probes/fur-elise-showcase.ts fixtures/eud/fur-elise-showcase-base.scx // @@ -27,12 +28,13 @@ import { program, nextFrame, print, playWav, centerView, centerLocation, reserveLocation, createUnit, removeUnitAt, killUnitAt, giveUnits, setMemory, units, P3, P4, P5, P6, P7, P8, test, expect } from "trigscript"; import { whole as straightWhole } from "./lib/fur-elise-soundtrack"; import { whole as cinematicWhole } from "./lib/fur-elise-cinematic"; +import { whole as remixWhole } from "./lib/fur-elise-remix"; import { SOUNDTRACK } from "./lib/fur-elise-showcase-choice"; import { CAM_X, CAM_Y, CELL } from "./lib/fur-elise-layout"; import { START, TOTAL, LAST_OFF, STARTS, CX, CY, CKIND, CTO, LABEL_F, LABEL_TEXT, FX_F, FX_K, FX_X, FX_Y, OVERLORD, pictureAt, explosions } from "./lib/fur-elise-showcase-run"; /** The piece, one clip: the soundtrack the switch picks (only the clip played goes in the map). */ -const WHOLE = SOUNDTRACK === "straight" ? straightWhole : cinematicWhole; +const WHOLE = SOUNDTRACK === "straight" ? straightWhole : SOUNDTRACK === "cinematic" ? cinematicWhole : remixWhole; /** units.dat's flingy bytes of types 12 … 15 (Battlecruiser, Spider Mine, Nuclear Missile, Civilian), one dword. */ const LOOKS = 0x664504; diff --git a/probes/lib/fur-elise-showcase-choice.ts b/probes/lib/fur-elise-showcase-choice.ts index a17d999..6d1400b 100644 --- a/probes/lib/fur-elise-showcase-choice.ts +++ b/probes/lib/fur-elise-showcase-choice.ts @@ -1,17 +1,33 @@ -// Which soundtrack the Für Elise showcase plays and draws (probes/fur-elise-showcase.ts): the one switch. "cinematic" -// (the arrangement, probes/lib/fur-elise-cinematic.ts, the default) or "straight" (the piece as written, -// probes/lib/fur-elise-soundtrack.ts). Built under Node, FUR_ELISE=straight picks the other without an edit: +// Which soundtrack the Für Elise showcase plays and draws (probes/fur-elise-showcase.ts): the one switch. "remix" (the +// trance remix, probes/lib/fur-elise-remix.ts, the default), "cinematic" (the cinematic arrangement, +// probes/lib/fur-elise-cinematic.ts) or "straight" (the piece as written, probes/lib/fur-elise-soundtrack.ts). Built +// under Node, FUR_ELISE=cinematic or FUR_ELISE=straight picks another without an edit: // // FUR_ELISE=straight MAP_NAME="Für Elise" NO_BASES=1 npx tsx scripts/build-fixture.mts probes/fur-elise-showcase.ts … // // (In the editor there is no environment: the constant below decides.) +import * as remix from "./fur-elise-remix-timeline"; import * as cinematic from "./fur-elise-cinematic-timeline"; import * as straight from "./fur-elise-timeline"; +export type Soundtrack = "remix" | "cinematic" | "straight"; /** The soundtrack when nothing says otherwise. */ -const DEFAULT: "cinematic" | "straight" = "cinematic"; +const DEFAULT: Soundtrack = "remix"; const asked = (globalThis as { process?: { env?: Record } }).process?.env?.FUR_ELISE; -export const SOUNDTRACK: "cinematic" | "straight" = asked === "straight" || asked === "cinematic" ? asked : DEFAULT; +export const SOUNDTRACK: Soundtrack = asked === "remix" || asked === "cinematic" || asked === "straight" ? asked : DEFAULT; -/** The chosen soundtrack's timeline: the same shape either way (probes/lib/fur-elise-timeline-gen.mts makes both). */ -export const TIMELINE = SOUNDTRACK === "straight" ? straight : cinematic; +/** The chosen soundtrack's timeline: the same shape each way (probes/lib/fur-elise-timeline-gen.mts makes them). */ +export const TIMELINE = SOUNDTRACK === "straight" ? straight : SOUNDTRACK === "cinematic" ? cinematic : remix; + +/** + * What a timeline does not say and the picture needs, by soundtrack: + * - `storm`: the section that gets the red chords and the white keys flashing red (the user's choice for the storm). + * The remix's storm is its second drop (probes/lib/fur-elise-remix-score.ts: "drop 2, the storm, the biggest"). + * - `big`: the sections where the rest of the band falls on the minimap in violet; the others show the piano alone. + * - `stage`: roles drawn on the main screen besides the piano's two hands, in the big sections only (the remix's stabs, + * which carry its storm's chords). + */ +export const LOOK: { readonly storm: string; readonly big: readonly string[]; readonly stage: readonly string[] } = + SOUNDTRACK === "remix" + ? { storm: "drop 2", big: remix.SECTIONS.filter((s) => s.kind === "drop" || s.kind === "build").map((s) => s.name), stage: ["synth"] } + : SOUNDTRACK === "cinematic" ? { storm: "storm", big: ["storm", "final"], stage: [] } : { storm: "storm", big: ["storm"], stage: [] }; diff --git a/probes/lib/fur-elise-showcase-run.ts b/probes/lib/fur-elise-showcase-run.ts index 0a1a893..6d56152 100644 --- a/probes/lib/fur-elise-showcase-run.ts +++ b/probes/lib/fur-elise-showcase-run.ts @@ -13,11 +13,13 @@ // cyan; in the storm the lead's chords red and the white keys flashing red on each; explosions on the strongest // moments; the rest of the band on the minimap in violet in the big sections only, so the intro and ending are calm. The probe measured the picture ~95 ms ahead of a long clip's sound: the clip starts LEAD frames early. import { FRAME, changesOver, fitKeys, isBlack, keyX, rollCells, whiteKeys, type FramedNote, type Pixel, type TimedNote } from "./note-timeline"; -import { TIMELINE } from "./fur-elise-showcase-choice"; +import { TIMELINE, LOOK } from "./fur-elise-showcase-choice"; import { AT, END, PITCH, VELOCITY, PART, BAR, BEAT, FRAME as FRAME_COL, HIT_FRAME, HIT_STRENGTH, HIT_PART } from "./fur-elise-timeline"; import { CELL, VIEW_X, VIEW_Y, CAM_X, BLACK_Y, WHITE_Y, ROW_GAP, FALL_Y0, STAGE_ROWS, MAP_W } from "./fur-elise-layout"; const { NOTES, ROLES, SECTIONS, SECONDS, HITS } = TIMELINE; +/** The drops' downbeats, [at, frame], where a timeline has them (the remix's): the biggest moments. */ +const DROPS: readonly (readonly [number, number])[] = (TIMELINE as { DROPS?: readonly (readonly [number, number])[] }).DROPS ?? []; /* ── The parts, by their roles ── */ @@ -25,15 +27,23 @@ const { NOTES, ROLES, SECTIONS, SECONDS, HITS } = TIMELINE; const UNPITCHED = ["drum-low", "drum-high", "cymbal", "impact", "riser"]; const roleOf = (part: number): string => ROLES[part]; export const isPitched = (part: number) => !UNPITCHED.includes(roleOf(part)); -/** The piano's two hands, on both keyboards: the lead (the right hand, the theme) gold, the accompaniment cyan. */ -export const LEAD_PART = ROLES.indexOf("lead" as never), OTHER_PART = ROLES.indexOf("accomp" as never); +/** + * On both keyboards: the melody (role "lead": the piano's right hand, and in the remix the trance lead that doubles it) + * gold, drawn on top of everything; the piano's left hand ("accomp") cyan. LEAD_PART and OTHER_PART are the first of each. + */ +const partsOf = (role: string) => ROLES.map((r, k) => (r === role ? k : -1)).filter((k) => k >= 0); +export const LEAD_PARTS = partsOf("lead"), OTHER_PARTS = partsOf("accomp"); +export const LEAD_PART = LEAD_PARTS[0] ?? -1, OTHER_PART = OTHER_PARTS[0] ?? -1; if (LEAD_PART < 0 || OTHER_PART < 0) throw new Error("The timeline's ROLES name no lead or no accomp."); -const onStage = (part: number) => part === LEAD_PART || part === OTHER_PART; +const isLead = (part: number) => LEAD_PARTS.includes(part), isAccomp = (part: number) => OTHER_PARTS.includes(part); +const onStage = (part: number) => isLead(part) || isAccomp(part); +/** Parts the main screen shows too, in the big sections only (LOOK.stage: the remix's stabs). */ +const isExtra = (part: number) => LOOK.stage.includes(roleOf(part)); /* ── The keyboards ── */ /** The main screen's keyboard: the hands' notes, at most 40 white keys (16 pixels apart fill the view); outliers by octaves. */ -export const STAGE_KEYS = fitKeys(NOTES.filter((n) => onStage(n[PART])).map((n) => n[PITCH]), 40, "whites"); +export const STAGE_KEYS = fitKeys(NOTES.filter((n) => onStage(n[PART]) || isExtra(n[PART])).map((n) => n[PITCH]), 40, "whites"); export const STAGE_LO = STAGE_KEYS.lo, STAGE_HI = STAGE_KEYS.hi; /** * White keys 16 to 20 pixels apart, the last at view x 830 (inside the 852 the widescreen view shows). A Spider Mine is @@ -81,46 +91,50 @@ export interface ShowNote extends FramedNote { readonly part: number; /** Each section's first bar, and the bar after the last. */ const sectionEnd = (k: number) => SECTIONS[k + 1]?.bar ?? Infinity; -const meanVelocity = (ns: readonly (readonly number[])[]) => ns.reduce((sum, n) => sum + n[VELOCITY], 0) / Math.max(1, ns.length); -const pitchedNotes = NOTES.filter((n) => isPitched(n[PART])); -const named = (...names: string[]) => SECTIONS.filter((s) => names.includes(s.name)).map((s) => s.name); -const byVelocity = SECTIONS.filter((s, k) => meanVelocity(pitchedNotes.filter((n) => n[BAR] >= s.bar && n[BAR] < sectionEnd(k))) >= 1.25 * meanVelocity(pitchedNotes)).map((s) => s.name); -/** - * The storm: red chords and red flashes (the user's choice). The section named "storm"; else the loud sections, played - * at a quarter or more over the piece's mean velocity. - */ -export const LOUD = named("storm").length ? named("storm") : byVelocity; +/** The storm: red chords and the white keys flashing red (the user's choice). LOOK.storm names it. */ +export const LOUD = SECTIONS.some((s) => s.name === LOOK.storm) ? [LOOK.storm] : []; /** - * The big sections, where the rest of the band shows on the minimap in violet: the storm and the final statement (the - * cinematic arrangement); the intro, the ending and the quieter sections show the piano alone. + * The big sections (LOOK.big): the rest of the band falls on the minimap in violet there, and the stage's extra parts + * show. The others — the piano's intro, the breakdowns, the ending — show the piano alone. */ -export const BIG = [...new Set([...LOUD, ...named("final")])]; +export const BIG = LOOK.big.filter((name) => SECTIONS.some((s) => s.name === name)); const inSections = (names: readonly string[]) => (bar: number) => SECTIONS.some((s, k) => names.includes(s.name) && bar >= s.bar && bar < sectionEnd(k)); const loudBar = inSections(LOUD), bigBar = inSections(BIG); -/** The lead's notes struck together in the storm (by bar and beat: the performance spreads a chord by a few ms). */ +/** Notes struck together in the storm by the lead or the stage's extra parts (by part, bar and beat: a performance spreads a chord by a few ms). */ +const chordKey = (n: readonly number[]) => `${isExtra(n[PART]) ? "x" : "l"} ${n[BAR]} ${n[BEAT]}`; const struckWith = new Map(); -for (const n of NOTES) if (n[PART] === LEAD_PART && loudBar(n[BAR])) struckWith.set(`${n[BAR]} ${n[BEAT]}`, (struckWith.get(`${n[BAR]} ${n[BEAT]}`) ?? 0) + 1); +for (const n of NOTES) if ((isLead(n[PART]) || isExtra(n[PART])) && loudBar(n[BAR])) struckWith.set(chordKey(n), (struckWith.get(chordKey(n)) ?? 0) + 1); export const notes: readonly ShowNote[] = NOTES.filter((n) => onStage(n[PART]) || (isPitched(n[PART]) && bigBar(n[BAR]))).map((n) => { // The timeline's own frame for the strike (the soundtrack's), and the frames its key is held. const on = ZERO + n[FRAME_COL], off = ZERO + Math.round(n[END] / FRAME); const source: TimedNote = { time: n[AT], seconds: n[END] - n[AT], note: n[PITCH], hand: n[PART], velocity: n[VELOCITY] }; - const stormChord = n[PART] === LEAD_PART && loudBar(n[BAR]) && (struckWith.get(`${n[BAR]} ${n[BEAT]}`) ?? 0) >= 2; + const stormChord = (isLead(n[PART]) || isExtra(n[PART])) && loudBar(n[BAR]) && (struckWith.get(chordKey(n)) ?? 0) >= 2; return { source, on, len: Math.max(2, off - on), note: n[PITCH], hand: n[PART], velocity: n[VELOCITY], chord: stormChord, part: n[PART], bar: n[BAR], beat: n[BEAT], stormChord }; }); -/** The hands, on both screens; the rest of the band (strings, brass, bass, synths, pads), in the big sections, on the minimap only. */ +/** The piano's hands (and the melody), on both screens; the stage's extra parts in the big sections; the rest of the band, on the minimap only. */ export const piano = notes.filter((n) => onStage(n.part)); -const orchestra = notes.filter((n) => !onStage(n.part)); +const extras = notes.filter((n) => isExtra(n.part)); +const orchestra = notes.filter((n) => !onStage(n.part) && !isExtra(n.part)); + +/** The impacts the timeline marks (HITS of the role "impact"), as frames of the picture with their strength. */ +const IMPACTS = HITS.filter((h) => roleOf(h[HIT_PART]) === "impact").map((h) => ({ frame: ZERO + h[HIT_FRAME], strength: h[HIT_STRENGTH] })); +/** The drops' downbeats as frames of the picture: strength 1, the biggest moments. */ +const DROP_FRAMES = DROPS.map(([, f]) => ({ frame: ZERO + f, strength: 1 })); -/** The frames the white keys flash red: two from each loud chord's first strike. */ +/** + * The frames the white keys flash red: two from each storm chord's first strike; where the timeline has drops (the + * remix), four from each drop's downbeat and each impact of strength 0.9 or more too. + */ export const flashes = new Set(); { const first = new Map(); - for (const n of piano) if (n.stormChord) { - const k = `${n.bar} ${n.beat}`; + for (const n of notes) if (n.stormChord) { + const k = `${isExtra(n.part) ? "x" : "l"} ${n.bar} ${n.beat}`; first.set(k, Math.min(first.get(k) ?? Infinity, n.on)); } for (const f of first.values()) { flashes.add(f); flashes.add(f + 1); } + if (DROP_FRAMES.length) for (const h of [...DROP_FRAMES, ...IMPACTS.filter((i) => i.strength >= 0.9)]) for (let d = 0; d < 4; d++) flashes.add(h.frame + d); } /** @@ -135,7 +149,7 @@ for (const h of HITS) if (roleOf(h[HIT_PART]) === "drum-low" && h[HIT_STRENGTH] /* ── What each frame shows ── */ -const colorOf = (n: ShowNote) => (!onStage(n.part) ? VIOLET : n.part === OTHER_PART ? CYAN : n.stormChord ? RED : GOLD); +const colorOf = (n: ShowNote) => (n.stormChord ? RED : isLead(n.part) ? GOLD : isAccomp(n.part) ? CYAN : VIOLET); /** A key's place on each screen (a note outside a keyboard moved in by octaves). */ export const stageX = (note: number) => VIEW_X + STAGE_X0 + keyX(STAGE_KEYS.fold(note), STAGE_LO, STAGE_PITCH); const rollKey = (note: number) => ROLL_KEYS.fold(note); @@ -167,12 +181,16 @@ const overlap = (a: Pixel, x: number, y: number) => a.unit === FLAG && Math.abs( function draw(f: number, before: readonly Pixel[]): Pixel[] { const out: Pixel[] = []; if (f < SETUP) return out; - const ps = near(piano, f), os = near(orchestra, f); + const ps = near(piano, f), xs = near(extras, f), os = near(orchestra, f); const flash = flashes.has(f); - // A key lit by the last note to strike it that is still held; `key` maps a note to the keyboard's key. + // A key lit by the melody first, then the left hand, then the stage's extra parts: the last of them to strike it that + // is still held. `key` maps a note to the keyboard's key. const keyColor = (k: number, idle: number, key: (note: number) => number) => { - const lit = ps.filter((n) => key(n.note) === k && n.on <= f && f < n.on + n.len); - return lit.length ? colorOf(lit[lit.length - 1]) : idle; + for (const group of [ps.filter((n) => isLead(n.part)), ps.filter((n) => !isLead(n.part)), xs]) { + const lit = group.filter((n) => key(n.note) === k && n.on <= f && f < n.on + n.len); + if (lit.length) return colorOf(lit[lit.length - 1]); + } + return idle; }; // The minimap: the upper keyboard row every key, the lower the white keys' fronts (a note below D2 lights its octave). for (const key of ROLL_LIST) { @@ -186,15 +204,21 @@ function draw(f: number, before: readonly Pixel[]): Pixel[] { const idle = isBlack(key) ? INDIGO : flash ? RED : WHITE; out.push({ x: stageX(key), y: VIEW_Y + (isBlack(key) ? BLACK_Y : WHITE_Y), unit: FLAG, color: keyColor(key, idle, STAGE_KEYS.fold) }); } - // The minimap roll: the orchestra first, the piano over it. - for (const c of rollCells(short([...os, ...ps], ROLL_STEP), f, { rows: ROLL_ROWS, step: ROLL_STEP, direction: "falling" })) { + // The minimap roll: the band first, then the stage's extra parts, the left hand, the melody last — on top. + const accomp = ps.filter((n) => !isLead(n.part)), lead = ps.filter((n) => isLead(n.part)); + for (const c of rollCells(short([...os, ...xs, ...accomp, ...lead], ROLL_STEP), f, { rows: ROLL_ROWS, step: ROLL_STEP, direction: "falling" })) { out.push({ x: rollX(c.n.note), y: rollY(ROLL_KEY_ROW - 1 - c.row), unit: OVERLORD, color: colorOf(c.n as ShowNote) }); } - // The main screen's roll: the piano. - for (const c of rollCells(short(ps, STAGE_STEP), f, { rows: STAGE_ROWS, step: STAGE_STEP, direction: "falling" })) { - const x = stageX(c.n.note), y = VIEW_Y + FALL_Y0 - c.row * ROW_GAP; - if (out.some((p) => overlap(p, x, y)) || before.some((p) => overlap(p, x, y))) continue; - out.push({ x, y, unit: FLAG, color: colorOf(c.n as ShowNote) }); + // The main screen's roll: the melody first, so that it keeps a place another part would take (a Flag waits a frame + // where it would overlap one already there), then the left hand, then the extra parts. + const taken = new Set(); + for (const group of [lead, accomp, xs]) { + for (const c of rollCells(short(group, STAGE_STEP), f, { rows: STAGE_ROWS, step: STAGE_STEP, direction: "falling" })) { + const x = stageX(c.n.note), y = VIEW_Y + FALL_Y0 - c.row * ROW_GAP; + if (taken.has(`${x} ${y}`) || out.some((p) => overlap(p, x, y)) || before.some((p) => overlap(p, x, y))) continue; + taken.add(`${x} ${y}`); + out.push({ x, y, unit: FLAG, color: colorOf(c.n as ShowNote) }); + } } return [...new Map(out.map((p) => [`${p.unit} ${p.x} ${p.y}`, p])).values()]; } @@ -208,19 +232,16 @@ export function pictureAt(f: number): Pixel[] { /* ── The explosions ── */ -/** The impacts the timeline marks (HITS of the role "impact"), as frames of the picture with their strength. */ -const IMPACTS = HITS.filter((h) => roleOf(h[HIT_PART]) === "impact").map((h) => ({ frame: ZERO + h[HIT_FRAME], strength: h[HIT_STRENGTH] })); /** - * The moments that get an explosion. With impacts in the timeline (the cinematic arrangement): those of strength 0.9 - * or more, the strongest first, at least 100 frames (4 s) apart — the band's first downbeat, the storm's three big - * bars, the final's return of the theme and its two last big bars, not every drum stroke. Without (the straight - * piece): the loud section's downbeats weighed by the velocities struck on them, the three heaviest four bars apart — - * C16, C9 and C1, the bars the score accents. + * The moments that get an explosion. With drops or impacts in the timeline (the remix, the cinematic arrangement): the + * drops' downbeats (strength 1) and the impacts of strength 0.9 or more, the strongest first, at least 100 frames (4 s) + * apart — the big arrivals, not every drum stroke. Without (the straight piece): the storm's downbeats weighed by the + * velocities struck on them, the three heaviest four bars apart — C16, C9 and C1, the bars the score accents. */ export const BOOMS: readonly { frame: number; strength: number }[] = (() => { const chosen: { frame: number; strength: number }[] = []; - if (IMPACTS.length) { - for (const h of [...IMPACTS].sort((x, y) => y.strength - x.strength || x.frame - y.frame)) { + if (IMPACTS.length || DROP_FRAMES.length) { + for (const h of [...DROP_FRAMES, ...IMPACTS].sort((x, y) => y.strength - x.strength || x.frame - y.frame)) { if (h.strength >= 0.9 && chosen.every((c) => Math.abs(c.frame - h.frame) >= 100)) chosen.push(h); } return chosen.sort((x, y) => x.frame - y.frame); @@ -233,15 +254,20 @@ export const BOOMS: readonly { frame: number; strength: number }[] = (() => { for (const [bar, w] of bars) chosen.push({ frame: Math.min(...notes.filter((n) => n.bar === bar && n.beat === 0).map((n) => n.on)), strength: w === most ? 1 : 0.9 }); return chosen.sort((x, y) => x.frame - y.frame); })(); +/** The storm's frames: an explosion there is the biggest. */ +const stormSpan = (() => { const k = SECTIONS.findIndex((s) => s.name === LOOK.storm); return k < 0 ? [Infinity, -Infinity] : [ZERO + SECTIONS[k].frame, ZERO + (SECTIONS[k + 1]?.frame ?? Infinity)]; })(); /** * Each explosion: a frame, a kind (1 a Wraith's, 2 a Battlecruiser's), where. The strongest moments (strength 1, the - * most a timeline gives) get three Battlecruisers across the stage; the others a Wraith over each note the lead strikes - * then (one in the middle if it strikes none). Their own explosion sounds are heard (the user's choice). + * most a timeline gives) get three Battlecruisers across the stage — five on the storm's (the remix's second drop, the + * biggest); the others a Wraith over each note the melody strikes then (one in the middle if it strikes none). Their own + * explosion sounds are heard (the user's choice). */ export const explosions: readonly { frame: number; kind: number; x: number; y: number }[] = BOOMS.flatMap((b) => { - if (b.strength >= 0.995) return [-240, 0, 240].map((dx) => ({ frame: b.frame, kind: 2, x: CAM_X + 40 + dx, y: VIEW_Y + 110 })); - const lead = piano.filter((n) => n.part === LEAD_PART && Math.abs(n.on - b.frame) <= 2); - return lead.length ? lead.map((n) => ({ frame: b.frame, kind: 1, x: stageX(n.note), y: VIEW_Y + 120 })) : [{ frame: b.frame, kind: 1, x: CAM_X + 40, y: VIEW_Y + 120 }]; + const storm = b.frame >= stormSpan[0] && b.frame < stormSpan[1]; + if (b.strength >= 0.995) return (storm && DROP_FRAMES.length ? [-320, -160, 0, 160, 320] : [-240, 0, 240]).map((dx) => ({ frame: b.frame, kind: 2, x: CAM_X + 40 + dx, y: VIEW_Y + 110 })); + const lead = piano.filter((n) => isLead(n.part) && Math.abs(n.on - b.frame) <= 2); + const xs = [...new Set(lead.map((n) => stageX(n.note)))]; + return xs.length ? xs.map((x) => ({ frame: b.frame, kind: 1, x, y: VIEW_Y + 120 })) : [{ frame: b.frame, kind: 1, x: CAM_X + 40, y: VIEW_Y + 120 }]; }).sort((x, y) => x.frame - y.frame); /* ── The tables the program plays back ── */ diff --git a/tests/fur-elise-showcase-run.test.ts b/tests/fur-elise-showcase-run.test.ts index 9c8f19b..7f9c9d1 100644 --- a/tests/fur-elise-showcase-run.test.ts +++ b/tests/fur-elise-showcase-run.test.ts @@ -1,6 +1,6 @@ /** * The Für Elise showcase's run (probes/lib/fur-elise-showcase-run.ts), on each soundtrack the switch picks - * (probes/lib/fur-elise-showcase-choice.ts: the cinematic arrangement, the straight piece): the keyboards hold every + * (probes/lib/fur-elise-showcase-choice.ts: the trance remix, the cinematic arrangement, the straight piece): the keyboards hold every * note (folded by octaves where they must), the parts and sections are found by their roles and names, the explosions * land on the strongest moments, the picture never asks the game for two Flags it would not make, and the changes the * program plays back rebuild every frame's picture. @@ -12,7 +12,7 @@ import { CELL, VIEW_X, VIEW_Y } from "../probes/lib/fur-elise-layout"; type Run = typeof import("../probes/lib/fur-elise-showcase-run"); type Choice = typeof import("../probes/lib/fur-elise-showcase-choice"); -describe.each(["cinematic", "straight"] as const)("the showcase's run on the %s soundtrack", (which) => { +describe.each(["remix", "cinematic", "straight"] as const)("the showcase's run on the %s soundtrack", (which) => { let r: Run, c: Choice; beforeAll(async () => { process.env.FUR_ELISE = which; @@ -34,16 +34,17 @@ describe.each(["cinematic", "straight"] as const)("the showcase's run on the %s it("puts the piano on the keyboards by role, and no drum, impact or riser on a roll", () => { const { ROLES } = c.TIMELINE; - expect([ROLES[r.LEAD_PART], ROLES[r.OTHER_PART]]).toEqual(["lead", "accomp"]); - expect(r.piano.every((n) => n.part === r.LEAD_PART || n.part === r.OTHER_PART)).toBe(true); + expect(r.LEAD_PARTS.every((k) => ROLES[k] === "lead") && r.OTHER_PARTS.every((k) => ROLES[k] === "accomp")).toBe(true); + expect(r.LEAD_PARTS.length).toBe(which === "remix" ? 2 : 1); + expect(r.piano.every((n) => r.LEAD_PARTS.includes(n.part) || r.OTHER_PARTS.includes(n.part))).toBe(true); expect(r.notes.every((n) => !["drum-low", "drum-high", "cymbal", "impact", "riser"].includes(ROLES[n.part]))).toBe(true); - expect(r.LOUD).toEqual(["storm"]); + expect(r.LOUD).toEqual([which === "remix" ? "drop 2" : "storm"]); }); - it("shows the rest of the band only in the big sections: the intro and the ending are the piano alone", () => { + it("shows the rest of the band only in the big sections: the intro, breakdowns and ending are the piano alone", () => { const { SECTIONS } = c.TIMELINE; - expect(r.BIG).toEqual(which === "cinematic" ? ["storm", "final"] : ["storm"]); - const band = r.notes.filter((n) => n.part !== r.LEAD_PART && n.part !== r.OTHER_PART); + expect(r.BIG).toEqual(which === "remix" ? ["drop 1", "build 1", "drop 2", "build 2", "drop 3"] : which === "cinematic" ? ["storm", "final"] : ["storm"]); + const band = r.notes.filter((n) => !r.LEAD_PARTS.includes(n.part) && !r.OTHER_PARTS.includes(n.part)); expect(band.length).toBeGreaterThan(0); for (const n of band) { const s = [...SECTIONS].reverse().find((x) => x.bar <= n.bar)!; @@ -65,7 +66,14 @@ describe.each(["cinematic", "straight"] as const)("the showcase's run on the %s it("explodes on a handful of the strongest moments, Battlecruisers on the strongest", () => { const { SECTIONS } = c.TIMELINE; const section = (f: number) => [...SECTIONS].reverse().find((s) => s.frame <= f - r.ZERO)!.name; - if (which === "cinematic") { + if (which === "remix") { + // The three drops' downbeats (the storm's, the second, the biggest: five Battlecruisers), two impacts between. + const drops = c.TIMELINE.SECTIONS.filter((s) => s.name.startsWith("drop")).map((s) => r.ZERO + s.frame); + expect(r.BOOMS.length).toBe(5); + for (const d of drops) expect(r.BOOMS.some((b) => b.frame === d && b.strength === 1)).toBe(true); + expect(r.explosions.filter((e) => e.frame === drops[1] && e.kind === 2).length).toBe(5); + expect(r.explosions.filter((e) => e.frame === drops[0] && e.kind === 2).length).toBe(3); + } else if (which === "cinematic") { // The band's first downbeat, three in the storm, the final's first downbeat and two of its last big bars. expect(r.BOOMS.map((b) => section(b.frame))).toEqual(["band", "storm", "storm", "storm", "final", "final", "final"]); expect(r.BOOMS[0].frame).toBe(r.ZERO + SECTIONS.find((s) => s.name === "band")!.frame); @@ -78,12 +86,13 @@ describe.each(["cinematic", "straight"] as const)("the showcase's run on the %s for (const b of r.BOOMS) expect(r.explosions.filter((e) => e.frame === b.frame).every((e) => e.kind === (b.strength >= 0.995 ? 2 : 1))).toBe(true); }); - it("flashes the white keys red only in the storm, and pulses the minimap's keys only in the big sections", () => { + it("flashes the white keys red in the storm (and the remix's drops and impacts), and pulses the minimap's keys only in the big sections", () => { const { SECTIONS } = c.TIMELINE; const at = (name: string) => r.ZERO + SECTIONS.find((s) => s.name === name)!.frame; const after = (name: string) => { const k = SECTIONS.findIndex((s) => s.name === name); return r.ZERO + (SECTIONS[k + 1]?.frame ?? Infinity); }; expect(r.flashes.size).toBeGreaterThan(20); - for (const f of r.flashes) expect(f >= at("storm") && f < after("storm") + 2).toBe(true); + for (const f of r.flashes) expect(r.BIG.some((name) => f >= at(name) && f < after(name) + 4)).toBe(true); + if (which !== "remix") for (const f of r.flashes) expect(f >= at(r.LOUD[0]) && f < after(r.LOUD[0]) + 2).toBe(true); for (const f of r.pulses) expect(r.BIG.some((name) => f >= at(name) && f < after(name) + 3)).toBe(true); }); From b2def23a2797347caf743ac5a93e08eded6a3344 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 12:38:46 -0600 Subject: [PATCH 30/31] Plan: the S7 showcase on the remix Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index 50d5de3..ae16063 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6897,6 +6897,31 @@ requirement. reshaping still reads as Für Elise, the drops' level. +#### S7 the showcase on the remix (built 2026-11-09) + +The user approved the trance remix, so it is now the showcase's default: `SOUNDTRACK` in +`probes/lib/fur-elise-showcase-choice.ts` is "remix", and `FUR_ELISE=cinematic` or `FUR_ELISE=straight` still builds the +others. What a timeline does not say comes from a small `LOOK` per soundtrack there: which section is the storm (the +remix's "drop 2", as its score names it), which sections are big (the remix's drops and builds), and which roles the +main screen shows besides the piano (the remix's stabs, role "synth"). + +**How the remix looks.** Every part with the role "lead" (the piano's right hand and the trance lead that doubles it) +is gold and drawn on top, on both screens; the left hand is cyan. In the drops and builds the stabs fall on the main +screen in violet, and the rest of the band (arps, pads, strings, bass) falls on the minimap in violet. The intro, the +breakdowns and the ending show the piano alone. In the storm the stab chords are red and the white keys flash red on +each; the white keys also flash red for four frames on each drop's downbeat and each impact of strength 0.9 or more. +Explosions come from the drops' downbeats and the impacts, strongest first, 4 s apart: five moments, game time 0:16.7 +(drop 1, three Battlecruisers), 0:59.8 (drop 2, the storm, five), 1:16.7 (an impact, Wraiths), 1:44.8 (drop 3, three), +2:14.8 (an impact, Wraiths). The 2-frame lead of the clip, the half-speed fall and the 16 px spacing are as before. +The cinematic and straight runs come out exactly as they did (the same changes and moments). + +**The map.** 3.79 MB, 154.8 s of sound (one Ogg, 3.5 MB), the end line at 2:26, the tables to 2:39; payload 3.6 MB, +204,505 changes, at most about 500 units at once. Tuning on the map's own Ogg: 41 pitches, none off. In the lifted +game every one of its 3,786 frames holds the worked-out picture and no explosion's unit outlives its frame; 0.15 ms a +frame on average, 0.79 ms at the most (frame 2542, drop 3 with its stabs and the band); `game-check` 825,992 accesses, +0 ending the game, 0 ignored, 0 never seen. In Maps/TrigScript: `trigscript-fur-elise.scx` (the remix), +`trigscript-fur-elise-cinematic.scx`, `trigscript-fur-elise-straight.scx`, the check sheet and 24 stills. Not played yet. + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice From 8c2c207d4387f8f5107939fb9455edce52c2ed03 Mon Sep 17 00:00:00 2001 From: Jeany Date: Mon, 9 Nov 2026 14:52:35 -0600 Subject: [PATCH 31/31] =?UTF-8?q?Plan:=20the=20F=C3=BCr=20Elise=20showcase?= =?UTF-8?q?=20played=20and=20published?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEdp4UsAHvBRUfa1qAdsTV --- docs/v4-plan.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/v4-plan.md b/docs/v4-plan.md index f48e268..61645b8 100644 --- a/docs/v4-plan.md +++ b/docs/v4-plan.md @@ -6922,6 +6922,13 @@ frame on average, 0.79 ms at the most (frame 2542, drop 3 with its stabs and the 0 ending the game, 0 ignored, 0 never seen. In Maps/TrigScript: `trigscript-fur-elise.scx` (the remix), `trigscript-fur-elise-cinematic.scx`, `trigscript-fur-elise-straight.scx`, the check sheet and 24 stills. Not played yet. +**Played and published (2026-11-09).** The user played the remix map in Remastered ("looks great, we'll go with this +map"). In the recording (StarCraft 2026.11.09 - 13.28.00.01.mp4, 152.6 s) the clip starts at 4.79 s and matches the +map's Ogg at 1.000, 0 samples of drift at every 10 s. The video is https://www.youtube.com/watch?v=CFVdWwmngyw; the +editor's TrigScript guide has the Showcase entry, with the map to download. Open: the sampled instruments, +`music.perform` and the rest of S7's music library come to the editor with the next TrigScript release, and the +library guide describes them then; the editor cannot import a `.samples` file yet (a whole piano is 125–137 MB). + ### Smaller things that show well Each is small and makes the editor feel like it knows the game. They go in where a slice