mirror of
https://github.com/juanjiant-bit/JIANT.git
synced 2026-12-05 12:24:42 +01:00
MATH tab: formulas of one's own sent to the device (MATH USER, JIANT FM V10.8.75)
The MATH tab compiles a formula of one's own to the device's bytecode and sends it to a track, now that the firmware plays them (JIANT FM V10.8.75, codex/v66-clean: firmware/src/math_user.c, JIANT BYTE's formula machine). - FVM (in the MATH section): a port of JIANT BYTE's compiler (its firmware/src/fvm.c, GPL-3.0, the owner's): its grammar (t w a n v; C's operators; sin cos tri saw sqr abs min max floor int fix rnd sat clip; a string as a table), its INT / FIX types, its folding, its instructions, serialized as math_user.c reads them (EDITOR_PROTOCOL.md "1.5"). ph() lp() hp() eu() and FUNC's calls are BYTE's only: refused with that message. At most 64 bytes, a stack of 12. FVM.run is math_user.c's machine in JavaScript; FVM.pack7 / unpack7 the backup's groups. - The tab: a text that is one of the firmware's 48 BYTE formulas is sent as its ALGO, as before; any other is MATH USER (the message says its size and INT -> BYTE or FIX -> FLOAT). Heard through the emulator's own machine (the wasm's FORMULA, track 1 at ALGO USER), the model when the wasm is older. Sent with FORMULA (100) to a device whose INFO has 'E' (45 02 64 12), read back and compared, then the eight values with ALGO -4 (USER) and WAVE 5 (INT) or 6 (FIX). Read: a track at ALGO USER gives its bytes; their text comes back if it was sent from this browser (kept in localStorage by its bytes). An older device: not sendable, as before. The generator's formulas are MATH USER ones. - The mock device answers FORMULA and says 'E' and 'C' 1.5 (before its 'D' / 'H'). - EDITOR_PROTOCOL.md: the proposal becomes "1.5: MATH USER, a formula of one's own (100; V10.8.75)": the command, the bytes (BYTE's FO_* numbers, the operand modes), the checks, what is not in JIANT FM, the project block, the presets; the version table and the frozen command numbers. Tests: - math_test.mjs: web/math_fvm_gold.json (142 texts compiled by BYTE's own fvm_compile from BYTE origin/main 1495526, serialized, run by its fvm_run): FVM gives BYTE's bytes for all 135 that fit (93 of BYTE's 96 factory formulas: B16 and F32 are over 64 bytes, F05 and F22 use ph(); and every operator), FVM.run BYTE's values for each (3 x 4160); the 7 refused refused; errors with their place; pack7; the generator's formulas fit. With EMU_WASM: B01's bytecode at ALGO USER plays B01's samples bit for bit; FORMULA reads back; a FIX formula on FLOAT sounds. Passes against a wasm built from the firmware's V10.8.75 commit (emsdk 6.0.11). - editor_browser_test.mjs: on the firmware wasm, a formula of one's own compiled, sent to track 4 (FORMULA 4 0 gives the editor's bytes, ALGO -4), read back into the editor with its text; without a device, one's own heard through the emulator (the model without one), a FIX floatbeat recognised. Passes (with that wasm); test_web, test_backup, test_manual pass. The public emulator (web/EMULATOR's pin) gets the VM when the pin moves to the firmware's V10.8.75 commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KMHk6yH4XbP1xxHYKCo9Mh
This commit is contained in:
5 files changed
+563
-48
No files matched your search
+40
-21
@@ -132,7 +132,7 @@ tag of the addition, as before).
|
||||
|
||||
- **Framing**: `F0 7D 46 4C cmd args F7`, one reply per request with the same `cmd` (no reply: an unknown command or
|
||||
a wrong fixed length), pushes never replies; the encodings v14, u32, pack7, strings.
|
||||
- **Command numbers** 1..10, 16..42, 64..77, 80, (1.1) 81 and (1.4) 95..97 as listed in this file; 11..15 stay
|
||||
- **Command numbers** 1..10, 16..42, 64..77, 80, (1.1) 81 (1.4) 95..97 and (1.5) 100 as listed in this file; 11..15 stay
|
||||
reserved (no reply).
|
||||
- **Reply layouts**: every byte stays where it is. New bytes only at the end of a reply, behind a request byte that
|
||||
asks for them (as `STEP_GET`'s flag 1, `WATCH`'s bits), or as a new `INFO` tag before `59`.
|
||||
@@ -170,6 +170,7 @@ regenerated from `params.c` and compared.
|
||||
| 1.2 | V10.6z7 | `VEL` ops 4 and 5: the keys' velocity, calibration and pressure (below); MENU ids 27..30 (VELOCITY, VEL MIN, AFTERTOUCH, VEL LEARN); `INFO` tag `43 02 01 02` |
|
||||
| 1.3 | V10.7.21 | `INFO` tag `58 01 seg` ('X'): the Bluetooth segment, 1 this build's, 2 missing, torn or another build's (the installer checks it after an update); `INFO` tag `43 02 01 03` |
|
||||
| 1.4 | V10.8.71 (public: V10.8.72) | a track's special ids P_COUNT + 0..3 (FX › OTT) through `TRACK_PARAM` and `DESC`; `uiCaps` bit 4; the project library `PROJ_LIST` / `PROJ_NAME` / `PROJ_OP` (95..97, since V10.8.54); MENU ids 33 SAVER and 34 PANEL; `INFO` tag `43 02 01 04` (below) |
|
||||
| 1.5 | V10.8.75 | `FORMULA` (100): MATH USER, a track's formula of its own (JIANT BYTE's bytecode); ALGO −4 USER; `INFO` tag `45 02 64 12`; `INFO` tag `43 02 01 05` (below) |
|
||||
|
||||
## 1.0: performance pushes (40-42)
|
||||
|
||||
@@ -320,28 +321,46 @@ EUCLID itself (MODES, a melodic track's CONTOUR RANGE MOTIF ROLE) instead of wri
|
||||
t->seq_idx)`, 127 stopped), sent with each step change while `WATCH` bit 5 is set, would let the roll draw each track's
|
||||
playhead as the device does (`pr_heads`).
|
||||
|
||||
## Proposal: a user formula for MATH (not in the firmware)
|
||||
## 1.5: MATH USER, a formula of one's own (100; V10.8.75)
|
||||
|
||||
MATH plays its own formulas only: BYTE's 48 (`eng_lofi.c` `lofi_byte`, ALGO = 4 × the formula) and FLOAT's 48
|
||||
(`lofi_float`), compiled C; there is no formula VM in JIANT FM and no command that carries a formula. The web editor's
|
||||
MATH tab sends what the device has (the engine by `SET` of `G_ENGSEL`, then P_E0..P_E7 by `TRACK_PARAM`: CHIP, WAVE,
|
||||
ALGO, VARIANT, MOTION, GRIT / FEEDBK, BEND / MORPH, LOOP) and keeps a formula of one's own in the browser, heard
|
||||
through its model of the BYTE voice. To send one, additively (protocol 1.5):
|
||||
`INFO` says `43 02 01 05`, and the tag `45 02 64 12` ('E', before `43`): the device takes formulas of up to 64 bytes
|
||||
with a stack of 12. An editor without it keeps a formula of its own in the browser, as before 1.5.
|
||||
|
||||
- **The bytecode** the editor already builds (`MathVM.rpn`, tested against its VM on every formula): a stack machine,
|
||||
one 7-bit byte an op. `00` t, `01` a, `03 n` a constant below 128, `02` + 5 bytes a 32-bit constant (7 bits each, LSB
|
||||
first); the binary ops `10`..`21` in this order: `+ - * / % & | ^ << >> < <= > >= == != && ||` (unsigned 32-bit, a
|
||||
shift's count & 31, / and % by 0 give 0, a comparison 0 / 1); `30` −, `31` ~, `32` ! (unary); `40` ?: (pops z, y,
|
||||
c). The firmware's own 48 are at most 90 bytes with a stack of 8: a limit of 128 bytes and 16 entries fits them all.
|
||||
- **100 FORMULA**: `track, op` — op 0 query (→ `track, rc, len, code`), op 1 set (`track, 1, len lo, len hi, code`),
|
||||
op 2 clear. The device checks the code once (every op known, the stack never under 1 nor over 16, exactly 1 left)
|
||||
and answers rc 0 or 1 (refused: the track as it was). The track's ALGO 192 (`U`, past B48) plays it through
|
||||
`lofi_byte`'s default case: `case 48: return fvm_run(t->code, t, a)`, with VAR, MOTION, LOOP, BEND, GRIT, CHIP and
|
||||
SYNC as for any BYTE formula. A project keeps it in a block of its own (`F` `U`: the six tracks' codes), so backups,
|
||||
songs and Studio carry it; firmware without the block loads ALGO 192 as B48.
|
||||
- **INFO** `46 02 1 128`: formulas of up to 128 bytes. An editor without it keeps a formula of one's own local, as now.
|
||||
- The cost: an op a sample, about 2 × the stock formula's time at the same length (a switch per op instead of compiled
|
||||
code); BYTE renders at half rate (`.half`), so a 90-byte formula stays within the budget of the heavier engines.
|
||||
A MATH track holds one formula of its own (`firmware/src/math_user.c`), played at **ALGO USER**: `P_E2` = −4 (−4..−1),
|
||||
before B01 / F01. `DESC` of a track that holds one (or is at USER) gives ALGO −4..191, its names `USER`, `B01` ..
|
||||
(`F01` .. on FLOAT); a track without one keeps 0..191 as before. Through MATH's BYTE voice (WAVE 5 or 7 SYNC) an INT
|
||||
formula plays as bytebeat (its low byte), with VARIANT (`a` = 1 + VARIANT / 8, and its mutation of t), MOTION, LOOP,
|
||||
BEND, GRIT, CHIP as for MATH's own; through FLOAT (WAVE 6) a FIX formula plays as floatbeat (−1 .. 1; an INT one as
|
||||
bytebeat), with `w` the note's phase. The device reads a formula at most 11025 times a second (a held value between)
|
||||
and sounds at most four voices of such formulas at once (every track's together; a fifth fades the oldest out).
|
||||
|
||||
| cmd | Request args | Reply args |
|
||||
| --- | --- | --- |
|
||||
| 100 FORMULA | track, op: 0 query; 1 set, then pack7 of the bytes; 2 clear | track, rc (0 done, 1 refused: not a formula the device runs, the track's as it was), length, pack7 of the bytes |
|
||||
|
||||
pack7 is `BACKUP_PUT`'s: groups of a byte holding the group's bit 7s (bit j for its byte j), then up to 7 bytes.
|
||||
|
||||
**The bytes** are JIANT BYTE's formula machine (`fvm.c`): the instructions its compiler makes from a text,
|
||||
serialized, with BYTE's operator numbers and meaning, so a formula is the same in both (`web/editor.html` `FVM`, the
|
||||
compiler's port, gives BYTE's own bytes for every formula of `web/math_fvm_gold.json`):
|
||||
|
||||
- byte 0: bit 0 the result's type (0 INT: unsigned 32 bits; 1 FIX: Q16.16), bit 1 a table pool follows: then its
|
||||
length (1..32) and its bytes (the formula's strings, `"36364689"[t>>11&7]`); the other bits 0;
|
||||
- then each instruction `op | md << 6`: `op` BYTE's `FO_*`: 0 ADD 1 SUB 2 MUL 3 DIVU 4 MODU 5 AND 6 OR 7 XOR 8 SHL 9 SHR
|
||||
10 LTU 11 LEU 12 GTU 13 GEU 14 EQ 15 NE 16 LTS 17 LES 18 GTS 19 GES 20 LAND 21 LOR 22 MINU 23 MAXU 24 MINS 25 MAXS
|
||||
26 MULF 27 MULIF 28 DIVF 29 DIVFI 30 MODF (binary: the stack's top and the operand), 33 NEG 34 NOT 35 LNOT 36 ITOF
|
||||
37 FTOI 38 ABS 39 FLOOR 40 SINI 41 SINF 42 TRII 43 TRIF 44 SAWI 45 SAWF 46 SQRI 47 SQRF 48 RNDI 49 RNDF 50 SAT (unary),
|
||||
52 PUSH, 53 SEL (`c ? x : y`), 54 TAB (the top an index into a table: its `offset << 8 | length` follows as a number);
|
||||
`md` the operand: 0 the stack (popped), 1 a number (LEB128: 7 bits a byte, the low first, bit 7 "more"), 2 a variable
|
||||
(a byte: bit 7 set a per-sample one, BYTE's `FA_*`: 128 t, 129 w; else a per-block one, `FU_*`: 0 a, 8 n the note,
|
||||
9 v the velocity; any other reads 0), 3 t (no byte).
|
||||
- / and % by 0 give 0, a shift takes its count & 31, FIX's products and quotients are BYTE's (64-bit, truncated).
|
||||
|
||||
The device checks a formula when it arrives: every op one of the above, its operand whole, the stack never under 1
|
||||
nor over 12, one value left, a table inside its pool; and its machine stays inside its stack and its bytes whatever
|
||||
they are. Not in JIANT FM (BYTE's, refused): `ph()` `lp()` `hp()` (a state per voice), `eu()`, FUNC's calls and
|
||||
`func{}`. A project keeps each track's formula in a block of its own (`F` `U`, after `O` `T`: an older firmware stops
|
||||
before it and loads ALGO −4 as B01); a user preset keeps ALGO USER, not the formula (the track's plays).
|
||||
|
||||
## NRPN (1.0)
|
||||
|
||||
|
||||
+451
-25
@@ -669,6 +669,7 @@ const CMD = { INFO: 1, GET: 2, SET: 3, DUMP: 4, DESC: 5, STEP_GET: 6, STEP_SET:
|
||||
FM6_GET: 68, FM6_PUT: 69, FM6_LIST: 70, FM6_ERASE: 71,
|
||||
FM6B_BEGIN: 74, FM6B_WRITE: 75, FM6B_END: 76, FM6B_LIST: 77, /* (JIANT 0.6.11, Felucca 1.4.1) FM6's voice bank */
|
||||
SCREEN: 78, SCREEN_DATA: 79, /* the screen mirror (EDITOR_PROTOCOL.md "Screen mirror") */
|
||||
FORMULA: 100, /* (V10.8.75, 1.5) MATH USER's formula of a track */
|
||||
};
|
||||
/* frames the device sends on its own (while WATCH is on); never replies */
|
||||
const PUSH = new Set([CMD.CHANGED, CMD.RELOAD, CMD.STEP_CHANGED, CMD.TRACK_CHANGED, CMD.SCREEN_DATA]);
|
||||
@@ -841,10 +842,18 @@ const parse = {
|
||||
}
|
||||
if (trailer[k - 3] === 0x44 && trailer[k - 2] === 1) o.board = trailer[k - 1];
|
||||
}
|
||||
/* (V10.8.75, 1.5) 'E' 2 bytes depth, right before 'C' 2 1 minor: FORMULA (100), MATH USER's formulas; null = none */
|
||||
o.formula = null;
|
||||
for (let k = trailer.length - 7; k >= 4; k--)
|
||||
if (trailer[k] === 0x43 && trailer[k + 1] === 2 && trailer[k + 2] === 1) {
|
||||
if (trailer[k - 4] === 0x45 && trailer[k - 3] === 2) o.formula = { max: trailer[k - 2], depth: trailer[k - 1] };
|
||||
break;
|
||||
}
|
||||
|
||||
return o;
|
||||
},
|
||||
[CMD.LYRIC](a) { const r = new Reader(a); return { track: r.b(), rc: r.b(), text: r.s() }; },
|
||||
[CMD.FORMULA](a) { const n = a[2] | 0; return { track: a[0], rc: a[1], code: FVM.unpack7(Array.from(a.slice(3))).slice(0, n), n }; }, /* (1.5) */
|
||||
[CMD.UI_STATE](a) {
|
||||
const r = new Reader(a), o = { caps: r.b(), palette: r.b(), font: r.b(), monitor: r.b(), filter: r.b() };
|
||||
const u28 = () => r.b() | r.b() << 7 | r.b() << 14 | r.b() << 21;
|
||||
@@ -993,6 +1002,7 @@ const req = {
|
||||
favGet: (engine, start, count) => [CMD.FAV_GET, [engine, ...v14enc(start), count]],
|
||||
favSet: (engine, preset, on) => [CMD.FAV_SET, [engine, ...v14enc(preset), on ? 1 : 0]],
|
||||
lyric: (track, text) => [CMD.LYRIC, text == null ? [track] : [track, ...strEnc(lyricText(text))]], /* (0.8.5) */
|
||||
formula: (track, op, code) => [CMD.FORMULA, [track & 0x7F, op, ...(op === 1 ? FVM.pack7(code) : [])]], /* (1.5) 0 query, 1 set, 2 clear */
|
||||
info: () => [CMD.INFO, []],
|
||||
get: (scope, id) => [CMD.GET, [scope, id]],
|
||||
set: (scope, id, v) => [CMD.SET, [scope, id, ...v14enc(v)]],
|
||||
@@ -1066,6 +1076,7 @@ function replyMatches(cmd, args, a) {
|
||||
case CMD.FAV_GET: case CMD.FAV_SET:
|
||||
return ![0, 3, 4].includes(a[0]) || (a[1] === args[0] && a[2] === args[1] && a[3] === args[2] && a[4] === args[3]);
|
||||
case CMD.LYRIC: return a[0] === args[0];
|
||||
case CMD.FORMULA: return a[0] === args[0];
|
||||
case CMD.SCREEN: return a[0] === args[0];
|
||||
case CMD.GET: case CMD.SET: case CMD.DESC: return a[0] === args[0] && a[1] === args[1];
|
||||
case CMD.STEP_GET: case CMD.STEP_SET: case CMD.NAMES: return a[0] === args[0];
|
||||
@@ -2506,11 +2517,22 @@ function makeMockDevice(opt = {}) {
|
||||
if (syncCaps()) { b(0x53); b(1); b(syncCaps()); if (!opt.noFm6) { b(0x50); b(1); b(3); } if (ratchetOn()) { b(0x52); b(1); b(4); if (!opt.noLocks) { b(0x4C); b(1); b(1); } }
|
||||
if (!opt.noFm6 && !opt.noVbank && ratchetOn()) { b(0x56); b(1); b(32); }
|
||||
if (lanesOn()) { b(0x4F); b(1); b(7); } } } /* (FM6 v2: no bank, preset patches; 0.6.11: the voice bank; 0.8.5: the lanes' modes) */
|
||||
if (st.uiCaps && !opt.noLyric && !opt.noFormula) { b(0x45); b(2); b(64); b(12); b(0x43); b(2); b(1); b(5); } /* (1.5) 'E': FORMULA, 'C' */
|
||||
if (opt.board || opt.hostPower) { b(0x44); b(1); b(opt.board || 3); } /* (SMK-37, ports/) 'D': the device */
|
||||
if (opt.hostPower) { b(0x48); b(2); b(15); b(16); } /* (ports/) 'H': SAMPLE GRAIN DRUM-X's samples, 16 slots */
|
||||
if (st.uiCaps && !opt.noLyric) { b(0x59); b(1); b(63); } /* (0.8.5) LYRIC, the last tag */
|
||||
}
|
||||
break;
|
||||
case CMD.FORMULA: { /* (1.5) editor.c ED_FORMULA (the mock: its length and header checked) */
|
||||
if (opt.noFormula || a.length < 2 || a[0] >= NTRK || a[1] > 2) return null;
|
||||
const tr = st.tracks[a[0]];
|
||||
let rc = 0;
|
||||
if (a[1] === 2) tr.formula = [];
|
||||
else if (a[1] === 1) { const c = FVM.unpack7(Array.from(a.slice(2))); if (c.length < 2 || c.length > 64 || c[0] > 3) rc = 1; else tr.formula = c; }
|
||||
const f = tr.formula || [];
|
||||
b(a[0]); b(rc); b(f.length); FVM.pack7(f).forEach(b);
|
||||
break;
|
||||
}
|
||||
case CMD.LYRIC: { /* (0.8.5) editor.c ED_LYRIC */
|
||||
if (opt.noLyric || !a.length || a[0] >= NTRK) return null;
|
||||
const tr = st.tracks[a[0]];
|
||||
@@ -3179,6 +3201,363 @@ const MathVM = (() => {
|
||||
}
|
||||
return { compile, parse, canon, rpn, run };
|
||||
})();
|
||||
/* (V10.8.75, MATH USER) JIANT BYTE's formula compiler (its firmware/src/fvm.c, GPL-3.0, the owner's: the grammar, the INT
|
||||
and FIX types, the folding, the instructions) ported, and the bytes JIANT FM's math_user.c runs: the instructions BYTE's
|
||||
fvm_compile makes, serialized. web/math_fvm_gold.json holds BYTE's own output for 142 formulas: math_test.mjs asks this
|
||||
port for the same bytes and the same values. The language: C's expressions of t (the time), w (FLOAT's phase), a
|
||||
(VARIANT's 1..16), n v (the note, its velocity); INT 32 bits unsigned (bytebeat), a number with a point FIX Q16.16
|
||||
(floatbeat); sin cos tri saw sqr abs min max floor int fix rnd sat clip, a string read as a table ("36364689"[t>>11&7]).
|
||||
JIANT FM has not BYTE's ph() lp() hp() (a state a voice) nor eu(): refused here. The bytes (EDITOR_PROTOCOL.md "100
|
||||
FORMULA"): [0] the type (bit 0 FIX) | 2 a table pool follows ([1] its length, its bytes); then op | md << 6 each (md 0 the
|
||||
stack, 1 a number (LEB128), 2 a variable's byte (bit 7 a per-sample one), 3 t); TAB (54) its table after it as a number.
|
||||
At most 64 bytes, a stack of 12 */
|
||||
const FVM = (() => {
|
||||
const MAX = 64, DEPTH = 12, MAXINS = 64, POOL = 32, MAXNODE = 160, FS = 44100;
|
||||
const INT = 0, FIX = 1;
|
||||
const O = {};
|
||||
["ADD", "SUB", "MUL", "DIVU", "MODU", "AND", "OR", "XOR", "SHL", "SHR", "LTU", "LEU", "GTU", "GEU", "EQ", "NE", "LTS", "LES",
|
||||
"GTS", "GES", "LAND", "LOR", "MINU", "MAXU", "MINS", "MAXS", "MULF", "MULIF", "DIVF", "DIVFI", "MODF", "EU", "NBIN", "NEG", "NOT",
|
||||
"LNOT", "ITOF", "FTOI", "ABS", "FLOOR", "SINI", "SINF", "TRII", "TRIF", "SAWI", "SAWF", "SQRI", "SQRF", "RNDI", "RNDF", "SAT",
|
||||
"NUN", "PUSH", "SEL", "TAB", "PH", "LP", "HP", "SAVE", "MUSIC"].forEach((n, k) => { O[n] = k; });
|
||||
const STK = 0, IMM = 1, UNI = 2, ARR = 3;
|
||||
const SINE = Array.from({ length: 1025 }, (_, i) => Math.round(32767 * Math.sin(2 * Math.PI * i / 1024)));
|
||||
const TANH = Array.from({ length: 257 }, (_, i) => Math.trunc(32767 * Math.tanh(i / 256 * 2)));
|
||||
const sineI = (ph) => { const i = ph >>> 22, a = SINE[i], b = SINE[(i + 1) & 1023]; return a + (((b - a) * ((ph >>> 7) & 0x7FFF)) >> 15); };
|
||||
const softclip = (x) => { const a = Math.abs(x), i = a >> 8, y = i >= 256 ? TANH[256] : TANH[i] + (((TANH[i + 1] - TANH[i]) * (a & 255)) >> 8); return x < 0 ? -y : y; };
|
||||
const hash = (h) => { h = Math.imul(h, 0x9E3779B1); h ^= h >>> 15; h = Math.imul(h, 0x85EBCA77); return (h ^ (h >>> 13)) >>> 0; };
|
||||
const EUT = [[3, 8], [5, 8], [2, 8], [3, 16], [5, 16], [7, 16], [9, 16], [4, 16], [11, 16], [5, 12], [7, 12], [4, 12], [3, 6], [2, 6], [6, 16], [13, 16]];
|
||||
function eu(s, seed) { /* (BYTE's fvm_eu: only for folding eu() of numbers) */
|
||||
const h = hash((Math.imul(seed, 0x9E3779B1) + Math.imul(s >>> 6, 0x85EBCA77)) >>> 0), g = [];
|
||||
for (let i = 0; i < 2; i++) { const e = (h >>> (i * 8)) & 15, k = EUT[e][0], n = EUT[e][1], r = (h >>> (16 + i * 4)) & 15; g.push(+((Math.imul((s + r) >>> 0, k) >>> 0) % n < k)); }
|
||||
switch (h >>> 30) { case 0: return g[0] | g[1]; case 1: return (g[0] & g[1]) | +((s & 15) === 0); case 2: return g[0] ^ g[1]; default: return (s >>> 4) & 1 ? g[1] : g[0]; }
|
||||
}
|
||||
const S = (x) => x | 0, U = (x) => x >>> 0;
|
||||
function op2(o, a, b) { /* BYTE's FVM_OPS2 */
|
||||
a >>>= 0; b >>>= 0;
|
||||
switch (o) {
|
||||
case O.ADD: return U(a + b); case O.SUB: return U(a - b); case O.MUL: case O.MULIF: return U(Math.imul(a, b));
|
||||
case O.DIVU: return b ? U(Math.floor(a / b)) : 0; case O.MODU: return b ? a % b : 0;
|
||||
case O.AND: return U(a & b); case O.OR: return U(a | b); case O.XOR: return U(a ^ b);
|
||||
case O.SHL: return U(a << (b & 31)); case O.SHR: return a >>> (b & 31);
|
||||
case O.LTU: return +(a < b); case O.LEU: return +(a <= b); case O.GTU: return +(a > b); case O.GEU: return +(a >= b);
|
||||
case O.EQ: return +(a === b); case O.NE: return +(a !== b);
|
||||
case O.LTS: return +(S(a) < S(b)); case O.LES: return +(S(a) <= S(b)); case O.GTS: return +(S(a) > S(b)); case O.GES: return +(S(a) >= S(b));
|
||||
case O.LAND: return +(a !== 0 && b !== 0); case O.LOR: return +(a !== 0 || b !== 0);
|
||||
case O.MINU: return a < b ? a : b; case O.MAXU: return a > b ? a : b;
|
||||
case O.MINS: return S(a) < S(b) ? a : b; case O.MAXS: return S(a) > S(b) ? a : b;
|
||||
case O.MULF: return U(Number(BigInt.asIntN(32, (BigInt(S(a)) * BigInt(S(b))) >> 16n)));
|
||||
case O.DIVF: return S(b) ? U(Number(BigInt.asIntN(32, (BigInt(S(a)) * 65536n) / BigInt(S(b))))) : 0;
|
||||
case O.DIVFI: return S(b) && S(b) !== -1 ? U(Math.trunc(S(a) / S(b))) : S(b) ? U(-S(a)) : 0;
|
||||
case O.MODF: return S(b) && S(b) !== -1 ? U(S(a) % S(b)) : 0;
|
||||
case O.EU: return eu(a, b);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
function op1(o, a) { /* BYTE's FVM_OPS1 */
|
||||
a >>>= 0;
|
||||
switch (o) {
|
||||
case O.NEG: return U(-S(a)); case O.NOT: return U(~a); case O.LNOT: return +(a === 0);
|
||||
case O.ITOF: return U(a << 16); case O.FTOI: return U(S(a) >> 16);
|
||||
case O.ABS: return S(a) < 0 ? U(-S(a)) : a; case O.FLOOR: return U(a & 0xFFFF0000);
|
||||
case O.SINI: return U((sineI(U(a << 24)) + 32768) >> 8); case O.SINF: return U(sineI(U(a << 16)) * 2);
|
||||
case O.TRII: return a & 128 ? 255 - ((a & 127) << 1) : (a & 127) << 1;
|
||||
case O.TRIF: return a & 0x8000 ? U(196608 - 4 * (a & 0xFFFF)) : U(4 * (a & 0xFFFF) - 65536);
|
||||
case O.SAWI: return a & 255; case O.SAWF: return U(2 * (a & 0xFFFF) - 65536);
|
||||
case O.SQRI: return a & 128 ? 0 : 255; case O.SQRF: return a & 0x8000 ? 0xFFFF0000 : 65536;
|
||||
case O.RNDI: return hash(a); case O.RNDF: return U(S(hash(a)) >> 15);
|
||||
case O.SAT: return U(softclip(S(a) >> 1) * 2);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
/* ---- the compiler: fvm.c's functions, in its order and with its names */
|
||||
const NK = { NUM: 0, ARR: 1, UNI: 2, OP1: 3, OP2: 4, SEL: 5, TAB: 6, ST: 7 };
|
||||
const TK = { ADD: 1, SUB: 2, MUL: 3, DIV: 4, MOD: 5, AND: 6, OR: 7, XOR: 8, SHL: 9, SHR: 10, LT: 11, LE: 12, GT: 13, GE: 14, EQ: 15, NE: 16, LAND: 17, LOR: 18, MIN: 19, MAX: 20 };
|
||||
const VARS = { t: [NK.ARR, INT, 0], w: [NK.ARR, FIX, 1], T: [NK.ARR, FIX, 2], x: [NK.ARR, INT, 3], X: [NK.ARR, FIX, 4],
|
||||
a: [NK.UNI, INT, 0], b: [NK.UNI, INT, 1], c: [NK.UNI, INT, 2], d: [NK.UNI, INT, 3], A: [NK.UNI, FIX, 4], B: [NK.UNI, FIX, 5],
|
||||
C: [NK.UNI, FIX, 6], D: [NK.UNI, FIX, 7], n: [NK.UNI, INT, 8], v: [NK.UNI, INT, 9], s: [NK.UNI, INT, 10], P: [NK.ARR, FIX, 12],
|
||||
p: [NK.UNI, FIX, 11], freq: [NK.UNI, FIX, 12], O1: [NK.ARR, FIX, 5], O2: [NK.ARR, FIX, 6], O3: [NK.ARR, FIX, 7], O4: [NK.ARR, FIX, 8],
|
||||
O5: [NK.ARR, FIX, 9], O6: [NK.ARR, FIX, 10], I: [NK.ARR, FIX, 11], w3: [NK.ARR, FIX, 4], w5: [NK.ARR, FIX, 11], wd: [NK.ARR, FIX, 3] };
|
||||
const CALLS = { sin: 1, cos: 1, tri: 1, saw: 1, sqr: 1, abs: 1, min: 2, max: 2, floor: 1, int: 1, fix: 1, rnd: 1, sat: 1, clip: 1, ph: 1, lp: 2, hp: 2, eu: 2,
|
||||
note: 3, chord: 3, kick: 1, snare: 1, hat: 1 };
|
||||
const BINS = [["*", 0, TK.MUL], ["/", 0, TK.DIV], ["%", 0, TK.MOD], ["+", 1, TK.ADD], ["-", 1, TK.SUB], ["<<", 2, TK.SHL], [">>", 2, TK.SHR],
|
||||
["<=", 3, TK.LE], [">=", 3, TK.GE], ["<", 3, TK.LT], [">", 3, TK.GT], ["==", 4, TK.EQ], ["!=", 4, TK.NE], ["&", 5, TK.AND], ["^", 6, TK.XOR],
|
||||
["|", 7, TK.OR], ["&&", 8, TK.LAND], ["||", 9, TK.LOR]];
|
||||
const ERR = ["", "syntax", "unknown name", "wrong arguments", "too long (64 instructions)", "too deep", "too complex", "strings too long (32 bytes)", "", "empty"];
|
||||
function compileIns(src) {
|
||||
const c = { s: String(src), i: 0, nd: [], err: 0, pos: 0, pool: [], ins: [], sp: 0, maxsp: 0, pd: 0, gd: 0, bati: -1, batk: -1 };
|
||||
const len = c.s.length, ch = () => (c.i < len ? c.s.charCodeAt(c.i) : 0);
|
||||
const fail = (code) => { if (!c.err) { c.err = code; c.pos = c.i; } };
|
||||
const nw = (kind, op, ty, a, b, cc, v) => { if (c.nd.length >= MAXNODE) { fail(6); return 0; } c.nd.push({ kind, op, ty, a, b, c: cc, v: v >>> 0 }); return c.nd.length - 1; };
|
||||
const ND = (x) => c.nd[x] || { kind: NK.NUM, ty: INT, v: 0 };
|
||||
const num = (ty, v) => nw(NK.NUM, 0, ty, 0, 0, 0, v);
|
||||
const un = (op, a, ty) => (ND(a).kind === NK.NUM ? num(ty, op1(op, ND(a).v)) : nw(NK.OP1, op, ty, a, 0, 0, 0));
|
||||
const tofix = (a) => (ND(a).ty === FIX ? a : un(O.ITOF, a, FIX));
|
||||
const toint = (a) => (ND(a).ty === INT ? a : un(O.FTOI, a, INT));
|
||||
const bin = (op, a, b, ty) => (ND(a).kind === NK.NUM && ND(b).kind === NK.NUM ? num(ty, op2(op, ND(a).v, ND(b).v)) : nw(NK.OP2, op, ty, a, b, 0, 0));
|
||||
const OPI = [0, O.ADD, O.SUB, O.MUL, O.DIVU, O.MODU, 0, 0, 0, 0, 0, O.LTU, O.LEU, O.GTU, O.GEU, O.EQ, O.NE, 0, 0, O.MINU, O.MAXU];
|
||||
const OPF = [0, O.ADD, O.SUB, O.MULF, O.DIVF, O.MODF, 0, 0, 0, 0, 0, O.LTS, O.LES, O.GTS, O.GES, O.EQ, O.NE, 0, 0, O.MINS, O.MAXS];
|
||||
function binop(tk, a, b) {
|
||||
switch (tk) {
|
||||
case TK.AND: return bin(O.AND, toint(a), toint(b), INT); case TK.OR: return bin(O.OR, toint(a), toint(b), INT);
|
||||
case TK.XOR: return bin(O.XOR, toint(a), toint(b), INT); case TK.SHL: return bin(O.SHL, toint(a), toint(b), INT);
|
||||
case TK.SHR: return bin(O.SHR, toint(a), toint(b), INT); case TK.LAND: return bin(O.LAND, a, b, INT); case TK.LOR: return bin(O.LOR, a, b, INT);
|
||||
}
|
||||
if (ND(a).ty === INT && ND(b).ty === INT) return bin(OPI[tk], a, b, INT);
|
||||
if (tk === TK.MUL && ND(a).ty !== ND(b).ty) { if (ND(a).ty === FIX) [a, b] = [b, a]; return bin(O.MULIF, a, b, FIX); }
|
||||
if (tk === TK.DIV && ND(a).ty === FIX && ND(b).ty === INT) return bin(O.DIVFI, a, b, FIX);
|
||||
a = tofix(a); b = tofix(b);
|
||||
return bin(OPF[tk], a, b, tk >= TK.LT && tk <= TK.NE ? INT : FIX);
|
||||
}
|
||||
const ws = () => { while (c.i < len && " \t\n\r".includes(c.s[c.i])) c.i++; };
|
||||
function eat(t) {
|
||||
ws();
|
||||
let k = 0;
|
||||
while (k < t.length && c.i + k < len && c.s[c.i + k] === t[k]) k++;
|
||||
if (k < t.length) return false;
|
||||
if (t.length === 1 && c.i + 1 < len) {
|
||||
const n = c.s[c.i + 1];
|
||||
if ((t === "<" || t === ">") && (n === t || n === "=")) return false;
|
||||
if ((t === "&" || t === "|") && n === t) return false;
|
||||
if ((t === "=" || t === "!") && n === "=") return false;
|
||||
}
|
||||
c.i += k; return true;
|
||||
}
|
||||
const isal = (x) => (x >= 97 && x <= 122) || (x >= 65 && x <= 90) || x === 95, isdg = (x) => x >= 48 && x <= 57;
|
||||
function number() {
|
||||
let v = 0, fr = 0, sc = 1, isf = false;
|
||||
if (ch() === 48 && c.i + 1 < len && (c.s[c.i + 1] === "x" || c.s[c.i + 1] === "X")) {
|
||||
c.i += 2;
|
||||
for (;;) { const x = ch(); let d; if (isdg(x)) d = x - 48; else if (x >= 97 && x <= 102) d = x - 87; else if (x >= 65 && x <= 70) d = x - 55; else break; v = U(Math.imul(v, 16) + d); c.i++; }
|
||||
} else {
|
||||
while (isdg(ch())) { v = U(Math.imul(v, 10) + ch() - 48); c.i++; }
|
||||
if (ch() === 46) { isf = true; c.i++; while (isdg(ch())) { if (sc < 100000000) { fr = fr * 10 + ch() - 48; sc *= 10; } c.i++; } }
|
||||
}
|
||||
while (ch() === 117 || ch() === 85) c.i++;
|
||||
if (isf) return num(FIX, U((v << 16) + Number((BigInt(fr) * 65536n + BigInt(Math.floor(sc / 2))) / BigInt(sc))));
|
||||
return num(INT, v);
|
||||
}
|
||||
function call(nm, ar) {
|
||||
const a = ar[0], b = ar[1], fx = ND(a).ty === FIX;
|
||||
switch (nm) {
|
||||
case "note": case "chord": case "kick": case "snare": case "hat": fail(2); return 0; /* (FUNC's: not here) */
|
||||
case "sin": return fx ? un(O.SINF, a, FIX) : un(O.SINI, a, INT);
|
||||
case "cos": return fx ? un(O.SINF, bin(O.ADD, a, num(FIX, 16384), FIX), FIX) : un(O.SINI, bin(O.ADD, a, num(INT, 64), INT), INT);
|
||||
case "tri": return fx ? un(O.TRIF, a, FIX) : un(O.TRII, a, INT);
|
||||
case "saw": return fx ? un(O.SAWF, a, FIX) : un(O.SAWI, a, INT);
|
||||
case "sqr": return fx ? un(O.SQRF, a, FIX) : un(O.SQRI, a, INT);
|
||||
case "abs": return un(O.ABS, a, ND(a).ty);
|
||||
case "min": return binop(TK.MIN, a, b); case "max": return binop(TK.MAX, a, b);
|
||||
case "floor": return fx ? un(O.FLOOR, a, FIX) : a;
|
||||
case "int": return toint(a); case "fix": return tofix(a);
|
||||
case "rnd": return fx ? un(O.RNDF, a, FIX) : un(O.RNDI, a, INT);
|
||||
case "sat": return un(O.SAT, tofix(a), FIX);
|
||||
case "clip": return bin(O.MAXS, bin(O.MINS, tofix(a), num(FIX, 65536), FIX), num(FIX, U(-65536)), FIX);
|
||||
case "ph": return nw(NK.ST, O.PH, FIX, tofix(a), 0, 0, 0);
|
||||
case "eu": return bin(O.EU, toint(a), toint(b), INT);
|
||||
default: return nw(NK.ST, nm === "lp" ? O.LP : O.HP, FIX, tofix(a), tofix(b), 0, 0);
|
||||
}
|
||||
}
|
||||
function primary() {
|
||||
ws();
|
||||
const x = ch();
|
||||
if (isdg(x) || (x === 46 && c.i + 1 < len && isdg(c.s.charCodeAt(c.i + 1)))) return number();
|
||||
if (x === 40) { c.i++; const k = expr(); if (!eat(")")) fail(1); return k; }
|
||||
if (x === 34 || x === 39) { /* a string as a table: "..."[i] */
|
||||
const q = c.s[c.i], st0 = c.pool.length;
|
||||
let st = st0, n = 0;
|
||||
c.i++;
|
||||
while (c.i < len && c.s[c.i] !== q) { if (c.pool.length >= POOL) { fail(7); return 0; } c.pool.push(c.s.charCodeAt(c.i++) & 255); n++; }
|
||||
if (c.s[c.i] !== q || !n || n > 255) { fail(1); return 0; }
|
||||
c.i++;
|
||||
for (let k0 = 0; k0 + n <= st0; k0++) { /* (the same string once) */
|
||||
let j = 0;
|
||||
while (j < n && c.pool[k0 + j] === c.pool[st0 + j]) j++;
|
||||
if (j === n) { c.pool.length = st0; st = k0; break; }
|
||||
}
|
||||
if (!eat("[")) { fail(1); return 0; }
|
||||
const ix = toint(expr());
|
||||
if (!eat("]")) fail(1);
|
||||
if (ND(ix).kind === NK.NUM) return num(INT, c.pool[st + ND(ix).v % n]);
|
||||
return nw(NK.TAB, O.TAB, INT, ix, 0, 0, st << 8 | n);
|
||||
}
|
||||
if (isal(x)) {
|
||||
const s0 = c.i;
|
||||
while (isal(ch()) || isdg(ch())) c.i++;
|
||||
const nm = c.s.slice(s0, c.i);
|
||||
if (nm.length >= 8) { fail(2); return 0; }
|
||||
ws();
|
||||
if (ch() === 40) {
|
||||
c.i++;
|
||||
if (!Object.prototype.hasOwnProperty.call(CALLS, nm)) { c.i = s0; fail(2); return 0; }
|
||||
const ar = [];
|
||||
if (!eat(")")) {
|
||||
do { if (ar.length >= 3) { fail(3); return 0; } ar.push(cond()); } while (eat(","));
|
||||
if (!eat(")")) fail(1);
|
||||
}
|
||||
if (ar.length !== CALLS[nm]) { fail(3); return 0; }
|
||||
return call(nm, ar);
|
||||
}
|
||||
if (nm === "sr") return num(INT, FS);
|
||||
if (nm === "PI") return num(FIX, 205887);
|
||||
if (Object.prototype.hasOwnProperty.call(VARS, nm)) { const [k, ty, ix] = VARS[nm]; return nw(k, 0, ty, 0, 0, 0, ix); }
|
||||
c.i = s0; fail(2); return 0;
|
||||
}
|
||||
fail(1); return 0;
|
||||
}
|
||||
function unaryInner() {
|
||||
if (c.err) return 0;
|
||||
if (eat("-")) { const a = unary(); return un(O.NEG, a, ND(a).ty); }
|
||||
if (eat("+")) return unary();
|
||||
if (eat("~")) return un(O.NOT, toint(unary()), INT);
|
||||
if (eat("!")) return un(O.LNOT, unary(), INT);
|
||||
return primary();
|
||||
}
|
||||
function unary() { if (c.pd >= 16) { fail(5); return 0; } c.pd++; const r = unaryInner(); c.pd--; return r; }
|
||||
function binat() {
|
||||
ws();
|
||||
if (c.bati === c.i) return c.batk;
|
||||
c.bati = c.i; c.batk = -1;
|
||||
const a = c.s[c.i] || "", b = c.s[c.i + 1] || "";
|
||||
if (a === ">" && b === ">" && c.s[c.i + 2] === ">") return (c.batk = BINS.length);
|
||||
for (let k = 0; k < BINS.length; k++) {
|
||||
const t = BINS[k][0];
|
||||
if (t[0] !== a) continue;
|
||||
if (t.length > 1) { if (t[1] === b) return (c.batk = k); continue; }
|
||||
if ((a === "<" || a === ">") && (b === a || b === "=")) continue;
|
||||
if ((a === "&" || a === "|") && b === a) continue;
|
||||
if ((a === "=" || a === "!") && b === "=") continue;
|
||||
return (c.batk = k);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
function level(lv) {
|
||||
let a = lv ? level(lv - 1) : unary();
|
||||
for (;;) {
|
||||
if (c.err) return 0;
|
||||
const k = binat();
|
||||
if (k === BINS.length && lv === 2) { c.i += 3; a = binop(TK.SHR, a, level(1)); }
|
||||
else if (k >= 0 && k < BINS.length && BINS[k][1] === lv) { c.i += BINS[k][0].length; a = binop(BINS[k][2], a, lv ? level(lv - 1) : unary()); }
|
||||
else return a;
|
||||
}
|
||||
}
|
||||
function cond() {
|
||||
const q = level(9);
|
||||
if (c.err || !eat("?")) return q;
|
||||
let x = expr();
|
||||
if (!eat(":")) { fail(1); return 0; }
|
||||
let y = cond();
|
||||
if (ND(x).ty !== ND(y).ty) { x = tofix(x); y = tofix(y); }
|
||||
if (ND(q).kind === NK.NUM) return ND(q).v ? x : y;
|
||||
return nw(NK.SEL, O.SEL, ND(x).ty, q, x, y, 0);
|
||||
}
|
||||
function expr() { let a = cond(); while (!c.err && eat(",")) a = cond(); return a; }
|
||||
/* the tree to the instructions */
|
||||
const emit = (op, md, k) => { if (c.ins.length >= MAXINS) { fail(4); return; } c.ins.push({ op, md, k: k >>> 0 }); };
|
||||
const psp = (d) => { c.sp += d; if (c.sp > c.maxsp) c.maxsp = c.sp; };
|
||||
const leaf = (n) => (n.kind === NK.NUM ? IMM : n.kind === NK.UNI ? UNI : n.kind === NK.ARR ? ARR : STK);
|
||||
const commut = (op) => [O.ADD, O.MUL, O.AND, O.OR, O.XOR, O.EQ, O.NE, O.LAND, O.LOR, O.MINU, O.MAXU, O.MINS, O.MAXS, O.MULF].includes(op);
|
||||
const MIRROR = { [O.LTU]: O.GTU, [O.GTU]: O.LTU, [O.LEU]: O.GEU, [O.GEU]: O.LEU, [O.LTS]: O.GTS, [O.GTS]: O.LTS, [O.LES]: O.GES, [O.GES]: O.LES };
|
||||
const mirror = (op) => (op in MIRROR ? MIRROR[op] : commut(op) ? op : O.NBIN);
|
||||
function gen(x) { if (c.gd >= 24) { fail(5); return; } c.gd++; genInner(x); c.gd--; }
|
||||
function genInner(x) {
|
||||
const n = ND(x);
|
||||
if (c.err) return;
|
||||
switch (n.kind) {
|
||||
case NK.NUM: case NK.UNI: case NK.ARR: emit(O.PUSH, leaf(n), n.v); psp(1); return;
|
||||
case NK.OP1: gen(n.a); emit(n.op, STK, 0); return;
|
||||
case NK.TAB: gen(n.a); emit(O.TAB, STK, n.v); return;
|
||||
case NK.SEL: gen(n.a); gen(n.b); gen(n.c); emit(O.SEL, STK, 0); psp(-2); return;
|
||||
case NK.ST: {
|
||||
gen(n.a);
|
||||
if (n.op === O.PH) { emit(O.PH, STK, 0); return; }
|
||||
const md = leaf(ND(n.b));
|
||||
if (md === STK) { gen(n.b); psp(-1); }
|
||||
emit(n.op, md, ND(n.b).v); return;
|
||||
}
|
||||
case NK.OP2: {
|
||||
let op = n.op, l = n.a, r = n.b;
|
||||
const ml = leaf(ND(l));
|
||||
let md = leaf(ND(r));
|
||||
if (md === STK && ml !== STK && mirror(op) !== O.NBIN) { op = mirror(op); r = n.a; l = n.b; md = leaf(ND(r)); }
|
||||
gen(l);
|
||||
if (md === STK) { gen(r); psp(-1); }
|
||||
emit(op, md, md === STK ? 0 : ND(r).v); return;
|
||||
}
|
||||
}
|
||||
}
|
||||
ws();
|
||||
let ty = INT;
|
||||
if (c.i >= len) c.err = 9;
|
||||
else if (/^func\b/.test(c.s.slice(c.i))) fail(2);
|
||||
else {
|
||||
const root = expr();
|
||||
ws();
|
||||
if (!c.err && c.i < len) fail(1);
|
||||
if (!c.err) { ty = ND(root).ty; gen(root); }
|
||||
if (!c.err && c.maxsp > DEPTH) fail(5);
|
||||
}
|
||||
return { err: c.err, pos: c.pos, ins: c.ins, pool: c.pool, ty, depth: c.maxsp };
|
||||
}
|
||||
/* compile: {ok, code (the bytes), ty, fix, depth} or {ok: false, error, pos} */
|
||||
function compile(src) {
|
||||
const r = compileIns(src);
|
||||
if (r.err) return { ok: false, error: ERR[r.err] || "error", pos: r.pos };
|
||||
const out = [r.ty | (r.pool.length ? 2 : 0)];
|
||||
if (r.pool.length) out.push(r.pool.length, ...r.pool);
|
||||
const leb = (k) => { do { const b = k & 127; k >>>= 7; out.push(b | (k ? 128 : 0)); } while (k); };
|
||||
for (const ins of r.ins) {
|
||||
if (ins.op === O.PH || ins.op === O.LP || ins.op === O.HP || ins.op === O.EU || ins.op > O.TAB)
|
||||
return { ok: false, error: "ph() lp() hp() eu(): JIANT BYTE's only, not in JIANT FM", pos: 0 };
|
||||
if (ins.md === ARR && ins.k === 0) { out.push(ins.op | 3 << 6); continue; }
|
||||
out.push(ins.op | (ins.md === STK ? 0 : ins.md === IMM ? 1 : 2) << 6);
|
||||
if (ins.op === O.TAB || ins.md === IMM) leb(ins.k);
|
||||
else if (ins.md === UNI) out.push(ins.k);
|
||||
else if (ins.md === ARR) out.push(128 | ins.k);
|
||||
}
|
||||
if (out.length > MAX) return { ok: false, error: `too long for JIANT FM (${out.length} of ${MAX} bytes)`, pos: 0 };
|
||||
return { ok: true, code: out, ty: r.ty, fix: r.ty === FIX, depth: r.depth };
|
||||
}
|
||||
/* the bytes run as math_user.c mu_run runs them (the same values; its masks: any bytes) */
|
||||
function run(code, t, w, a, n = 60, v = 100) {
|
||||
const s = new Uint32Array(16), u = [a >>> 0, n, v], e = Math.min(code.length, MAX);
|
||||
let sp = 0, p = 1;
|
||||
if (code[0] & 2) p = 2 + (code[1] & 31);
|
||||
while (p < e) {
|
||||
let o = code[p++] | 0, b = 0, k;
|
||||
const md = o >> 6;
|
||||
o &= 63;
|
||||
if (md === 1 || o === O.TAB) { for (let sh = 0; sh < 32; sh += 7) { k = code[p++] | 0; b = U(b | (k & 127) << sh); if (!(k & 128)) break; } }
|
||||
else if (md === 2) { k = code[p++] | 0; b = k === 128 ? t >>> 0 : k === 129 ? w >>> 0 : k === 0 ? u[0] : k === 8 ? u[1] : k === 9 ? u[2] : 0; }
|
||||
else if (md === 3) b = t >>> 0;
|
||||
else if (o < O.NBIN) b = s[--sp & 15];
|
||||
if (o === O.PUSH) { s[sp++ & 15] = b; continue; }
|
||||
const i = (sp - 1) & 15;
|
||||
if (o === O.SEL) { sp -= 2; s[(sp - 1) & 15] = s[(sp - 1) & 15] ? s[sp & 15] : s[(sp + 1) & 15]; }
|
||||
else if (o === O.TAB) { k = b & 255; s[i] = k ? (code[2 + (((b >>> 8) + s[i] % k) & 31)] | 0) : 0; }
|
||||
else s[i] = o < O.NBIN ? op2(o, s[i], b) : op1(o, s[i]);
|
||||
}
|
||||
return s[0];
|
||||
}
|
||||
/* the sample it plays (BYTE's fvm_sample: INT its low byte as bytebeat, FIX -1 .. 1), Q15 */
|
||||
const sample = (code, x) => ((code[0] & 1) ? Math.max(-32767, Math.min(32767, (x | 0) >> 1)) : (x & 255) * 256 - 32640);
|
||||
/* pack7 (BACKUP_PUT's groups: a byte of the group's bits 7, then up to 7 bytes) and back */
|
||||
function pack7(b) {
|
||||
const o = [];
|
||||
for (let i = 0; i < b.length; i += 7) {
|
||||
const g = b.slice(i, i + 7);
|
||||
let m = 0;
|
||||
g.forEach((x, j) => { m |= (x >> 7) << j; });
|
||||
o.push(m, ...g.map((x) => x & 127));
|
||||
}
|
||||
return o;
|
||||
}
|
||||
function unpack7(a) {
|
||||
const o = [];
|
||||
for (let i = 0; i < a.length;) { const m = a[i++], k = Math.min(7, a.length - i); for (let j = 0; j < k; j++) o.push(a[i++] | ((m >> j) & 1) << 7); }
|
||||
return o;
|
||||
}
|
||||
return { compile, run, sample, pack7, unpack7, MAX, DEPTH, O, hash };
|
||||
})();
|
||||
/* eng_lofi.c lofi_mut: VAR as a mutation of the time (v >> 4 the way, v & 15 how much) */
|
||||
function mathMut(t, v) {
|
||||
const k = v & 15;
|
||||
@@ -3281,8 +3660,9 @@ function mathScore(fn, a) {
|
||||
/* a MATH sound's eight values (P_E0..P_E7, eng_lofi.c ENG_LOFI .edit): BYTE {CHIP, WAVE 5 (7: SYNC), ALGO, VARIANT,
|
||||
MOTION, GRIT, BEND, LOOP}; FLOAT {ALGO B, WAVE 6, ALGO, VARIANT, MOTION, FEEDBK, MORPH, LOOP}. ALGO is the formula x 4 */
|
||||
function mathValues(o) {
|
||||
return o.wave === 6 ? [(o.algoB | 0) * 4, 6, o.f * 4, o.var | 0, o.motion | 0, o.fbk | 0, o.morph | 0, o.loop | 0]
|
||||
: [o.chip ?? 2, o.sync ? 7 : 5, o.f * 4, o.var | 0, o.motion | 0, o.grit | 0, o.bend | 0, o.loop | 0];
|
||||
const algo = o.user ? -4 : o.f * 4; /* (V10.8.75) ALGO USER: -4, the track's own formula */
|
||||
return o.wave === 6 ? [(o.algoB | 0) * 4, 6, algo, o.var | 0, o.motion | 0, o.fbk | 0, o.morph | 0, o.loop | 0]
|
||||
: [o.chip ?? 2, o.sync ? 7 : 5, algo, o.var | 0, o.motion | 0, o.grit | 0, o.bend | 0, o.loop | 0];
|
||||
}
|
||||
/* the emulator (felucca.wasm with editor-api.h) playing it: a fresh device, track 1 made MATH as the editor's send does
|
||||
(SET of G_ENGSEL: the engine and its first preset, then the eight values), the other tracks out of the mix, a note on
|
||||
@@ -3298,6 +3678,8 @@ function mathEmuRender(ex, o) {
|
||||
const info = ed([1]), pe0 = info ? info[info.indexOf(0) + 5] : 115; /* (INFO: version, 0, NENGINES P_COUNT G_COUNT NSTEP P_E0) */
|
||||
const dry = o.dry ? { 113: 127, 114: 0, 33: 0, 34: 0, 35: 0, 36: 0, 1: 0, 3: 127, 5: 0, 6: 0, 7: 0, 51: 0, 54: 0, 57: 0, 60: 0, 13: 0, 14: 0, 15: 0, 16: 0 } : {};
|
||||
for (const [id, v] of Object.entries(dry)) ed([31, 0, +id, ...v14(v)]);
|
||||
const fr = o.code ? ed([100, 0, 1, ...FVM.pack7(o.code)]) : null; /* (V10.8.75) MATH USER: track 1's formula, the device's
|
||||
VM (null: a firmware without FORMULA) */
|
||||
mathValues(o).forEach((v, k) => ed([31, 0, pe0 + k, ...v14(v)]));
|
||||
ex.web_mix_skip(0x3E);
|
||||
for (let i = 0; i < 8; i++) ex.web_render(1024);
|
||||
@@ -3311,7 +3693,7 @@ function mathEmuRender(ex, o) {
|
||||
l.set(new Float32Array(ex.memory.buffer, ex.web_out_l(), m), k);
|
||||
r.set(new Float32Array(ex.memory.buffer, ex.web_out_r(), m), k);
|
||||
}
|
||||
return { l, r };
|
||||
return { l, r, formula: !!(fr && fr[1] === 0) };
|
||||
}
|
||||
/*MATH-END*/
|
||||
|
||||
@@ -3417,15 +3799,15 @@ const TEXT = {
|
||||
devicePending: "反映しました。再生を停止すると保存されます。",
|
||||
|
||||
other: "English", connect: "接続", disconnect: "切断", mock: "モック(実機なし)",
|
||||
tabMath: "MATH", mathHelp: "MATH の数式。BYTE はバイトビート(時間 t の式、その下位 8 ビットが音)、FLOAT はその正弦版です。本体の 48 + 48 から選び、編集または自作し、試聴、生成、トラックへ送信できます。本体は内蔵の数式だけを演奏します。自作の数式はここで(MATH の BYTE ボイスのモデルで)聴けますが、ファームウェアがユーザー数式に対応するまで送れません(EDITOR_PROTOCOL.md の提案を参照)。",
|
||||
tabMath: "MATH", mathHelp: "MATH の数式。BYTE はバイトビート(時間 t の式、その下位 8 ビットが音)、FLOAT はその正弦版です。本体の 48 + 48 から選ぶか、自作の数式を書いて(JIANT BYTE と同じ言語: t w a n v、sin cos tri saw sqr abs min max floor int fix rnd sat clip、\"...\"[i] の表)、試聴、生成、トラックへ送信できます。自作の数式は V10.8.75 以降の本体で MATH USER(ALGO USER)として演奏されます: 64 バイトまで。",
|
||||
mathGrammarT: "文法(ファームウェアと同じ)", mathGrammar: "t: 時間。ノート 1 周期に 31 ステップ(C4 で約 8 kHz)。MOTION は遅いビットの速さ(0: 1/16、64: そのまま、128..255 SYNC: 小節に同期)、LOOP は t を窓に閉じ込め、VARIANT は t を変形(方法: VAR / 16、量: VAR % 16)し a = 1 + VAR / 8(1..16)を与え、BEND は t を折り返します。\n数値: 123、0x1F(u は任意)。演算子は C と同じで、すべて符号なし 32 ビット: ( )、単項 - ~ !、* / %、+ -、<< >>、< <= > >=、== !=、&、^、|、&&、||、c ? x : y。比較と ! は 0 か 1。下位 8 ビットが鳴ります(CHIP: 8、4、1 ビット)。\n例(本体): t * (42 & t >> 10) · t * (0xCA98 >> (t >> 9 & 14) & 15) | t >> 8 · (t >> 13 | t % 24) & (t >> 7 | t % 19)。",
|
||||
mathOwn: "— 自作 —", mathFloatRo: "FLOAT の数式はファームウェアの C(固定小数点の正弦)です。試聴と送信のみ。編集は BYTE で。",
|
||||
mathErr: "エラー:", mathAt: "位置", mathIsStock: "本体の数式: 送信できます", mathOwnOk: "自作の数式: ここで試聴のみ、送信不可", mathTerms: "項",
|
||||
mathErr: "エラー:", mathAt: "位置", mathIsStock: "本体の数式: 送信できます", mathOwnOk: "自作の数式(MATH USER)", mathTerms: "項",
|
||||
mathPlay: "再生", mathStop: "停止", mathLoop: "ループ", mathRendering: "計算中…", mathNoEmu: "エミュレーターに届きません: FLOAT は試聴できません。",
|
||||
mathFixFirst: "先に数式を直してください。", mathSrcEmu: "試聴: エミュレーターのサンプル(本体のコード)", mathSrcModel: "試聴: MATH の BYTE ボイスのモデル(自作の数式)",
|
||||
mathSeed: "シード", mathGen: "数式を生成", mathGenPatch: "音色を生成", mathGenerated: "生成しました: シード",
|
||||
mathSend: "トラックへ送る", mathRead: "トラックから読む", mathConnect: "送るには FM-1(またはエミュレーター)を接続してください。",
|
||||
mathOwnNoSend: "送信不可: 本体は内蔵の BYTE 数式 48 個のみ演奏します。", mathSent: "送信しました:", mathSentClamped: "送信しました(本体が一部の値を補正):",
|
||||
mathOwnNoSend: "送信不可: この本体のファームウェアは自作の数式(V10.8.75 の MATH USER)に未対応です。", mathUserSend: "自作の数式: トラックの数式として送り、ALGO を USER にします。", mathUserRefused: "本体が数式を拒否しました:", mathReadUser: "読みました(数式のテキストはこのブラウザにありません):", mathSent: "送信しました:", mathSentClamped: "送信しました(本体が一部の値を補正):",
|
||||
mathNotMath: "MATH トラックではありません:", mathReadOk: "読みました:",
|
||||
tabRoll: "ピアノロール", rollFit: "全体表示", rollUndo: "元に戻す", rollReading: "ステップを読み込み中", rollGrid: "DRUM グリッド", rollNotes: "ノート",
|
||||
rollHelp: "空いたマスをタップするとノートを追加します(DRUM トラックではヒット)。ノートをタップすると選択、もう一度タップで削除。ノートを上下にドラッグで音程、右へドラッグで長さ(TIE ステップ)。それ以外のドラッグでスクロール、ピンチ(または Ctrl + ホイール)でズーム。上の帯で小節へ移動、下のレーンでベロシティ・チャンス・ラチェットを描きます。キー: 矢印、Delete、A アクセント、S スライド、Ctrl+Z 元に戻す。変更はすぐにトラックへ書き込まれます。",
|
||||
@@ -3545,15 +3927,15 @@ const TEXT = {
|
||||
devicePending: "Applied. Settings will save when playback stops.",
|
||||
|
||||
other: "Español", connect: "Connect", disconnect: "Disconnect", mock: "Mock device (no hardware)",
|
||||
tabMath: "MATH", mathHelp: "MATH's formulas. BYTE is bytebeat: a formula of the time t whose low 8 bits are the sound; FLOAT its sibling of sines. Pick one of the device's 48 + 48, edit it or write your own, hear it, generate one, and send it to a track. The device plays only its own formulas: a formula of yours is heard here (the model of MATH's BYTE voice) but cannot be sent until the firmware takes user formulas (see the proposal in EDITOR_PROTOCOL.md).",
|
||||
tabMath: "MATH", mathHelp: "MATH's formulas. BYTE is bytebeat: a formula of the time t whose low 8 bits are the sound; FLOAT its sibling of sines. Pick one of the device's 48 + 48 or write your own (JIANT BYTE's language: t w a n v, sin cos tri saw sqr abs min max floor int fix rnd sat clip, a \"...\"[i] table), hear it, generate one, and send it to a track. From V10.8.75 the device plays your own as MATH USER (ALGO USER): up to 64 bytes of its bytecode.",
|
||||
mathGrammarT: "Grammar (the firmware's)", mathGrammar: "t: the time, 31 steps a cycle of the note (C4: about 8 kHz); MOTION runs its slow bits at their own speed (0: 1/16, 64: as written, 128..255 SYNC: on the bar), LOOP holds t in a window, VARIANT mutates t (its way: VAR / 16, how much: VAR % 16) and gives a = 1 + VAR / 8 (1..16), BEND folds t.\nNumbers: 123, 0x1F (an optional u). Operators as in C, all unsigned 32-bit: ( ), unary - ~ !, then * / %, + -, << >>, < <= > >=, == !=, &, ^, |, &&, ||, c ? x : y. A comparison or ! gives 0 or 1. The low 8 bits are played (CHIP: 8, 4 or 1 of them).\nExamples (the device's): t * (42 & t >> 10) · t * (0xCA98 >> (t >> 9 & 14) & 15) | t >> 8 · (t >> 13 | t % 24) & (t >> 7 | t % 19).",
|
||||
mathOwn: "— your own —", mathFloatRo: "FLOAT's formulas are the firmware's own C (sines in fixed point): listen and send; edit BYTE formulas.",
|
||||
mathErr: "Error:", mathAt: "at", mathIsStock: "the device's own formula: it can be sent", mathOwnOk: "Your formula: heard here, not sendable", mathTerms: "terms",
|
||||
mathErr: "Error:", mathAt: "at", mathIsStock: "the device's own formula: it can be sent", mathOwnOk: "Your formula (MATH USER)", mathTerms: "terms",
|
||||
mathPlay: "Play", mathStop: "Stop", mathLoop: "Loop", mathRendering: "Rendering…", mathNoEmu: "The emulator is not reachable from here: no sound for FLOAT.",
|
||||
mathFixFirst: "Fix the formula first.", mathSrcEmu: "Heard: the emulator's own samples (the device's code)", mathSrcModel: "Heard: the model of MATH's BYTE voice (your formula)",
|
||||
mathSeed: "Seed", mathGen: "Generate formula", mathGenPatch: "Generate sound", mathGenerated: "Generated: seed",
|
||||
mathSend: "Send to track", mathRead: "Read track", mathConnect: "Connect the FM-1 (or the emulator) to send.",
|
||||
mathOwnNoSend: "Not sendable: the device plays its own 48 BYTE formulas only.", mathSent: "Sent to", mathSentClamped: "Sent (some values clamped by the device) to",
|
||||
mathOwnNoSend: "Not sendable: this device's firmware has no formulas of one's own (MATH USER, V10.8.75).", mathUserSend: "Your formula: sent as the track's own, ALGO set to USER.", mathUserRefused: "The device refused the formula:", mathReadUser: "Read (the formula's text is not in this browser) from", mathSent: "Sent to", mathSentClamped: "Sent (some values clamped by the device) to",
|
||||
mathNotMath: "Not a MATH track:", mathReadOk: "Read from",
|
||||
tabRoll: "Piano roll", rollFit: "Fit", rollUndo: "Undo", rollReading: "Reading the steps", rollGrid: "DRUM grid", rollNotes: "notes",
|
||||
rollHelp: "Tap an empty cell to add a note (a hit on a DRUM track); tap a note to select it, tap it again to remove it. Drag a note up or down to change its pitch, to the right to hold it (TIE steps). Drag elsewhere to scroll, pinch (or Ctrl + wheel) to zoom. The strip at the top jumps to a bar; the lane at the bottom draws velocity, chance or ratchet. Keys: arrows, Delete, A accent, S slide, Ctrl+Z undo. Every change is written to the track at once.",
|
||||
@@ -3629,15 +4011,15 @@ const TEXT = {
|
||||
userBank: "User presets", none: "none",
|
||||
},
|
||||
es: {
|
||||
tabMath: "MATH", mathHelp: "Las fórmulas de MATH. BYTE es bytebeat: una fórmula del tiempo t cuyos 8 bits bajos son el sonido; FLOAT, su hermana de senos. Elegí una de las 48 + 48 del equipo, editala o escribí la tuya, escuchala, generá una y mandala a una pista. El equipo toca solo sus propias fórmulas: una tuya se escucha acá (el modelo de la voz BYTE de MATH) pero no se puede mandar hasta que el firmware acepte fórmulas de usuario (ver la propuesta en EDITOR_PROTOCOL.md).",
|
||||
tabMath: "MATH", mathHelp: "Las fórmulas de MATH. BYTE es bytebeat: una fórmula del tiempo t cuyos 8 bits bajos son el sonido; FLOAT, su hermana de senos. Elegí una de las 48 + 48 del equipo o escribí la tuya (el lenguaje de JIANT BYTE: t w a n v, sin cos tri saw sqr abs min max floor int fix rnd sat clip, una tabla \"...\"[i]), escuchala, generá una y mandala a una pista. Desde V10.8.75 el equipo toca la tuya como MATH USER (ALGO USER): hasta 64 bytes de su bytecode.",
|
||||
mathGrammarT: "Gramática (la del firmware)", mathGrammar: "t: el tiempo, 31 pasos por ciclo de la nota (C4: unos 8 kHz); MOTION mueve sus bits lentos a su propia velocidad (0: 1/16, 64: tal cual, 128..255 SYNC: con el compás), LOOP encierra t en una ventana, VARIANT muta t (la forma: VAR / 16, cuánto: VAR % 16) y da a = 1 + VAR / 8 (1..16), BEND pliega t.\nNúmeros: 123, 0x1F (con u opcional). Operadores como en C, todo sin signo de 32 bits: ( ), unarios - ~ !, luego * / %, + -, << >>, < <= > >=, == !=, &, ^, |, &&, ||, c ? x : y. Una comparación o ! da 0 o 1. Suenan los 8 bits bajos (CHIP: 8, 4 o 1).\nEjemplos (del equipo): t * (42 & t >> 10) · t * (0xCA98 >> (t >> 9 & 14) & 15) | t >> 8 · (t >> 13 | t % 24) & (t >> 7 | t % 19).",
|
||||
mathOwn: "— la tuya —", mathFloatRo: "Las fórmulas FLOAT son el C del firmware (senos en punto fijo): escuchalas y mandalas; se editan las BYTE.",
|
||||
mathErr: "Error:", mathAt: "en", mathIsStock: "una fórmula del equipo: se puede mandar", mathOwnOk: "Tu fórmula: se escucha acá, no se puede mandar", mathTerms: "términos",
|
||||
mathErr: "Error:", mathAt: "en", mathIsStock: "una fórmula del equipo: se puede mandar", mathOwnOk: "Tu fórmula (MATH USER)", mathTerms: "términos",
|
||||
mathPlay: "Tocar", mathStop: "Parar", mathLoop: "Repetir", mathRendering: "Calculando…", mathNoEmu: "No se llega al emulador desde acá: FLOAT sin sonido.",
|
||||
mathFixFirst: "Corregí la fórmula primero.", mathSrcEmu: "Suena: las muestras del emulador (el código del equipo)", mathSrcModel: "Suena: el modelo de la voz BYTE de MATH (tu fórmula)",
|
||||
mathSeed: "Semilla", mathGen: "Generar fórmula", mathGenPatch: "Generar sonido", mathGenerated: "Generado: semilla",
|
||||
mathSend: "Mandar a la pista", mathRead: "Leer pista", mathConnect: "Conectá el FM-1 (o el emulador) para mandar.",
|
||||
mathOwnNoSend: "No se puede mandar: el equipo toca solo sus 48 fórmulas BYTE.", mathSent: "Mandado a", mathSentClamped: "Mandado (el equipo ajustó algún valor) a",
|
||||
mathOwnNoSend: "No se puede mandar: el firmware de este equipo no tiene fórmulas propias (MATH USER, V10.8.75).", mathUserSend: "Tu fórmula: va como la fórmula propia de la pista, ALGO en USER.", mathUserRefused: "El equipo rechazó la fórmula:", mathReadUser: "Leído (el texto de la fórmula no está en este navegador) de", mathSent: "Mandado a", mathSentClamped: "Mandado (el equipo ajustó algún valor) a",
|
||||
mathNotMath: "No es una pista MATH:", mathReadOk: "Leído de", track: "Pista",
|
||||
other: "日本語", connect: "Conectar", disconnect: "Desconectar", sound: "Sonido", tabSeq: "Secuenciador", tabTracks: "Pistas",
|
||||
tabSettings: "Ajustes", library: "Biblioteca", projects: "Proyectos", reload: "Releer", remove: "Quitar", time: "Tiempo",
|
||||
@@ -6642,9 +7024,11 @@ function rollBuild() {
|
||||
/* ============================================================ MATH (the formula editor) === */
|
||||
/* MATH's formulas: write or edit one (BYTE: the VM above, the firmware's grammar), its picture, its sound (the emulator's
|
||||
own samples when the device can play it: one of the firmware's formulas; the BYTE model otherwise), a seeded
|
||||
generator, and a send to a track (the eight values by TRACK_PARAM after the engine). The device plays its 48 + 48
|
||||
formulas only: a formula of one's own stays in the browser (the proposal: EDITOR_PROTOCOL.md "a user formula"). Nothing
|
||||
is built or run until the tab opens; audio only on Play */
|
||||
generator, and a send to a track (the eight values by TRACK_PARAM after the engine). (V10.8.75) A formula of one's own
|
||||
is MATH USER: compiled here to the device's bytecode (FVM, JIANT BYTE's compiler), heard through the emulator's own
|
||||
machine (else the model), sent with FORMULA (100) and ALGO USER (-4) to a device whose INFO says 'E' (EDITOR_PROTOCOL.md
|
||||
"1.5"); an older device keeps it in the browser, as before. Nothing is built or run until the tab opens; audio only on
|
||||
Play */
|
||||
const MATH_ENG = 3; /* the engine byte: LOFI, named MATH by INFO */
|
||||
const mth = { built: false, wave: 5, f: 0, c: null, src: "", seed: 1, ctx: null, node: null, mod: null, modTried: false, raf: 0,
|
||||
v: { note: 60, chip: 2, var: 0, motion: 0, grit: 0, bend: 0, loop: 0, sync: 0, algoB: 0, fbk: 0, morph: 0 } };
|
||||
@@ -6702,11 +7086,23 @@ function mathInsert(s) {
|
||||
ta.selectionStart = ta.selectionEnd = a + s.length; ta.focus();
|
||||
mathCompile();
|
||||
}
|
||||
/* (V10.8.75) a text: one of the firmware's own (MathVM recognises it: sent as its ALGO), else a formula of one's own,
|
||||
MATH USER: compiled to the device's bytecode (FVM, JIANT BYTE's compiler), run by the same machine for the picture and
|
||||
the model; FIX (a number with a point, sin(w) ..) is a floatbeat, sent with WAVE FLOAT */
|
||||
function mathCompileSrc(src) {
|
||||
const s = MathVM.compile(src);
|
||||
if (s.ok && s.stock >= 0) return s;
|
||||
const f = FVM.compile(src);
|
||||
if (!f.ok) return { ok: false, error: f.error, pos: f.pos };
|
||||
const code = f.code;
|
||||
const fn = f.fix ? (t, a) => ((FVM.sample(code, FVM.run(code, t, (t << 11) >>> 0, a)) >> 8) + 128) & 255 : (t, a) => FVM.run(code, t, 0, a) & 255;
|
||||
return { ok: true, stock: -1, user: true, fvm: f, fn, size: code.length, usesA: /\ba\b/.test(src) };
|
||||
}
|
||||
/* the formula checked as typed: its error and where, or what it is (one of the firmware's: sendable) */
|
||||
function mathCompile() {
|
||||
const src = $("mf").value, msg = $("merr");
|
||||
if (mth.wave === 6) { mth.c = null; msg.className = "dim"; msg.textContent = t("mathFloatRo"); mathPicture(); mathSendUi(); return; }
|
||||
mth.c = MathVM.compile(src);
|
||||
mth.c = mathCompileSrc(src);
|
||||
if (!mth.c.ok) {
|
||||
msg.className = "merr bad";
|
||||
msg.textContent = `${t("mathErr")} ${mth.c.error} (${t("mathAt")} ${mth.c.pos + 1}): ${src.slice(Math.max(0, mth.c.pos - 12), mth.c.pos)}▸${src.slice(mth.c.pos, mth.c.pos + 12)}`;
|
||||
@@ -6714,7 +7110,8 @@ function mathCompile() {
|
||||
if (mth.c.stock >= 0) mth.f = mth.c.stock;
|
||||
$("mstock").value = String(mth.c.stock >= 0 ? mth.c.stock : -1);
|
||||
msg.className = "merr ok";
|
||||
msg.textContent = mth.c.stock >= 0 ? `B${String(mth.c.stock + 1).padStart(2, "0")} · ${t("mathIsStock")}` : `${t("mathOwnOk")} (${mth.c.size} ${t("mathTerms")}${mth.c.usesA ? ", a" : ""})`;
|
||||
msg.textContent = mth.c.stock >= 0 ? `B${String(mth.c.stock + 1).padStart(2, "0")} · ${t("mathIsStock")}` :
|
||||
`${t("mathOwnOk")} (USER · ${mth.c.fvm.code.length}/${FVM.MAX} B · ${mth.c.fvm.fix ? "FIX → FLOAT" : "INT → BYTE"})`;
|
||||
}
|
||||
mathPicture(); mathSendUi();
|
||||
}
|
||||
@@ -6773,10 +7170,16 @@ async function mathModule() {
|
||||
}
|
||||
async function mathRender() {
|
||||
const v = mth.v, secs = 3, o = { ...v, wave: mth.wave, f: mth.f, secs, gate: 2.4 };
|
||||
const exact = mth.wave === 6 || (mth.c && mth.c.ok && mth.c.stock >= 0);
|
||||
const user = mth.wave === 5 && mth.c && mth.c.ok && mth.c.user;
|
||||
const exact = mth.wave === 6 || (mth.c && mth.c.ok && mth.c.stock >= 0) || user;
|
||||
if (exact) {
|
||||
const m = await mathModule();
|
||||
if (m) { const inst = await WebAssembly.instantiate(m, {}); const r = mathEmuRender(inst.exports, o); return { ...r, src: "emu" }; }
|
||||
if (m) {
|
||||
const inst = await WebAssembly.instantiate(m, {});
|
||||
if (!user) return { ...mathEmuRender(inst.exports, o), src: "emu" };
|
||||
const r = mathEmuRender(inst.exports, { ...o, user: true, code: mth.c.fvm.code, wave: mth.c.fvm.fix ? 6 : 5 });
|
||||
if (r.formula) return { ...r, src: "emu" }; /* (V10.8.75: a firmware with FORMULA: the device's own VM) */
|
||||
}
|
||||
if (mth.wave === 6) return null;
|
||||
}
|
||||
if (!mth.c || !mth.c.ok) return null;
|
||||
@@ -6816,14 +7219,22 @@ function mathGenPatch() {
|
||||
mathLoadStock(f);
|
||||
sayK("mathGenerated", ` #${mth.seed}`);
|
||||
}
|
||||
/* (V10.8.75) the texts of the formulas sent from here (the device keeps the bytes only): by their bytes, in this browser */
|
||||
function mathTextKeep(code, src) {
|
||||
try { const m = JSON.parse(localStorage.getItem("jiantMathUser") || "{}"); m[code.join(",")] = src; const k = Object.keys(m); if (k.length > 200) delete m[k[0]]; localStorage.setItem("jiantMathUser", JSON.stringify(m)); } catch (e) { /* none */ }
|
||||
}
|
||||
function mathTextOf(code) {
|
||||
try { const m = JSON.parse(localStorage.getItem("jiantMathUser") || "{}"); return m[code.join(",")] ?? null; } catch (e) { return null; }
|
||||
}
|
||||
function mathSendUi() {
|
||||
const b = $("msend"), why = $("msendmsg"); if (!b) return;
|
||||
const ok = mth.wave === 6 || (mth.c && mth.c.ok && mth.c.stock >= 0);
|
||||
const user = mth.wave === 5 && mth.c && mth.c.ok && mth.c.user, has = !!(dev && dev.info && dev.info.formula);
|
||||
const ok = mth.wave === 6 || (mth.c && mth.c.ok && mth.c.stock >= 0) || (user && has);
|
||||
const ntrk = dev && dev.info && dev.info.ntrk ? dev.info.ntrk : 0, sel = $("mtrk");
|
||||
if (sel.options.length !== ntrk) sel.replaceChildren(...Array.from({ length: ntrk }, (_, i) => el("option", { value: i, text: `T${i + 1}` })));
|
||||
if (dev && dev.sel != null && !sel.dataset.touched) sel.value = String(dev.sel);
|
||||
b.disabled = !dev || !dev.dump || !ok || !ntrk; $("mread").disabled = !dev || !dev.dump || !ntrk;
|
||||
why.textContent = !dev ? t("mathConnect") : ok ? "" : t("mathOwnNoSend");
|
||||
why.textContent = !dev ? t("mathConnect") : ok ? (user ? t("mathUserSend") : "") : t("mathOwnNoSend");
|
||||
}
|
||||
/* the sound to a track: selected (TRACK), made MATH (SET of G_ENGSEL: the device's own engine change, its first preset),
|
||||
then its eight values (TRACK_PARAM), read back */
|
||||
@@ -6833,11 +7244,17 @@ async function mathSend() {
|
||||
if (tr !== (d.sel || 0)) d.sel = parse[CMD.TRACK](await rq(req.track(tr))).sel;
|
||||
const td = parse[CMD.TRACK_DUMP](await rq(req.trackDump(tr)), d.info);
|
||||
if (td.engine !== MATH_ENG) { selfLoad(true); await rq(req.set(1, gEng(), MATH_ENG)); }
|
||||
const vals = mathValues({ ...mth.v, wave: mth.wave, f: mth.f }), got = [];
|
||||
const user = mth.wave === 5 && mth.c && mth.c.ok && mth.c.user;
|
||||
if (user) { /* (V10.8.75) MATH USER: the formula first (FORMULA 100), read back */
|
||||
const code = mth.c.fvm.code, r = parse[CMD.FORMULA](await rq(req.formula(tr, 1, code)));
|
||||
if (r.rc || r.code.join() !== code.join()) { sayK("mathUserRefused", ` T${tr + 1}`); return; }
|
||||
mathTextKeep(code, $("mf").value);
|
||||
}
|
||||
const vals = mathValues({ ...mth.v, wave: user ? (mth.c.fvm.fix ? 6 : 5) : mth.wave, f: mth.f, user }), got = [];
|
||||
for (let k = 0; k < 8; k++) got.push(parse[CMD.TRACK_PARAM](await rq(req.trackParam(tr, d.info.pe0 + k, vals[k]))).value);
|
||||
await afterSoundChange("ready");
|
||||
const same = got.every((x, k) => x === vals[k]);
|
||||
sayK(same ? "mathSent" : "mathSentClamped", ` T${tr + 1}: ${mth.wave === 6 ? "F" : "B"}${String(mth.f + 1).padStart(2, "0")}`);
|
||||
sayK(same ? "mathSent" : "mathSentClamped", ` T${tr + 1}: ${user ? "USER" : (mth.wave === 6 ? "F" : "B") + String(mth.f + 1).padStart(2, "0")}`);
|
||||
});
|
||||
}
|
||||
/* a MATH track's sound into the editor (its formula and values) */
|
||||
@@ -6849,7 +7266,15 @@ async function mathRead() {
|
||||
const e = td.p.slice(d.info.pe0, d.info.pe0 + 8), w = e[1] === 6 ? 6 : 5, v = mth.v;
|
||||
if (w === 6) Object.assign(v, { algoB: e[0] >> 2, var: e[3], motion: e[4], fbk: e[5], morph: e[6], loop: e[7] });
|
||||
else Object.assign(v, { chip: e[0], sync: e[1] === 7 ? 1 : 0, var: e[3], motion: e[4], grit: e[5], bend: e[6], loop: e[7] });
|
||||
mathSetWave(w, true); mathKnobs(); mathLoadStock(Math.min(47, e[2] >> 2));
|
||||
if (e[2] < 0 && d.info.formula) { /* (V10.8.75) ALGO USER: the track's formula, its text if known here */
|
||||
const r = parse[CMD.FORMULA](await rq(req.formula(tr, 0)));
|
||||
mathSetWave(5, true); mathKnobs();
|
||||
const txt = mathTextOf(r.code);
|
||||
if (txt != null) { $("mf").value = txt; mathCompile(); }
|
||||
sayK(txt != null ? "mathReadOk" : "mathReadUser", ` T${tr + 1} (USER, ${r.n} B)`);
|
||||
return;
|
||||
}
|
||||
mathSetWave(w, true); mathKnobs(); mathLoadStock(Math.min(47, Math.max(0, e[2]) >> 2));
|
||||
sayK("mathReadOk", ` T${tr + 1}`);
|
||||
});
|
||||
}
|
||||
@@ -6864,7 +7289,8 @@ if (QS.get("test") === "1") window.jiantRollTest = {
|
||||
},
|
||||
idle: () => rollChain,
|
||||
show: (note) => { roll.view.top = note + 4; rollClamp(); rollInvalidate(); },
|
||||
math: () => ({ built: mth.built, playing: !!mth.node, wave: mth.wave, f: mth.f, v: { ...mth.v }, ok: !!(mth.c && mth.c.ok), stock: mth.c ? mth.c.stock : null, src: $("mf").value, last: mth.last ? mth.last.src : null }),
|
||||
math: () => ({ built: mth.built, playing: !!mth.node, wave: mth.wave, f: mth.f, v: { ...mth.v }, ok: !!(mth.c && mth.c.ok), stock: mth.c ? mth.c.stock : null, src: $("mf").value, last: mth.last ? mth.last.src : null,
|
||||
user: !!(mth.c && mth.c.user), code: mth.c && mth.c.fvm ? mth.c.fvm.code.slice() : null }),
|
||||
mathRender: async () => { const r = await mathRender(); return r ? { src: r.src, n: r.l.length, peak: r.l.reduce((m, x) => Math.max(m, Math.abs(x)), 0) } : null; },
|
||||
};
|
||||
async function rollRefreshStep(i) {
|
||||
|
||||
@@ -253,6 +253,20 @@ if (fs.existsSync(WASM)) {
|
||||
await p.click("#mgen"); await p.click("#mread"); await p.waitForTimeout(800);
|
||||
const after = await p.evaluate(() => window.jiantRollTest.math());
|
||||
check("MATH (firmware): read back from the track into the editor", after.wave === before.wave && after.f === before.f && after.v.var === before.v.var && after.stock !== -1 || (after.wave === 6 && after.f === before.f));
|
||||
/* (V10.8.75) MATH USER: a formula of one's own sent to track 4 (FORMULA 100, then ALGO USER), read back */
|
||||
const ownSrc = "(t * (t >> 9 | t >> 13) & 46) + sin(t >> 2) / 4";
|
||||
await p.fill("#mf", ownSrc); await p.waitForTimeout(150);
|
||||
const own = await p.evaluate(() => window.jiantRollTest.math());
|
||||
await p.selectOption("#mtrk", "3"); await p.dispatchEvent("#mtrk", "change");
|
||||
check("MATH USER (firmware): one's own formula compiled to the device's bytecode, sendable", own.ok && own.user && own.code && !(await p.isDisabled("#msend")));
|
||||
await p.click("#msend"); await p.waitForFunction(() => /T4: USER/.test(document.querySelector("#status").textContent), null, { timeout: 30000 });
|
||||
const fo = dev([100, 3, 0]), tdu = dev([29, 3]), algo = (tdu[3 + (pe0 + 2) * 2] | tdu[4 + (pe0 + 2) * 2] << 7) - 8192;
|
||||
const bytes = []; for (let i = 3; i < fo.length; i += 8) { const m = fo[i]; for (let j = 1; j <= 7 && i + j < fo.length; j++) bytes.push(fo[i + j] | ((m >> (j - 1)) & 1) << 7); }
|
||||
check(`MATH USER (firmware): on track 4 (FORMULA 4 0: ${fo[2]} B, the editor's), ALGO ${algo} (USER)`, fo[1] === 0 && fo[2] === own.code.length &&
|
||||
bytes.slice(0, fo[2]).join() === own.code.join() && algo === -4 && tdu[1] === 3);
|
||||
await p.fill("#mf", "t"); await p.click("#mread"); await p.waitForTimeout(800);
|
||||
const back = await p.evaluate(() => window.jiantRollTest.math());
|
||||
check("MATH USER (firmware): read back into the editor: its text (kept with its bytes), USER", back.src === ownSrc && back.user);
|
||||
if (OUT) await p.screenshot({ path: path.join(OUT, "math-firmware-desktop.png"), fullPage: true });
|
||||
await p.close();
|
||||
} else console.log(`editor (browser): the roll on the firmware: no ${WASM} (EMU_WASM=...)`.padEnd(80) + " skip");
|
||||
@@ -272,7 +286,11 @@ for (const [vp, touch, tag] of [[{ width: 1280, height: 900 }, false, "desktop"]
|
||||
await p.fill("#mf", "t * (42 & t >> 10) | t >> 6"); await p.waitForTimeout(100);
|
||||
m = await p.evaluate(() => window.jiantRollTest.math());
|
||||
const rm = await p.evaluate(() => window.jiantRollTest.mathRender());
|
||||
check(`MATH (${tag}): one's own formula heard through the model (peak ${rm && rm.peak.toFixed(2)}), not sendable`, m.ok && m.stock === -1 && rm && rm.src === "model" && rm.peak > 0.01 && await p.isDisabled("#msend"));
|
||||
const want = fs.existsSync(WASM) ? "emu" : "model"; /* (V10.8.75: the emulator's own VM plays one's own formulas) */
|
||||
check(`MATH (${tag}): one's own formula heard through the ${want} (peak ${rm && rm.peak.toFixed(2)}), not sendable unconnected`, m.ok && m.stock === -1 && m.user && rm && rm.src === want && rm.peak > 0.005 && await p.isDisabled("#msend"));
|
||||
await p.fill("#mf", "sin(w * (1 + (t >> 12 & 3))) * 0.5"); await p.waitForTimeout(100);
|
||||
m = await p.evaluate(() => window.jiantRollTest.math());
|
||||
check(`MATH (${tag}): a floatbeat of one's own (FIX: BYTE's language, sent on WAVE FLOAT)`, m.ok && m.user && m.code && (m.code[0] & 1) === 1 && /FLOAT/.test(await p.textContent("#merr")));
|
||||
await p.selectOption("#mstock", "6"); await p.waitForTimeout(100);
|
||||
if (fs.existsSync(WASM)) {
|
||||
const re = await p.evaluate(() => window.jiantRollTest.mathRender());
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
[{"src": "(~t >> 2) * ((127u & t * (7u & t >> 10)) < (245u & t * (2u + (5u & t >> 14))))", "code": [0, 244, 34, 73, 2, 244, 73, 10, 69, 7, 194, 69, 127, 244, 73, 14, 69, 5, 64, 2, 194, 69, 245, 1, 10, 2], "ty": 0, "hash": [4027174158, 3684274789, 3164885460], "unsup": null}, {"src": "(t * ((3u + (1u ^ (t >> 10 & 5u))) * (5u + (3u & t >> 14)))) >> (t >> 8 & 3u)", "code": [0, 244, 73, 10, 69, 5, 71, 1, 64, 3, 244, 73, 14, 69, 3, 64, 5, 2, 194, 244, 73, 8, 69, 3, 9], "ty": 0, "hash": [1757348662, 53736608, 991045669], "unsup": null}, {"src": "((-t & 4095u) * (255u & t * (t & t >> 13)) >> 12) + (127u & t * (234u & t >> 8 & t >> 3) >> (3u & t >> 14))", "code": [0, 244, 33, 69, 255, 31, 244, 73, 13, 197, 194, 69, 255, 1, 2, 73, 12, 244, 73, 8, 69, 234, 1, 244, 73, 3, 5, 194, 244, 73, 14, 69, 3, 9, 69, 127, 0], "ty": 0, "hash": [1751011762, 3687120624, 3509362617], "unsup": null}, {"src": "t * (((t >> 9) ^ ((t >> 9) - 1u) ^ 1u) % 13u)", "code": [0, 244, 73, 9, 244, 73, 9, 65, 1, 7, 71, 1, 68, 13, 194], "ty": 0, "hash": [1114282695, 4121702147, 2797371965], "unsup": null}, {"src": "((t >> 13 | t % 24u) & (t >> 7 | t % 19u)) << 3", "code": [0, 244, 73, 13, 244, 68, 24, 6, 244, 73, 7, 244, 68, 19, 6, 5, 72, 3], "ty": 0, "hash": [426755837, 824299141, 3757098005], "unsup": null}, {"src": "t * (t ^ (t + (t >> 15 | 1u)) ^ (((t - 1280u) ^ t) >> 10))", "code": [0, 244, 73, 15, 70, 1, 192, 199, 244, 65, 128, 10, 199, 73, 10, 7, 194], "ty": 0, "hash": [2114953371, 2004644325, 1479238021], "unsup": null}, {"src": "(t * (0xCA98u >> (t >> 9 & 14u) & 15u)) | t >> 8", "code": [0, 116, 152, 149, 3, 244, 73, 9, 69, 14, 9, 69, 15, 194, 244, 73, 8, 6], "ty": 0, "hash": [247731060, 3007809888, 1495094820], "unsup": null}, {"src": "(t * (t >> 8 | t >> 9) & 46u & t >> 8) ^ ((t & t >> 13) | t >> 6)", "code": [0, 244, 73, 8, 244, 73, 9, 6, 194, 69, 46, 244, 73, 8, 5, 244, 73, 13, 197, 244, 73, 6, 6, 7], "ty": 0, "hash": [2016343158, 4090457118, 525436849], "unsup": null}, {"src": "(t >> 4) * (13u & 0x8898A989u >> (t >> 11 & 30u))", "code": [0, 244, 73, 4, 116, 137, 211, 226, 196, 8, 244, 73, 11, 69, 30, 9, 69, 13, 2], "ty": 0, "hash": [3262698113, 1207060348, 3839114944], "unsup": null}, {"src": "t * (t >> ((8u * ((t >> 15) | (t >> 8))) & 31u) & (20u | (((t >> 19) * 5u) >> (t & 31u)) | t >> 3))", "code": [0, 244, 244, 73, 15, 244, 73, 8, 6, 66, 8, 69, 31, 9, 244, 73, 19, 66, 5, 244, 69, 31, 9, 70, 20, 244, 73, 3, 6, 5, 194], "ty": 0, "hash": [1763224772, 3320114954, 2072902250], "unsup": null}, {"src": "(t & t % 255u) - (t * 3u & t >> 13 & t >> 6)", "code": [0, 244, 68, 255, 1, 197, 244, 66, 3, 244, 73, 13, 5, 244, 73, 6, 5, 1], "ty": 0, "hash": [2083820246, 1650692403, 120963858], "unsup": null}, {"src": "(t * (t >> 9 | t >> 13) & (t >> 6 | t >> 11) & 127u) + ((t >> 4) * (3u + (t >> 12 & 3u)) & 64u)", "code": [0, 244, 73, 9, 244, 73, 13, 6, 194, 244, 73, 6, 244, 73, 11, 6, 5, 69, 127, 244, 73, 4, 244, 73, 12, 69, 3, 64, 3, 2, 69, 64, 0], "ty": 0, "hash": [2019634796, 4226353079, 3452799033], "unsup": null}, {"src": "t + (t & (t ^ t >> 6)) - t * ((t >> 9) & (t % 16u ? 2u : 6u) & t >> 9)", "code": [0, 244, 73, 6, 199, 197, 192, 244, 73, 9, 244, 68, 16, 116, 2, 116, 6, 53, 5, 244, 73, 9, 5, 194, 1], "ty": 0, "hash": [3415164616, 2154244997, 2587907457], "unsup": null}, {"src": "t * (t >> 11 & t >> 8 & 123u & t >> 3)", "code": [0, 244, 73, 11, 244, 73, 8, 5, 69, 123, 244, 73, 3, 5, 194], "ty": 0, "hash": [1802188389, 847263819, 744388307], "unsup": null}, {"src": "(t * 9u & t >> 4) | (t * 5u & t >> 7) | (t * 3u & t >> 10)", "code": [0, 244, 66, 9, 244, 73, 4, 5, 244, 66, 5, 244, 73, 7, 5, 6, 244, 66, 3, 244, 73, 10, 5, 6], "ty": 0, "hash": [237208415, 3408843360, 1632405756], "unsup": null}, {"src": "(t * ((t & 4096u ? (t % 65536u < 59392u ? 7u : t & 7u) : 16u) + (1u & t >> 14)) >> (3u & -t >> (t & 2048u ? 2 : 10))) | t >> (t & 16384u ? (t & 4096u ? 10 : 3) : 2)", "code": [0, 244, 69, 128, 32, 244, 68, 128, 128, 4, 74, 128, 208, 3, 116, 7, 244, 69, 7, 53, 116, 16, 53, 244, 73, 14, 69, 1, 0, 194, 244, 33, 244, 69, 128, 16, 116, 2, 116, 10, 53, 9, 69, 3, 9, 244, 244, 69, 128, 128, 1, 244, 69, 128, 32, 116, 10, 116, 3, 53, 116, 2, 53, 9, 6], "ty": 0, "hash": [2779320897, 616924554, 2564763348], "unsup": null}, {"src": "(t * ((3u + (1u ^ (t >> 10 & 5u))) * (a + (3u & t >> 14)))) >> (t >> 8 & 3u)", "code": [0, 244, 73, 10, 69, 5, 71, 1, 64, 3, 244, 73, 14, 69, 3, 128, 0, 2, 194, 244, 73, 8, 69, 3, 9], "ty": 0, "hash": [746565896, 2284453197, 433703024], "unsup": null}, {"src": "t * ((t >> (a & 15u) | t >> 8) & 63u & t >> 4)", "code": [0, 244, 180, 0, 69, 15, 9, 244, 73, 8, 6, 69, 63, 244, 73, 4, 5, 194], "ty": 0, "hash": [3599023841, 898307758, 3764364982], "unsup": null}, {"src": "(t * a & t >> 7) | (t * 3u & t >> 10)", "code": [0, 244, 130, 0, 244, 73, 7, 5, 244, 66, 3, 244, 73, 10, 5, 6], "ty": 0, "hash": [3841346451, 2741455790, 2072671052], "unsup": null}, {"src": "(t >> a | t) * (t >> 9 & 7u)", "code": [0, 244, 137, 0, 198, 244, 73, 9, 69Line truncated
|
||||
+52
-1
@@ -8,6 +8,10 @@
|
||||
// a C compiler: the hashes made again from that source
|
||||
// - the proposed bytecode (EDITOR_PROTOCOL.md "a user formula"): the same samples as the VM, its size and stack
|
||||
// - the generator: seeded (one seed, one formula), every formula valid and moving
|
||||
// - (V10.8.75) MATH USER: FVM, the port of JIANT BYTE's compiler, against BYTE's own (web/math_fvm_gold.json: 142 texts
|
||||
// compiled by BYTE's fvm_compile, serialized, run by its fvm_run): the same bytes for every one, the same values from
|
||||
// FVM.run (JIANT FM's math_user.c) at three a's; the refused ones refused; pack7 both ways; the generator's formulas
|
||||
// compile to at most 64 bytes; given EMU_WASM, a formula sent with FORMULA (100) to the emulator plays and reads back
|
||||
// - EMU_WASM (default build/emu/felucca.wasm): the BYTE model against the emulator's own samples, formula by formula
|
||||
// (the waveforms' correlation), and the eight values a send writes, read back
|
||||
import fs from "fs";
|
||||
@@ -17,7 +21,7 @@ import { execFileSync } from "child_process";
|
||||
const HERE = path.dirname(new URL(import.meta.url).pathname);
|
||||
const html = fs.readFileSync(path.join(HERE, "editor.html"), "utf8");
|
||||
const core = html.slice(html.indexOf("/*MATH-BEGIN*/"), html.indexOf("/*MATH-END*/"));
|
||||
const X = new Function(core + "; return { MATH_BYTE, MATH_FLOAT, MathVM, mathMut, mathMotion, mathGenerate, mathScore, mathRenderByte, mathEmuRender, mathValues };")();
|
||||
const X = new Function(core + "; return { MATH_BYTE, MATH_FLOAT, MathVM, FVM, mathMut, mathMotion, mathGenerate, mathScore, mathRenderByte, mathEmuRender, mathValues };")();
|
||||
let fails = 0;
|
||||
const ok = (c, what) => { console.log(`${what.padEnd(96)} ${c ? "ok" : "FAIL"}`); if (!c) fails++; };
|
||||
const fnv = (h, x) => Math.imul(h ^ x, 16777619) >>> 0;
|
||||
@@ -82,6 +86,37 @@ const MUT_HASH = 3332514091;
|
||||
ok(moving >= 36, `generator: every formula valid, ${moving} of 40 changing over time without being noise`);
|
||||
console.log(" e.g. seed 1: " + gen[0] + "\n seed 2: " + gen[1]);
|
||||
}
|
||||
/* ---- (V10.8.75) MATH USER: the port of BYTE's compiler against BYTE's */
|
||||
{
|
||||
const G = JSON.parse(fs.readFileSync(path.join(HERE, "math_fvm_gold.json"), "utf8"));
|
||||
let same = 0, bad = [], vals = 0, refused = 0;
|
||||
for (const x of G) {
|
||||
const c = X.FVM.compile(x.src);
|
||||
if (!x.code || x.code.length > 64) { if (c.ok) bad.push(x.src); else refused++; continue; }
|
||||
if (!c.ok || c.code.join() !== x.code.join()) { bad.push(x.src); continue; }
|
||||
same++;
|
||||
let k = 0;
|
||||
for (; k < 3; k++) {
|
||||
let h = 2166136261;
|
||||
const a = [1, 7, 16][k];
|
||||
for (let i = 0; i < 4160; i++) {
|
||||
const t = i < 4096 ? Math.imul(i, k + 1) >>> 0 : X.FVM.hash((Math.imul(i, 7919) + k) >>> 0);
|
||||
h = fnv(h, X.FVM.run(c.code, t, Math.imul(t, 2654435761) >>> 0, a));
|
||||
}
|
||||
if (h !== x.hash[k]) break;
|
||||
}
|
||||
if (k === 3) vals++;
|
||||
}
|
||||
ok(!bad.length && same >= 135, `FVM: JIANT BYTE's fvm_compile's bytes for ${same} formulas (93 of BYTE's 96 factory, every operator)${bad.length ? " NOT: " + bad.slice(0, 3).join(" | ") : ""}`);
|
||||
ok(vals === same, `FVM.run: BYTE's fvm_run's values for all ${vals} (3 x 4160 each)`);
|
||||
ok(refused >= 7, `FVM: BYTE's ph() lp() eu() and the ones over 64 bytes refused (${refused})`);
|
||||
const e1 = X.FVM.compile("t * (42 & t >> 10"), e2 = X.FVM.compile("t + q"), e3 = X.FVM.compile("lp(sin(w), 0.5)");
|
||||
ok(!e1.ok && e1.pos === 17 && !e2.ok && e2.pos === 4 && !e3.ok, `FVM: errors say what and where (${e1.error} ${e1.pos}, ${e2.error} ${e2.pos}, ${e3.error})`);
|
||||
const p = Array.from({ length: 64 }, (_, i) => (i * 37 + 5) & 255);
|
||||
ok(X.FVM.unpack7(X.FVM.pack7(p)).join() === p.join() && X.FVM.pack7(p).every((b) => b < 128), "pack7: 64 bytes there and back, every byte 7-bit");
|
||||
const gen = Array.from({ length: 40 }, (_, k) => X.FVM.compile(X.mathGenerate(k + 1)));
|
||||
ok(gen.every((c) => c.ok && c.code.length <= 64 && !c.fix), `generator: its 40 formulas are MATH USER formulas (INT, ${Math.max(...gen.map((c) => c.code.length))} B the longest)`);
|
||||
}
|
||||
/* ---- the model against the emulator */
|
||||
const WASM = process.env.EMU_WASM || path.join(HERE, "..", "build", "emu", "felucca.wasm");
|
||||
if (fs.existsSync(WASM)) {
|
||||
@@ -109,6 +144,22 @@ if (fs.existsSync(WASM)) {
|
||||
const back = (k) => { const q = [31, 0, 115 + k]; new Uint8Array(ex.memory.buffer, ex.web_ed_buf(), 3).set(q); const n = ex.web_ed(3); const a = new Uint8Array(ex.memory.buffer, ex.web_ed_reply(), n); return (a[2] | a[3] << 7) - 8192; };
|
||||
const want = X.mathValues(o), got = want.map((_, k) => back(k));
|
||||
ok(got.join() === want.join() && r.l.some((x) => Math.abs(x) > 1e-3), `the emulator takes a send's eight values (ALGO 188 = B48, MOTION 200: SYNC) and sounds: ${got.join(" ")}`);
|
||||
{ /* (V10.8.75) a formula of one's own: FORMULA (100) to the emulator, ALGO USER: it plays; B01's text as USER: B01's samples */
|
||||
const ex2 = await fresh(), b01 = X.FVM.compile(X.MATH_BYTE[0]).code;
|
||||
const o2 = { wave: 5, f: 0, chip: 2, var: 0, motion: 0, note: 60, secs: 0.6, dry: true };
|
||||
const u = X.mathEmuRender(ex2, { ...o2, user: true, code: b01 }), s0 = X.mathEmuRender(await fresh(), o2);
|
||||
if (!u.formula) console.log("MATH USER on the emulator: its firmware has no FORMULA (before V10.8.75)".padEnd(96) + " skip");
|
||||
else {
|
||||
let d = 0; for (let i = 0; i < u.l.length; i++) d = Math.max(d, Math.abs(u.l[i] - s0.l[i]));
|
||||
ok(d === 0, `MATH USER on the emulator: B01's bytecode at ALGO USER plays B01's samples, bit for bit (C4: under the 11 kHz cap)`);
|
||||
const q = [100, 0, 0]; new Uint8Array(ex2.memory.buffer, ex2.web_ed_buf(), 3).set(q);
|
||||
const n = ex2.web_ed(3), a = Array.from(new Uint8Array(ex2.memory.buffer, ex2.web_ed_reply(), n));
|
||||
ok(a[1] === 0 && a[2] === b01.length && X.FVM.unpack7(a.slice(3)).slice(0, a[2]).join() === b01.join(), `FORMULA 0 0: the formula read back (${a[2]} B)`);
|
||||
const f20 = X.FVM.compile(X.MATH_FLOAT[19][0] === "odd partials, built up" ? "(sin(w)+((t>>11&3)>0?sin(w*3)/3:0.)+((t>>11&3)>1?sin(w*5)/5:0.)+((t>>11&3)>2?sin(w*7)/7:0.))*3/4" : "sin(w)");
|
||||
const uf = X.mathEmuRender(await fresh(), { ...o2, wave: 6, user: true, code: f20.code });
|
||||
ok(f20.ok && f20.fix && uf.formula && uf.l.some((x) => Math.abs(x) > 1e-3), `MATH USER, FIX on WAVE FLOAT (F20's text in BYTE's FIX, ${f20.code && f20.code.length} B): it sounds`);
|
||||
}
|
||||
}
|
||||
} else console.log(`model vs emulator: no ${WASM} (EMU_WASM=...)`.padEnd(96) + " skip");
|
||||
console.log(fails ? `MATH TESTS FAILED (${fails})` : "math tests passed");
|
||||
process.exit(fails ? 1 : 0);
|
||||
Reference in new issue
Block a user