1159 lines
58 KiB
Python
1159 lines
58 KiB
Python
#!/usr/bin/env python3
|
|
"""Compose native 70334 terrain WDTs for Source-only (Octo) map IDs.
|
|
|
|
REA contract (runtime/continuation-20261110/map-wdt/rea.private.json):
|
|
every original 70334 terrain WDT (32 pinned bodies, e.g. Map30/36/47/129/189)
|
|
is exactly MVER(18) MPHD(32) MAIN(4096*8) MAID(4096*32); MPHD flags 0x248
|
|
(0x24a adds MCCV); active MAIN cells are (1,0) and inactive cells (2,0); each
|
|
active MAID row has rootADT/obj0ADT/obj1ADT/tex0ADT/minimapTexture present and
|
|
lodADT/mapTexture/mapTextureN zero. MPHD word 7 (pd4) is zero everywhere, so
|
|
zero is the observed "absent" value of an MPHD FileDataID word. The client
|
|
selects the WDT only through Map.db2 WdtFileDataID (map-activation REA).
|
|
|
|
Source-only maps have no native companions (lgt/occ/fogs/mpv/tex/wdl, minimap
|
|
tiles), so those words default to zero and stay a runtime-held question. An
|
|
empty OBJ1 uses the proven empty control 790799.
|
|
|
|
The WMO root helper reuses map_asset_preflight.classic_wmo_numeric_candidate
|
|
and writes 0 into MODI for doodad names that have no owning binding, keeping
|
|
every MODD placement and group MODR index unchanged.
|
|
"""
|
|
import struct
|
|
import math
|
|
import statistics
|
|
|
|
import map_asset_preflight as terrain
|
|
|
|
TILE_ROLES = terrain._TERRAIN_WDT_TILE_ROLES # rootADT obj0ADT obj1ADT tex0ADT lodADT mapTexture mapTextureN minimapTexture
|
|
GLOBAL_ROLES = terrain._TERRAIN_WDT_GLOBAL_ROLES + ('pd4',)
|
|
NATIVE_TERRAIN_FLAGS = 0x248
|
|
EMPTY_OBJ1 = 790799
|
|
_ROLE_INDEX = {'ROOT': 0, 'OBJ0': 1, 'OBJ1': 2, 'TEX0': 3, 'MINIMAP': 7}
|
|
_REQUIRED = ('ROOT', 'OBJ0', 'OBJ1', 'TEX0')
|
|
|
|
|
|
def _fdi(value, zero=False):
|
|
return type(value) is int and (0 if zero else 1) <= value <= 0xffffffff
|
|
|
|
|
|
def _chunk(tag, body):
|
|
return tag[::-1].encode('ascii') + struct.pack('<I', len(body)) + body
|
|
|
|
|
|
def compose_terrain_wdt(tiles, *, flags=NATIVE_TERRAIN_FLAGS, global_file_data_ids=None):
|
|
"""Return (wdt_bytes, audit) for explicit per-tile role bindings.
|
|
|
|
tiles: {(x, y): {'ROOT', 'OBJ0', 'OBJ1', 'TEX0'[, 'MINIMAP']}} with nonzero
|
|
FileDataIDs. Only listed tiles are active; every other cell is (2, 0).
|
|
"""
|
|
if flags not in (0x248, 0x24a):
|
|
raise ValueError('Only the observed native terrain MPHD profiles are admitted')
|
|
globals_ = dict.fromkeys(GLOBAL_ROLES, 0)
|
|
if global_file_data_ids:
|
|
if not set(global_file_data_ids) <= set(GLOBAL_ROLES) or \
|
|
not all(_fdi(v, zero=True) for v in global_file_data_ids.values()):
|
|
raise ValueError('Unknown or invalid MPHD global FileDataID')
|
|
globals_.update(global_file_data_ids)
|
|
if not isinstance(tiles, dict) or not tiles:
|
|
raise ValueError('Nonempty explicit tile bindings required')
|
|
main = bytearray(struct.pack('<II', 2, 0) * 4096)
|
|
maid = bytearray(4096 * 32)
|
|
for xy, roles in sorted(tiles.items()):
|
|
if (type(xy) is not tuple or len(xy) != 2
|
|
or any(type(v) is not int or not 0 <= v < 64 for v in xy)):
|
|
raise ValueError('Exact integer tile coordinates required')
|
|
if (not isinstance(roles, dict) or not set(_REQUIRED) <= set(roles)
|
|
or not set(roles) <= set(_ROLE_INDEX)
|
|
or not all(_fdi(v) for v in roles.values())):
|
|
raise ValueError('ROOT/OBJ0/OBJ1/TEX0 (optional MINIMAP) nonzero bindings required')
|
|
index = xy[1] * 64 + xy[0]
|
|
struct.pack_into('<II', main, index * 8, 1, 0)
|
|
words = [0] * 8
|
|
for role, value in roles.items():
|
|
words[_ROLE_INDEX[role]] = value
|
|
struct.pack_into('<8I', maid, index * 32, *words)
|
|
mphd = struct.pack('<8I', flags, *(globals_[r] for r in GLOBAL_ROLES))
|
|
output = (_chunk('MVER', struct.pack('<I', 18)) + _chunk('MPHD', mphd)
|
|
+ _chunk('MAIN', bytes(main)) + _chunk('MAID', bytes(maid)))
|
|
return output, dict(kind='source-only-native-terrain-WDT-v1', flags=flags,
|
|
globals=globals_, active_tiles=[list(xy) for xy in sorted(tiles)],
|
|
inactive_cell_state=[2, 0], zero_roles=['lodADT', 'mapTexture', 'mapTextureN'],
|
|
minimap_bound=sum('MINIMAP' in r for r in tiles.values()),
|
|
runtime_verified=False)
|
|
|
|
|
|
def parse_wdt(raw):
|
|
"""Decode a WDT produced here (or an original terrain WDT) for audits."""
|
|
spans = terrain._global_wmo_chunk_spans(raw)
|
|
if not {'MVER', 'MPHD', 'MAIN', 'MAID'} <= set(spans):
|
|
raise ValueError('MVER/MPHD/MAIN/MAID WDT required')
|
|
words = struct.unpack_from('<8I', raw, spans['MPHD'][0])
|
|
tiles = {}
|
|
for index in range(4096):
|
|
state = struct.unpack_from('<II', raw, spans['MAIN'][0] + index * 8)
|
|
if state[0] & 1:
|
|
tiles[(index % 64, index // 64)] = dict(zip(
|
|
TILE_ROLES, struct.unpack_from('<8I', raw, spans['MAID'][0] + index * 32)))
|
|
return dict(version=struct.unpack_from('<I', raw, spans['MVER'][0])[0], flags=words[0],
|
|
globals=dict(zip(GLOBAL_ROLES, words[1:])), tiles=tiles)
|
|
|
|
|
|
def _wmo_names(raw, tag):
|
|
out, at = [], 0
|
|
while at + 8 <= len(raw):
|
|
name = raw[at:at + 4][::-1].decode('latin1')
|
|
size = struct.unpack_from('<I', raw, at + 4)[0]
|
|
if name == tag:
|
|
body = raw[at + 8:at + 8 + size]
|
|
return [p.decode('ascii').replace('\\', '/').lower() for p in body.split(b'\0') if p]
|
|
at += 8 + size
|
|
return out
|
|
|
|
|
|
# Material tuples (flags, shader, blend) seen in native 70334 WMO roots but
|
|
# missing from map_asset_preflight's structural list. Same standard as that list
|
|
# (observed native assets). REA: runtime/continuation-20261110/map-wdt/
|
|
# rea-native-wmo-material-tuples.private.json, 860 native roots; examples are
|
|
# (2,0,0) in 112844 and (132,0,1) in 108077 (15 rows).
|
|
# 2026-11-12: (0,6,0) 110 rows, (17,0,0) 22 rows, (232,0,0) 2 rows in the same receipt (gap-tile buildings).
|
|
NATIVE_OBSERVED_MATERIAL_TUPLES = frozenset({(2, 0, 0), (132, 0, 1), (0, 3, 0), # (0,3,0): 110048
|
|
(197, 0, 1), (193, 0, 0), # 113992; 114998 and 461920
|
|
(0, 6, 0), (17, 0, 0), (232, 0, 0),
|
|
# 2026-11-22 full scan of all 1417 resident native roots
|
|
# (claude-lane/maps14-20261122/scan_tuples.py): (0,1,0) 228 rows
|
|
# (107234), (16,1,0) 7 (107243), (48,0,0) 5 (114998).
|
|
(0, 1, 0), (16, 1, 0), (48, 0, 0)})
|
|
# Flag-bit unions of tuples observed for the same (shader, blend): (5,0,0)
|
|
# = (1,0,0) | (4,0,0), (3,0,0) = (1,0,0) | (2,0,0), and
|
|
# (41,0,0) = (1,0,0) | (40,0,0). These preserve the source flags and
|
|
# shader 0/blend 0; the combinations are structurally admitted, not observed
|
|
# as complete tuples or accepted by the native renderer.
|
|
# 2026-11-22: (24,0,0) = (8,0,0) [9 native rows] | (16,0,0) [98]; (49,0,0) = (1,0,0) | (48,0,0).
|
|
NATIVE_FLAG_UNION_MATERIAL_TUPLES = frozenset({(5, 0, 0), (3, 0, 0), (41, 0, 0), (24, 0, 0), (49, 0, 0)})
|
|
|
|
|
|
def numeric_wmo_root(raw, root_path, *, texture_bindings, group_bindings, doodad_bindings,
|
|
native_observed_tuples=frozenset(), legacy_material_profile=None, sky_binding=None):
|
|
"""Numeric root via the existing converter; unbound doodad names -> MODI 0.
|
|
|
|
Returns (bytes, audit) where audit['absent_doodads'] lists the names whose
|
|
MODI word is 0 (no owning native/converted binding).
|
|
"""
|
|
referenced = _wmo_names(raw, 'MODN')
|
|
absent = sorted(p for p in set(referenced) if not _fdi(doodad_bindings.get(p)))
|
|
sentinel = {p: 0xfffff000 + n for n, p in enumerate(absent)}
|
|
if len(sentinel) > 0xfff:
|
|
raise ValueError('Too many unbound doodad names')
|
|
bindings = dict(doodad_bindings)
|
|
bindings.update(sentinel)
|
|
extra = frozenset(native_observed_tuples)
|
|
if not extra <= NATIVE_OBSERVED_MATERIAL_TUPLES | NATIVE_FLAG_UNION_MATERIAL_TUPLES:
|
|
raise ValueError('Material tuple not in the native-observed receipt')
|
|
allowed = terrain._WMO_STRUCTURAL_MATERIAL_TUPLES
|
|
terrain._WMO_STRUCTURAL_MATERIAL_TUPLES = allowed | extra
|
|
try:
|
|
out, audit = terrain.classic_wmo_numeric_candidate(
|
|
raw, root_path, texture_bindings=texture_bindings,
|
|
group_bindings=group_bindings, doodad_bindings=bindings, referenced_doodads_only=True,
|
|
**({'sky_binding': sky_binding} if sky_binding is not None else {}),
|
|
**({'legacy_material_profile': legacy_material_profile} if legacy_material_profile else {}))
|
|
finally:
|
|
terrain._WMO_STRUCTURAL_MATERIAL_TUPLES = allowed
|
|
by_sentinel = {v: p for p, v in sentinel.items()}
|
|
out = bytearray(out)
|
|
at, used = 0, []
|
|
while at + 8 <= len(out):
|
|
tag = bytes(out[at:at + 4][::-1]).decode('latin1')
|
|
size = struct.unpack_from('<I', out, at + 4)[0]
|
|
if tag == 'MODI':
|
|
for k in range(at + 8, at + 8 + size, 4):
|
|
value = struct.unpack_from('<I', out, k)[0]
|
|
if value in by_sentinel:
|
|
struct.pack_into('<I', out, k, 0)
|
|
used.append(by_sentinel[value])
|
|
at += 8 + size
|
|
out, liquid_flag_cleared = legacy_group_liquid_root(normalize_wmo_root_counts(bytes(out)))
|
|
out, mogi_flags_masked = native_mogi_flags(out)
|
|
out, lod_count_cleared = native_single_lod_root(out)
|
|
out, zero_scale_rows = native_wmo_doodad_scales(out)
|
|
audit = dict(audit, absent_doodads=sorted(used), MOHD_counts_from_emitted_chunks=True,
|
|
zero_scale_doodad_rows=zero_scale_rows,
|
|
source_doodad_transform_and_upper_flags_preserved=not zero_scale_rows,
|
|
legacy_group_liquid_flag_cleared=liquid_flag_cleared,
|
|
MOGI_group_data_flags_cleared=mogi_flags_masked,
|
|
MOHD_numLod_cleared=lod_count_cleared,
|
|
group_environment_complete=False,
|
|
required_environment_stage='numeric_wmo_family with original Source groups and map ownership',
|
|
absent_doodad_policy='MODI 0; MODD placements and group MODR preserved',
|
|
native_observed_material_tuples=sorted(extra))
|
|
return bytes(out), audit
|
|
|
|
|
|
# MOHD word index -> (chunk, record bytes). nTextures counts MOMT materials;
|
|
# a numeric root's nDoodadNames counts MODI FileDataIDs (MODN otherwise).
|
|
_MOHD_COUNTS = (('nTextures', 0, 'MOMT', 64), ('nGroups', 1, 'MOGI', 32),
|
|
('nPortals', 2, 'MOPT', 20), ('nLights', 3, 'MOLT', 48),
|
|
('nDoodadNames', 4, 'MODI', 4), ('nDoodadDefs', 5, 'MODD', 40),
|
|
('nDoodadSets', 6, 'MODS', 32))
|
|
|
|
|
|
def _wmo_root_chunks(raw):
|
|
out, at = [], 0
|
|
while at + 8 <= len(raw):
|
|
size = struct.unpack_from('<I', raw, at + 4)[0]
|
|
if at + 8 + size > len(raw):
|
|
raise ValueError('Truncated WMO root chunk')
|
|
out.append((raw[at:at + 4][::-1].decode('latin1'), at + 8, size))
|
|
at += 8 + size
|
|
if at != len(raw):
|
|
raise ValueError('Trailing WMO root bytes')
|
|
return out
|
|
|
|
|
|
def _wmo_root_records(raw):
|
|
spans = {tag: (at, size) for tag, at, size in _wmo_root_chunks(raw)}
|
|
if 'MOHD' not in spans or spans['MOHD'][1] < 28:
|
|
raise ValueError('WMO root MOHD required')
|
|
actual = {}
|
|
for name, word, tag, width in _MOHD_COUNTS:
|
|
if name == 'nDoodadNames' and 'MODI' not in spans:
|
|
at, size = spans.get('MODN', (0, 0))
|
|
actual[name] = sum(1 for p in raw[at:at + size].split(b'\0') if p)
|
|
else:
|
|
size = spans.get(tag, (0, 0))[1]
|
|
if size % width:
|
|
raise ValueError(f'{tag} extent is not a whole number of records')
|
|
actual[name] = size // width
|
|
return spans, actual
|
|
|
|
|
|
def wmo_root_count_audit(raw):
|
|
"""Compare every MOHD count with the records its chunk actually holds."""
|
|
spans, actual = _wmo_root_records(raw)
|
|
header = struct.unpack_from('<7I', raw, spans['MOHD'][0])
|
|
declared = {name: header[word] for name, word, _, _ in _MOHD_COUNTS}
|
|
mismatches = {n: dict(MOHD=declared[n], chunk=actual[n]) for n in declared if declared[n] != actual[n]}
|
|
extra = {}
|
|
if 'GFID' in spans and spans['GFID'][1] // 4 != actual['nGroups']:
|
|
extra['GFID'] = dict(groups=actual['nGroups'], GFID=spans['GFID'][1] // 4)
|
|
if 'MOPR' in spans:
|
|
at, size = spans['MOPR']
|
|
bad = sum(1 for k in range(at, at + size - 7, 8)
|
|
if struct.unpack_from('<H', raw, k)[0] >= actual['nPortals'])
|
|
if bad:
|
|
extra['MOPR_portal_index_out_of_range'] = bad
|
|
if 'MODS' in spans:
|
|
at, size = spans['MODS']
|
|
bad = [k for k in range(at, at + size, 32)
|
|
if sum(struct.unpack_from('<II', raw, k + 20)) > actual['nDoodadDefs']]
|
|
if bad:
|
|
extra['MODS_set_beyond_MODD'] = len(bad)
|
|
if extra:
|
|
mismatches.update(extra)
|
|
return dict(declared=declared, actual=actual, mismatches=mismatches)
|
|
|
|
|
|
def normalize_wmo_root_counts(raw):
|
|
"""Rewrite MOHD counts from the emitted chunks; every other byte unchanged."""
|
|
spans, actual = _wmo_root_records(raw)
|
|
output = bytearray(raw)
|
|
for name, word, _, _ in _MOHD_COUNTS:
|
|
struct.pack_into('<I', output, spans['MOHD'][0] + word * 4, actual[name])
|
|
audit = wmo_root_count_audit(bytes(output))
|
|
if audit['mismatches']:
|
|
raise ValueError('WMO root records are inconsistent beyond MOHD counts: %r' % audit['mismatches'])
|
|
return bytes(output)
|
|
|
|
|
|
# MOHD.flags (u16 at MOHD+60) bit 0x4 = groupLiquid is a LiquidType ID. Native
|
|
# roots with the bit mark dry groups with groupLiquid 0; legacy roots (bit clear)
|
|
# use 15 for "no group liquid" and take MLIQ types from the liquid itself. Source
|
|
# groups carry the legacy 15, so a converted root with the bit set makes the
|
|
# client treat every such group as filled liquid (underwater rendering, no breath).
|
|
MOHD_USE_LIQUID_TYPE_ID = 0x4
|
|
|
|
|
|
def legacy_group_liquid_root(raw):
|
|
"""Clear MOHD flag 0x4 so Source groups keep legacy liquid semantics; other bytes unchanged."""
|
|
spans, _ = _wmo_root_records(raw)
|
|
at, size = spans['MOHD']
|
|
if size < 64:
|
|
raise ValueError('WMO root MOHD lacks flags')
|
|
flags = struct.unpack_from('<H', raw, at + 60)[0]
|
|
if not flags & MOHD_USE_LIQUID_TYPE_ID:
|
|
return raw, False
|
|
out = bytearray(raw)
|
|
struct.pack_into('<H', out, at + 60, flags & ~MOHD_USE_LIQUID_TYPE_ID)
|
|
return bytes(out), True
|
|
|
|
|
|
# Source (1.12) roots copy each group's MOGP flags into MOGI. Native 70334
|
|
# MOGI never carries the MOGP data-presence bits (BSP 0x1, MOCV 0x4, MOLR 0x200,
|
|
# MODR 0x800, MLIQ 0x1000, 0x1000000/0x2000000/0x40000000): absent from every group of the 1419
|
|
# native roots (REA runtime/continuation-20261111/wmo-outdoor/
|
|
# census4.private.log), e.g. MOGP 0x1a49 -> MOGI 0x48. A converted exterior
|
|
# MOGI 0x1049 left the group unrendered whenever the camera was outdoors.
|
|
MOGI_GROUP_DATA_FLAGS = 0x1 | 0x4 | 0x200 | 0x800 | 0x1000 | 0x1000000 | 0x2000000 | 0x40000000
|
|
|
|
|
|
def native_mogi_flags(raw):
|
|
"""Clear MOGP-only data bits from every MOGI entry; returns (bytes, entries changed)."""
|
|
spans, _ = _wmo_root_records(raw)
|
|
if 'MOGI' not in spans:
|
|
return raw, 0
|
|
at, size = spans['MOGI']
|
|
out, changed = bytearray(raw), 0
|
|
for k in range(at, at + size - size % 32, 32):
|
|
flags = struct.unpack_from('<I', raw, k)[0]
|
|
if flags & MOGI_GROUP_DATA_FLAGS:
|
|
struct.pack_into('<I', out, k, flags & ~MOGI_GROUP_DATA_FLAGS); changed += 1
|
|
return (bytes(out), changed) if changed else (raw, 0)
|
|
|
|
|
|
# Source TerrainInfo::IsOutdoorWMO (Maps/GridMap.cpp) uses the high nibble,
|
|
# including its two global group exceptions and map30 tower overrides.
|
|
# Native70334 IsOutdoors2082f20 instead tests group flags bit0x8 before
|
|
# WMOAreaTable overrides. Never infer Source semantics from masked MOGI flags.
|
|
def source_wmo_outdoors(flags, group_id, *, source_root_id, map_ids):
|
|
if any(type(value)is not int or not 0<=value<=0xffffffff
|
|
for value in (flags,group_id))or(source_root_id is not None and
|
|
(type(source_root_id)is not int or not 0<=source_root_id<=0xffffffff)):
|
|
raise ValueError('Source WMO flags/group/root uint32 required')
|
|
# Without placement ownership, the only admissible answer is one proved
|
|
# identical for map30 and all other maps (the sole Source map branch).
|
|
if map_ids is None:
|
|
map_ids=(0,30)
|
|
elif (not isinstance(map_ids,(list,tuple))or not map_ids or
|
|
any(type(value)is not int or not 0<=value<=0xffffffff for value in map_ids)or
|
|
len(set(map_ids))!=len(map_ids)):
|
|
raise ValueError('Explicit unique Source map ownership required')
|
|
if source_root_id is None and 30 in map_ids and group_id not in (19307,19343):
|
|
raise ValueError('Source WMOID needed for map30-dependent environment')
|
|
source_flags=0x2a05 if group_id in (19307,19343) else flags
|
|
answers=set()
|
|
for map_id in map_ids:
|
|
current=0x2805 if map_id==30 and source_root_id in (0,4013,4193,4293) else source_flags
|
|
answers.add((current&0xf000)!=0x2000)
|
|
if len(answers)!=1:
|
|
raise ValueError('Map-dependent Source outdoor semantics require separate group resources')
|
|
return answers.pop()
|
|
|
|
|
|
def native_wmo_outdoor_flags(root, groups, *, source_root_id, map_ids, source_profiles):
|
|
"""Translate only bit0x8 in qualified Source MOGP/MOGI pairs.
|
|
|
|
Profiles retain original, unmasked MOGP flags and group IDs. `groups` may
|
|
contain a qualified subset; original native/reused groups are never guessed.
|
|
All other current bytes, IDs, geometry, liquid and reference flags survive.
|
|
This is an explicit Source-environment stage of the existing WMO pipeline.
|
|
"""
|
|
if (not isinstance(root,bytes)or not isinstance(groups,dict)or not groups or
|
|
not isinstance(source_profiles,dict)or set(groups)!=set(source_profiles)):
|
|
raise ValueError('Explicit Source group bodies and original flag profiles required')
|
|
spans,_=_wmo_root_records(root)
|
|
if 'MOGI'not in spans:raise ValueError('Source root MOGI required')
|
|
at,size=spans['MOGI']
|
|
if size%32:raise ValueError('MOGI entry extent')
|
|
out=bytearray(root);changed={};audit=[]
|
|
for index,body in sorted(groups.items()):
|
|
if type(index)is not int or not 0<=index<size//32 or not isinstance(body,bytes):
|
|
raise ValueError('Qualified Source group index/body required')
|
|
profile=source_profiles[index]
|
|
if set(profile)!={'flags','group_id'}:raise ValueError('Original Source MOGP flag/group profile required')
|
|
records={tag:(at,size)for tag,at,size in _wmo_root_chunks(body)}
|
|
if 'MOGP'not in records:raise ValueError('Complete MOGP required')
|
|
gp,extent=records['MOGP']
|
|
if extent<68:raise ValueError('Complete MOGP header required')
|
|
flags=struct.unpack_from('<I',body,gp+8)[0];group_id=struct.unpack_from('<I',body,gp+56)[0]
|
|
if group_id!=profile['group_id']or(flags^profile['flags'])&~8:
|
|
raise ValueError('Current group differs from original Source flag provenance')
|
|
outside=source_wmo_outdoors(profile['flags'],group_id,source_root_id=source_root_id,map_ids=map_ids)
|
|
target=(flags|8)if outside else(flags&~8)
|
|
updated=bytearray(body);struct.pack_into('<I',updated,gp+8,target)
|
|
if target!=flags:changed[index]=bytes(updated)
|
|
mogi_at=at+index*32;mogi_flags=struct.unpack_from('<I',out,mogi_at)[0]
|
|
native_mogi=(mogi_flags|8)if outside else(mogi_flags&~8)
|
|
struct.pack_into('<I',out,mogi_at,native_mogi)
|
|
audit.append({'group_index':index,'group_id':group_id,'source_flags':profile['flags'],
|
|
'prior_group_flags':flags,'native_group_flags':target,
|
|
'prior_mogi_flags':mogi_flags,'native_mogi_flags':native_mogi,'outdoors':outside})
|
|
return (bytes(out)if bytes(out)!=root else root),changed,audit
|
|
|
|
|
|
def numeric_wmo_family(raw, root_path, source_groups, *, map_ids, **root_inputs):
|
|
"""Complete Source root/group conversion with explicit environment ownership.
|
|
|
|
Keep original MOGP flags before any root data-bit masking or liquid stage.
|
|
Callers publish the returned group bodies under their supplied GFID bindings.
|
|
The lower-level root-only adapter remains a structural candidate; it cannot
|
|
establish group environment semantics without these original group inputs.
|
|
"""
|
|
spans,_=_wmo_root_records(raw);mohd,size=spans['MOHD']
|
|
if size<64:raise ValueError('Complete Source MOHD environment identity required')
|
|
count=struct.unpack_from('<I',raw,mohd+4)[0];root_id=struct.unpack_from('<I',raw,mohd+32)[0]
|
|
if not isinstance(source_groups,dict)or set(source_groups)!=set(range(count)):
|
|
raise ValueError('Complete original Source group family required')
|
|
profiles={};converted={}
|
|
for index,body in sorted(source_groups.items()):
|
|
normalized,detail=terrain.classic_wmo_group_candidate(body)
|
|
spans={tag:(at,size)for tag,at,size in _wmo_root_chunks(normalized)}
|
|
gp,size=spans['MOGP'];flags=struct.unpack_from('<I',normalized,gp+8)[0];group_id=struct.unpack_from('<I',normalized,gp+56)[0]
|
|
profiles[index]={'flags':flags,'group_id':group_id}
|
|
converted[index]=normalize_mogp_batch_counts(normalized)[0]
|
|
root,audit=numeric_wmo_root(raw,root_path,**root_inputs)
|
|
root,_=native_mogi_bounds(root,converted)
|
|
root,changed,environment=native_wmo_outdoor_flags(root,converted,source_root_id=root_id,map_ids=map_ids,source_profiles=profiles)
|
|
converted.update(changed)
|
|
return root,converted,dict(audit,environment_policy='Source-TerrainInfo-IsOutdoorWMO-to-native-group-bit8-v1',
|
|
source_root_id=root_id,source_map_ids=list(map_ids),source_group_profiles=profiles,
|
|
environment=environment,group_environment_complete=True)
|
|
|
|
|
|
# MOGI bounds. Native 70334 MOGI boxes equal their group's MOGP box (3663/3663
|
|
# groups, REA runtime/continuation-20261111/wmo-outdoor/bbox-census.private.log).
|
|
# Source roots can carry group 0 with the whole-root box (25 converted roots, e.g.
|
|
# Windhorn Canyon 8571000: MOGI[0] -966..88 vs MOGP -830..-685); the client then
|
|
# places an outdoor camera anywhere in the WMO inside that far exterior group and
|
|
# culls the rest of the WMO (canyon invisible outdoors, visible from the cave).
|
|
|
|
|
|
def native_mogi_bounds(root, groups):
|
|
"""Copy each MOGP bounding box into its MOGI entry.
|
|
|
|
`groups` maps MOGI index -> group file bytes (missing indices are left
|
|
alone). Returns (root, entries changed); other bytes unchanged.
|
|
"""
|
|
spans, _ = _wmo_root_records(root)
|
|
if 'MOGI' not in spans:
|
|
return root, 0
|
|
at, size = spans['MOGI']
|
|
out, changed = bytearray(root), 0
|
|
for index, raw in groups.items():
|
|
if not 0 <= index < size // 32:
|
|
raise ValueError('MOGI index out of range')
|
|
mogp = dict(_chunk_list(raw)).get('MOGP')
|
|
if mogp is None or len(mogp) < 36:
|
|
raise ValueError('WMO group lacks MOGP header')
|
|
box = mogp[12:36]
|
|
k = at + 32 * index + 4
|
|
if out[k:k + 24] != box:
|
|
out[k:k + 24] = box; changed += 1
|
|
return (bytes(out), changed) if changed else (root, 0)
|
|
|
|
|
|
# MOHD.numLod (u16 at MOHD+62). Every native 70334 root whose MOHD flags lack
|
|
# 0x1 and the LOD bit 0x10 (286/286 with flags 0) has numLod 0 and one GFID per
|
|
# group; the converter emitted numLod 1 with flags 0 (REA census.private.json).
|
|
MOHD_LOD = 0x10
|
|
|
|
|
|
def native_single_lod_root(raw):
|
|
"""numLod 1 -> 0 on a single-GFID-set root without LOD flags; returns (bytes, changed)."""
|
|
spans, _ = _wmo_root_records(raw)
|
|
at, size = spans['MOHD']
|
|
if size < 64:
|
|
raise ValueError('WMO root MOHD lacks flags')
|
|
flags, lods = struct.unpack_from('<HH', raw, at + 60)
|
|
groups = struct.unpack_from('<I', raw, at + 4)[0]
|
|
gfid = spans['GFID'][1] // 4 if 'GFID' in spans else groups
|
|
if lods != 1 or flags & (MOHD_LOD | 0x1) or gfid != groups:
|
|
return raw, False
|
|
out = bytearray(raw)
|
|
struct.pack_into('<H', out, at + 62, 0)
|
|
return bytes(out), True
|
|
|
|
|
|
# MODF+62 is padding in Source (1.12) ADT placements and the WMO scale in native
|
|
# ones (1024 = 1.0; every native ADT/WDT placement is nonzero). Copied Source
|
|
# padding 0 draws the WMO at zero size while the server keeps its collision.
|
|
MODF_UNIT_SCALE = 1024
|
|
MODF_HAS_SCALE = 0x4 # every native placement: flags 0xc (has scale | FileDataID)
|
|
|
|
|
|
def native_modf_scale(raw):
|
|
"""Native MODF scale: flag 0x4 set, scale 0 -> 1024; returns (bytes, placements changed)."""
|
|
out, changed, at = bytearray(raw), 0, 0
|
|
while at + 8 <= len(raw):
|
|
size = struct.unpack_from('<I', raw, at + 4)[0]
|
|
if at + 8 + size > len(raw):
|
|
raise ValueError('Truncated map chunk')
|
|
if raw[at:at + 4][::-1] == b'MODF':
|
|
if size % 64:
|
|
raise ValueError('MODF extent is not a whole number of placements')
|
|
for k in range(at + 8, at + 8 + size, 64):
|
|
flags, scale = struct.unpack_from('<H', raw, k + 56)[0], struct.unpack_from('<H', raw, k + 62)[0]
|
|
if scale == 0 or not flags & MODF_HAS_SCALE:
|
|
struct.pack_into('<H', out, k + 56, flags | MODF_HAS_SCALE)
|
|
struct.pack_into('<H', out, k + 62, scale or MODF_UNIT_SCALE); changed += 1
|
|
at += 8 + size
|
|
return bytes(out), changed
|
|
|
|
|
|
def native_wmo_doodad_scales(raw):
|
|
"""Preserve effectively hidden doodads without giving the client a singular transform."""
|
|
spans, _ = _wmo_root_records(raw)
|
|
start, size = spans.get('MODD', (0, 0))
|
|
changes = [i for i in range(size // 40)
|
|
if struct.unpack_from('<f', raw, start + 40 * i + 32)[0] == 0.0]
|
|
if not changes:
|
|
return raw, changes
|
|
out = bytearray(raw)
|
|
for i in changes:
|
|
# Same finite scale as the C01 converted-WMO correction.
|
|
struct.pack_into('<f', out, start + 40 * i + 32, 0.001)
|
|
return bytes(out), changes
|
|
|
|
|
|
def _chunk_list(raw):
|
|
return [(tag, raw[at:at + size]) for tag, at, size in _wmo_root_chunks(raw)]
|
|
|
|
|
|
def _pack_chunks(items):
|
|
return b''.join(tag[::-1].encode('latin1') + struct.pack('<I', len(data)) + data for tag, data in items)
|
|
|
|
|
|
# The 145 converted liquid groups currently use only these four uniform wet
|
|
# nibbles. The Source vmap extractor resolves a legacy nibble as n+1; all
|
|
# four resulting IDs exist in the recovered native 70334 LiquidType.db2.
|
|
# Other Source nibbles require a separate material/class proof.
|
|
SOURCE_WMO_NATIVE_LIQUID_IDS = {0: 1, 3: 4, 4: 5, 6: 7}
|
|
|
|
|
|
def _native_wmo_liquid_tile_flag(source_type, old):
|
|
"""Retain shared seams and water flow variants in native ID-mode flags.
|
|
|
|
The Source and native wet-cell 0x80 bits both mark overlap with another
|
|
group. Native ID 1/5 water permits 0x10/0x20 flow variants on unshared
|
|
cells; ID 4 slime and ID 7 magma do not. Shared cells use 0xC0 for all
|
|
classes. Dry holes keep only upper bits observed for their native class.
|
|
"""
|
|
if old & 0xf == 0xf:
|
|
return (old & 0x7f) if source_type in (0, 4) else 0x0f
|
|
if not old & 0x40:
|
|
raise ValueError('Source wet MLIQ tile lacks native base flag')
|
|
if old & 0x80:
|
|
return 0xc0
|
|
return 0x40 | ((old & 0x30) if source_type in (0, 4) else 0)
|
|
|
|
|
|
def emit_native_wmo_liquid_group(raw, *, liquid_type_id=None, align_surface_z=False):
|
|
"""Convert a legacy group MLIQ to native liquid-type-ID mode.
|
|
|
|
The Source WMO extractor obtains a legacy liquid entry from the first wet
|
|
tile's low nibble plus one. The caller can supply the expected DB2 ID to
|
|
prevent a silent class change. Native ID-mode groups round-trip exactly.
|
|
Geometry, wet coverage, vertex UV/opacity bytes, and heights are retained.
|
|
``align_surface_z`` is an explicit correction for groups whose MLIQ base Z
|
|
is far from their wet surface; it never changes the vertex heights.
|
|
"""
|
|
if type(raw) is not bytes:
|
|
raise ValueError('WMO group bytes required')
|
|
top = _chunk_list(raw)
|
|
if [tag for tag, _ in top].count('MOGP') != 1:
|
|
raise ValueError('One MOGP required')
|
|
mogp = next(body for tag, body in top if tag == 'MOGP')
|
|
if len(mogp) < 68:
|
|
raise ValueError('Complete MOGP header required')
|
|
sub = _chunk_list(mogp[68:])
|
|
liquid = [body for tag, body in sub if tag == 'MLIQ']
|
|
if len(liquid) > 1:
|
|
raise ValueError('Multiple MLIQ chunks')
|
|
flags = struct.unpack_from('<I', mogp, 8)[0]
|
|
if bool(flags & 0x1000) != bool(liquid):
|
|
raise ValueError('MOGP liquid flag and MLIQ presence disagree')
|
|
prior_type = struct.unpack_from('<I', mogp, 0x34)[0]
|
|
if not liquid:
|
|
# Native ID-mode groups may be flooded without a grid (for example a
|
|
# Deeprun Tram group). Only the legacy sentinel 15 becomes dry 0.
|
|
chosen = 0 if prior_type == 15 else prior_type
|
|
if liquid_type_id is not None and liquid_type_id != chosen:
|
|
raise ValueError('Requested liquid ID differs from group')
|
|
changed_tiles = changed_wet_tiles = changed_dry_tiles = 0
|
|
new_mliq = None
|
|
else:
|
|
mliq = liquid[0]
|
|
if len(mliq) < 30:
|
|
raise ValueError('Short MLIQ')
|
|
xv, yv, xt, yt = struct.unpack_from('<4I', mliq)
|
|
if not 2 <= xv <= 4096 or not 2 <= yv <= 4096 or (xt, yt) != (xv - 1, yv - 1):
|
|
raise ValueError('MLIQ vertex/tile dimensions differ from native grid')
|
|
tile_start = 30 + 8 * xv * yv
|
|
if len(mliq) != tile_start + xt * yt:
|
|
raise ValueError('MLIQ byte extent differs from native grid')
|
|
wet = [i for i, value in enumerate(mliq[tile_start:]) if value & 0xf != 0xf]
|
|
if not wet:
|
|
raise ValueError('MLIQ has no wet tile')
|
|
wet_types = {mliq[tile_start + i] & 0xf for i in wet}
|
|
if prior_type == 15:
|
|
if len(wet_types) != 1:
|
|
raise ValueError('Legacy MLIQ contains multiple liquid classes')
|
|
source_type = next(iter(wet_types))
|
|
if source_type not in SOURCE_WMO_NATIVE_LIQUID_IDS:
|
|
raise ValueError('Source liquid class lacks a native ID proof')
|
|
chosen = SOURCE_WMO_NATIVE_LIQUID_IDS[source_type]
|
|
if liquid_type_id is not None and liquid_type_id != chosen:
|
|
raise ValueError('Requested liquid ID differs from Source tile type')
|
|
else:
|
|
chosen = prior_type
|
|
if liquid_type_id is not None and liquid_type_id != chosen:
|
|
raise ValueError('Requested liquid ID differs from existing group')
|
|
if wet_types != {0}:
|
|
raise ValueError('ID-mode group has nonzero wet tile type')
|
|
if not 1 <= chosen <= 0xffffffff:
|
|
raise ValueError('Invalid LiquidType ID')
|
|
updated = bytearray(mliq)
|
|
changed_tiles = changed_wet_tiles = changed_dry_tiles = 0
|
|
if prior_type == 15:
|
|
for i, old in enumerate(mliq[tile_start:]):
|
|
at = tile_start + i
|
|
new = _native_wmo_liquid_tile_flag(source_type, old)
|
|
if new != old:
|
|
updated[at] = new
|
|
changed_tiles += 1
|
|
if old & 0xf == 0xf:
|
|
changed_dry_tiles += 1
|
|
else:
|
|
changed_wet_tiles += 1
|
|
if align_surface_z:
|
|
touched = set()
|
|
for i in wet:
|
|
x, y = i % xt, i // xt
|
|
touched.update((y*xv+x, y*xv+x+1, (y+1)*xv+x, (y+1)*xv+x+1))
|
|
heights = [struct.unpack_from('<f', mliq, 30 + 8*i + 4)[0] for i in touched]
|
|
if not heights or not all(-100000.0 <= z <= 100000.0 for z in heights):
|
|
raise ValueError('Nonfinite or implausible wet vertex height')
|
|
struct.pack_into('<f', updated, 24, statistics.median(heights))
|
|
new_mliq = bytes(updated)
|
|
header = bytearray(mogp[:68])
|
|
struct.pack_into('<I', header, 0x34, chosen)
|
|
new_sub = [(tag, new_mliq if tag == 'MLIQ' else body) for tag, body in sub]
|
|
new_mogp = bytes(header) + _pack_chunks(new_sub)
|
|
out = _pack_chunks([(tag, new_mogp if tag == 'MOGP' else body) for tag, body in top])
|
|
return out, dict(liquid_type_id=chosen, wet_tiles=len(wet) if liquid else 0,
|
|
changed_tile_flags=changed_tiles,
|
|
changed_wet_tile_flags=changed_wet_tiles,
|
|
changed_dry_tile_flags=changed_dry_tiles,
|
|
aligned_surface_z=bool(liquid and align_surface_z),
|
|
changed=out != raw)
|
|
|
|
|
|
def enable_native_wmo_liquid_ids(root):
|
|
"""Set MOHD 0x4 after *every* child group has ID-mode groupLiquid values."""
|
|
spans, _ = _wmo_root_records(root)
|
|
at, size = spans['MOHD']
|
|
if size < 64:
|
|
raise ValueError('WMO root MOHD lacks flags')
|
|
prior = struct.unpack_from('<H', root, at + 60)[0]
|
|
if prior & MOHD_USE_LIQUID_TYPE_ID:
|
|
return root, False
|
|
result = bytearray(root)
|
|
struct.pack_into('<H', result, at + 60, prior | MOHD_USE_LIQUID_TYPE_ID)
|
|
return bytes(result), True
|
|
|
|
|
|
def native_wmo_liquid_component(root_groups, seed_roots):
|
|
"""Close liquid-mode roots through every shared GFID group.
|
|
|
|
A group body is addressed by FileDataID, so two roots referencing that ID
|
|
cannot safely select different interpretations of its groupLiquid field.
|
|
Call with the full relevant root -> GFID roster, not only wet roots.
|
|
Return deterministic tuples of selected roots and all their child groups.
|
|
"""
|
|
owners = {}
|
|
normalized = {}
|
|
for root, groups in root_groups.items():
|
|
if type(root) is not int or root <= 0:
|
|
raise ValueError('Invalid WMO root FileDataID')
|
|
groups = tuple(groups)
|
|
if any(type(group) is not int or group <= 0 for group in groups) or len(set(groups)) != len(groups):
|
|
raise ValueError('Invalid or repeated GFID child')
|
|
normalized[root] = groups
|
|
for group in groups:
|
|
owners.setdefault(group, set()).add(root)
|
|
selected = set(seed_roots)
|
|
if not selected or any(type(root) is not int or root not in normalized for root in selected):
|
|
raise ValueError('Unknown or empty WMO liquid seed set')
|
|
frontier = list(selected)
|
|
while frontier:
|
|
root = frontier.pop()
|
|
for group in normalized[root]:
|
|
for other in owners[group] - selected:
|
|
selected.add(other)
|
|
frontier.append(other)
|
|
return tuple(sorted(selected)), tuple(sorted({group for root in selected for group in normalized[root]}))
|
|
|
|
|
|
def validate_native_wmo_liquid_owners(root_groups, root_flags, converted_groups):
|
|
"""Refuse a converted group whose any owning root lacks MOHD liquid-ID mode."""
|
|
converted_groups = tuple(converted_groups)
|
|
owners = {}
|
|
for root, groups in root_groups.items():
|
|
if root not in root_flags:
|
|
raise ValueError('Missing WMO root liquid-mode flags')
|
|
for group in groups:
|
|
owners.setdefault(group, set()).add(root)
|
|
for group in converted_groups:
|
|
if group not in owners:
|
|
raise ValueError('Converted WMO group has no owning root')
|
|
if any(not (root_flags[root] & MOHD_USE_LIQUID_TYPE_ID) for root in owners[group]):
|
|
raise ValueError('Shared WMO group has a legacy-mode owning root')
|
|
return len(converted_groups)
|
|
|
|
|
|
def normalize_mogp_batch_counts(raw):
|
|
"""Convert Source's cumulative exterior batch count to native counts.
|
|
|
|
Native MOGP trans/int/ext counts sum to the number of MOBA records. Some
|
|
Source groups put that total in ext instead. Only that recognized profile
|
|
is changed; other inconsistent headers are held for inspection.
|
|
"""
|
|
top = _chunk_list(raw)
|
|
mogp = [body for tag, body in top if tag == 'MOGP']
|
|
if len(mogp) != 1 or len(mogp[0]) < 68:
|
|
raise ValueError('One complete MOGP header required')
|
|
trans, interior, exterior = struct.unpack_from('<3H', mogp[0], 0x28)
|
|
batches = [body for tag, body in _chunk_list(mogp[0][68:]) if tag == 'MOBA']
|
|
if not batches and (trans, interior, exterior) == (0, 0, 0):
|
|
# Five native 70334 groups have geometry but no MOBA or batch counts.
|
|
return raw, False
|
|
if len(batches) != 1 or len(batches[0]) % 24:
|
|
raise ValueError('One whole-record MOBA chunk required')
|
|
count = len(batches[0]) // 24
|
|
if trans + interior + exterior == count:
|
|
return raw, False
|
|
if exterior != count or trans + interior > count:
|
|
raise ValueError('Unrecognized MOGP batch-count profile')
|
|
fixed = bytearray(raw)
|
|
offset = next(at for tag, at, _ in _wmo_root_chunks(raw) if tag == 'MOGP')
|
|
struct.pack_into('<H', fixed, offset + 0x2c, count - trans - interior)
|
|
return bytes(fixed), True
|
|
|
|
|
|
def normalize_mogp_batch_gaps(raw):
|
|
"""Move collision-only triangles after contiguous MOBA batches.
|
|
|
|
Native 70334 groups place every MOBA batch from index zero without an
|
|
inner gap. Source groups can put material-255 collision triangles between
|
|
batches, while their MOBR tree still refers to the old triangle numbers.
|
|
Keep each batch's triangle order and every unbatched triangle; remap MOBR
|
|
through the permutation. Unrecognized geometry is refused.
|
|
"""
|
|
top = _chunk_list(raw)
|
|
mogp = [body for tag, body in top if tag == 'MOGP']
|
|
if len(mogp) != 1 or len(mogp[0]) < 68:
|
|
raise ValueError('One complete MOGP header required')
|
|
header, nested = mogp[0][:68], _chunk_list(mogp[0][68:])
|
|
if not any(tag == 'MOBA' for tag, _ in nested):
|
|
# Native groups with geometry and no draw batches exist. There is no
|
|
# batch boundary to normalize in that profile.
|
|
indices = [body for tag, body in nested if tag == 'MOVI']
|
|
triangles = len(indices[0]) // 6 if len(indices) == 1 and len(indices[0]) % 6 == 0 else 0
|
|
return raw, dict(changed=False, triangles=triangles, batches=0,
|
|
moved_triangles=0)
|
|
for tag in ('MOVI', 'MOPY', 'MOBA'):
|
|
if sum(found == tag for found, _ in nested) != 1:
|
|
raise ValueError('One ' + tag + ' chunk required')
|
|
if sum(found == 'MOBR' for found, _ in nested) > 1:
|
|
raise ValueError('At most one MOBR chunk required')
|
|
by = {tag: body for tag, body in nested}
|
|
movi, mopy, moba = (by[tag] for tag in ('MOVI', 'MOPY', 'MOBA'))
|
|
mobr = by.get('MOBR', b'')
|
|
if (len(movi) % 6 or len(mopy) != len(movi) // 3 or
|
|
len(moba) % 24 or len(mobr) % 2):
|
|
raise ValueError('WMO triangle, batch, or MOBR stride differs')
|
|
triangles = len(movi) // 6
|
|
if not moba:
|
|
return raw, dict(changed=False, triangles=triangles, batches=0,
|
|
moved_triangles=0)
|
|
batches, used, prior_end = [], [], 0
|
|
for at in range(0, len(moba), 24):
|
|
start, count = struct.unpack_from('<IH', moba, at + 12)
|
|
if (start % 3 or count % 3 or start < prior_end or
|
|
start + count > 3 * triangles):
|
|
raise ValueError('Overlapping, unaligned, or out-of-bounds MOBA batch')
|
|
batches.append((start, count, moba[at:at + 24]))
|
|
used.extend(range(start // 3, (start + count) // 3))
|
|
prior_end = start + count
|
|
covered = set(used)
|
|
if len(covered) != len(used):
|
|
raise ValueError('MOBA batches overlap in triangles')
|
|
if len(used) == prior_end // 3:
|
|
return raw, dict(changed=False, triangles=triangles, batches=len(batches),
|
|
moved_triangles=0)
|
|
unbatched = [i for i in range(triangles) if i not in covered]
|
|
if any(mopy[2 * i + 1] != 0xff for i in unbatched):
|
|
raise ValueError('Unbatched triangle has a material')
|
|
order = used + unbatched
|
|
inverse = {old: new for new, old in enumerate(order)}
|
|
if len(inverse) != triangles:
|
|
raise ValueError('Triangle permutation incomplete')
|
|
remapped = bytearray(mobr)
|
|
for at in range(0, len(mobr), 2):
|
|
old = struct.unpack_from('<H', mobr, at)[0]
|
|
if old >= triangles or inverse[old] > 0xffff:
|
|
raise ValueError('MOBR triangle reference out of range')
|
|
struct.pack_into('<H', remapped, at, inverse[old])
|
|
new_movi = b''.join(movi[6 * i:6 * i + 6] for i in order)
|
|
new_mopy = b''.join(mopy[2 * i:2 * i + 2] for i in order)
|
|
new_moba = bytearray(moba)
|
|
offset = 0
|
|
for at, (_, count, _) in zip(range(0, len(moba), 24), batches):
|
|
struct.pack_into('<I', new_moba, at + 12, offset)
|
|
offset += count
|
|
replacements = {'MOVI': new_movi, 'MOPY': new_mopy,
|
|
'MOBA': bytes(new_moba), 'MOBR': bytes(remapped)}
|
|
rebuilt = header + _pack_chunks([(tag, replacements.get(tag, body))
|
|
for tag, body in nested])
|
|
result = _pack_chunks([(tag, rebuilt if tag == 'MOGP' else body)
|
|
for tag, body in top])
|
|
if len(result) != len(raw):
|
|
raise ValueError('WMO group extent changed')
|
|
return result, dict(changed=True, triangles=triangles, batches=len(batches),
|
|
moved_triangles=sum(i < prior_end // 3 for i in unbatched),
|
|
mobr_references=len(mobr) // 2)
|
|
|
|
|
|
def normalize_malp_rectangles(malp, wet_mask, *, grid=128):
|
|
"""Carve overlapping far-liquid patches without losing covered wet cells.
|
|
|
|
MALP records are 32 bytes; their first four bytes are x0,y0,x1,y1.
|
|
Smaller patches keep overlap cells, as in the verified Z42M repair. The
|
|
remaining 28 bytes of every retained patch are copied unchanged.
|
|
"""
|
|
if len(malp) % 32 or len(wet_mask) != grid * grid or not 1 <= grid <= 255:
|
|
raise ValueError('Invalid MALP records or wet-mask dimensions')
|
|
records = [malp[i:i + 32] for i in range(0, len(malp), 32)]
|
|
rects = [tuple(record[:4]) for record in records]
|
|
if any(not 0 <= x0 < x1 <= grid or not 0 <= y0 < y1 <= grid
|
|
for x0, y0, x1, y1 in rects):
|
|
raise ValueError('MALP rectangle outside liquid grid')
|
|
|
|
def overlaps(a, b):
|
|
return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3]
|
|
|
|
overlaps_before = sum(overlaps(a, b) for i, a in enumerate(rects)
|
|
for b in rects[i + 1:])
|
|
audit = dict(patches_before=len(records), overlap_pairs_before=overlaps_before,
|
|
patches_after=len(records), wet_cells_preserved=True)
|
|
if not overlaps_before:
|
|
return malp, audit
|
|
|
|
def subtract(a, b):
|
|
if not overlaps(a, b):
|
|
return [a]
|
|
x0, y0, x1, y1 = a
|
|
bx0, by0 = max(x0, b[0]), max(y0, b[1])
|
|
bx1, by1 = min(x1, b[2]), min(y1, b[3])
|
|
return [r for r in ((x0, y0, x1, by0), (x0, by1, x1, y1),
|
|
(x0, by0, bx0, by1), (bx1, by0, x1, by1))
|
|
if r[0] < r[2] and r[1] < r[3]]
|
|
|
|
def wet_bbox(r):
|
|
points = [(x, y) for y in range(r[1], r[3]) for x in range(r[0], r[2])
|
|
if wet_mask[y * grid + x]]
|
|
if not points:
|
|
return None
|
|
return min(x for x, _ in points), min(y for _, y in points), \
|
|
max(x for x, _ in points) + 1, max(y for _, y in points) + 1
|
|
|
|
kept = [] # (rectangle, original record index)
|
|
for index in sorted(range(len(rects)), key=lambda i: ((rects[i][2] - rects[i][0]) *
|
|
(rects[i][3] - rects[i][1]), i)):
|
|
pieces = [rects[index]]
|
|
for blocker, _ in kept:
|
|
pieces = [piece for r in pieces for piece in subtract(r, blocker)]
|
|
for piece in pieces:
|
|
clipped = wet_bbox(piece)
|
|
if clipped:
|
|
kept.append((clipped, index))
|
|
if any(overlaps(a, b) for i, (a, _) in enumerate(kept) for b, _ in kept[i + 1:]):
|
|
raise ValueError('MALP overlap remained after carving')
|
|
for y in range(grid):
|
|
for x in range(grid):
|
|
if wet_mask[y * grid + x] and any(a <= x < c and b <= y < d for a, b, c, d in rects):
|
|
if not any(a <= x < c and b <= y < d for (a, b, c, d), _ in kept):
|
|
raise ValueError('MALP carving lost a wet cell')
|
|
result = b''.join(bytes(rect) + records[i][4:] for rect, i in
|
|
sorted(kept, key=lambda item: (item[1], item[0][1], item[0][0])))
|
|
audit['patches_after'] = len(kept)
|
|
return result, audit
|
|
|
|
|
|
def omit_absent_doodad_placements(root, groups):
|
|
"""Drop MODD placements whose MODI FileDataID is 0 (no owning model).
|
|
|
|
Native roots keep zero MODI words only when no placement uses them (e.g.
|
|
Uldaman 109782: 50 zero words, 0 referencing MODD). A referenced zero makes
|
|
the client open FileDataID 0 (ASSERT(fileID), Timbermaw). Removed
|
|
placements are renumbered out of MODD, each MODS range and every group's
|
|
MODR; all other bytes are kept. `groups` maps group FDI -> bytes; returns
|
|
(root, {fdi: new group bytes for changed groups}, audit).
|
|
"""
|
|
items = _chunk_list(root); parts = dict(items)
|
|
modi = [v for (v,) in struct.iter_unpack('<I', parts.get('MODI', b''))]
|
|
modd = parts.get('MODD', b'')
|
|
count = len(modd) // 40
|
|
keep = [i for i in range(count) if modi[struct.unpack_from('<I', modd, 40 * i)[0] & 0xFFFFFF]]
|
|
if len(keep) == count:
|
|
return root, {}, dict(omitted_placements=0)
|
|
remap = {old: new for new, old in enumerate(keep)}
|
|
new_modd = b''.join(modd[40 * i:40 * i + 40] for i in keep)
|
|
sets = bytearray(parts.get('MODS', b''))
|
|
for at in range(0, len(sets), 32):
|
|
start, n = struct.unpack_from('<II', sets, at + 20)
|
|
kept = [remap[i] for i in range(start, start + n) if i in remap]
|
|
struct.pack_into('<II', sets, at + 20, kept[0] if kept else sum(1 for i in keep if i < start), len(kept))
|
|
root = normalize_wmo_root_counts(_pack_chunks([(t, new_modd if t == 'MODD' else bytes(sets) if t == 'MODS' else d) for t, d in items]))
|
|
changed = {}
|
|
for fdi, raw in groups.items():
|
|
top = _chunk_list(raw); out = []; touched = False
|
|
for tag, data in top:
|
|
if tag == 'MOGP':
|
|
nested = _chunk_list(data[68:])
|
|
rebuilt = []
|
|
for t, d in nested:
|
|
if t == 'MODR':
|
|
refs = [v for (v,) in struct.iter_unpack('<H', d)]
|
|
new = [remap[v] for v in refs if v in remap]
|
|
if new != refs:
|
|
touched = True; d = struct.pack(f'<{len(new)}H', *new)
|
|
rebuilt.append((t, d))
|
|
data = data[:68] + _pack_chunks(rebuilt)
|
|
out.append((tag, data))
|
|
if touched:
|
|
changed[fdi] = _pack_chunks(out)
|
|
return root, changed, dict(omitted_placements=count - len(keep), kept_placements=len(keep), changed_groups=sorted(changed))
|
|
|
|
|
|
def empty_map_companions():
|
|
"""Native 70334 empty forms for the six WDT MPHD companion files.
|
|
|
|
Every working terrain/WMO WDT binds all six (lgt occ fogs mpv tex wdl);
|
|
zero words reach AsyncFile ASSERT(fileID) (Timbermaw 819). REA: native
|
|
empty files with these exact bytes: lgt 1100947 (MVER 20), occ 1101293
|
|
(MVER 18 + empty MAOI/MAOH), fogs 1668793 (MVER 2), mpv 2488184 (MVER 3),
|
|
wdl 791059 (MVER 18, empty MLDD/MLDX/MLMD/MLMX, all-zero MAOF = no low-res
|
|
cells). tex (TXVR 1 + TXBT) has no native empty instance; the zero-entry
|
|
TXBT form is structural only (held for runtime acceptance).
|
|
"""
|
|
mver = lambda v: _chunk('MVER', struct.pack('<I', v))
|
|
return dict(
|
|
lgt=mver(20),
|
|
occ=mver(18) + _chunk('MAOI', b'') + _chunk('MAOH', b''),
|
|
fogs=mver(2),
|
|
mpv=mver(3),
|
|
tex=_chunk('TXVR', struct.pack('<I', 1)) + _chunk('TXBT', b''),
|
|
wdl=mver(18) + b''.join(_chunk(t, b'') for t in ('MLDD', 'MLDX', 'MLMD', 'MLMX')) + _chunk('MAOF', bytes(16384)))
|
|
|
|
|
|
def _root_adt_samples(raw):
|
|
"""MCNK index -> (base z, 145 MCVT floats, low-res hole mask) from a root ADT."""
|
|
out, at = {}, 0
|
|
while at + 8 <= len(raw):
|
|
tag = raw[at:at + 4][::-1]; size = struct.unpack_from('<I', raw, at + 4)[0]
|
|
if tag == b'MCNK':
|
|
body = raw[at + 8:at + 8 + size]
|
|
x, y = struct.unpack_from('<II', body, 4)
|
|
holes = struct.unpack_from('<H', body, 0x3C)[0]
|
|
z = struct.unpack_from('<3f', body, 0x68)[2]
|
|
sub, mcvt = 0x80, None
|
|
while sub + 8 <= len(body):
|
|
st = body[sub:sub + 4][::-1]; ss = struct.unpack_from('<I', body, sub + 4)[0]
|
|
if st == b'MCVT':
|
|
mcvt = struct.unpack_from('<145f', body, sub + 8)
|
|
sub += 8 + ss
|
|
if mcvt is None:
|
|
raise ValueError('MCNK without MCVT')
|
|
out[(x, y)] = (z, mcvt, holes)
|
|
at += 8 + size
|
|
if len(out) != 256:
|
|
raise ValueError('Root ADT needs 256 MCNK')
|
|
return out
|
|
|
|
|
|
def wdl_cell_from_root_adt(raw):
|
|
"""(MARE 545 int16, MAHO 16 uint16) for one tile from its root ADT heights.
|
|
|
|
REA against native WDLs 790111/790639 and their root ADTs: outer 17x17 =
|
|
MCNK corner vertex (row/col 16 from the far edge), truncated (99.3% exact,
|
|
rest within 1). Inner 16x16 = mean of the chunk's 145 MCVT heights,
|
|
truncated (98.9% exact). MAHO = 16 rows, bit c set when MCNK (c, r) has all
|
|
low-res holes (0xFFFF); 41/41 native tiles equal.
|
|
"""
|
|
s = _root_adt_samples(raw)
|
|
h = lambda cx, cy, r, c: s[(cx, cy)][0] + s[(cx, cy)][1][r * 17 + c]
|
|
clamp = lambda v: max(-32768, min(32767, int(v)))
|
|
outer = [clamp(h(min(c, 15), min(r, 15), 8 if r == 16 else 0, 8 if c == 16 else 0)) for r in range(17) for c in range(17)]
|
|
inner = [clamp(s[(c, r)][0] + sum(s[(c, r)][1]) / 145) for r in range(16) for c in range(16)]
|
|
holes = [sum(1 << c for c in range(16) if s[(c, r)][2] == 0xFFFF) for r in range(16)]
|
|
return struct.pack('<545h', *(outer + inner)), struct.pack('<16H', *holes)
|
|
|
|
|
|
def compose_wdl(cells):
|
|
"""Native 70334 WDL: MVER 18, empty MLDD/MLDX/MLMD/MLMX, MAOF, per tile MARE+MAHO."""
|
|
head = _chunk('MVER', struct.pack('<I', 18)) + b''.join(_chunk(t, b'') for t in ('MLDD', 'MLDX', 'MLMD', 'MLMX'))
|
|
maof = [0] * 4096; body = bytearray(); base = len(head) + 8 + 16384
|
|
for (x, y), (mare, maho) in sorted(cells.items(), key=lambda kv: kv[0][1] * 64 + kv[0][0]):
|
|
if len(mare) != 1090 or len(maho) != 32:
|
|
raise ValueError('MARE 1090 / MAHO 32 bytes required')
|
|
maof[y * 64 + x] = base + len(body)
|
|
body += _chunk('MARE', mare) + _chunk('MAHO', maho)
|
|
return head + _chunk('MAOF', struct.pack('<4096I', *maof)) + bytes(body)
|
|
|
|
|
|
def parse_tex(raw):
|
|
"""Native .tex: TXVR 1, TXBT 12-byte (FileDataID, TXMD stream offset, flags), one TXMD per entry."""
|
|
chunks = [(t, raw[at:at + n]) for t, at, n in _wmo_root_chunks(raw)]
|
|
entries = [struct.unpack_from('<III', d, k) for t, d in chunks if t == 'TXBT' for k in range(0, len(d), 12)]
|
|
bodies = [d for t, d in chunks if t == 'TXMD']
|
|
if len(entries) != len(bodies):
|
|
raise ValueError('TXBT/TXMD count differ')
|
|
return {fdi: (flags, body) for (fdi, _, flags), body in zip(entries, bodies)}
|
|
|
|
|
|
def compose_tex(entries):
|
|
"""entries {FileDataID: (flags, TXMD body)} -> native .tex (ascending FDI, offsets over TXMD chunks)."""
|
|
table, stream = bytearray(), bytearray()
|
|
for fdi in sorted(entries):
|
|
flags, body = entries[fdi]
|
|
table += struct.pack('<III', fdi, len(stream), flags)
|
|
stream += _chunk('TXMD', body)
|
|
return _chunk('TXVR', struct.pack('<I', 1)) + _chunk('TXBT', bytes(table)) + bytes(stream)
|
|
|
|
|
|
def normalize_flat_terrain_ocean_material(root, lod=None):
|
|
"""Use native ocean material with matching explicit or inferred vertex layouts.
|
|
|
|
Native70334 144428790 hardcodes type2 to vertex format2; type1250
|
|
Material130 selects format0. Thus each full8x8 layer needs81 explicit
|
|
zero float heights followed by its81 original depth bytes. Explicit object0
|
|
already selects format0; finite, bounded explicit ocean heights preserve that payload
|
|
and compact rectangle while changing only the material type. Explicit object2
|
|
likewise retains its depth-only layout and implicit zero height. The caller
|
|
must establish owning Map.OceanLiquidTypeID1250. Preserve masks, depth,
|
|
bounds, attributes, terrain and LOD shore data; rebase changed chunk sizes.
|
|
"""
|
|
result = bytearray(root)
|
|
root_edits = []
|
|
changed_formats = set()
|
|
explicit_format0_edits = 0
|
|
explicit_format2_edits = 0
|
|
vertex_offsets = []
|
|
held = 0
|
|
chunks = list(_wmo_root_chunks(root))
|
|
liquids = [(at, size) for tag, at, size in chunks if tag == 'MH2O']
|
|
if len(liquids) > 1:
|
|
raise ValueError('Multiple terrain MH2O chunks')
|
|
for at, size in liquids:
|
|
if size < 3072:
|
|
raise ValueError('Truncated MH2O header')
|
|
liquid = bytearray(root[at:at + size])
|
|
for cell in range(256):
|
|
offset, count, _attributes = struct.unpack_from('<3I', liquid, cell * 12)
|
|
if not count:
|
|
continue
|
|
if count > 128 or offset < 3072 or offset + count * 24 > size:
|
|
raise ValueError('Unbounded MH2O instance array')
|
|
for layer in range(count):
|
|
pos = offset + layer * 24
|
|
liquid_type, liquid_object = struct.unpack_from('<HH', liquid, pos)
|
|
if liquid_type != 2 or liquid_object not in (0, 2, 42):
|
|
continue
|
|
if liquid_object != 0 and liquid[pos + 4:pos + 12] not in (bytes(8), bytes(6) + b'\x80\x00'):
|
|
held += 1
|
|
continue
|
|
old_vertex = struct.unpack_from('<I', liquid, pos + 20)[0]
|
|
if liquid_object in (0, 2):
|
|
# Explicit LVF0 has float heights then depth; LVF2 has depth
|
|
# with implicit zero height. Material changes cannot alter
|
|
# these explicit layouts. Preserve rectangles and payloads.
|
|
ox, oy, width, height = struct.unpack_from('<4B', liquid, pos + 12)
|
|
if not (1 <= width <= 8 and 1 <= height <= 8 and ox + width <= 8 and oy + height <= 8):
|
|
raise ValueError('Unbounded explicit ocean rectangle')
|
|
vertices = (width + 1) * (height + 1)
|
|
if old_vertex < 3072 or old_vertex + vertices * (5 if liquid_object == 0 else 1) > size:
|
|
raise ValueError('Unbounded explicit ocean vertices')
|
|
exists = struct.unpack_from('<I', liquid, pos + 16)[0]
|
|
mask_size = (width * height + 7) // 8
|
|
if exists and (exists < 3072 or exists + mask_size > size):
|
|
raise ValueError('Unbounded explicit ocean mask')
|
|
mask = int.from_bytes(liquid[exists:exists + mask_size], 'little') if exists else (1 << (width * height)) - 1
|
|
used = {yy * (width + 1) + xx for y in range(height) for x in range(width)
|
|
if mask >> (y * width + x) & 1
|
|
for yy in (y, y + 1) for xx in (x, x + 1)}
|
|
if liquid_object == 0:
|
|
low, high = struct.unpack_from('<ff', liquid, pos + 4)
|
|
heights = [struct.unpack_from('<f', liquid, old_vertex + v * 4)[0] for v in used]
|
|
if not (math.isfinite(low) and math.isfinite(high) and low <= high and
|
|
all(math.isfinite(h) and low <= h <= high for h in heights)):
|
|
held += 1
|
|
continue
|
|
struct.pack_into('<H', liquid, pos, 1250)
|
|
root_edits.append(at + pos)
|
|
changed_formats.add(liquid_object)
|
|
if liquid_object == 0:
|
|
explicit_format0_edits += 1
|
|
else:
|
|
explicit_format2_edits += 1
|
|
continue
|
|
if old_vertex < 3072 or old_vertex + 81 > size:
|
|
raise ValueError('Unbounded depth-only ocean vertices')
|
|
# Object42 uses the full9x9 grid irrespective of rectangle bytes.
|
|
# Keep old allocations/offsets stable; append the converted array.
|
|
new_vertex = len(liquid)
|
|
liquid.extend(bytes(81 * 4))
|
|
liquid.extend(root[at + old_vertex:at + old_vertex + 81])
|
|
struct.pack_into('<H', liquid, pos, 1250)
|
|
struct.pack_into('<I', liquid, pos + 20, new_vertex)
|
|
root_edits.append(at + pos)
|
|
changed_formats.add(42)
|
|
vertex_offsets.append((old_vertex, new_vertex))
|
|
if root_edits:
|
|
if any(tag == 'MCIN' for tag, _, _ in chunks):
|
|
raise ValueError('Ocean conversion requires the reviewed split ROOT without MCIN')
|
|
growth = len(liquid) - size
|
|
result[at:at + size] = liquid
|
|
struct.pack_into('<I', result, at - 4, len(liquid))
|
|
# MHDR pointers are relative to its own payload. MCNK inner offsets
|
|
# are chunk-local and remain unchanged when top-level chunks move.
|
|
headers = [(ha, hs) for tag, ha, hs in chunks if tag == 'MHDR']
|
|
if headers:
|
|
if len(headers) != 1 or headers[0][1] != 64:
|
|
raise ValueError('Unreviewed terrain MHDR')
|
|
ha, _ = headers[0]
|
|
if ha > at:
|
|
raise ValueError('MHDR follows ocean payload')
|
|
starts = {ca - 8 for _, ca, _ in chunks}
|
|
for word in range(1, 12):
|
|
value = struct.unpack_from('<I', root, ha + word * 4)[0]
|
|
if not value:
|
|
continue
|
|
target = ha + value
|
|
if target not in starts:
|
|
raise ValueError('MHDR pointer does not name a top-level chunk')
|
|
if target >= at + size:
|
|
struct.pack_into('<I', result, ha + word * 4, value + growth)
|
|
output_lod = None if lod is None else bytearray(lod)
|
|
lod_edits = []
|
|
if root_edits and lod is not None:
|
|
for tag, at, size in _wmo_root_chunks(lod):
|
|
if tag != 'MALP':
|
|
continue
|
|
if size % 32:
|
|
raise ValueError('Truncated MALP ocean patch')
|
|
for pos in range(at, at + size, 32):
|
|
liquid_type, liquid_object = struct.unpack_from('<HH', lod, pos + 4)
|
|
zero_bounds = (bytes(8), bytes(6) + b'\x80\x00', b'\x00\x00\x80\x00' * 2)
|
|
low, high = struct.unpack_from('<ff', lod, pos + 16)
|
|
valid_level = (math.isfinite(low) and math.isfinite(high) and low <= high) if liquid_object == 0 else lod[pos + 16:pos + 24] in zero_bounds
|
|
if liquid_type == 2 and liquid_object in changed_formats and valid_level:
|
|
struct.pack_into('<H', output_lod, pos + 4, 1250)
|
|
lod_edits.append(pos + 4)
|
|
return bytes(result), None if output_lod is None else bytes(output_lod), dict(
|
|
policy='native70334-ocean-material1250-explicit-and-depth-v3', root_instances=len(root_edits),
|
|
lod_patches=len(lod_edits), held_nonzero_ocean_instances=held,
|
|
root_type_offsets=root_edits, lod_type_offsets=lod_edits,
|
|
vertex_offset_replacements=vertex_offsets, explicit_zero_height_samples=81 * len(vertex_offsets),
|
|
explicit_format0_instances=explicit_format0_edits, explicit_format2_instances=explicit_format2_edits,
|
|
expanded_depth_only_instances=len(vertex_offsets))
|