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

1621 lines
87 KiB
Python

#!/usr/bin/env python3
"""Class trainer/talent spell presentation hotfixes for the pinned 70334 client.
Scope: every Octo spell taught through a class SkillLine (SkillLine category 7),
every Talent rank, server spell_chain ranks of talent chains, and the closure
of trigger/description references. Each in-scope source spell is compared to
the effective client state (native DB2 export overlaid by the current package)
and only differing presentation / client-definition fields are emitted, as
same-ID overrides of the native record or as new allocated child records.
REA contract reused (no new binary analysis):
* SpellMisc.Attributes[15] bit 0x2000 selects the flat player tooltip value;
without it $s is scaled by ExpectedStat (concussion 6117 = 2603 * 235%).
A/B verified in game on 12636-row checkpoint (DEVELOPMENT_BACKLOG.md).
* $s/$m/$M read SpellEffect.EffectBasePointsF with Variance, base*(1 +/- |v|/2)
(spell_definition_common.review_existing_effect_range).
* $d/$o/$t read SpellMisc.DurationIndex -> SpellDuration and
SpellEffect.EffectAuraPeriod; $h/$n/$u read SpellAuraOptions.
* Spell family masks are a different namespace (cooldown family routes), so
SpellClassOptions is never written here.
* Visuals/sounds: SpellXSpellVisual -> SpellVisual -> events/kits -> SoundKit.
Only native visual IDs proven by shared vanilla visual identity are reused.
Nothing here installs, grants spells or changes server behaviour.
"""
import argparse
from collections import Counter, defaultdict
from copy import deepcopy
import hashlib
import json
import math
from pathlib import Path
import re
import struct
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
import spell_passive_compat as codec # noqa: E402
from spell_shield_slam_compat import EXTRA_TABLES as ACTIVE_TABLES # noqa: E402
from octo_client_data import canonical_sha256 # noqa: E402
from turtle_data import DBC, spell_layout, spell_tooltip_graph, read_spell_chain # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
POLICY = 'source-class-spell-presentation-v1'
# Additional reviewed 70334 layouts (table hash, layout hash, serialized field
# sequence sha256), pinned from the actual DB2 headers and DBD definitions.
CLASS_TABLES = {
'SkillLine': (3040725462, 1734549884, '625446338a0fd5e9294ffed774de5f256b47dbde3a147b065a76582e8229f814'),
'SpellDuration': (0xb423fa7a, 0xa931bd2b, '497bba0611673aba1b5eed0e57e29ac21d29fe1a5409d55b890c3287cd11499f'),
'SpellCastTimes': (0xfdba5a66, 0x75b6bd3a, '8fdee04a7d1ac7de954be0b18c00e655de577460515a7bd4a4819b4c3bb05050'),
'SpellRange': (0xe051a69c, 0xada13705, '34da39ff61d859a88b5bb7f969ba6c16ef1b4827a075b25ecee1ed436be0eaaf'),
'SpellRadius': (0xab7e4841, 0xf9a913ee, 'a074772481e5194a7850072e2c4d59dda641dd2d536729296e862a8316c336b2'),
'SpellTargetRestrictions': (0xe064a75c, 0x1eab753e, 'ad128bb24efcc2b0775857bd3979f39f3692557d1e57255d626ae8c551d5b04a'),
}
SOURCE_SHAPES = {'Spell': 173, 'SkillLine': 22, 'SkillLineAbility': 15, 'Talent': 21,
'SpellDuration': 4, 'SpellCastTimes': 4, 'SpellRange': 22, 'SpellRadius': 4,
'SpellIcon': 2, 'SpellVisual': 16}
CLASS_SKILL_CATEGORY = 7
# Octo files account collections under category 7; they are not trainer/talent
# class skills (all their abilities carry ClassMask 0).
NON_CLASS_LINE_NAMES = ('Companions', 'Mounts', 'Glyphs', 'Toys', 'VFX')
FLAT_TOOLTIP_ATTR15 = 0x2000
NATIVE_TABLES = ('Spell', 'SpellName', 'SpellMisc', 'SpellEffect', 'SpellAuraOptions', 'SpellCooldowns',
'SpellPower', 'SpellLevels', 'SpellCategories', 'SpellDuration', 'SpellCastTimes',
'SpellRange', 'SpellRadius', 'SpellXSpellVisual', 'SpellCategory', 'SpellVisual',
'SpellTargetRestrictions', 'SkillLineAbility', 'SkillLine')
CHILD_BY_SPELL = ('SpellMisc', 'SpellAuraOptions', 'SpellCooldowns', 'SpellLevels', 'SpellCategories',
'SpellXSpellVisual', 'SpellTargetRestrictions')
QUESTION_MARK_ICON = 134400
def signed(n):
return struct.unpack('<i', struct.pack('<I', n))[0]
def floating(n):
value = struct.unpack('<f', struct.pack('<I', n))[0]
if not math.isfinite(value):
raise ValueError('Nonfinite source float')
return value
def close(a, b):
return abs(float(a) - float(b)) <= 1e-4 * max(1.0, abs(float(a)), abs(float(b)))
# ---------------------------------------------------------------- schemas
def table_metadata(table):
for registry in (codec.TABLES, codec.SUPPLEMENTAL_TABLES, ACTIVE_TABLES):
if table in registry:
return registry[table]
return CLASS_TABLES[table]
def raw_schema(dbd_dir, table, *, metadata=None):
"""Field sequence for a reviewed layout without the digest gate (pin discovery)."""
metadata = table_metadata(table) if metadata is None else metadata
text = (Path(dbd_dir) / (table + '.dbd')).read_text()
kinds = {}
for line in text.split('LAYOUT', 1)[0].splitlines():
match = re.match(r'(int(?:<[^>]+>)?|float|locstring|string)\s+(\w+)\??', line)
if match:
kinds[match[2]] = match[1].split('<')[0]
marker = f'LAYOUT {metadata[1]:08X}\n'
if text.count(marker) != 1:
raise ValueError('Missing reviewed native layout: ' + table)
block = re.split(r'\r?\n[ \t]*\r?\n', text.split(marker, 1)[1], maxsplit=1)[0]
if codec.BUILD not in block:
raise ValueError('Native build differs: ' + table)
result = []
for line in block.splitlines():
if not line or line.startswith(('BUILD', 'COMMENT')) or line.startswith('$noninline,id$ID'):
continue
line = re.sub(r'^\$[^$]+\$', '', line)
match = re.fullmatch(r'(\w+)(?:<(u?)(8|16|32|64)>)?(?:\[(\d+)\])?', line)
if not match:
raise ValueError('Unreviewed native field syntax')
name, unsigned, bits, count = match.groups()
result.append((name, kinds[name], int(bits or 32), bool(unsigned), int(count or 1)))
return result
def checked_schema(dbd_dir, table):
if table in codec.TABLES or table in codec.SUPPLEMENTAL_TABLES:
return codec.fields(Path(dbd_dir) / (table + '.dbd'), table)
fields = raw_schema(dbd_dir, table)
pin = table_metadata(table)[2]
if pin is not None and canonical_sha256(fields) != pin:
raise ValueError('Reviewed native field sequence changed: ' + table)
return fields
def decode(wire, fields, ident):
"""Inverse of codec.encode for rows a package stores only as wire bytes."""
out, at = dict(ID=ident), 0
for name, kind, bits, unsigned, count in fields:
values = []
for _ in range(count):
if kind in ('string', 'locstring'):
end = wire.index(b'\0', at)
values.append(wire[at:end].decode('utf-8'))
at = end + 1
elif kind == 'float':
values.append(struct.unpack_from('<f', wire, at)[0])
at += 4
else:
values.append(int.from_bytes(wire[at:at + bits // 8], 'little', signed=not unsigned))
at += bits // 8
out[name] = values if count > 1 else values[0]
if at != len(wire):
raise ValueError('Package wire row length differs from schema')
return out
# ---------------------------------------------------------------- source
def load_source(directory):
directory = Path(directory)
return {name: DBC(directory / (name + '.dbc'), width) for name, width in SOURCE_SHAPES.items()}
def class_scope(source, chain_rows=()):
"""Return {spell_id: sorted origins} for trainer/talent roots and closure."""
spells = source['Spell']
lines = source['SkillLine']
class_lines = {r[0] for r in lines.rows if r[1] == CLASS_SKILL_CATEGORY
and lines.string(r[3]) not in NON_CLASS_LINE_NAMES}
roots = defaultdict(set)
for row in source['SkillLineAbility'].rows:
if row[1] in class_lines and row[2] in spells.by_id:
roots[row[2]].add('class-skill-line')
talent_ranks = set()
for row in source['Talent'].rows:
for ident in row[4:13]:
if ident and ident in spells.by_id:
roots[ident].add('talent-rank')
talent_ranks.add(ident)
members = defaultdict(list)
rank_of = {}
for spell, first, rank in chain_rows:
members[first].append(spell)
rank_of[spell] = first
for ident in list(talent_ranks):
for other in members.get(rank_of.get(ident), ()):
if other in spells.by_id:
roots[other].add('talent-spell-chain')
graph = spell_tooltip_graph(spells, sorted(roots))
for ident in graph['records']:
if ident not in roots:
roots[ident].add('trigger-or-description-reference')
return {ident: sorted(origin) for ident, origin in sorted(roots.items())}, class_lines, graph['missing']
def extend_scope(source, scope, spell_ids):
"""Explicit Source catalogue roots and their existing presentation closure.
This only defines client presentation records; it grants no learned spell.
Unknown Source IDs stay explicit missing dependencies rather than becoming
invented records. Existing class origins and scope remain intact.
"""
if (not isinstance(spell_ids, list) or len(spell_ids) > 20000 or
any(type(i) is not int or not 0 < i <= 0x7fffffff for i in spell_ids)):
raise ValueError('Bounded positive Source spell ID list required')
graph = spell_tooltip_graph(source['Spell'], spell_ids)
roots = set(spell_ids)
result = {ident: set(origins) for ident, origins in scope.items()}
for ident in graph['records']:
result.setdefault(ident, set()).add('explicit-source-root' if ident in roots
else 'explicit-source-reference')
return {ident: sorted(origins) for ident, origins in sorted(result.items())}, graph['missing']
def package_set_links(package_rows, schema):
"""Read valid set links from both named and recovered wire-only rows."""
result = []
for row in package_rows:
if row['table_name'] != 'ItemSetSpell' or row.get('record_status', 'valid') != 'valid':
continue
record = row.get('record')
if record is None:
record = decode(bytes.fromhex(row['wire_hex']), schema, row['id'])
result.append(record)
return result
def source_spell(source, ident, offsets, *, server_template=None):
if ident not in source['Spell'].by_id:
if server_template is None:
raise ValueError('Missing Source DBC and current SQL spell definition: ' + str(ident))
# SQL-only local spells have no DBC donor. The named SQL constructor
# supplies every DTO scalar and effect field; only identity/slot indices
# are structural. Missing columns retain the same fail-closed checks.
return server_spell_definition(dict(id=ident, effects=[dict(index=i) for i in range(3)]),
server_template)
raw = source['Spell'].by_id[ident]
text = source['Spell'].string
o = offsets
effects = []
for i in range(3):
effects.append(dict(
index=i, effect=raw[o['Effect'] + i], aura=raw[o['EffectAura'] + i],
base=signed(raw[o['EffectBasePoints'] + i]), dice=signed(raw[o['EffectBaseDice'] + i]),
die=signed(raw[o['EffectDieSides'] + i]), dice_per_level=floating(raw[o['EffectDicePerLevel'] + i]),
per_level=floating(raw[o['EffectRealPointsPerLevel'] + i]), mechanic=raw[o['EffectMechanic'] + i],
target=[raw[o['ImplicitTargetA'] + i], raw[o['ImplicitTargetB'] + i]],
radius=raw[o['EffectRadiusIndex'] + i], period=raw[o['EffectAuraPeriod'] + i],
amplitude=floating(raw[o['EffectAmplitude'] + i]), chain=raw[o['EffectChainTargets'] + i],
misc=signed(raw[o['EffectMiscValue'] + i]), trigger=raw[o['EffectTriggerSpell'] + i],
per_combo=floating(raw[o['EffectPointsPerCombo'] + i]),
chain_amplitude=floating(raw[o['EffectChainAmplitude'] + i])))
record = dict(
id=ident, name=text(raw[o['Name_lang']]), rank=text(raw[o['NameSubtext_lang']]),
description=text(raw[o['Description_lang']]), aura_description=text(raw[o['AuraDescription_lang']]),
school=raw[o['School']], category=raw[o['Category']], dispel=raw[o['DispelType']],
mechanic=raw[o['Mechanic']], attributes=[signed(raw[o['Attributes'] + i]) for i in range(5)],
cast_time=raw[o['CastingTimeIndex']], proc_flags=raw[o['ProcFlags']], recovery=raw[o['RecoveryTime']],
category_recovery=raw[o['CategoryRecoveryTime']], proc_chance=raw[o['ProcChance']],
proc_charges=raw[o['ProcCharges']], levels=dict(MaxLevel=raw[o['MaxLevel']], BaseLevel=raw[o['BaseLevel']],
SpellLevel=raw[o['SpellLevel']]), duration=raw[o['DurationIndex']], power_type=signed(raw[o['PowerType']]),
mana_cost=raw[o['ManaCost']], mana_per_level=raw[o['ManaCostPerLevel']],
mana_per_second=raw[o['ManaPerSecond']], range=raw[o['RangeIndex']], speed=floating(raw[o['Speed']]),
stack=raw[o['CumulativeAura']], visual=raw[o['SpellVisualID']], icon=raw[o['SpellIconID']],
mana_pct=raw[o['ManaCostPct']], start_category=raw[o['StartRecoveryCategory']],
start_recovery=raw[o['StartRecoveryTime']], defense=raw[o['DefenseType']],
prevention=raw[o['PreventionType']], max_targets=raw[o['MaxTargets']],
max_target_level=raw[o['MaxTargetLevel']],targets=raw[o['Targets']],
target_creature_type=raw[o['TargetCreatureType']],effects=effects)
if server_template is not None:
record = server_spell_definition(record, server_template)
return record
def server_spell_definition(record, row):
"""Current named Source SQL values over a DBC-shaped presentation DTO.
This is not a SQL query or a tooltip renderer. Unknown/missing columns fail
closed; timing indices still resolve against the actual Source DBC stores.
"""
if row.get('entry') != record['id']:
raise ValueError('Source spell_template identity differs')
out = deepcopy(record)
fields = dict(name='name', rank='nameSubtext', description='description',
aura_description='auraDescription',school='school',category='category',
dispel='dispel',mechanic='mechanic',cast_time='castingTimeIndex',proc_flags='procFlags',
recovery='recoveryTime',category_recovery='categoryRecoveryTime',proc_chance='procChance',
proc_charges='procCharges',duration='durationIndex',power_type='powerType',
mana_cost='manaCost',mana_per_level='manCostPerLevel',mana_per_second='manaPerSecond',
range='rangeIndex',speed='speed',stack='stackAmount',visual='spellVisual1',icon='spellIconId',
mana_pct='manaCostPercentage',start_category='startRecoveryCategory',start_recovery='startRecoveryTime',
defense='dmgClass',prevention='preventionType',max_targets='maxAffectedTargets',
max_target_level='maxTargetLevel',targets='targets',target_creature_type='targetCreatureType')
for target, column in fields.items():
if column not in row:raise ValueError('Missing current Source SQL column: '+column)
value = row[column]
if target in ('name','rank','description','aura_description'):
if not isinstance(value,str):raise ValueError('Source SQL text type differs: '+column)
elif not isinstance(value,(int,float)) or isinstance(value,bool) or not math.isfinite(value):
raise ValueError('Source SQL scalar type differs: '+column)
out[target] = value
# Source SQL stores POWER_HEALTH as uint32 0xfffffffe; the DBC DTO and
# native PowerType field use the same signed -2 representation.
out['power_type'] = signed(int(out['power_type']) & 0xffffffff)
attrs = ['attributes','attributesEx','attributesEx2','attributesEx3','attributesEx4']
out['attributes'] = [signed(int(row[n]) & 0xffffffff) for n in attrs]
out['levels'] = {target:row[column] for target,column in
[('MaxLevel','maxLevel'),('BaseLevel','baseLevel'),('SpellLevel','spellLevel')]}
effect_fields = dict(effect='effect',aura='effectApplyAuraName',base='effectBasePoints',
dice='effectBaseDice',die='effectDieSides',dice_per_level='effectDicePerLevel',
per_level='effectRealPointsPerLevel',mechanic='effectMechanic',radius='effectRadiusIndex',
period='effectAmplitude',amplitude='effectMultipleValue',chain='effectChainTarget',
misc='effectMiscValue',trigger='effectTriggerSpell',per_combo='effectPointsPerComboPoint',
chain_amplitude='dmgMultiplier')
for index,effect in enumerate(out['effects'],1):
for target,prefix in effect_fields.items():
key=prefix+str(index)
if key not in row or not isinstance(row[key],(int,float)) or isinstance(row[key],bool) or not math.isfinite(row[key]):
raise ValueError('Source SQL effect scalar differs: '+key)
effect[target]=row[key]
effect['dice']=signed(int(effect['dice']) & 0xffffffff)
effect['target']=[row['effectImplicitTargetA'+str(index)],row['effectImplicitTargetB'+str(index)]]
return out
def effect_value(e):
"""Vanilla roll base+[dice..die] -> native mean and Variance (CalcValue form)."""
if e['die'] <= 1:
low = high = e['base'] + e['dice']
else:
a, b = sorted((e['dice'], e['die']))
low, high = e['base'] + a, e['base'] + b
mean = (low + high) / 2
variance = 0.0 if low == high or mean == 0 else abs((high - low) / mean)
return mean, float(struct.unpack('<f', struct.pack('<f', variance))[0]), low, high
# ---------------------------------------------------------------- server coefficients
# REA (tortoise core): WorldObject::SpellBonusWithCoeffs adds benefit*coeff,
# coeff = spell_template.effectBonusCoefficientN when >= 0, else the derived
# CalculateDefaultCoefficient(). Benefit is caster total AP when customFlags has
# SPELL_CUSTOM_BONUS_COEFF_USES_AP, spell power for magic/none damage classes,
# and only flat +damage auras for melee/ranged (no AP/SP term). Native tooltip
# $s/$o add SP*EffectBonusCoefficient and AP*BonusCoefficientFromAP.
COEFF_USES_AP = 0x800000
FIXED_DAMAGE = 0x10 # SPELL_CUSTOM_FIXED_DAMAGE: no done bonus
# "$s1 damage plus 35% of your Attack Power": once BonusCoefficientFromAP puts
# the AP term into $s1 the trailing phrase would count it twice.
AP_CLAIM = re.compile(r'(benefits from|increased by|modified by)[^.]*attack power|of (your|the [a-z]+\'s) '
r'(melee |ranged )?attack power', re.I)
AP_PHRASE = re.compile(r'(\$s\d) damage plus \d+% of your Attack Power')
BONUS_EFFECTS = (2, 9, 10) # SCHOOL_DAMAGE, HEALTH_LEECH, HEAL
BONUS_AURAS = (3, 8, 53) # PERIODIC_DAMAGE, PERIODIC_HEAL, PERIODIC_LEECH
# scripts/spells OnEffectDamageCalculate AP terms: name -> (effect index or None, AP coeff, mode)
SCRIPT_AP = {
'spell_warrior_bloodthirst': (0, 0.35, 'add'),
'spell_rogue_surprise_attack': (None, 0.25, 'add'),
'spell_rogue_noxious_assault': (None, 0.30, 'add'),
'spell_hunter_lacerate': (0, 0.40, 'replace'),
'spell_hunter_kill_command_damage': (None, 0.80, 'replace'),
'spell_hunter_strike_together_damage': (None, 0.20, 'replace'),
'spell_shaman_totemic_slam': (0, 0.10, 'replace'),
}
SCRIPT_AP_BY_ID = {1510: 0.04, 14294: 0.05, 14295: 0.06} # spell_hunter_volley periodic RANGED AP
# SpellAuras periodic damage hooks (family-mask branches): name -> AP per tick.
AURA_AP_BY_NAME = {'Garrote': 0.03}
SCRIPT_HELD = {
'spell_warrior_shield_slam': 'adds shield block value (no native coefficient)',
'spell_warrior_execute': 'rage-dependent damage via trigger 20647',
'spell_warrior_execute_trigger': 'rage-dependent damage',
'spell_rogue_eviscerate': 'AP*combo*0.03 (combo-dependent)',
'spell_druid_ferocious_bite': 'AP*combo*0.03 plus energy (combo-dependent)',
# Rip: SpellAuras AP*min(cp,4)/100 per tick (combo-dependent) - held by text claim.
}
def read_server_coefficients(path, mod_path=None):
"""spell_template export (+ optional spell_mod Id/Custom/DmgClass) -> {id: row}."""
import csv
rows = {}
with open(path, newline='') as handle:
for r in csv.DictReader(handle, delimiter='\t'):
rows[int(r['entry'])] = dict(
effects=[(int(r['effect%d' % i]), int(r['effectApplyAuraName%d' % i]),
float(r['effectBonusCoefficient%d' % i])) for i in (1, 2, 3)],
custom=int(r['customFlags']), dmg_class=int(r['dmgClass']), script=r.get('script_name') or '',
school=int(r.get('school') or 0))
if mod_path:
with open(mod_path, newline='') as handle:
for r in csv.DictReader(handle, delimiter='\t'):
row = rows.get(int(r['Id']))
if row is None:
continue
if int(r['Custom']) > 0:
row['custom'] |= int(r['Custom'])
if int(r['DmgClass']) >= 0:
row['dmg_class'] = int(r['DmgClass'])
return rows
def server_bonus(row, ident=None, name=None):
"""Return ({effect index: dict(sp, ap, replace)}, [held notes]) for one server spell.
Effects without a server bonus term get zero coefficients (native retail
values would otherwise add Forever SP/AP to the tooltip); effects whose
server coefficient is the unported default are held and left unchanged.
"""
out, held = {}, []
uses_ap = bool(row['custom'] & COEFF_USES_AP)
for index, (effect, aura, coeff) in enumerate(row['effects']):
if not (effect in BONUS_EFFECTS or (effect == 6 and aura in BONUS_AURAS)):
continue
if row['custom'] & FIXED_DAMAGE:
out[index] = dict(sp=0.0, ap=0.0, replace=False)
elif uses_ap:
if coeff < 0:
held.append(dict(effect=index, kind='server-default-ap-coefficient-not-ported'))
continue
out[index] = dict(sp=0.0, ap=coeff, replace=False)
elif row['dmg_class'] in (2, 3) or row.get('school', 0) == 0:
# Melee/ranged class or physical school: benefit is flat +damage auras only.
out[index] = dict(sp=0.0, ap=0.0, replace=False)
elif coeff >= 0:
out[index] = dict(sp=coeff, ap=0.0, replace=False)
else:
held.append(dict(effect=index, kind='server-default-sp-coefficient-not-ported'))
script = SCRIPT_AP.get(row['script'])
if script:
where, ap, mode = script
for index in ([where] if where is not None else sorted(out)):
entry = out.setdefault(index, dict(sp=0.0, ap=0.0, replace=False))
entry['ap'] = ap if mode == 'replace' else entry['ap'] + ap
if mode == 'replace':
entry.update(sp=0.0, replace=True)
elif row['script'] in SCRIPT_HELD:
held.append(dict(kind='server-script-term-held', script=row['script'], note=SCRIPT_HELD[row['script']]))
if ident in SCRIPT_AP_BY_ID:
targets = [i for i, (effect, aura, _) in enumerate(row['effects']) if effect == 6 and aura == 3]
for index in targets:
out.setdefault(index, dict(sp=0.0, ap=0.0, replace=False))['ap'] += SCRIPT_AP_BY_ID[ident]
if not targets:
held.append(dict(kind='server-script-term-held', script='spell_hunter_volley',
note='periodic AP term without a periodic-damage effect'))
if name in AURA_AP_BY_NAME:
for index, (effect, aura, _) in enumerate(row['effects']):
if effect == 6 and aura == 3:
out.setdefault(index, dict(sp=0.0, ap=0.0, replace=False))['ap'] += AURA_AP_BY_NAME[name]
defaulted = {n['effect'] for n in held if 'effect' in n}
for index, (effect, _, _) in enumerate(row['effects']):
if effect and index not in out and index not in defaulted:
out[index] = dict(sp=0.0, ap=0.0, replace=False)
return out, held
# ---------------------------------------------------------------- native view
def normalize_native_export(record, schema):
"""Normalize System.Text.Json byte[] only against an exact native schema.
DBCD's unsigned8-bit arrays serialize as base64; other native arrays must
already be JSON lists of the reviewed width. Strings and scalar fields are
never converted heuristically.
"""
import base64
import binascii
if not isinstance(record, dict):
raise ValueError('Native exported record must be an object')
result = dict(record)
for name, kind, bits, unsigned, count in schema:
if count <= 1:
continue
value = record.get(name)
if isinstance(value, str):
if (kind, bits, unsigned) != ('int', 8, True):
raise ValueError('Only native unsigned8-bit arrays may use base64: ' + name)
try:
value = list(base64.b64decode(value, validate=True))
except (ValueError, binascii.Error):
raise ValueError('Invalid native byte-array base64: ' + name) from None
if not isinstance(value, list) or len(value) != count:
raise ValueError('Native exported array width differs: ' + name)
result[name] = list(value)
return result
class NativeView:
"""Native DB2 exports overlaid by the current package (same table/id wins)."""
def __init__(self, native_dirs, package_rows, schemas=None, *, package_only_spell_text=False):
self.rows = {}
self.unavailable_baselines = []
for table in NATIVE_TABLES:
for directory in native_dirs:
path = Path(directory) / (table + '.json')
if path.exists():
records = json.loads(path.read_text())
if schemas and table in schemas:
records = [normalize_native_export(r, schemas[table]) for r in records]
self.rows[table] = {r['ID']: r for r in records}
break
else:
if table == 'Spell' and package_only_spell_text:
self.rows[table] = {}
self.unavailable_baselines.append(table)
else:
raise ValueError('Missing native export: ' + table)
self.native_max = {t: max(v) if v else 0 for t, v in self.rows.items()}
self.package_ids = defaultdict(dict)
for index, row in enumerate(package_rows):
table = row['table_name']
self.package_ids[table][row['id']] = index
if table in self.rows:
record = row.get('record')
if record is None and not row.get('wire_hex'):
self.rows[table].pop(row['id'], None) # package removal row
continue
if record is None:
if not schemas or table not in schemas:
raise ValueError('Record-less package row needs a schema: ' + table)
record = decode(bytes.fromhex(row['wire_hex']), schemas[table], row['id'])
self.rows[table][row['id']] = record
self.by_spell = {}
for table in CHILD_BY_SPELL + ('SpellEffect', 'SpellPower'):
index = defaultdict(list)
for record in self.rows[table].values():
if record.get('DifficultyID', 0) == 0:
index[record['SpellID']].append(record)
self.by_spell[table] = index
def one(self, table, spell):
found = self.by_spell[table].get(spell, [])
if table == 'SpellPower':
found = [r for r in found if r['OrderIndex'] == 0]
return sorted(found, key=lambda r: r['ID'])[0] if found else None
def effects(self, spell):
result = {}
for record in sorted(self.by_spell['SpellEffect'].get(spell, []), key=lambda r: r['ID']):
result.setdefault(record['EffectIndex'], record)
return result
# ---------------------------------------------------------------- dependency rows
class Allocator:
def __init__(self, view, maxima):
self.view, self.maxima, self.next = view, maxima, {}
def __call__(self, table):
if table not in self.next:
self.next[table] = max(self.maxima.get(table, 0), self.view.native_max.get(table, 0),
max(self.view.package_ids.get(table, {0: 0})), max(self.view.rows[table] or [0])) + 1
value = self.next[table]
self.next[table] += 1
return value
class Dependencies:
"""Resolve source duration/cast/range/radius indices to native rows by value."""
def __init__(self, source, view, allocate, *, strict_timing=False):
self.source, self.view, self.allocate = source, view, allocate
self.strict_timing = strict_timing
self.cache, self.new_rows, self.held, self.predicates = {}, [], [], {}
def prefer(self, table, source_ident, resolved, current):
"""Keep the client's current index when its values already match."""
same = self.predicates.get((table, source_ident))
row = self.view.rows[table].get(current)
if same is not None and row is not None and same(row):
return current
return resolved
def _resolve(self, table, ident, wanted, same, build):
key = (table, ident)
self.predicates[key] = same
if key in self.cache:
return self.cache[key]
rows = self.view.rows[table]
if ident in rows and same(rows[ident]):
result = ident
else:
matches = sorted(i for i, r in rows.items() if same(r))
if matches:
result = matches[0]
else:
result = self.allocate(table)
record = dict(build(), ID=result)
rows[result] = record
self.new_rows.append((table, record, ident))
self.cache[key] = result
return result
def duration(self, ident):
if not ident:
return 0
row = self.source['SpellDuration'].by_id.get(ident)
if row is None:
self.held.append(dict(kind='missing-source-duration', reference=ident))
return None
base, per_level, maximum = signed(row[1]), signed(row[2]), signed(row[3])
if per_level:
if self.strict_timing:
self.held.append(dict(kind='level-scaled-duration-not-native-resource-duration',reference=ident))
return None
self.held.append(dict(kind='level-scaled-duration-base-used', reference=ident))
want = dict(Duration=base, MaxDuration=maximum if maximum else base, DurationPerResource=0)
return self._resolve('SpellDuration', ident, want, lambda r: all(r.get(k) == v for k, v in want.items()),
lambda: dict(want))
def cast_time(self, ident):
if not ident:
return 1
row = self.source['SpellCastTimes'].by_id.get(ident)
if row is None:
return None
if self.strict_timing and signed(row[2]):
self.held.append(dict(kind='level-scaled-cast-time-unrepresented',reference=ident))
return None
base, minimum = signed(row[1]), signed(row[3])
want = dict(Base=base, Minimum=minimum)
return self._resolve('SpellCastTimes', ident, want, lambda r: all(r.get(k) == v for k, v in want.items()),
lambda: dict(want))
def range(self, ident):
if not ident:
return 1
row = self.source['SpellRange'].by_id.get(ident)
if row is None:
return None
low, high, flags = floating(row[1]), floating(row[2]), row[3]
name, short = self.source['SpellRange'].string(row[4]), self.source['SpellRange'].string(row[13])
def same(r):
return (all(close(x, low) for x in r['RangeMin']) and all(close(x, high) for x in r['RangeMax'])
and r['Flags'] == flags)
return self._resolve('SpellRange', ident, None, same, lambda: dict(
DisplayName_lang=name, DisplayNameShort_lang=short, Flags=flags, RangeMin=[low, low], RangeMax=[high, high]))
def radius(self, ident):
if not ident:
return 0
row = self.source['SpellRadius'].by_id.get(ident)
if row is None:
return None
radius, per_level, maximum = floating(row[1]), floating(row[2]), floating(row[3])
def same(r):
return close(r['Radius'], radius) and close(r['RadiusPerLevel'], per_level) and close(r['RadiusMax'], maximum)
return self._resolve('SpellRadius', ident, None, same, lambda: dict(
Radius=radius, RadiusPerLevel=per_level, RadiusMin=0, RadiusMax=maximum))
# ---------------------------------------------------------------- icons and visuals
def icon_index(listing, source):
"""Source SpellIcon ID -> client FileDataID by exact icon path.
`listing` is the client's own CASC root listing (casc-tool list --format
csv: fdid,size,resolved,name), so every mapped FileDataID is known to the
pinned client; a community `fdid;path` listfile is also accepted.
"""
wanted = defaultdict(list)
for row in source['SpellIcon'].rows:
path = source['SpellIcon'].string(row[1]).replace('\\', '/').lower()
if path:
wanted[path + '.blp'].append(row[0])
found = {}
with open(listing, encoding='utf-8', errors='replace') as stream:
for line in stream:
line = line.rstrip('\n')
if ';' in line:
fid, _, path = line.partition(';')
else:
parts = line.split(',')
if len(parts) < 4:
continue
fid, path = parts[0], parts[3]
if not fid.isdigit():
continue
path = path.replace('\\', '/').lower()
for ident in wanted.get(path, ()):
found[ident] = int(fid)
return found
def visual_index(source, view, offsets, base_visual_ids=None):
"""Vanilla SpellVisual ID -> native SpellVisual ID, proven by shared spells.
A source visual is mapped only where same-ID same-name native spells carrying
that vanilla visual agree on one native visual (majority with >=1 witness),
or where the native SpellVisual table has the identical ID and a shared
spell confirms it. No assets are invented.
"""
names = view.rows['SpellName']
votes = defaultdict(Counter)
for raw in source['Spell'].rows:
ident = raw[0]
visual = raw[offsets['SpellVisualID']]
native_name = names.get(ident, {}).get('Name_lang')
if not visual or native_name is None:
continue
if native_name != source['Spell'].string(raw[offsets['Name_lang']]):
continue
link = view.one('SpellXSpellVisual', ident)
if link:
votes[visual][link['SpellVisualID']] += 1
mapping = {}
# Shared-spell witnesses keep the vanilla ID in 1904/1933 cases, so an
# original 1.12 visual ID that the client also defines maps to itself.
for visual in base_visual_ids or ():
if visual in view.rows['SpellVisual'] and visual not in votes:
mapping[visual] = dict(native=visual, witnesses=0, agree=0, rule='original-1.12-identity')
for visual, counter in votes.items():
(best, count), = counter.most_common(1)
if visual in counter:
best = visual
mapping[visual] = dict(native=best, witnesses=sum(counter.values()), agree=counter[best])
return mapping
def same_name_visual(view, name, exclude):
by_name = getattr(view, '_names', None)
if by_name is None:
by_name = defaultdict(list)
for ident, record in view.rows['SpellName'].items():
by_name[record['Name_lang']].append(ident)
view._names = by_name
counter = Counter()
for ident in by_name.get(name, ()):
if ident == exclude:
continue
link = view.one('SpellXSpellVisual', ident)
if link:
counter[link['SpellVisualID']] += 1
return counter.most_common(1)[0][0] if counter else None
# ---------------------------------------------------------------- comparison
def plan(source, view, scope, offsets, *, icons, visuals, allocate, coefficients=None,
tooltip_closure=False, server_templates=None):
"""Return (records, report). Records are (table, record, meta) tuples."""
deps = Dependencies(source, view, allocate, strict_timing=tooltip_closure)
out, held = [], []
stats = Counter()
audit = []
def emit(table, record, baseline, spell, reason, effect_index=None):
changed = sorted(k for k in record if baseline is None or baseline.get(k) != record[k])
out.append((table, record, dict(source_spell_id=spell, baseline=baseline, changed=changed,
reason=reason, source_effect_index=effect_index)))
stats[table] += 1
def override(table, baseline, want, spell, effect_index=None):
if baseline is None:
return
if tooltip_closure:
# Keep reviewed text and caster/coefficient decisions intact. This
# pass repairs native typed definitions, never renders literal text
# or silently reverts accepted custom AP/SP/scaling policies.
protected = set(want) if table in ('Spell','SpellName') else set()
if table == 'SpellEffect':
protected.update(('EffectBonusCoefficient','BonusCoefficientFromAP','ScalingClass','Coefficient'))
for key in sorted(protected & want.keys()):
if baseline.get(key)!=want[key]:
audit.append(dict(spell=spell,table=table,id=baseline['ID'],field=key,
policy='preserved-accepted-text-or-caster-modifier',source_effect_index=effect_index))
want={k:v for k,v in want.items()if k not in protected}
record = deepcopy(baseline)
changed = False
for key, value in want.items():
old = record.get(key)
same = (close(old, value) if isinstance(value, float) or isinstance(old, float) else old == value) \
if not isinstance(value, list) else (len(old) == len(value) and all(
close(a, b) if isinstance(b, float) else a == b for a, b in zip(old, value)))
if not same:
record[key] = value
changed = True
if changed:
emit(table, record, baseline, spell, 'same-ID-source-authoritative-override', effect_index)
for ident in scope:
src = source_spell(source, ident, offsets,server_template=server_templates.get(ident)) if server_templates is not None else source_spell(source, ident, offsets)
name_row = view.rows['SpellName'].get(ident)
is_new = name_row is None
if not is_new and name_row['Name_lang'] != src['name']:
stats['name-collision-overridden'] += 1
stats['new-definition' if is_new else 'existing-definition'] += 1
duration = deps.duration(src['duration'])
cast = deps.cast_time(src['cast_time'])
rng = deps.range(src['range'])
if tooltip_closure and cast is None:
existing_misc = view.one('SpellMisc', ident)
if existing_misc is not None:
# A missing native level-scaling term must not erase an
# accepted cast reference or block independent numeric rows.
cast = existing_misc['CastingTimeIndex']
held.append(dict(spell=ident,kind='existing-cast-reference-preserved-unrepresented-Source-timing',
reference=src['cast_time'],native_reference=cast))
if None in (duration, cast, rng):
held.append(dict(spell=ident, kind='missing-source-timing-reference'))
continue
icon = icons.get(src['icon'])
bonus = {}
if coefficients is not None and ident in coefficients:
bonus, notes = server_bonus(coefficients[ident], ident, src['name'])
held.extend(dict(spell=ident, **n) for n in notes)
if bonus:
stats['server-coefficient-spells'] += 1
if not tooltip_closure and any(v['ap'] for v in bonus.values()) and AP_PHRASE.search(src['description']):
src['description'] = AP_PHRASE.sub(r'\1 damage', src['description'])
stats['ap-phrase-folded-into-value'] += 1
damaging = any(eff in BONUS_EFFECTS or (eff == 6 and aura in BONUS_AURAS)
for eff, aura, _ in coefficients[ident]['effects'])
if damaging and not any(v['ap'] for v in bonus.values()) and AP_CLAIM.search(src['description']):
held.append(dict(spell=ident, kind='source-text-claims-ap-scaling-unobserved-in-server'))
# -- presentation parents
name = dict(ID=ident, Name_lang=src['name'])
text = dict(ID=ident, NameSubtext_lang=src['rank'], Description_lang=src['description'],
AuraDescription_lang=src['aura_description'])
if is_new:
emit('SpellName', name, None, ident, 'new-source-class-spell-parent')
emit('Spell', text, None, ident, 'new-source-class-spell-parent')
else:
# Package-owned text (e.g. Codex literal-constant descriptions) is a
# reviewed decision and is preserved; only native text is replaced.
if ident not in view.package_ids['SpellName']:
override('SpellName', name_row, dict(Name_lang=src['name']), ident)
spell_row = view.rows['Spell'].get(ident)
if spell_row is None:
emit('Spell', text, None, ident, 'new-source-class-spell-parent')
elif ident not in view.package_ids['Spell']:
override('Spell', spell_row, {k: v for k, v in text.items() if k != 'ID'}, ident)
# -- SpellMisc
misc_want = dict(CastingTimeIndex=cast, DurationIndex=duration, RangeIndex=rng,
SchoolMask=1 << src['school'], Speed=src['speed'])
if icon:
misc_want['SpellIconFileDataID'] = icon
misc = view.one('SpellMisc', ident) if tooltip_closure else (None if is_new else view.one('SpellMisc', ident))
if misc is None:
if icon is None:
held.append(dict(spell=ident, kind='new-definition-icon-unresolved-question-mark'))
attributes = src['attributes'] + [0] * 12
attributes[15] |= FLAT_TOOLTIP_ATTR15
record = dict(deepcopy(codec.NEW_MISC_NEUTRAL), ID=allocate('SpellMisc'), SpellID=ident,
Attributes=attributes, SpellIconFileDataID=icon or QUESTION_MARK_ICON,
DurationIndex=duration, CastingTimeIndex=cast, RangeIndex=rng,
SchoolMask=1 << src['school'], Speed=src['speed'])
emit('SpellMisc', record, None, ident, 'new-source-class-spell-child')
else:
attributes = list(misc['Attributes'])
attributes[15] |= FLAT_TOOLTIP_ATTR15
misc_want['Attributes'] = attributes
misc_want['DurationIndex'] = deps.prefer('SpellDuration', src['duration'], duration, misc['DurationIndex'])
misc_want['CastingTimeIndex'] = deps.prefer('SpellCastTimes', src['cast_time'], cast, misc['CastingTimeIndex'])
misc_want['RangeIndex'] = deps.prefer('SpellRange', src['range'], rng, misc['RangeIndex'])
override('SpellMisc', misc, misc_want, ident)
# -- SpellEffect
native_effects = view.effects(ident) if tooltip_closure else ({} if is_new else view.effects(ident))
for e in src['effects']:
native = native_effects.get(e['index'])
if not e['effect']:
if native is not None and native['Effect']:
override('SpellEffect', native, dict(Effect=0, EffectAura=0, EffectBasePointsF=0.0, Variance=0.0,
EffectTriggerSpell=0, EffectMiscValue=[0, 0]), ident, e['index'])
continue
if e['dice_per_level']:
held.append(dict(spell=ident, effect=e['index'], kind='dice-per-level-not-representable'))
if tooltip_closure:continue
mean, variance, _, _ = effect_value(e)
radius = deps.radius(e['radius'])
if radius is None:
held.append(dict(spell=ident, effect=e['index'], kind='missing-source-radius'))
if tooltip_closure:continue
radius = 0
# Modern radius slots follow ImplicitTarget A/B; vanilla has one radius.
slot = 1 if e['target'][1] else 0
radii = [0, 0]
radii[slot] = radius
want = dict(Effect=e['effect'], EffectAura=e['aura'], EffectBasePointsF=float(mean), Variance=variance,
EffectRealPointsPerLevel=e['per_level'], EffectAuraPeriod=e['period'],
EffectAmplitude=e['amplitude'], EffectChainTargets=e['chain'],
EffectChainAmplitude=e['chain_amplitude'], EffectPointsPerResource=e['per_combo'],
EffectTriggerSpell=e['trigger'], ImplicitTarget=list(e['target']))
server = bonus.get(e['index'])
if server is not None:
want.update(EffectBonusCoefficient=float(server['sp']), BonusCoefficientFromAP=float(server['ap']))
if server['replace']:
want.update(EffectBasePointsF=0.0, Variance=0.0) # script sets damage = AP*k
stats['server-coefficient-effects'] += 1
if native is None:
record = dict(deepcopy(codec.NEW_EFFECT_NEUTRAL), ID=allocate('SpellEffect'), SpellID=ident,
EffectIndex=e['index'], EffectBasePointsF=0.0, EffectMiscValue=[e['misc'], 0],
EffectRadiusIndex=radii, EffectMechanic=e['mechanic'])
record.update(want)
emit('SpellEffect', record, None, ident, 'new-source-class-spell-child', e['index'])
else:
want['EffectMiscValue'] = [e['misc'], native['EffectMiscValue'][1]]
current = native['EffectRadiusIndex']
kept = [deps.prefer('SpellRadius', e['radius'], radius, c) == c and c for c in current]
if e['radius'] and any(kept):
radii = list(current)
elif not e['radius'] and e['effect'] == native['Effect']:
radii = list(current) # native-only radius on the same mechanic
want['EffectRadiusIndex'] = radii
if native.get('ScalingClass') or native.get('Coefficient'):
want.update(ScalingClass=0, Coefficient=0.0)
if server is None and (native['Effect'] != e['effect'] or native['EffectAura'] != e['aura']):
# Redesigned native effect: its coefficients describe another mechanic.
want.update(EffectBonusCoefficient=0.0, BonusCoefficientFromAP=0.0)
override('SpellEffect', native, want, ident, e['index'])
# -- simple children
children = {
# Without proc flags the chance column is the 101 default, not data.
'SpellAuraOptions': dict(ProcCharges=src['proc_charges'], CumulativeAura=src['stack'],
**({'ProcChance': src['proc_chance']} if src['proc_flags'] else {})),
'SpellCooldowns': dict(RecoveryTime=src['recovery'], CategoryRecoveryTime=src['category_recovery'],
StartRecoveryTime=src['start_recovery']),
'SpellLevels': dict(src['levels']),
'SpellTargetRestrictions': dict(MaxTargets=src['max_targets'],MaxTargetLevel=src.get('max_target_level',0)),
'SpellCategories': dict(DispelType=src['dispel'], Mechanic=src['mechanic'], DefenseType=src['defense'],
PreventionType=src['prevention'], StartRecoveryCategory=src['start_category']),
}
if src['category']:
if src['category'] in view.rows['SpellCategory']:
children['SpellCategories']['Category'] = src['category']
else:
held.append(dict(spell=ident, kind='source-category-absent-natively', reference=src['category']))
neutral = dict(codec.CHILD_NEUTRAL)
for table, want in children.items():
baseline = view.one(table,ident) if tooltip_closure else (None if is_new else view.one(table, ident))
if baseline is None:
if table == 'SpellAuraOptions' and not (src['proc_flags'] or src['proc_charges'] or src['stack']):
continue
if not any(want.values()):
continue
if table == 'SpellTargetRestrictions':
base = dict(DifficultyID=0, ConeDegrees=0.0, MaxTargets=0, MaxTargetLevel=0, TargetCreatureType=0,
Targets=0, Width=0.0)
elif table == 'SpellAuraOptions':
base = dict(DifficultyID=0, CumulativeAura=0, ProcCategoryRecovery=0, ProcChance=0, ProcCharges=0,
SpellProcsPerMinuteID=0, ProcTypeMask=[0, 0])
else:
base = deepcopy(neutral[table])
record = dict(base, ID=allocate(table), SpellID=ident, **want)
emit(table, record, None, ident, 'new-source-class-spell-child')
else:
override(table, baseline, want, ident)
# -- power cost
power_want = dict(PowerType=src['power_type'], ManaCost=src['mana_cost'], ManaCostPerLevel=src['mana_per_level'],
ManaPerSecond=src['mana_per_second'], PowerCostPct=float(src['mana_pct']))
power = view.one('SpellPower',ident) if tooltip_closure else (None if is_new else view.one('SpellPower', ident))
if power is None:
if src['mana_cost'] or src['mana_pct'] or src['mana_per_second']:
record = dict(ID=allocate('SpellPower'), OrderIndex=0, ManaCost=0, ManaCostPerLevel=0, ManaPerSecond=0,
PowerDisplayID=0, AltPowerBarID=0, PowerCostPct=0.0, PowerCostMaxPct=0.0, OptionalCostPct=0.0,
PowerPctPerSecond=0.0, PowerType=0, RequiredAuraSpellID=0, OptionalCost=0, SpellID=ident)
record.update(power_want)
emit('SpellPower', record, None, ident, 'new-source-class-spell-child')
else:
override('SpellPower', power, power_want, ident)
# -- visual link (only where the client has none)
if not tooltip_closure and view.one('SpellXSpellVisual', ident) is None and src['visual']:
mapped = visuals.get(src['visual'])
native_visual = mapped['native'] if mapped else same_name_visual(view, src['name'], ident)
if native_visual and native_visual in view.rows['SpellVisual']:
record = dict(ID=allocate('SpellXSpellVisual'), DifficultyID=0, SpellVisualID=native_visual,
Probability=1.0, Flags2=0, Priority=0, SpellIconFileID=0, ActiveIconFileID=0,
ViewerUnitConditionID=0, ViewerPlayerConditionID=0, CasterUnitConditionID=0,
CasterPlayerConditionID=0, SpellID=ident)
emit('SpellXSpellVisual', record, None, ident,
'new-source-visual-via-shared-vanilla-visual' if mapped else 'new-source-visual-via-same-name-native')
else:
held.append(dict(spell=ident, kind='visual-unmapped', reference=src['visual']))
if not tooltip_closure:out.extend(skill_line_rows(source, view, scope, allocate, held, stats))
for table, record, ident in deps.new_rows:
out.append((table, record, dict(source_spell_id=None, baseline=None, changed=sorted(record),
reason='new-source-dependency-row', source_reference=ident,
source_effect_index=None)))
stats[table] += 1
held.extend(deps.held)
return out, dict(stats=dict(sorted(stats.items())), held=held,preserved_decisions=audit)
def native_tooltip_plan(source, view, roots, offsets, *, server_templates, icons, allocate, coefficients=None):
"""Whole Source tooltip graph, current SQL DTOs, unique typed native joins.
Only the existing metadata constructors are used. A readable native gap is
not asserted to be runtime absence; opaque baselines and missing current SQL
dependencies remain explicit. No native function or live query is called.
"""
if not isinstance(roots,list) or len(roots)>20000 or any(type(i)is not int or not 0<i<=0x7fffffff for i in roots):
raise ValueError('Bounded Source tooltip root IDs required')
pending=list(sorted(set(roots)));seen=set();missing=set();fallback=set();definitions={}
while pending:
ident=pending.pop()
if ident in seen or ident in missing:continue
if ident not in source['Spell'].by_id and ident not in server_templates:missing.add(ident);continue
if len(seen)>=20000:raise ValueError('Native tooltip graph bound')
row=server_templates.get(ident)
if row is None:fallback.add(ident)
src=source_spell(source,ident,offsets,server_template=row);definitions[ident]=src;seen.add(ident)
references={e['trigger']for e in src['effects']if e['trigger']}
for text in(src['description'],src['aura_description']):
references.update(map(int,re.findall(r'(?<!\$)\$(?:[*/][0-9.]+;)?([1-9][0-9]*)[A-Za-z]',text)))
if any(not 0<i<=0x7fffffff for i in references):raise ValueError('Native tooltip Source dependency ID bound')
pending.extend(references-seen-missing)
collisions=[];blocked=set()
# Only relationships the numeric constructor consumes as singular. Visual
# variants are intentionally not unique and are outside this repair.
for table in tuple(t for t in CHILD_BY_SPELL if t!='SpellXSpellVisual')+('SpellEffect','SpellPower'):
for ident in seen:
groups=defaultdict(list)
for row in view.by_spell[table].get(ident,[]):
if table=='SpellPower' and row['OrderIndex']!=0:continue
key=row['EffectIndex'] if table=='SpellEffect' else row['OrderIndex'] if table=='SpellPower' else 0
groups[key].append(row['ID'])
for key,ids in groups.items():
if len(ids)>1:
collisions.append(dict(spell=ident,table=table,secondary_key=key,ids=sorted(ids)))
blocked.add(ident)
scope={i:['native-tooltip-root' if i in roots else 'native-tooltip-dependency']for i in sorted(seen-blocked)}
rows,report=plan(source,view,scope,offsets,icons=icons,visuals={},allocate=allocate,
coefficients=coefficients,tooltip_closure=True,server_templates=server_templates)
report.update(roots=len(set(roots)),graph_spells=len(seen),scope_ids=sorted(seen),
missing_source_ids=sorted(missing),DBC_only_dependency_ids=sorted(fallback),
duplicate_native_parent_or_effect_keys=collisions,held_duplicate_spell_ids=sorted(blocked),
native_baseline_unavailable=list(view.unavailable_baselines),
source_target_role_audit=[dict(spell=i,Targets=s['targets'],TargetCreatureType=s['target_creature_type'],
policy='raw-namespace-audit-only; MaxTargets/MaxTargetLevel are the qualified projection')
for i,s in definitions.items()if s.get('targets')or s.get('target_creature_type')],
policy='current-Source-SQL-typed-tooltip-closure-preserve-existing-text-and-caster-modifiers')
return rows,report
def skill_line_rows(source, view, scope, allocate, held, stats):
"""Spellbook placement: SkillLineAbility for class spells the client lacks.
REA: the original book lists a known spell under the SkillLine (category 7,
class Flags 1040) of its SkillLineAbility row; ranks chain through
SupercedesSpell. Native rows equal the vanilla rows field-for-field for 3412
of 3413 shared class abilities (same SkillLine IDs, ClassMask, MinSkillLineRank,
AcquireMethod), so Octo rows are carried over 1:1 and only added where no
native row for that spell exists. Existing rows also retain the Source rank
predecessor: placement alone does not prove SupercedesSpell matches Octo.
Lines absent natively are held.
"""
rows = source['SkillLineAbility']
lines = source['SkillLine']
names = {r[0]: lines.string(r[3]) for r in lines.rows}
native_lines = view.rows['SkillLine']
placed = {r['Spell'] for r in view.rows['SkillLineAbility'].values()}
previous = {}
for r in rows.rows:
if r[8]:
previous.setdefault((r[1], r[8]), r[2])
scope = set(scope)
out = []
for r in sorted(rows.rows, key=lambda r: r[0]):
if r[2] not in scope or r[2] in placed or lines.by_id.get(r[1], (0, 0))[1] != CLASS_SKILL_CATEGORY:
continue
if names.get(r[1]) in NON_CLASS_LINE_NAMES:
continue
line = native_lines.get(r[1])
if line is None or line['CategoryID'] != CLASS_SKILL_CATEGORY:
held.append(dict(spell=r[2], kind='source-skill-line-absent-natively', reference=r[1]))
continue
race = signed(r[3])
record = dict(ID=allocate('SkillLineAbility'), AbilityVerb_lang='', AbilityAllVerb_lang='', SkillLine=r[1],
Spell=r[2], MinSkillLineRank=r[7], ClassMask=signed(r[4]),
SupercedesSpell=previous.get((r[1], r[2]), 0), AcquireMethod=r[9],
TrivialSkillLineRankHigh=r[10], TrivialSkillLineRankLow=r[11], Flags=0, NumSkillUps=1,
UniqueBit=0, TradeSkillCategoryID=0, SkillupSkillLineID=0, Field_5_5_4_67090_014=[0, 0],
RaceMasks=[race, 0])
view.rows['SkillLineAbility'][record['ID']] = record
out.append(('SkillLineAbility', record, dict(source_spell_id=r[2], baseline=None, changed=sorted(record),
reason='new-source-class-spell-book-placement', source_effect_index=None)))
stats['SkillLineAbility'] += 1
out.extend(skill_line_rank_rows(source, view, scope, held, stats))
return out
def skill_line_rank_rows(source, view, scope, held, stats):
"""Repair existing class-book rank links without replacing other fields.
Reuses the same Source forward-link -> native SupercedesSpell contract as
skill_line_rows. A missing higher-rank placement remains the placement
planner's decision; deprecated/internal Source links do not create rows.
Duplicate equal links are harmless; ambiguous predecessors are held.
"""
scope = set(scope)
lines = source['SkillLine']
class_lines = {r[0] for r in lines.rows if r[1] == CLASS_SKILL_CATEGORY
and lines.string(r[3]) not in NON_CLASS_LINE_NAMES}
present = {(r[1], r[2]) for r in source['SkillLineAbility'].rows}
previous = defaultdict(set)
for row in source['SkillLineAbility'].rows:
if row[1] in class_lines and row[8] in scope and (row[1], row[8]) in present:
previous[(row[1], row[8])].add(row[2])
out = []
reported = set()
for baseline in sorted(view.rows['SkillLineAbility'].values(), key=lambda r: r['ID']):
key = baseline['SkillLine'], baseline['Spell']
predecessors = previous.get(key, set())
if len(predecessors) > 1:
if key not in reported:
held.append(dict(spell=key[1], kind='ambiguous-source-rank-predecessor',
reference=key[0], predecessors=sorted(predecessors)))
reported.add(key)
continue
if not predecessors:
continue
wanted = next(iter(predecessors))
if baseline['SupercedesSpell'] == wanted:
continue
record = deepcopy(baseline)
record['SupercedesSpell'] = wanted
view.rows['SkillLineAbility'][record['ID']] = record
out.append(('SkillLineAbility', record,
dict(source_spell_id=record['Spell'], baseline=baseline,
changed=['SupercedesSpell'], reason='source-class-spell-rank-predecessor',
source_effect_index=None)))
stats['SkillLineAbility-rank-link'] += 1
return out
LEARN_SPELL = 36
PROFESSION_CATEGORIES = (9, 11)
def trainer_wrappers(source, offsets, trainer_spells):
"""Trainer-offered LEARN_SPELL wrappers plus every Octo effect-36 spell
whose trigger is placed on a class or profession skill line."""
spells, lines = source['Spell'], source['SkillLine']
category = {r[0]: r[1] for r in lines.rows}
names = {r[0]: lines.string(r[3]) for r in lines.rows}
placed = set()
for r in source['SkillLineAbility'].rows:
cat = category.get(r[1])
if cat in PROFESSION_CATEGORIES or (cat == CLASS_SKILL_CATEGORY and names.get(r[1]) not in NON_CLASS_LINE_NAMES):
placed.add(r[2])
result, direct = {}, []
for raw in spells.rows:
triggers = [raw[offsets['EffectTriggerSpell'] + i] for i in range(3)
if raw[offsets['Effect'] + i] == LEARN_SPELL and raw[offsets['EffectTriggerSpell'] + i]]
if not triggers:
continue
origin = []
if raw[0] in trainer_spells:
origin.append('trainer-offered')
if any(t in placed for t in triggers):
origin.append('teaches-class-or-profession-spell')
if origin:
result[raw[0]] = dict(triggers=triggers, origins=origin)
for ident in sorted(trainer_spells):
if ident not in result:
direct.append(ident)
return result, direct
def wrapper_rows(source, view, offsets, wrappers, icons, allocate, already, held, stats):
"""Native contract (original 1423 -> Rend 772): the wrapper record itself
carries the taught spell's name, rank subtext and icon; SpellMisc
Attributes[15] 0x2000; one SpellEffect Effect 36 whose EffectTriggerSpell is
the taught spell (ImplicitTarget [0, 0]). The trainer frame and its tooltip
read these wrapper rows, so each missing wrapper gets the same record shape
from its Octo row."""
deps = Dependencies(source, view, allocate)
out = []
for ident in sorted(wrappers):
if ident in view.rows['SpellName'] or ident in already:
stats['wrapper-already-defined'] += 1
continue
src = source_spell(source, ident, offsets)
icon = icons.get(src['icon'])
if icon is None:
taught = view.one('SpellMisc', wrappers[ident]['triggers'][0])
icon = taught['SpellIconFileDataID'] if taught else None
if icon is None:
held.append(dict(spell=ident, kind='wrapper-icon-unresolved-question-mark'))
rng = deps.range(src['range'])
cast = deps.cast_time(src['cast_time'])
attributes = src['attributes'] + [0] * 12
attributes[15] |= FLAT_TOOLTIP_ATTR15
records = [
('SpellName', dict(ID=ident, Name_lang=src['name'])),
('Spell', dict(ID=ident, NameSubtext_lang=src['rank'], Description_lang=src['description'],
AuraDescription_lang=src['aura_description'])),
('SpellMisc', dict(deepcopy(codec.NEW_MISC_NEUTRAL), ID=allocate('SpellMisc'), SpellID=ident,
Attributes=attributes, SpellIconFileDataID=icon or QUESTION_MARK_ICON, DurationIndex=0,
CastingTimeIndex=cast or 1, RangeIndex=rng or 1, SchoolMask=1 << src['school'],
Speed=src['speed']))]
for e in src['effects']:
if not e['effect']:
continue
effect = dict(deepcopy(codec.NEW_EFFECT_NEUTRAL), ID=allocate('SpellEffect'), SpellID=ident,
EffectIndex=e['index'], Effect=e['effect'], EffectAura=e['aura'], EffectBasePointsF=0.0,
EffectTriggerSpell=e['trigger'], EffectMiscValue=[e['misc'], 0],
ImplicitTarget=list(e['target']), EffectChainAmplitude=1.0)
if e['effect'] != LEARN_SPELL:
effect['EffectBasePointsF'] = float(effect_value(e)[0])
records.append(('SpellEffect', effect))
if any(src['levels'].values()):
records.append(('SpellLevels', dict(codec.CHILD_NEUTRAL['SpellLevels'], ID=allocate('SpellLevels'),
SpellID=ident, **src['levels'])))
for table, record in records:
out.append((table, record, dict(source_spell_id=ident, baseline=None, changed=sorted(record),
reason='new-source-trainer-wrapper', source_effect_index=record.get('EffectIndex'))))
stats['wrapper-' + table] += 1
stats['wrapper-defined'] += 1
for table, record, ident in deps.new_rows:
out.append((table, record, dict(source_spell_id=None, baseline=None, changed=sorted(record),
reason='new-source-dependency-row', source_reference=ident,
source_effect_index=None)))
return out
def package_rows(records, schemas):
rows = []
for table, record, meta in records:
wire = codec.encode(record, schemas[table])
row = dict(table_name=table, table_hash=hex(table_metadata(table)[0]), id=record['ID'], record=record,
wire_hex=wire.hex(), sha256=hashlib.sha256(wire).hexdigest(),
source_spell_id=meta['source_spell_id'], source_effect_index=meta['source_effect_index'],
baseline_record_sha256=canonical_sha256(meta['baseline']) if meta['baseline'] is not None else None,
allocation_policy=meta['reason'], changed_fields=meta['changed'], policy=POLICY)
if meta['baseline'] is not None:
row['preserved_native_fields'] = sorted(k for k in record if k not in meta['changed'])
if 'source_reference' in meta:
row['source_reference'] = meta['source_reference']
rows.append(row)
return rows
def merge(package, rows, *, publish=True):
"""One row per table/id: a class row replaces an older one (recorded)."""
result = deepcopy(package)
index = {(r['table_name'], r['id']): i for i, r in enumerate(result['rows'])}
replaced, added = [], 0
for row in rows:
key = (row['table_name'], row['id'])
if key in index:
old = result['rows'][index[key]]
replaced.append(dict(table=key[0], id=key[1], previous_policy=old.get('policy') or old.get('allocation_policy'),
previous_sha256=old['sha256']))
row = dict(row, replaced_previous_package_row_sha256=old['sha256'])
result['rows'][index[key]] = row
else:
index[key] = len(result['rows'])
result['rows'].append(row)
added += 1
if publish:
from item_sparse_compat import package_payloads, package_pages
result['push_id'], _ = package_payloads(result['rows'])
result['pushes'] = package_pages(result['rows'])
else:
# An internal composition result cannot carry stale parent pages.
# The final owner must rebuild the explicit working delta and invoke
# the unchanged guarded publication boundary before codec generation.
result.pop('push_id', None)
result.pop('pushes', None)
result['publication_ready'] = False
result['kind'] = 'unpublished-class-component'
return result, dict(added=added, replaced=replaced)
# ---------------------------------------------------------------- tooltip renderer (offline check)
TOKEN = re.compile(r'\$(?:(?P<op>[*/])(?P<num>[0-9.]+);)?(?P<ref>[0-9]*)(?P<kind>[sSmMoOtTdDhHnNxXaArRqQuUeEbBfFiI])(?P<idx>[1-3]?)')
class Renderer:
"""Approximate native formatter over effective rows (flat player branch)."""
def __init__(self, view):
self.view = view
def _effect(self, spell, index):
return self.view.effects(spell).get(index)
def value(self, spell, kind, index):
v = self.view
misc = v.one('SpellMisc', spell)
k = kind.lower()
if k == 'd':
if not misc or not misc['DurationIndex']:
return None
d = v.rows['SpellDuration'].get(misc['DurationIndex'])
if not d or d['Duration'] <= 0:
return None
seconds = d['Duration'] / 1000
if seconds >= 60 and seconds % 60 == 0:
return '%g min' % (seconds / 60)
return '%g sec' % seconds
if k in 'hnu':
options = v.one('SpellAuraOptions', spell)
field = dict(h='ProcChance', n='ProcCharges', u='CumulativeAura')[k]
return '%d' % (options[field] if options else 0)
if k == 'r':
r = v.rows['SpellRange'].get(misc['RangeIndex']) if misc else None
return '%g' % r['RangeMax'][0] if r else None
if k == 'i':
restriction = v.one('SpellTargetRestrictions', spell)
return '%d' % restriction['MaxTargets'] if restriction and restriction['MaxTargets'] else None
i = int(index or 1) - 1
effect = self._effect(spell, i)
if effect is None:
return None
if k in 'sm':
base, var = effect['EffectBasePointsF'], effect['Variance']
low, high = base * (1 - abs(var) / 2), base * (1 + abs(var) / 2)
if kind == 'M':
return '%d' % round(abs(high))
if k == 'm' or round(low) == round(high):
return '%d' % round(abs(low))
return '%d to %d' % (round(abs(low)), round(abs(high)))
if k == 'o':
if not misc or not effect['EffectAuraPeriod']:
return None
d = v.rows['SpellDuration'].get(misc['DurationIndex'])
if not d or d['Duration'] <= 0:
return None
ticks = d['Duration'] // effect['EffectAuraPeriod']
return '%d' % round(abs(effect['EffectBasePointsF']) * ticks)
if k == 't':
return '%g' % (effect['EffectAuraPeriod'] / 1000) if effect['EffectAuraPeriod'] else None
if k == 'x':
return '%d' % effect['EffectChainTargets']
if k == 'a':
radius = v.rows['SpellRadius'].get(next((r for r in effect['EffectRadiusIndex'] if r), 0))
return '%g' % radius['Radius'] if radius else None
if k == 'q':
return '%d' % effect['EffectMiscValue'][0]
if k == 'e':
return '%g' % effect['EffectAmplitude']
if k == 'b':
return '%g' % effect['EffectPointsPerResource']
if k == 'f':
return '%g' % effect['EffectChainAmplitude']
return None
def render(self, spell, text):
unresolved = []
def replace(match, numeric=False):
ref = int(match['ref']) if match['ref'] else spell
kind = match['kind']
if numeric and kind.lower() == 's':
kind = 'm'
value = self.value(ref, kind, match['idx'])
if value is None:
unresolved.append(match[0])
return match[0]
if match['op'] and re.fullmatch(r'-?[0-9.]+', value):
n = float(match['num'])
number = float(value) * n if match['op'] == '*' else float(value) / n
value = '%g' % abs(number)
return value
def expression(match):
body = TOKEN.sub(lambda m: replace(m, True), match[1])
if not re.fullmatch(r'[0-9.+\-*/() ]+', body):
unresolved.append(match[0])
return match[0]
try:
value = eval(body, {'__builtins__': {}}, {}) # digits/operators only
except (SyntaxError, ZeroDivisionError):
unresolved.append(match[0])
return match[0]
return '%g' % round(abs(value), 1)
text = re.sub(r'\$[lgLG]([^:;]*):([^;]*);', lambda m: m[2], text)
text = re.sub(r'\$\{([^}]*)\}(?:\.[0-9])?', expression, text)
rendered = TOKEN.sub(replace, text)
return rendered, unresolved
SAMPLE_NAMES = ('Mind Flay', 'Pyroblast', 'Execute', 'Rend', 'Renew', 'Sinister Strike', 'Moonfire', 'Aimed Shot',
'Shadow Bolt', 'Holy Light', 'Lightning Bolt', 'Bloodthirst', 'Mortal Strike', 'Frostbolt', 'Fireball',
'Arcane Missiles', 'Shadow Word: Pain', 'Flash Heal', 'Corruption', 'Curse of Agony', 'Backstab',
'Eviscerate', 'Serpent Sting', 'Multi-Shot', 'Rejuvenation', 'Starfire', 'Seal of Righteousness',
'Consecration', 'Earth Shock', 'Healing Wave', 'Heroic Strike', 'Immolate', 'Blizzard', 'Sunder Armor')
def tooltip_check(view, scope, source, offsets):
"""Render every in-scope description/aura text from effective rows."""
renderer = Renderer(view)
results, failures = {}, []
for ident in scope:
record = view.rows['Spell'].get(ident)
if record is None or ident not in view.rows['SpellName']:
failures.append(dict(spell=ident, kind='missing-parent'))
continue
out = {}
for field in ('Description_lang', 'AuraDescription_lang'):
text, unresolved = renderer.render(ident, record[field])
out[field] = text
if unresolved:
failures.append(dict(spell=ident, field=field, tokens=unresolved))
results[ident] = out
sample = []
names = view.rows['SpellName']
for name in SAMPLE_NAMES:
ranks = [i for i in scope if names.get(i, {}).get('Name_lang') == name]
if not ranks:
sample.append((name, None))
continue
best = max(ranks, key=lambda i: (view.rows['Spell'][i]['NameSubtext_lang'], i))
sample.append((name, best))
return results, failures, sample
# ---------------------------------------------------------------- CLI
PRIORITY_COEFFICIENT_NAMES = ('Concussion Blow', 'Shield Slam', 'Execute', 'Bloodthirst', 'Mortal Strike',
'Heroic Strike', 'Cleave', 'Revenge', 'Thunder Clap', 'Rend', 'Deep Wound')
RELATIONSHIPS = {'Bloodrage': (2687, 29131), 'Enrage talent': (12317, 13045, 13046, 13047, 13048),
'Enrage buff': (12880, 14201, 14202, 14203, 14204), 'Blood Craze talent': (16487, 16489, 16492),
'Blood Craze buff': (16488, 16490, 16491)}
# Live observations the local tortoise rows do not explain (Octo fork behaviour, held).
OCTO_FORK_HELD = {
'Concussion Blow': 'Octo deals ~800-900 on high-level targets; local spell_template 12809/51600-51602 has '
'dmgClass melee, no AP flag, default coefficient -> flat $s2 (115..235). Coefficient unobserved.',
}
def coefficient_report(view, coefficients, scope, source, offsets):
"""Offline check: emitted native coefficients equal the server rule; priority formulas."""
mismatched, counted = [], Counter()
for ident in scope:
row = coefficients.get(ident)
if row is None:
counted['scope-not-in-server'] += 1
continue
bonus, _ = server_bonus(row, ident, source_spell(source, ident, offsets)['name'])
effects = view.effects(ident)
for index, want in bonus.items():
native = effects.get(index)
if native is None:
counted['effect-absent'] += 1
continue
ok = close(native['EffectBonusCoefficient'], want['sp']) and close(native['BonusCoefficientFromAP'], want['ap'])
counted['ap' if want['ap'] else 'sp' if want['sp'] else 'zero'] += 1
if not ok:
mismatched.append(dict(spell=ident, effect=index))
priority = []
for ident in scope:
name = source_spell(source, ident, offsets)['name']
if not name.startswith(PRIORITY_COEFFICIENT_NAMES):
continue
effects = view.effects(ident)
terms = []
for index in sorted(effects):
e = effects[index]
if not e['Effect']:
continue
term = '%s%d=%g' % ('s', index + 1, e['EffectBasePointsF'])
if e['BonusCoefficientFromAP']:
term += '+%.3g*AP' % e['BonusCoefficientFromAP']
if e['EffectBonusCoefficient']:
term += '+%.3g*SP' % e['EffectBonusCoefficient']
terms.append(term)
script = coefficients.get(ident, {}).get('script', '')
priority.append('coeff %s %s (%d)%s: %s' % (name, view.rows['Spell'].get(ident, {}).get('NameSubtext_lang', ''),
ident, ' [%s]' % script if script else '', ', '.join(terms)))
relations = {k: {i: dict(in_scope=i in scope, defined=i in view.rows['SpellName']) for i in v}
for k, v in RELATIONSHIPS.items()}
return dict(checked=dict(counted), mismatched=len(mismatched), mismatched_sample=mismatched[:50],
priority=priority, relationships=relations, octo_fork_held=OCTO_FORK_HELD)
def main():
parser = argparse.ArgumentParser(description=__doc__.split('\n')[0])
parser.add_argument('--source-dbc', type=Path, required=True)
parser.add_argument('--spell-chain', type=Path, required=True)
parser.add_argument('--package', type=Path, required=True)
parser.add_argument('--native', type=Path, action='append', required=True)
parser.add_argument('--db2', type=Path, default=Path.home() / 'Projects/WoW-Hybrid/servers/trinity-forever/install/bin/dbc/enUS')
parser.add_argument('--dbd', type=Path, default=Path.home() / 'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions')
parser.add_argument('--icon-listing', type=Path, required=True,
help='Client CASC icon listing (casc-tool list interface/icons/* --format csv)')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--report', type=Path, required=True)
parser.add_argument('--tooltip-sample', type=Path)
parser.add_argument('--item-set-links', action='store_true', help='Define missing ItemSetSpell bonus spells')
parser.add_argument('--trainer-spells', type=Path, help='Distinct npc_trainer/npc_trainer_template spell IDs')
parser.add_argument('--base-spell-visual', type=Path, help='Original 1.12 dbc.MPQ SpellVisual.dbc (identity rule)')
parser.add_argument('--server-coefficients', type=Path,
help='spell_template TSV: entry, effect1-3, effectApplyAuraName1-3, '
'effectBonusCoefficient1-3, customFlags, dmgClass, script_name')
parser.add_argument('--server-spell-mod', type=Path, help='spell_mod TSV: Id, Custom, DmgClass')
parser.add_argument('--scope-spells', type=Path,
help='JSON list of additional Source racial/pet/collection spell roots')
parser.add_argument('--package-only-spell-text', action='store_true',
help='Explicitly use accepted package text when the native Spell export is unavailable')
parser.add_argument('--defer-publication', action='store_true',
help='Stage encoded component rows; final composition must validate the working registry')
parser.add_argument('--component-output', type=Path,
help='Optional separate encoded class-row component (saved before merge/checks)')
args = parser.parse_args()
source = load_source(args.source_dbc)
offsets = spell_layout()
package = json.loads(args.package.read_text())
# Recovered working packages retain exact wire bodies without decoded
# records. Every native table overlaid by this consumer needs its pinned
# schema, rather than only the historically record-less SkillLineAbility.
overlay_schemas = {table: checked_schema(args.dbd, table) for table in NATIVE_TABLES}
view = NativeView(args.native, package['rows'], overlay_schemas,
package_only_spell_text=args.package_only_spell_text)
scope, class_lines, missing = class_scope(source, read_spell_chain(args.spell_chain))
explicit_scope = None
if args.scope_spells:
roots = json.loads(args.scope_spells.read_text())
before = len(scope)
scope, extra_missing = extend_scope(source, scope, roots)
missing = sorted(set(missing) | set(extra_missing))
explicit_scope = dict(roots=len(set(roots)), added_scope=len(scope) - before,
missing_source_ids=extra_missing)
maxima = {}
for table in ('SpellMisc', 'SpellEffect', 'SpellAuraOptions', 'SpellCooldowns', 'SpellPower', 'SpellLevels',
'SpellCategories', 'SpellTargetRestrictions', 'SkillLineAbility', 'SpellXSpellVisual', 'SpellDuration', 'SpellCastTimes', 'SpellRange', 'SpellRadius'):
meta = table_metadata(table)
maxima[table] = codec.db2_header(args.db2 / (table + '.db2'), meta[0], meta[1])
allocate = Allocator(view, maxima)
icons = icon_index(args.icon_listing, source)
base_visuals = set(DBC(args.base_spell_visual, 16).by_id) if args.base_spell_visual else None
visuals = visual_index(source, view, offsets, base_visuals)
item_set = None
if args.item_set_links:
# Live package ItemSetSpell links whose bonus spell the client lacks:
# new definitions only (existing natives stay owned by the item pipeline).
from item_set_compat import TABLES as SET_TABLES, fields as set_fields
_, set_layout, set_count = SET_TABLES['ItemSetSpell']
set_schema = set_fields(args.dbd / 'ItemSetSpell.dbd', set_layout, set_count)
links = package_set_links(package['rows'], set_schema)
roots = sorted({r['SpellID'] for r in links if r['SpellID'] not in view.rows['SpellName']})
known = [i for i in roots if i in source['Spell'].by_id]
graph = spell_tooltip_graph(source['Spell'], known)
extra = sorted(i for i in graph['records'] if i not in view.rows['SpellName'] and i not in scope)
item_set = dict(links=len(links), sets=len({r['ItemSetID'] for r in links}), missing_roots=len(roots),
roots_absent_from_source=sorted(set(roots) - set(known)),
closure_new_definitions=len(extra) - len([i for i in extra if i in roots]),
definitions=len(extra), root_ids=roots)
for ident in extra:
scope[ident] = ['item-set-bonus' if ident in roots else 'item-set-closure']
coefficients = read_server_coefficients(args.server_coefficients, args.server_spell_mod) \
if args.server_coefficients else None
records, report = plan(source, view, sorted(scope), offsets, icons=icons, visuals=visuals, allocate=allocate,
coefficients=coefficients)
if explicit_scope is not None:
report['explicit_scope'] = explicit_scope
if item_set is not None:
report['item_set'] = item_set
if args.trainer_spells:
trainer = {int(line.split()[0]) for line in args.trainer_spells.read_text().split('\n') if line.strip()}
wrappers, direct = trainer_wrappers(source, offsets, trainer)
defined = {r['ID'] for t, r, _ in records if t == 'SpellName'}
stats = Counter()
records.extend(wrapper_rows(source, view, offsets, wrappers, icons, allocate, defined, report['held'], stats))
missing_direct = sorted(i for i in direct if i not in view.rows['SpellName'] and i not in defined)
report['trainer'] = dict(trainer_spells=len(trainer), wrappers=len(wrappers),
trainer_offered_wrappers=sum('trainer-offered' in w['origins'] for w in wrappers.values()),
direct_trainer_spells=len(direct), direct_missing_natively=len(missing_direct),
direct_missing_sample=missing_direct[:50],
not_in_source_dbc=sorted(i for i in trainer if i not in source['Spell'].by_id)[:50],
stats=dict(stats))
tables = sorted({t for t, _, _ in records})
schemas = {t: checked_schema(args.dbd, t) for t in tables}
rows = package_rows(records, schemas)
component_path = args.component_output
if args.defer_publication and component_path is None:
component_path = args.report.with_name('component-rows.private.json')
if component_path is not None:
component_path.write_text(json.dumps(dict(kind='unpublished-class-component', policy=POLICY,
parent_package_sha256=hashlib.sha256(args.package.read_bytes()).hexdigest(),
publication_ready=False, rows=rows), separators=(',', ':'), ensure_ascii=False) + '\n')
merged, merge_report = merge(package, rows, publish=not args.defer_publication)
merged['class_spell_extension'] = dict(policy=POLICY, rows=len(rows), parent_package_sha256=hashlib.sha256(
args.package.read_bytes()).hexdigest(), installed=False, engine_loaded=False)
args.output.write_text(json.dumps(merged, separators=(',', ':'), ensure_ascii=False) + '\n')
origins = Counter(o for v in scope.values() for o in v)
report.update(scope=dict(in_scope_spells=len(scope), class_skill_lines=len(class_lines), origins=dict(origins),
missing_references=missing), rows_by_table=dict(Counter(r['table_name'] for r in rows)),
merge=dict(added=merge_report['added'], replaced=len(merge_report['replaced']),
replaced_rows=merge_report['replaced']),
visual_index=len(visuals), icon_index=len(icons),
unavailable_native_baselines=view.unavailable_baselines,
held_by_kind=dict(Counter(h['kind'] for h in report['held'])),
output_sha256=hashlib.sha256(args.output.read_bytes()).hexdigest(), push_id=merged.get('push_id'),
publication_ready=not args.defer_publication,
component_rows_path=str(component_path) if component_path is not None else None)
check_view = NativeView(args.native, merged['rows'], overlay_schemas,
package_only_spell_text=args.package_only_spell_text)
results, failures, sample = tooltip_check(check_view, sorted(scope), source, offsets)
lines = []
for name, ident in sample:
if ident is None:
lines.append('%s: not in scope' % name)
continue
rank = check_view.rows['Spell'][ident]['NameSubtext_lang']
lines.append('%s (%d, %s)\n %s' % (name, ident, rank, results[ident]['Description_lang']))
if results[ident]['AuraDescription_lang']:
lines.append(' aura: ' + results[ident]['AuraDescription_lang'])
if args.tooltip_sample:
args.tooltip_sample.write_text('\n'.join(lines) + '\n')
if coefficients is not None:
report['coefficients'] = coefficient_report(check_view, coefficients, scope, source, offsets)
if args.tooltip_sample:
with args.tooltip_sample.open('a') as handle:
for line in report['coefficients']['priority']:
handle.write(line + '\n')
report['tooltip_check'] = dict(rendered=len(results), unresolved_texts=len(failures),
unresolved=failures[:400], sample=[i for _, i in sample])
args.report.write_text(json.dumps(report, indent=1, ensure_ascii=False) + '\n')
print('class spells: scope %d, rows %d (added %d, replaced %d); tooltip texts unresolved %d' % (
len(scope), len(rows), merge_report['added'], len(merge_report['replaced']), len(failures)))
if __name__ == '__main__':
main()