#!/usr/bin/env python3 """Extract drop tables, native item descriptors and combat/HUD patterns.""" import hashlib,json,uuid from PIL import Image from extract_graphics import ROOT,decode from extract_start_room import RGB,write_json from nes_object_graphics import P,item def prepare(): out=ROOT/'extracted/combat';out.mkdir(exist_ok=True,parents=True) group_sig=bytes.fromhex('5d14151b1c1d1707080e040f2321220d1013282a2716090a030112060b2430') groups=P.index(group_sig);rate=groups+len(group_sig)+4;assert list(P[rate:rate+4])==[80,152,104,104] table=list(P[rate+4:rate+44]);assert table[:10]==[34,24,34,24,35,24,34,34,24,24] no_drop=list(P[groups:groups+7]);sets=[list(P[groups+7:groups+13]),list(P[groups+13:groups+22]),list(P[groups+22:groups+31])] spawn_sig=bytes.fromhex('55b578987a9a6cac8d8263a3759577975abaa375b59687997abaac6355957688795a9a6c') spawn_at=P.index(spawn_sig,5*16384,6*16384) spawn_lines=['// Native spawn spots for right, left, down, up entries.', 'declare global spawn_spots: array = ['+', '.join(map(str,P[spawn_at:spawn_at+36]))+'];', 'declare struct SpawnData() {',' fn cell(direction: int, cycle: int) -> int {',' let row=if direction==1 { 0 } else if direction==2 { 1 } else if direction==4 { 2 } else { 3 };',' return spawn_spots[row*9+cycle] else 0;',' }','}',''] (ROOT/'src/enemies/octorok/spawns.generated.pbs').write_text('\n'.join(spawn_lines)) # Explicitly derive group membership and cycle results from ROM bytes. lines=['// Generated native monster drop data.','declare global drop_table: array = ['+', '.join(map(str,table))+'];','declare global drop_rates: array = ['+', '.join(map(str,P[rate:rate+4]))+'];','declare struct DropData() {',' fn group(monster: int) -> int {',' if '+' || '.join(f'monster=={n}' for n in no_drop)+' { return -1; }'] for i,values in enumerate(sets):lines.append(' if '+' || '.join(f'monster=={n}' for n in values)+f' {{ return {i}; }}') lines+=[' return 3;',' }',' fn item(group: int, cycle: int) -> int { return drop_table[group*10+cycle] else -1; }',' fn rate(group: int) -> int { return drop_rates[group] else 0; }','}',''] (ROOT/'src/loot/data.generated.pbs').write_text('\n'.join(lines)) patterns=bytearray(8192) for offset,length,address in [(32895,1792,0),(19892,2304,1792),(53595,1824,2272),(34687,1792,4096),(51515,2080,5888),(36479,224,7968)]:patterns[address:address+length]=P[offset:offset+length] rows=[list(P[103187+i*4:103191+i*4]) for i in range(4)]+[list(P[103171:103175])] rgb=dict(RGB);rgb.update({2:(0,0,188),34:(104,136,252),41:(56,184,0),12:(0,64,88),28:(0,136,136),44:(88,248,216)}) colors=[[(0,0,0,0) if i==0 and row_id<4 else (*rgb[c],255) for i,c in enumerate(row)] for row_id,row in enumerate(rows)] specs={0:item(1),15:item(28),24:item(22),34:item(25),35:item(20),135:item(20,1),200:item(34),201:item(34,1),202:item(35,2)} assert specs[34]['tiles'][0]==243 and specs[201]['tiles']==[130,132] keys=set() for info in specs.values(): for tile in info['tiles'][:info['sides']]:keys.update(((tile&1)*256+(tile&254),(tile&1)*256+(tile&254)+1)) digit_codes=list(range(10))+[33,36];keys.update(256+n for n in digit_codes) root='characters/combat';folder=ROOT/'assets'/root;folder.mkdir(exist_ok=True,parents=True);u=str(uuid.uuid5(uuid.NAMESPACE_URL,'zelda1/'+root));artifacts=[];glyphs={} for key in sorted(keys): im=Image.new('RGBA',(8,8));im.putdata([colors[0][v] for v in decode(patterns[key*16:(key+1)*16])]);path=folder/f'ppu_{key*16:04x}.png';im.save(path);index=len(artifacts);glyphs[key]=index artifacts.append({'file':path.name,'index':index,'artifact_id':f'combat-ppu-{key*16:04x}','fingerprint':hashlib.sha256(path.read_bytes()).hexdigest()}) write_json(folder/'asset.json',{'schema_version':1,'asset_uuid':u,'name':'NES combat and counter patterns','type':'glyph_bank','preload':{'enabled':True},'output':{'format':'GLYPH/indexed_v1','codec':'NONE','metadata':{'tile_size':'8x8'},'pipeline':{'palettes':[{'index':i,'palette':{'rgba8888':[int.from_bytes(bytes(c),'big',signed=True) for c in row]}} for i,row in enumerate(colors)]}},'artifacts':artifacts}) write_json(folder/'studio.asset.json',{'schema_version':1,'glyph_bank_specialization':'sprites'}) registry_path=ROOT/'assets/.prometeu/index.json';reg=json.loads(registry_path.read_text());matches=[a for a in reg['assets'] if a['root']==root] if matches:assert len(matches)==1 and matches[0]['asset_uuid']==u else: n=reg['next_asset_id'];reg['next_asset_id']+=1;reg['assets'].append({'asset_id':n,'asset_uuid':u,'root':root,'included_in_build':True});write_json(registry_path,reg) top=[glyphs.get((t&1)*256+(t&254),0) for t in range(256)];bottom=[glyphs.get((t&1)*256+(t&254)+1,0) for t in range(256)] lines=['// Generated PPU mappings; odd 8x16 sprite IDs select the background table.', 'declare global combat_top: array = ['+', '.join(map(str,top))+'];','declare global combat_bottom: array = ['+', '.join(map(str,bottom))+'];','declare struct CombatData() {',' fn top(tile: int) -> int { return combat_top[tile] else 0; }',' fn bottom(tile: int) -> int { return combat_bottom[tile] else 0; }',' fn digit(code: int) -> int {'] for code in digit_codes:lines.append(f' if code=={code} {{ return {glyphs[256+code]}; }}') lines+=[' return 0;',' }',' fn drop_tile(item: int, phase: int) -> int {'] for n in (0,15,24,34):lines.append(f' if item=={n} {{ return {specs[n]["tiles"][0]}; }}') lines+=[' return if phase==0 { 80 } else { 82 };',' }','}',''];(ROOT/'src/combat_graphics/data.generated.pbs').write_text('\n'.join(lines)) write_json(out/'rom-data.json',{'rom_sha256':hashlib.sha256((ROOT/'.tmp/zelda-1.nes').read_bytes()).hexdigest(),'drop_tables_prg':groups,'rates':list(P[rate:rate+4]),'groups':sets,'no_drop':no_drop,'items':table,'item_descriptors':specs,'glyph_keys':glyphs,'native_palettes':rows,'bounce_table_prg':P.index(bytes.fromhex('01fffe02ffff')),'scope':'Native red Octorok combat, consumable drops, sword beam and HUD counters; no audio.'}) print('Published combat bank:',len(artifacts),'8x8 patterns; native drop tables and item descriptors') if __name__=='__main__':prepare()