230 lines
13 KiB
Python
230 lines
13 KiB
Python
"""Compare every available source/selected spell and all direct/periodic coefficient slots."""
|
|
import argparse
|
|
import collections
|
|
import csv
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
OPS = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(OPS))
|
|
from spell_effect_coefficients import decision, f32
|
|
from class_spell_compat import server_bonus
|
|
from turtle_data import DBC, spell_layout
|
|
|
|
ROW_START = re.compile('(?m)^(\\d+)\\t(?=[A-Za-z_][A-Za-z_0-9]*=)')
|
|
FIELD = re.compile('\\t([A-Za-z_][A-Za-z_0-9]*)=')
|
|
|
|
def native(table, folder):
|
|
text = (folder / (table + '.tsv')).read_text()
|
|
records = list(ROW_START.finditer(text))
|
|
result = {}
|
|
for index, m in enumerate(records):
|
|
# One dump delimiter separates records. Interior newlines are part of
|
|
# a localized description. Normalize CRLF on both sides.
|
|
end = records[index + 1].start() if index + 1 < len(records) else len(text)
|
|
body = text[m.start():end].removesuffix('\n')
|
|
fields = FIELD.split(body)
|
|
row = dict(zip(fields[1::2], fields[2::2], strict=True))
|
|
ident = int(row['ID'])
|
|
assert int(m[1]) == ident and ident not in result
|
|
result[ident] = row
|
|
return result
|
|
|
|
|
|
def tsv(path):
|
|
with path.open() as f:
|
|
return list(csv.DictReader(f, delimiter='\t'))
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
for name in ('selected','out','world','shapes','original','definitions','cohort'):
|
|
ap.add_argument('--' + name, type=Path, required=True)
|
|
ap.add_argument('--effect-dir', type=Path)
|
|
args = ap.parse_args()
|
|
out = args.out
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
world = args.world
|
|
effective = {int(r['entry']): r for r in tsv(world / 'spell_template.tsv')}
|
|
original = args.original
|
|
dbc = DBC(original / 'Spell.dbc', 173)
|
|
cast = DBC(original / 'SpellCastTimes.dbc', 4).by_id
|
|
duration = DBC(original / 'SpellDuration.dbc', 4).by_id
|
|
def signed(i):
|
|
return i if i < 2 ** 31 else i - 2 ** 32
|
|
cast = {k: tuple(map(signed, row)) for k, row in cast.items()}
|
|
duration = {k: tuple(map(signed, row)) for k, row in duration.items()}
|
|
offsets = spell_layout(args.definitions / 'Spell.dbd')
|
|
native_effect = native('SpellEffect', args.effect_dir or args.selected)
|
|
spells = native('Spell', args.selected)
|
|
native_names = native('SpellName', args.selected)
|
|
levels = collections.defaultdict(list)
|
|
for row in native('SpellLevels',args.selected).values():
|
|
if row['DifficultyID']=='0':
|
|
levels[int(row['SpellID'])].append(int(row['SpellLevel']))
|
|
selected_durations = native('SpellDuration', args.selected)
|
|
misc = collections.defaultdict(list)
|
|
for row in native('SpellMisc',args.selected).values():
|
|
if row['DifficultyID']=='0':
|
|
misc[int(row['SpellID'])].append(row)
|
|
by_slot = collections.defaultdict(list)
|
|
for row in native_effect.values():
|
|
if row['DifficultyID']=='0':
|
|
by_slot[int(row['SpellID']), int(row['EffectIndex'])].append(row)
|
|
mod = {int(r['Id']): r for r in tsv(args.shapes / 'spell-mod-shapes.tsv')}
|
|
extra_flags = {int(r['Id']): int(r['AttributesEx3']) for r in tsv(args.shapes / 'spell-mod-bonus-flags.tsv')}
|
|
assert extra_flags.keys() == mod.keys()
|
|
for key in mod:
|
|
mod[key]['AttributesEx3'] = extra_flags[key]
|
|
effect_mod = {(int(r['Id']), int(r['EffectIndex'])): r for r in tsv(args.shapes / 'spell-effect-mod.tsv')}
|
|
assert all(int(r['DmgClass'])==int(mod[int(r['Id'])]['DmgClass']) and int(r['Custom'])==int(mod[int(r['Id'])]['Custom']) for r in tsv(world/'spell_mod.tsv'))
|
|
origin = {int(r['spell_id']): r['scope'] for r in tsv(args.cohort)}
|
|
formula_counts = collections.Counter()
|
|
record_counts = collections.Counter()
|
|
desc_counts = collections.Counter()
|
|
origins = collections.Counter()
|
|
sources = collections.Counter()
|
|
scope_rows = []
|
|
text_rows = []
|
|
changes = []
|
|
controls = []
|
|
read_ids = set()
|
|
for r in tsv(args.shapes/'spell-shapes.tsv'):
|
|
sid = int(r['entry'])
|
|
e = effective[sid]
|
|
read_ids.add(sid)
|
|
m = mod.get(sid, {})
|
|
def override(key,old):
|
|
value = int(m.get(key, -1))
|
|
return value if value >= 0 else int(old)
|
|
def body(col):
|
|
return bytes.fromhex(r['HEX(' + col + ')']).decode().replace('\r\n', '\n').replace('\r', '\n')
|
|
name = body('name')
|
|
tree = dbc.by_id.get(sid)
|
|
client = spells.get(sid, {})
|
|
scope = origin.get(sid, 'world-only')
|
|
for field,key in (('description','Description_lang'),('auraDescription','AuraDescription_lang')):
|
|
src = body(field)
|
|
sel = client.get(key)
|
|
old = dbc.string(tree[offsets[key]]) if tree else None
|
|
old = old.replace('\r\n', '\n').replace('\r', '\n') if old else old
|
|
status = 'missing-native' if sel is None else 'equal' if src == sel else 'text-differs'
|
|
desc_counts[field, status] += 1
|
|
tokens = lambda x: ','.join(re.findall('\\$(?:[0-9]+)?[A-Za-z]+[0-9]*', x or ''))
|
|
def text_sha(text):
|
|
return hashlib.sha256(text.encode()).hexdigest() if text is not None else ''
|
|
for label,body_text in (('source',src),('selected',sel)):
|
|
if body_text and '${' in body_text:
|
|
formula_counts[field, label] += 1
|
|
text_rows.append((sid,name,scope,field,status,src==old,tokens(src),tokens(sel),
|
|
text_sha(src),text_sha(sel),text_sha(old)))
|
|
spell=dict(id=sid,name=name,school=int(r['school']),level=int(r['spellLevel']),base_level=int(r['baseLevel']),
|
|
attributes_ex3=override('AttributesEx3',r['attributesEx3']),attributes=override('Attributes',r['attributes']),attributes_ex=override('AttributesEx',r['attributesEx']),cast=override('CastingTimeIndex',r['castingTimeIndex']),
|
|
duration=override('DurationIndex',r['durationIndex']),family=override('SpellFamilyName',r['spellFamilyName']),
|
|
family_mask=int(m.get('SpellFamilyFlags',0)) or int(r['spellFamilyFlags']),custom=int(e['customFlags'])|int(m.get('Custom',0)),
|
|
dmg_class=override('DmgClass',e['dmgClass']),script=e['script_name'],slots=[])
|
|
for index in range(3):
|
|
n = str(index + 1)
|
|
modifier = effect_mod.get((sid, index), {})
|
|
def get(key,typ=int):
|
|
v = modifier.get(key[0].upper() + key[1:])
|
|
return typ(v) if v is not None and float(v) != -1 else typ(r[key + n])
|
|
ef = get('effect')
|
|
aura = get('effectApplyAuraName')
|
|
period = get('effectAmplitude')
|
|
target = (get('effectImplicitTargetA'), get('effectImplicitTargetB'))
|
|
die = get('effectDieSides')
|
|
dice = get('effectBaseDice')
|
|
points = get('effectBasePoints')
|
|
low, high = (dice, dice) if die in (0, 1) else sorted((dice, die))
|
|
authoritative = (ef, aura, period, *target, points, dice, die)
|
|
original_fields=('Effect', 'EffectAura', 'EffectAuraPeriod', 'ImplicitTargetA',
|
|
'ImplicitTargetB', 'EffectBasePoints', 'EffectBaseDice', 'EffectDieSides')
|
|
odb = None
|
|
if tree:
|
|
source_values = [tree[offsets[field] + index] for field in original_fields]
|
|
odb = (*source_values[:5], *map(signed, source_values[5:]))
|
|
spell['slots'].append(dict(effect=ef,aura=aura,period=period,targets=target,
|
|
per_level=get('effectRealPointsPerLevel',float),combo=get('effectPointsPerComboPoint',float),bonus=float(e['effectBonusCoefficient'+n]),
|
|
mean=points+(low+high)/2,source_parity=odb==authoritative,original=odb))
|
|
possible,_=server_bonus(dict(custom=spell['custom'],dmg_class=spell['dmg_class'],school=spell['school'],script=spell['script'],
|
|
effects=[(s['effect'],s['aura'],s['bonus']) for s in spell['slots']]),sid,name)
|
|
for ix,s in enumerate(spell['slots']):
|
|
if s['effect']==0:
|
|
continue
|
|
rows = by_slot.get((sid, ix), [])
|
|
row = rows[0] if len(rows) == 1 else None
|
|
api = (None, None)
|
|
target = None
|
|
source = None
|
|
raw = None
|
|
if not row:
|
|
status = 'missing-native-slot' if not rows else 'ambiguous-native-slot'
|
|
elif not tree:
|
|
status = 'world-only-no-octo-row'
|
|
elif native_names.get(sid,{}).get('Name_lang')!=name:
|
|
status = 'native-name-differs'
|
|
else:
|
|
status,target,source,raw=decision(spell,ix,s['original'][:2],row,levels.get(sid,[None])[0] if len(levels.get(sid,[]))==1 else None,possible.get(ix),cast,duration)
|
|
if status in ('change','exact'):
|
|
choices = misc.get(sid, [])
|
|
native_misc = choices[0] if len(choices) == 1 else None
|
|
if not native_misc or int(native_misc['SchoolMask']) != 1 << spell['school']:
|
|
status = 'native-school-differs'
|
|
else:
|
|
attributes = list(map(int, native_misc['Attributes'].split(',')))
|
|
if attributes[3] & 0x20000000:
|
|
status = 'native-caster-modifiers-bypassed'
|
|
if s['effect']==6:
|
|
effective_duration = duration.get(spell['duration'])
|
|
native_duration = selected_durations.get(int(native_misc['DurationIndex']))
|
|
if not effective_duration or not native_duration or int(native_duration['Duration'])!=effective_duration[1]:
|
|
status = 'native-duration-differs'
|
|
# DB2 stores the roll as mean and relative variance. Those
|
|
# native values must recover the same integer endpoints.
|
|
base = s['original'][5]
|
|
dice, die = s['original'][6:]
|
|
low, high = sorted((dice, die)) if die not in (0, 1) else (dice, dice)
|
|
mean = float(row['EffectBasePointsF'])
|
|
variance = float(row['Variance'])
|
|
reconstructed = sorted((round(mean * (1 - variance / 2)), round(mean * (1 + variance / 2))))
|
|
if reconstructed != [base+low,base+high]:
|
|
status = 'native-roll-range-differs'
|
|
if row:
|
|
api = tuple((float(row[k]) for k in ('EffectBonusCoefficient', 'BonusCoefficientFromAP')))
|
|
record_counts[status] += 1
|
|
origins[scope, status] += 1
|
|
if source:
|
|
sources[source, status] += 1
|
|
if status=='change':
|
|
patch = dict(ID=int(row['ID']))
|
|
for key,want,have in zip(('EffectBonusCoefficient','BonusCoefficientFromAP'),target,api,strict=True):
|
|
if want!=f32(have):
|
|
patch[key] = want
|
|
if len(patch)==1:
|
|
raise AssertionError(('float comparison', sid, ix, target, api))
|
|
changes.append(patch)
|
|
scope_rows.append((sid,name,scope,ix,row['ID'] if row else '',s['effect'],s['aura'],spell['level'],s['bonus'],spell['script'],source or '',status,*api,*(raw or (None,None))))
|
|
if sid in (585,591,598,984,1004,6060,10933,10934,589,594,970,992,2767,10892,10893,10894,23881,23892,23893,23894,2054,2060,10965,10952):
|
|
controls.append(dict(spell=sid,slot=ix,name=name,record=int(row['ID']) if row else None,status=status,origin=source,api=api,source_coefficient=raw,roll_mean=s['mean'],period=s['period'],source_override=s['bonus'],level=spell['level']))
|
|
assert set(effective) == read_ids
|
|
def write(name,header,data):
|
|
with (out/name).open('w',newline='') as f:
|
|
w = csv.writer(f, delimiter='\t', lineterminator='\n')
|
|
w.writerow(header.split())
|
|
w.writerows(data)
|
|
write('effects.tsv','spell name scope slot record effect aura spell_level world_coefficient script source status selected_sp selected_ap expected_sp expected_ap',scope_rows)
|
|
write('descriptions.tsv','spell name scope field status matches_octo original_tokens selected_tokens source_sha256 selected_sha256 octo_sha256',text_rows)
|
|
write('spell-inventory.tsv','spell octo world selected description_present',[(i,int(i in dbc.by_id),int(i in read_ids),int(i in native_names),int(i in spells)) for i in sorted(set(dbc.by_id)|read_ids|set(native_names))])
|
|
(out / 'rows.json').write_text(json.dumps(sorted(changes, key=lambda v: v['ID']), indent=1) + '\n')
|
|
(out / 'controls.json').write_text(json.dumps(controls, indent=1) + '\n')
|
|
save = lambda cnt: {'/'.join(k) if isinstance(k, tuple) else k: v for k, v in sorted(cnt.items())}
|
|
summary=dict(octo_spells=len(dbc.rows),world_templates=len(read_ids),native_effect_rows=len(native_effect),selected_spells=len(spells),world_active_effect_slots=len(scope_rows),
|
|
source_fields_changed=sum(len(r)-1 for r in changes),changed_spells=len({r[0] for r in scope_rows if r[11]=='change'}),statuses=save(record_counts),description_statuses=save(desc_counts),description_formula_strings=save(formula_counts),origin_statuses=save(origins),coefficient_origins=save(sources),
|
|
spell_mod=len(mod),effect_mod=len(effect_mod))
|
|
(out / 'summary.json').write_text(json.dumps(summary, indent=1) + '\n')
|
|
print({k: v for k, v in summary.items() if not isinstance(v, dict)}, flush=True)
|
|
if __name__=='__main__':
|
|
main()
|