Files
WoW-Hybrid-gateway/ops/tirisfal_geometry_audit.py

111 lines
7.0 KiB
Python

#!/usr/bin/env python3
"""Read-only terrain/placement comparison; never authorizes a minimap from image differences."""
import argparse,collections,hashlib,json,math,re,struct
from pathlib import Path
from map_asset_preflight import adt_height_profile
def chunks(raw):
result={};at=0
while at<len(raw):
if at+8>len(raw):raise ValueError('Truncated chunk')
tag=raw[at:at+4][::-1].decode('ascii');size=struct.unpack_from('<I',raw,at+4)[0];at+=8
if at+size>len(raw):raise ValueError('Truncated body')
if tag!='MCNK' and tag in result:raise ValueError('Duplicate chunk '+tag)
result[tag]=raw[at:at+size];at+=size
return result
def placements(raw, native=False, file_names=None):
c=chunks(raw);out={}
for tag,size in [('MDDF',36),('MODF',64)]:
data=c.get(tag,b'')
if len(data)%size:raise ValueError('Placement size')
rows={}
for at in range(0,len(data),size):
row=data[at:at+size];name,uid,*transform=struct.unpack_from('<II6f',row)
if uid in rows or not all(math.isfinite(x) for x in transform):raise ValueError('Placement identity/transform')
# Source MODF has no scale field (native added it in the old padding).
scale=struct.unpack_from('<H',row,32)[0]/1024 if tag=='MDDF' else (struct.unpack_from('<H',row,62)[0]/1024 if native and struct.unpack_from('<H',row,56)[0]&4 else 1.0)
if native:
model=(file_names or {}).get(name)
else:
names=c.get('MMDX' if tag=='MDDF' else 'MWMO',b'');offsets=c.get('MMID' if tag=='MDDF' else 'MWID',b'')
if name*4+4>len(offsets):raise ValueError('Model index')
offset=struct.unpack_from('<I',offsets,name*4)[0];end=names.find(b'\0',offset)
if end<0:raise ValueError('Model path terminator')
model=names[offset:end].decode('ascii')
if model:model=model.lower().replace('\\','/').removesuffix('.mdx')+'.m2' if model.lower().endswith('.mdx') else model.lower().replace('\\','/')
rows[uid]={'transform':transform,'scale':scale,'raw_name':name,'model':model}
out[tag]=rows
return out
def compare(source,native,source_obj,native_obj,tile,tolerance=.001,file_names=None):
a=adt_height_profile(source,tile);b=adt_height_profile(native,tile)
deltas=[abs(x-y) for key in ['V9','V8'] for x,y in zip(a[key],b[key])]
holes=sum(a['cells'][k]['holes']!=b['cells'][k]['holes'] for k in a['cells'])
objects={};sa=placements(source_obj);sb=placements(native_obj,True,file_names)
for kind in sa:
x,y=sa[kind],sb[kind]
remaining=dict(y);unmatched=[];unknown=0;matched=0
for uid,row in x.items():
if row['model'] is None:unknown+=1;continue
candidates=[(other,value) for other,value in remaining.items() if value['model']==row['model'] and abs(row['scale']-value['scale'])<=tolerance and all(abs(i-j)<=tolerance for i,j in zip(row['transform'],value['transform']))]
if candidates:
del remaining[candidates[0][0]];matched+=1
else:unmatched.append(uid)
unknown+=sum(v['model'] is None for v in remaining.values())
objects[kind]={'source_unmatched':sorted(unmatched),'native_unmatched':sorted(remaining),'matched':matched,'unknown_models':unknown}
changed=max(deltas)>tolerance or holes>0 or any((v['source_unmatched'] or v['native_unmatched']) and not v['unknown_models'] for v in objects.values())
return {'terrain_vertices_changed':sum(d>tolerance for d in deltas),'max_height_delta':max(deltas),'hole_cells_changed':holes,'placements':objects,'geometry_changed':changed,'model_identity_compared':not any(v['unknown_models'] for v in objects.values()),'scope':'Heights/holes and named-model transforms; model-path identity does not prove mesh equality'}
def run(root):
variants=json.loads((root/'source-variants.json').read_text())['rows'];bytile=collections.defaultdict(list)
for r in variants:bytile[r['x'],r['y']].append(r)
wanted=set()
for obj in (root/'native').rglob('*_obj0.adt'):
for tag,size in [('MDDF',36),('MODF',64)]:
data=chunks(obj.read_bytes()).get(tag,b'')
wanted.update(struct.unpack_from('<I',data,i)[0] for i in range(0,len(data),size))
file_names={}
for line in Path('/mnt/Games/@project/listfiles/community-listfile.csv').open():
ident,_,name=line.strip().partition(';')
if ident.isdecimal() and int(ident) in wanted:file_names[int(ident)]=name
# Retain every archive comparison; selection of a loaded source version is separate.
findings=[]
for tile,rows in sorted(bytile.items()):
x,y=tile;base=root/'native/world/maps/azeroth';native=(base/f'azeroth_{x}_{y}.adt').read_bytes();obj=(base/f'azeroth_{x}_{y}_obj0.adt').read_bytes()
for r in rows:
source=Path(r['file']).read_bytes()
if hashlib.sha256(source).hexdigest()!=r['sha256']:raise ValueError('Source input changed')
findings.append({'tile':list(tile),'archive':r['archive'],'source_sha256':r['sha256'],'native_sha256':hashlib.sha256(native).hexdigest(),'native_obj_sha256':hashlib.sha256(obj).hexdigest(),**compare(source,native,source,obj,tile,file_names=file_names)})
(root/'geometry-variants.json').write_text(json.dumps(findings,indent=2)+'\n')
priority_file=root/'source-priority.json'
if priority_file.exists():
priority=json.loads(priority_file.read_text());selected={}
if not isinstance(priority,list) or len(set(priority))!=len(priority):raise ValueError('Explicit unique archive priority required')
for row in findings:
if row['archive'] not in priority:raise ValueError('Unranked source archive')
key=tuple(row['tile'])
if key not in selected or priority.index(row['archive'])<priority.index(selected[key]['archive']):selected[key]=row
(root/'selected-geometry.json').write_text(json.dumps({'priority_high_to_low':priority,'rows':list(selected.values())},indent=2)+'\n')
print('Compared',len(findings),'variants;',sum(r['geometry_changed'] for r in findings),'with terrain/placement differences')
def group_geometry(raw):
"""Order-independent triangle geometry; textures and vertex normals are separate."""
c=chunks(raw);body=c['MOGP']
if len(body)<68:raise ValueError('Short group header')
nested=chunks(body[68:]);vertices=nested.get('MOVT',b'');indices=nested.get('MOVI',b'')
if len(vertices)%12 or len(indices)%6:raise ValueError('Invalid mesh strides')
points=list(struct.iter_unpack('<3f',vertices));triangles=[]
if not all(math.isfinite(v) for point in points for v in point):raise ValueError('Nonfinite vertex')
for tri in struct.iter_unpack('<3H',indices):
if any(i>=len(points) for i in tri):raise ValueError('Triangle outside vertex array')
triangles.append(tuple(sorted(tuple(round(v,4) for v in points[i]) for i in tri)))
return sorted(triangles)
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('root',type=Path);run(p.parse_args().root)