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

367 lines
19 KiB
Python

#!/usr/bin/env python3
"""Source random properties ("of the X") as native 70334 ItemBonus lists.
REA contract (receipts in the report; no new binary analysis):
* Source (Tortoise/Octo 1.12): Item::SetItemRandomProperties stores the
ItemRandomProperties ID in ITEM_FIELD_RANDOM_PROPERTIES_ID (44) and its three
SpellItemEnchantment IDs in PROP_ENCHANTMENT_SLOT_0..2 (enchant slots 3..5).
item_template.random_property names an item_enchantment_template group.
* Native 70334 (wow_classic_beta ROOT): no ItemRandomProperties/ItemRandomSuffix
DB2 (FDIDs 1237441/1237592 absent) and ItemData has no RandomPropertiesID.
The original data expresses suffixes as ItemBonus lists: Type 2 = [ItemModType,
StatPercentEditor] and Type 5 = [ItemNameDescriptionID, priority] (e.g. list
12722 "of the Bear" = Sta/Str 6666 + suffix 14302), delivered through
ItemData.ItemBonusKey.BonusListIDs.
* Type 2 adds to StatPercentEditor of the matching or first empty (-1) stat
slot; the displayed value is round(StatPercentEditor*RandPropPoints*0.0001)
(item_sparse_compat.coefficient, in-game verified for ItemSparse rows).
Source equip-spell auras are mapped to the ItemModTypes the original suffix
lists use for the same suffix name; the name correlation is measured, not
assumed. Nothing installs, grants items or changes server behaviour.
"""
import argparse
from collections import Counter, defaultdict
import hashlib
import json
from pathlib import Path
import re
import struct
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from item_sparse_compat import coefficient # noqa: E402
from octo_client_data import canonical_sha256 # noqa: E402
import spell_passive_compat as codec # noqa: E402
from turtle_data import DBC # noqa: E402
POLICY = 'source-random-property-native-item-bonus-v1'
# table hash, layout (read from the pinned 70334 DB2 headers)
TABLES = {'ItemBonus': (0x8318900A, 0x79CD4525), 'ItemBonusList': (0x96232523, 0x22A28539),
'ItemNameDescription': (0x70C2E7FD, 0xB616608D)}
SUFFIX_COLOR = -11776 # every original "of ..." ItemNameDescription row
STAT = {0: 4, 1: 3, 2: 7, 3: 5, 4: 6} # aura29 misc -> ItemModType
RESIST = {4: 51, 8: 55, 16: 52, 32: 54, 64: 56} # aura22 school mask
QUALITY = {2: 'GoodF', 3: 'SuperiorF', 7: 'SuperiorF', 4: 'EpicF', 5: 'EpicF', 6: 'EpicF'}
DEFENSE_SKILL = 95
def budget_column(inventory_type, item_class, subclass):
"""Same RandPropPoints column rule as item_sparse_compat.intrinsic_stat_fields."""
inv = inventory_type
index = (0 if inv in (1, 4, 5, 7, 15, 17, 20, 25) else 1 if inv in (3, 6, 8, 10, 12)
else 2 if inv in (2, 9, 11, 14, 16, 23) else 3 if inv in (13, 21, 22)
else (3 if subclass == 19 else 0) if inv == 26 else 4 if inv == 28 else None)
if item_class == 2 and inv in (15, 26) and subclass in (2, 3, 18, 19):
index = 4
return index
def schema(dbd, table):
"""70334 hotfix body fields; noninline IDs omitted, inline IDs kept."""
text = (Path(dbd) / (table + '.dbd')).read_text()
kinds = {}
for line in text.split('LAYOUT', 1)[0].splitlines():
m = re.match(r'(int(?:<[^>]+>)?|float|locstring|string)\s+(\w+)\??', line)
if m:
kinds[m[2]] = m[1].split('<')[0]
marker = f'LAYOUT {TABLES[table][1]:08X}\n'
if text.count(marker) != 1:
raise ValueError('Missing 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)
out = []
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)
m = re.fullmatch(r'(\w+)(?:<(u?)(8|16|32|64)>)?(?:\[(\d+)\])?', line)
if not m:
raise ValueError('Unreviewed native field syntax')
name, unsigned, bits, count = m.groups()
out.append((name, kinds[name], int(bits or 32), bool(unsigned), int(count or 1)))
return out
def db2_max(path, table):
head = Path(path).read_bytes()[:208]
if head[:4] != b'WDC5' or struct.unpack_from('<II', head, 152) != TABLES[table]:
raise ValueError('Native DB2 header differs: ' + table)
return struct.unpack_from('<I', head, 164)[0]
def spell_stats(spell):
"""Equip-spell -> [(ItemModType, amount)] or a held reason."""
effects = [(spell['effect%d' % i], spell['effectApplyAuraName%d' % i], spell['effectMiscValue%d' % i],
spell['effectBasePoints%d' % i], spell['effectDieSides%d' % i]) for i in (1, 2, 3)]
effects = [e for e in effects if e[0]]
if not effects or any(e[0] != 6 for e in effects):
return None, 'non-aura-effect'
if any(e[4] != 1 for e in effects):
return None, 'random-amount'
amounts = {e[3] + 1 for e in effects}
auras = tuple(sorted((e[1], e[2]) for e in effects))
if len(amounts) != 1:
return None, 'mixed-amounts'
amount = amounts.pop()
if len(effects) == 1:
aura, misc = effects[0][1], effects[0][2]
if aura == 29 and misc in STAT: return [(STAT[misc], amount)], None
if aura == 22 and misc in RESIST: return [(RESIST[misc], amount)], None
if aura == 13 and misc and misc & (misc - 1) == 0 and 2 <= misc <= 64:
return [(83 + misc.bit_length() - 1, amount)], None
if aura == 135 and misc == 126: return [(41, amount)], None
if aura == 124: return [(39, amount)], None
if aura == 161: return [(46, amount)], None
if aura == 85 and misc == 0: return [(43, amount)], None
if aura == 30 and misc == DEFENSE_SKILL: return [(12, amount)], None
return None, 'unmapped-aura-%d' % aura
if auras == ((99, 0), (124, 0)): return [(38, amount)], None
if auras == ((13, 126), (135, 126)): return [(45, amount)], None
return None, 'unmapped-aura-set'
class Effective:
"""Native exports overlaid by package rows (same table/id wins)."""
def __init__(self, native_dir, rows):
self.tables = {}
for t in ('Item', 'ItemSparse', 'ItemSet', 'ItemBonus', 'ItemBonusList', 'ItemNameDescription'):
self.tables[t] = {r['ID']: r for r in json.loads((Path(native_dir) / (t + '.json')).read_text())}
self.native_ids = {t: set(v) for t, v in self.tables.items()}
self.package_ids = defaultdict(set)
for r in rows:
t = r['table_name']
self.package_ids[t].add(r['id'])
if t in self.tables:
if r.get('record_status', 'valid') != 'valid':
self.tables[t].pop(r['id'], None)
elif isinstance(r.get('record'), dict):
self.tables[t][r['id']] = dict(r['record'], ID=r['id'])
def plan(source, irp, sie, eff, points, maxima):
spells = {r[0]: dict(zip(source['spell_columns'], r)) for r in source['spells']}
groups = defaultdict(list)
for entry, ench, _ in source['groups']:
groups[entry].append(ench)
names = defaultdict(list)
for r in eff.tables['ItemNameDescription'].values():
names[r['Description_lang']].append(r['ID'])
native_lists = defaultdict(list)
for r in eff.tables['ItemBonus'].values():
native_lists[r['ParentItemBonusListID']].append(r)
native_suffix_types = defaultdict(set)
suffix_in_lists = set()
for rs in native_lists.values():
s = [r for r in rs if r['Type'] == 5]
if s:
suffix_in_lists.add(s[0]['Value'][0])
native_suffix_types[eff.tables['ItemNameDescription'][s[0]['Value'][0]]['Description_lang']].add(
tuple(sorted(r['Value'][0] for r in rs if r['Type'] == 2)))
nxt = {t: maxima[t] + 1 for t in TABLES}
new_names, prop_cache, lists, mapping = {}, {}, {}, []
held, stats = Counter(), Counter()
held_props, correlation = {}, Counter()
def suffix_id(text):
if text in new_names: return new_names[text]
ids = sorted(names.get(text, []), key=lambda i: (i not in suffix_in_lists, i))
if ids: return ids[0]
new_names[text] = nxt['ItemNameDescription']; nxt['ItemNameDescription'] += 1
return new_names[text]
def prop(pid):
if pid in prop_cache: return prop_cache[pid]
row = irp.by_id.get(pid)
if row is None:
prop_cache[pid] = (None, 'property-absent'); return prop_cache[pid]
total = defaultdict(int)
for ench in row[2:5]:
if not ench: continue
e = sie.by_id.get(ench)
if e is None:
prop_cache[pid] = (None, 'enchantment-absent'); return prop_cache[pid]
for k in range(3):
kind, amount, arg = e[1 + k], e[4 + k], e[10 + k]
if not kind: continue
if kind == 4 and arg == 0:
total[50] += amount
elif kind == 3:
sp = spells.get(arg)
got, why = spell_stats(sp) if sp else (None, 'spell-absent')
if got is None:
prop_cache[pid] = (None, why); return prop_cache[pid]
for t, v in got: total[t] += v
else:
prop_cache[pid] = (None, 'enchant-type-%d' % kind); return prop_cache[pid]
suffix = irp.string(row[7])
if not suffix or not total:
prop_cache[pid] = (None, 'no-suffix-or-stats'); return prop_cache[pid]
native = native_suffix_types.get(suffix)
if native is not None:
correlation['agree' if tuple(sorted(total)) in native else 'differs'] += 1
else:
correlation['no-native-suffix-name'] += 1
prop_cache[pid] = ((suffix, dict(total)), None)
return prop_cache[pid]
items = sorted(source['items'])
for entry, group in items:
sparse, basic = eff.tables['ItemSparse'].get(entry), eff.tables['Item'].get(entry)
props = sorted(set(groups.get(group, [])))
if not props:
held['item:no-enchantment-group'] += 1; continue
if sparse is None or basic is None:
held['item:native-definition-absent'] += 1; stats['pairs_held'] += len(props); continue
quality = QUALITY.get(sparse['OverallQualityID'])
column = budget_column(sparse['InventoryType'], basic['ClassID'], basic['SubclassID'])
level = points.get(sparse['ItemLevel'])
if quality is None or column is None or level is None or sparse.get('ContentTuningID') or sparse.get('PlayerLevelToItemLevelCurveID'):
held['item:no-reviewed-budget'] += 1; stats['pairs_held'] += len(props); continue
budget = level[quality][column]
slots = list(zip(sparse['StatModifier_bonusStat'], sparse['StatPercentEditor']))
stats['items_resolved'] += 1
for pid in props:
got, why = prop(pid)
if got is None:
held['pair:' + why] += 1; held_props[pid] = why; stats['pairs_held'] += 1; continue
suffix, total = got
bonuses, free, ok = [], [i for i, (t, _) in enumerate(slots) if t == -1], True
for t in sorted(total):
at = next((i for i, (s, _) in enumerate(slots) if s == t), None)
base = slots[at][1] if at is not None else 0
shown = int(base * budget * .0001 + .5) if base else 0
want = coefficient(shown + total[t], budget)
if want is None or (at is None and not free):
ok = False; break
if at is None: free.pop(0)
bonuses.append((t, want - base))
if not ok:
held['pair:stat-slot-or-rounding'] += 1; stats['pairs_held'] += 1; continue
key = (suffix_id(suffix), tuple(bonuses))
if key not in lists:
lists[key] = nxt['ItemBonusList']; nxt['ItemBonusList'] += 1
mapping.append((entry, pid, lists[key]))
stats['pairs_resolved'] += 1
if nxt['ItemBonusList'] > 0xFFFF:
raise ValueError('ItemBonus.ParentItemBonusListID is u16')
records = [('ItemNameDescription', dict(ID=i, Description_lang=t, Color=SUFFIX_COLOR)) for t, i in sorted(new_names.items(), key=lambda x: x[1])]
for (suffix, bonuses), lid in sorted(lists.items(), key=lambda x: x[1]):
records.append(('ItemBonusList', dict(ID=lid, Flags=0)))
order = [(2, [t, c, 0, 0]) for t, c in bonuses] + [(5, [suffix, 0, 0, 0])]
for index, (kind, value) in enumerate(order):
records.append(('ItemBonus', dict(ID=nxt['ItemBonus'], Value=value, ParentItemBonusListID=lid, Type=kind, OrderIndex=index)))
nxt['ItemBonus'] += 1
report = dict(items=len(items), item_pairs=sum(len(set(groups.get(g, []))) for _, g in items),
stats=dict(stats), held=dict(held), distinct_lists=len(lists), new_suffix_names=sorted(new_names),
properties_resolved=sum(1 for v in prop_cache.values() if v[0]), properties_held=Counter(held_props.values()),
suffix_name_correlation=dict(correlation))
return records, sorted(mapping), report
def set_membership(eff, set_items):
"""Every effective ItemSet member: native/package Item+ItemSparse present?"""
out = dict(sets=0, members=0, both=0, missing=[], held_sets=Counter())
template = defaultdict(set)
for entry, sid in set_items:
template[sid].add(entry)
for sid, s in sorted(eff.tables['ItemSet'].items()):
members = [i for i in s['ItemID'] if i]
out['sets'] += 1
for i in members:
out['members'] += 1
if i in eff.tables['Item'] and i in eff.tables['ItemSparse']:
out['both'] += 1
else:
out['missing'].append(dict(set=sid, item=i, has_item=i in eff.tables['Item'],
has_sparse=i in eff.tables['ItemSparse'],
source_template=i in template.get(sid, ())))
out['held_sets'][sid] += 1
out['sets_complete'] = out['sets'] - len(out['held_sets'])
out['held_sets'] = dict(out['held_sets'])
return out
def header(mapping):
rows = ','.join('{%d,%d,%d}' % m for m in mapping) or '{0,0,0}'
return ('// Generated by ops/item_random_property_compat.py: source item+random property -> native ItemBonusList.\n'
'#pragma once\n#include <algorithm>\n#include <cstdint>\n#include <iterator>\n'
'namespace gateway::item_random_property_profile {\n'
'inline constexpr uint32_t ItemBonusListTable=0x%08x;\n' % TABLES['ItemBonusList'][0] +
'struct Row {uint32_t item,property,list;};\n'
'inline constexpr Row Rows[]={' + rows + '};\n'
'inline uint32_t resolve(uint32_t item,uint32_t property){\n'
' if(!item || !property)return 0;\n'
' auto p=std::lower_bound(std::begin(Rows),std::end(Rows),Row{item,property,0},[](const Row& a,const Row& b){return a.item<b.item || (a.item==b.item && a.property<b.property);});\n'
' return p!=std::end(Rows) && p->item==item && p->property==property?p->list:0;\n}\n}\n')
def stage_header(package):
"""Codec header for a package; the default include holds an empty table."""
ext = package.get('random_property_extension')
if not ext:
return None
mapping = [tuple(m) for m in ext['mapping']]
if mapping != sorted(set(mapping)) or any(len(m) != 3 for m in mapping):
raise ValueError('Random-property mapping must be sorted and unique')
lists = {r['id'] for r in package['rows'] if int(r['table_hash'],16) == TABLES['ItemBonusList'][0]
and r.get('record_status','valid') == 'valid'}
if not {m[2] for m in mapping} <= lists:
raise ValueError('Random-property mapping names a list absent from the package')
text = header(mapping)
if hashlib.sha256(text.encode()).hexdigest() != ext['header_sha256']:
raise ValueError('Random-property header differs from the package record')
return text
def main():
p = argparse.ArgumentParser(description=__doc__.split('\n')[0])
p.add_argument('--package', type=Path, required=True)
p.add_argument('--native', type=Path, required=True, help='DB2 JSON exports (all fields)')
p.add_argument('--octo-dbc', type=Path, required=True, help='Directory with ItemRandomProperties/SpellItemEnchantment.dbc')
p.add_argument('--server-dbc', type=Path, default=Path.home() / 'Servers/tortoise-docker/data/dbc')
p.add_argument('--source', type=Path, required=True, help='Tortoise random-property source snapshot')
p.add_argument('--points', type=Path, default=Path(__file__).resolve().parents[1] / 'runtime/target-70334-all-item-budgets-20261017.json')
p.add_argument('--db2', type=Path, default=Path.home() / 'Projects/WoW-Hybrid/servers/trinity-forever/install/bin/dbc/enUS')
p.add_argument('--dbd', type=Path, default=Path.home() / 'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions')
p.add_argument('--output', type=Path, required=True)
p.add_argument('--report', type=Path, required=True)
p.add_argument('--header', type=Path, required=True)
a = p.parse_args()
dbc = {}
for name, width in (('ItemRandomProperties', 16), ('SpellItemEnchantment', 24)):
path = a.octo_dbc / (name + '.dbc')
if hashlib.sha256(path.read_bytes()).digest() != hashlib.sha256((a.server_dbc / (name + '.dbc')).read_bytes()).digest():
raise ValueError('Octo client and server DBC differ: ' + name)
dbc[name] = DBC(path, width)
package = json.loads(a.package.read_text())
source = json.loads(a.source.read_text())
eff = Effective(a.native, package['rows'])
points = {r['ID']: r for r in json.loads(a.points.read_text())}
maxima = {t: max([db2_max(a.db2 / (t + '.db2'), t)] + list(eff.package_ids.get(t, [0]))) for t in TABLES}
records, mapping, report = plan(source, dbc['ItemRandomProperties'], dbc['SpellItemEnchantment'], eff, points, maxima)
schemas = {t: schema(a.dbd, t) for t in TABLES}
rows = []
for table, record in records:
wire = codec.encode(record, schemas[table])
rows.append(dict(table_name=table, table_hash='0x%08x' % TABLES[table][0], id=record['ID'], record=record,
wire_hex=wire.hex(), sha256=hashlib.sha256(wire).hexdigest(), policy=POLICY))
from class_spell_compat import merge
merged, merge_report = merge(package, rows)
merged['random_property_extension'] = dict(policy=POLICY, rows=len(rows), mapping=[list(m) for m in mapping],
parent_package_sha256=hashlib.sha256(a.package.read_bytes()).hexdigest(),
header_sha256=hashlib.sha256(header(mapping).encode()).hexdigest(), installed=False, engine_loaded=False)
a.output.write_text(json.dumps(merged, separators=(',', ':'), ensure_ascii=False) + '\n')
a.header.write_text(header(mapping))
report.update(rows_by_table=dict(Counter(t for t, _ in records)), merge=dict(added=merge_report['added'], replaced=len(merge_report['replaced'])),
schema_sha256={t: canonical_sha256(s) for t, s in schemas.items()}, total_rows=len(merged['rows']),
set_membership=set_membership(Effective(a.native, merged['rows']), source['set_items']),
installed=False, engine_loaded=False, gameplay_verified=False)
a.report.write_text(json.dumps(report, indent=1, default=list) + '\n')
s = report['stats']
print(f"pairs resolved {s.get('pairs_resolved', 0)}/{report['item_pairs']}; lists {report['distinct_lists']}; rows +{len(rows)}")
if __name__ == '__main__':
main()