Files
zelda-1-prometeu-port/tools/extract_start_room.py
T

129 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""Decode the first overworld room's graphics directly from the verified ROM."""
import hashlib
import json
from PIL import Image
from extract_graphics import ROOT, ROM_SHA256, decode
ROOM_ID = 0x77
# Digital RGB approximations, consistent with the Link export. NES codes remain
# authoritative; composite NES output has no single exact RGB interpretation.
RGB = {0x0F: (0, 0, 0), 0x1A: (0, 168, 0), 0x17: (172, 124, 0),
0x37: (252, 216, 168), 0x12: (0, 88, 248), 0x30: (248, 248, 248),
0x00: (124, 124, 124), 0x16: (248, 56, 0), 0x27: (252, 160, 68),
0x36: (248, 184, 160)}
def write_json(path, value):
path.write_text(json.dumps(value, indent=2) + "\n")
def extract(room_id=ROOM_ID, output_name="start"):
rom = (ROOT / ".tmp/zelda-1.nes").read_bytes()
if hashlib.sha256(rom).hexdigest() != ROM_SHA256:
raise ValueError("Unverified ROM revision")
prg = rom[16:]
if prg[103168 + 47] != ROOM_ID:
raise ValueError("Overworld starting-room metadata differs from the reference")
def locate(signature):
signature = bytes.fromhex(signature)
if prg.count(signature) != 1:
raise ValueError("Expected a unique verified table signature")
return prg.index(signature)
primary_offset = locate("246ff3fa98908f958e907476f3242689")
secondary_offset = primary_offset + 56
primary = prg[primary_offset:secondary_offset]
secondary = prg[secondary_offset:secondary_offset + 64]
assert secondary[:16] == bytes.fromhex("242424246f6f6f6ff3f3f3f3fafafafa")
directory_offset = locate("d89b0d9c3e9c809cc49cf69c329d6d9d")
directory = [int.from_bytes(prg[directory_offset + i * 2:directory_offset + i * 2 + 2], "little")
for i in range(16)]
attrs = [prg[99328 + i * 128 + room_id] for i in range(6)]
# LayoutRoomOW shifts the room descriptor four times, discarding bit 7.
# Preserve bit 6: this room uses layout $72, not layout $32.
layout_id = attrs[3] & 0x7F
layout_offset = 87064 + layout_id * 16
descriptors = prg[layout_offset:layout_offset + 16]
tilemap = [[0x24] * 32 for _ in range(30)]
palette_map = [[0] * 32 for _ in range(30)]
columns = []
object_replacements = [0xC8, 0xD8, 0xC4, 0xBC, 0xC0, 0xC0]
for x, descriptor in enumerate(descriptors):
heap = 5 * 16384 + directory[descriptor >> 4] - 0x8000
cursor, remaining = heap, descriptor & 0x0F
while True:
if prg[cursor] & 0x80:
if remaining == 0:
break
remaining -= 1
cursor += 1
if cursor >= 6 * 16384:
raise ValueError("Column descriptor crossed its bank")
start = cursor
squares = []
while len(squares) < 11:
value = prg[cursor]
index = value & 0x3F
if index >= len(primary):
raise ValueError("Unknown overworld metatile")
squares.extend([index] * (2 if value & 0x40 else 1))
cursor += 1
if len(squares) != 11:
raise ValueError("Column does not decode to eleven squares")
columns.append({"descriptor": descriptor, "prg_offset": start,
"compressed_hex": prg[start:cursor].hex(), "squares": squares})
for y, index in enumerate(squares):
base = primary[index]
if 0xE5 <= base <= 0xEA:
base = object_replacements[base - 0xE5]
tiles = list(secondary[index * 4:index * 4 + 4]) if index < 16 else list(range(base, base + 4))
palette = (attrs[1] if 2 <= x <= 13 and 2 <= y <= 8 else attrs[0]) & 3
for ordinal, (dx, dy) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))):
tx, ty = x * 2 + dx, 8 + y * 2 + dy
tilemap[ty][tx] = tiles[ordinal]
palette_map[ty][tx] = palette
patterns = bytearray(4096)
patterns[0:0x700] = prg[34687:34687 + 1792]
patterns[0x700:0xF20] = prg[51515:51515 + 2080]
patterns[0xF20:0x1000] = prg[36479:36479 + 224]
assert prg[103168:103171] == bytes.fromhex("3f0020")
palettes = [list(prg[103171 + n * 4:103175 + n * 4]) for n in range(4)]
output = ROOT / f"extracted/overworld/{output_name}"
output.mkdir(parents=True, exist_ok=True)
tile_dir = output / "tiles"
tile_dir.mkdir(exist_ok=True)
used = sorted({(tilemap[y][x], palette_map[y][x]) for y in range(8, 30) for x in range(32)})
canvas = Image.new("RGBA", (256, 240), (0, 0, 0, 255))
images = {}
for tile_id, palette_id in used:
indices = decode(patterns[tile_id * 16:(tile_id + 1) * 16])
image = Image.new("RGBA", (8, 8))
image.putdata([(*RGB[palettes[palette_id][index]], 255) for index in indices])
image.save(tile_dir / f"tile_{tile_id:02x}_p{palette_id}.png")
images[(tile_id, palette_id)] = image
for y in range(8, 30):
for x in range(32):
canvas.paste(images[(tilemap[y][x], palette_map[y][x])], (x * 8, y * 8))
canvas.save(output / "room.png")
canvas.resize((768, 720), Image.Resampling.NEAREST).save(output / "room@3x.png")
data = {"rom_sha256": ROM_SHA256, "room_id": room_id, "layout_id": layout_id,
"start_room_id_prg_offset": 103168 + 47,
"layout_prg_offset": layout_offset, "room_attributes": attrs,
"primary_table_prg_offset": primary_offset, "secondary_table_prg_offset": secondary_offset,
"column_directory_prg_offset": directory_offset, "columns": columns,
"background_nes_palettes": palettes, "tilemap": tilemap, "palette_map": palette_map,
"used_tiles": [{"tile_id": t, "palette_id": p, "file": f"tile_{t:02x}_p{p}.png"} for t, p in used],
"scope": "Overworld terrain only; HUD reserved, no collisions, transitions or room secrets"}
write_json(output / "room.json", data)
print(json.dumps({"room": hex(room_id), "layout": hex(layout_id),
"unique_tile_palette_pairs": len(used), "columns": len(columns)}, indent=2))
return data
if __name__ == "__main__":
extract()