#!/usr/bin/env python3 """Extract Tetris Battle Gaiden (J) graphics from the user's ROM into PNGs + a JSON manifest. Never commit the outputs (they are ROM-derived): they go to re/runs/gfx/extract/ (gitignored). usage: gfx_extract.py ROM OUTDIR [--validate DUMP_PREFIX] --validate re/runs/gfx/dma2/f04200 rebuild that battle frame from ROM assets (+ the game state that is not graphics: board cells, meter/name tiles, OAM) and compare it to the Mesen screenshot. Spec: re/notes/graphics.md.""" import json import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from gfx_decomp import decompress, lorom # noqa: E402 from gfx_snes import Layer, diff_stats, palette, read_png_rgb, render_mode1, tile_sheet, write_png # noqa: E402 def ptr24(rom, addr): o = lorom(addr) return rom[o] | (rom[o + 1] << 8) | (rom[o + 2] << 16) def raw(rom, addr, n): o = lorom(addr) return rom[o:o + n] # ---- what the battle screen loads (80:8355 .. 80:8556; re/notes/graphics.md) ------------------------- BATTLE_STATIC = [ # name, ROM source, VRAM byte address it is uploaded to, bytes uploaded, bpp, use ('battle_obj', 0x9F8000, 0x0000, 0x2000, 4, 'OBJ name table 1: preview minis, stock orbs, meter, READY/GO'), ('battle_bg1_chr', 0x9EDE2D, 0x4000, 0x2000, 4, 'BG1 tiles: board cells (tile = cell value), frame, kana font'), ('battle_bg1_map', 0x859F84, 0xF000, 0x0800, 0, 'BG1 32x32 tilemap: board frames and centre column'), ('battle_bg3_chr', 0x9F969C, 0xE000, 0x1000, 2, 'BG3 tiles (2bpp; BG3 is off on the main screen in battle)'), ] STAGE_CHR_TABLE, STAGE_MAP_TABLE, STAGE_PAL_TABLE = 0x808453, 0x808471, 0x80848F # 10 x 24-bit each BASE_PALETTE = 0x85EC27 # 512 bytes, full CGRAM (80:850B) CUTIN_TABLE = 0x80BD07 # 10 x 4 bytes: 24-bit pointer + pad (80:BC27) CUTIN_PAL_TABLE = 0x8296F9 # 6 x 4 bytes; palette n = table[n>>2] + (n&3)*128, 32 bytes (82:96AA) CHARACTERS = ['Halloween', 'Mirurun', 'Shaman', 'Aladdin', 'Princess', 'Bit', 'Ninja', 'Wolfman', 'Dragon', 'Queen'] # Other screens: compressed assets seen in a boot -> battle capture (re/runs/gfx/dma2/dma.txt), by caller. SCREEN_OF_CALLER = [ (0x83A400, 0x83A500, 'logo'), (0x83F200, 0x83F300, 'title'), (0x84EB00, 0x84EE00, 'book/intro'), (0x84EE00, 0x84F200, 'book/intro'), (0x838200, 0x838500, 'character select'), (0x848F00, 0x849400, 'battle world map'), (0x808300, 0x808560, 'battle'), (0x80BC00, 0x80BD00, 'power cut-in'), ] def screen_for(caller): for lo, hi, name in SCREEN_OF_CALLER: if lo <= caller < hi: return name return 'unknown' def scaled(w, h, img, s): W, H = w * s, h * s out = bytearray(W * H * 3) for y in range(H): row = (y // s) * w for x in range(W): o = (row + x // s) * 3 out[(y * W + x) * 3:(y * W + x) * 3 + 3] = img[o:o + 3] return W, H, out def save_sheet(path, data, bpp, pal16, scale=2, cols=16): w, h, img = tile_sheet(data, bpp, pal16, cols) w, h, img = scaled(w, h, img, scale) write_png(path, w, h, img) return w, h def battle_vram(rom, stage, obj2=None): """VRAM image of the battle screen for `stage` from ROM data alone (board cells not included).""" v = bytearray(0x10000) for _, src, dst, n, _, _ in BATTLE_STATIC: d, _, _ = decompress(rom, src) v[dst:dst + n] = d[:n] chr_ = decompress(rom, ptr24(rom, STAGE_CHR_TABLE + 3 * stage))[0] v[0x6000:0x6000 + 0x7000] = chr_[:0x7000] mp = decompress(rom, ptr24(rom, STAGE_MAP_TABLE + 3 * stage))[0] v[0xF800:0x10000] = mp[:0x800] if obj2 is not None: # name table 2 holds whatever the previous screen left (map kana) until a cut-in v[0x2000:0x4000] = obj2 return v def battle_cgram(rom, stage): c = bytearray(raw(rom, BASE_PALETTE, 512)) c[0x60:0x100] = raw(rom, ptr24(rom, STAGE_PAL_TABLE + 3 * stage), 160) # palettes 3-7 (80:84AD) return c def cutin_palette(rom, n): base = ptr24(rom, CUTIN_PAL_TABLE + 4 * (n >> 2)) return raw(rom, base + (n & 3) * 128, 32) def main(): rom = open(sys.argv[1], 'rb').read() out = sys.argv[2] os.makedirs(out, exist_ok=True) manifest = {'rom': os.path.basename(sys.argv[1]), 'battle': {}, 'stages': [], 'cutins': [], 'other_assets': []} base_cg = raw(rom, BASE_PALETTE, 512) base_pal = palette(base_cg) # Battle statics for name, src, dst, n, bpp, use in BATTLE_STATIC: d, csize, _ = decompress(rom, src) entry = {'rom': f'{src:06X}', 'compressed': csize, 'size': len(d), 'vram': f'{dst:04X}', 'uploaded': n, 'bpp': bpp, 'use': use} if bpp == 4: pal = base_pal[128:144] if 'obj' in name else base_pal[16:32] save_sheet(f'{out}/{name}.png', d[:n], 4, pal) if name == 'battle_bg1_chr': save_sheet(f'{out}/{name}_p2.png', d[:0x400], 4, base_pal[32:48], scale=4) save_sheet(f'{out}/{name}_p0.png', d[:0x400], 4, base_pal[0:16], scale=4) entry['png'] = f'{name}.png' elif bpp == 2: save_sheet(f'{out}/{name}.png', d[:n], 2, base_pal[0:4]) entry['png'] = f'{name}.png' manifest['battle'][name] = entry manifest['battle']['palette'] = {'rom': f'{BASE_PALETTE:06X}', 'size': 512, 'use': 'full CGRAM; P1 cells palette 1, P2 palette 2, crystals palette 0'} # Stages: compose the background alone (BG2) at 256x224 for s in range(10): chr_src, map_src, pal_src = (ptr24(rom, t + 3 * s) for t in (STAGE_CHR_TABLE, STAGE_MAP_TABLE, STAGE_PAL_TABLE)) v = battle_vram(rom, s) cg = battle_cgram(rom, s) img = render_mode1(v, cg, bytes(0x220), {2: Layer(0x6000, 0xF800, 4)}, 0x02) write_png(f'{out}/stage_{s}_{CHARACTERS[s].lower()}.png', 256, 224, img) manifest['stages'].append({'stage': s, 'opponent': CHARACTERS[s], 'chr': f'{chr_src:06X}', 'map': f'{map_src:06X}', 'palette': f'{pal_src:06X}', 'palette_rows': '3-7', 'png': f'stage_{s}_{CHARACTERS[s].lower()}.png'}) # Power cut-in characters (OBJ name table 2) for c in range(10): src = ptr24(rom, CUTIN_TABLE + 4 * c) d, csize, _ = decompress(rom, src) pal = palette(cutin_palette(rom, c)) save_sheet(f'{out}/cutin_{c}_{CHARACTERS[c].lower()}.png', d, 4, pal) alt = palette(cutin_palette(rom, c + 12)) if c + 12 < 24 else None if alt: save_sheet(f'{out}/cutin_{c}_{CHARACTERS[c].lower()}_alt.png', d, 4, alt) manifest['cutins'].append({'character': CHARACTERS[c], 'rom': f'{src:06X}', 'size': len(d), 'compressed': csize, 'vram': '2000-37FF (words 1000/1600/1C00: 0C00+0C00+0800 bytes)', 'palette': f'{ptr24(rom, CUTIN_PAL_TABLE + 4 * (c >> 2)) + (c & 3) * 128:06X}', 'palette_alt': f'{ptr24(rom, CUTIN_PAL_TABLE + 4 * ((c + 12) >> 2)) + ((c + 12) & 3) * 128:06X}', 'cgram_row': 11}) # Everything else the capture decompressed (title, intro book, character select, map) cap = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'runs', 'gfx', 'dma2', 'dma.txt') seen = set() if os.path.exists(cap): for line in open(cap): if 'DECOMP' not in line: continue parts = dict(p.split('=') for p in line.split()[2:]) src, caller, dst = int(parts['src'], 16), int(parts['caller'], 16), int(parts['dst'], 16) if src in seen: continue seen.add(src) d, csize, _ = decompress(rom, src) scr = screen_for(caller) name = f'asset_{src:06X}' # Previews use a generic grey ramp: the real palette depends on the screen's CGRAM. grey = [(i * 17, i * 17, i * 17) for i in range(16)] save_sheet(f'{out}/{name}.png', d, 4, grey, scale=1, cols=32) manifest['other_assets'].append({'rom': f'{src:06X}', 'size': len(d), 'compressed': csize, 'caller': f'{caller:06X}', 'screen': scr, 'wram_buffer': f'{dst:06X}', 'png': f'{name}.png'}) json.dump(manifest, open(f'{out}/manifest.json', 'w'), indent=1) print(f'wrote {out}/manifest.json: {len(manifest["battle"])} battle assets, {len(manifest["stages"])} stages, ' f'{len(manifest["cutins"])} cut-ins, {len(manifest["other_assets"])} other assets') if '--validate' in sys.argv: validate(rom, sys.argv[sys.argv.index('--validate') + 1], out) def validate(rom, pre, out): """Rebuild a battle frame: graphics from ROM; game state (board cells, dynamic BG1 entries, OAM, animated palette rows 8-10) from the capture. Compare to the Mesen screenshot.""" real_v = open(pre + '.vram', 'rb').read() real_cg = open(pre + '.cgram', 'rb').read() oam = open(pre + '.oam', 'rb').read() wram = open(pre + '.wram', 'rb').read() stage = wram[0xE1] # opponent id = stage unless $D9 overrides (80:8339) v = battle_vram(rom, stage, obj2=real_v[0x2000:0x4000]) # Board cells: tile = cell value, attr $24/$28 (palette 1/2, priority), crystals $20 (palette 0) (81:8000). for player, (board, word0) in enumerate(((0x296, 0x7864), (0x4F6, 0x7872))): for r in range(22): for c in range(10): cell = wram[board + r * 10 + c] attr = 0x20 if cell == 6 else (0x24 if player == 0 else 0x28) a = (word0 + r * 32 + c) * 2 v[a], v[a + 1] = cell, attr # Other dynamic BG1 entries (meter columns at words 78A2/78BD, name rows 7B12.., gauge 7B44/7B52): runtime # text/meters. Count how many BG1 map bytes still differ and take them from the capture. dyn = [a for a in range(0xF000, 0xF800) if v[a] != real_v[a]] for a in dyn: v[a] = real_v[a] cg = bytearray(battle_cgram(rom, stage)) cg[0x100:0x160] = real_cg[0x100:0x160] # OBJ palettes 8-10 are colour-cycled at runtime (81:9369) img = render_mode1(v, cg, oam, {1: Layer(0x4000, 0xF000, 4), 2: Layer(0x6000, 0xF800, 4)}, 0x13) write_png(f'{out}/validate_battle.png', 256, 224, img) w, h, ref = read_png_rgb(pre + '.png') print(f'validate: stage {stage}; {len(dyn)} BG1 map bytes of runtime text/meters taken from the capture; ' f'{100 * diff_stats(img, ref):.2f}% of pixels differ from {pre}.png') if __name__ == '__main__': main()