Files
firestorm/MW4COMPARE/tools/mw4db.py
T
83478b7666 Add MW4COMPARE: .mw4 decompiler toolchain and V4H comparison harness
Tooling built to recover editable source for six 'Mech chassis that exist
in the parallel FS_Build_V4H build but not in this repo. Reverse-engineers
every compiled record type in the .mw4 package format back to the .data /
.instance / .subsystems / .damage / .contents / .torso / .engine /
.armature sources the content pipeline consumes.

Nothing here is wired into the game build. It is a standalone analysis
harness run from Linux.

Package format
--------------
"#VBD" container. Directory records are [len][name][FILETIME][origSize]
[storedSize][offset], payload base at dword 0x0C. A record is stored raw
when storedSize == origSize, otherwise LZW (9->12-bit LSB-first codes,
256=clear, 257=EOF, dict from 258), per Database.cpp:451.

GameModel records are flat /Zp4 structs following the C++ inheritance
chain Entity(0) -> Mover(28) -> MWObject(80) -> Vehicle(664) -> Mech(756),
1636 bytes total. CreateMessage records follow Replicator -> Entity ->
Mover -> MWMover -> MWObject -> Vehicle -> Mech from start=16 (the
undeclared Connection__Message header), ending at 341 and padded to 344.

tools/decompile/
----------------
  datamap.py        header-driven layout engine; CHAIN + ANCHORS
                    {Vehicle:664, Mech:756} assert the struct offsets
  mw4msg.py         CreateMessage reader/walker
  data.py           .data      constants.py  define/table symbol resolution
  damage.py         .damage    contents.py   .contents
  smallmodel.py     .torso + .engine         instance.py  .instance
  armature.py / armature_parts.py  .armature + armaturedata/armaturevideo
  assembly.py       joint hierarchy renderer
  make_generic_doll.py  builds generic MFD/Radar damage dolls
  verify_*.py       per-type round-trip verifiers

Verified round-trip across all 64 shared chassis:
  .armature      2938/2976 pages     .subsystems  7579/7585 keys
  .data map      6071/6071 values    .data trip   8291/8306 keys
  .damage        6605/6605 keys      .contents    7480/7480 keys
  .torso+.engine 1280/1280 keys      .instance     896/896 keys, 64/64 pages
  armature_parts 1202/1202 .data, 1149/1202 .video

Layout-discovery lessons (documented in DECOMPILING.md)
-------------------------------------------------------
- Never let a field map be discovered by the values that verify it. A
  value-matching pass reported 4288/4288 while mis-assigning 34 keys. The
  map was rebuilt from header declaration order, anchored on uniquely
  resolved fields.
- Read the factory, not the data. 12 .data fields and 5 Torso fields are
  declared plain Stuff::Scalar but multiplied by Radians_Per_Degree in
  Mech_Tool.cpp:889 / Torso_Tool.cpp.
- Strip typedefs before walking a header. A stray `typedef int AttributeID;`
  masked a missing ClassID - two 4-byte errors cancelling out, caught only
  by the ANCHORS assertion.
- A verifier that silently narrows its own input reports success. Braced
  blocks must be hidden before splitting pages, replacing both CR and LF,
  because a `Shadow={...}` block contains a line reading `[shadow]` and
  splitlines() also splits on bare CR.
- NSWIZZLE is undefined, so the #else branch is live and orders members
  differently. bool is 1 byte; char x[MaxStringLength] is 256.
- V4H carries stale Mech IDs (their Atlas is 5, ours 6), so 64 of 65 shared
  chassis are off by one; --retarget-ids emits $(M_<Chassis>)/$(IDS_<Chassis>).

reports/ holds generated diffs. The two ~5 MB manifest-*.tsv intermediates
are gitignored; regenerate everything with run-comparison.sh.

Co-authored-by: Claude Opus 5 (Anthropic) <noreply@anthropic.com>
Co-authored-by: GitHub Copilot <copilot@github.com>
2026-08-08 16:47:57 -05:00

150 lines
5.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""
mw4db.py - reader for GameOS "#VBD" resource packages (*.mw4).
Format (from mw4\\Libraries\\stuff\\Database.cpp):
header (20 bytes, little-endian)
char[4] tag "#VBD"
u32 format
u32 contentVersion (63 for this codebase, VER_CONTENTVERSION)
u32 indexSize byte offset of the payload area
u16 recordCount
u16 nextId
then `recordCount` directory records, packed, no alignment:
s64 FILETIME when this entry was last (re)packed
u32 dataLength decompressed size
u32 recLength stored size
u32 dataOffset offset from `indexSize`
u16 recordId
u8 nameLength
char[] name (latin-1, backslash-separated, may carry
{qualifier} / [page] suffixes)
payload at indexSize + dataOffset, `recLength` bytes.
Storage rule (Database.cpp:451): recLength == dataLength -> raw,
otherwise LZW-compressed with gos_LZCompress.
The decompressor is a faithful port of gos_LZDecompress from
CoreTech\\Libraries\\GameOS\\FileIO.cpp - variable-width LZW, LSB-first,
9 -> 12 bits, CLEAR = 256, EOF = 257, dictionary starts at 258.
"""
import struct, hashlib, os
def lz_decompress(src: bytes) -> bytes:
src = bytes(src) + b"\x00\x00\x00\x00" # u32-read padding margin
bitpos = 0
def getcode(width, mask):
nonlocal bitpos
i = bitpos >> 3
v = src[i] | (src[i + 1] << 8) | (src[i + 2] << 16) | (src[i + 3] << 24)
v = (v >> (bitpos & 7)) & mask
bitpos += width
return v
CLEAR, EOF, FREE = 256, 257, 258
chain = [0] * 8192
suffix = [0] * 8192
width, mask, maxindex, free = 9, 511, 512, FREE
oldchain = oldsuffix = 0
out = bytearray()
while True:
code = getcode(width, mask)
if code == EOF:
break
if code == CLEAR:
width, mask, maxindex, free = 9, 511, 512, FREE
code = getcode(width, mask) # ClearHash emits one literal
out.append(code & 0xFF)
oldchain, oldsuffix = code, code & 0xFF
continue
stack = []
if code >= free: # KwKwK special case
stack.append(oldsuffix)
suffix[code] = oldsuffix
chain[code] = oldchain
walk = oldchain
else:
walk = code
while walk >= 256:
stack.append(suffix[walk])
walk = chain[walk]
stack.append(walk)
oldsuffix = walk & 0xFF
out += bytes(reversed(stack))
suffix[free] = oldsuffix
chain[free] = oldchain
free += 1
oldchain = code
if free == maxindex and width != 12:
width += 1
maxindex <<= 1
mask = (mask << 1) | 1
return bytes(out)
def read_index(path):
"""Parse directory only. Fast - no decompression.
Returns (contentVersion, [(recordId, name, dataLen, recLen, storedBytes), ...])
or None when the file is not a #VBD package.
"""
with open(path, "rb") as fh:
data = fh.read()
if data[:4] != b"#VBD":
return None
_tag, _fmt, content, indexsize, nrec, _nextid = struct.unpack_from("<4sIIIHH", data, 0)
out, off = [], 20
for _ in range(nrec):
off += 8 # FILETIME
dlen, rlen, doff = struct.unpack_from("<III", data, off); off += 12
rid, nlen = struct.unpack_from("<HB", data, off); off += 3
name = data[off:off + nlen].decode("latin-1"); off += nlen
raw = data[indexsize + doff: indexsize + doff + rlen] if dlen else b""
out.append((rid, name, dlen, rlen, raw))
return content, out
def read_records(path):
"""Parse and decode every record.
Returns (contentVersion, [(recordId, name, dataLen, recLen, decodedBytes), ...])
"""
r = read_index(path)
if r is None:
return None
content, recs = r
out = []
for rid, name, dlen, rlen, raw in recs:
blob = b"" if not dlen else (raw if rlen == dlen else lz_decompress(raw))
out.append((rid, name, dlen, rlen, blob))
return content, out
def norm(name: str) -> str:
"""Canonical comparison key for an entry name.
Package entry names are case-inconsistent between builds (V4H's packer
lowercased everything) and use backslashes. Always compare through this.
"""
return name.lower().replace("\\", "/")
def md5(b: bytes) -> str:
return hashlib.md5(b).hexdigest()
def walk_packages(root):
"""Yield (absolutePath, relativePathWithForwardSlashes) for every *.mw4 under root."""
for dirpath, _dirs, files in os.walk(root):
for f in sorted(files):
if f.lower().endswith(".mw4"):
p = os.path.join(dirpath, f)
yield p, os.path.relpath(p, root).replace("\\", "/")