110 lines
4.7 KiB
Python
110 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Build queryable enUS 70334 BroadcastText DBReply records from the frozen NPC text index."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import struct
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
INDEX_SHA256 = '78566423f7b587bfe4b8649990ce3fd98e80cd4a8e6eea728db1ec29676ef533'
|
|
TABLE_HASH = 0x021826BB
|
|
LAYOUT_HASH = 0x00EB45B3
|
|
TAIL = struct.Struct('<IiiHiIi2I3H3H')
|
|
PAGE_LIMIT = 16384
|
|
|
|
|
|
def cstring(text):
|
|
if '\0' in text:
|
|
raise ValueError('embedded NUL in BroadcastText')
|
|
return text.encode('utf-8') + b'\0'
|
|
|
|
|
|
def record(row):
|
|
# DB2StorageBase::WriteRecord emits two C strings and the inline ID. No
|
|
# ChatType field exists. The original NPC_TEXT_UPDATE did not carry audio.
|
|
return cstring(row['Text']) + cstring(row['Text1']) + TAIL.pack(
|
|
row['ID'], row['LanguageID'], 0, 0, 0, 0, 0, 0, 0,
|
|
*row['EmoteID'], *row['EmoteDelay'])
|
|
|
|
|
|
def native_ids(db2):
|
|
# WDC5, one ordinary section, inline bitpacked ID in field 2. These are
|
|
# layout-specific checks, independent of text contents and ID contiguity.
|
|
if db2[:4] != b'WDC5' or len(db2) < 364:
|
|
raise ValueError('expected the 70334 BroadcastText WDC5 file')
|
|
count, fields, stride, _, table, layout = struct.unpack_from('<6I', db2, 136)
|
|
index, = struct.unpack_from('<H', db2, 174)
|
|
sections, = struct.unpack_from('<I', db2, 200)
|
|
_, offset, rows, _, sparse, ids, related, maps, copies = struct.unpack_from('<Q8I', db2, 204)
|
|
bits, width, _, storage = struct.unpack_from('<HHII', db2, 244 + fields * 4 + index * 24)
|
|
if (table, layout, fields, index, sections, rows) != (TABLE_HASH, LAYOUT_HASH, 12, 2, 1, count):
|
|
raise ValueError('BroadcastText metadata mismatch')
|
|
if any((sparse, ids, related, maps, copies)) or storage not in (1, 5) or bits + width > stride * 8:
|
|
raise ValueError('unsupported native ID storage')
|
|
if offset + count * stride > len(db2):
|
|
raise ValueError('short native record section')
|
|
return {(int.from_bytes(db2[pos:pos + stride], 'little') >> bits) & ((1 << width) - 1)
|
|
for pos in range(offset, offset + count * stride, stride)}
|
|
|
|
|
|
def encode_page(rows):
|
|
# Count and each [ID, payload offset] use little endian. Each inflated page
|
|
# is at most 16 KiB, so a 16-bit relative offset suffices.
|
|
payload = bytearray()
|
|
directory = bytearray(struct.pack('<H', len(rows)))
|
|
for identity, data in rows:
|
|
directory.extend(struct.pack('<IH', identity, len(payload)))
|
|
payload.extend(data)
|
|
raw = directory + payload
|
|
assert len(raw) <= PAGE_LIMIT
|
|
return rows[0][0], rows[-1][0], len(raw), zlib.compress(raw, 9)
|
|
|
|
|
|
def generate(index, db2):
|
|
if hashlib.sha256(index).hexdigest() != INDEX_SHA256:
|
|
raise ValueError('unexpected enUS NPC text index digest')
|
|
original = native_ids(db2)
|
|
pages, batch, used, previous = [], [], 2, 0
|
|
for line in index.splitlines():
|
|
row = json.loads(line)
|
|
identity = row['ID']
|
|
if identity <= previous or identity >= 1 << 24 or identity in original:
|
|
raise ValueError(f'invalid/conflicting target ID {identity}')
|
|
previous = identity
|
|
data = record(row)
|
|
size = 6 + len(data)
|
|
if size + 2 > PAGE_LIMIT:
|
|
raise ValueError(f'oversize record {identity}')
|
|
if used + size > PAGE_LIMIT:
|
|
pages.append(encode_page(batch)); batch, used = [], 2
|
|
batch.append((identity, data)); used += size
|
|
if batch:
|
|
pages.append(encode_page(batch))
|
|
output = ['// Generated by ops/build_broadcast_text_reply.py from the pinned enUS index.',
|
|
'#pragma once', '#include <cstdint>', 'namespace gateway::broadcast_text::data {',
|
|
'struct Page { uint32_t first, last; uint16_t size, compressed; const char* bytes; };',
|
|
'inline constexpr uint16_t PageLimit = 16384;', 'inline constexpr Page Pages[] = {']
|
|
for first, last, size, compressed in pages:
|
|
output.append(f'{{{first},{last},{size},{len(compressed)},')
|
|
for pos in range(0, len(compressed), 64):
|
|
output.append('"' + ''.join(f'\\{b:03o}' for b in compressed[pos:pos + 64]) + '"')
|
|
output.append('},')
|
|
output.extend(('};', '}', ''))
|
|
return '\n'.join(output)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('index', type=Path)
|
|
parser.add_argument('native_db2', type=Path)
|
|
parser.add_argument('output', type=Path)
|
|
parser.add_argument('--check', action='store_true')
|
|
args = parser.parse_args()
|
|
header = generate(args.index.read_bytes(), args.native_db2.read_bytes())
|
|
if args.check:
|
|
if args.output.read_bytes() != header.encode():
|
|
raise SystemExit('BroadcastText generated header differs')
|
|
else:
|
|
args.output.write_bytes(header.encode())
|