149 lines
9.7 KiB
Python
149 lines
9.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Classify addon/native disagreements against explicit current Source inputs."""
|
|
import argparse,collections,hashlib,json,struct
|
|
from pathlib import Path
|
|
|
|
def dbc(path,fields):
|
|
raw=path.read_bytes()
|
|
if len(raw)<20 or raw[:4]!=b'WDBC':raise ValueError('WDBC header required')
|
|
count,actual,size,string_size=struct.unpack_from('<4I',raw,4)
|
|
if actual!=fields or size!=4*fields or count>100000 or string_size>16777216 or len(raw)!=20+count*size+string_size:raise ValueError('Source DBC shape/bounds')
|
|
rows={}
|
|
for i in range(count):
|
|
row=struct.unpack_from('<'+'I'*fields,raw,20+i*size)
|
|
if row[0] in rows:raise ValueError('Duplicate Source row')
|
|
rows[row[0]]=row
|
|
strings=raw[20+count*size:]
|
|
def string(offset):
|
|
if not 0<=offset<len(strings):raise ValueError('Source string offset')
|
|
end=strings.find(b'\0',offset)
|
|
if end<0:raise ValueError('Source string terminator')
|
|
return strings[offset:end].decode('utf8')
|
|
return rows,string
|
|
|
|
def classify(addon,native,source):
|
|
if addon==source and native==source:return 'both-correct'
|
|
if addon==source:return 'addon-correct'
|
|
if native==source:return 'DB2-correct'
|
|
return 'both-wrong'
|
|
|
|
def source_inputs(root):
|
|
columns=json.loads((root/'item-columns.json').read_text());items={}
|
|
for line in (root/'source-items.tsv').read_text().splitlines():
|
|
values=line.split('\t')
|
|
if len(values)!=len(columns):raise ValueError('Source SQL columns')
|
|
row=dict(zip(columns,map(int,values)))
|
|
if row['entry'] in items:raise ValueError('Duplicate Source item')
|
|
items[row['entry']]=row
|
|
variants=json.loads((root/'source-dbc-variants.json').read_text())['rows']
|
|
def effective(name,fields):
|
|
chosen=select_variant([v for v in variants if v['member'].replace('\\','/').split('/')[-1]==name])
|
|
path=Path(chosen['file'])
|
|
if hashlib.sha256(path.read_bytes()).hexdigest()!=chosen['sha256']:raise ValueError('Source DBC changed')
|
|
return dbc(path,fields)
|
|
displays,text=effective('ItemDisplayInfo.dbc',23)
|
|
sets,_=effective('ItemSet.dbc',45)
|
|
return items,displays,text,sets
|
|
|
|
def run(root):
|
|
items,displays,text,sets=source_inputs(root);rows=[];icons=[];counts=collections.defaultdict(collections.Counter)
|
|
for r in json.loads((root/'selected-addon-differences.json').read_text()):
|
|
group=r['group'];ident=r['id'];row=dict(r);source=None
|
|
if group=='icons':
|
|
item=items.get(ident);display=displays.get(item['display_id']) if item else None
|
|
if display:
|
|
token=text(display[5]).replace('\\','/').lower()
|
|
if not token.startswith('interface/icons/'):token='interface/icons/'+token
|
|
if not token.endswith('.blp'):token+='.blp'
|
|
if '..' in token or token.count('/')!=2:raise ValueError('Bounded icon path')
|
|
icons.append({'id':ident,'display_id':item['display_id'],'member':token})
|
|
else:row['classification_source']='source-unresolved';rows.append(row)
|
|
continue
|
|
if group=='setSpells' and ident in sets:source=sorted(set(sets[ident][27:35])-{0})
|
|
elif group=='itemSpells' and ident in items:source=sorted({items[ident]['spellid_'+str(i)] for i in range(1,6)}-{0})
|
|
elif group=='itemSets' and ident in items:source=items[ident]['set_id']
|
|
elif group=='armor' and ident in items:source={k:items[ident][k] for k in ['armor','block','subclass']}
|
|
row['source']=source;row['classification_source']='source-unresolved' if source is None else classify(r['addon'],r['native'],source)
|
|
counts[group][row['classification_source']]+=1;rows.append(row)
|
|
(root/'source-icon-requests.json').write_text(json.dumps(icons,indent=2)+'\n')
|
|
(root/'non-icon-authority.json').write_text(json.dumps(rows,indent=2)+'\n')
|
|
print('Source classifications',json.dumps(counts,sort_keys=True),'icon requests',len(icons))
|
|
|
|
|
|
def image_mips(raw):
|
|
"""Canonical decoded RGBA for every authored mip; encoding/header bytes are separate."""
|
|
import io
|
|
from PIL import Image
|
|
if len(raw)>8388608 or raw[:4] not in [b'BLP1',b'BLP2']:raise ValueError('Bounded BLP required')
|
|
base=20 if raw[:4]==b'BLP2' else 28
|
|
if len(raw)<base+128:raise ValueError('BLP header')
|
|
width,height=struct.unpack_from('<II',raw,12)
|
|
if not 1<=width<=4096 or not 1<=height<=4096:raise ValueError('BLP dimensions')
|
|
offsets=struct.unpack_from('<16I',raw,base);sizes=struct.unpack_from('<16I',raw,base+64)
|
|
level_limit=max(width,height).bit_length();unused=[(i,offsets[i],sizes[i]) for i in range(level_limit,16) if offsets[i] or sizes[i]]
|
|
# Four Source BC1 icons have this exact exporter underflow in unused slots.
|
|
# None of the authored mip extents/pixels are repaired or inferred here.
|
|
known_unused=(raw[:4]==b'BLP2' and width==height==64 and tuple(raw[8:12])==(2,1,0,1) and unused==[(7,len(raw),(-len(raw))&0xffffffff),(15,0,sizes[0])])
|
|
if unused and not known_unused:raise ValueError('Unexpected unused mip directory entries')
|
|
digest=hashlib.sha256();levels=0;ended=False
|
|
for i,(offset,size) in enumerate(zip(offsets[:level_limit],sizes[:level_limit])):
|
|
if not offset and not size:ended=True;continue
|
|
if ended or not offset or not size or offset+size>len(raw):raise ValueError('BLP mip extent/sequence')
|
|
w,h=max(1,width>>i),max(1,height>>i)
|
|
if raw[:4]==b'BLP2' and raw[8]==3:
|
|
if size!=w*h*4:raise ValueError('BGRA mip size')
|
|
image=Image.frombytes('RGBA',(w,h),raw[offset:offset+size],'raw','BGRA')
|
|
else:
|
|
copy=bytearray(raw);struct.pack_into('<II',copy,12,w,h);struct.pack_into('<16I',copy,base,offset,*([0]*15));struct.pack_into('<16I',copy,base+64,size,*([0]*15))
|
|
image=Image.open(io.BytesIO(copy));image.load();image=image.convert('RGBA')
|
|
if image.size!=(w,h):raise ValueError('Decoded mip dimensions')
|
|
digest.update(struct.pack('<II',w,h));digest.update(image.tobytes());levels+=1
|
|
if not levels:raise ValueError('Missing mip pixels')
|
|
return {'sha256':digest.hexdigest(),'width':width,'height':height,'mips':levels,'unused_directory_normalization_required':bool(unused)}
|
|
|
|
def icon_authority(root):
|
|
variants=json.loads((root/'source-icon-variants.json').read_text());requests={r['id']:r for r in json.loads((root/'source-icon-requests.json').read_text())};native_paths=json.loads((root/'native-icon-paths.json').read_text());by_member=collections.defaultdict(list)
|
|
for row in variants:by_member[row['member']].append(row)
|
|
cache={}
|
|
def decoded(raw):
|
|
key=hashlib.sha256(raw).hexdigest()
|
|
if key not in cache:cache[key]=image_mips(raw)
|
|
return cache[key]
|
|
results=[];counts=collections.Counter();raw_counts=collections.Counter()
|
|
for r in json.loads((root/'selected-addon-differences.json').read_text()):
|
|
if r['group']!='icons':continue
|
|
row=dict(r);request=requests.get(r['id']);matches=by_member.get(request['member'],[]) if request else []
|
|
try:chosen=select_variant(matches)
|
|
except ValueError:row['classification_source']='source-unresolved';results.append(row);counts[row['classification_source']]+=1;continue
|
|
raw=Path(chosen['file']).read_bytes()
|
|
if hashlib.sha256(raw).hexdigest()!=chosen['sha256']:raise ValueError('Source icon changed')
|
|
addon_path=None
|
|
if isinstance(r['addon'],dict):addon_path=r['addon'].get('loose_path')
|
|
elif isinstance(r['addon'],str):
|
|
if not r['addon'].startswith('interface/icons/') or r['addon'].count('/')!=2:raise ValueError('Addon icon path')
|
|
addon_path=Path('/mnt/Games/OctoWoW-LOCAL-Client/_classic_beta_/Interface/Icons')/Path(r['addon']).name
|
|
addon=Path(addon_path).read_bytes() if addon_path and Path(addon_path).exists() else None
|
|
native=(root/'native-icons'/native_paths[str(r['native']['file_data_id'])]).read_bytes() if r['native'] else None
|
|
for key,value in [('addon',addon),('native',native)]:
|
|
if value is not None and isinstance(r[key],dict) and hashlib.md5(value).hexdigest()!=r[key]['content_key']:raise ValueError('Earlier addon/native asset pin changed')
|
|
row['source']={'member':requests[r['id']]['member'],'archive':chosen['archive'],'sha256':chosen['sha256'],'md5':chosen['md5']}
|
|
row['classification_source_blob']=classify(addon,native,raw);raw_counts[row['classification_source_blob']]+=1
|
|
try:
|
|
source_pixels=decoded(raw);a=decoded(addon) if addon else None;b=decoded(native) if native else None
|
|
row['classification_source']=classify(a['sha256'] if a else None,b['sha256'] if b else None,source_pixels['sha256']);row['decoded_mips']={'source':source_pixels,'addon':a,'native':b}
|
|
except (ValueError,OSError,NotImplementedError) as e:row['classification_source']='decode-unresolved';row['error']=str(e)
|
|
counts[row['classification_source']]+=1;results.append(row)
|
|
(root/'icon-authority.json').write_text(json.dumps(results,indent=2)+'\n');print('Icon decoded-mip classifications',dict(counts),'exact blobs',dict(raw_counts))
|
|
|
|
|
|
def select_variant(matches):
|
|
priority=['patch-o.mpq','patch-5.mpq','patch-4.mpq','patch-3.mpq','patch-2.mpq','patch-1.mpq','patch.mpq']
|
|
patched=[v for v in matches if v['archive'].lower() in priority]
|
|
if patched:return min(patched,key=lambda v:priority.index(v['archive'].lower()))
|
|
if matches and len({v['sha256'] for v in matches})==1:return matches[0]
|
|
raise ValueError('Missing or ambiguous Source asset')
|
|
|
|
if __name__=='__main__':
|
|
p=argparse.ArgumentParser(description=__doc__);p.add_argument('root',type=Path);p.add_argument('--icons',action='store_true');a=p.parse_args();run(a.root)
|
|
if a.icons:icon_authority(a.root)
|