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

286 lines
20 KiB
Python

#!/usr/bin/env python3
"""Build source enchantment to native ItemVisual presentation data.
The runtime profile takes the effective Octo DBC and native ItemVisuals DB2.
The candidate-agreement generator is retained for historical batch reviews.
"""
import argparse,hashlib,json,re
from collections import Counter
from pathlib import Path
from turtle_data import ROOT,DBC
TYPE_NAMES=('NONE','COMBAT_SPELL','DAMAGE','EQUIP_SPELL','RESISTANCE','STAT','TOTEM')
def namespace(source,target):
proof={}
for role,path in [('source',source),('target',target)]:
raw=path.read_bytes();text=raw.decode()
for value,name in enumerate(TYPE_NAMES):
if not re.search(r'\bITEM_ENCHANTMENT_TYPE_'+name+r'\s*=\s*'+str(value)+r'\s*[,}]',text):raise ValueError('Enchantment effect namespace differs: '+name)
proof[role+'_sha256']=hashlib.sha256(raw).hexdigest()
return dict(policy='named-legacy-enchantment-effects-v1',types=dict(zip(TYPE_NAMES,range(7))),**proof)
def generate(candidates,native,visuals,proof):
if proof.get('policy')!='named-legacy-enchantment-effects-v1'or proof.get('types')!=dict(zip(TYPE_NAMES,range(7))):raise ValueError('Require named source/native enchant namespace')
if any(not re.fullmatch('[0-9a-f]{64}',proof.get(k,''))for k in ('source_sha256','target_sha256')):raise ValueError('Require namespace content pins')
if not 1<=len(candidates)<=16 or any(t.fields!=24 for t in candidates):raise ValueError('Reviewed24-column source enchant candidates required')
if not isinstance(native,list)or not isinstance(visuals,list)or len(native)>100000 or len(visuals)>100000:raise ValueError('Bounded native enchant/visual records required')
destinations={}
for row in native:
ident=row.get('ID')
if type(ident)is not int or not 0<=ident<=0x7fffffff or ident in destinations:raise ValueError('Native enchant identity differs')
if not isinstance(row.get('Name_lang'),str)or type(row.get('ItemVisual'))is not int or not 0<=row['ItemVisual']<=65535:raise ValueError('Native enchant presentation fields differ')
for key in ('Effect','EffectArg'):
if not isinstance(row.get(key),list)or len(row[key])!=3 or any(type(v)is not int for v in row[key]):raise ValueError('Native enchant effect identity fields differ')
destinations[ident]=row
known_visuals = native_visual_records(visuals)
definitions=[];excluded=[]
for ident in sorted(set().union(*(t.by_id for t in candidates))):
if type(ident)is not int or not 0<ident<=0x7fffffff:raise ValueError('Source enchant identity bound')
rows=[(t,t.by_id[ident])for t in candidates if ident in t.by_id]
source_visuals={r[22]for _,r in rows}
if len(source_visuals)==1 and not next(iter(source_visuals)):
definitions.append(dict(enchantment=ident,visual=0,source_visual=0,classification='source-no-visual-agreement'));continue
shapes={(t.string(r[13]),tuple(r[1:4]),tuple(r[10:13]),r[22])for t,r in rows}
reason=None
if len(shapes)!=1:reason='ambiguous-source-visual-identity'
else:
name,effects,args,source_visual=next(iter(shapes));target=destinations.get(ident)
if any(v not in range(7)for v in effects):reason='unreviewed-source-effect-type'
elif not target:reason='missing-native-enchantment'
elif name!=target['Name_lang']:reason='different-native-name'
elif not {(e,a)for e,a in zip(effects,args)if e}<=set(zip(target['Effect'],target['EffectArg'])):reason='different-effect-identity'
elif target['ItemVisual']not in known_visuals or not any(known_visuals[target['ItemVisual']]['ModelFileID']):reason='missing-native-visual-model-record'
else:
definitions.append(dict(enchantment=ident,visual=target['ItemVisual'],source_visual=source_visual,source_name=name,
model_file_ids=known_visuals[target['ItemVisual']]['ModelFileID'],classification='source-agreement-native-identity'))
if reason:excluded.append(dict(enchantment=ident,reason=reason))
return dict(kind='source-owned-enchantment-visual-profile',schema_version=1,definitions=definitions,excluded=excluded,
namespace=proof,installed=False,model_assets_verified=False,gameplay_verified=False,
limitations=['Only visual identity is converted; native enchant effects/procs/stats are not rewritten.',
'Per-record source candidate agreement is not proof of full archive precedence.',
'A positive native model reference is not proof that the actual client loaded or rendered the asset.'])
def native_visual_records(visuals):
if not isinstance(visuals, list) or len(visuals) > 100000:
raise ValueError('Bounded native ItemVisuals rows required')
known_visuals = {}
for row in visuals:
ident = row.get('ID')
if type(ident) is not int or not 0 < ident <= 65535 or ident in known_visuals:
raise ValueError('Native visual identity differs')
models = row.get('ModelFileID')
if not isinstance(models, list) or len(models) != 5:
raise ValueError('Native visual model references differ')
if any(type(model) is not int or not 0 <= model <= 0x7fffffff for model in models):
raise ValueError('Native visual model references differ')
known_visuals[ident] = row
return known_visuals
def authoritative_profile(source, visuals):
if source.fields != 24:
raise ValueError('Expected the Octo 24-column SpellItemEnchantment table')
records = native_visual_records(visuals)
definitions = []
excluded = []
for ident, row in sorted(source.by_id.items()):
if not 0 < ident <= 0x7fffffff:
raise ValueError('Source enchant identity bound')
visual = row[22]
if visual and (visual not in records or not any(records[visual]['ModelFileID'])):
reason = 'source-sentinel' if visual == 0xffffffff else 'missing-native-visual-model-record'
excluded.append(dict(enchantment=ident, source_visual=visual, reason=reason))
continue
definitions.append(dict(enchantment=ident, visual=visual))
return dict(definitions=definitions, excluded=excluded)
def header(profile):
rows=profile['definitions']
if not rows or [r['enchantment']for r in rows]!=sorted({r['enchantment']for r in rows}):raise ValueError('Require unique sorted source enchant IDs')
if any(type(r['visual'])is not int or not 0<=r['visual']<=65535 for r in rows):raise ValueError('Native item visual width differs')
return '''// Generated from Octo SpellItemEnchantment and build 70334 ItemVisuals.
#pragma once
#include <algorithm>
#include <cstdint>
#include <iterator>
namespace gateway::item_enchantment_visual_profile {
struct Definition {uint32_t enchantment;uint16_t visual;};
inline constexpr Definition Rows[]={'''+','.join('{'+str(r['enchantment'])+','+str(r['visual'])+'}'for r in rows)+'''};
inline const Definition* find(uint32_t id){auto p=std::lower_bound(std::begin(Rows),std::end(Rows),id,[](const auto& r,uint32_t value){return r.enchantment<value;});return p!=std::end(Rows)&&p->enchantment==id?p:nullptr;}
inline uint16_t resolve(uint32_t permanent,uint32_t temporary){
if(const auto* p=find(permanent);p && p->visual)return p->visual;
const auto* t=find(temporary);return t?t->visual:0;
}
}
'''
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
sources=p.add_mutually_exclusive_group(required=True)
sources.add_argument('--source', type=Path, help='Effective source SpellItemEnchantment.dbc after archive precedence')
sources.add_argument('--source-candidate',type=Path,action='append')
p.add_argument('--native-enchantments',type=Path)
p.add_argument('--native-visuals',type=Path,required=True)
p.add_argument('--source-enums',type=Path)
p.add_argument('--target-enums',type=Path)
p.add_argument('--output',type=Path,required=True)
a=p.parse_args();out=a.output.resolve()
if out.exists()or out.is_symlink()or not out.is_relative_to(ROOT/'runtime')or not out.parent.is_dir():p.error('Require a NEW private runtime stage with existing parent')
visuals=json.loads(a.native_visuals.read_text())
if a.source:
table = DBC(a.source, 24)
result = authoritative_profile(table, visuals)
result['source_sha256'] = table.digest()
result['native_visual_export_sha256'] = hashlib.sha256(a.native_visuals.read_bytes()).hexdigest()
else:
if not all((a.native_enchantments, a.source_enums, a.target_enums)):
p.error('Candidate review requires --native-enchantments, --source-enums and --target-enums')
paths=sorted(set(a.source_candidate));tables=[DBC(path,24)for path in paths]
result=generate(tables,json.loads(a.native_enchantments.read_text()),json.loads(a.native_visuals.read_text()),namespace(a.source_enums,a.target_enums))
result['source_candidates']=[dict(path=str(t.path),sha256=t.digest(),rows=t.count)for t in tables]
result['native_exports']={name:dict(path=str(path),sha256=hashlib.sha256(path.read_bytes()).hexdigest())for name,path in [('SpellItemEnchantment',a.native_enchantments),('ItemVisuals',a.native_visuals)]}
result['converter_sha256'] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
payload=header(result).encode();result['header_sha256']=hashlib.sha256(payload).hexdigest()
out.mkdir(mode=0o700);(out/'item_enchantment_visual_profile.hpp').write_bytes(payload)
(out/'profile.json').write_text(json.dumps(result,sort_keys=True,indent=2)+'\n')
print(json.dumps(dict(definitions=len(result['definitions']),classifications=dict(Counter(r.get('classification','mapped' if r['visual'] else 'zero') for r in result['definitions'])),excluded=dict(Counter(r['reason']for r in result['excluded'])),installed=False)))
def defense_scalar_rows(source_enchants,source_spells,native,schemas):
"""Source equip-spell defense skill -> existing native classic defense stat.
No server execution or stat-field updates are generated. Preserve native
effect type/argument, constraints, icons and visual references. Only the
source name and constant amount change for this reviewed representation.
"""
from copy import deepcopy
import struct
from octo_client_data import canonical_sha256
from spell_passive_compat import encode,SUPPLEMENTAL_TABLES
from turtle_data import spell_layout
table=SUPPLEMENTAL_TABLES['SpellItemEnchantment'];schema=schemas
if source_enchants.fields!=24 or source_spells.fields!=173 or canonical_sha256(schema)!=table[2]:raise ValueError('Pinned enchantment schema required')
by_id={r['ID']:r for r in native};layout=spell_layout();rows=[];blocked=[]
if len(by_id)!=len(native):raise ValueError('Duplicate native enchantment identity')
integer=lambda v:struct.unpack('<i',struct.pack('<I',v))[0]
floatval=lambda v:struct.unpack('<f',struct.pack('<I',v))[0]
for ident,s in sorted(source_enchants.by_id.items()):
n=by_id.get(ident)
if not n or n['Effect']!=[5,0,0] or n['EffectArg']!=[12,0,0]:continue
if s[1:4]!=(3,0,0)or s[11:13]!=(0,0):continue
spell=source_spells.by_id.get(s[10])
if spell is None:blocked.append(dict(enchantment=ident,reason='source defense equip spell missing'));continue
if (tuple(spell[layout['Effect']:layout['Effect']+3]),tuple(spell[layout['EffectAura']:layout['EffectAura']+3]),integer(spell[layout['EffectMiscValue']]))!=((6,0,0),(30,0,0),95):continue
if (spell[layout['EffectDieSides']]not in(0,1)or any(floatval(spell[layout[k]])for k in('EffectRealPointsPerLevel','EffectDicePerLevel','EffectPointsPerCombo'))):
blocked.append(dict(enchantment=ident,reason='nonconstant source defense amount'));continue
if n['EffectScalingPoints']!=[0,0,0]or n['ScalingClass']or n['ScalingClassRestricted']:
blocked.append(dict(enchantment=ident,reason='native defense scaling differs'));continue
amount=integer(spell[layout['EffectBasePoints']])+spell[layout['EffectDieSides']]
if not 0<=amount<=32767:raise ValueError('Bounded source defense amount required')
new=deepcopy(n);new['Name_lang']=source_enchants.string(s[13]);new['HordeName_lang']='';new['EffectPointsMin']=[amount,0,0]
if new==n:continue
raw=encode(new,schema)
rows.append(dict(table_name='SpellItemEnchantment',table_hash=hex(table[0]),id=ident,record=new,wire_hex=raw.hex(),sha256=hashlib.sha256(raw).hexdigest(),policy='source-constant-defense-enchantment-overlay-v1',source_spell_id=s[10],source_record_sha256=canonical_sha256(list(s)),baseline_record_sha256=canonical_sha256(n)))
return dict(kind='source-defense-enchantment-batch',rows=rows,blocked=blocked,installed=False,engine_accepted=False,gameplay_verified=False)
def scalar_namespace(source_items,target_items,source_auras,target_auras,source_shared,target_shared,source_enums,target_enums):
"""Pin named item-stat, unit-stat and aura meanings before folding equip spells."""
proof=namespace(source_enums,target_enums)
item_stats={'MANA':0,'HEALTH':1,'AGILITY':3,'STRENGTH':4,'INTELLECT':5,'SPIRIT':6,'STAMINA':7}
stats={'STRENGTH':0,'AGILITY':1,'STAMINA':2,'INTELLECT':3,'SPIRIT':4}
auras={'MOD_STAT':29,'MOD_INCREASE_HEALTH':34,'MOD_INCREASE_ENERGY':35}
for label,paths,names,prefix in (
('item_stats',(source_items,target_items),item_stats,'ITEM_MOD_'),
('unit_stats',(source_shared,target_shared),stats,'STAT_'),
('auras',(source_auras,target_auras),auras,'SPELL_AURA_')):
for side,path in zip(('source','target'),paths):
data=path.read_bytes();text=data.decode()
for name,value in names.items():
if not re.search(r'\b'+prefix+name+r'\s*=\s*'+str(value)+r'\s*[,}]',text):
raise ValueError('Unreviewed enchant scalar namespace: '+label+'/'+name)
proof[label+'_'+side+'_sha256']=hashlib.sha256(data).hexdigest()
proof.update(scalar_policy='source-permanent-health-mana-primary-stat-enchants-v1',item_stats=item_stats,unit_stats=stats,auras=auras)
return proof
def constant_enchantment_rows(source_enchants,source_spells,native,schema,proof):
"""Batch permanent scalar enchant effects without invoking mismatched native spells.
Source EQUIP_SPELL with an unconditional permanent health/mana/primary-stat
aura becomes the matching native STAT effect. Direct resistance/primary-stat
effects retain their meanings. Proc, duration, scaling and unknown constraint
families remain explicitly deferred. No server state or item ownership changes.
"""
from copy import deepcopy
import struct
from turtle_data import spell_layout
from spell_passive_compat import encode,SUPPLEMENTAL_TABLES
if (proof.get('scalar_policy')!='source-permanent-health-mana-primary-stat-enchants-v1' or proof.get('types')!=dict(zip(TYPE_NAMES,range(7)))
or any(not re.fullmatch('[0-9a-f]{64}',proof.get(k,''))for k in ('source_sha256','target_sha256',*[label+'_'+side+'_sha256'for label in ('item_stats','unit_stats','auras')for side in ('source','target')]))):raise ValueError('Verified scalar namespaces required')
if source_enchants.fields!=24 or source_spells.fields!=173:raise ValueError('Reviewed enchant/spell DBC layouts required')
table=SUPPLEMENTAL_TABLES['SpellItemEnchantment']
from octo_client_data import canonical_sha256
if canonical_sha256(schema)!=table[2]:raise ValueError('Pinned native enchantment layout required')
dest={r['ID']:r for r in native}
if len(dest)!=len(native):raise ValueError('Duplicate target enchant IDs')
layout=spell_layout();signed=lambda x:struct.unpack('<i',struct.pack('<I',x))[0]
def fold(spell):
o=layout
allowed={o[k]for k in ('ID','Attributes','CastingTimeIndex','ProcChance','DurationIndex','RangeIndex','EquippedItemClass','Effect','EffectDieSides','EffectBaseDice','EffectBasePoints','ImplicitTargetA','EffectAura','EffectMiscValue','SpellIconID','StanceBarOrder')}
for key in ('Name_lang','NameSubtext_lang','Description_lang','AuraDescription_lang'):allowed.update(range(o[key],o[key]+9))
allowed.update(range(o['EffectChainAmplitude'],o['EffectChainAmplitude']+3))
if any(v and i not in allowed for i,v in enumerate(spell)):raise ValueError('equip spell has extra conditions, targets or effects')
if ([spell[o[k]]for k in ('Attributes','CastingTimeIndex','DurationIndex','RangeIndex','EquippedItemClass','Effect','ImplicitTargetA')]!=[192,1,21,1,0xffffffff,6,1]
or spell[o['StanceBarOrder']]not in (0,0xffffffff) or spell[o['ProcChance']]not in (0,100,101)
or any(v not in (0,0x3f800000)for v in spell[o['EffectChainAmplitude']:o['EffectChainAmplitude']+3])):
raise ValueError('equip spell is not an unconditional permanent self aura')
dice=spell[o['EffectDieSides']]
if dice not in (0,1) or spell[o['EffectBaseDice']]!=dice:raise ValueError('equip spell has variable dice')
amount=signed(spell[o['EffectBasePoints']])+dice;aura=spell[o['EffectAura']];misc=signed(spell[o['EffectMiscValue']])
if aura==29 and misc in range(5):stat=(4,3,7,5,6)[misc]
elif aura==34 and misc==0:stat=1
elif aura==35 and misc==0:stat=0
else:raise ValueError('equip spell scalar mechanic not reviewed')
if not 0<amount<=32767:raise ValueError('equip spell amount bound')
return 5,stat,amount
rows=[];blocked=[];unchanged=[]
for ident,s in sorted(source_enchants.by_id.items()):
n=dest.get(ident)
try:
if n is None:raise ValueError('missing target enchant baseline')
if s[23]:raise ValueError('source application slot flags require review')
if any(n.get(k,0)for k in ('Duration','Charges','Flags','ScalingClass','ScalingClassRestricted','RequiredSkillID','RequiredSkillRank','MinLevel','MaxLevel','ItemLevelMin','ItemLevelMax','TransmogUseConditionID','Field_12_1_5_69594_011','Field_12_1_5_69594_021')) or n['EffectScalingPoints']!=[0,0,0]:
raise ValueError('target duration, scaling or application constraints require review')
effects=[];args=[];amounts=[];folded=[]
for slot in range(3):
kind=s[1+slot];arg=s[10+slot];lo=signed(s[4+slot]);hi=signed(s[7+slot])
if kind==0:
if arg or lo or hi:raise ValueError('non-neutral unused effect slot')
effect,argument,amount=0,0,0
elif kind==3:
spell=source_spells.by_id.get(arg)
if spell is None:raise ValueError('source equip spell missing')
if lo or hi:raise ValueError('equip spell includes extra amount')
effect,argument,amount=fold(spell);folded.append(arg)
elif kind in (4,5):
if lo!=hi or not 0<=lo<=32767:raise ValueError('direct effect amount is variable or out of range')
if (kind==4 and arg not in range(7))or(kind==5 and arg not in (0,1,3,4,5,6,7)):raise ValueError('direct effect argument unreviewed')
effect,argument,amount=kind,arg,lo
else:raise ValueError('proc, damage or totem mechanic requires separate conversion')
effects.append(effect);args.append(argument);amounts.append(amount)
if not any(effects):raise ValueError('no scalar enchant effects')
new=deepcopy(n);new.update(Name_lang=source_enchants.string(s[13]),HordeName_lang='',Effect=effects,EffectArg=args,EffectPointsMin=amounts)
if not new['Name_lang']:raise ValueError('source enchant name missing')
if new==n:unchanged.append(ident);continue
raw=encode(new,schema)
rows.append(dict(table_name='SpellItemEnchantment',table_hash=hex(table[0]),id=ident,record=new,wire_hex=raw.hex(),sha256=hashlib.sha256(raw).hexdigest(),policy=proof['scalar_policy'],folded_source_spell_ids=folded,visuals_preserved_from_native=True))
except ValueError as error:blocked.append(dict(enchantment=ident,reason=str(error)))
return dict(rows=rows,blocked=blocked,unchanged=unchanged,source_count=len(source_enchants.by_id),namespace=proof,installed=False,engine_loaded=False,gameplay_verified=False)