Files
WoW-Hybrid-gateway/ops/spell_set_modifier_compat.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

155 lines
16 KiB
Python

"""Source-owned permanent flat/percent set modifiers with identity-derived masks.
No source bit positions are copied into target affect masks. Unknown operations,
nonzero parent masks, triggered/mixed effects and incomplete inventories stay held.
The server remains authoritative for set activation and modified spell execution.
"""
from pathlib import Path
from copy import deepcopy
import hashlib,re
from octo_client_data import canonical_sha256
from spell_passive_compat import integer,CONDITIONS,NEW_EFFECT_NEUTRAL,new_registry_values,verified_spell_icon,BUILD,SCHEMA
from spell_definition_common import checked_constant_source,review_effect_shape,review_new_timing,new_definition_records,REQUIRED_REFERENCE_TABLES,NEW_DEFINITION_CHILD_TABLES
from spell_affect_compat import derive
from item_batch_stage import available_index
POLICY='permanent-set-flat-percent-modifier-with-identity-affect-v1'
FAMILY_POLICY='named-all-class-zero-own-mask-set-modifier-v1'
PINS={'source_affect':'c28a62b9abc6583e7c92450bc48dd88f3f84a40cc5962f5e135bb6daa6a6a255','source_op':'fd1c65c0266b77a310c066bc3ccce86fe39f73a6cd10f67192d419009f95ead1','target_op':'9149582d4020bfc5d4a537512ad48b836c4bb47a33efc49841625475b42a6c08','source_aura':'ed7f67babe916cbbf91f7a1f1a9a9af694a2469d2e07eb10e94f0ae883678cb8','target_aura':'1784b495ea9704bbe12223c2ad42d9d5fea7d320f0dc6c0055cd090cb7e5498b','source_family':'c35debb8623259cd4b46ed2d393403ad4572e4dd618141e98e333cd3c4b753f4','target_family':'9b0e2ad90eea77c961b00f1fc482e9d9e521aa85c58b63863a35d3a338a31799'}
# Source custom31/32/33 have unrelated target meanings and are not mapped.
OPERATIONS=(('DAMAGE','HealingAndDamage',0,0),('DURATION','Duration',1,1),('THREAT','Hate',2,2),('CHARGES','ProcCharges',4,4),('RANGE','Range',5,5),('RADIUS','Radius',6,6),('CRITICAL_CHANCE','CritChance',7,7),('ALL_EFFECTS','Points',8,8),('CASTING_TIME','ChangeCastTime',10,10),('COOLDOWN','Cooldown',11,11),('COST','PowerCost0',14,14),('CRIT_DAMAGE_BONUS','CritDamageAndHealing',15,15),('RESIST_MISS_CHANCE','HitChance',16,16),('JUMP_TARGETS','ChainTargets',17,17),('CHANCE_OF_SUCCESS','ProcChance',18,18),('ACTIVATION_TIME','Period',19,19),('DOT','PeriodicHealingAndDamage',22,22),('MULTIPLE_VALUE','Amplitude',27,27))
FAMILIES={'SPELLFAMILY_'+name:value for name,value in [('MAGE',3),('WARRIOR',4),('WARLOCK',5),('PRIEST',6),('DRUID',7),('ROGUE',8),('HUNTER',9),('PALADIN',10),('SHAMAN',11)]}
ATTRS=(('SPELL_ATTR_IS_ABILITY','SPELL_ATTR0_IS_ABILITY',16),('SPELL_ATTR_PASSIVE','SPELL_ATTR0_PASSIVE',64),('SPELL_ATTR_HIDDEN_CLIENTSIDE','SPELL_ATTR0_DO_NOT_DISPLAY_SPELLBOOK_AURA_ICON_COMBAT_LOG',128),('SPELL_ATTR_HIDE_IN_COMBAT_LOG','SPELL_ATTR0_DO_NOT_LOG',256),('SPELL_ATTR_DONT_AFFECT_SHEATH_STATE','SPELL_ATTR0_DO_NOT_SHEATH',0x40000))
def _named(text,name,value):
if not re.search(r'\b'+name+r'\s*=\s*(?:'+str(value)+r'|0[xX]0*'+format(value,'x')+r')\s*[,}]',text,re.I):raise ValueError('Named set modifier enum differs: '+name)
def contract():
return dict(policy=POLICY,header_sha256=dict(PINS),operations=[dict(source_name='SPELLMOD_'+s,target_name=t,source_value=a,target_value=b)for s,t,a,b in OPERATIONS],auras=[dict(source_name='SPELL_AURA_ADD_'+x+'_MODIFIER',target_name='SPELL_AURA_ADD_'+x+'_MODIFIER',source_value=v,target_value=v)for x,v in [('FLAT',107),('PCT',108)]],families=dict(FAMILIES),attributes=[dict(source_name=s,target_name=t,source_value=v,target_value=v)for s,t,v in ATTRS])
def namespace(paths):
if set(paths)!=set(PINS):raise ValueError('Complete set modifier namespace inputs required')
text={}
for role,p in paths.items():
b=Path(p).read_bytes()
if hashlib.sha256(b).hexdigest()!=PINS[role]:raise ValueError('Pinned set modifier namespace changed: '+role)
text[role]=b.decode()
if 'mSpellAffectMap.find((spellId<<8) + effectId)'not in text['source_affect']or 'return spellEntry->EffectItemType[effectId];'not in text['source_affect']:raise ValueError('Source override/fallback affect consumer changed')
for s,t,a,b in OPERATIONS:_named(text['source_op'],'SPELLMOD_'+s,a);_named(text['target_op'],t,b)
for x,v in [('FLAT',107),('PCT',108)]:
for role in ('source_aura','target_aura'):_named(text[role],'SPELL_AURA_ADD_'+x+'_MODIFIER',v)
for name,v in FAMILIES.items():
for role in ('source_family','target_family'):_named(text[role],name,v)
for s,t,v in ATTRS:_named(text['source_op'],s,v);_named(text['target_family'],t,v)
return contract()
def validate_namespace(proof):
if proof!=contract()or canonical_sha256(proof)!=canonical_sha256(contract()):raise ValueError('Exact named set modifier namespace required')
def validate_family(value):
if not isinstance(value,dict)or set(value)!={'policy','name','source_id','target_id','source_mask','target_mask'}or value['policy']!=FAMILY_POLICY:raise ValueError('Explicit all-class modifier family identity required')
v=FAMILIES.get(value['name'])
if v is None:raise ValueError('Unsupported modifier class family')
for k in ('source_id','target_id'):integer(value[k],v,v,'named modifier family')
for k,n in [('source_mask',2),('target_mask',4)]:
if not isinstance(value[k],list)or len(value[k])!=n or any(type(x)is not int or x for x in value[k]):raise ValueError('Nonzero parent family masks require separate conversion')
return v
def captured_family(raw,disk,offsets,proof):
validate_namespace(proof);value=integer(raw['spellFamilyName'],1,255,'source modifier family');name=next((n for n,v in FAMILIES.items()if v==value),None)
words=list(disk[offsets['SpellClassMask']:offsets['SpellClassMask']+2])
if name is None or raw['spellFamilyFlags']!=0 or disk[offsets['SpellClassSet']]!=value or words!=[0,0]:raise ValueError('Server/captured named modifier family or own mask differs')
result=dict(policy=FAMILY_POLICY,name=name,source_id=value,target_id=FAMILIES[name],source_mask=words,target_mask=[0]*4);validate_family(result);return result
def source_spell(dbc,raw,offsets,*,semantics):
src=checked_constant_source(dbc,raw,offsets,set_modifier_context=semantics);validate_source(src);return src
def validate_source(src):
validate_namespace(src.get('set_modifier_context'));validate_family(src.get('class_family'));integer(src.get('entry'),1,0x7fffffff,'source set modifier')
for k,n in [('attributes',5),('power',6),('equippedItem',3),('visuals',2)]:
if not isinstance(src.get(k),list)or len(src[k])!=n or any(type(x)is not int for x in src[k]):raise ValueError('Complete typed modifier groups required')
if src['attributes']not in([192,0,0,0,0],[448,0,0,0,0],[464,0,0,0,0],[262608,0,0,0,0]):raise ValueError('Unreviewed modifier presentation flags')
if tuple(src.get(k)for k in ('school','castingTimeIndex','durationIndex','rangeIndex','speed'))!=(0,1,21,1,0):raise ValueError('Unreviewed modifier school or timing')
if src['power']!=[0]*6 or src['equippedItem']!=[-1,0,0]or src['visuals']!=[0,0]:raise ValueError('Unreviewed modifier resources/equipment/visuals')
if set(src.get('conditions',{}))!=set(CONDITIONS)or any(type(v)is not int or (v not in(0,101)if k=='procChance'else v!=0)for k,v in src['conditions'].items()):raise ValueError('Conditional or triggered modifier requires separate policy')
if src.get('timing')!={k:0 for k in ('recoveryTime','categoryRecoveryTime','startRecoveryCategory','startRecoveryTime')}:raise ValueError('Modifier cooldown must be neutral')
if set(src.get('levels',{}))!={'spellLevel','baseLevel','maxLevel'}:raise ValueError('Complete modifier levels required')
for v in src['levels'].values():integer(v,0,65535,'modifier level')
integer(src.get('spellIconId'),1,0x7fffffff,'modifier source icon')
fallbacks=src.get('source_effect_affect_fallbacks')
if not isinstance(fallbacks,list)or len(fallbacks)!=3 or any(type(v)is not int or not 0<=v<=0xffffffff for v in fallbacks):raise ValueError('Complete source effect affect fallbacks required')
if not isinstance(src.get('effects'),list)or len(src['effects'])!=3:raise ValueError('Complete modifier effect slots required')
active=[];operations={a for _,_,a,_ in OPERATIONS}
for i,e in enumerate(src['effects']):
review_effect_shape(e)
if not e[0]:
if e!=[0]*11+[-1]or fallbacks[i]:raise ValueError('Nonneutral empty modifier effect')
continue
if e[:2]not in([6,107],[6,108])or e[3:7]!=[1,1,0,0]or e[8:11]!=[1,0,0]or e[11]not in(-1,0):raise ValueError('Mixed, scaled or targeted modifier effect requires separate policy')
if e[7]not in operations:raise ValueError('Source modifier operation has no reviewed named target equivalent')
integer(e[2]+1,-0xffffff,0xffffff,'signed flat/percent modifier amount');active.append(i)
if not active:raise ValueError('No flat or percent modifier effects')
for k in ('name','nameSubtext','description','auraDescription'):
if not isinstance(src.get(k),str)or '\0'in src[k]or len(src[k].encode())>4096:raise ValueError('Modifier text bound')
# Token rendering is a separate translation layer; preserve source text exactly.
if not src['name']:raise ValueError('Named modifier source required')
return active
def effective_affect_mask(src,index,snapshot):
if not isinstance(snapshot,dict)or snapshot.get('kind')!='local-read-only-exact-set-modifier-affect-snapshot'or snapshot.get('named_columns')!=['entry','effectId','SpellFamilyMask']or snapshot.get('equal')is not True or snapshot.get('mutated')is not False or snapshot.get('first_sha256')!=snapshot.get('second_sha256')or not re.fullmatch('[a-f0-9]{64}',str(snapshot.get('first_sha256'))):raise ValueError('Pinned equal read-only affect snapshot required')
ids=snapshot.get('spell_ids')
if not isinstance(ids,list)or not 1<=len(ids)<=4096 or len(set(ids))!=len(ids)or any(type(v)is not int or v<=0 for v in ids)or src['entry']not in ids:raise ValueError('Complete source affect snapshot scope required')
overrides={}
for row in snapshot.get('rows',[]):
if not isinstance(row,dict)or set(row)!={'entry','effect_index','source_mask'}:raise ValueError('Typed source affect override required')
ident=row['entry'];i=row['effect_index'];mask=row['source_mask']
if type(ident)is not int or ident not in ids or type(i)is not int or not 0<=i<=2 or type(mask)is not int or not 0<=mask<=0xffffffffffffffff or (ident,i)in overrides:raise ValueError('Ambiguous source affect override')
overrides[ident,i]=mask
return overrides.get((src['entry'],index),src['source_effect_affect_fallbacks'][index])
def review(component,spell):
proof=component['modifier_namespace'];validate_namespace(proof);src=spell['source_definition'];indices=validate_source(src)
if src['set_modifier_context']!=proof:raise ValueError('Modifier source namespace differs')
family=validate_family(src['class_family']);inputs=component['affect_inventory'];mappings=spell['affect_mappings']
if set(mappings)!={str(i)for i in indices}:raise ValueError('Complete per-effect source affect masks required')
for i in indices:
source_mask=effective_affect_mask(src,i,component['source_affect_snapshot'])
actual=derive(inputs['source'],inputs['target'][str(family)],family,source_mask)
if actual!=mappings[str(i)]:raise ValueError('Derived modifier affect mask differs')
return indices
def native_mask_words(words):
if not isinstance(words,list)or len(words)!=4 or any(type(v)is not int or not 0<=v<=0xffffffff for v in words):raise ValueError('Four unsigned derived mask words required')
return [v if v<0x80000000 else v-0x100000000 for v in words]
def new_component(sources,native,schemas,maxima,registry,*,source_tables,target_icon_names,new_icon_ids,icon_assets,read_icon,modifier_namespace,affect_inventory,source_affect_snapshot):
if not isinstance(sources,list)or not 1<=len(sources)<=4096 or len({s['entry']for s in sources})!=len(sources):raise ValueError('Unique bounded set modifier sources required')
if any(t not in native for t in (*REQUIRED_REFERENCE_TABLES,'SpellCastTimes','SpellDuration','SpellRange')):raise ValueError('Complete native modifier references required')
if set(new_icon_ids)!={str(s['entry'])for s in sources}:raise ValueError('Explicit modifier icon identities required')
review_new_timing(source_tables,native,21);validate_namespace(modifier_namespace);registry=deepcopy(registry);available=available_index(icon_assets)
occupied={t:{r['ID']for r in native[t]}for t in NEW_DEFINITION_CHILD_TABLES};new_registry_values(registry,maxima,occupied,tables=NEW_DEFINITION_CHILD_TABLES)
result=dict(kind='source-set-modifier-definition-candidates',build=BUILD,schema=SCHEMA,definition_policy=POLICY,modifier_namespace=deepcopy(modifier_namespace),affect_inventory=deepcopy(affect_inventory),source_affect_snapshot=deepcopy(source_affect_snapshot),records=[],spells=[],id_remapping=False,dependency_complete=False,installable=False,installed=False,engine_accepted=False,gameplay_verified=False)
for src in sorted(sources,key=lambda r:r['entry']):
indices=validate_source(src);ident=src['entry'];family=validate_family(src['class_family'])
for t in REQUIRED_REFERENCE_TABLES:
if any((r.get('ID')if t in ('Spell','SpellName')else r.get('SpellID'))==ident for r in native[t]):raise ValueError('Set modifier has positive native reference: '+t)
spell=dict(spell_id=ident,source_definition=deepcopy(src),source_record_sha256=canonical_sha256(src),class_family=deepcopy(src['class_family']),levels=deepcopy(src['levels']),effect_indices=indices,affect_mappings={str(i):derive(affect_inventory['source'],affect_inventory['target'][str(family)],family,effective_affect_mask(src,i,source_affect_snapshot))for i in indices},known_spells_modified=False,engine_accepted=False)
review(result,spell);fid,asset=verified_spell_icon(src,new_icon_ids,source_tables['SpellIcon'],target_icon_names,available,read_icon)
ops={a:b for _,_,a,b in OPERATIONS};effects={i:dict(deepcopy(NEW_EFFECT_NEUTRAL),EffectAura=src['effects'][i][1],EffectBasePointsF=src['effects'][i][2]+1,EffectMiscValue=[ops[src['effects'][i][7]],0],EffectSpellClassMask=native_mask_words(spell['affect_mappings'][str(i)]['target_mask']))for i in indices}
result['records']+=new_definition_records(src,effects,fid,schemas,maxima,registry,occupied,allocation_prefix='new-source-set-modifier-definition');spell['icon_asset']=dict(file_data_id=fid,**asset);result['spells'].append(spell)
result['child_id_registry']=registry;return result
def review_record(src,spell_metadata,row):
"""Exact per-row semantics after the component's independent mask review.
The composer separately owns source/namespace/derived-mask revalidation,
wire/schema/ID allocation checks and complete required-table-set enforcement.
"""
from spell_passive_compat import NEW_MISC_NEUTRAL,CHILD_NEUTRAL
indices=validate_source(src);family=validate_family(src['class_family']);ident=src['entry'];table=row.get('table_name');record=row.get('record');rid=row.get('id')
if not isinstance(record,dict)or row.get('source_spell_id')!=ident or record.get('ID')!=rid or spell_metadata.get('spell_id')!=ident or spell_metadata.get('effect_indices')!=indices:raise ValueError('Set modifier record or metadata identity differs')
if table=='SpellName':expected=dict(ID=ident,Name_lang=src['name'])
elif table=='Spell':expected=dict(ID=ident,NameSubtext_lang=src['nameSubtext'],Description_lang=src['description'],AuraDescription_lang=src['auraDescription'])
elif table=='SpellMisc':expected=dict(deepcopy(NEW_MISC_NEUTRAL),ID=rid,SpellID=ident,Attributes=src['attributes']+[0]*12,SpellIconFileDataID=spell_metadata['icon_asset']['file_data_id'],DurationIndex=src['durationIndex'],SchoolMask=1<<src['school'])
elif table=='SpellEquippedItems':expected=dict(ID=rid,SpellID=ident,EquippedItemClass=src['equippedItem'][0],EquippedItemSubclass=src['equippedItem'][1],EquippedItemInvTypes=src['equippedItem'][2])
elif table=='SpellClassOptions':expected=dict(ID=rid,SpellID=ident,ModalNextSpell=0,SpellClassSet=family,SpellClassMask=[0]*4)
elif table=='SpellLevels':expected=dict(CHILD_NEUTRAL['SpellLevels'],ID=rid,SpellID=ident,SpellLevel=src['levels']['spellLevel'],BaseLevel=src['levels']['baseLevel'],MaxLevel=src['levels']['maxLevel'])
elif table=='SpellEffect':
i=record.get('EffectIndex')
if type(i)is not int or i not in indices:raise ValueError('Set modifier effect index differs')
operations={a:b for _,_,a,b in OPERATIONS};expected=dict(deepcopy(NEW_EFFECT_NEUTRAL),ID=rid,SpellID=ident,EffectIndex=i,EffectAura=src['effects'][i][1],EffectBasePointsF=src['effects'][i][2]+1,EffectMiscValue=[operations[src['effects'][i][7]],0],EffectSpellClassMask=native_mask_words(spell_metadata['affect_mappings'][str(i)]['target_mask']))
else:raise ValueError('Unreviewed set modifier table: '+str(table))
if record!=expected:raise ValueError('Set modifier source record semantics differ: '+table)
return True