Files

113 lines
7.3 KiB
Python

"""#34 (2026-11-25): Octo models for spawned GameObject displays the 70334 client has no row/model for (census
go-import-20261124/missing.json; 63 M2 here, WMOs separately). Octo MD20 v256 -> build8 fixups -> m2_equipment_convert
(conv8 options) -> MD21 container. FDIDs: the retail listfile FDID of the native path when it exists (none are in the
Classic store), else new FDIDs from 8830000. Hardcoded textures: client FDID with identical bytes, else the native path's
FDID when in store, else the Octo BLP added at a new FDID. Writes go-models.json (models, art, holds)."""
import json, struct, sys, hashlib, shutil, re
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')
from casc_asset_package import model_container
import m2_equipment_convert as c, octo_mpq, frozen_store as fs
# 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
W = Path(__file__).resolve().parent
md5 = lambda b: hashlib.md5(b).hexdigest(); sha = lambda b: hashlib.sha256(b).hexdigest()
st = fs.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
lf = {}
for l in open('/mnt/Games/@project/listfiles/community-listfile.csv', errors='replace'):
i, _, p = l.rstrip('\n').partition(';'); lf[p.lower()] = int(i)
FREE = [8830000]; assert not any(8830000 <= f < 8832000 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
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])
f = lf.get(path.lower().replace('\\', '/'))
if f in fids: return f
if h not in new_tex:
t = new_fdid(); out = W / 'out' / f'{t}.blp'; out.write_bytes(raw); new_tex[h] = t
art.append(dict(file_data_id=t, path=path.lower().replace('\\', '/'), ckey=h, kind='BLP', file=str(out)))
return new_tex[h]
missing = [r for r in json.load(open(W / 'classified.json')) if r['kind'] == 'm2']
src = W / 'src'; shutil.rmtree(src, ignore_errors=True); src.mkdir(); (W / 'out').exists() and shutil.rmtree(W / 'out'); (W / 'out').mkdir()
rows = []; by_member = {}
for r in missing:
member = r['octo_model'][:-4] + '.m2'; raw = read(member) or read(r['octo_model'])
assert raw and raw[:4] == b'MD20', member
raw = bytearray(raw); fix = []
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'))
elif k == 1 and name and read(name): struct.pack_into('<I', raw, k_o + 16 * i, 0); fix.append((i, 'type1 -> hardcoded'))
h = sha(raw); (src / f'{h}.m2').write_bytes(raw); by_member.setdefault(member, []).append(r['display'])
if h not in {x['sha256'] for x in rows}:
rows.append(dict(member=member, archive='octo', sha256=h, file=f'{h}.m2', magic='MD20', version=struct.unpack_from('<I', raw, 4)[0], fixups=fix))
json.dump(dict(matches=rows), open(src / 'manifest.json', 'w'), indent=1)
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 ('conv', 'conva', 'convb'): shutil.rmtree(W / d, ignore_errors=True)
a = c.batch(src / 'manifest.json', W / 'conva', canonicalize_rigid_views=True, **kw)
b = c.batch(src / 'manifest.json', W / 'convb', canonicalize_rigid_views=False, **kw)
conv = W / 'conv'; conv.mkdir(); recs = []; bb = {r['source_sha256']: r for r in b['records']}
for r in a['records']:
s = 'conva'
if not r['structural_conversion_complete'] and bb[r['source_sha256']]['structural_conversion_complete']: r = bb[r['source_sha256']]; s = 'convb'
for o in r.get('outputs', []): shutil.copy(W / s / o['file'], conv / o['file'])
recs.append(r)
models = {}; holds = []
for r in recs:
member = r['source_candidates'][0]['member']; base = member[:-3]
if not r['structural_conversion_complete']:
holds.append(dict(member=member, displays=by_member[member], reason=r.get('blocked') or r.get('blockers') or 'conversion incomplete')); continue
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 = lf.get(base + '.m2')
if m2f is None or m2f in fids: m2f = new_fdid()
skfs = []
for v in range(len(skinl)):
f = lf.get(f'{base}{v:02}.skin')
if f is None or f in fids: f = new_fdid()
skfs.append(f)
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(member=member, displays=by_member[member], reason='texture missing in Octo: %s' % bad)); continue
m2 = model_container(body, skfs, txid); (W / 'out' / f'{m2f}.m2').write_bytes(m2)
art.append(dict(file_data_id=m2f, path=base + '.m2', ckey=md5(m2), kind='M2', file=str(W / 'out' / f'{m2f}.m2')))
for v, (skf, skin) in enumerate(zip(skfs, skinl)):
(W / 'out' / f'{skf}.skin').write_bytes(skin)
art.append(dict(file_data_id=skf, path=base + f'{v:02}.skin', ckey=md5(skin), kind='SKIN', file=str(W / 'out' / f'{skf}.skin')))
models[member] = dict(displays=by_member[member], sequence_hash_rebuilt=hashed, m2=m2f, skins=skfs, txid=txid, box=list(struct.unpack_from('<6f', body, 0xA0)))
seen = set() # CASC compatibility names: [a-z0-9_./-] only, unique (the client resolves by FDID)
for x in art:
q = re.sub('[^a-z0-9_./-]', '_', x['path'].lower())
if q in seen: b, e = q.rsplit('.', 1); q = f"{b}_{x['file_data_id']}.{e}"
seen.add(q); x['path'] = q
json.dump(dict(models=models, art=art, holds=holds, next_free=FREE[0]), open(W / 'go-models.json', 'w'), indent=1)
print('models', len(models), 'displays', sum(len(m['displays']) for m in models.values()), 'held', len(holds), 'art', len(art), 'new textures', len(new_tex))
[print('HOLD', h) for h in holds]