Files

139 lines
8.7 KiB
Python

"""#76 catalogue rule (2026-11-26): Turtle helms whose model has an item texture slot (M2 texture type 2) but whose
ItemDisplayInfo carries no ModelMaterialResources render unpainted (owner: two helmets 'without paint' in Orgrimmar).
The rows came from Codex hotfix displays (755xxx-761xxx, ModelMaterialResourcesID 0) baked into the client DB2s.
2026-11-26 owner: audit all items -> every Turtle item (display_id>0, inputs/turtle-item-displays.tsv) resolve the Octo display's
ModelTexture name -> native item/objectcomponents/head/<name>.blp FDID present in the store, else the Octo bytes
(already in the store by content key, else imported as a new FDID). Then set IDI.ModelMaterialResourcesID[slot] and
add the ItemDisplayInfoModelMatRes row (TextureType 2) the 70334 renderer reads. New textures get TextureFileData rows.
Writes inputs/after/*.db2 + inputs/art.json. Displays shared by items with different Octo textures are held."""
import collections, hashlib, json, struct, subprocess, sys
from pathlib import Path
H = Path(__file__).resolve().parent; sys.path.insert(0, str(H))
sys.path.insert(0, '/mnt/Games/@project/gateway/ops/maps14-20261122'); import octo_mpq
import frozen_store as fs
TOOL = ['dotnet', '/mnt/Games/@project/wt-merge/ops/db2-bake-20261122/tool/bin/Debug/net10.0/Db2Bake.dll']
DEFS = '/mnt/Games/@project/tools/WoWDBDefs/definitions'
OCTO = Path('/mnt/Games/@project/gateway/runtime/continuation-20261113/claude-lane/octo-dbc-diff-20261122/octo/ItemDisplayInfo.dbc')
LISTFILE = '/mnt/Games/@project/listfiles/community-listfile.csv'
TABLES = {'ItemDisplayInfo': 1266429, 'ItemDisplayInfoModelMatRes': 4050937, 'TextureFileData': 982459,
'ModelFileData': 1337833, 'ItemAppearance': 0, 'ItemModifiedAppearance': 0}
NEW_FDID = 8890100
md5 = lambda b: hashlib.md5(b).hexdigest()
st = fs.Store(); root = st.root; lay = st.layout; assert lay['root_md5'] == fs.ROOT
ck = {}; bykey = collections.defaultdict(list); allf = set()
for g in lay['groups']:
f = 0
for i, (d,) in enumerate(struct.iter_unpack('<I', memoryview(root)[g['ids_offset']:g['ckeys_offset']])):
f += d; allf.add(f)
if g['locale'] & 2 and not g.get('flags1'):
k = root[g['ckeys_offset'] + 16 * i:g['ckeys_offset'] + 16 * i + 16].hex(); ck.setdefault(f, k); bykey[k].append(f)
f += 1
lf = {}; lfids = set(); fdir = {}; lpath = {}
for l in open(LISTFILE, encoding='utf8', errors='replace'):
a, p = l.rstrip('\n').split(';', 1); lfids.add(int(a))
if p.lower().startswith('item/objectcomponents/'): fdir[int(a)] = p.lower().split('/')[2]; lpath[int(a)] = p
if p.startswith('item/objectcomponents/'): lf.setdefault(p.lower().split('/')[-1], []).append((p.lower().split('/')[2], int(a)))
B = H / 'inputs/before'; A = H / 'inputs/after'
for name, fid in TABLES.items():
if fid and not (B / f'{name}.db2').exists(): (B / f'{name}.db2').write_bytes(st.read(ck[fid])[2])
for name in ('ItemAppearance', 'ItemModifiedAppearance'):
if not (B / f'{name}.db2').exists():
fid = {'ItemAppearance': 982462, 'ItemModifiedAppearance': 982457}[name]; (B / f'{name}.db2').write_bytes(st.read(ck[fid])[2])
def dump(t):
for l in subprocess.run(TOOL + ['dump', str(B), DEFS, t], capture_output=True, text=True, check=True).stdout.splitlines():
x = l.split('\t'); yield dict(a.split('=', 1) for a in x[1:])
tfd = {}; tex = collections.defaultdict(list)
for r in dump('TextureFileData'): tfd[int(r['FileDataID'])] = int(r['MaterialResourcesID']); tex[int(r['MaterialResourcesID'])].append(int(r['FileDataID']))
mod = collections.defaultdict(list)
for r in dump('ModelFileData'): mod[int(r['ModelResourcesID'])].append(int(r['FileDataID']))
mmr = collections.defaultdict(dict); nmmr = 0
for r in dump('ItemDisplayInfoModelMatRes'):
mmr[int(r['ItemDisplayInfoID'])][int(r['ModelIndex'])] = int(r['MaterialResourcesID']); nmmr = max(nmmr, int(r['ID']))
idi = {int(r['ID']): r for r in dump('ItemDisplayInfo')}
app = {int(r['ID']): int(r['ItemDisplayInfoID']) for r in dump('ItemAppearance')}
ima = collections.defaultdict(set)
for r in dump('ItemModifiedAppearance'): ima[int(r['ItemID'])].add(app.get(int(r['ItemAppearanceID'])))
b = OCTO.read_bytes(); _, n, nf, rs, _ = struct.unpack_from('<4s4I', b, 0); so = 20 + n * rs
def s(o): return b[so + o:b.index(b'\0', so + o)].decode()
octo = {}
for i in range(n):
r = struct.unpack_from('<%dI' % nf, b, 20 + i * rs); octo[r[0]] = (s(r[1]), s(r[2]), s(r[3]), s(r[4]))
cache = {}; gaps = set()
def types(f):
if f not in cache:
raw = st.read(ck[f])[2]; at = 0; md = None; txid = []
while at + 8 <= len(raw):
t, ln = struct.unpack_from('<4sI', raw, at)
if t == b'MD21': md = raw[at + 8:at + 8 + ln]
if t == b'TXID': txid = list(struct.unpack_from('<%dI' % (ln // 4), raw, at + 8))
at += 8 + ln
tc, to = struct.unpack_from('<II', md, 0x50) if md else (0, 0)
cache[f] = [struct.unpack_from('<I', md, to + 16 * k)[0] for k in range(tc)]
for k, ty in enumerate(cache[f]):
if ty == 0 and k < len(txid) and txid[k] and txid[k] not in allf: gaps.add(txid[k])
return cache[f]
art = []; newf = NEW_FDID; tex_of = {}
def resolve(name, want_dir):
global newf
key = name.lower()
if key in tex_of: return tex_of[key]
hits = [f for dd, f in lf.get(f'{key}.blp', []) if f in ck and dd == want_dir] or [f for dd, f in lf.get(f'{key}.blp', []) if f in ck]
if hits: tex_of[key] = min(hits); return tex_of[key]
raw = None
for dd in (want_dir, 'head', 'weapon', 'shield', 'shoulder', 'cape', 'quiver', 'ammo'):
try: raw = octo_mpq.read(f'Item\\ObjectComponents\\{dd}\\{name}.blp')
except Exception: raw = None
if raw: break
if not raw: tex_of[key] = None; return None
h = md5(raw)
if bykey.get(h): tex_of[key] = min(bykey[h]); return tex_of[key]
while newf in allf or newf in lfids: newf += 1
p = H / 'inputs/art' / f'{key}.blp'; p.parent.mkdir(exist_ok=True); p.write_bytes(raw)
art.append(dict(file=str(p), ckey=h, file_data_id=newf, path=f'item/objectcomponents/{want_dir}/{key}.blp', kind='BLP'))
tex_of[key] = newf; newf += 1; return tex_of[key]
want = collections.defaultdict(set); holds = []
for l in open(H / 'inputs/turtle-item-displays.tsv'):
item, od = map(int, l.split())
for d in ima.get(item, ()):
x = idi.get(d)
if not x or od not in octo: continue
mres = [int(v) for v in x['ModelResourcesID'].split(',')]; mats = [int(v) for v in x['ModelMaterialResourcesID'].split(',')]
for i in range(2):
if not mres[i]: continue
files = [f for f in mod.get(mres[i], []) if f in ck]
if not files: continue
ty = types(files[0])
if mats[i] or mmr[d].get(i) or 2 not in ty: continue
want[(d, i)].add((octo[od][2 + i], fdir.get(files[0], 'head')))
idi_set = {}; mm_rows = []; tfd_rows = []; nmr = max(tfd.values()) + 1
for (d, i), names in sorted(want.items()):
names = {x for x in names if x[0]}
if len(names) != 1: holds.append((d, i, sorted(names))); continue
f = resolve(*names.pop())
if not f: holds.append((d, i, 'texture absent on Octo too')); continue
if f not in tfd:
tfd[f] = nmr; tfd_rows.append(dict(ID=f, FileDataID=f, UsageType=0, MaterialResourcesID=nmr)); nmr += 1
m = tfd[f]
cur = idi_set.get(d) or [int(v) for v in idi[d]['ModelMaterialResourcesID'].split(',')]
cur[i] = m; idi_set[d] = cur
nmmr += 1; mm_rows.append(dict(ID=nmmr, MaterialResourcesID=m, TextureType=2, ModelIndex=i, ItemDisplayInfoID=d))
rows = {'ItemDisplayInfo': [dict(ID=d, ModelMaterialResourcesID=v) for d, v in sorted(idi_set.items())],
'ItemDisplayInfoModelMatRes': mm_rows, 'TextureFileData': tfd_rows}
for t, rr in rows.items():
(H / f'inputs/{t}-rows.json').write_text(json.dumps(rr, indent=0))
if not rr: continue
cmd = 'setrows' if t == 'ItemDisplayInfo' else 'addrows'
print(subprocess.run(TOOL + [cmd, str(B), DEFS, t, str(H / f'inputs/{t}-rows.json'), str(A / f'{t}.db2')], capture_output=True, text=True, check=True).stdout.strip())
for g in sorted(gaps): # hardcoded M2 texture absent from the native store: Octo file on the native FDID
p = lpath.get(g)
raw = None
if p:
try: raw = octo_mpq.read(p.replace('/', '\\'))
except Exception: raw = None
if not raw: holds.append((g, 'hardcoded texture absent on Octo too', p)); continue
out = H / 'inputs/art' / p.split('/')[-1]; out.parent.mkdir(exist_ok=True); out.write_bytes(raw)
art.append(dict(file=str(out), ckey=md5(raw), file_data_id=g, path=p, kind='BLP'))
(H / 'inputs/art.json').write_text(json.dumps(art, indent=1))
(H / 'inputs/holds.json').write_text(json.dumps(holds, indent=1))
print('displays', len(idi_set), 'slots', len(mm_rows), 'new TFD', len(tfd_rows), 'new art', len(art), 'holds', len(holds))