Files
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

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

155 lines
13 KiB
Python

#!/usr/bin/env python3
"""Build native per-item armor baselines and reviewed shield curve records.
Per-item baselines reproduce the70334 source formula and explicit installed
overlays, allowing ItemSparse armor deltas without changing shared curves. The
older whole-bucket shield conversion still rejects mixed armor and preserves
other native quality columns. Neither path invents item levels.
"""
import argparse,copy,hashlib,json,math,struct
from pathlib import Path
from item_sparse_compat import ROOT,fields,encode,check_db2,f32
TABLE=0xffbb8dc2;LAYOUT=0x7e6c94f9
NATIVE=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever/install/bin/dbc/enUS/ItemArmorShield.db2'
DBD=Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/ItemArmorShield.dbd'
ARMOR_TABLES={'ItemArmorShield':(TABLE,LAYOUT,2),'ItemArmorQuality':(0xb94a5807,0x2935aa9d,1),
'ItemArmorTotal':(0x029d50fe,0xeb155d51,5),'ArmorLocation':(0xb1911544,0xfb67352f,5)}
def native_armor_baseline(proto,qualities,totals,locations,shields):
"""Reproduce70334 ItemTemplate::GetArmor from effective native records.
This does not alter a global curve. Callers must include installed curve
hotfixes in the input tables, then convert only the per-item armor delta.
Missing records fail instead of inventing a zero baseline.
"""
identity={key:proto[key]for key in ('entry','class','subclass','inventory_type','item_level','quality')}
if any(type(v)is not int for v in identity.values()) or identity['class']!=4 or identity['subclass']not in(1,2,3,4,6):raise ValueError('Unreviewed armor item category')
if not 0<identity['entry']<=0x7fffffff or not 0<=identity['item_level']<=32767 or not 0<=identity['inventory_type']<=28 or not 0<=identity['quality']<=7:raise ValueError('Armor source identity bound')
level=identity['item_level'];quality=3 if identity['quality']==7 else identity['quality']
def find(rows,ident):
if not isinstance(rows,list) or len(rows)>4096 or len({r['ID']for r in rows})!=len(rows):raise ValueError('Duplicate/oversized native armor table')
match=[r for r in rows if r['ID']==ident]
if len(match)!=1:raise ValueError('Native armor baseline record missing')
return match[0]
def number(value):
if type(value)not in(int,float) or not math.isfinite(value) or value<0:raise ValueError('Invalid native armor coefficient')
try:return f32(value)
except (OverflowError,struct.error):raise ValueError('Native armor coefficient overflow')from None
if identity['subclass']==6:
row=find(shields,level)
if row.get('ItemLevel')!=level or not isinstance(row.get('Quality'),list) or len(row['Quality'])!=7:raise ValueError('Native shield armor baseline shape differs')
amount=number(row['Quality'][quality]);inputs={'ItemArmorShield':copy.deepcopy(row)}
else:
q=find(qualities,level);total=find(totals,level)
location=find(locations,5 if identity['inventory_type']==20 else identity['inventory_type'])
if total.get('ItemLevel')!=level or not isinstance(q.get('Qualitymod'),list) or len(q['Qualitymod'])!=7:raise ValueError('Native armor baseline shape differs')
material,modifier={1:('Cloth','Clothmodifier'),2:('Leather','Leathermodifier'),3:('Mail','Chainmodifier'),4:('Plate','Platemodifier')}[identity['subclass']]
amount=number(number(number(q['Qualitymod'][quality])*number(total[material]))*number(location[modifier]))
inputs={'ItemArmorQuality':copy.deepcopy(q),'ItemArmorTotal':copy.deepcopy(total),'ArmorLocation':copy.deepcopy(location)}
rounded=number(amount+f32(.5))
if not math.isfinite(rounded) or not 0<=rounded<4294967296:raise ValueError('Native armor baseline overflow')
return dict(kind='native-70334-item-armor-baseline',identity=identity,native_armor=int(rounded),inputs=inputs)
def generate(source,groups,native,schema):
buckets={(r['item_level'],r['quality']):r for r in groups};baselines={r['ID']:r for r in native};changed={};evidence=[]
if len(buckets)!=len(groups) or len(baselines)!=len(native):raise ValueError('Duplicate armor budget identity')
for p in source:
if p['class']!=4 or p['subclass']!=6:continue
level,quality=int(p['item_level']),int(p['quality'])
if (level,quality) not in buckets or level not in baselines:raise ValueError('Source/native shield budget missing')
g=buckets[level,quality]
if not 0<=quality<=6 or g['count']<1 or len(g['entries'])!=g['count'] or len(set(g['entries']))!=g['count'] or g['distinct_armor']!=1 or g['armor_min']!=g['armor_max'] or g['armor_min']!=p['armor'] or p['entry'] not in g['entries']:
raise ValueError('Nonuniform/stale shield bucket; per-item native armor support required')
value=int(p['armor'])
if not 0<=value<=0xffffffff:raise ValueError('Armor outside source uint32 bounds')
if int(struct.unpack('<f',struct.pack('<f',value))[0])!=value:raise ValueError('Armor cannot be represented exactly as native float')
row=changed.setdefault(level,copy.deepcopy(baselines[level]))
if row['ItemLevel']!=level or len(row['Quality'])!=7:raise ValueError('Native armor curve identity/shape differs')
row['Quality'][quality]=value
evidence.append({'item_level':level,'quality':quality,'all_server_entries':g['entries'],'count':g['count'],'native_before':baselines[level]['Quality'][quality],'authoritative_armor':value})
records=[]
for level,row in sorted(changed.items()):
raw=encode(row,schema);records.append({'table_name':'ItemArmorShield','table_hash':hex(TABLE),'id':level,'record':row,'wire_hex':raw.hex(),'sha256':hashlib.sha256(raw).hexdigest()})
return {'build':'1.60.1.70334','records':records,'bucket_evidence':evidence,
'limits':['Only selected shield buckets with uniform armor across the entire local DB are converted.',
'Mixed-value buckets fail instead of altering other shields or fabricating item levels.',
'No general cloth/leather/mail/plate/weapon conversion or gameplay equivalence claimed.']}
def snapshot(output):
from local_tortoise import db
if not output.resolve().is_relative_to(ROOT/'runtime') or output.exists():raise ValueError('Require new runtime snapshot output')
raw=db("SET SESSION group_concat_max_len=1048576; SELECT HEX(JSON_OBJECT('item_level',item_level,'quality',quality,'count',COUNT(*),'distinct_armor',COUNT(DISTINCT armor),'armor_min',MIN(armor),'armor_max',MAX(armor),'entries_csv',GROUP_CONCAT(entry ORDER BY entry SEPARATOR ','))) FROM tw_world.item_template WHERE class=4 AND subclass=6 GROUP BY item_level,quality ORDER BY item_level,quality;")
rows=[]
for line in raw.splitlines():
r=json.loads(bytes.fromhex(line).decode());r['entries']=list(map(int,r.pop('entries_csv').split(',')))
if len(r['entries'])!=r['count']:raise ValueError('Truncated shield group snapshot')
rows.append(r)
output.write_text(json.dumps(rows,indent=2)+'\n');print('Read',len(rows),'authoritative shield buckets; no DB/client changes.')
def effective_armor_tables(tables,package,schemas):
"""Validate and overlay curves once, shared by owned and bulk conversion."""
effective={};applied=[]
for name in ARMOR_TABLES:
rows=tables[name]
if not isinstance(rows,list) or len(rows)>4096 or len({r['ID']for r in rows})!=len(rows):raise ValueError('Native armor table identity/count bound')
keys={'ID',*(field[0]for field in schemas[name])}
for row in rows:
if set(row)!=keys or type(row['ID'])is not int or not 0<row['ID']<=0x7fffffff:raise ValueError('Native armor row schema/identity differs')
encode(row,schemas[name])
effective[name]={r['ID']:copy.deepcopy(r)for r in rows}
if package is not None:
from item_sparse_compat import package_payloads
if package.get('build')!='1.60.1.70334' or package.get('schema')!='wowstatic_camelot_1_60_1':raise ValueError('Armor overlay package build/schema differs')
push,_=package_payloads(package['rows'])
if package.get('push_id')!=push:raise ValueError('Armor overlay package content differs')
for row in package['rows']:
name=row['table_name']
if name not in ARMOR_TABLES:continue
if (row.get('record_status','valid')!='valid' or int(row['table_hash'],16)!=ARMOR_TABLES[name][0]
or set(row['record'])!={'ID',*(field[0]for field in schemas[name])}
or row['record'].get('ID')!=row['id'] or encode(row['record'],schemas[name]).hex()!=row['wire_hex']):raise ValueError('Armor overlay record differs from native schema')
effective[name][row['id']]=copy.deepcopy(row['record']);applied.append(dict(table=name,id=row['id']))
return {k:list(v.values())for k,v in effective.items()},applied
def baseline_profile(source,tables,package,schemas):
"""Overlay explicit compatibility curves before deriving per-item bases."""
if not isinstance(source,list) or not 1<=len(source)<=4096 or len({p['entry']for p in source})!=len(source):raise ValueError('Source armor identity/count bound')
values,applied=effective_armor_tables(tables,package,schemas)
baselines=[native_armor_baseline(p,values['ItemArmorQuality'],values['ItemArmorTotal'],values['ArmorLocation'],values['ItemArmorShield'])for p in sorted(source,key=lambda p:p['entry'])]
return dict(kind='native-70334-per-item-armor-baselines',build='1.60.1.70334',baselines=baselines,applied_curve_overlays=applied,
hotfix_overlays_considered=package is not None,global_curve_records_generated=0,installed=False,engine_accepted=False,gameplay_verified=False,
limits=['Per-item baseline components only; preserve actual source armor using ItemSparse EXTRA_ARMOR, never alter item level.',
'No appearance, item-set, durability, spell or full-equipment conversion claim; actual engine acceptance remains required.'])
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=['snapshot','generate','baselines']);p.add_argument('--output',type=Path,required=True)
for name in ('source','groups','native','qualities','totals','locations','package'):p.add_argument('--'+name,type=Path)
a=p.parse_args()
if not a.output.resolve().is_relative_to(ROOT):p.error('Output must stay in gateway')
if a.action=='snapshot':snapshot(a.output)
elif a.action=='baselines':
if any(getattr(a,n)is None for n in ('source','native','qualities','totals','locations')):p.error('Baselines require --source --native --qualities --totals --locations')
paths={name:getattr(a,arg)for name,arg in [('ItemArmorShield','native'),('ItemArmorQuality','qualities'),('ItemArmorTotal','totals'),('ArmorLocation','locations')]}
sha=lambda path:hashlib.sha256(path.read_bytes()).hexdigest()
input_pins={name:sha(path)for name,path in dict(paths,source=a.source,**({'package':a.package}if a.package else {})).items()}
schemas={};provenance={}
for name,(table,layout,count)in ARMOR_TABLES.items():
db2=NATIVE.with_name(name+'.db2');dbd=DBD.with_name(name+'.dbd');check_db2(db2,table,layout);schemas[name]=fields(dbd,layout,count)
provenance[name]=dict(db2_sha256=sha(db2),dbd_sha256=sha(dbd),table_hash=hex(table),layout_hash=hex(layout))
r=baseline_profile(json.loads(a.source.read_text()),{name:json.loads(path.read_text())for name,path in paths.items()},json.loads(a.package.read_text())if a.package else None,schemas)
if input_pins!={name:sha(path)for name,path in dict(paths,source=a.source,**({'package':a.package}if a.package else {})).items()}:raise ValueError('Armor baseline inputs changed during conversion')
reference=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever/src/server/game/Entities/Item/ItemTemplate.cpp'
for name in ARMOR_TABLES:
if sha(NATIVE.with_name(name+'.db2'))!=provenance[name]['db2_sha256'] or sha(DBD.with_name(name+'.dbd'))!=provenance[name]['dbd_sha256']:raise ValueError('Native armor definitions changed during conversion')
r.update(input_sha256=input_pins,native_tables=provenance,converter_sha256=sha(Path(__file__)),
reference_function=dict(name='ItemTemplate::GetArmor',source_file_sha256=sha(reference)))
a.output.write_text(json.dumps(r,sort_keys=True,indent=2)+'\n');print('Generated',len(r['baselines']),'per-item native armor baseline components; no curves/client/server changed.')
else:
if any(getattr(a,n) is None for n in ('source','groups','native')):p.error('Generation requires --source --groups --native')
check_db2(NATIVE,TABLE,LAYOUT);schema=fields(DBD,LAYOUT,2)
r=generate(json.loads(a.source.read_text()),json.loads(a.groups.read_text()),json.loads(a.native.read_text()),schema)
sha=lambda path:hashlib.sha256(path.read_bytes()).hexdigest()
r['native_tables']={'ItemArmorShield':{'table_hash':hex(TABLE),'layout_hash':hex(LAYOUT),'db2_sha256':sha(NATIVE),'dbd_sha256':sha(DBD)}}
r['input_sha256']={k:sha(getattr(a,k)) for k in ('source','groups','native')}
a.output.write_text(json.dumps(r,indent=2)+'\n');print('Generated',len(r['records']),'source-uniform native shield armor rows; actual-client validation required.')