Files
WoW-Hybrid-gateway/ops/minimap_water125_resolve.py
2026-11-30 10:44:01 +02:00

111 lines
5.9 KiB
Python

#!/usr/bin/env python3
"""Choose water-only, Source-majority whole, or hold for live minimap tiles."""
import argparse
import itertools
import json
from pathlib import Path
import numpy as np
from booty_bay_minimap import opaque_bc1, replace_cells
from minimap_water125 import rgb_any, wet_cells, source_water_coloured, digest
def resolve(root):
survey=json.loads((root/'survey.json').read_text())
rows={(r['zone'],r['x'],r['y']):r for r in survey}
assets=json.loads((root/'candidate-assets.json').read_text())
by_path={r['path']:r for r in assets}
selected={key for key,row in rows.items() if row['path'] in by_path}
data={}
for key,row in rows.items():
native_path=root/'native'/row['path']
native=rgb_any(native_path.read_bytes())
source_raw=Path(row['source']['file']).read_bytes()
source=rgb_any(source_raw)
adt=root/'terrain'/'_unresolved'/f"FILE{row['adt']:08X}.dat"
if not adt.exists():
found=list((root/'terrain'/'world'/'maps'/row['zone']).glob(f"*_{row['x']}_{row['y']}.adt"))
if len(found)!=1:raise ValueError('missing live terrain '+str(key))
adt=found[0]
wet=np.repeat(np.repeat(wet_cells(adt.read_bytes()),4,axis=0),4,axis=1)
water=source_water_coloured(source,wet)
dry=np.abs(source.astype(np.int16)-native.astype(np.int16)).max(axis=2)[~wet]
majority=not len(dry) or float(np.mean(dry<=16))>=0.5
candidate=rgb_any(Path(by_path[row['path']]['file']).read_bytes()) if key in selected else native
data[key]=dict(native=native,source=source,water=water,candidate=candidate,
majority=majority,dry_match=float(np.mean(dry<=16)) if len(dry) else 1.0)
edges=[]
for key in rows:
zone,x,y=key
for side,other in [('east',(zone,x+1,y)),('south',(zone,x,y+1))]:
if other not in rows or not (key in selected or other in selected):continue
a,b=data[key],data[other]
take=(lambda x,y:(x[:,-1],y[:,0])) if side=='east' else (lambda x,y:(x[-1,:],y[0,:]))
wa,wb=take(a['water'],b['water']);mask=wa&wb
if not mask.any():continue
def delta(left,right):
la,rb=take(a[left],b[right])
return float(np.abs(la[mask].astype(np.int16)-rb[mask].astype(np.int16)).mean())
ceiling=max(delta('source','source'),delta('native','native'))+1.0
edges.append((key,other,side,int(mask.sum()),ceiling,
{(sa,sb):delta({'native':'native','water':'candidate','whole':'source'}[sa],
{'native':'native','water':'candidate','whole':'source'}[sb])
for sa in ('native','water','whole') for sb in ('native','water','whole')}))
pending=set(selected);components=[]
while pending:
start=pending.pop();component={start};queue=[start]
while queue:
z,x,y=queue.pop()
for peer in ((z,x+1,y),(z,x-1,y),(z,x,y+1),(z,x,y-1)):
if peer in pending:pending.remove(peer);component.add(peer);queue.append(peer)
components.append(sorted(component))
choices={}
for component in components:
local=[e for e in edges if e[0] in component or e[1] in component]
domains=[('native','water','whole') if data[k]['majority'] else ('native','water') for k in component]
best=None
for values in itertools.product(*domains):
candidate=dict(zip(component,values))
if any(e[5][(candidate.get(e[0],'native'),candidate.get(e[1],'native'))]>e[4]
for e in local):continue
cost=(sum(v=='native' for v in values),sum(v=='whole' for v in values))
if best is None or cost<best[0]:best=(cost,candidate)
if best is None:raise ValueError('no seam-safe state for '+str(component))
choices.update(best[1])
output=root/'resolved';output.mkdir(exist_ok=True)
final=[];states=[]
for key in sorted(selected):
row=rows[key];state=choices[key]
states.append(dict(zone=key[0],x=key[1],y=key[2],fdid=row['fdid'],state=state,
dry_match=round(data[key]['dry_match'],4)))
if state=='native':continue
parent=(root/'native'/row['path']).read_bytes()
if state=='water':raw=Path(by_path[row['path']]['file']).read_bytes()
else:
source=Path(row['source']['file']).read_bytes()
if rgb_any(source).shape!=(512,512,3):raise ValueError('Source dimensions')
if len(source) < len(parent):
raw=replace_cells(source,parent,np.zeros((128,128),dtype=bool))
else:
off=opaque_bc1(parent,512);so=opaque_bc1(source,512)
raw=parent[:off]+source[so:]
if not np.array_equal(rgb_any(raw),data[key]['source']):raise ValueError('whole Source mismatch')
dest=output/row['path'];dest.parent.mkdir(parents=True,exist_ok=True);dest.write_bytes(raw)
final.append(dict(path=row['path'],file_data_id=row['fdid'],file=str(dest),
before_sha256=digest(parent),after_sha256=digest(raw)))
(output/'candidate-assets.json').write_text(json.dumps(final,indent=2)+'\n')
(output/'states.json').write_text(json.dumps(states,indent=2)+'\n')
failures=[]
for a,b,side,pairs,ceiling,costs in edges:
after=costs[(choices.get(a,'native'),choices.get(b,'native'))]
if after>ceiling:failures.append((a,b,side,after-ceiling))
if failures:raise ValueError('resolved seam regression '+str(failures[:3]))
return dict(selected=len(selected),kept=len(final),whole=sum(s['state']=='whole' for s in states),
held=sum(s['state']=='native' for s in states),edges=len(edges),regressions=len(failures))
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--root',type=Path,required=True)
print(json.dumps(resolve(parser.parse_args().root)))