# Tetris Battle Gaiden reimplementation Clean reimplementation of the SNES game Tetris Battle Gaiden (BPS, 1993) in C++20 + SDL3 for Linux. Goals: faithful original mode first, then extensible/moddable — 4-player, new characters, data-driven powers, configurable piece queue, upgraded graphics. ## Milestones - **M0 — RE mapping: DONE.** Findings in `re/NOTES.md` (index, tooling, boot/frame structure) and `re/notes/{mechanics,battle,flow_chars_ai,powers_detail,ai_detail,timing}.md` (powers_detail supersedes battle.md where they differ). Each finding is tagged [C] confirmed in emulator or [I] inferred from code. - **M1 — SDL3 skeleton: DONE.** Single board with ROM-derived shapes/rotation/speeds/queue/meter. - **M2 — original game: DONE.** Full flow (title, options, char select, 1P Battle World → Dragon → Queen → ending with continues, 2P), ROM-exact mechanics/timings/powers, the original CPU (needs the user's ROM). Known gaps: placeholder flat-colour graphics, no sound, no attract demo, minor open RE questions (Hanten/Roulette victim flag, Kaiten with a human, low-stack edge cases, stone under Suritote/Medusa). - **M3 — extensions: DONE.** 2-4 player VS with targeting policies, data-driven roster/powers/rules (mod files, `data/README.md`), configurable queue + randomizer, replays, attract demo, pause, saved settings + key rebinding, original graphics (`src/gfx`, `src/app/art_draw.*`: boards, stages, exact cut-in animations, portraits), line-clear flash, original music/SFX (`src/audio` + `external/snes_spc`, wired via `src/app/game_sound.*`). Open questions for the user: `QUESTIONS.md`. ## Build / test ``` cmake -S . -B build -G Ninja && cmake --build build ./build/tbg_tests # core rule tests; exit code = failure count TBG_ROM=rom/tbg_jp.sfc ./build/tbg_tests # also runs the original-CPU tests TBG_ROM=rom/tbg_jp.sfc ./build/tbg_audio_tests # sound engine; ./build/snd_validate ROM re/runs/snd/ref vs the Python reference ./build/ai_validate rom/tbg_jp.sfc re/runs/ai2/log* re/runs/ai2/rec_d* # RomAi vs captured real-game decisions ./build/tbg [--rom PATH] # full game from the title screen ./build/tbg [cpu0-3] # quick battle, e.g. `./build/tbg Shaman Bit cpu2`; R rematch # P1: WASD, W cast, F/G = A/B rotate, Q/E L/R, C/Z X/Y. P2: arrows, Up cast, ./, A/B, # [ ] L/R, / ; X/Y. Gamepads (SNES layout). Enter/A confirm, Esc back TBG_PRESS="10:ok,20:down" ... # dev: inject P1 menu presses (with TBG_SHOT for headless screen checks) TBG_CAST="400:0:4" ... # dev: at battle frame 400, seat 0 casts its level-4 power (check power animations) TBG_METER="100:0:4" ... # dev: at battle frame 100, seat 0's crystal meter = 4 (pause screen power texts) TBG_SHOT=out.bmp TBG_SHOT_FRAME=3000 SDL_VIDEO_DRIVER=offscreen ./build/tbg # render N sim frames, save screenshot SDL_VIDEO_DRIVER=offscreen timeout 3 ./build/tbg # headless smoke test (exit 124 = ran fine) ``` ## Code layout - `src/core/` — `tbg_core`, the game rules. **No SDL, no I/O** here, so it stays testable and can be driven by 4 players, replays, or compared against the ROM. Cell values and layouts deliberately mirror the ROM (10x24 board top-row-first, 2 hidden rows that never block; cell 1 block / 4 stone / 6 crystal; piece ids O L J S Z I T). - `src/gfx/` — ROM graphics decoder (no SDL); `tools/gfx_dump ROM OUT` renders what it decodes. - `src/audio/` — ROM sound: `cpu65816.*` runs bank-$88 code, `sound_ops.*` op generator, `sound.*` SPC host + API. External: `external/snes_spc` (LGPL, shared lib, unmodified). - `src/screens/` — the ROM's own non-battle screens (`snes.*` 65816+hardware model, `ppu.*` renderer, `flow.*` SceneRunner: logo → title → select → map → (our battle at 81:A443, $E0/$E1/$DE read, wins written back) → results/continue → ending). Boots into our menus; Esc swaps to/from the original ones (setting "Boot original menus", key `boot_original_menus`, default off). The book select (VS setup START) is captured at boot either way. Validate: `./build/scr_validate rom/tbg_jp.sfc re/runs/scr/main` (logo/title 0.00%, select 6.5%, map 2.1%); tests `./build/tbg_screens_tests`. Removable: the plan is native screens later (ROM independence). - `src/app/` — SDL3 front end only: `main.cpp` scenes/flow, `art_draw.*` original-art renderer, `draw.*` flat renderer + text, `controls.*` key/pad mapping, `settings.*` saved options. Dev aids: `TBG_SHOT`, `TBG_PRESS`, `TBG_SEED`, `XDG_DATA_HOME` (redirect settings/replays when testing). - `src/core/rom_ai.*` — literal port of the ROM CPU (planner + pad logic) over a WRAM model; reads its tables from the user's ROM at runtime (never embed ROM bytes in the repo). Keep it a transliteration of `re/tools/ai_ref.py` and re-run `ai_validate` after any change (must stay 411/411). - `tests/core_tests.cpp` — dependency-free CHECK-macro tests. Add a test for every rule taken from the ROM. - Defaults reproduce the original; extensions are opt-in flags (e.g. `Timing::allow_hard_drop`, `QueueMode::Mirrored`). When porting a ROM rule, cite the routine address in a short comment (e.g. `// 81:CE6C`). ## RE tooling (see re/NOTES.md for details and quirks) - ROM: `rom/tbg_jp.sfc` (gitignored; source `~/Downloads/Tetris Battle Gaiden (Japan).sfc`). Use the JP ROM for analysis; the English patch in `~/Downloads/` is only for reading names. - Ghidra 12.1.2 + `ghidra-snes` extension (built locally); project `ghidra/tbg`, scripts in `re/ghidra_scripts/`, disassembly export in `re/export/asm/` (trust the asm, not the decompiler). Don't run two `analyzeHeadless` jobs on `ghidra/tbg` at once — give parallel agents their own project dir. - `re/runs/flow_ghidra/lst/` and `re/runs/mech_1/battle.asm` cover code the static export misses (coverage-seeded). - Mesen2 headless: `re/mesen.sh [rom]`; Lua helpers `re/lua/*_lib.lua`. Savestates only work inside an exec callback. Low RAM is accessed through bank mirrors — watch mirrors too. - REA (`npx rea-agents@6.7.0`) is registered as an MCP server in `~/.claude.json`. ## Working conventions - The user (siege) knows C and Python; explain C++ concepts relative to C. Prefers autonomous, agent-heavy progress — keep working through the milestone rather than stopping to ask; use parallel agents for independent RE tasks, each writing its own `re/notes/*.md` file. - `sudo` can't be run from Claude Code (no TTY, not even via `!`); give the user one copy-pasteable command to run in a normal terminal. - Commit as work lands, with the Co-Authored-By trailer. Don't commit ROMs, Ghidra projects, savestates or `re/runs/`. ## Paused work (resume here) - **Compact power casts: DONE 2026-10-21** (user: the full-screen cut-in was "super super intrusive"). Setting `cast_animation` (Options + VS setup), default Compact: `MatchConfig::cast_freeze_cap` = 30 (main.cpp `kCompactCastFreeze`; 0 = original; replays `castcap`), the power applies when the short freeze ends (same result, test `test_cast_freeze_cap_shortens_the_pause_only`). ArtRenderer: small cut-in band over the caster's field (100 f), effects on their own timeline (`kCompactSkip` = 70 skips the original cut-in time) over the running game, whole-screen washes limited to the involved boards (`compact_fx_`), Bomb's window clipped to the victim field. Flat renderer has no cut-in (only the freeze changes). Original = unchanged. Headless-checked 2026-10-21: all 40 powers (10 characters x 4 levels, shots at +15/60/150/300 f) and a 4P inner-seat cast. Fixed then: self powers wash only the caster's field; washes run at half strength once play resumes; Change darkens only during the swap; the cut-in band fits each character's visible art (Wolfman's sits low in its canvas and was clipped out); the Dainashi web is clipped to the victim's field (both modes). Still to judge in play: Wolfman/Ninja band art is small (their poses move a lot); Bomb/Gang/Stardust effects play after the result already applied; Fever's banner is screen-centred (over the queue). - **AssetSource wired: DONE 2026-10-21** — `ArtRenderer(SDL_Renderer*, const gfx::AssetSource&)`, `--assets DIR` / `asset_dir` setting; checked: the extracted folder alone (no ROM) renders the battle like the ROM. Menus, sound and the AI still need the ROM (screens run ROM code; extracted WAVs/ai_bank81.bin could back them later). - **English menus: DONE** — `--menu-rom` / `menu_rom`, auto-detects `rom/tbg_en.sfc` or an "*English*" file next to the main ROM (banks 81 + 88 must equal the JP ROM); Options "Menu language". Title checked headless in both. - **Modern ruleset: DONE 2026-10-21** (decided with the user): `Timing::ruleset` (Classic default, byte-identical) / Modern (`Timing::modern()`): SRS shapes `piece_def(t, srs)` + `srs_kicks`, `Piece::srs` (hidden rows collide, y < 0 blocks), guideline lock delay (`modern_lock_delay` 30, `modern_lock_resets` 15, step reset on a new lowest row), DAS/ARR (`das_delay`/`das_repeat`, 0 = instant), `soft_drop_factor`, `Player::step_modern`, lock out = whole piece above the field. Hold (`Timing::hold`, `Input::hold`, any ruleset), ghost (`Player::ghost()`), T-spins (3-corner + last action rotation; mini/full, TST kick = full), `guideline_attack()` table + combo/B2B/PC (`Timing::guideline_attack`, either ruleset) with cancelling in `Match::distribute_attack`. Select uses X/Y in Modern. Replays: new "modern" line + hold = input bit 11. App: settings ruleset/hold/garbage (VS setup) and das/arr/soft_drop_factor (Options); `modern_input()` remaps Up = hard drop, L = cast, R = hold; Modern VS uses Bag7 (unless a mod picked another generator) and `ModernCpu` for CPU seats (FaithfulCpu assumes ROM rules); 1P/demo stay Classic. Tests: `tests/modern_tests.cpp`. `ModernCpu` (src/core/ai.*): BFS over SRS moves/kicks/soft drops (tucks, T-spins), El-Tetris features + attack/B2B/combo/crystals/TSD slots/danger, hold, 1-piece lookahead, re-paths every action frame, handles Reverse/Mahi/Nu/Hanten/Roulette, casts by the ROM COM predicates; difficulty = `kProfiles` in ai.cpp (0 Beginner ~21 PPM, 1 Casual ~46 PPM — user: the old level 1 was far too strong for a casual human; 2 Strong ~98, 3 Max ~178; low levels add judgement noise + plausible-but-wrong placements, no hold/T-spins/lookahead); ~0.4 ms/decision optimized, ~2 ms debug; tests `tests/modern_cpu_tests.cpp`. T-spin/B2B/combo/PC popups: DONE (`MatchEvent::Bonus`, `BonusPopups` in draw.*). Mirrored queue (own previews per player): DONE. - Dragon and Queen selectable in VS: DONE — our select screen (`vs_selectable_`), the book select, and the ROM's own 2P select via its hidden L/R pick. - Reference for behaviour: Apotris (https://gitea.com/akouzoukos/apotris, GPL-3.0 — read for behaviour only, don't copy code) and the public Tetris Guideline / SRS kick tables. - **Battle extras (`re/notes/anim_battle_extra.md`): DONE 2026-10-21.** Classic stock netting 81:D6AE (`MatchConfig::stock_netting`, pairwise for N players, TBG garbage only; replays: `faithful` line, older replays play without); big clear 81:92D9 (`MatchConfig::big_clear_freeze` 16 f, Modern 0; white stage/frame flash in both renderers — our frame art goes white entirely, the ROM keeps the BG1 border colours); round-win marks 81:FBF2 (`gfx::load_win_mark`, flight frame-exact from the ROM tables; 3-4P: half size beside the header, P3/P4 tinted); incoming-garbage gauge = ROM tile A0 (2P centre column x 118/129, 3-4P beside the field). Danger is audio-only (done). Pause screen (§4): DONE natively (`src/app/pause_screen.*`, texts `gfx::PauseTexts` in `src/gfx/pause_text.*`): portraits + label + text box per player (2P: P1 top-left / P2 bottom-right as the original; 3-4P a 2x2 grid); affordable -> "LEVEL n" + description, Up/Down browse levels 1-4 per human seat (82:A85C); else how-to text, or with crystals off (crystal_interval 0) the stack-height comment (82:D159 cols 3-6, 82:AA0F). ROM texts at runtime: JP strings drawn with the pause font (96:E869, 8298cc state machine) or the English patch's 18x8-tile 2bpp bitmaps (JSL BE:8500, pointer word = bank | addr hi) when Menu language = English; our own English text (`own_power_text` etc.) for no ROM / modded characters or powers. Pause SFX $08. Dev aid: `TBG_METER=frame:seat:value`. Not done: preview minis (we draw pieces). Dev aids: `TBG_TETRIS=frame:seat` (4 rows + I pieces -> a CPU seat Tetrises; shot at the 2nd white frame), `TBG_SHOT_ROUNDEND=N` (shot N frames into a round-end freeze). - Dark's flashlight: DONE from the measured spec (`re/notes/anim_dark.md`) in both renderers (`dark_cone_row` in draw.hpp). - **VERIFY FIRST** (use `TBG_CAST="frame:seat:level"` + `TBG_SHOT`): headless-checked (by eye, vs the notes; positions differ from the original's layout): Bomb, READY/GO, Dark, Medusa, Pentris, Sol, Stardust, Copy, Yose, Seesaw, Gang, Press, Mambo, Fever, Clear, HyperFly, Fly, Moses (glow toned down), Noroi, Change, Fax, Vampire, Suritote, Inori (plays the rolled power's animation), Mirurun, Cut, Roulette, Shield cast; lasting tints Shield (made stronger), Reverse, Mahi, Doubles, Fever, Noroi; Doton/Select brightened but not re-shot. Effect tints now end with the suspension (windows from the notes outlast it for Moses/Cut/Fly/Yose...). Not checked: Mayakashi (flicker not caught on camera), Nu (its suspension 62 ends before the effect starts: only the cut-in shows), the tint-only casts (Remocon, Kaiten, Hanten, Nakayoshi, Dainashi). Also: CONTROLS screen capture with a real gamepad, VS with human seats on pads 3-4, continue/ending sounds. Known gaps: sprite motion paths are invented (only Bomb/Dark exact), BG3-overlay/mosaic effects approximated by tints, Remocon pad sprite not found. VERIFY by ear: ROM-flow battles no longer restart the stage song / results song (checked only from the logged sink calls); Options "Menu language" toggle (reboots the ROM screens; not run). Battle layout (2026-10-21, Puyo Puyo Tetris style): HOLD box off each field's top-left (hold on), own NEXT column down its right (Mirrored queue; shared queue keeps the centre box); 4 boards with side boxes don't fit 960 px, so `ArtRenderer::render_battle` draws them on a wider transparent canvas scaled over the stage (`field()` returns window coords). Headless-checked 2P/3P/4P mirrored + 4P shared; VERIFY: real play, popups and cast effects at the 4P scale. Timed Stardust (`Match::falling_stars`) shot in compact mode only. Seesaw now exact (2026-10-22, `re/notes/anim_battle.md` "Seesaw"): timed run `Match::seesaw()` / `tick_seesaw` (victims rise at rel 175, caster rows lift 236, caster drops 277, rows land 293), kids/seesaw/sliding rows in `ArtRenderer::draw_seesaw`; headless-compared with the emulator frame by frame (P1 + P2 casts, original + compact). Not shot: 3-4P. Found then: every `PowerDef::suspend` is counted from rel 100 (the ROM's cast -> victim resumes is +100: Seesaw 369, Stardust 507, Copy 586), so original-mode freezes end ~100 f early — not changed yet. - **Battle animations: research DONE** (`re/notes/anim_battle.md`, tools `re/tools/anim_*.py`); **implementation started**: `gfx::load_effect_sheet(rom, power)` (per-power effect sprite strips + palettes, table from `re/runs/anim/extract/assets.txt`) and `gfx::load_ready_go(rom)` (R E A D Y G O letters, 16x16) exist and are verified via `tools/gfx_dump`; `Match::casting()` now also lists all targets. **Next:** in `src/app/art_draw.cpp` (READY/GO done: `draw_ready_go`; Bomb, Medusa, Clear, Fly, HyperFly, Moses, Yose, Noroi, Sol, Change, Copy, Fax done (unverified except Bomb) in `ArtRenderer::draw_effect`, extend that switch) add effects driven by rel = frames since the cast (track `m.frozen()` at cast start, rel = start - frozen): show the cut-in only for rel < ~100, then per power (notes §3): Bomb exact (circle window centred at victim field (40,41) orig px, r = 16 + 8*floor((rel-146)/3), additive orange tint R 1->21 over rel 145-201, G 1->5 over 145-159; explosions = 32x32 frames at sheet x 0/32/64/96 at random victim cells rel 229-364; fade 365-388), Medusa white flash 152-196 + grey victim 240-388, Pentris critter (sheet poses ~42x32) pushing up the centre 103-345, Stardust dark tint + falling stars (sheet tile 0A), Mirurun pink sprites sweeping the caster's bottom rows 103-226, Copy/Fax scanning light bar, Fly/HyperFly glow, Clear white fade, the rest as tints from the table; persistent status tints (Shield, Reverse, Mahi, Doton, Select, Fever, Doubles, Noroi); READY/GO at round start (letters stacked at (120,49) spread to x 88..152 over 35 f, ±14 px wave, GO at x 112/136 from +150 to +205; map orig x 128 -> queue column centre, y -> kFrameY + 2y). - **VS select with original menus: DONE 2026-10-21.** The ROM's 2P select keeps running for 2 seats; its hidden boss pick (83:8266, enabled by $DA=1/$DB=$FE, which `SceneRunner::boss_select` pokes at every select entry) gives Dragon/Queen while L/R is held to the end — our overlay previews the boss on that page. With seats 3-4 set, `SceneRunner::vs_takeover` parks the ROM in its select loop (Stop::VsSelect at 8381E1/838136 after the book has opened) and the app's Select scene draws a "book select" over `vs_select_backdrop()` (BG2 with the page contents replaced by paper); B leaves via the select's own exit (838262, A=1 → title). VS setup's START uses the same book (captured headless at startup by `capture_vs_backdrop`, ~1 s on a thread). Verified headless (2P boss, 3P, 4P, back, JP + English). TBG_PRESS now takes "from-to:btn", "p2.btn" and l/r. - **Other screens: DONE** (src/screens). Left: untested real 2P via the ROM select; ROM's $D2/$F6/$F7 ignored (our settings used); the ROM stage intro (~7 s) plays before our READY/GO. - (old) **Other screens' animations: research DONE** (`re/notes/anim_screens.md`: run the ROM's own scene code in a 65816 + PPU model — Python reference `re/tools/scr_snes.py` + `scr_ppu.py` matches Mesen 0-6.5%). Next: port to C++ (reuse `src/audio/cpu65816.*`), render 256x224 at 2x, feed our input, route sound calls to tbg_audio. - (old) **Other screens' animations: research paused** (tools `re/lua/scr_*.lua`, `re/tools/scr_*.py` incl. a 65816/PPU sim `scr_snes.py`; no notes yet). Goal: `re/notes/anim_screens.md` (title mode 7, intro book, char select, map, boss intros, continue, ending) then implement. Run only ONE background agent at a time (credits).