#!/usr/bin/env python3 """Extract Zelda's raw NES pattern graphics without guessing sprite composition.""" import argparse import hashlib import json from pathlib import Path from PIL import Image, ImageDraw ROOT = Path(__file__).resolve().parents[1] ROM_SHA256 = "89232edf4f9b52e3cb872094bc78973de080befca2ddea893b6e936066514d4e" SOURCE = "https://github.com/aldonunez/zelda1-disassembly/blob/master/src/bins.xml" # Offsets are relative to PRG, excluding the 16-byte iNES header. # PPU destinations checked against bank 1, bank 2 and bank 3 load routines. BLOCKS = [ ("demo_sprites", 19892, 2304, 0x0700), ("demo_background", 22196, 2080, 0x1700), ("common_sprites", 32895, 1792, 0x0000), ("common_background", 34687, 1792, 0x1000), ("common_misc", 36479, 224, 0x1F20), ("underworld_background", 49435, 2080, 0x1700), ("overworld_background", 51515, 2080, 0x1700), ("overworld_sprites", 53595, 1824, 0x08E0), ("underworld_sprites_358", 55419, 544, 0x09E0), ("underworld_sprites_469", 55963, 544, 0x09E0), ("underworld_sprites_common", 56507, 256, 0x08E0), ("underworld_sprites_127", 56763, 544, 0x09E0), ("bosses_1257", 57307, 1024, 0x0C00), ("bosses_3468", 58331, 1024, 0x0C00), ("boss_ganon", 59355, 1024, 0x0C00), ] def decode(data): """NES 2bpp: eight low-plane bytes followed by eight high-plane bytes.""" if len(data) != 16: raise ValueError("A pattern must contain exactly 16 bytes") return [((data[y] >> (7 - x)) & 1) | (((data[y + 8] >> (7 - x)) & 1) << 1) for y in range(8) for x in range(8)] def indexed(pixels, size): image = Image.new("P", size) # Neutral palette, deliberately not presented as original game colors. image.putpalette([v for c in (0, 85, 170, 255) for v in (c, c, c)] + [0] * 756) image.putdata(pixels) return image def encode(pixels): """Reverse decoding to verify the PNG preserves every source bit.""" return bytes(sum(((pixels[y * 8 + x] >> plane) & 1) << (7 - x) for x in range(8)) for plane in range(2) for y in range(8)) def extract(rom_path, output): rom = rom_path.read_bytes() digest = hashlib.sha256(rom).hexdigest() if digest != ROM_SHA256: raise ValueError("ROM differs from the verified input; offsets must be validated first") if rom[:4] != b"NES\x1a" or len(rom) != 16 + 8 * 16384: raise ValueError("Unexpected ROM layout") prg = rom[16:] output.mkdir(parents=True, exist_ok=True) manifest = {"rom_sha256": digest, "offset_basis": "PRG (file offset minus 16)", "reference": SOURCE, "palette": "neutral grayscale indices 0..3", "scope": "All 15 documented raw pattern blocks; not assembled scenes or animations", "blocks": [], "ppu_sets": []} all_tiles = [] for name, offset, length, ppu in BLOCKS: block_dir = output / "tiles" / name block_dir.mkdir(parents=True, exist_ok=True) count = length // 16 sheet = Image.new("P", (128, ((count + 15) // 16) * 8)) sheet.putpalette(indexed([0] * 64, (8, 8)).getpalette()) records = [] for n in range(count): source = prg[offset + n * 16:offset + (n + 1) * 16] pixels = decode(source) if encode(pixels) != source: raise AssertionError("Tile roundtrip failed") tile = indexed(pixels, (8, 8)) path = block_dir / f"{n:03d}.png" tile.save(path) # Validate the saved file, not only the in-memory decoder. with Image.open(path) as saved: if encode(list(saved.getdata())) != source: raise AssertionError(f"PNG roundtrip failed: {path}") sheet.paste(tile, ((n % 16) * 8, (n // 16) * 8)) all_tiles.append(tile) records.append({"index": n, "prg_offset": offset + n * 16, "file_offset": offset + 16 + n * 16, "ppu_address": f"0x{ppu + n * 16:04X}", "png": path.relative_to(output).as_posix(), "sha256_2bpp": hashlib.sha256(source).hexdigest()}) sheets = output / "sheets" sheets.mkdir(exist_ok=True) sheet.save(sheets / f"{name}.png") sheet.resize((sheet.width * 4, sheet.height * 4), Image.Resampling.NEAREST).save( sheets / f"{name}@4x.png") manifest["blocks"].append({"name": name, "prg_offset": offset, "length": length, "tiles": records}) # Reconstruct the actual pattern memory used by each level, including gaps. common = ["common_sprites", "common_background", "common_misc"] sets = {"demo": common + ["demo_sprites", "demo_background"], "overworld": common + ["demo_sprites", "overworld_background", "overworld_sprites"]} for level in range(1, 10): enemies = "127" if level in (1, 2, 7) else "358" if level in (3, 5, 8) else "469" boss = "bosses_1257" if level in (1, 2, 5, 7) else "bosses_3468" if level != 9 else "boss_ganon" sets[f"dungeon_{level}"] = common + ["underworld_background", "underworld_sprites_common", f"underworld_sprites_{enemies}", boss] (output / "ppu").mkdir(exist_ok=True) for name, names in sets.items(): memory = bytearray(8192) for block_name in names: _, offset, length, ppu = next(b for b in BLOCKS if b[0] == block_name) memory[ppu:ppu + length] = prg[offset:offset + length] for table, base in (("sprites", 0), ("background", 4096)): sheet = indexed([0] * (128 * 128), (128, 128)) for n in range(256): tile = indexed(decode(memory[base + n * 16:base + (n + 1) * 16]), (8, 8)) sheet.paste(tile, ((n % 16) * 8, (n // 16) * 8)) sheet.save(output / "ppu" / f"{name}_{table}.png") manifest["ppu_sets"].append({"name": name, "blocks_in_load_order": names}) width = 640 height = sum((((length // 16 + 15) // 16) * 24 + 32) for _, _, length, _ in BLOCKS) overview = Image.new("RGB", (width, height), "#252525") draw = ImageDraw.Draw(overview) y = 0 for name, _, length, _ in BLOCKS: draw.text((8, y + 8), f"{name} ({length // 16} tiles)", fill="white") with Image.open(output / "sheets" / f"{name}.png") as sheet: zoom = sheet.convert("RGB").resize((384, sheet.height * 3), Image.Resampling.NEAREST) overview.paste(zoom, (8, y + 28)) y += ((length // 16 + 15) // 16) * 24 + 32 overview.save(output / "overview.png") manifest["tile_count"] = len(all_tiles) manifest["unique_tile_count"] = len({bytes(t.getdata()) for t in all_tiles}) manifest["png_count"] = len(list(output.rglob("*.png"))) (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") print(json.dumps({k: manifest[k] for k in ("tile_count", "unique_tile_count", "png_count")}, indent=2)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--rom", type=Path, default=ROOT / ".tmp/zelda-1.nes") parser.add_argument("--output", type=Path, default=ROOT / "extracted/graphics") args = parser.parse_args() extract(args.rom, args.output)