233 lines
14 KiB
Python
233 lines
14 KiB
Python
"""Build the 14 Turtle maps the client lacks (Octo client MPQs = Source, read-only).
|
|
|
|
Per map: OBJ0 (adt_split_candidate + native MODF scale), OBJ1 (adt_obj1), generated _lod.adt (fix-lod make_lod with
|
|
the client's flat donor), Source minimap tiles, converted custom WMO families and doodad M2s, WDT with all six MPHD
|
|
companions (empty lgt/occ/fogs/mpv, wdl from root heights, tex from the native TXMD catalogue), Map rows.
|
|
ROOT/TEX0 tiles were converted earlier (all57 batch) and are resident. Reproduction check: repro820.py (820 OBJ0
|
|
byte-equal to the accepted install). FDIDs from 8800000.
|
|
|
|
python3 build_maps14.py [map ...] (default: all 14)
|
|
"""
|
|
import json, struct, sys, hashlib, collections, re
|
|
from pathlib import Path
|
|
import numpy as np
|
|
HERE = Path(__file__).resolve().parent
|
|
sys.path.insert(0, str(HERE)); sys.path.insert(0, '/mnt/Games/@project/gateway/ops')
|
|
import client_read as R, octo_mpq as O, wmo_convert as WC, model_convert as MC
|
|
import source_map_wdt as smw, map_asset_preflight as terrain, adt_obj1, casc_asset_package as casc
|
|
from recover_bindings import chunks, maid
|
|
import liquid_repro as LQ
|
|
|
|
FIRST = 8800000
|
|
MAPS = {26: 'PVPZone05', 27: 'Sunnyglade', 28: 'PVPZone05', 451: 'development', 532: 'Karazahn', 800: 'KarazhanCrypt',
|
|
801: 'Moomoo', 802: 'Grove', 807: 'EmeraldSanctum', 813: 'Winterveil', 814: 'Karazahn40', 815: 'Giln',
|
|
817: 'HighElfPVP', 821: 'netherstormbg'}
|
|
SENT = 0xFFFFFFF0 # Source models absent from the Octo client itself (not drawn on Octo either)
|
|
DONOR = (1286528, 1290303, 1290304) # client flat donor lod / mapTexture / mapTextureN (fix-zero-lod)
|
|
OUT = HERE / 'build'; OUT.mkdir(exist_ok=True)
|
|
md5 = lambda d: hashlib.md5(d).hexdigest(); sha = lambda d: hashlib.sha256(d).hexdigest()
|
|
norm = lambda p: p.replace('\\', '/').lower()
|
|
|
|
# ---- client root content keys (reuse identical content) ----
|
|
ck2fdi = {}
|
|
_root = R.root
|
|
for g in R.rl['groups']:
|
|
ident = 0
|
|
for i, (dlt,) in enumerate(struct.iter_unpack('<I', memoryview(_root)[g['ids_offset']:g['ckeys_offset']])):
|
|
ident += dlt; ck2fdi.setdefault(bytes(_root[g['ckeys_offset'] + 16 * i:g['ckeys_offset'] + 16 * i + 16]).hex(), ident); ident += 1
|
|
assets = {}; by_md5 = {}; NEXT = [FIRST]; reused = collections.Counter()
|
|
def alloc(data, kind, ext, fdi=None):
|
|
m = md5(data)
|
|
if fdi is None:
|
|
if m in by_md5: return by_md5[m]
|
|
if m in ck2fdi: reused[kind] += 1; return ck2fdi[m]
|
|
fdi = NEXT[0]; NEXT[0] += 1
|
|
p = OUT / f'{fdi}{ext}'; p.write_bytes(data)
|
|
assets[fdi] = dict(file_data_id=fdi, kind=kind, file=str(p), content_key=m, sha256=sha(data), bytes=len(data),
|
|
path=f'wowhybrid/source-map/{sha(data)}{ext}')
|
|
by_md5[m] = fdi; return fdi
|
|
def reserve(n):
|
|
out = list(range(NEXT[0], NEXT[0] + n)); NEXT[0] += n; return out
|
|
|
|
# ---- textures: native only when byte-identical to Octo (import-octo-assets rule) ----
|
|
TEX = {}; tex_report = collections.Counter()
|
|
def tex_fdi(path):
|
|
p = norm(path)
|
|
if p in TEX: return TEX[p]
|
|
octo = O.read(p.replace('/', '\\')); nat = WC.LF.get(p); nat = nat if nat in WC.IDS else None
|
|
if octo is None and nat is None: tex_report['missing'] += 1; r = None
|
|
elif octo is None: tex_report['native_only'] += 1; r = nat
|
|
elif nat is not None and R.read_fdid(nat) == octo: tex_report['native_equal'] += 1; r = nat
|
|
else: tex_report['imported'] += 1; r = alloc(octo, 'blp', '.blp')
|
|
TEX[p] = r; return r
|
|
|
|
# ---- WMO path bindings: recovered (continents/accepted maps) > native listfile ----
|
|
RB = json.load(open(HERE / 'recovered-bindings.json'))
|
|
RW = {p: int(max(c, key=c.get)) for p, c in RB['wmos'].items()}
|
|
LFW = {}
|
|
for l in open('/mnt/Games/@project/listfiles/community-listfile.csv', encoding='utf-8', errors='replace'):
|
|
a, _, q = l.rstrip('\n').partition(';')
|
|
if q.endswith('.wmo'): LFW.setdefault(q.lower(), int(a))
|
|
def wmo_fdi(p):
|
|
p = norm(p)
|
|
if p in RW: return RW[p]
|
|
f = LFW.get(p); return f if f in WC.IDS else None
|
|
|
|
def model_box(fdi):
|
|
if fdi in assets: raw = Path(assets[fdi]['file']).read_bytes()
|
|
else:
|
|
try: raw = R.read_fdid(fdi)
|
|
except Exception: return None
|
|
if raw[:4] == b'MD21': raw = raw[8:8 + struct.unpack_from('<I', raw, 4)[0]]
|
|
if raw[:4] != b'MD20': return None
|
|
return struct.unpack_from('<6f', raw, 0xA0)
|
|
|
|
def strip_sentinels(obj0):
|
|
"""Drop MDDF placements bound to SENT and remap per-MCNK MCRD doodad references."""
|
|
top = [[t, b] for t, b in chunks(obj0)]
|
|
mddf = next(b for t, b in top if t == 'MDDF'); n = len(mddf) // 36
|
|
keep = [i for i in range(n) if struct.unpack_from('<I', mddf, 36 * i)[0] != SENT]
|
|
if len(keep) == n: return obj0, 0
|
|
remap = {old: new for new, old in enumerate(keep)}
|
|
for e in top:
|
|
if e[0] == 'MDDF': e[1] = b''.join(mddf[36 * i:36 * i + 36] for i in keep)
|
|
elif e[0] == 'MCNK':
|
|
sub = [[t, b] for t, b in chunks(e[1])]
|
|
for s in sub:
|
|
if s[0] == 'MCRD':
|
|
refs = struct.unpack(f'<{len(s[1]) // 4}I', s[1])
|
|
s[1] = b''.join(struct.pack('<I', remap[r]) for r in refs if r in remap)
|
|
e[1] = b''.join(t[::-1].encode() + struct.pack('<I', len(b)) + b for t, b in sub)
|
|
return b''.join(t[::-1].encode() + struct.pack('<I', len(b)) + b for t, b in top), n - len(keep)
|
|
|
|
# ---- fix-lod height/lod helpers (verbatim logic, client donor) ----
|
|
def root_heights(raw):
|
|
v9 = np.full((129, 129), np.nan, np.float32); v8 = np.full((128, 128), np.nan, np.float32); n = 0
|
|
for t, c in chunks(raw):
|
|
if t != 'MCNK': continue
|
|
ix, iy = struct.unpack_from('<2I', c, 4); z = np.float32(struct.unpack_from('<f', c, 0x68 + 8)[0])
|
|
for st, sc in chunks(c[128:]):
|
|
if st == 'MCVT':
|
|
h = np.frombuffer(sc[:580], '<f4') + z; a = h.reshape(-1)[:145]
|
|
o = np.stack([a[r * 17:r * 17 + 9] for r in range(9)]); i = np.stack([a[r * 17 + 9:r * 17 + 17] for r in range(8)])
|
|
v9[iy * 8:iy * 8 + 9, ix * 8:ix * 8 + 9] = o; v8[iy * 8:iy * 8 + 8, ix * 8:ix * 8 + 8] = i; n += 1
|
|
return (v9, v8) if n == 256 else None
|
|
DL = {t: c for t, c in chunks(R.read_fdid(DONOR[0]))}
|
|
LEVELS = list(struct.iter_unpack('<f4I', DL['MLLL'])); SKIRT = np.frombuffer(DL['MLSI'], '<u2'); assert len(DL['MLVH']) // 4 == 33025 + len(SKIRT)
|
|
def make_lod(v9, v8):
|
|
hv = np.concatenate([v9.reshape(-1), v8.reshape(-1)]).astype('<f4'); hv = np.concatenate([hv, hv[SKIRT] - np.float32(LEVELS[0][0])]).astype('<f4')
|
|
hd = bytearray(DL['MLHD']); struct.pack_into('<2f', hd, 4, float(hv[:33025].min()) - 32.0, float(hv[:33025].max()))
|
|
order = ['MVER', 'MLHD', 'MLVH', 'MLLL', 'MLND', 'MLVI', 'MLSI']
|
|
return b''.join(t[::-1].encode() + struct.pack('<I', len(c)) + c for t, c in ((t, bytes(hd) if t == 'MLHD' else hv.tobytes() if t == 'MLVH' else DL[t]) for t in order))
|
|
|
|
# ---- Source minimaps (fix-minimap: 256x256 DXT1 re-framed with the client's native minimap header) ----
|
|
MM0 = R.read_fdid(8548267); assert len(MM0) == 33940
|
|
TRS = {}
|
|
for l in O.read('textures\\Minimap\\md5translate.trs').decode('latin1').splitlines():
|
|
a, _, b = l.partition('\t')
|
|
if b and not l.lower().startswith('dir:'): TRS[a.strip().lower()] = b.strip()
|
|
def minimap(d, x, y):
|
|
name = TRS.get(f'{d.lower()}\\map{x:02d}_{y:02d}.blp')
|
|
b = O.read('textures\\Minimap\\' + name) if name else None
|
|
if not isinstance(b, bytes) or b[:4] != b'BLP2' or struct.unpack_from('<4B2I', b, 8) != (2, 0, 0, 0, 256, 256): return None
|
|
off, = struct.unpack_from('<I', b, 20); data = b[off:off + 32768]
|
|
return alloc(MM0[:1172] + data, 'minimap', '.blp') if len(data) == 32768 else None
|
|
|
|
# ---- native TXMD catalogue for .tex companions ----
|
|
CM = json.load(open(HERE / 'client-maps.json'))
|
|
CATALOG = {}
|
|
for mid, row in CM.items():
|
|
if not row['wdt']: continue
|
|
try: w = R.read_fdid(row['wdt'])
|
|
except Exception: continue
|
|
c = dict(chunks(w))
|
|
if 'MPHD' not in c: continue
|
|
tx = struct.unpack_from('<8I', c['MPHD'])[5]
|
|
if not tx: continue
|
|
try:
|
|
for k, v in smw.parse_tex(R.read_fdid(tx)).items(): CATALOG.setdefault(k, v)
|
|
except Exception: pass
|
|
|
|
def main(selected):
|
|
report = dict(maps={}, wmos={}, models={})
|
|
inv = json.load(open(HERE / 'inventory.json'))
|
|
# 1. doodad M2s the client lacks
|
|
for p in sorted({p for v in inv.values() for p in v['missing']['m2']}):
|
|
r, err = MC.convert(p)
|
|
if err: report['models'][p] = dict(status='absent-in-octo-client', bound=SENT); WC.RM[p] = SENT; continue
|
|
skin_ids = [alloc(s, 'skin', '.skin') for s in r['skins']]
|
|
tex_ids = [(tex_fdi(n) or 0) if typ == 0 else 0 for typ, n in r['textures']]
|
|
f = alloc(casc.model_container(r['body'], skin_ids, tex_ids), 'm2', '.m2'); WC.RM[p] = f
|
|
report['models'][p] = dict(status='converted', fdi=f, skins=skin_ids, textures=tex_ids)
|
|
# 2. custom WMO families
|
|
owners = collections.defaultdict(set)
|
|
for mid, v in inv.items():
|
|
for p in v['missing']['wmo']: owners[p].add(int(mid))
|
|
for p, maps in sorted(owners.items()):
|
|
raw, groups = WC.source_family(p)
|
|
raw, nulled = WC.null_absent_secondary(raw, lambda n: O.read(norm(n).replace('/', '\\')) is not None or WC.LF.get(norm(n)) in WC.IDS)
|
|
tex = {}
|
|
for t in WC.wmo_names(raw, 'MOTX'):
|
|
f = tex_fdi(t)
|
|
if f: tex[norm(t)] = f
|
|
dood = {norm(d): WC.model_fdi(d) for d in WC.wmo_names(raw, 'MODN')}; dood = {k: v for k, v in dood.items() if v and v != SENT}
|
|
gb = reserve(len(groups))
|
|
root, conv, audit = smw.numeric_wmo_family(raw, p, groups, map_ids=sorted(maps), texture_bindings=tex, group_bindings=gb,
|
|
doodad_bindings=dood, legacy_material_profile=WC.LEG(raw), **WC.SKY(raw),
|
|
native_observed_tuples=WC.tuples(raw) & (smw.NATIVE_OBSERVED_MATERIAL_TUPLES | smw.NATIVE_FLAG_UNION_MATERIAL_TUPLES))
|
|
for i, g in conv.items(): alloc(g, 'wmo-group', '.wmo', fdi=gb[i])
|
|
RW[norm(p)] = alloc(root, 'wmo-root', '.wmo')
|
|
report['wmos'][p] = dict(fdi=RW[norm(p)], groups=gb, absent_doodads=len(audit['absent_doodads']), maps=sorted(maps), nulled_secondary=nulled)
|
|
# 3. tiles + WDT per map
|
|
B57 = json.load(open('/mnt/Games/@project/gateway/runtime/continuation-20261026/all57-terrain-integrated-batch/all57-terrain-component-and-WDT-bindings.json'))
|
|
maps57 = {m['source_map_id']: m for m in B57['maps']}
|
|
empties = smw.empty_map_companions()
|
|
for mid in selected:
|
|
d = MAPS[mid]; m = maps57[mid]; tiles = {}; held = []; extra = {}; stats = collections.Counter()
|
|
cells = {}; used_tex = set()
|
|
for t in m['tile_bindings']:
|
|
xy = (t['x'], t['y']); b = t['bindings']
|
|
if 'TEX0' not in b: held.append(list(xy)); continue
|
|
root, lerr = LQ.native_root(d, xy)
|
|
if b.get('ROOT') and R.read_fdid(b['ROOT']) == root: rootf = b['ROOT']; stats['root_resident'] += 1
|
|
else: rootf = alloc(root, 'ADT-root', '.adt'); stats['root_new' if b.get('ROOT') else 'root_unheld'] += 1
|
|
src = O.read(f'World\\Maps\\{d}\\{d}_{xy[0]}_{xy[1]}.adt')
|
|
c = collections.defaultdict(bytes)
|
|
for tg, x in chunks(src): c[tg] += x
|
|
ids = {}
|
|
for q in {norm(x.decode('latin1')) for x in c['MMDX'].split(b'\0') if x}:
|
|
f = WC.model_fdi(q); ids[q] = f if f else SENT
|
|
for q in {norm(x.decode('latin1')) for x in c['MWMO'].split(b'\0') if x}:
|
|
f = wmo_fdi(q)
|
|
if not f: raise SystemExit(f'unbound WMO {q} on {mid} {xy}')
|
|
ids[q] = f
|
|
out, _ = terrain.adt_split_candidate(src, xy, file_data_ids=ids, roles=('obj0',))
|
|
obj0, dropped = strip_sentinels(smw.native_modf_scale(out['obj0'])[0]); stats['dropped_absent_doodads'] += dropped
|
|
obj1, a1 = adt_obj1.build_obj1(obj0, model_box); stats['obj1_held_models'] += len(a1['held_models'])
|
|
hh = root_heights(root)
|
|
lod = alloc(make_lod(*hh), 'ADT-lod', '.lod.adt') if hh else DONOR[0]
|
|
mm = minimap(d, *xy); stats['minimaps'] += bool(mm)
|
|
tiles[xy] = dict(ROOT=rootf, OBJ0=alloc(obj0, 'ADT-obj0', '.obj0.adt'), OBJ1=alloc(obj1, 'ADT-obj1', '.obj1.adt'), TEX0=b['TEX0'])
|
|
if mm: tiles[xy]['MINIMAP'] = mm
|
|
extra[xy] = lod
|
|
cells[xy] = smw.wdl_cell_from_root_adt(root)
|
|
used_tex |= {v for (v,) in struct.iter_unpack('<I', dict(chunks(R.read_fdid(b['TEX0']))).get('MDID', b'')) if v}
|
|
glob = {r: alloc(empties[r], 'WDT-' + r, '.' + r) for r in ('lgt', 'occ', 'fogs', 'mpv')}
|
|
glob['wdl'] = alloc(smw.compose_wdl(cells), 'WDT-wdl', '.wdl')
|
|
glob['tex'] = alloc(smw.compose_tex({f: CATALOG[f] for f in used_tex if f in CATALOG}), 'WDT-tex', '.tex')
|
|
wdt, _ = smw.compose_terrain_wdt(tiles, global_file_data_ids=glob)
|
|
wdt = bytearray(wdt); sp = terrain._global_wmo_chunk_spans(bytes(wdt))['MAID'][0]
|
|
for (x, y), lod in extra.items():
|
|
k = sp + (y * 64 + x) * 32; struct.pack_into('<I', wdt, k + 16, lod); struct.pack_into('<I', wdt, k + 24, DONOR[2])
|
|
wdt = bytes(wdt); back = smw.parse_wdt(wdt); assert back['tiles'].keys() == tiles.keys() and back['flags'] == 0x248
|
|
report['maps'][mid] = dict(directory=d, wdt=alloc(wdt, 'WDT', '.wdt'), active_tiles=len(tiles), held_tiles=held,
|
|
tex_entries=sum(f in CATALOG for f in used_tex), tex_missing=len(used_tex - set(CATALOG)), **stats)
|
|
print(mid, d, report['maps'][mid] | dict(held_tiles=len(held)), flush=True)
|
|
report.update(first_fdi=FIRST, last_fdi=NEXT[0] - 1, assets=sorted(assets.values(), key=lambda a: a['file_data_id']),
|
|
textures=dict(tex_report), reused_existing=dict(reused))
|
|
(HERE / 'build-report.json').write_text(json.dumps(report, indent=1))
|
|
print('assets', len(assets), 'fdi', FIRST, NEXT[0] - 1, 'textures', dict(tex_report), 'reused', dict(reused))
|
|
|
|
if __name__ == '__main__':
|
|
main([int(a) for a in sys.argv[1:]] or sorted(MAPS))
|