Files
WoW-Hybrid-gateway/ops/spell_item_enchantment_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

216 lines
13 KiB
Python

"""Positive permanent item-enchantment definitions; never synthesize missing parents.
Reuse the scalar enchantment converter's exact child closure. An enchant ID is
not a damage amount: both named permanent-enchantment consumers ignore the
calculated damage and install that child into the permanent slot with zero duration.
"""
from copy import deepcopy
import hashlib
import math
import re
from pathlib import Path
import spell_crafting_compat as capture
import spell_passive_compat as codec
from octo_client_data import canonical_sha256
from spell_definition_common import REQUIRED_REFERENCE_TABLES
POLICY = 'positive-permanent-item-enchantment-with-source-exact-scalar-child-v1'
KIND = 'source-item-enchantment-definition-components'
def contract():
return dict(policy=POLICY, source_effect=53, native_effect=53,
source_item_target_flag=16, native_item_target_flag=16,
source_not_shapeshifted=65536, native_not_shapeshifted=65536,
permanent_slot_duration_ms=0, positive_native_parent_only=True,
source_exact_scalar_child_required=True,
unused_source_cast_ui=[0, 3], ignored_nondamage_coefficient=[-1, 0])
def literal(text, name):
uncommented = re.sub(r'/\*.*?\*/|//[^\n]*', '', text, flags=re.S)
matches = re.findall(r'\b' + re.escape(name) + r'\s*=\s*(0x[0-9a-fA-F]+|[0-9]+)\s*[,}]', uncommented)
if len(matches) != 1:
raise ValueError('Unique named literal enum required: ' + name)
return int(matches[0], 0)
def method(text, signature):
start = text.index(signature)
opening = text.index('{', start)
depth = 1
end = opening + 1
while depth and end < len(text):
depth += (text[end] == '{') - (text[end] == '}')
end += 1
if depth:
raise ValueError('Incomplete permanent enchantment consumer')
return text[start:end]
def namespace(paths):
required = {'source_spell_enum', 'target_spell_enum', 'source_target_enum',
'target_target_enum', 'source_entry', 'source_consumer', 'target_consumer'}
if set(paths) != required:
raise ValueError('Complete named permanent enchantment proof required')
texts = {key: Path(value).read_text() for key, value in paths.items()}
witnesses = [('source_spell_enum', 'SPELL_EFFECT_ENCHANT_ITEM', 53),
('target_spell_enum', 'SPELL_EFFECT_ENCHANT_ITEM', 53),
('source_target_enum', 'TARGET_FLAG_ITEM', 16),
('target_target_enum', 'TARGET_FLAG_ITEM', 16),
('source_spell_enum', 'SPELL_ATTR_NOT_SHAPESHIFT', 65536),
('target_spell_enum', 'SPELL_ATTR0_NOT_SHAPESHIFTED', 65536)]
if any(literal(texts[key], name) != value for key, name, value in witnesses):
raise ValueError('Permanent enchantment namespace changed')
if not re.search(r'//\s*uint32\s+castUI;[^\n]*not used', texts['source_entry']):
raise ValueError('Unused source CastUI proof changed')
source = method(texts['source_consumer'], 'void Spell::EffectEnchantItemPerm(')
target = method(texts['target_consumer'], 'void Spell::EffectEnchantItemPerm()')
if (not re.search(r'enchant_id\s*=\s*m_spellInfo->EffectMiscValue\[eff_idx\]', source)
or not re.search(r'enchant_id\s*=\s*effectInfo->MiscValue', target)
or re.search(r'\b(?:damage|CalculateDamage|CalcValue)\b', source + target)
or not re.search(r'SetEnchantment\(PERM_ENCHANTMENT_SLOT,\s*enchant_id,\s*0,\s*0\)', source)
or not re.search(r'SetEnchantment\(PERM_ENCHANTMENT_SLOT,\s*enchant_id,\s*0,\s*0,', target)):
raise ValueError('Permanent enchantment child/no-damage contract changed')
return dict(contract=contract(), inputs={key: dict(path=str(paths[key]),
sha256=hashlib.sha256(Path(paths[key]).read_bytes()).hexdigest()) for key in sorted(paths)},
consumers={key: hashlib.sha256(value.encode()).hexdigest()
for key, value in [('source', source), ('target', target)]})
def require_contract(proof):
if not isinstance(proof, dict) or proof.get('contract') != contract():
raise ValueError('Reviewed named permanent enchantment contract required')
def source_spell(dbc, raw, offsets, *, semantics):
require_contract(semantics)
expected = capture.disk_fields(dbc, raw.get('entry'), offsets)
adjusted = deepcopy(raw)
differences = []
# Only the active permanent effect can use the reviewed no-damage default.
if (raw.get('effect1') == 53 and raw.get('effect2') == raw.get('effect3') == 0
and expected.get('effectBonusCoefficient1') == -1
and type(raw.get('effectBonusCoefficient1')) in (int, float)
and raw['effectBonusCoefficient1'] == 0):
adjusted['effectBonusCoefficient1'] = -1
differences.append(dict(field='effectBonusCoefficient1', source_client=-1,
local_server=0, policy='permanent-enchant-consumer-ignores-damage'))
capture.source_spell(dbc, adjusted, offsets)
validate_source(raw, semantics=semantics)
return deepcopy(raw), differences
def validate_source(source, *, semantics):
require_contract(semantics)
expected_keys = set(capture.SCALARS) | {prefix + str(i + 1) for prefix, _, count, _ in capture.ARRAYS for i in range(count)} | {prefix + str(i + 1) for prefix, _, _ in capture.EFFECTS for i in range(3)} | {key for key, _ in capture.TAIL} | {key + suffix for key, _ in capture.TEXTS for suffix in ('', 'Flags')} | {'equippedItemClass', 'equippedItemSubClassMask', 'equippedItemInventoryTypeMask', 'spellVisual1', 'spellVisual2', 'spellIconId', 'activeIconId', 'spellPriority', 'spellFamilyFlags', 'minTargetLevel', 'customFlags', 'script_name'} | {f'effectBonusCoefficient{i}' for i in range(1, 4)}
if not isinstance(source, dict) or set(source) != expected_keys:
raise ValueError('Complete captured source definition required')
text = {'name', 'nameSubtext', 'description', 'auraDescription'}
allowed = text | {key + 'Flags' for key in text} | {
'entry', 'attributes', 'castUI', 'castingTimeIndex', 'rangeIndex', 'procChance',
'equippedItemClass', 'equippedItemSubClassMask', 'equippedItemInventoryTypeMask',
'interruptFlags', 'spellIconId', 'spellVisual1', 'spellLevel', 'stanceBarOrder',
'targets', 'effect1', 'effectBaseDice1', 'effectDieSides1', 'effectBasePoints1',
'effectMiscValue1', *[f'effectBonusCoefficient{i}' for i in range(1, 4)],
*[f'dmgMultiplier{i}' for i in range(1, 4)]}
if any(value not in (0, '') for key, value in source.items() if key not in allowed):
raise ValueError('Unreviewed permanent enchantment condition/effect')
for key, value in source.items():
if key in text or key == 'script_name':
if not isinstance(value, str) or '\0' in value or len(value.encode()) > 4096:
raise ValueError('Invalid source enchantment text')
elif type(value) not in (int, float) or not math.isfinite(value) or type(value) is bool:
raise ValueError('Invalid source enchantment scalar')
if (source['effect1'] != 53 or source['attributes'] not in (0, 65536)
or source['targets'] != 16 or source['castUI'] not in (0, 3)
or source['castingTimeIndex'] not in (1, 14) or source['rangeIndex'] != 1
or source['procChance'] != 101 or source['interruptFlags'] not in (0, 15)
or source['equippedItemClass'] not in (2, 4) or source['equippedItemSubClassMask'] <= 0
or source['equippedItemInventoryTypeMask'] < 0
or source['stanceBarOrder'] not in (-1, 0) or source['spellLevel'] not in (0, 5)
or source['effectDieSides1'] not in (0, 1) or source['effectBaseDice1'] not in (0, 1)
or source['effectBasePoints1'] not in (-1, 0)
or source['effectBonusCoefficient1'] not in (-1, 0)
or any(source[f'effectBonusCoefficient{i}'] != -1 for i in (2, 3))
or source['dmgMultiplier1'] != 1
or any(source[f'dmgMultiplier{i}'] not in (0, 1) for i in (2, 3))):
raise ValueError('Unreviewed permanent enchantment shape')
codec.integer(source['entry'], 1, 0x7fffffff, 'source enchantment spell')
codec.integer(source['effectMiscValue1'], 1, 0x7fffffff, 'source enchantment child')
return source['effectMiscValue1']
def positive(source, native, *, semantics, scalar_children):
child = validate_source(source, semantics=semantics)
if child not in scalar_children:
raise ValueError('Exact source scalar enchantment child not proved')
if any(table not in native for table in REQUIRED_REFERENCE_TABLES):
raise ValueError('Complete native positive enchantment context required')
ident = source['entry']
selected = {table: [row for row in native[table]
if (row['ID'] if table in ('Spell', 'SpellName') else row.get('SpellID')) == ident]
for table in REQUIRED_REFERENCE_TABLES}
def single(table, required=False):
rows = selected[table]
if len(rows) > 1 or required and not rows:
raise ValueError('Missing/duplicate enchantment parent context: ' + table)
if rows:
codec.integer(rows[0]['ID'], 1, 0x7fffffff, 'positive native child row')
return rows[0] if rows else None
name = single('SpellName', True)
text = single('Spell', True)
misc = single('SpellMisc', True)
effect = single('SpellEffect', True)
if name['Name_lang'] != source['name']:
raise ValueError('Same-ID native enchantment name collision')
attrs = misc['Attributes']
if (len(attrs) != 17 or attrs[:5] != [source['attributes'], 0, 0, 0, 0]
or any(value for index, value in enumerate(attrs[5:], 5) if index != 15)
or attrs[15] & ~0x2000):
raise ValueError('Native enchantment attribute semantics differ')
expected_misc = dict(codec.NEW_MISC_NEUTRAL, Attributes=attrs,
CastingTimeIndex=source['castingTimeIndex'], DurationIndex=0,
RangeIndex=source['rangeIndex'])
if set(misc) != set(expected_misc) | {'ID', 'SpellID', 'SpellIconFileDataID'} or any(misc[key] != value for key, value in expected_misc.items()):
raise ValueError('Native enchantment timing/school/context differs')
codec.integer(misc['SpellIconFileDataID'], 1, 0x7fffffff, 'retained native icon')
expected_effect = dict(codec.NEW_EFFECT_NEUTRAL, Effect=53, EffectAura=0,
EffectIndex=0, EffectBasePointsF=0, ImplicitTarget=[0, 0],
EffectMiscValue=[child, 0])
if set(effect) != set(expected_effect) | {'ID', 'SpellID'} or any(effect[key] != value for key, value in expected_effect.items()):
raise ValueError('Native permanent enchantment effect differs')
for table in REQUIRED_REFERENCE_TABLES:
if table in ('SpellName', 'Spell', 'SpellMisc', 'SpellEffect'):
continue
row = single(table, table in ('SpellEquippedItems', 'SpellTargetRestrictions', 'SpellXSpellVisual'))
if row is None:
if table == 'SpellLevels' and source['spellLevel'] or table == 'SpellInterrupts' and source['interruptFlags']:
raise ValueError('Missing source nonneutral enchantment context: ' + table)
continue
values = {key: value for key, value in row.items() if key not in ('ID', 'SpellID')}
if table == 'SpellEquippedItems':
expected = dict(EquippedItemClass=source['equippedItemClass'],
EquippedItemSubclass=source['equippedItemSubClassMask'],
EquippedItemInvTypes=source['equippedItemInventoryTypeMask'])
elif table == 'SpellTargetRestrictions':
expected = dict(DifficultyID=0, ConeDegrees=0, Width=0, MaxTargetLevel=0,
MaxTargets=0, TargetCreatureType=0, Targets=16)
elif table == 'SpellXSpellVisual':
expected = dict(DifficultyID=0, SpellVisualID=source['spellVisual1'], Probability=1,
Flags2=0, Priority=1, SpellIconFileID=0, ActiveIconFileID=0,
ViewerUnitConditionID=0, ViewerPlayerConditionID=0,
CasterUnitConditionID=0, CasterPlayerConditionID=0)
elif table == 'SpellShapeshift':
expected = dict(ShapeshiftExclude=[0, 0], ShapeshiftMask=[0, 0], StanceBarOrder=0)
elif table in codec.CHILD_NEUTRAL:
expected = deepcopy(codec.CHILD_NEUTRAL[table])
if table == 'SpellAuraOptions':
expected['ProcChance'] = source['procChance']
elif table == 'SpellLevels':
expected['SpellLevel'] = source['spellLevel']
elif table == 'SpellInterrupts':
expected['InterruptFlags'] = source['interruptFlags']
else:
raise ValueError('Nonneutral enchantment dependency: ' + table)
if values != expected:
raise ValueError('Native source enchantment context differs: ' + table)
return dict(spell_id=ident, source_record_sha256=canonical_sha256(source),
source_enchantment_id=child, native_enchantment_id=child,
retained_icon_file_id=misc['SpellIconFileDataID'], source_definition=deepcopy(source),
definition_policy=POLICY, installed=False, engine_accepted=False,
gameplay_verified=False), text