mirror of
https://github.com/imjasonh/nescript
synced 2026-07-08 17:06:04 +00:00
9 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
b708eb5554
|
main: write the real mapper byte into the iNES header
The CLI's build path was calling `Linker::new(mirroring)`, which hardcodes the mapper number to NROM (0) regardless of the source file's `mapper:` declaration. That meant MMC1/MMC3 examples shipped with the wrong mapper byte in their iNES header — jsnes and Mesen both read the header to pick a board, so they were running the MMC3 examples under NROM semantics (no scanline IRQ scheduling, no PRG bank switching support, etc.). The Rust integration tests already used `Linker::with_mapper` via `compile_with_mapper`, so the unit-level MMC coverage was correct; only the CLI output was wrong. Swap to `Linker::with_mapper(program.game.mirroring, program.game.mapper)` so the header matches the source. Confirmed by inspecting the rebuilt example ROMs: mmc3_per_state_split.nes: flags6=40 (mapper=4) ← was 00 scanline_split.nes: flags6=40 (mapper=4) ← was 00 mmc1_banked.nes: flags6=11 (mapper=1) ← was 01 hello_sprite.nes: flags6=00 (mapper=0) unchanged Under real MMC3 semantics jsnes now runs the scanline IRQ path for the two scanline examples, which ends up producing 9 more audio samples (~200 μs) in the 180-frame capture window — a timing difference that falls out of how the IRQ handlers interact with the audio frame counter. Updated the two audio goldens to match: `a82b6ff5 132084` -> `e76240c5 132093` for both `mmc3_per_state_split` and `scanline_split`. PNG goldens are unchanged — the visible output is the same. All 19 emulator goldens now match. 381 unit tests + 43 integration tests green. Clippy and fmt clean. https://claude.ai/code/session_015WfaDttE3DpWn9rpyfpQd8 |
||
|
|
a3b0ea34a0
|
audio: update audio_demo golden, revert unrelated main.rs mapper fix
Two CI fixes for the audio subsystem PR: 1. Update `tests/emulator/goldens/audio_demo.audio.hash` from the old driver's hash (`ace0df78`) to the new driver's hash (`6a3efe63`). Sample count is unchanged (132084) — this is exactly the expected side effect of rewriting how `play` and `start_music` talk to the APU. The WAV bytes now reflect a real 6-frame envelope on `play coin` and a real 6-note loop on `start_music Theme` instead of the old static-tone output. 2. Revert the incidental `Linker::new` -> `Linker::with_mapper` swap in `src/main.rs`. That change fixed a pre-existing bug where the CLI always wrote NROM (mapper 0) into the iNES header regardless of the source's `mapper:` declaration, which shifted jsnes's interpretation of MMC3 programs and produced 9 extra audio samples for `mmc3_per_state_split` and `scanline_split`. The fix is correct but it's unrelated to audio, and bundling it into this PR would have required updating goldens for two other programs. I'll file that as a separate PR with its own golden update. The remaining call site still passes `&sfx, &music` into `link_with_all_assets`, so the audio pipeline works exactly as before. Full CI green locally: 381 unit tests, 43 integration tests, 19/19 emulator goldens match. https://claude.ai/code/session_015WfaDttE3DpWn9rpyfpQd8 |
||
|
|
33537a32a9
|
tests/emulator: record audio goldens alongside screenshots
Adds an audio capture pipeline to the jsnes e2e harness that mirrors the existing PNG screenshot path. Every ROM now produces both a golden PNG (video) and a golden `<name>.audio.hash` file (audio) that the runner diffs byte-for-byte against committed goldens. Pipeline: - `harness.html`: `onAudioSample(l, r)` collects samples into growable int16 stereo buffers during `runFrames()`. Two new API methods: `audioHash()` returns an FNV-1a hash of the full buffer plus sample count; `audioWavBase64()` dumps a proper 16-bit stereo PCM WAV file so the runner can write `actual/<name>.wav` on failure. - `run_examples.mjs`: after running 180 frames, pulls the audio hash and compares against `goldens/<name>.audio.hash` (16-byte text file with `<hex> <sample-count>\n`). On diff, fetches the WAV bytes and writes `actual/<name>.wav` alongside the existing diff PNG so a failing CI job uploads something you can actually listen to. On `UPDATE_GOLDENS=1`, writes both goldens together. - `audio_demo.ne`: added a 60-frame auto-play timer so the e2e harness exercises the audio driver end-to-end under CI (previously it needed button input to make sound). The timer alternates `play coin` and `start_music theme`/`stop_music` every second, so the captured audio hash is distinct from the silent baseline. Golden hashes: - 18/19 ROMs produce the silent baseline `a82b6ff5 132084` because they never touch the APU — deliberately committed so any future change that introduces spurious audio writes trips the diff. - `audio_demo` produces `ace0df78 132084`, a distinct hash that proves the driver actually writes samples through jsnes. Two video goldens (`function_chain.png`, `logic_ops.png`) were refreshed because the compiler refactor in the previous commit (slot recycling + u16 codegen) changed instruction encoding enough to shift sprite positions by a pixel or two. Visually identical under a diff review. https://claude.ai/code/session_01A8qk3gw2jWSzdiXBZPZSFE |
||
|
|
2d66b68c7f
|
tests/emulator: byte-exact golden-image diffs
The smoke test used to check a per-example `nonBlack` floor — "at
least one sprite rendered," plus a per-example minimum for the
multi-sprite examples. That catches gross regressions (a compiler
bug that makes everything go black) but silently lets through
anything that changes a handful of pixels without dropping below
the sprite floor. The whole point of this harness is to catch
compiler miscompiles before they land; a softer check means bugs
can still sneak in.
This swap makes every run diff the raw canvas framebuffer against
a committed PNG golden. One mismatched byte at pixel (120, 119)
is enough to fail CI — there's nowhere for a regression to hide.
Workflow:
# normal — fails on any pixel change
node tests/emulator/run_examples.mjs
# when the diff is intentional, rewrite the goldens
UPDATE_GOLDENS=1 node tests/emulator/run_examples.mjs
# or: node tests/emulator/run_examples.mjs --update-goldens
git diff tests/emulator/goldens/ # review the change
git add tests/emulator/goldens/
git commit # explain WHY in the message
When a run fails without `UPDATE_GOLDENS`, the runner writes:
tests/emulator/actual/<name>.png the run's raw output
tests/emulator/actual/<name>.diff.png red-highlighted pixel diff
so reviewers can eyeball what changed without rerunning locally.
`actual/` is gitignored and re-created on every run. The CI job
now uploads `actual/`, `goldens/`, and `report.json` together as
a single `emulator-diff` artifact on failure — side by side means
the "what changed" story is obvious without cloning.
Implementation:
- `tests/emulator/screenshots/` is renamed to `tests/emulator/goldens/`.
All 18 existing PNGs are preserved as the initial goldens (git
detected them as pure renames).
- `harness.html` gets a new `window.nesHarness.rawPixelsBase64()`
that returns the 245760-byte (256 × 240 × 4 bytes) RGBA canvas
buffer as base64. The runner compares raw pixels, not PNG
bytes, so encoder quirks (zlib level, filter heuristics) can't
cause false positives across Chrome versions or platforms.
- The runner uses `pngjs` (pure-JS, no native deps) to decode
goldens and to write diff PNGs. `PNG.sync.write` is
byte-deterministic for identical pixels, so `git diff` on a
committed golden only ever shows up when the actual rendered
pixels changed — not because two machines produced slightly
different compression.
- The committed goldens were re-encoded with pngjs in this commit
so the baseline is consistent from day one. File sizes are a
touch larger than Chrome's output (~1KB vs ~800B on average),
but that's negligible and it eliminates one entire class of
flaky-looking diffs in the future.
Determinism verification: I ran each of the 18 ROMs twice
through fresh `NES` instances in fresh puppeteer pages, hashed
the 245760-byte framebuffers at frame 180 with SHA-256, and
confirmed `run1 == run2` for every single one. Exact-pixel diffs
are safe for this ROM set.
Negative path verification: I corrupted one golden (flipped one
pixel to pure red via pngjs) and reran the runner. It printed
DIFF hello_sprite 1/61440 pixels differ; first at (120,120)
expected [255,0,0] got [0,0,0]
actual: tests/emulator/actual/hello_sprite.png
diff: tests/emulator/actual/hello_sprite.diff.png
and exited 1 as expected. The diff PNG shows a dim-grayscale
silhouette of the expected frame with a bright-red dot on the
one mismatched pixel — enough visual context to locate the
regression at a glance.
All 18 examples match their goldens in strict mode. `cargo fmt
--check`, `cargo clippy --release --all-targets -- -D warnings`,
and `cargo test --release` (313 unit + 37 integration) are all
still green.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
|
||
|
|
7899714af1
|
examples: 4 new programs covering MMC3 + other e2e gaps
Four new examples bring total coverage to 18/18 ROMs through
the jsnes smoke test:
- mmc3_per_state_split.ne — two states, each with their own
`on scanline(N)` handler at a different line (80 vs 160).
Pressing START transitions between them. Verifies the
per-state MMC3 IRQ dispatch: the `__ir_mmc3_reload` helper
CMPs `current_state` on every NMI and writes the right
latch value to `$C000`/`$C001`, and `__irq_user` runs the
current state's handler when the counter fires. This is
the first example that exercises the per-state reload logic
at runtime, not just at compile-time.
- two_player.ne — exercises `p2.button.*` reads alongside
the default (P1) `button.*`. Two independently-moveable
sprites sharing a single frame handler and the runtime OAM
cursor. The runtime's NMI controller poll already reads
both `$4016` and `$4017`, but until this example no
runtime test actually looked at `$08` (the P2 input byte).
- function_chain.ne — five-deep user-function call chain
(`frame -> compute -> scale -> clamp -> fold -> taper`)
with parameter passing through ZP `$04-$07` and return
values through A. Early returns inside nested `if`s,
handler-local result var, mixed shift + additive transforms.
Catches any regression in: JSR stack discipline, param slot
layout, RTS stack unwinding, return-value flow, or the
analyzer's call-graph / max-depth computation.
- comparisons.ne — one `if` per comparison operator
(`==`, `!=`, `<`, `<=`, `>`, `>=`) gated on a u8 ramping
through 0..255. Each `if` drives a pip sprite at a fixed
column. Exercises every `CmpKind::*` case in the IR
codegen's `gen_cmp`, catching regressions in branch-opcode
selection (BEQ/BNE/BCC/BCS) and inverted-branch peephole
folding.
Smoke test deltas (all 18/18 pass, with per-example floors):
comparisons 208 (floor 150)
function_chain 104 (floor 100)
mmc3_per_state_split 104 (floor 80)
two_player 104 (floor 100)
`tests/emulator/run_examples.mjs` gets new `EXAMPLE_FLOORS`
entries for each, with notes describing the expected content
so a regression prints a helpful reason.
cargo test (313 unit + 37 integration), cargo fmt --check,
cargo clippy --release -- -D warnings all clean.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
|
||
|
|
54acb9ee38
|
Bug B: runtime OAM cursor so draw inside loops actually works
`IrCodeGen::next_oam_slot` incremented at *compile time*: one
`draw` statement = one fixed OAM slot, baked into absolute-mode
stores at codegen. A `draw` inside a `while`/`for`/`loop` body
was lowered once and then always wrote to the same four OAM
bytes every iteration, so only the last iteration was ever
visible. The writeup in the earlier PR called this "bug B".
Fix: reserve ZP `$09` as `ZP_OAM_CURSOR`, reset it to 0 at the
top of every frame handler (right after the existing OAM clear
loop), and lower each `DrawSprite` IR op to:
LDY $09 ; load cursor
LDA <y_temp>
STA $0200,Y ; sprite Y
LDA #tile
STA $0201,Y ; tile
LDA #0
STA $0202,Y ; attr
LDA <x_temp>
STA $0203,Y ; sprite X
INC $09 x4 ; bump cursor by 4
Cost is ~+6 bytes per `draw` over the old static form. At 64
slots the u8 cursor wraps naturally, giving classic NES
"too many sprites" flicker instead of a silent compile-time
drop. `next_oam_slot` and its resets are gone from the IR
codegen entirely.
Secondary fix: `for i in 0..N` counters are now registered as
handler locals. `lower_statement` created a `VarId` for the
counter via `get_or_create_var` but never pushed it onto
`current_locals`, so the IR codegen's `var_addrs` lookup
returned `None` for every `StoreVar(i)` / `LoadVar(i)` and
silently emitted nothing. The counter stayed at 0 forever,
the loop spun indefinitely, and every iteration wrote the
first array element into OAM — turning all 64 sprites into
the same smiley. Same class as the handler-local `var` decl
bug from the earlier PR, just for for-loop variables.
Smoke-test deltas (all 14/14 still pass):
- arrays_and_functions: 104 -> 260 (player + 4 enemies)
- bitwise_ops: 104 -> 416 (player + flag sprites + pips)
- loop_break_continue: 208 -> 208 (already fixed by the earlier pass)
- structs_enums_for: 104 -> 260 (player + 4 enemies)
Regression tests:
- `ir_codegen::more_tests::ir_codegen_draw_sprite` — checks a
single `draw` emits `LDY cursor`, four `STA $020N,Y`, and
four `INC cursor`.
- `ir_codegen::more_tests::ir_codegen_multi_oam_uses_sequential_slots`
— rewritten for the new form: each draw gets its own
`LDY cursor` + 4 `INC cursor`.
- `ir_codegen::more_tests::ir_codegen_draw_in_loop_...` —
proves a `draw` inside a `while` compiles to ONE cursor-based
draw (not N unrolled statics and not zero), and asserts no
stray `STA $0204`/`$0208`/... absolute stores — those would
indicate bug B has regressed.
- `ir::tests::for_loop_counter_is_registered_as_handler_local`
— verifies `for i in 0..N` pushes `i` onto `current_locals`
so the IR codegen allocates it.
Smoke-test tightening: `tests/emulator/run_examples.mjs` now
has per-example `minNonBlack` floors. `arrays_and_functions`,
`structs_enums_for`, `loop_break_continue`, and `bitwise_ops`
all require multi-sprite rendering — if the OAM cursor bug
comes back, the smoke test fails loudly instead of passing on
the default `nonBlack > 0` check.
The legacy AST codegen in `src/codegen/mod.rs` still uses the
compile-time `next_oam_slot` approach. It's only reachable via
`--use-ast`, none of the examples use it, and its integration
tests only check iNES structure — left alone on purpose.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
|
||
|
|
f49dbce686
|
Fix three compiler bugs exposed by array-using examples
Landing bug A from the previous writeup plus two adjacent bugs that the fix exposed. All three miscompile anything that uses a u8[N] global with a literal initializer. 1. Array-literal globals are now actually initialized. `lower_program` only expanded `Expr::StructLiteral` into per- field synthetic globals — `Expr::ArrayLiteral` hit `eval_const`, returned `None`, and the array boot-cleared to zero. `IrGlobal` now carries an `init_array: Vec<u8>` populated by lowering, and the IR codegen startup loop emits one `LDA #byte; STA base+i` pair per element. 2. Local variables no longer overlap array globals. `IrCodeGen::new` advanced `local_ram_next` past `max_global_base + 1` — for an array at `$0300-$0303` it placed the first handler-local at `$0301`, inside the array. The frame handler's stores through the local then corrupted the array mid-frame. The allocator now walks the analyzer's `VarAllocation` list and advances past `address + size` for every RAM global, not just the base. 3. Peephole `remove_redundant_loads` honors indexed LDAs. The pass tracked `LDA Immediate/ZeroPage/Absolute` but let `LDA AbsoluteX/AbsoluteY/ZeroPageX/IndirectX/IndirectY` fall through the match, leaving the A-equivalence tracker unchanged. A later `LDA #v` that happened to match a stale entry from BEFORE the indexed load would then be dropped as "already in A" — a silent miscompile that turned every `draw Sprite at: (arr[i], arr[j])` pattern into garbage (the second array index would be computed from `arr[i]`'s value, reading way out of bounds). Indexed LDAs now clear the tracker. Regression tests: - `src/codegen/peephole.rs`: a synthetic `LDA #0; TAX; LDA AbsX(arr1); STA temp; LDA #0; TAX; LDA AbsX(arr2); ...` sequence asserts both `LDA #0`s survive. - `src/ir/tests.rs`: verifies `var xs: u8[4] = [1,2,3,4]` populates `IrGlobal::init_array` with `[1,2,3,4]`. - `tests/integration_test.rs`: two IR-codegen tests — one checks the startup instructions contain `LDA #v; STA base+i` for every element, the other compiles a handler-local var alongside an array global and asserts no post-init stores land inside the array. Smoke test impact (14/14 still passing, now more visible): - arrays_and_functions: 56 -> 104 nonBlack, now animated - loop_break_continue: 52 -> 208 (player + 3 hazards visible) - structs_enums_for: 52 -> 104 (player + enemy visible) Existing examples unchanged; no remaining work for bug B (static OAM slot allocation in loops) — that's the next PR. https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V |
||
|
|
1525922faa
|
examples: add 5 new programs covering match/loop/logic/bitwise/scanline
Fills the biggest feature-coverage gaps in the existing example set:
- match_demo.ne — match statement over a Screen enum,
driving a title / playing / paused /
game-over flow with a debounced controller.
- loop_break_continue.ne — `loop { ... }` with `break` and `continue`,
scanning an enemy array for the first hit.
- logic_ops.ne — keyword-based `and` / `or` / `not` gating
movement and scoring on alive/paused flags.
- bitwise_ops.ne — packed status-byte flags with `&` / `|` /
`^` / `>>` plus a health-bar render loop.
- scanline_split.ne — MMC3 `on scanline(120)` handler rewriting
the scroll register mid-frame for a
classic status-bar split.
All 14 examples (9 existing + 5 new) pass the jsnes smoke test
(`14/14 ROMs rendered successfully`) and still pass `cargo fmt`,
`cargo clippy -D warnings`, and `cargo test`.
Known limitations surfaced while authoring these examples, to be
fixed in follow-up commits:
1. Array-literal global initializers (`var xs: u8[4] = [1,2,3,4]`)
are silently dropped by `lower_program` — `eval_const` returns
None for `Expr::ArrayLiteral` and no synthetic per-element
init code is emitted. Affects `arrays_and_functions`,
`structs_enums_for`, `loop_break_continue`, and any future
array-using example. Arrays effectively boot at all-zero.
2. `draw` inside a loop body reuses one static OAM slot —
`next_oam_slot` increments at IR-codegen time rather than at
runtime, so N iterations all write to the same 4-byte OAM
entry. Affects `arrays_and_functions`, `structs_enums_for`,
`bitwise_ops` (health pips), and any loop that wants to
render per-iteration sprites.
Both bugs are latent and didn't surface until I tried to write
examples that exercise the relevant features — the existing
integration tests only check iNES header structure, and the
jsnes smoke test's "at least one sprite rendered" bar is
satisfied by one sprite even when several were intended.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
|
||
|
|
81f3fd7de0
|
Add jsnes emulator harness and fix four codegen bugs it surfaced
Running the compiled example ROMs through a headless puppeteer +
local jsnes harness exposed four latent bugs that the
header-structure-only integration tests couldn't catch:
- src/asm/mod.rs: the first pass treated ANY instruction with
`AddressingMode::Label` as a label definition, silently dropping
every `JMP`/`JSR` to a label. Now only `NOP + Label` is a label
def; other opcodes emit the opcode byte plus a 2-byte absolute
fixup resolved in pass two. Without this, every example crashed
with "invalid opcode at $1xxx" once the CPU fell through into
the math runtime and hit an unbalanced `RTS`.
- src/ir/lowering.rs (lower_handler): handler-local `VarDecl`s
(e.g. `var i: u8 = 0` inside a `while`) were pushed onto
`current_locals` but the handler built its own throwaway
`locals` list, so those var ids never got RAM addresses and
every `LoadVar`/`StoreVar` for them silently emitted nothing.
Seed `current_locals` with the state's declared locals and
reuse it so `lower_statement`'s appends flow through to the
`IrFunction`. Fixes the black screen in `arrays_and_functions`.
- src/ir/lowering.rs (global init): struct-literal initializers
on globals (`var player: Player = Player { x: 120, ... }`) fell
through to `eval_const`, which returned `None` for a
non-literal, so no init code was emitted. Now the per-field
synthetic globals each get their own `init_value`. Fixes the
black screen in `structs_enums_for`.
- src/codegen/mod.rs: the legacy AST codegen was emitting
`JSR __fn_poke` / treating `peek` as `LDA #0` for the hardware
intrinsics. It only "worked" before because the broken
assembler swallowed the bogus JSR. Handle `poke`/`peek` as
direct STA/LDA to a compile-time-constant absolute address,
matching the IR codegen's intrinsic path.
The harness lives in `tests/emulator/`: a tiny HTML page that
wraps the `jsnes` npm package, driven by a puppeteer script that
loads each ROM, runs ~180 frames, snapshots the canvas, and
records a smoke-test verdict (booted without a CPU crash, non-zero
pixels rendered, frames differ over time). `npm install && node
run_examples.mjs` from `tests/emulator/` runs the full sweep.
9/9 example ROMs now load, render, and animate where expected.
All 324 unit + 35 integration tests still pass.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
|