#!/usr/bin/env python3 """TBG graphics decompressor (80:B7DA) and LoROM helpers. Format ("interleaved RLE"): the output is written with stride 2, first the even bytes, then the odd ones. 00 FF plane marker: if writing even bytes, restart at dest+1 (odd bytes); else end of data 1nnnnnnn vv run: byte vv, max(n,1) times 0nnnnnnn ... literal: the next max(n,1) bytes (n == 0 still writes one byte: the 65816 loop is do-while.) Each output byte advances the destination by 2. """ import sys def lorom(addr): """SNES LoROM address -> file offset.""" bank, lo = (addr >> 16) & 0x7F, addr & 0xFFFF assert lo >= 0x8000, hex(addr) return bank * 0x8000 + lo - 0x8000 def decompress(rom, src, out=None, dst=0): """Decode the stream at SNES address `src` into bytearray `out` at offset `dst` (grown as needed). Returns (out, compressed_size, end_offset).""" if out is None: out = bytearray() p = lorom(src) start = p y = dst odd = False def put(off, v): if off >= len(out): out.extend(b'\0' * (off + 1 - len(out))) out[off] = v while True: b0 = rom[p] if b0 == 0x00 and rom[p + 1] == 0xFF: if odd: return out, p + 2 - start, y odd = True y = dst + 1 p += 2 continue n = max(b0 & 0x7F, 1) if b0 >= 0x80: v = rom[p + 1] for _ in range(n): put(y, v) y += 2 p += 2 else: p += 1 for _ in range(n): put(y, rom[p]) p += 1 y += 2 if __name__ == '__main__': rom = open(sys.argv[1], 'rb').read() src = int(sys.argv[2], 16) out, size, _ = decompress(rom, src) print(f'{src:06X}: {size} bytes -> {len(out)} bytes') if len(sys.argv) > 3: open(sys.argv[3], 'wb').write(out)