161 lines
6.9 KiB
Python
161 lines
6.9 KiB
Python
"""Build an isolated Source-format 32_48 ADT and one-file patch-9.MPQ."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import struct
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
import editor_export_127 as export
|
|
|
|
SOURCE_DATA = Path.home() / 'Games/octo/drive_c/Octowow/Data'
|
|
SCRATCH = Path('/mnt/Games/@project/editor-server-127')
|
|
MEMBER = 'World\\Maps\\Azeroth\\Azeroth_32_48.adt'
|
|
|
|
|
|
def crypt_table():
|
|
table = [0] * 0x500
|
|
seed = 0x100001
|
|
for i in range(0x100):
|
|
for j in range(5):
|
|
seed = (seed * 125 + 3) % 0x2AAAAB
|
|
top = (seed & 0xffff) << 16
|
|
seed = (seed * 125 + 3) % 0x2AAAAB
|
|
table[i + j * 0x100] = top | (seed & 0xffff)
|
|
return table
|
|
|
|
|
|
CRYPT = crypt_table()
|
|
|
|
|
|
def mpq_hash(value, offset):
|
|
a, b = 0x7fed7fed, 0xeeeeeeee
|
|
for ch in value.upper().encode('ascii'):
|
|
a = (CRYPT[offset + ch] ^ (a + b)) & 0xffffffff
|
|
b = (ch + a + b + (b << 5) + 3) & 0xffffffff
|
|
return a
|
|
|
|
|
|
def mpq_encrypt(payload, key):
|
|
if len(payload) % 4:
|
|
raise ValueError('MPQ table alignment')
|
|
seed = 0xeeeeeeee
|
|
words = []
|
|
for (plain,) in struct.iter_unpack('<I', payload):
|
|
seed = (seed + CRYPT[0x400 + (key & 0xff)]) & 0xffffffff
|
|
words.append((plain ^ (key + seed)) & 0xffffffff)
|
|
key = (((~key << 21) + 0x11111111) | (key >> 11)) & 0xffffffff
|
|
seed = (plain + seed + (seed << 5) + 3) & 0xffffffff
|
|
return struct.pack('<' + 'I' * len(words), *words)
|
|
|
|
|
|
def one_file_mpq(member, payload):
|
|
# MPQ v0, uncompressed single-unit file. libmpq's exact hash/crypt
|
|
# algorithms and flags come from tortoise's bundled libmpq/common.c.
|
|
slots = 8
|
|
file_at = 32
|
|
hash_at = (file_at + len(payload) + 3) & ~3
|
|
block_at = hash_at + slots * 16
|
|
size = block_at + 16
|
|
header = struct.pack('<4s2I2H4I', b'MPQ\x1a', 32, size, 0, 3,
|
|
hash_at, block_at, slots, 1)
|
|
entries = [b'\xff' * 16 for _ in range(slots)]
|
|
slot = mpq_hash(member, 0) & (slots - 1)
|
|
entries[slot] = struct.pack('<2I2HI', mpq_hash(member, 0x100),
|
|
mpq_hash(member, 0x200), 0, 0, 0)
|
|
hashes = mpq_encrypt(b''.join(entries), mpq_hash('(hash table)', 0x300))
|
|
block = struct.pack('<4I', file_at, len(payload), len(payload), 0x81000000)
|
|
blocks = mpq_encrypt(block, mpq_hash('(block table)', 0x300))
|
|
return header + payload + b'\0' * (hash_at - file_at - len(payload)) + hashes + blocks
|
|
|
|
|
|
def source_overlay(source, edited, native_root, native_obj0):
|
|
# Reuse 21bb's semantic guard, including water, MODF, and model/rotation
|
|
# checks. Only the approved terrain/position values are extracted below.
|
|
_, _, review = export.extract(source, edited, native_root, native_obj0)
|
|
changed = {y * 16 + x for x, y in review['changed_coordinates']}
|
|
moved = set(review['snapped_unique_ids'])
|
|
_, saved_cells = export.chunk_map(edited)
|
|
source_rows = export.top(source)
|
|
saved_doodads = export.placement_rows(dict(export.top(edited))['MDDF'], 36)
|
|
rows = []
|
|
cell = 0
|
|
for tag, body in source_rows:
|
|
if tag == 'MCNK':
|
|
if cell in changed:
|
|
dst = saved_cells[cell]
|
|
dst_sub = export.subchunks(dst)
|
|
mutable = bytearray(body)
|
|
for subtag, width in (('MCVT', 580), ('MCNR', 435)):
|
|
marker = subtag[::-1].encode()
|
|
at = mutable.find(marker, 128)
|
|
if at < 0 or struct.unpack_from('<I', mutable, at + 4)[0] != width:
|
|
raise ValueError(f'Source {subtag} layout at MCNK {cell}')
|
|
mutable[at + 8:at + 8 + width] = dst_sub[subtag]
|
|
struct.pack_into('<f', mutable, 112, struct.unpack_from('<f', dst, 112)[0])
|
|
body = bytes(mutable)
|
|
cell += 1
|
|
elif tag == 'MDDF' and moved:
|
|
mutable = bytearray(body)
|
|
for at in range(0, len(mutable), 36):
|
|
uid = struct.unpack_from('<I', mutable, at + 4)[0]
|
|
if uid in moved:
|
|
mutable[at + 8:at + 20] = saved_doodads[uid][8:20]
|
|
body = bytes(mutable)
|
|
rows.append(tag[::-1].encode() + struct.pack('<I', len(body)) + body)
|
|
output = b''.join(rows)
|
|
if len(output) != len(source):
|
|
raise ValueError('Source overlay changed ADT byte length/MCIN offsets')
|
|
return output, review
|
|
|
|
|
|
def stage_data(source_data, output):
|
|
data = output / 'Data'
|
|
data.mkdir(parents=True, exist_ok=True)
|
|
if any(data.iterdir()):
|
|
raise ValueError('isolated Source Data directory must be empty')
|
|
selected = []
|
|
for archive in source_data.iterdir():
|
|
if archive.is_file() and archive.suffix.lower() == '.mpq':
|
|
destination = data / archive.name
|
|
# Source lives on a different filesystem in this environment;
|
|
# reflink when possible and make a physical copy otherwise.
|
|
subprocess.run(['cp', '--reflink=auto', str(archive), str(destination)], check=True)
|
|
selected.append(archive.name)
|
|
if not selected:
|
|
raise ValueError('no Source MPQs')
|
|
if any(name.lower() == 'patch-9.mpq' for name in selected):
|
|
raise ValueError('Source already contains patch-9.MPQ')
|
|
return data, sorted(selected)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('edited', type=Path)
|
|
parser.add_argument('--source', type=Path, default=export.SOURCE)
|
|
parser.add_argument('--native-root', type=Path, default=Path('/mnt/Games/@project/editor-export-127/base/root.adt'))
|
|
parser.add_argument('--native-obj0', type=Path, default=Path('/mnt/Games/@project/editor-export-127/base/obj0.adt'))
|
|
parser.add_argument('--source-data', type=Path, default=SOURCE_DATA)
|
|
parser.add_argument('--output', type=Path, default=SCRATCH / 'edited')
|
|
args = parser.parse_args()
|
|
source = args.source.read_bytes()
|
|
overlay, review = source_overlay(source, args.edited.read_bytes(),
|
|
args.native_root.read_bytes(), args.native_obj0.read_bytes())
|
|
data, archives = stage_data(args.source_data, args.output)
|
|
member_file = args.output / 'source-overlay' / 'Azeroth_32_48.adt'
|
|
member_file.parent.mkdir(parents=True, exist_ok=True)
|
|
member_file.write_bytes(overlay)
|
|
archive = data / 'patch-9.MPQ'
|
|
archive.write_bytes(one_file_mpq(MEMBER, overlay))
|
|
report = dict(review=review, source_sha256=hashlib.sha256(source).hexdigest(),
|
|
overlay_sha256=hashlib.sha256(overlay).hexdigest(),
|
|
source_archives=archives, mpq=str(archive),
|
|
note='patch-O.mpq is copied but ignored by tortoise extractors; control must disclose any resulting drift')
|
|
(args.output / 'overlay-report.json').write_text(json.dumps(report, indent=2) + '\n')
|
|
print(json.dumps(dict(archive=str(archive), changed_mcnks=review['changed_mcnks'],
|
|
snapped_doodads=review['snapped_doodads'])))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|