Files

165 lines
10 KiB
Python

"""#144 (2026-11-27): creature displays whose Octo model is a Turtle-patch override (patch-3/4/5) of a Blizzard path.
The October creature-model mapping reused the native FDID of the same path, so these creatures render Blizzard's later
model with Turtle's textures (Molten Corehound 20807: white parts). Owner rule 2026-11-21: same name is not the same file.
For every such display used by a tw_world creature: convert the Octo model (build_m2 pipeline of content-gomodels) onto new
FDIDs, add a CreatureModelData copy of the row the display used (new FileDataID + GeoBox), point the display at it, and
resolve its texture variations from the Octo files (FDID with identical bytes, else a new FDID).
Inputs: ../../parity/turtle-override-creature-models-20261127.json, inputs/used_disp.txt (tw_world creature display ids)."""
import json, struct, sys, hashlib, shutil, re, collections
from pathlib import Path
sys.path.insert(0, '/mnt/Games/@project/wt-master-merge/ops'); sys.path.insert(0, '/mnt/Games/@project/gateway/ops/maps14-20261122')
H = Path(__file__).resolve().parent; sys.path.insert(1, str(H))
from casc_asset_package import model_container
import m2_equipment_convert as c, octo_mpq
# Load only this helper from the owning checkout; external build inputs keep
# their existing import paths. A stale master checkout must not supply hashing.
import importlib.util
_sequence_hash_spec = importlib.util.spec_from_file_location(
"_owned_m2_sequence_hash", Path(__file__).resolve().parents[1] / "m2_sequence_hash.py")
_sequence_hash_module = importlib.util.module_from_spec(_sequence_hash_spec)
_sequence_hash_spec.loader.exec_module(_sequence_hash_module)
native_sequence_hash = _sequence_hash_module.native_sequence_hash
import getdb2
md5 = lambda b: hashlib.md5(b).hexdigest(); sha = lambda b: hashlib.sha256(b).hexdigest()
LANE = Path('/mnt/Games/@project/gateway/runtime/continuation-20261113/claude-lane')
DUMP = LANE / 'octo-dbc-diff-20261122/dump'
ONLY = set(sys.argv[1:]) # optional display ids (pilot)
def rows(f):
for l in open(DUMP / f, errors='replace'):
yield dict(x.split('=', 1) for x in l.rstrip('\n').split('\t')[1:] if '=' in x)
def tsv(p):
out = {}
for l in open(p):
parts = l.rstrip('\n').split('\t'); d = dict(x.split('=', 1) for x in parts[1:] if '=' in x); out[int(parts[0])] = d
return out
norm = lambda p: p.lower().replace('\\', '/').replace('.mdx', '.m2')
ov = {p for p, mpq, _ in json.load(open(LANE / 'parity/turtle-override-creature-models-20261127.json'))
if not mpq.lower().startswith('patch.mpq') and p.startswith('creature/')}
octo_cmd = {r['ID']: norm(r['ModelName']) for r in rows('CreatureModelData.octo.tsv')}
used = {l.strip() for l in open(H / 'inputs/used_disp.txt') if l.strip()}
cdi = tsv(H / 'inputs/cdi.before.tsv'); cmd = tsv(H / 'inputs/cmd.before.tsv')
targets = []
for r in rows('CreatureDisplayInfo.octo.tsv'):
p = octo_cmd.get(r['ModelID'])
if p in ov and r['ID'] in used and (not ONLY or r['ID'] in ONLY): targets.append((int(r['ID']), p, r.get('TextureVariation', '')))
print('displays', len(targets), 'models', len({p for _, p, _ in targets}))
st = getdb2.store(); root = st.root; fids = set(); ck = {}
for g in st.layout['groups']:
f = 0
for i, (d,) in enumerate(struct.iter_unpack('<I', memoryview(root)[g['ids_offset']:g['ckeys_offset']])):
f += d; fids.add(f); ck.setdefault(root[g['ckeys_offset'] + 16 * i:g['ckeys_offset'] + 16 * i + 16].hex(), set()).add(f); f += 1
BASE = 8850000; FREE = [BASE]; assert not any(BASE <= f < BASE + 20000 for f in fids)
def new_fdid():
FREE[0] += 1; return FREE[0] - 1
def read(p):
try: return octo_mpq.read(p.replace('/', '\\'))
except Exception: return None
OUT = H / 'out'; shutil.rmtree(OUT, ignore_errors=True); OUT.mkdir()
art = []; new_tex = {}
def tex_fdid(path):
raw = read(path)
if raw is None: return None
h = md5(raw)
if h in ck: return min(ck[h])
if h not in new_tex:
t = new_fdid(); o = OUT / f'{t}.blp'; o.write_bytes(raw); new_tex[h] = t
art.append(dict(file_data_id=t, path='creature/octo_turtle/' + path.lower().replace('\\', '/').split('creature/', 1)[-1], ckey=h, kind='BLP', file=str(o)))
return new_tex[h]
# 1) convert every model once
src = H / 'src'; shutil.rmtree(src, ignore_errors=True); src.mkdir(); man = []
for p in sorted({p for _, p, _ in targets}):
raw = read(p) or read(p[:-3] + '.mdx'); assert raw and raw[:4] == b'MD20', p
raw = bytearray(raw); fix = [(0, 'cameras stripped (converter creature contract)')]
struct.pack_into('<II', raw, 292, 0, 0); struct.pack_into('<II', raw, 300, 0, 0)
k_n, k_o = struct.unpack_from('<II', raw, 92)
for i in range(k_n):
k, fl, ln, at = struct.unpack_from('<4I', raw, k_o + 16 * i)
name = bytes(raw[at:at + ln]).rstrip(b'\0').decode('latin1') if ln else ''
if k == 2 and ln and (':' in name or name.startswith(('\\', '/'))): struct.pack_into('<I', raw, k_o + 16 * i + 8, 0); fix.append((i, 'type2 name cleared'))
h = sha(raw); (src / f'{h}.m2').write_bytes(raw)
man.append(dict(member=p, archive='octo', sha256=h, file=f'{h}.m2', magic='MD20', version=struct.unpack_from('<I', raw, 4)[0], fixups=fix))
chunks = [[]]; size = 0
for m in man:
n = (src / m['file']).stat().st_size
if chunks[-1] and size + n > 120 << 20: chunks.append([]); size = 0
chunks[-1].append(m); size += n
kw = dict(allow_qualified_cutout_shader16=True, paired_single_texture_rule=True, convert_ribbons=True, convert_particles=True,
downgrade_hermite=True, convert_uv_animation=True, convert_lights=True, resample_step_visibility=True, drop_unreachable_events=True,
two_texture_rule=True, legacy_replaceable_types=True)
for d in ('conva', 'convb', 'conv'): shutil.rmtree(H / d, ignore_errors=True)
arec = []; brec = []
for i, ch in enumerate(chunks):
json.dump(dict(matches=ch), open(src / f'manifest{i}.json', 'w'), indent=1)
for r in c.batch(src / f'manifest{i}.json', H / 'conva' / str(i), canonicalize_rigid_views=True, creature=True, **kw)['records']: r['_dir'] = f'conva/{i}'; arec.append(r)
for r in c.batch(src / f'manifest{i}.json', H / 'convb' / str(i), canonicalize_rigid_views=False, creature=True, **kw)['records']: r['_dir'] = f'convb/{i}'; brec.append(r)
print('chunk', i, len(ch), flush=True)
conv = H / 'conv'; conv.mkdir(); bb = {r['source_sha256']: r for r in brec}; models = {}; holds = []
for r in arec:
if not r['structural_conversion_complete'] and bb[r['source_sha256']]['structural_conversion_complete']: r = bb[r['source_sha256']]
s = r['_dir']
member = r['source_candidates'][0]['member']; base = member[:-3]
if not r['structural_conversion_complete']:
holds.append(dict(model=member, reason=str(r.get('blocked') or r.get('blockers') or 'conversion incomplete'))); continue
for o in r.get('outputs', []): shutil.copy(H / s / o['file'], conv / o['file'])
body, hashed = native_sequence_hash((conv / (r['source_sha256'] + '.md20')).read_bytes())
skinl = [(conv / o['file']).read_bytes() for o in r['outputs'] if o['role'] == 'native-skin']
m2f = new_fdid(); skfs = [new_fdid() for _ in skinl]
n, o = struct.unpack_from('<II', body, 80); txid = []; bad = []
for i in range(n):
t, _, ln, no = struct.unpack_from('<IIII', body, o + 16 * i)
if t == 0:
name = body[no:no + ln].rstrip(b'\0').decode('latin1'); f = tex_fdid(name)
if f is None: bad.append(name); f = 0
txid.append(f)
else: txid.append(0)
if bad: holds.append(dict(model=member, reason='texture missing in Octo: %s' % bad)); continue
m2 = model_container(body, skfs, txid); (OUT / f'{m2f}.m2').write_bytes(m2)
q = 'creature/octo_turtle/' + base.split('creature/', 1)[-1]
art.append(dict(file_data_id=m2f, path=q + '.m2', ckey=md5(m2), kind='M2', file=str(OUT / f'{m2f}.m2')))
for v, (skf, skin) in enumerate(zip(skfs, skinl)):
(OUT / f'{skf}.skin').write_bytes(skin)
art.append(dict(file_data_id=skf, path=q + f'{v:02}.skin', ckey=md5(skin), kind='SKIN', file=str(OUT / f'{skf}.skin')))
models[member] = dict(m2=m2f, skins=skfs, box=list(struct.unpack_from('<6f', body, 0xA0)), hash_rebuilt=hashed)
# 2) CreatureModelData copies + CreatureDisplayInfo repoints
next_cmd = max(cmd) + 1; cmd_new = {}; cmd_rows = []; cdi_rows = []; skipped = []
def num(v):
try: return int(v)
except ValueError: return float(v)
for did, p, tv in targets:
if p not in models: skipped.append((did, 'model held')); continue
if did not in cdi: skipped.append((did, 'no client CDI row')); continue
old = int(cdi[did]['ModelID']); key = (old, p)
if key not in cmd_new:
if old not in cmd: skipped.append((did, f'client CMD {old} missing')); continue
src_row = cmd[old]; row = {'ID': next_cmd}
for k, v in src_row.items():
if k == 'ID': continue
row[k] = [num(x) for x in v.split(',')] if ',' in v else num(v)
row['FileDataID'] = models[p]['m2']; row['GeoBox'] = models[p]['box']
cmd_rows.append(row); cmd_new[key] = next_cmd; next_cmd += 1
names = [x for x in tv.split(',')]; dirp = p.rsplit('/', 1)[0]; tex = []
for nme in names[:3]:
tex.append(tex_fdid(f'{dirp}/{nme}.blp') or 0 if nme else 0)
cur = [int(x) for x in cdi[did]['TextureVariationFileDataID'].split(',')]
newtex = (tex + [0, 0, 0])[:3] + cur[3:]
missing = [n for n, t in zip(names[:3], tex) if n and not t]
if missing: skipped.append((did, f'variation texture missing in Octo {missing}')); continue
cdi_rows.append(dict(ID=did, ModelID=cmd_new[key], TextureVariationFileDataID=newtex))
seen = set()
for x in art:
q = re.sub('[^a-z0-9_./-]', '_', x['path'].lower())
if q in seen: bq, e = q.rsplit('.', 1); q = f"{bq}_{x['file_data_id']}.{e}"
seen.add(q); x['path'] = q
json.dump(cmd_rows, open(H / 'inputs/cmd-rows.json', 'w'), indent=0)
json.dump(cdi_rows, open(H / 'inputs/cdi-rows.json', 'w'), indent=0)
json.dump(dict(models=models, art=art, holds=holds, skipped=skipped, next_free=FREE[0]), open(H / 'crmodels.json', 'w'), indent=1)
print('models', len(models), 'held', len(holds), 'cmd rows', len(cmd_rows), 'cdi rows', len(cdi_rows), 'skipped', len(skipped),
'art', len(art), 'new textures', len(new_tex))
for h in holds[:20]: print('HOLD', h)
print(collections.Counter(r for _, r in skipped).most_common(8))