#!/usr/bin/env python3 """Native room $66 shop $78, keeping actors/text/prices outside the terrain.""" import json,hashlib from PIL import Image from extract_graphics import ROOT,decode from extract_start_room import RGB,write_json from nes_object_graphics import P,descriptor,item from validate_octorok_graphics import native_image def metadata(source_room=102,source_stage=3,stage=11): attrs=list(P[99328+i*128+source_room] for i in range(6));index=((attrs[1]&252)-64)//4;assert index in (13,14) at=99328+512+index*3;wares=list(P[at:at+3]);prices=list(P[at+60:at+63]);assert ([v&63 for v in wares],prices)==(([28,25,6],[160,100,60]) if index==14 else ([28,0,8],[130,20,80])) selectors=P.index(bytes.fromhex('406042420406480a4c0ed0d2d2dcdc dede626262'.replace(' ','')));select=P[selectors+index];flags=(select&192)>>6|(wares[0]&192)|((wares[2]&192)>>4)|((wares[1]&192)>>2);assert flags==15 ptr=16384+int.from_bytes(P[16384+(select&63):16386+(select&63)],'little')-32768 return {'source_stage':source_stage,'source_room':source_room,'stage':stage,'object_type':106+index,'cave_index':index,'entry_x':attrs[0]&240,'entry_y':(attrs[5]&7)*16+77,'wares':[v&63 for v in wares],'raw_wares':wares,'prices':prices,'ware_prg_offset':at,'text_selector':select&63,'text_prg_offset':ptr,'flags':flags} def prepare_one(supply=False): m=metadata(68,15,16) if supply else metadata();prefix='supply-shop-' if supply else 'shop-';file_prefix='supply_shop_' if supply else 'shop_';out=ROOT/('extracted/supply_shop' if supply else 'extracted/shop');out.mkdir(parents=True,exist_ok=True);folder=ROOT/'assets/tilesets/cave_start';path=folder/'asset.json';doc=json.loads(path.read_text());arts=[a for a in doc['artifacts'] if not a['artifact_id'].startswith(prefix if supply else ('shop-','supply-shop-'))];start=max(a['index'] for a in arts)+1;assert len(arts)==start colors=[tuple((c&0xffffffff)>>s&255 for s in (24,16,8,0)) for c in doc['output']['pipeline']['palettes'][0]['palette']['rgba8888']];parts=[] def add(im,x,y,kind): for c in sorted(set(im.getdata())): if c not in colors:colors.append(c) assert len(colors)<=16 for yy in range(0,im.height,8): for xx in range(0,im.width,8): crop=im.crop((xx,yy,xx+8,yy+8));p=folder/f'{file_prefix}{len(arts)-start:03d}.png';crop.save(p);i=len(arts);arts.append({'file':p.name,'index':i,'artifact_id':f'{prefix}{i-start}','fingerprint':hashlib.sha256(p.read_bytes()).hexdigest()});parts.append([kind,x+xx,y+yy,i]) patterns=bytearray(8192) for off,length,dest in [(32895,1792,0),(19892,2304,1792),(53595,1824,2272),(34687,1792,4096),(51515,2080,5888),(36479,224,7968)]:patterns[dest:dest+length]=P[off:off+length] row=json.loads((ROOT/'extracted/cave/start/room.json').read_text())['nes_palettes'][2] def font(t): im=Image.new('RGBA',(8,8));im.putdata([(0,0,0,0) if v==0 else (*RGB[row[v]],255) for v in decode(patterns[4096+t*16:4096+(t+1)*16])]);return im info=descriptor(m['object_type'],mirrored=True,object_attribute=129);add(native_image(info),120,129,0) address=0x21a4;cursor=m['text_prg_offset'];text=[] while True: v=P[cursor];cursor+=1;t=v&63;x=(address-8192)%32*8;y=(address-8192)//32*8 if t!=37:add(font(t),x,y,1);text.append({'tile':t,'x':x,'y':y}) address+=1;control=v&192 if control==192:break if control:address=0x21c4 if control==128 else 0x21e4 # Native price transfer $22C8: X and 3 fields, each 4 characters wide. add(font(33),64,176,2) for i,price in enumerate(m['prices']): digits=f'{price:3d}' for j,c in enumerate(digits): if c!=' ':add(font(int(c)),80+i*32+j*8,176,2) doc['artifacts']=arts;doc['output']['pipeline']['palettes'][0]['palette']['rgba8888']=[int.from_bytes(bytes(c),'big',signed=True) for c in colors];write_json(path,doc) module=ROOT/('src/stages/cave_supply_shop' if supply else 'src/stages/cave_shop');module.mkdir(parents=True,exist_ok=True) flat=[v for row in parts for v in row] code='// Generated merchant, message, price transfer and ROM wares.\nimport { Scene } from @zelda1:scene;\n' code+='declare global shop_parts: array = ['+','.join(map(str,flat))+'];\n' code+='declare global shop_items: array = ['+','.join(map(str,m['wares']))+'];\n' code+='declare global shop_prices: array = ['+','.join(map(str,m['prices']))+'];\n' code+='declare struct ShopArt() {\n fn item(i: int) -> int { return shop_items[i] else -1; }\n fn price(i: int) -> int { return shop_prices[i] else 0; }\n fn draw(visible: bool,bought: bool,offset: int) -> void {\n' code+=f' for i: int from 0 until {len(parts)} {{\n' code+=' let kind=shop_parts[i*4] else 0;\n if kind==2 || (kind==0 && visible) || (kind==1 && !bought) { let x=shop_parts[i*4+1] else 0; let y=shop_parts[i*4+2] else 0; let glyph=shop_parts[i*4+3] else 0; Scene.emit_sprite(glyph,0,x,y+offset,3,0); }\n }\n }\n}\n' if supply:code=code.replace('ShopArt','SupplyShopArt') (module/'art.generated.pbs').write_text(code);source=(ROOT/'src/stages/cave_start/room.generated.pbs').read_text().replace('CaveData','SupplyShopData' if supply else 'ShopCaveData').replace('terrain','shop_terrain');(module/'room.generated.pbs').write_text(source) ref=Image.open(ROOT/'extracted/cave/start/room_taken.png').convert('RGBA') for kind,x,y,g in parts:ref.alpha_composite(Image.open(folder/next(a['file'] for a in arts if a['index']==g)).convert('RGBA'),(x,y)) # Exact native item palettes: shield 0, key 2, blue candle 1; price rupee flashes. slots_at=P.index(bytes.fromhex('01000000060504040202030d090c1b1c'));desc_at=P.index(bytes.fromhex('14212223010121222122010101010115'));attrs_at=P.index(bytes.fromhex('ff01ff00000202000100020000020201')) slots=[P[slots_at+ware] for ware in m['wares']];palettes=[(P[attrs_at+slot]+(P[desc_at+ware]%16 if slot in (0,2,4,7,11) else 0))%4 for ware,slot in zip(m['wares'],slots)] assert palettes==([0,1,0] if supply else [0,2,1]) m['item_palette_sources']={'slots_prg':slots_at,'descriptors_prg':desc_at,'attributes_prg':attrs_at} for i,(slot,pal) in enumerate(zip(slots,palettes)): spec=item(slot,attribute=pal);ref.alpha_composite(native_image(spec),(88+i*32,153)) ref.alpha_composite(native_image(item(22,attribute=1)),(48,172));ref.save(out/'shop_available.png') m.update(parts=parts,text_tiles=text,keeper_descriptor=info,first_glyph=start,colors=len(colors),item_slots=slots,item_palettes=palettes);write_json(out/'rom-data.json',m) print('Native shop',hex(m['source_room']),m['prices'],'; appended',len(parts),'glyphs; scene slots unchanged') def prepare(): prepare_one();prepare_one(True) if __name__=='__main__':prepare()