Files
WoW-Hybrid-gateway/ops/item_appearance_preflight.py
2026-11-23 03:28:32 +02:00

1000 lines
80 KiB
Python

#!/usr/bin/env python3
"""Bulk source/target appearance dependencies in the existing item pipeline.
Read-only preflight, never an installable package. Same-ID rows and equal source
name tokens do not prove matching geometry, textures, or destination behavior.
"""
import argparse
from collections import Counter, defaultdict
import hashlib
import json
import math
import re
from pathlib import Path
import struct
from item_icon_preflight import observed_item_display, read_observed_inventory, listfile_index, MAX_LISTFILE_BYTES
from item_package_preflight import read_public_json, read_compatibility_package, bounded_digest, MAX_COMPATIBILITY_PACKAGE_JSON_BYTES
from turtle_data import inventory_item_snapshot, item_display_composition, _canonical
ROOT = Path(__file__).resolve().parents[1]
TARGET_TABLES = ('ItemModifiedAppearance', 'ItemAppearance', 'ItemDisplayInfo',
'ItemDisplayInfoMaterialRes', 'ModelFileData', 'TextureFileData',
'ComponentModelFileData', 'ComponentTextureFileData')
MODIFIED_TABLE=0xe491ac55
MODIFIED_LAYOUT=0x03a6c979
MODIFIED_SCHEMA=(('ID','int',32,False,1),('ItemID','int',32,False,1),
('ItemAppearanceModifierID','int',32,False,1),('ItemAppearanceID','int',32,False,1),
('OrderIndex','int',32,False,1),('TransmogSourceTypeEnum','int',8,True,1),('Flags','int',32,False,1))
APPEARANCE_TABLE=0x42261b89
APPEARANCE_LAYOUT=0x481c4281
APPEARANCE_SCHEMA=(('DisplayType','int',8,False,1),('ItemDisplayInfoID','int',32,False,1),
('DefaultIconFileDataID','int',32,False,1),('UiOrder','int',32,False,1),('TransmogPlayerConditionID','int',32,False,1))
VISIBLE_ARMOR_SLOTS=frozenset((1,3,4,5,6,7,8,9,10,14,16,19,20,23))
def native_weapon_parent_candidates(source,dbc,target,package_rows,names):
"""Resolve exact weapon model/texture references, never similar names.
Source path construction follows WoWee readItemDisplayArt/weapon loading.
Model format and effective source bytes are NOT declared equivalent: this
is deliberate reuse of already-supported native geometry/materials.
"""
displays=index(target['ItemDisplayInfo']);models=resources(index(target['ModelFileData']),'ModelResourcesID');textures=resources(index(target['TextureFileData']),'MaterialResourcesID')
geometry_types=defaultdict(set)
for parent in target['ItemAppearance']:
display=displays.get(parent['ItemDisplayInfoID'])
if display and not parent['TransmogPlayerConditionID']:
geometry_types[tuple(display['ModelResourcesID'])].add(parent['DisplayType'])
basics={r['id']:r['record']for r in package_rows if r['table_name']=='Item'and r.get('record_status','valid')=='valid'}
candidates={};blocked=[]
for record in source['records']:
item=record['raw_fields'];ident=item['entry']
if item['class']!=2 or ident not in basics:continue
raw=dbc.by_id.get(item['display_id']);display=displays.get(item['display_id'])
try:
if raw is None or display is None:raise ValueError('source-or-native-display-missing')
comp=item_display_composition(dbc,raw)
if any(comp['GeosetGroup']+comp['Flags']+comp['HelmetGeosetVisID'])or any(comp['Texture'])or raw[10]or raw[22]:raise ValueError('nontrivial-source-geoset-layer-or-visual')
if any(display.get(k,0)for k in('Flags','GeosetGroupOverride','ItemVisual','ParticleColorID','ItemRangedDisplayInfoID','StateSpellVisualKitID','SheathedSpellVisualKitID','UnsheathedSpellVisualKitID'))or any(display['GeosetGroup']+display['AttachmentGeosetGroup']+display['HelmetGeosetVis']+display['ModelType']):raise ValueError('nontrivial-native-geoset-or-visual')
types=geometry_types.get(tuple(display['ModelResourcesID']),set())
if len(types)!=1:raise ValueError('missing-or-ambiguous-native-geometry-display-type')
refs=[]
for slot in range(2):
model=comp['ModelName'][slot];texture=comp['ModelTexture'][slot]
mr=display['ModelResourcesID'][slot];tr=display['ModelMaterialResourcesID'][slot]
if not model and not texture and not mr and not tr:continue
if not re.fullmatch(r'[A-Za-z0-9_-]+\.(?:mdx|MDX|m2|M2)',model)or not re.fullmatch(r'[A-Za-z0-9_-]+',texture):raise ValueError('unreviewed-source-weapon-path-token')
mf=models.get(mr,[]);tf=textures.get(tr,[])
expected_model='item/objectcomponents/weapon/'+model.rsplit('.',1)[0].lower()+'.m2';expected_texture='item/objectcomponents/weapon/'+texture.lower()+'.blp'
if len(mf)!=1 or len(tf)!=1 or names.get(mf[0])!=[expected_model]or names.get(tf[0])!=[expected_texture]:raise ValueError('native-model-or-material-reference-differs')
refs.append(dict(slot=slot,model_file_id=mf[0],texture_file_id=tf[0],model_path=expected_model,texture_path=expected_texture))
if not refs:raise ValueError('empty-native-weapon-resources')
icon=basics[ident]['IconFileDataID']
if type(icon)is not int or not 0<icon<0x80000000:raise ValueError('positive-published-item-icon-required')
candidates[ident]=dict(item_id=ident,source_display_id=item['display_id'],display_type=next(iter(types)),icon_file_id=icon,resources=refs,policy='exact-source-model-texture-native-reference-reuse',source_asset_equivalence_verified=False)
except ValueError as error:blocked.append(dict(item_id=ident,source_display_id=item['display_id'],reason=str(error)))
return candidates,blocked
def native_equipment_variant_candidates(source,dbc,target,package_rows,names,selected_items,*,unparented_candidates=None,allow_unpublished_references=False):
"""Match source equipment paths to complete existing native variants.
Display IDs may differ. BOTH geometry and material references must match;
recolors are not interchangeable. Helmets preserve the existing native
race-specific model family and require matching helmet visibility fields.
Layered armor requires exact region/material references, complete native
sex selectors and witnessed nonzero glove/boot geosets. Shoulders preserve
both positional model selectors. No new model or material rows are created.
Explicit reference-only mode also resolves unowned transmog dependencies
against EXISTING parents. It cannot create an item/parent or infer metadata.
"""
if (not isinstance(selected_items,set)or not 1<=len(selected_items)<=4096
or any(type(i)is not int or not 0<i<0x80000000 for i in selected_items)):raise ValueError('Bounded variant selection required')
if unparented_candidates is not None and (not isinstance(unparented_candidates,dict)or unparented_candidates):raise ValueError('Empty explicit unparented candidate output required')
if type(allow_unpublished_references)is not bool or (allow_unpublished_references and unparented_candidates is not None):raise ValueError('Reference-only review cannot create appearance parents')
if source.get('snapshot_verification',{}).get('content_and_schema_and_ids_verified')is not True:raise ValueError('Verified source snapshot required')
displays=index(target['ItemDisplayInfo']);parents=defaultdict(list)
for p in target['ItemAppearance']:
if not p['TransmogPlayerConditionID']:parents[p['ItemDisplayInfoID']].append(p)
model=resources(index(target['ModelFileData']),'ModelResourcesID');texture=resources(index(target['TextureFileData']),'MaterialResourcesID')
layered={r['ItemDisplayInfoID']for r in target.get('ItemDisplayInfoMaterialRes',[])}
layer_rows=defaultdict(list)
for r in target.get('ItemDisplayInfoMaterialRes',[]):layer_rows[r['ItemDisplayInfoID']].append(r)
# WoWee itemComponentDir / resolveItemRegionTexture: Classic8 body regions;
# target ItemDisplayInfoMaterialRes ComponentSection uses these same named
# regions. Only exact single unisex native textures are admitted here.
body_dirs=('armuppertexture','armlowertexture','handtexture','torsouppertexture',
'torsolowertexture','leguppertexture','leglowertexture','foottexture')
component_models=index(target.get('ComponentModelFileData',[]));component_textures=index(target.get('ComponentTextureFileData',[]))
originals={r['identity'][1]:r['raw_fields']for r in source['records']}
if len(originals)!=len(source['records']):raise ValueError('Duplicate source variant identity')
for r in source['records']:
if r['identity']!=['Item',r['raw_fields']['entry']]or r.get('raw_sha256')!=hashlib.sha256(_canonical(r['raw_fields'])).hexdigest():raise ValueError('Source variant identity/hash differs')
geoset_witnesses=defaultdict(list);geoset_display_types=defaultdict(set)
shape_witnesses=defaultdict(list)
shape_parents={p['ID']:p for rows in parents.values()for p in rows}
for link in target['ItemModifiedAppearance']:
item=originals.get(link['ItemID'])
if (link['ItemAppearanceModifierID'] or not item or item['class']!=4
or item['inventory_type']not in(1,3)):continue
raw=dbc.by_id.get(item['display_id'])
if raw is None:continue
comp=item_display_composition(dbc,raw)
if any(comp['GeosetGroup']+comp['Flags'])or any(comp['Texture']):continue
parent=shape_parents.get(link['ItemAppearanceID'])
display=displays.get(parent['ItemDisplayInfoID'])if parent else None
if display:
key=(item['inventory_type'],tuple(x.lower()for x in comp['ModelName']),tuple(comp['HelmetGeosetVisID']),tuple(display['ModelResourcesID']))
shape_witnesses[key].append((item['entry'],parent['DisplayType']))
for link in target['ItemModifiedAppearance']:
# The source display identity plus the native default item chain is the
# witness, not a similar item name or a numeric geoset match alone.
item=originals.get(link['ItemID'])
if link['ItemAppearanceModifierID']or not item or item['class']!=4 or item['inventory_type']not in(4,5,6,7,8,9,10,19,20):continue
candidates=parents.get(item['display_id'],[])
if not any(p['ID']==link['ItemAppearanceID']for p in candidates):continue
raw=dbc.by_id.get(item['display_id']);d=displays.get(item['display_id'])
if raw is None or d is None:continue
comp=item_display_composition(dbc,raw);groups=comp['GeosetGroup']
plain_layers=groups==[0,0,0]and any(comp['Texture'])
if plain_layers and {i for i,v in enumerate(comp['Texture'])if v}!={r['ComponentSection']for r in layer_rows[d['ID']]}:continue
if ((not groups[0]and not plain_layers)or any(groups[1:]+comp['Flags']+comp['HelmetGeosetVisID'])
or any(comp['ModelName']+comp['ModelTexture'])or raw[10]or raw[22]
or d['GeosetGroup']!=groups+[0]*3 or any(d['AttachmentGeosetGroup'])):continue
key=item['subclass'],item['inventory_type'],tuple(groups)
geoset_witnesses[key].append(item['entry'])
geoset_display_types[key].update(p['DisplayType']for p in candidates if p['ID']==link['ItemAppearanceID'])
published={(r['table_name'],r['id']):r['record']for r in package_rows if r.get('record_status','valid')=='valid'}
variants={};blocked=[]
for record in source['records']:
item=record['raw_fields'];ident=item['entry']
if ident not in selected_items:continue
if not allow_unpublished_references and (('Item',ident)not in published or ('ItemSparse',ident)not in published):continue
if record['identity']!=['Item',ident]or record['raw_sha256']!=hashlib.sha256(_canonical(item)).hexdigest():raise ValueError('Source variant identity/hash differs')
kind=('weapon'if item['class']==2 else'shield'if item['class']==4 and item['subclass']==6 and item['inventory_type']==14
else'head'if item['class']==4 and item['inventory_type']==1
else'shoulder'if item['class']==4 and item['inventory_type']==3
else'body'if item['class']==4 and item['inventory_type']in(4,5,6,7,8,9,10,19,20)else None)
if not kind:continue
try:
raw=dbc.by_id.get(item['display_id'])
if raw is None:raise ValueError('source-display-missing')
comp=item_display_composition(dbc,raw)
geosets=comp['GeosetGroup'];geoset_proof=[]
if kind=='body':
geoset_proof=geoset_witnesses.get((item['subclass'],item['inventory_type'],tuple(geosets)),[])
if (any(geosets)and not geoset_proof)or any(comp['Flags'])or(kind!='head'and any(comp['HelmetGeosetVisID']))or(kind!='body'and any(comp['Texture']))or raw[10]or raw[22]:raise ValueError('nontrivial-source-geoset-layer-or-visual')
body_expected={}
if kind=='body':
if any(comp['ModelName']+comp['ModelTexture']):raise ValueError('layered-armor-has-attached-model')
for section,token in enumerate(comp['Texture']):
if not token:continue
if not re.fullmatch(r'[A-Za-z0-9_-]+',token):raise ValueError('unreviewed-source-body-texture-token')
body_expected[section]='item/texturecomponents/'+body_dirs[section]+'/'+token.lower()
if not body_expected:raise ValueError('empty-source-body-layers')
expected=[]
for m,t in zip(comp['ModelName'],comp['ModelTexture']):
if not m and not t:expected.append(None);continue
if not re.fullmatch(r'[A-Za-z0-9_-]+\.(?:mdx|MDX|m2|M2)',m)or not re.fullmatch(r'[A-Za-z0-9_-]+',t):raise ValueError('unreviewed-source-equipment-path-token')
expected.append(('item/objectcomponents/'+kind+'/'+m.rsplit('.',1)[0].lower()+'.m2','item/objectcomponents/'+kind+'/'+t.lower()+'.blp'))
if not any(expected)and kind!='body':raise ValueError('empty-source-equipment-resources')
matches=[]
for d in displays.values():
display_parents=parents.get(d['ID'],[])
if not display_parents:
shape_proof=shape_witnesses.get((item['inventory_type'],tuple(x.lower()for x in comp['ModelName']),tuple(comp['HelmetGeosetVisID']),tuple(d['ModelResourcesID'])),[])if kind in('head','shoulder')else[]
types=({t for _,t in shape_proof}if kind in('head','shoulder')else
geoset_display_types.get((item['subclass'],item['inventory_type'],tuple(geosets)),set()))
if (unparented_candidates is None or kind not in('body','head','shoulder')
or not(geoset_proof if kind=='body'else shape_proof)or len(types)!=1):continue
# A matching native display may have no published appearance
# parent. This is a candidate allocation, not an existing ID.
display_parents=[dict(ID=None,DisplayType=next(iter(types)))]
if kind!='body'and d['ID']in layered:continue
if (any(d.get(k,0)for k in('Flags','GeosetGroupOverride','ItemVisual','ParticleColorID','ItemRangedDisplayInfoID','OverrideSwooshSoundKitID','SheatheTransformMatrixID','StateSpellVisualKitID','SheathedSpellVisualKitID','UnsheathedSpellVisualKitID'))
or d['GeosetGroup']!=geosets+[0]*3 or any(d['AttachmentGeosetGroup'])or d['HelmetGeosetVis']!=comp['HelmetGeosetVisID']):continue
refs=[]
if kind=='body':
if any(d['ModelResourcesID']+d['ModelMaterialResourcesID'])or any(mt not in(-1,0)for mt in d['ModelType']):continue
layers=layer_rows[d['ID']]
if len(layers)!=len(body_expected)or {r['ComponentSection']for r in layers}!=set(body_expected):continue
for r in sorted(layers,key=lambda r:r['ComponentSection']):
tf=texture.get(r['MaterialResourcesID'],[]);wanted=body_expected[r['ComponentSection']]
if len(tf)==1 and names.get(tf[0])==[wanted+'_u.blp']:
refs.append(dict(component_section=r['ComponentSection'],texture_file_id=tf[0],texture_path=wanted+'_u.blp',native_unisex_layer_preserved=True))
elif len(tf)==2:
family=[]
for fid in tf:
c=component_textures.get(fid)
if not c or c['GenderIndex']not in(0,1)or c['ClassID']or c['RaceID']:break
path=wanted+('_m.blp'if c['GenderIndex']==0 else'_f.blp')
if names.get(fid)!=[path]:break
family.append(dict(file_data_id=fid,path=path,gender_index=c['GenderIndex']))
if len(family)!=2 or {f['gender_index']for f in family}!={0,1}:break
refs.append(dict(component_section=r['ComponentSection'],texture_family=family,native_gender_specific_family_preserved=True))
else:break
else:
if geoset_proof:refs.append(dict(source_geoset_groups=geosets,native_geoset_groups=d['GeosetGroup'],source_display_witness_item_ids=sorted(set(geoset_proof))))
for p in display_parents:
if geoset_proof and p['DisplayType']not in geoset_display_types[item['subclass'],item['inventory_type'],tuple(geosets)]:continue
matches.append((p,d,refs))
continue
for slot,wanted in enumerate(expected):
mr=d['ModelResourcesID'][slot];tr=d['ModelMaterialResourcesID'][slot];mt=d['ModelType'][slot]
if wanted is None:
if mr or tr or mt not in(-1,0):break
continue
mf=model.get(mr,[]);tf=texture.get(tr,[])
if mt!=0 or not mf or len(tf)!=1 or names.get(tf[0])!=[wanted[1]]:break
if kind=='head':
# Existing native families include both *_tam and
# modern *_za_m / *_kt_f names. Preserve the entire
# checked family rather than dropping newer variants.
pattern=re.escape(wanted[0][:-3])+r'_[a-z]{2}_?[mf]\.m2'
if any(len(names.get(fid,[]))!=1 or not re.fullmatch(pattern,names[fid][0])for fid in mf):break
refs.append(dict(slot=slot,model_file_ids=mf,model_paths=[names[fid][0]for fid in mf],texture_file_id=tf[0],texture_path=wanted[1],native_race_specific_family_preserved=True,helmet_visibility=comp['HelmetGeosetVisID']))
elif kind=='shoulder'and len(mf)==2:
family=[]
for fid in mf:
c=component_models.get(fid)
if not c or c['PositionIndex']not in(0,1)or c['GenderIndex']!=2 or c['ClassID']or c['RaceID']:break
position=c['PositionIndex']
if expected[position]is None or names.get(fid)!=[expected[position][0]]:break
family.append(dict(file_data_id=fid,path=expected[position][0],position_index=position))
if len(family)!=2 or {f['position_index']for f in family}!={0,1}:break
refs.append(dict(slot=slot,positioned_model_family=family,texture_file_id=tf[0],texture_path=wanted[1],native_shoulder_positions_preserved=True))
else:
if len(mf)!=1 or names.get(mf[0])!=[wanted[0]]:break
refs.append(dict(slot=slot,model_file_id=mf[0],texture_file_id=tf[0],model_path=wanted[0],texture_path=wanted[1]))
else:
if not parents.get(d['ID'])and kind in('head','shoulder'):
refs.append(dict(source_geometry_witness_item_ids=sorted({i for i,_ in shape_proof})))
for p in display_parents:matches.append((p,d,refs))
# A verified same-display chain is stronger than another modern
# duplicate resource variant. Numeric identity alone never enters
# matches: every candidate above passed the full resource checks.
same_display=[match for match in matches if match[1]['ID']==item['display_id']]
if same_display:matches=same_display
existing=[match for match in matches if match[0]['ID']is not None]
if existing:matches=existing
if len(matches)!=1:raise ValueError('missing-or-ambiguous-exact-native-resource-variant')
p,d,refs=matches[0]
if p['ID']is None:
icon=published['Item',ident]['IconFileDataID']
if type(icon)is not int or not 0<icon<0x80000000:raise ValueError('positive-published-item-icon-required')
unparented_candidates[ident]=dict(item_id=ident,source_display_id=item['display_id'],native_display_info_id=d['ID'],
display_type=p['DisplayType'],icon_file_id=icon,resources=refs,native_parent_absent_in_pinned_export=True,
policy='exact-source-material-native-display-parent',source_asset_equivalence_verified=False)
continue
variants[ident]=dict(item_id=ident,source_display_id=item['display_id'],native_appearance_id=p['ID'],native_display_info_id=d['ID'],display_type=p['DisplayType'],resources=refs,policy='exact-source-model-and-material-existing-native-variant',source_asset_equivalence_verified=False)
except ValueError as error:blocked.append(dict(item_id=ident,source_display_id=item['display_id'],reason=str(error)))
return variants,blocked
def missing_weapon_links(source,target,package_rows,registry,native_max,*,parent_candidates=None,parent_native_max=None,visible_armor=False,selected_items=None,modern_basics=None,resource_variants=None):
"""Add missing links using a witnessed existing native appearance, in bulk.
The witness must be another authentic source weapon with the SAME source
display ID and an existing default native chain to that exact display.
This preserves native geometry/materials; it is not source asset conversion
or proof that modified Octo asset bytes equal Forever's existing assets.
Never replace an existing variant or grant a transmog collection unlock.
"""
import copy
from item_sparse_compat import encode
if source.get('snapshot_verification',{}).get('content_and_schema_and_ids_verified')is not True:raise ValueError('Verified source snapshot required')
if type(native_max)is not int or not 0<native_max<0x7fffffff:raise ValueError('Native appearance row maximum required')
if type(visible_armor)is not bool:raise ValueError('Explicit visible armor scope required')
if selected_items is not None and(not isinstance(selected_items,set)or not 1<=len(selected_items)<=4096
or any(type(i)is not int or not 0<i<0x80000000 for i in selected_items)):raise ValueError('Bounded selected item identities required')
def visible(item):return item['class']==2 or(visible_armor and item['class']==4 and item['inventory_type']in VISIBLE_ARMOR_SLOTS)
originals={r['identity'][1]:r['raw_fields']for r in source['records']}
if len(originals)!=len(source['records']):raise ValueError('Duplicate source identity')
for record in source['records']:
raw=record['raw_fields']
if record['identity']!=['Item',raw['entry']]or record.get('raw_sha256')!=hashlib.sha256(_canonical(raw)).hexdigest():raise ValueError('Source appearance identity/hash differs')
appearances=index(target['ItemAppearance']);displays=index(target['ItemDisplayInfo']);links=index(target['ItemModifiedAppearance'])
if any(i>native_max for i in links):raise ValueError('Native link exceeds pinned maximum')
for row in package_rows:
if row['table_name']=='ItemAppearance'and row.get('record_status','valid')=='valid':appearances[row['id']]=dict(row['record'])
if row['table_name']=='ItemModifiedAppearance':
if row.get('record_status','valid')!='valid':raise ValueError('Appearance removal policy is unreviewed')
links[row['id']]=dict(row['record'])
by_item=defaultdict(list);witnesses=defaultdict(list);modern_witnesses=defaultdict(list)
for row in links.values():
by_item[row['ItemID']].append(row)
original=originals.get(row['ItemID']);parent=appearances.get(row['ItemAppearanceID'])
if (row['ItemAppearanceModifierID']==0 and original and visible(original)and parent
and parent['ItemDisplayInfoID']==original['display_id'] and parent['ItemDisplayInfoID']in displays
and not parent.get('TransmogPlayerConditionID')):
witnesses[original['class'],original['display_id']].append((row['ItemID'],row['ItemAppearanceID']))
# Explicit opt-in: preserve a same-source-display donor's modern native
# appearance even when its native display ID differs. Source appearance
# identity, not a similar name, chooses the donor; positive same-ID native
# class/subclass/slot checks prevent unrelated destination collisions.
basic=(modern_basics or{}).get(row['ItemID'])
if (row['ItemAppearanceModifierID']==0 and original and visible(original)and parent and basic
and parent['ItemDisplayInfoID']in displays and not parent.get('TransmogPlayerConditionID')
and all(basic.get(k)==original.get(v)for k,v in(('ClassID','class'),('SubclassID','subclass'),('InventoryType','inventory_type')))):
modern_witnesses[original['class'],original['inventory_type'],original['display_id']].append((row['ItemID'],row['ItemAppearanceID']))
installed={}
for row in package_rows:
if row.get('record_status','valid')=='valid':installed[row['table_name'],row['id']]=row.get('record',{})
reg=copy.deepcopy(registry)
if reg.get('version')!=1 or not isinstance(reg.get('slots'),dict):raise ValueError('Appearance registry version required')
slots=reg['slots'];values=list(slots.values())
if len(set(values))!=len(values)or any(type(i)is not int or not native_max<i<0x80000000 for i in values):raise ValueError('Appearance allocation collision/bound')
next_id=max([native_max,*values,*links]);records=[];bindings=[];blocked=[]
parents=reg.setdefault('parents',{})if parent_candidates is not None else{}
if parent_candidates is not None:
if type(parent_native_max)is not int or not 0<parent_native_max<0x7fffffff or not isinstance(parents,dict):raise ValueError('Pinned native appearance maximum and registry required')
if len(set(parents.values()))!=len(parents)or any(type(i)is not int or not parent_native_max<i<0x80000000 for i in parents.values()):raise ValueError('Parent appearance allocation collision/bound')
next_parent=max([parent_native_max,*parents.values(),*appearances]);created=set()
for ident,original in sorted(originals.items()):
if selected_items is not None and ident not in selected_items:continue
if not ident or not visible(original):continue
basic=installed.get(('Item',ident));sparse=installed.get(('ItemSparse',ident))
if basic is None or sparse is None:continue
if basic.get('ClassID')!=original['class']or basic.get('InventoryType')!=original['inventory_type']:raise ValueError('Published source equipment category differs')
if by_item.get(ident):continue
candidates=witnesses.get((original['class'],original['display_id']),[]);policy='source-shared-display-native-display-identity'
if not candidates and modern_basics is not None:
candidates=modern_witnesses.get((original['class'],original['inventory_type'],original['display_id']),[])
policy='source-shared-display-preserve-modern-native-item'
parent_ids=sorted({parent for _,parent in candidates});reference=None
if not parent_ids and resource_variants is not None and ident in resource_variants:
variant=resource_variants[ident];parent=appearances.get(variant['native_appearance_id'])
if (variant['item_id']!=ident or variant['source_display_id']!=original['display_id']
or variant['policy']!='exact-source-model-and-material-existing-native-variant'or not parent
or parent['ItemDisplayInfoID']!=variant['native_display_info_id']or parent['DisplayType']!=variant['display_type']
or parent.get('TransmogPlayerConditionID')):raise ValueError('Native resource variant belongs to another source/parent')
parent_ids=[parent['ID']];policy=variant['policy'];reference=variant
if len(parent_ids)!=1:
reference=(parent_candidates or{}).get(ident)
parent_display=reference.get('native_display_info_id',original['display_id'])if reference else original['display_id']
if reference and not parent_ids and not any(p['ItemDisplayInfoID']==parent_display for p in appearances.values()if p['ID']<=parent_native_max):
if reference['item_id']!=ident or reference['source_display_id']!=original['display_id']or reference['policy']not in('exact-source-model-texture-native-reference-reuse','exact-source-material-native-display-parent'):raise ValueError('Native resource candidate belongs to another source')
if reference['policy']=='exact-source-material-native-display-parent'and(parent_display not in displays or reference.get('native_parent_absent_in_pinned_export')is not True or not any(r.get('source_display_witness_item_ids')or r.get('source_geometry_witness_item_ids')for r in reference['resources'])):raise ValueError('Unparented native display lacks witnessed source geometry or geoset')
key=f'{original["display_id"]}:{reference["icon_file_id"]}:{reference["display_type"]}'if parent_display==original['display_id']else f'native:{parent_display}:{reference["icon_file_id"]}:{reference["display_type"]}'
if key not in parents:next_parent+=1;parents[key]=next_parent
parent_id=parents[key]
parent=dict(ID=parent_id,DisplayType=reference['display_type'],ItemDisplayInfoID=parent_display,DefaultIconFileDataID=reference['icon_file_id'],UiOrder=0,TransmogPlayerConditionID=0)
if parent_id in appearances and appearances[parent_id]!=parent:raise ValueError('Allocated appearance parent conflicts with existing data')
if parent_id not in appearances and parent_id not in created:
raw_parent=encode(parent,APPEARANCE_SCHEMA)
records.append(dict(table_name='ItemAppearance',table_hash=hex(APPEARANCE_TABLE),id=parent_id,record=parent,wire_hex=raw_parent.hex(),sha256=hashlib.sha256(raw_parent).hexdigest(),source_display_id=original['display_id']));created.add(parent_id)
parent_ids=[parent_id]
else:
blocked.append(dict(item_id=ident,source_display_id=original['display_id'],reason='missing-or-ambiguous-native-source-display-witness',candidate_parent_ids=parent_ids));continue
key=str(ident)
if key not in slots:next_id+=1;slots[key]=next_id
row_id=slots[key]
if row_id in links or not row_id<0x80000000:raise ValueError('New appearance link collides with existing row')
row=dict(ID=row_id,ItemID=ident,ItemAppearanceModifierID=0,ItemAppearanceID=parent_ids[0],OrderIndex=0,TransmogSourceTypeEnum=0,Flags=0)
raw=encode(row,MODIFIED_SCHEMA)
records.append(dict(table_name='ItemModifiedAppearance',table_hash=hex(MODIFIED_TABLE),id=row_id,record=row,wire_hex=raw.hex(),sha256=hashlib.sha256(raw).hexdigest(),source_item=ident,source_display_id=original['display_id']))
binding=dict(item_id=ident,source_display_id=original['display_id'],native_appearance_id=parent_ids[0],source_witness_item_ids=sorted({i for i,_ in candidates}),native_resources_preserved=True,source_asset_equivalence_verified=False,rendering_verified=False)
binding.update(witness_policy=reference['policy']if reference else policy,native_display_info_id=appearances[parent_ids[0]]['ItemDisplayInfoID']if parent_ids[0]in appearances else reference.get('native_display_info_id',original['display_id']))
if reference:binding['native_resource_reference']=reference
bindings.append(binding)
return dict(kind='source-witnessed-missing-weapon-appearance-links',build='1.60.1.70334',records=records,bindings=bindings,blocked=blocked,registry=reg,installable=False,installed=False,engine_loaded=False,
limits=['Existing source/server item IDs preserved; only internal appearance-link row IDs allocated.','Existing native geometry/materials reused via exact shared source display and existing native source-item witness. Modified source asset equivalence remains unverified.','No existing appearance variants replaced, collection unlocks granted, new assets imported or gameplay state changed.'])
def compose_weapon_links(package,components):
"""Preserve the published registry prefix; stage a native resource experiment."""
import copy
from item_sparse_compat import encode,package_payloads,package_pages
if package.get('build')!='1.60.1.70334'or components.get('kind')!='source-witnessed-missing-weapon-appearance-links':raise ValueError('Reviewed appearance component/build identity required')
bindings={r['item_id']:r for r in components['bindings']}
if len(bindings)!=sum(r['table_name']=='ItemModifiedAppearance'for r in components['records'])or not bindings:raise ValueError('Complete distinct appearance binding required')
for row in components['records']:
record=row['record'];binding=bindings.get(row.get('source_item'))
if row['table_name']=='ItemAppearance':
if row['table_hash']!=hex(APPEARANCE_TABLE)or record.get('ID')!=row['id']or not any(b['native_appearance_id']==row['id']and b.get('native_resource_reference')for b in bindings.values())or encode(record,APPEARANCE_SCHEMA).hex()!=row['wire_hex']:raise ValueError('New appearance parent contract differs')
for b in bindings.values():
ref=b.get('native_resource_reference',{})
if b['native_appearance_id']==row['id']and ref.get('policy')=='exact-source-material-native-display-parent':
if (record['ItemDisplayInfoID']!=ref['native_display_info_id']or record['DisplayType']!=ref['display_type']or record['DefaultIconFileDataID']!=ref['icon_file_id']or not ref.get('native_parent_absent_in_pinned_export')):raise ValueError('New native display parent identity differs')
continue
if (row['table_name']!='ItemModifiedAppearance'or row['table_hash']!=hex(MODIFIED_TABLE)or record.get('ID')!=row['id']
or not binding or binding['item_id']!=record.get('ItemID')or binding['native_appearance_id']!=record.get('ItemAppearanceID')
or not(binding['source_witness_item_ids']or binding.get('native_resource_reference',{}).get('policy')in('exact-source-model-texture-native-reference-reuse','exact-source-model-and-material-existing-native-variant','exact-source-material-native-display-parent'))or not binding['native_resources_preserved']
or any(record.get(k)for k in('ItemAppearanceModifierID','OrderIndex','TransmogSourceTypeEnum','Flags'))
or encode(record,MODIFIED_SCHEMA).hex()!=row['wire_hex']):raise ValueError('Appearance link/source/wire contract differs')
result=copy.deepcopy(package);result['rows']+=copy.deepcopy(components['records'])
result['push_id']=package_payloads(result['rows'])[0];result['pushes']=package_pages(result['rows'])
result['appearance_scope']='Experimental missing equipment links/parents using existing native resources; source asset fidelity not verified.'
result['model_policy']='Preserve existing Forever models; import source assets only for missing items without usable native models.'
return result
def source_equipment_asset_requests(items,dbc):
"""Batch exact source resource requests, independent of published metadata.
A missing ItemSparse record must not hide an equipped item's model. Paths
follow the existing WoWee item-component reader; alternatives are retained
rather than selecting source archive precedence or a gender variant here.
"""
if not isinstance(items,list)or not 1<=len(items)<=4096 or dbc.fields!=23:raise ValueError('Bounded source item/display batch required')
seen=set();requests={};records=[];blocked=[]
body_dirs=('armuppertexture','armlowertexture','handtexture','torsouppertexture',
'torsolowertexture','leguppertexture','leglowertexture','foottexture')
def token(value):
if not isinstance(value,str)or not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',value):raise ValueError('Unreviewed source equipment asset token')
return value.lower()
def add(ident,kind,slot,paths,**context):
key=(kind,tuple(paths));entry=requests.setdefault(key,dict(kind=kind,paths=list(paths),users=[]))
entry['users'].append(dict(item_id=ident,slot=slot,**context))
for item in sorted(items,key=lambda r:r['entry']):
ident=uint(item['entry'],True)
if ident in seen:raise ValueError('Duplicate source equipment item ID')
seen.add(ident);cls=uint(item['class']);inv=uint(item['inventory_type']);sub=uint(item['subclass'])
kind=('weapon'if cls==2 else'shield'if cls==4 and sub==6 and inv==14
else'head'if cls==4 and inv==1 else'shoulder'if cls==4 and inv==3
else'body'if cls==4 and inv in(4,5,6,7,8,9,10,19,20)else None)
if kind is None:continue
raw=dbc.by_id.get(item['display_id'])
if raw is None:blocked.append(dict(item_id=ident,reason='source-display-missing'));continue
comp=item_display_composition(dbc,raw);record=dict(item_id=ident,source_display_id=item['display_id'],kind=kind,composition=comp,source_record_sha256=hashlib.sha256(_canonical(item)).hexdigest())
records.append(record)
try:
for slot,(model,material)in enumerate(zip(comp['ModelName'],comp['ModelTexture'])):
if kind=='body'and (model or material):
# Body-region layers are resolved below. Nonempty attached
# model columns need an independently verified attachment
# context; there is no generic ObjectComponents/Body rule.
record['unresolved_attached_models']=True
continue
if model:
match=re.fullmatch(r'([A-Za-z0-9_-]+)\.(?:mdx|m2)',model,re.I)
if not match:raise ValueError('Unreviewed source model extension')
stem=token(match[1]);path='item/objectcomponents/'+kind+'/'+stem
if kind=='head':
# Race/sex suffixes require a source family inventory;
# never invent a single human/tauren-only model.
add(ident,'model-family',slot,[path],source_suffixes_unresolved=True)
else:add(ident,'model',slot,[path+'.m2'])
if material:add(ident,'material',slot,['item/objectcomponents/'+kind+'/'+token(material)+'.blp'])
for section,name in enumerate(comp['Texture']):
if not name:continue
stem='item/texturecomponents/'+body_dirs[section]+'/'+token(name)
add(ident,'body-material',section,[stem+suffix+'.blp'for suffix in('_f','_m','_u','')],selection='source-gendered-then-unisex-then-plain',region=section)
if raw[10]or raw[22]:record['unresolved_visuals']=dict(SpellVisualID=raw[10],ItemVisual=raw[22])
except ValueError as error:blocked.append(dict(item_id=ident,reason=str(error)))
return dict(kind='source-equipment-asset-requests',records=records,requests=sorted(requests.values(),key=lambda r:(r['kind'],r['paths'])),blocked=blocked,
source_display_sha256=dbc.digest(),source_item_count=len(items),published_metadata_required=False,
source_precedence_verified=False,converted=False,installed=False,engine_loaded=False)
def catalogue_equipment_asset_requests(source, dbc):
"""Apply the existing bounded extractor to a complete verified catalogue.
Merge exact dependencies across chunks; do not infer native equivalence from
item IDs or names. Shared meshes retain all source users and material variants.
"""
rows = [r['raw_fields'] for r in source['records']]
if not 1 <= len(rows) <= 131072:
raise ValueError('Bounded source catalogue required')
nonwire = [r['entry'] for r in rows if type(r['entry']) is int and not 0 < r['entry'] <= 0xffffffff]
rows = [r for r in rows if r['entry'] not in nonwire]
ids = [uint(r['entry'], True) for r in rows]
if len(set(ids)) != len(ids):
raise ValueError('Duplicate catalogue item ID')
rows.sort(key=lambda r:r['entry'])
records, blocked, requests = [], [], {}
for start in range(0, len(rows), 4096):
part = source_equipment_asset_requests(rows[start:start+4096], dbc)
records.extend(part['records']); blocked.extend(part['blocked'])
for request in part['requests']:
key = request['kind'], tuple(request['paths'])
merged = requests.setdefault(key, dict(request, users=[]))
merged['users'].extend(request['users'])
return dict(kind='source-equipment-asset-requests', records=records,
requests=[requests[k] for k in sorted(requests)], blocked=blocked,
source_display_sha256=dbc.digest(), source_item_count=len(rows),
source_snapshot=source.get('snapshot_provenance'), blocked_nonwire_source_item_ids=nonwire,
published_metadata_required=False, source_precedence_verified=False,
converted=False, installed=False, engine_loaded=False)
def native_equipment_asset_names(requests,stream):
"""One bounded exact-path pass; name presence never proves local loading."""
if not isinstance(requests,list)or len(requests)>16384:raise ValueError('Bounded equipment asset requests required')
by_path=defaultdict(list);families=defaultdict(list);matches={}
for i,r in enumerate(requests):
if not isinstance(r,dict)or r.get('kind')not in('model','model-family','material','body-material')or not isinstance(r.get('paths'),list)or not 1<=len(r['paths'])<=4:raise ValueError('Reviewed equipment asset request required')
matches[i]=[]
for path in r['paths']:
if not isinstance(path,str)or len(path)>256 or not re.fullmatch(r'item/(?:objectcomponents|texturecomponents)/[a-z0-9_/-]+(?:\.(?:m2|blp))?',path)or any(p in('','.','..')for p in path.split('/')):raise ValueError('Canonical equipment asset path required')
(families if r['kind']=='model-family'else by_path)[path].append(i)
digest=hashlib.sha256();total=0;lines=0
while True:
raw=stream.readline(4097)
if not raw:break
lines+=1;total+=len(raw)
if len(raw)>4096 or total>MAX_LISTFILE_BYTES or lines>5000000:raise ValueError('Target listfile byte/line bound')
digest.update(raw);key,sep,path=raw.strip().partition(b';')
if not sep or not re.fullmatch(rb'[0-9]{1,10}',key)or not 0<int(key)<=0xffffffff:raise ValueError('Malformed native file identity')
try:name=path.decode('utf-8').lower()
except UnicodeDecodeError:continue
selected=list(by_path.get(name,[]))
if name.startswith('item/objectcomponents/head/')and name.endswith('.m2'):
family,_,suffix=name[:-3].rpartition('_')
if re.fullmatch('[a-z]{2}[mf]',suffix):selected.extend(families.get(family,[]))
for i in selected:
row=dict(file_data_id=int(key),path=name)
if row not in matches[i]:matches[i].append(row)
if len(matches[i])>128:raise ValueError('Native equipment alias/family bound')
return dict(kind='native-equipment-exact-path-reference-classification',listfile_sha256=digest.hexdigest(),listfile_lines=lines,
requests=[dict(r,native_references=sorted(matches[i],key=lambda x:(x['path'],x['file_data_id'])),native_name_present=bool(matches[i]),native_bytes_verified=False)for i,r in enumerate(requests)],
converted=False,installed=False,engine_loaded=False,limits=['Exact source paths or declared head race/sex families only; no similar-name model substitution.','FileDataID name presence does not prove installed bytes, supported model format, source equivalence or item rendering.'])
def model_vertex_stream(raw):
"""Compare declared vertices, not full model compatibility or MPQ precedence.
WoWee m2_loader.cpp: M2Header/M2VertexDisk and the version<264 cursor
establish the extra Vanilla playable-animation and embedded-view pairs.
Only actually observed source256 and target272/274 layouts are accepted.
Vertex ordering is retained; equal hashes do not prove equal skin topology,
material bindings, animation, attachments or effective source selection.
"""
if not isinstance(raw,bytes) or not 88<=len(raw)<=67108864:
raise ValueError('Bounded model vertex body required')
if raw[:4]==b'MD21':
# First validate every container boundary with the existing parser.
model_dependency_chunks(raw)
length=struct.unpack_from('<I',raw,4)[0];raw=raw[8:8+length]
if len(raw)<88 or raw[:4]!=b'MD20':raise ValueError('MD20 vertex body required')
version=struct.unpack_from('<I',raw,4)[0]
if version not in (256,257,272,274):raise ValueError('Unreviewed model vertex layout')
legacy=version in (256,257)
minimum=324 if legacy else 304
if len(raw)<minimum:raise ValueError('Truncated model vertex header')
vertex_header,texture_header=(68,92) if legacy else (60,80)
count,offset=struct.unpack_from('<II',raw,vertex_header)
textures,texture_offset=struct.unpack_from('<II',raw,texture_header)
def bounded(at,n,stride,label):
if n>1048576 or (n and (at<minimum or at>len(raw) or n>(len(raw)-at)//stride)):
raise ValueError('Invalid model '+label+' extent')
return raw[at:at+n*stride] if n else b''
vertices=bounded(offset,count,48,'vertex')
texture_rows=bounded(texture_offset,textures,16,'texture')
if textures>4096:raise ValueError('Model texture count bound')
geometry=hashlib.sha256();skinning=hashlib.sha256()
streams={name:hashlib.sha256() for name in ('position','normal','uv0','uv1')}
for at in range(0,len(vertices),48):
row=vertices[at:at+48]
values=struct.unpack('<3f',row[:12])+struct.unpack('<7f',row[20:48])
if not all(math.isfinite(value) for value in values):raise ValueError('Nonfinite model vertex')
geometry.update(row[:12]+row[20:48]);skinning.update(row[12:20])
for name,a,b in (('position',0,12),('normal',20,32),('uv0',32,40),('uv1',40,48)):
streams[name].update(row[a:b])
declared=[]
for index,(kind,flags,length,at) in enumerate(struct.iter_unpack('<4I',texture_rows)):
name=None
if length:
if length>4096:raise ValueError('Model texture name length bound')
text=bounded(at,length,1,'texture name')
# Source256 stores a bounded char array; actual source assets can
# exclude the trailing NUL from its length. Never read beyond that
# array. The converter explicitly terminates the target string.
if not text.endswith(b'\0') and (not legacy or b'\0'in text or not text.lower().endswith(b'.blp')):raise ValueError('Model texture name terminator')
text=text.rstrip(b'\0')
if b'\0' in text:raise ValueError('Model texture name terminator')
try:name=text.decode('ascii') or None
except UnicodeDecodeError:raise ValueError('Unreviewed model texture name encoding') from None
if name is not None:
parts=name.replace('\\','/').split('/')
if name.startswith(('/', '\\')) or ':' in name or any(p in ('','.', '..') for p in parts) or any(ord(c)<32 for c in name):
raise ValueError('Unsafe model texture path')
# The original reader dereferences a name only when length>0. Actual
# target replaceable slots retain nonzero offsets with zero length;
# source slots also contain an explicitly empty NUL name. Preserve these
# without following unused offsets or inventing an external texture.
declared.append(dict(slot=index,type=kind,flags=flags,name=name,
declared_name_bytes=length,unused_name_offset=at if not length else None,
external_name_declared=name is not None,type_semantics_reviewed=False))
return dict(md20_version=version,vertex_count=count,
ordered_geometry_sha256=geometry.hexdigest(),ordered_skinning_sha256=skinning.hexdigest(),
ordered_attribute_sha256={name:digest.hexdigest() for name,digest in streams.items()},
declared_textures=declared,full_model_equivalence_verified=False,
source_precedence_verified=False,engine_loaded=False)
def model_dependency_chunks(raw):
"""Bound the existing WoWee md21Body/SFID/AFID reader contracts.
No vertex, skeleton, texture or animation conversion. Other chunk tags are
retained opaquely instead of assuming every uint32 is a FileDataID. TXID's
uint32 slot array is cross-checked with M2Converter.ReadTXID in
SliderBeen/MultiConverter735, then verified against local extracted BLPs.
"""
if not isinstance(raw,bytes) or not 8<=len(raw)<=67108864 or raw[:4]!=b'MD21':
raise ValueError('Require bounded MD21 container')
chunks={};pos=0
while pos<len(raw):
if pos+8>len(raw) or len(chunks)>=64:raise ValueError('Model chunk header/count bound')
tag,size=struct.unpack_from('<4sI',raw,pos);pos+=8
if tag in chunks or size>len(raw)-pos:raise ValueError('Duplicate/truncated model chunk')
chunks[tag]=(pos,size);pos+=size
start,size=chunks[b'MD21']
if size<8 or raw[start:start+4]!=b'MD20':raise ValueError('Missing bounded MD20 body')
skins=[];textures=[];anims=[]
if b'SFID' in chunks:
at,size=chunks[b'SFID']
if size%4 or size>65536:raise ValueError('Skin FileDataID array bound')
skins=list(struct.unpack_from('<'+str(size//4)+'I',raw,at))
if b'TXID' in chunks:
at,size=chunks[b'TXID']
if size%4 or size>65536:raise ValueError('Texture FileDataID array bound')
textures=list(struct.unpack_from('<'+str(size//4)+'I',raw,at))
if b'AFID' in chunks:
at,size=chunks[b'AFID']
if size%8 or size>65536:raise ValueError('Animation FileDataID array bound')
anims=[dict(animation_id=a,variation=v,file_data_id=f) for a,v,f in struct.iter_unpack('<HHI',raw[at:at+size])]
return dict(md20_version=struct.unpack_from('<I',raw,start+4)[0],skin_file_ids=skins,texture_file_ids=textures,animation_files=anims,
opaque_chunks=[dict(tag_hex=tag.hex(),bytes=value[1])for tag,value in sorted(chunks.items())if tag not in (b'MD21',b'SFID',b'AFID',b'TXID')],
skin_path_fallback_unreviewed=b'SFID' not in chunks,dependency_complete=False)
def scan_model_files(directory, *, vertices=False):
directory=Path(directory);root=directory.resolve()
if directory.is_symlink() or not directory.is_dir():raise ValueError('Require regular extracted model directory')
rows=[];blocked=[];total=0;ids=set();versions=Counter();opaque=Counter();vertex_blocked=[]
for path in sorted(directory.rglob('*.m2')):
if len(rows)+len(blocked)>=65536 or path.is_symlink() or not path.resolve().is_relative_to(root):raise ValueError('Model file/path count bound')
if not 8<=path.stat().st_size<=67108864:raise ValueError('Model file size bound')
with path.open('rb')as stream:raw=stream.read(67108865)
total+=len(raw)
if len(raw)>67108864 or total>1073741824:raise ValueError('Model batch byte bound')
row=dict(path=path.relative_to(directory).as_posix(),bytes=len(raw),sha256=hashlib.sha256(raw).hexdigest())
try:row.update(model_dependency_chunks(raw))
except ValueError as error:blocked.append(dict(**row,reason=str(error)));continue
if vertices:
try:row['vertex_stream']=model_vertex_stream(raw)
except ValueError as error:vertex_blocked.append(dict(path=row['path'],sha256=row['sha256'],reason=str(error)))
rows.append(row);versions[row['md20_version']]+=1;opaque.update(chunk['tag_hex']for chunk in row['opaque_chunks'])
ids.update(i for i in row['skin_file_ids'] if i)
ids.update(i for i in row['texture_file_ids'] if i)
ids.update(a['file_data_id'] for a in row['animation_files'] if a['file_data_id'])
result=dict(kind='target-model-declared-dependency-inventory',models=rows,blocked=blocked,
declared_file_ids=sorted(ids),counts=dict(parsed_models=len(rows),blocked_models=len(blocked),
bytes=total,declared_file_ids=len(ids),md20_versions=dict(versions),opaque_chunk_counts=dict(opaque)),
dependency_complete=False,engine_loaded=False,converted=False,
limits=['Only reviewed SFID, AFID and TXID chunk structures are decoded; other chunks remain opaque, including possible additional dependencies.',
'Zero file IDs are retained as source slots but not requested. No synthetic skin/animation paths or placeholder files.',
'Chunk integrity is not model geometry, effect, texture or gameplay verification.'])
if vertices:result.update(vertex_streams_requested=True,vertex_stream_blocked=vertex_blocked,
vertex_stream_count=sum('vertex_stream' in row for row in rows))
return result
def uint(value, positive=False):
if type(value) is not int or not int(positive) <= value <= 0xffffffff:
raise ValueError('Appearance reference must be a bounded unsigned integer')
return value
def index(rows):
if not isinstance(rows, list) or len(rows) > 200000:
raise ValueError('Appearance export record bound')
result = {}
for row in rows:
if not isinstance(row, dict):raise ValueError('Malformed appearance row')
ident = uint(row.get('ID'), True)
if ident in result:raise ValueError('Duplicate destination table identity')
result[ident] = row
return result
def resources(rows, field):
result = defaultdict(list)
for row in rows.values():
key = uint(row.get(field))
file_id = uint(row.get('FileDataID'), True)
if key:result[key].append(file_id)
return {key:sorted(set(ids)) for key, ids in result.items()}
def pairs(row, field):
values = row.get(field)
if not isinstance(values, list) or len(values) != 2:
raise ValueError('Destination appearance component array must have two slots')
return [uint(value) for value in values]
def compare_appearances(source, dbc, target):
if (source.get('kind') != 'source-item-dependency-inventory' or
source.get('snapshot_verification', {}).get('content_and_schema_and_ids_verified') is not True):
raise ValueError('Require the existing verified full source snapshot')
if set(target) != set(TARGET_TABLES):raise ValueError('Require the complete target appearance table set')
tables = {name:index(target[name]) for name in TARGET_TABLES}
modified = defaultdict(list)
for row in tables['ItemModifiedAppearance'].values():
item_id = uint(row.get('ItemID'), True)
uint(row.get('ItemAppearanceID'));uint(row.get('ItemAppearanceModifierID'))
modified[item_id].append(row)
models = resources(tables['ModelFileData'], 'ModelResourcesID')
textures = resources(tables['TextureFileData'], 'MaterialResourcesID')
materials = defaultdict(list)
for row in tables['ItemDisplayInfoMaterialRes'].values():
uint(row.get('ComponentSection'));uint(row.get('MaterialResourcesID'))
materials[uint(row.get('ItemDisplayInfoID'), True)].append(row)
source_displays = {}; target_displays = {}; rows = []; missing = set();groups = defaultdict(dict);nonwire=[]
source_rows = source.get('records')
if not isinstance(source_rows, list) or not 1 <= len(source_rows) <= 100000:
raise ValueError('Source item row bound')
seen = set()
for record in sorted(source_rows, key=lambda row:row['identity'][1]):
item = record.get('raw_fields')
if not isinstance(item,dict):raise ValueError('Malformed source item row')
entry = uint(item.get('entry'))
if (record.get('identity') != ['Item', entry] or entry in seen or
record.get('raw_sha256') != hashlib.sha256(_canonical(item)).hexdigest()):
raise ValueError('Source item identity/hash differs')
seen.add(entry)
if not entry:
nonwire.append(entry);continue
if item.get('class') not in (2, 4) or not item.get('inventory_type'):continue
display = uint(item.get('display_id'));raw = dbc.by_id.get(display)
composition = item_display_composition(dbc, raw) if raw else None
if composition is not None:
source_displays[display] = composition
geometry_context = {key:composition[key] for key in ('ModelName','GeosetGroup','Flags','HelmetGeosetVisID')}
geometry_context['source_inventory_type'] = uint(item['inventory_type'])
# Names are only exact contextual-token candidates. No model is
# resolved by basename, extension substitution or visual resemblance.
signature = hashlib.sha256(_canonical(geometry_context)).hexdigest()
groups[signature][display] = dict(display_id=display, geometry_context=geometry_context,
texture_tokens={key:composition[key] for key in ('ModelTexture','Texture')})
candidates = sorted(modified.get(entry, []), key=lambda row:row['ID'])
links = []
for candidate in candidates:
appearance_id = candidate['ItemAppearanceID'];appearance = tables['ItemAppearance'].get(appearance_id)
info_id = uint(appearance.get('ItemDisplayInfoID')) if appearance else None
info = tables['ItemDisplayInfo'].get(info_id)
links.append(dict(modified_appearance_id=candidate['ID'], modifier=candidate['ItemAppearanceModifierID'],
appearance_id=appearance_id, display_id=info_id))
if appearance is None:missing.add(('ItemAppearance', appearance_id));continue
if info is None:missing.add(('ItemDisplayInfo', info_id));continue
if info_id in target_displays:continue
model_ids = pairs(info, 'ModelResourcesID');material_ids = pairs(info, 'ModelMaterialResourcesID')
body = sorted(materials.get(info_id, []), key=lambda row:row['ID'])
for ident in model_ids:
if ident and ident not in models:missing.add(('ModelResourcesID',ident))
for ident in material_ids + [row['MaterialResourcesID'] for row in body]:
if ident and ident not in textures:missing.add(('MaterialResourcesID',ident))
target_displays[info_id] = dict(record=info,
model_file_ids_by_slot=[models.get(ident,[]) for ident in model_ids],
material_file_ids_by_slot=[textures.get(ident,[]) for ident in material_ids],
body_materials=[dict(record=row,file_data_ids=textures.get(row['MaterialResourcesID'],[])) for row in body],
source_equivalence_verified=False, asset_bytes_verified=False)
reasons = []
if composition is None:reasons.append('source-display-missing')
if not candidates:reasons.append('target-item-appearance-chain-missing')
elif any(link['display_id'] not in target_displays for link in links):reasons.append('target-appearance-chain-incomplete')
reasons.append('source-target-asset-and-composition-equivalence-unverified')
rows.append(dict(item_id=entry, source_display_id=display, source_inventory_type=item['inventory_type'],
target_candidates=links, classification='unresolved-dependencies', blockers=reasons))
variants = []
for signature, displays in sorted(groups.items()):
values = [displays[key] for key in sorted(displays)]
texture_variants = {hashlib.sha256(_canonical(row['texture_tokens'])).hexdigest() for row in values}
if len(texture_variants) > 1:
variants.append(dict(context_sha256=signature,geometry_context=values[0]['geometry_context'],
source_displays=values,texture_variant_count=len(texture_variants),
verified_shared_geometry=False,recolor_conversion_ready=False))
return dict(schema_version=1, kind='source-target-item-appearance-preflight', target_build='1.60.1.70334',
source_identity=source['source_identity'], blocked_nonwire_source_item_ids=nonwire,
counts=dict(source_items=len(source_rows), blocked_nonwire_source_items=len(nonwire),
wearable_weapon_armor_items=len(rows), referenced_source_displays=len(source_displays),
reachable_target_displays=len(target_displays), target_rows={key:len(value) for key,value in tables.items()},
classifications=dict(Counter(row['classification'] for row in rows)),
missing_target_item_chains=sum(not row['target_candidates'] for row in rows),
source_context_texture_variant_groups=len(variants)), items=rows,
source_compositions={str(key):value for key,value in sorted(source_displays.items())},
target_compositions={str(key):value for key,value in sorted(target_displays.items())},
missing_target_table_references=[dict(namespace=key,id=value) for key,value in sorted(missing)],
source_reference_variant_candidates=variants, converted=False, installable=False, engine_loaded=False,
limits=['All three compatible/recolor/new-model classes require asset/dependency proof; unresolved rows remain class4.',
'Same source model tokens with different textures are candidates only; no shared geometry or asset availability is inferred.',
'Target item appearance chains preserve every modifier; no default variant, race/gender model or texture is silently selected.',
'Source body texture regions and target ComponentSection enums are retained separately, not numerically equated.',
'Resource IDs resolve to FileDataIDs, not verified files. Component model/texture tables are inventoried but selection semantics remain unreviewed.',
'Source is a public local Tortoise snapshot plus observed Octo file content, not verified live Octo database equivalence.'])
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--source-snapshot',type=Path,default=ROOT/'runtime/all-item-templates-20261017')
p.add_argument('--observed-inventory',type=Path,default=ROOT/'runtime/octo-observed-itemdisplay-inventory-20261017.json')
p.add_argument('--source-dbc',type=Path,default=ROOT/'runtime/octo-itemdisplay-block-fill-owned-20261017/capture/ItemDisplayInfo.dbc')
p.add_argument('--catalogue-assets',action='store_true',help='Batch all source equipment references and exact native names; no asset installation')
p.add_argument('--target-exports',type=Path);p.add_argument('--output',type=Path,required=True)
p.add_argument('--listfile',type=Path,default=ROOT.parent/'listfiles/community-listfile.csv')
p.add_argument('--target-assets',type=Path,help='Optional previously extracted local model directory; no extraction or installation')
p.add_argument('--model-vertices',action='store_true',help='Also validate declared vertex streams; does not attest full model equivalence')
p.add_argument('--missing-weapon-links',action='store_true',help='Stage only missing source-witnessed native weapon links; no installation or asset conversion')
p.add_argument('--package',type=Path,help='Current published metadata required for weapon link staging')
p.add_argument('--registry',type=Path,help='Separate new/reused internal appearance-row registry for weapon link staging')
p.add_argument('--package-output',type=Path,help='Optional new experimental package with missing weapon links; never install')
p.add_argument('--native-display-parents',action='store_true',help='Also stage missing parents only for exact source/native weapon model and texture references')
p.add_argument('--native-resource-variants',action='store_true',help='Resolve selected equipment by exact source model/material/body-region references to existing native appearances')
p.add_argument('--visible-armor-links',action='store_true',help='Include visible armor/shields using exact source-display witnesses; no armor layer/geoset conversion')
p.add_argument('--owned-items',type=Path,help='Generate bindings only for owned inventory items; retain the full source witness graph')
p.add_argument('--source-set-catalogue',type=Path,help='Select complete checked source-set families from an existing catalogue manifest')
p.add_argument('--native-item-basics',type=Path,help='Opt in to preserving modern donor appearances with positive native class/subclass/slot checks; requires --owned-items')
a = p.parse_args()
if a.model_vertices and a.target_assets is None:p.error('--model-vertices requires retained --target-assets')
if a.missing_weapon_links and(a.package is None or a.registry is None):p.error('Weapon link stage requires explicit --package and --registry')
if a.native_display_parents and not a.missing_weapon_links:p.error('--native-display-parents requires --missing-weapon-links')
if a.visible_armor_links and not a.missing_weapon_links:p.error('--visible-armor-links requires --missing-weapon-links')
if a.owned_items and not a.missing_weapon_links:p.error('--owned-items requires --missing-weapon-links')
if a.source_set_catalogue and(not a.missing_weapon_links or a.owned_items):p.error('--source-set-catalogue requires --missing-weapon-links and no --owned-items')
if a.native_item_basics and not(a.owned_items or a.source_set_catalogue):p.error('--native-item-basics requires explicit owned/set selection')
if a.native_resource_variants and not(a.owned_items or a.source_set_catalogue):p.error('--native-resource-variants requires explicit owned/set selection')
if not a.output.resolve().is_relative_to(ROOT/'runtime') or a.output.exists():p.error('Require new private runtime output')
observed, observed_hash = read_observed_inventory(a.observed_inventory)
if a.source_dbc.is_symlink() or not 20 <= a.source_dbc.stat().st_size <= 67108864:raise ValueError('Source DBC byte bound')
raw = a.source_dbc.read_bytes();dbc, context = observed_item_display(observed, raw)
if a.catalogue_assets:
if a.missing_weapon_links or a.package_output:
p.error('Catalogue asset inventory is independent of link mutation')
source=inventory_item_snapshot(a.source_snapshot)
result=catalogue_equipment_asset_requests(source,dbc)
with a.listfile.open('rb') as stream:
naming=native_equipment_asset_names(result['requests'],stream)
result.update(requests=naming['requests'],native_listfile_sha256=naming['listfile_sha256'],
observed_source_context=context,observed_inventory_sha256=observed_hash,
converter_sha256=bounded_digest(Path(__file__)))
result['counts']=dict(source_items=result['source_item_count'],equipment_records=len(result['records']),
unique_dependencies=len(result['requests']),
missing_exact_native_names=sum(not r['native_name_present'] for r in result['requests']),
source_blockers=len(result['blocked']))
with a.output.open('x') as stream:json.dump(result,stream,sort_keys=True,separators=(',',':'));stream.write('\n')
print(json.dumps(dict(output=str(a.output),counts=result['counts'],installed=False)))
return
if not a.target_exports:p.error('--target-exports required for appearance comparison')
target={};pins={}
for table in TARGET_TABLES:
target[table],pins[table]=read_public_json(a.target_exports/(table+'.json'))
manifest,manifest_hash=read_public_json(a.target_exports/'manifest.json',1048576)
if (manifest.get('kind')!='local-target-appearance-schema-exports' or
manifest.get('build')!='1.60.1.70334' or set(manifest.get('tables',{}))!=set(TARGET_TABLES)):
raise ValueError('Require pinned target-build export manifest')
for table,pin in manifest['tables'].items():
if pin.get('export',{}).get('sha256')!=pins[table]:raise ValueError('Target export differs from retained manifest')
for key in ('db2','definition'):
file=pin.get(key,{})
if bounded_digest(Path(file.get('path','')),67108864)!=file.get('sha256'):
raise ValueError('Target DB2/definition source drift after export')
for key in ('reader_source','reader_binary'):
file=manifest.get(key,{})
if bounded_digest(Path(file.get('path','')),4194304)!=file.get('sha256'):
raise ValueError('Target schema-reader drift after export')
source=inventory_item_snapshot(a.source_snapshot)
if a.missing_weapon_links:
from item_sparse_compat import check_db2
meta=manifest['tables']['ItemModifiedAppearance'];native=Path(meta['db2']['path']);definition=Path(meta['definition']['path'])
check_db2(native,MODIFIED_TABLE,MODIFIED_LAYOUT)
block=definition.read_text().split('LAYOUT 03A6C979\n',1)[1].split('\nLAYOUT',1)[0]
expected=['$id$ID<32>','$relation$ItemID<32>','ItemAppearanceModifierID<32>','ItemAppearanceID<32>','OrderIndex<32>','TransmogSourceTypeEnum<u8>','Flags<32>']
if '1.60.1.70334'not in block or [r for r in block.splitlines()if r and not r.startswith(('BUILD','COMMENT'))]!=expected:raise ValueError('Unreviewed modified-appearance schema')
registry_path=a.registry.resolve()
if not registry_path.is_relative_to(ROOT/'runtime')or registry_path==a.output.resolve():raise ValueError('Separate runtime appearance registry required')
package,package_hash=read_compatibility_package(a.package)
registry,registry_hash=read_public_json(a.registry)if a.registry.exists()else(dict(version=1,slots={}),None)
with native.open('rb')as stream:maximum=struct.unpack_from('<I',stream.read(168),164)[0]
parent_kwargs={};resource_review=None
if a.native_display_parents:
parent_meta=manifest['tables']['ItemAppearance'];parent_file=Path(parent_meta['db2']['path']);parent_dbd=Path(parent_meta['definition']['path'])
check_db2(parent_file,APPEARANCE_TABLE,APPEARANCE_LAYOUT)
parent_block=parent_dbd.read_text().split('LAYOUT 481C4281\n',1)[1].split('\nLAYOUT',1)[0]
expected_parent=['$noninline,id$ID<32>','DisplayType<8>','ItemDisplayInfoID<32>','DefaultIconFileDataID<32>','UiOrder<32>','TransmogPlayerConditionID<32>']
if '1.60.1.70334'not in parent_block or [r for r in parent_block.splitlines()if r and not r.startswith(('BUILD','COMMENT'))]!=expected_parent:raise ValueError('Unreviewed appearance parent schema')
with parent_file.open('rb')as stream:parent_max=struct.unpack_from('<I',stream.read(168),164)[0]
model_refs=resources(index(target['ModelFileData']),'ModelResourcesID');texture_refs=resources(index(target['TextureFileData']),'MaterialResourcesID')
# Restrict naming scan to source weapon displays; no whole client extraction.
display_ids={r['raw_fields']['display_id']for r in source['records']if r['raw_fields']['class']==2}
wanted=set()
for display in target['ItemDisplayInfo']:
if display['ID']not in display_ids:continue
for ident in display['ModelResourcesID']:wanted.update(model_refs.get(ident,[]))
for ident in display['ModelMaterialResourcesID']:wanted.update(texture_refs.get(ident,[]))
if a.listfile.is_symlink()or not a.listfile.is_file()or a.listfile.stat().st_size>MAX_LISTFILE_BYTES:raise ValueError('Target listfile bound')
with a.listfile.open('rb')as stream:names,listing=listfile_index(stream,wanted,max_wanted=65536)
if bounded_digest(a.listfile,MAX_LISTFILE_BYTES)!=listing['sha256']:raise ValueError('Listfile changed during native resource review')
candidates,unresolved=native_weapon_parent_candidates(source,dbc,target,package['rows'],names)
parent_kwargs=dict(parent_candidates=candidates,parent_native_max=parent_max);resource_review=dict(candidates=candidates,blocked=unresolved,target_listfile_sha256=listing['sha256'])
owned_hash=None;selected=None
if a.owned_items:
from item_batch_stage import owned_item_priorities
owned,owned_hash=read_public_json(a.owned_items)
selected={r['entry']for r in owned_item_priorities(owned)}
if a.source_set_catalogue:
from item_catalog_stage import set_source_selection
from item_set_compat import extract_sets
catalog_path=a.source_set_catalogue/'manifest.json';catalog,catalog_hash=read_public_json(catalog_path,16777216)
if (catalog.get('selection')!='source-set-families'or catalog.get('kind')!='source-item-catalogue-conversion'
or catalog.get('source_snapshot_identity')!=source['source_identity']):raise ValueError('Source set catalogue identity differs')
set_path=Path(catalog['source_set_table']['path']);set_hash=catalog['source_set_table']['sha256']
if bounded_digest(set_path,16777216)!=set_hash:raise ValueError('Source set table changed')
family,selection=set_source_selection([r['raw_fields']for r in source['records']],extract_sets(set_path)[0],set(catalog['source_set_ids']))
if json.loads(json.dumps(selection))!=catalog['source_set_selection']:raise ValueError('Source set roster differs')
selected={p['entry']for p in family}
if a.native_item_basics:
native_items,native_items_hash=read_public_json(a.native_item_basics)
from item_package_preflight import target_index
parent_kwargs['modern_basics']=target_index(native_items,'Item')
if a.native_resource_variants:
model_refs=resources(index(target['ModelFileData']),'ModelResourcesID');texture_refs=resources(index(target['TextureFileData']),'MaterialResourcesID');wanted=set()
for display in target['ItemDisplayInfo']:
for ident in display['ModelResourcesID']:wanted.update(model_refs.get(ident,[]))
for ident in display['ModelMaterialResourcesID']:wanted.update(texture_refs.get(ident,[]))
for layer in target['ItemDisplayInfoMaterialRes']:wanted.update(texture_refs.get(layer['MaterialResourcesID'],[]))
if a.listfile.is_symlink()or not a.listfile.is_file()or a.listfile.stat().st_size>MAX_LISTFILE_BYTES:raise ValueError('Target listfile bound')
with a.listfile.open('rb')as stream:names,listing=listfile_index(stream,wanted,max_wanted=65536)
if bounded_digest(a.listfile,MAX_LISTFILE_BYTES)!=listing['sha256']:raise ValueError('Listfile changed during variant review')
new_parents={}if a.native_display_parents else None
variants,unresolved=native_equipment_variant_candidates(source,dbc,target,package['rows'],names,selected,unparented_candidates=new_parents)
parent_kwargs['resource_variants']=variants
if new_parents:
parent_kwargs['parent_candidates']={**parent_kwargs.get('parent_candidates',{}),**new_parents};parent_kwargs['parent_native_max']=parent_max
resource_review=dict(previous_parent_review=resource_review,variant_candidates=variants,unparented_candidates=new_parents,variant_blocked=unresolved,target_listfile_sha256=listing['sha256'])
result=missing_weapon_links(source,target,package['rows'],registry,maximum,visible_armor=a.visible_armor_links,selected_items=selected,**parent_kwargs)
if a.owned_items:
if bounded_digest(a.owned_items)!=owned_hash:raise ValueError('Owned inventory changed during appearance staging')
result.update(owned_inventory_sha256=owned_hash,selected_item_ids=sorted(selected))
if a.source_set_catalogue:
if bounded_digest(catalog_path,16777216)!=catalog_hash or bounded_digest(set_path,16777216)!=set_hash:raise ValueError('Source set selection inputs changed')
result.update(source_set_catalogue_sha256=catalog_hash,source_set_table_sha256=set_hash,selected_item_ids=sorted(selected))
if a.native_item_basics:
if bounded_digest(a.native_item_basics)!=native_items_hash:raise ValueError('Native item baseline changed during appearance staging')
result['native_item_basics_sha256']=native_items_hash
result['visible_armor_included']=a.visible_armor_links
if resource_review:result['native_resource_review']=resource_review
result.update(input_sha256=dict(source_manifest=source['source_identity']['manifest_sha256'],target_exports=pins,target_manifest=manifest_hash,package=package_hash,registry=registry_hash),source_identity=source['source_identity'])
result['implementation_sha256']={name:bounded_digest(ROOT/'ops'/name,1048576)for name in('item_appearance_preflight.py','item_sparse_compat.py','turtle_data.py','item_icon_preflight.py','item_package_preflight.py')}
composed=compose_weapon_links(package,result)if a.package_output else None
if a.package_output and(not a.package_output.resolve().is_relative_to(ROOT/'runtime')or a.package_output.exists()or a.package_output.resolve()in(a.output.resolve(),registry_path)):raise ValueError('New separate runtime package output required')
if bounded_digest(a.package,MAX_COMPATIBILITY_PACKAGE_JSON_BYTES)!=package_hash:raise ValueError('Published package changed during appearance stage')
if a.output.resolve()==a.package.resolve():raise ValueError('Appearance output must not replace active package')
with a.output.open('x')as stream:json.dump(result,stream,sort_keys=True,indent=2);stream.write('\n')
temporary=a.registry.with_name(a.registry.name+'.new')
with temporary.open('x')as stream:json.dump(result['registry'],stream,sort_keys=True,indent=2);stream.write('\n')
temporary.replace(a.registry)
if composed:
with a.package_output.open('x')as stream:json.dump(composed,stream,sort_keys=True,separators=(',',':'));stream.write('\n')
print(json.dumps(dict(candidate_links=len(result['bindings']),component_rows=len(result['records']),blocked=len(result['blocked']),installed=False,output=str(a.output))))
return
result=compare_appearances(source,dbc,target)
if a.target_assets is not None:
if not a.target_assets.resolve().is_relative_to(ROOT/'runtime'):raise ValueError('Require private runtime target assets')
result['target_model_dependencies']=scan_model_files(a.target_assets,vertices=a.model_vertices)
wanted=set()
for display in result['target_compositions'].values():
for field in ('model_file_ids_by_slot','material_file_ids_by_slot'):
for ids in display[field]:wanted.update(ids)
for material in display['body_materials']:wanted.update(material['file_data_ids'])
if 'target_model_dependencies' in result:
wanted.update(result['target_model_dependencies']['declared_file_ids'])
if a.listfile.is_symlink() or not a.listfile.is_file() or a.listfile.stat().st_size>MAX_LISTFILE_BYTES:
raise ValueError('Target listfile file bound')
with a.listfile.open('rb') as stream:names,listing=listfile_index(stream,wanted,max_wanted=65536)
if bounded_digest(a.listfile,MAX_LISTFILE_BYTES)!=listing['sha256']:raise ValueError('Target listfile drift during comparison')
result['target_file_naming_references']={str(ident):names.get(ident,[]) for ident in sorted(wanted)}
result['counts'].update(referenced_target_file_ids=len(wanted),target_file_ids_with_names=len(names))
result['target_listfile_scan']=listing
result.update(observed_source_context=context,input_sha256=dict(observed_inventory=observed_hash,
source_dbc=hashlib.sha256(raw).hexdigest(),target_exports=pins,target_manifest=manifest_hash,target_listfile=listing['sha256']),
target_export_manifest=manifest,
target_export_provenance='Local schema-reader exports; DB2/DBD/reader/export bytes rehashed against retained manifest, not independently re-exported by this preflight.')
with a.output.open('x') as stream:json.dump(result,stream,indent=2,sort_keys=True,allow_nan=False);stream.write('\n')
print(json.dumps(dict(output=str(a.output),counts=result['counts'],installable=False),sort_keys=True))
if __name__=='__main__':main()