#!/usr/bin/env python3 """Decode the verified ROM's title PPU records, palettes and OAM; publish UI.""" import hashlib,json from PIL import Image from extract_graphics import ROOT,ROM_SHA256,decode from extract_start_room import write_json,RGB TITLE_UUID='73c07dc9-f2a6-48ce-a221-2949ad10be36' MENU_UUID='8a4283fe-9532-46db-868b-852ca9914730' def prepare(): rom=(ROOT/'.tmp/zelda-1.nes').read_bytes();assert hashlib.sha256(rom).hexdigest()==ROM_SHA256 p=rom[16:];rgb=dict(RGB);rgb.update({0x10:(188,188,188),0x08:(80,48,0),0x28:(248,216,120),0x3b:(160,252,224),0x22:(104,136,252),0x07:(136,20,0)}) registry_path=ROOT/'assets/.prometeu/index.json';registry=json.loads(registry_path.read_text()) def register(root,uuid): matches=[a for a in registry['assets'] if a['asset_uuid']==uuid or a['root']==root] if matches: assert len(matches)==1 and matches[0]['asset_uuid']==uuid and matches[0]['root']==root matches[0]['included_in_build']=True;return matches[0]['asset_id'] n=registry['next_asset_id'];registry['next_asset_id']+=1;registry['assets'].append({'asset_id':n,'asset_uuid':uuid,'root':root,'included_in_build':True});return n def rgba(colors):return [int.from_bytes(bytes(c),'big',signed=True) for c in colors] # Use authoritative pointers in this ROM, not stale .dat offsets in bins.xml. table=next(i for i in range(105830,107300) if p[i+6:i+8]==bytes.fromhex('1468') and p[i+12:i+14]==bytes.fromhex('1c68')) def record_offset(index): ptr=int.from_bytes(p[table+index*2:table+index*2+2],'little') assert 0x8000<=ptr<0xc000 return 6*16384+ptr-0x8000 def transfer(offset,memory): start=offset;records=[] while p[offset]<128: address=p[offset]*256+p[offset+1];control=p[offset+2];count=control&63 or 64;stride=32 if control&128 else 1;offset+=3 assert 0x2000<=address<0x4000 for i in range(count):memory[address+i*stride]=p[offset if control&64 else offset+i] records.append({'address':address,'control':control,'count':count}) offset+=1 if control&64 else count return {'prg_offset':start,'length':offset+1-start,'records':records} memory=bytearray(0x4000);memory[0x2000:0x2800]=bytes([36])*0x800 title_record=transfer(record_offset(8),memory) palette_offset=p.index(bytes.fromhex('3f0020360f00103617270f36081a2836303b22')) palettes=[list(p[palette_offset+3+i*4:palette_offset+7+i*4]) for i in range(8)] glow=[0x27,0x37,0x37,0x27,0x17,0x07,0x07,0x17] runtime_colors=[] for i,row in enumerate(palettes):runtime_colors.append([(*rgb[c],255) if j or i<4 else (0,0,0,0) for j,c in enumerate(row)]) for value in glow:runtime_colors.append([(*rgb[c],255) for c in (0x36,0x17,value,0x0f)]) canonical=runtime_colors[0] patterns=bytearray(8192) for offset,length,address in [(32895,1792,0),(34687,1792,0x1000),(36479,224,0x1f20),(19892,2304,0x700),(22196,2080,0x1700)]:patterns[address:address+length]=p[offset:offset+length] oam_offset=p.index(bytes.fromhex('77cac2d077ccc2c877ca8228')) oam=[list(p[oam_offset+i:oam_offset+i+4]) for i in range(0,112,4)] title_id=register('ui/title',TITLE_UUID) bank=ROOT/'assets/ui/title';bank.mkdir(parents=True,exist_ok=True) artifacts=[];glyphs={} used_bg=sorted({memory[0x2000+y*32+x] for y in range(30) for x in range(32)}) used_sp={tile+dy for y,tile,attr,x in oam for dy in (0,1)} for base in (0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae,0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe,0xc0,0xc2,0xc4,0xc6,0xc8):used_sp.update((base,base+1)) # Include the shared heart cursor, rendered with the native menu sprite row. used_sp.update((0xf3,0xf2)) for base,used,label in [(4096,used_bg,'bg'),(0,sorted(used_sp),'sp')]: for tile in used: image=Image.new('RGBA',(8,8));image.putdata([canonical[v] for v in decode(patterns[base+tile*16:base+(tile+1)*16])]) path=bank/f'{label}_{tile:02x}.png';image.save(path);index=len(artifacts);glyphs[(label,tile)]=index artifacts.append({'file':path.name,'index':index,'artifact_id':f'title-{label}-{tile:02x}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()}) write_json(bank/'asset.json',{'schema_version':1,'asset_uuid':TITLE_UUID,'name':'NES title patterns','type':'glyph_bank','output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':'8x8'},'pipeline':{'palettes':[{'index':i,'palette':{'rgba8888':rgba(row)}} for i,row in enumerate(runtime_colors)]}},'preload':{'enabled':True},'artifacts':artifacts}) write_json(bank/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'tileset'}) def palette_at(x,y): attr=memory[0x23c0+(y//4)*8+x//4];return (attr>>(((y%4)//2)*4+((x%4)//2)*2))&3 def publish_scene(root,uuid,asset,tiles): register(root,uuid);path=ROOT/'assets'/root;path.mkdir(parents=True,exist_ok=True) write_json(path/'asset.json',{'schema_version':1,'asset_uuid':uuid,'name':root.split('/')[-1],'type':'scene_bank','output':{'format':'SCENE/tilemap_v1','codec':'NONE','pipeline':{}},'preload':{'enabled':True}}) empty={'active':False,'glyph_id':0,'palette_id':0,'flip_x':False,'flip_y':False} def layer(active,w,h,t):return {'active':active,'glyph_asset_id':asset,'tile_size':8,'parallax_factor_x':1.0,'parallax_factor_y':1.0,'width':w,'height':h,'tiles':t} write_json(path/'scene-bank.pack-request.json',{'schema_version':1,'format':'SCENE/tilemap_v1','version':1,'layers':[layer(True,32,30,tiles)]+[layer(False,1,1,[empty]) for _ in range(3)]}) for cycle in (0,1,4,5): tiles=[] for y in range(30): for x in range(32): palette=palette_at(x,y);palette=8+cycle if palette==1 else palette tiles.append({'active':True,'glyph_id':glyphs[('bg',memory[0x2000+y*32+x])],'palette_id':palette,'flip_x':False,'flip_y':False}) publish_scene(f'scenes/title_{cycle}',f'be91004{cycle}-f99b-44e3-bd00-48850f27f000',title_id,tiles) # Generate the full title image independently with its actual NES palettes/OAM. out=ROOT/'extracted/game_flow';out.mkdir(exist_ok=True,parents=True) canvas=Image.new('RGBA',(256,240)) for y in range(30): for x in range(32): tile=memory[0x2000+y*32+x];row=runtime_colors[palette_at(x,y)];im=Image.new('RGBA',(8,8));im.putdata([row[v] for v in decode(patterns[4096+tile*16:4096+(tile+1)*16])]);canvas.paste(im,(x*8,y*8)) def sprite(canvas,tile,x,y,attrs): im=Image.new('RGBA',(8,16));row=runtime_colors[4+(attrs&3)] im.putdata([row[v] for n in (tile,tile+1) for v in decode(patterns[n*16:(n+1)*16])]) if attrs&64:im=im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) if attrs&128:im=im.transpose(Image.Transpose.FLIP_TOP_BOTTOM) canvas.alpha_composite(im,(x,y+1)) initial_sprites=list(oam) for y in (184,202,218): offset=0 if y<185 else 8 if y<194 else 16 initial_sprites += [[y,tile+offset,0,x] for x,tile in zip((80,88,96,104),(0xb2,0xb4,0xb6,0xb8))] initial_sprites += [[168,tile,0,x] for x,tile in zip((80,88,96,104),(0xa2,0xa4,0xa6,0xa8))] # Lower OAM index wins over later sprites; compose back-to-front. for y,tile,attrs,x in reversed(initial_sprites):sprite(canvas,tile,x,y,attrs) canvas.save(out/'title.png');canvas.resize((768,720),Image.Resampling.NEAREST).save(out/'title@3x.png') # Native post-death text, limited to implemented CONTINUE / RETRY (SAVE omitted). menu_memory=bytearray(0x4000);menu_memory[0x2000:0x23c0]=bytes([36])*960 menu_record=transfer(record_offset(2),menu_memory) label_codes=[bytes([12,24,23,29,18,23,30,14]),bytes([27,14,29,27,34])] label_positions=[menu_memory.find(code,0x2000,0x23c0) for code in label_codes] assert all(address>=0x2000 for address in label_positions) # Preserve native label positions, but do not display SAVE or its caution box # while storage is outside this iteration. clean_menu=bytearray(0x4000);clean_menu[0x2000:0x23c0]=bytes([36])*960 for address,code in zip(label_positions,label_codes):clean_menu[address:address+len(code)]=code menu_memory=clean_menu selection_modes=p.index(bytes.fromhex('f30250273747030d00'),5*16384,6*16384)+6 cursor_data=list(p[selection_modes-6:selection_modes]) menu_rows_y=[(address-0x2000)//32 for address in label_positions] assert p[selection_modes+74:selection_modes+78]==bytes.fromhex('a9408529') menu_palette_offset=p.index(bytes.fromhex('3f00200f3000120f1627360f0c1c2c0f121c2c0f2927070f2227070f2627070f152730ff')) menu_rows=[list(p[menu_palette_offset+3+i*4:menu_palette_offset+7+i*4]) for i in range(8)] menu_rgb=dict(rgb);menu_rgb.update({0x0c:(0,64,88),0x1c:(0,136,136),0x2c:(88,248,216),0x12:(0,88,248),0x29:(56,184,0),0x26:(248,120,88),0x15:(164,0,164)}) menu_colors=[[(0,0,0,0) if j==0 and i>=4 else (*menu_rgb[c],255) for j,c in enumerate(row)] for i,row in enumerate(menu_rows)] mbank=ROOT/'assets/ui/continue';mbank.mkdir(parents=True,exist_ok=True);menu_id=register('ui/continue',MENU_UUID);marts=[];mids={} for label,base,used in [('bg',4096,sorted(set(menu_memory[0x2000:0x23c0]))),('sp',4096,[0xf3])]: for tile in used: image=Image.new('RGBA',(8,8));pattern_tile = tile - 1 if label == 'sp' else tile image.putdata([menu_colors[0][v] for v in decode(patterns[base+pattern_tile*16:base+(pattern_tile+1)*16])]);path=mbank/f'{label}_{tile:02x}.png';image.save(path);n=len(marts);mids[(label,tile)]=n marts.append({'file':path.name,'index':n,'artifact_id':f'continue-{label}-{tile:02x}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()}) write_json(mbank/'asset.json',{'schema_version':1,'asset_uuid':MENU_UUID,'name':'NES continue menu','type':'glyph_bank','output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':'8x8'},'pipeline':{'palettes':[{'index':i,'palette':{'rgba8888':rgba(row)}} for i,row in enumerate(menu_colors)]}},'preload':{'enabled':True},'artifacts':marts}) write_json(mbank/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'tileset'}) for flash in (0,1,2): tiles=[] for y in range(30): for x in range(32):tiles.append({'active':True,'glyph_id':mids[('bg',menu_memory[0x2000+y*32+x])],'palette_id':1 if (flash==1 and y==menu_rows_y[0]) or (flash==2 and y==menu_rows_y[1]) else 0,'flip_x':False,'flip_y':False}) publish_scene(f'scenes/continue_{flash}',f'be92000{flash}-f99b-44e3-bd00-48850f27f000',menu_id,tiles) menu_module=ROOT/'src/screens/continue_menu';menu_module.mkdir(parents=True,exist_ok=True) menu_lines=['// Generated from the verified ROM menu labels and cursor table.', 'declare struct ContinueData() {', f' fn cursor_glyph() -> int {{ return {mids[("sp",0xf3)]}; }}', f' fn cursor_x() -> int {{ return {cursor_data[2]}; }}', ' fn cursor_y(selection: int) -> int {', f' return if selection == 0 {{ {cursor_data[3]+1} }} else {{ {cursor_data[5]+1} }};', ' }','}',''] (menu_module/'graphics.generated.pbs').write_text('\n'.join(menu_lines)) # Generate native glyph map and OAM records for runtime authoring. module=ROOT/'src/screens/title';module.mkdir(parents=True,exist_ok=True) mapping=[glyphs.get(('sp',tile),0) for tile in range(256)] lines=['// Generated from verified title OAM and CHR patterns.', 'declare global title_glyphs: array = ['+', '.join(map(str,mapping))+'];', 'declare struct TitleData() {',' fn glyph(tile: int) -> int {', ' if tile < 0 || tile >= 256 { return 0; }', ' return title_glyphs[tile] else 0;',' }', ' fn draw_pair(tile: int, x: int, y: int, attr: int, priority: int) -> void {', ' let flip_x = attr % 128 >= 64;', ' let flip_y = attr >= 128;', ' let top = if flip_y { tile + 1 } else { tile };', ' let bottom = if flip_y { tile } else { tile + 1 };', ' Scene.emit_ui_sprite(this.glyph(top), 4 + attr % 4, x, y + 1, 8, flip_x, flip_y, priority);', ' Scene.emit_ui_sprite(this.glyph(bottom), 4 + attr % 4, x, y + 9, 8, flip_x, flip_y, priority);', ' }',' fn draw_static() -> void {'] lines += [f' this.draw_pair({tile}, {x}, {y}, {attrs}, {128-i});' for i,(y,tile,attrs,x) in enumerate(oam)] lines += [' }','}',''] (module/'graphics.generated.pbs').write_text('import { Scene } from @zelda1:scene;\n\n'+'\n'.join(lines)) write_json(out/'rom-data.json',{'rom_sha256':ROM_SHA256,'transfer_directory_prg_offset':table,'title':title_record,'palette_prg_offset':palette_offset,'native_palettes':palettes,'glow_colors':glow,'oam_prg_offset':oam_offset,'initial_oam':oam,'sprite_glyphs':{str(t):g for (l,t),g in glyphs.items() if l=='sp'},'continue':menu_record,'continue_cursor_glyph':mids[('sp',0xf3)],'continue_label_addresses':label_positions,'continue_cursor_data':cursor_data,'scope':'Title scene, native glow/waterfall/OAM and reduced CONTINUE/RETRY menu. Save slots, registration and save not in this iteration.'}) for item in registry['assets']: if item['root'] in ('scenes/title_2','scenes/title_3','scenes/title_6','scenes/title_7'): item['included_in_build']=False write_json(registry_path,registry) print(f'Title: {len(artifacts)} glyphs, 4 unique glow scenes; continue menu: {len(marts)} glyphs, 3 scenes') if __name__=='__main__': prepare() from prepare_save_ui import prepare as prepare_save_ui prepare_save_ui()