411 lines
20 KiB
Python
411 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
"""Stage one read-only Octo terrain tile as a Noggit Wrath folder client."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import struct
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
sys.path.insert(0, str(HERE / 'maps14-20261122'))
|
|
import octo_mpq
|
|
import map_asset_preflight
|
|
import liquid_repro
|
|
import source_map_wdt
|
|
sys.path.insert(0, str(HERE)) # liquid_repro's legacy path must not select another checkout.
|
|
from m2_equipment_convert import convert_equipment
|
|
|
|
DBCS = ('AreaTable AreaTrigger Map LoadingScreens Light LightParams LightSkybox '
|
|
'LightIntBand LightFloatBand GroundEffectDoodad GroundEffectTexture '
|
|
'TerrainType LiquidType SoundProviderPreferences SoundAmbience ZoneMusic '
|
|
'ZoneIntroMusicTable SoundEntries WMOAreaTable GameObjectDisplayInfo').split()
|
|
SOURCE_BUILD = (1, 12, 1, 5875)
|
|
EDITOR_BUILD = (3, 3, 5, 12340)
|
|
NONE_FIELDS = {'CorpseMapID', 'TimeOfDayOverride'}
|
|
HELPERS = (
|
|
['textures/shanecube.blp'] +
|
|
[f'tileset/generic/{colour}.blp' for colour in ('black', 'blue', 'green', 'red')] +
|
|
['environments/stars/stars.mdx',
|
|
'interface/icons/inv_misc_enggizmos_swissarmy.blp',
|
|
'item/objectcomponents/weapon/armorreflect4.blp',
|
|
'world/generic/passivedoodads/particleemitters/ashenvalewisps.m2'] +
|
|
[f'world/scale/{name}.m2' for name in (
|
|
'50x50', '100x100', '250x250', '500x500', '1000x1000', 'humanmalescale',
|
|
'50yardradiusdisc', '50yardradiussphere', '200yardradiusdisc',
|
|
'200yardradiussphere', '777yardradiusdisc', '777yardradiussphere')] +
|
|
['world/wmo/azeroth/buildings/human_farm/farm.wmo',
|
|
'world/wmo/dungeon/md_fishinghole/md_fishingholeice_001.wmo'])
|
|
|
|
|
|
def chunks(raw):
|
|
at = 0
|
|
while at + 8 <= len(raw):
|
|
size = struct.unpack_from('<I', raw, at + 4)[0]
|
|
end = at + 8 + size
|
|
if end > len(raw):
|
|
raise ValueError('truncated chunk')
|
|
yield raw[at:at + 4][::-1].decode('ascii'), at + 8, size
|
|
at = end
|
|
if at != len(raw):
|
|
raise ValueError('trailing chunk bytes')
|
|
|
|
|
|
def layout(dbd, build):
|
|
for block in re.split(r'\n\s*\n', dbd.read_text()):
|
|
matches = []
|
|
for line in block.splitlines():
|
|
if not line.startswith('BUILD '):
|
|
continue
|
|
for match in re.findall(r'\d+\.\d+\.\d+\.\d+(?:-\d+\.\d+\.\d+\.\d+)?', line):
|
|
ends = [tuple(map(int, part.split('.'))) for part in match.split('-')]
|
|
matches.append(ends[0] <= build <= ends[-1])
|
|
if not any(matches):
|
|
continue
|
|
fields = []
|
|
for line in block.splitlines():
|
|
if not line or line.startswith(('BUILD ', 'LAYOUT ', 'COMMENT ')):
|
|
continue
|
|
token = line.split()[0]
|
|
token = re.sub(r'^\$[^$]*\$', '', token)
|
|
match = re.fullmatch(r'([\w]+)(?:<[^>]+>)?(?:\[(\d+)\])?', token)
|
|
if not match:
|
|
raise ValueError(f'unreviewed DBD token {dbd.name}: {token}')
|
|
fields.append((match[1], int(match[2] or 1)))
|
|
if fields:
|
|
return fields
|
|
raise ValueError(f'no DBD layout {dbd.name} {build}')
|
|
|
|
|
|
def slices(fields, locale_words):
|
|
result = {}
|
|
at = 0
|
|
for name, count in fields:
|
|
width = count * (locale_words if name.endswith('_lang') else 1)
|
|
if name in result:
|
|
raise ValueError('duplicate DBD field ' + name)
|
|
result[name] = (at, width, count)
|
|
at += width
|
|
return result, at
|
|
|
|
|
|
def convert_dbc(name, raw, definition):
|
|
if len(raw) < 21 or raw[:4] != b'WDBC':
|
|
raise ValueError(name + ' is not WDBC')
|
|
rows, source_columns, source_width, string_bytes = struct.unpack_from('<4I', raw, 4)
|
|
if source_width != 4 * source_columns or len(raw) != 20 + rows * source_width + string_bytes:
|
|
raise ValueError(name + ' WDBC bounds')
|
|
before, count = slices(layout(definition, SOURCE_BUILD), 9)
|
|
after, width = slices(layout(definition, EDITOR_BUILD), 17)
|
|
if count != source_columns:
|
|
raise ValueError(f'{name} source columns {source_columns} != DBD {count}')
|
|
strings = raw[20 + rows * source_width:]
|
|
output = bytearray(struct.pack('<4s4I', b'WDBC', rows, width, width * 4, len(strings)))
|
|
defaulted = []
|
|
for field in after:
|
|
if field not in before:
|
|
defaulted.append(field)
|
|
for index in range(rows):
|
|
source = struct.unpack_from('<' + 'I' * count, raw, 20 + index * source_width)
|
|
dest = [0] * width
|
|
for field, (start, span, target_count) in after.items():
|
|
if field not in before:
|
|
if field in NONE_FIELDS:
|
|
dest[start:start + span] = [0xffffffff] * span
|
|
continue
|
|
old_start, old_span, old_count = before[field]
|
|
if field.endswith('_lang'):
|
|
if target_count != 1 or old_count != 1:
|
|
raise ValueError(name + ' localized array requires review')
|
|
dest[start] = source[old_start]
|
|
dest[start + 16] = source[old_start + 8]
|
|
else:
|
|
for offset in range(min(span, old_span)):
|
|
dest[start + offset] = source[old_start + offset]
|
|
output.extend(struct.pack('<' + 'I' * width, *dest))
|
|
output.extend(strings)
|
|
return bytes(output), dict(rows=rows, source_columns=count, target_columns=width,
|
|
defaulted_fields=defaulted)
|
|
|
|
|
|
def map_difficulty(map_dbc, definition):
|
|
columns, width = slices(layout(definition, EDITOR_BUILD), 17)
|
|
rows, map_columns, record_size, _ = struct.unpack_from('<4I', map_dbc, 4)
|
|
if {'ID', 'MapID', 'Difficulty', 'Message_lang', 'RaidDuration',
|
|
'MaxPlayers', 'Difficultystring'} != set(columns):
|
|
raise ValueError('unreviewed MapDifficulty target layout')
|
|
output = bytearray(struct.pack('<4s4I', b'WDBC', rows, width, 4 * width, 1))
|
|
for index in range(rows):
|
|
map_id = struct.unpack_from('<I', map_dbc, 20 + index * record_size)[0]
|
|
words = [0] * width
|
|
words[columns['ID'][0]] = map_id
|
|
words[columns['MapID'][0]] = map_id
|
|
output.extend(struct.pack('<' + 'I' * width, *words))
|
|
output.append(0)
|
|
return bytes(output)
|
|
|
|
|
|
def put(root, logical, raw):
|
|
target = root / logical.replace('\\', '/').lower()
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
target.write_bytes(raw)
|
|
return target
|
|
|
|
|
|
def names(raw, tag):
|
|
for kind, start, size in chunks(raw):
|
|
if kind == tag:
|
|
return [part.decode('latin1') for part in raw[start:start + size].split(b'\0') if part]
|
|
return []
|
|
|
|
|
|
def m2_textures(raw):
|
|
if raw[:4] != b'MD20' or len(raw) < 88:
|
|
return []
|
|
count, offset = struct.unpack_from('<II', raw, 80)
|
|
if count > 1024 or offset + count * 16 > len(raw):
|
|
return []
|
|
result = []
|
|
for index in range(count):
|
|
kind, _, length, name_at = struct.unpack_from('<4I', raw, offset + 16 * index)
|
|
if kind == 0 and 0 < length <= 512 and name_at + length <= len(raw):
|
|
result.append(raw[name_at:name_at + length].rstrip(b'\0').decode('latin1'))
|
|
return result
|
|
|
|
|
|
def parts(raw):
|
|
return {tag: raw[start:start + size] for tag, start, size in chunks(raw) if tag != 'MCNK'}
|
|
|
|
|
|
def indexed_names(blob, offsets):
|
|
return [blob[at:blob.index(b'\0', at)].decode('latin1').replace('\\', '/').lower()
|
|
for (at,) in struct.iter_unpack('<I', offsets)]
|
|
|
|
|
|
def roundtrip_other_roles(editor_tile, native_tex0, native_obj0):
|
|
source = parts(editor_tile)
|
|
texture = parts(native_tex0)
|
|
object_parts = parts(native_obj0)
|
|
texture_names = [name.replace('\\', '/').lower() for name in names(editor_tile, 'MTEX')]
|
|
texture_ids = [row[0] for row in struct.iter_unpack('<I', texture['MDID'])]
|
|
if len(texture_names) != len(texture_ids):
|
|
raise ValueError('Source/native texture slot count differs')
|
|
bindings = dict(zip(texture_names, texture_ids))
|
|
for tag, name_tag, index_tag, stride in (
|
|
('MDDF', 'MMDX', 'MMID', 36), ('MODF', 'MWMO', 'MWID', 64)):
|
|
paths = indexed_names(source[name_tag], source[index_tag])
|
|
native_ids = {struct.unpack_from('<I', object_parts[tag], at + 4)[0]:
|
|
struct.unpack_from('<I', object_parts[tag], at)[0]
|
|
for at in range(0, len(object_parts[tag]), stride)}
|
|
for at in range(0, len(source[tag]), stride):
|
|
index, uid = struct.unpack_from('<II', source[tag], at)
|
|
if uid not in native_ids:
|
|
raise ValueError('Source placement absent from live OBJ0')
|
|
path = paths[index]
|
|
if path in bindings and bindings[path] != native_ids[uid]:
|
|
raise ValueError('inconsistent placement asset binding')
|
|
bindings[path] = native_ids[uid]
|
|
output, _ = map_asset_preflight.adt_split_candidate(
|
|
editor_tile, (32, 48), file_data_ids=bindings, roles=('tex0', 'obj0'),
|
|
normalize_edge_invariant_alpha8=True)
|
|
obj0, _ = source_map_wdt.native_modf_scale(output['obj0'])
|
|
projected = parts(obj0)
|
|
if projected['MDDF'] != object_parts['MDDF']:
|
|
raise ValueError('doodad placements differ from live OBJ0')
|
|
prior = {struct.unpack_from('<I', projected['MODF'], at + 4)[0]:
|
|
projected['MODF'][at:at + 64] for at in range(0, len(projected['MODF']), 64)}
|
|
current = {struct.unpack_from('<I', object_parts['MODF'], at + 4)[0]:
|
|
object_parts['MODF'][at:at + 64] for at in range(0, len(object_parts['MODF']), 64)}
|
|
if any(current.get(uid) != value for uid, value in prior.items()):
|
|
raise ValueError('Source WMO placement differs from live OBJ0')
|
|
return dict(tex0_byte_equal=output['tex0'] == native_tex0,
|
|
doodad_byte_equal=True, source_wmo_byte_equal=True,
|
|
source_wmos=len(prior), live_extra_wmos=len(set(current) - set(prior)))
|
|
|
|
|
|
def roundtrip_root(editor_tile):
|
|
root = map_asset_preflight.adt_split_candidate(
|
|
editor_tile, (32, 48), file_data_ids={}, roles=('root',))[0]['root']
|
|
root, _ = map_asset_preflight.adt_root_still_river_candidate(
|
|
root, source_legacy_authoritative=True)
|
|
root, _ = liquid_repro.retype_off_sea(root)
|
|
return liquid_repro.strip_mclq(root)
|
|
|
|
|
|
def stage(destination, definitions, native_root=None, native_tex0=None, native_obj0=None):
|
|
if destination.is_relative_to(Path.home() / 'Games/octo'):
|
|
raise ValueError('source Octo client is read-only')
|
|
common = destination / 'Data/common.MPQ'
|
|
patch = destination / 'Data/patch.MPQ'
|
|
locale = destination / 'Data/enUS/locale-enUS.MPQ'
|
|
locale.mkdir(parents=True, exist_ok=True)
|
|
(destination / 'Data/enUS/realmlist.wtf').write_text('set realmlist localhost\n')
|
|
report = {'dbc': {}, 'assets': {'written': 0, 'missing': []}}
|
|
for name in DBCS:
|
|
source = octo_mpq.read('DBFilesClient\\' + name + '.dbc')
|
|
if source is None:
|
|
raise ValueError('missing Octo DBC ' + name)
|
|
converted, detail = convert_dbc(name, source, definitions / (name + '.dbd'))
|
|
put(patch, 'DBFilesClient/' + name + '.dbc', converted)
|
|
report['dbc'][name] = detail
|
|
map_dbc = (patch / 'dbfilesclient/map.dbc').read_bytes()
|
|
difficulty = map_difficulty(map_dbc, definitions / 'MapDifficulty.dbd')
|
|
put(patch, 'DBFilesClient/MapDifficulty.dbc', difficulty)
|
|
report['dbc']['MapDifficulty'] = dict(rows=struct.unpack_from('<I', difficulty, 4)[0],
|
|
source_columns=None,
|
|
target_columns=struct.unpack_from('<I', difficulty, 8)[0],
|
|
defaulted_fields=['Difficulty', 'Message_lang', 'RaidDuration',
|
|
'MaxPlayers', 'Difficultystring'],
|
|
synthesized_from='Map.ID')
|
|
tile_name = 'World\\Maps\\Azeroth\\Azeroth_32_48.adt'
|
|
tile = octo_mpq.read(tile_name)
|
|
wdt = octo_mpq.read('World\\Maps\\Azeroth\\Azeroth.wdt')
|
|
if tile is None or wdt is None:
|
|
raise ValueError('missing Source Elwynn tile/WDT')
|
|
if struct.unpack_from('<I', tile, 8)[0] != 18 or 'MH2O' not in {t for t, _, _ in chunks(tile)}:
|
|
raise ValueError('Elwynn is not already v18/MH2O')
|
|
put(patch, tile_name, tile)
|
|
main = next((start for tag, start, size in chunks(wdt) if tag == 'MAIN' and size == 64 * 64 * 8), None)
|
|
if main is None:
|
|
raise ValueError('unexpected Source WDT MAIN')
|
|
one = bytearray(wdt)
|
|
selected = 48 * 64 + 32
|
|
if not struct.unpack_from('<I', one, main + selected * 8)[0] & 1:
|
|
raise ValueError('Elwynn 32_48 inactive')
|
|
for index in range(4096):
|
|
if index != selected:
|
|
one[main + index * 8:main + index * 8 + 8] = bytes(8)
|
|
put(patch, 'World/Maps/Azeroth/Azeroth.wdt', one)
|
|
wdl = octo_mpq.read('World\\Maps\\Azeroth\\Azeroth.wdl')
|
|
if wdl is None or not {'MVER', 'MAOF', 'MARE'} <= {tag for tag, _, _ in chunks(wdl)}:
|
|
raise ValueError('missing Source Azeroth WDL horizon')
|
|
put(patch, 'World/Maps/Azeroth/Azeroth.wdl', wdl)
|
|
report['wdl'] = dict(bytes=len(wdl), sha256=hashlib.sha256(wdl).hexdigest())
|
|
required = set(names(tile, 'MTEX') + names(tile, 'MMDX') + names(tile, 'MWMO'))
|
|
report['helpers'] = dict(requested=HELPERS, missing=[], aliases=[],
|
|
legacy_m2_without_skin=[], converted_m2=[], m2_conversion_failures=[],
|
|
editor_preview_resampled=[])
|
|
written = set()
|
|
def asset(path, missing, *, destination_path=None):
|
|
normalized = (destination_path or path).replace('\\', '/').lower()
|
|
if normalized in written:
|
|
return
|
|
raw = octo_mpq.read(path)
|
|
if raw is None:
|
|
missing.append(path)
|
|
return
|
|
if normalized.endswith('.m2') and raw[:4] == b'MD20' and struct.unpack_from('<I', raw, 4)[0] in (256, 257):
|
|
try:
|
|
source = raw
|
|
if struct.unpack_from('<I', source, 4)[0] == 257:
|
|
source = source[:4] + struct.pack('<I', 256) + source[8:]
|
|
body, skins, _ = convert_equipment(
|
|
source, allow_qualified_cutout_shader16=True,
|
|
paired_single_texture_rule=True, convert_ribbons=True,
|
|
convert_particles=True, convert_uv_animation=True,
|
|
convert_lights=True,
|
|
editor_preview_resample_pre_window=(normalized ==
|
|
'world/azeroth/elwynn/activedoodads/abbeybell/nsabbeybell.m2'))
|
|
if normalized.endswith('/nsabbeybell.m2'):
|
|
report['helpers']['editor_preview_resampled'].append(normalized)
|
|
if body[:4] != b'MD20' or struct.unpack_from('<I', body, 4)[0] != 272 or not skins:
|
|
raise ValueError('unreviewed converter output')
|
|
# The v272 writer appends 16 bytes to each particle record.
|
|
# Noggit's v264 reader uses a 476-byte record; relocate a
|
|
# compact array while retaining the track payload addresses.
|
|
native = bytearray(body)
|
|
particle_count, particle_offset = struct.unpack_from('<II', native, 296)
|
|
if particle_count:
|
|
if particle_offset + particle_count * 492 > len(native):
|
|
raise ValueError('particle array outside converted model')
|
|
compact = b''.join(native[particle_offset + i * 492:
|
|
particle_offset + i * 492 + 476]
|
|
for i in range(particle_count))
|
|
native.extend(b'\0' * (-len(native) % 16))
|
|
struct.pack_into('<I', native, 300, len(native))
|
|
native.extend(compact)
|
|
struct.pack_into('<I', native, 4, 264)
|
|
raw = bytes(native)
|
|
for index, skin in enumerate(skins):
|
|
skin_path = normalized[:-3] + f'{index:02}.skin'
|
|
put(common, skin_path, skin)
|
|
written.add(skin_path)
|
|
report['helpers']['converted_m2'].append(normalized)
|
|
except ValueError as error:
|
|
report['helpers']['m2_conversion_failures'].append(dict(path=normalized,reason=str(error)[:120]))
|
|
put(common, normalized, raw)
|
|
written.add(normalized)
|
|
if normalized.endswith('.m2'):
|
|
skin_count = 0
|
|
for index in range(8):
|
|
skin = normalized[:-3] + f'{index:02}.skin'
|
|
data = octo_mpq.read(skin)
|
|
if data is None:
|
|
break
|
|
put(common, skin, data)
|
|
written.add(skin)
|
|
skin_count += 1
|
|
if not skin_count and normalized not in report['helpers']['converted_m2']:
|
|
report['helpers']['legacy_m2_without_skin'].append(normalized)
|
|
for texture in m2_textures(raw):
|
|
asset(texture, missing)
|
|
if normalized.endswith('.wmo'):
|
|
for texture in names(raw, 'MOTX'):
|
|
asset(texture, missing)
|
|
for model in names(raw, 'MODN'):
|
|
# WMO doodad names retain legacy .MDX/.MDL suffixes while the
|
|
# Source archive stores their MD20 payloads under .M2 names.
|
|
if model.lower().endswith(('.mdx', '.mdl')):
|
|
model = model[:-4] + '.m2'
|
|
asset(model, missing)
|
|
stem = path[:-4]
|
|
for group in range(64):
|
|
member = f'{stem}_{group:03}.wmo'
|
|
data = octo_mpq.read(member)
|
|
if data is None:
|
|
break
|
|
put(common, member, data)
|
|
written.add(member.replace('\\', '/').lower())
|
|
for path in sorted(required):
|
|
asset(path, report['assets']['missing'])
|
|
for path in HELPERS:
|
|
if path.endswith('.mdx'):
|
|
source = path[:-4] + '.m2'
|
|
if octo_mpq.read(path) is None and octo_mpq.read(source) is not None:
|
|
report['helpers']['aliases'].append(dict(requested=path,source=source))
|
|
asset(source, report['helpers']['missing'])
|
|
continue
|
|
asset(path, report['helpers']['missing'])
|
|
report['assets']['written'] = len(written)
|
|
report['tile'] = dict(name=tile_name, sha256=hashlib.sha256(tile).hexdigest(),
|
|
source_bytes=len(tile), editor_copy_exact=True)
|
|
converted_root = roundtrip_root(tile)
|
|
report['roundtrip'] = dict(root_sha256=hashlib.sha256(converted_root).hexdigest(),
|
|
root_bytes=len(converted_root),
|
|
live_root_equal=(converted_root == native_root.read_bytes()) if native_root else None)
|
|
if native_root and not report['roundtrip']['live_root_equal']:
|
|
raise ValueError('Elwynn root round-trip differs from live native root')
|
|
if native_tex0 and native_obj0:
|
|
report['roundtrip'].update(roundtrip_other_roles(
|
|
tile, native_tex0.read_bytes(), native_obj0.read_bytes()))
|
|
if not report['roundtrip']['tex0_byte_equal']:
|
|
raise ValueError('Elwynn TEX0 round-trip differs from live native tile')
|
|
(destination / 'editor-client-127-report.json').write_text(json.dumps(report, indent=2) + '\n')
|
|
return report
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--output', type=Path, default=Path('/mnt/Games/@project/editor-client-127'))
|
|
parser.add_argument('--definitions', type=Path,
|
|
default=Path('/mnt/Games/@project/tools/noggit-red/build/bin/definitions'))
|
|
parser.add_argument('--native-root', type=Path, help='read-only extracted live root FDID from LOCAL WDT')
|
|
parser.add_argument('--native-tex0', type=Path, help='read-only extracted live TEX0 FDID')
|
|
parser.add_argument('--native-obj0', type=Path, help='read-only extracted live OBJ0 FDID')
|
|
args = parser.parse_args()
|
|
result = stage(args.output, args.definitions, args.native_root, args.native_tex0, args.native_obj0)
|
|
print(json.dumps(dict(dbc=len(result['dbc']), assets=result['assets']['written'],
|
|
missing=len(result['assets']['missing']), tile=result['tile']['sha256'][:12],
|
|
roundtrip_root=result['roundtrip']['live_root_equal'])))
|