112 lines
5.0 KiB
Python
112 lines
5.0 KiB
Python
#!/usr/bin/env python3
|
|
"""#124 Earthen Ring: set pallet-array fields of one WDC5 row in place, appending pallet entries when a value is new.
|
|
|
|
Faction.db2 (70334) stores ReputationClassMask/Flags/Base/RaceMasks* as bitpacked-indexed-array columns (pallet type 4).
|
|
The live package dropped faction 1014's third reputation entry (Source: races 434, classes 1439, flags 16, base 0), so a
|
|
Tauren/Orc/Troll non-shaman matches no entry and the faction is hidden. DBCD's writer re-encodes the whole table and
|
|
changes ParentFactionID on 181 unrelated rows, so this tool edits only:
|
|
- the touched columns' pallets (one appended array each when the value is not already present),
|
|
- field_info additional_data_size, header pallet_size, and section file offsets (shifted by the inserted bytes),
|
|
- the target record's index bits.
|
|
Every other record keeps its exact bytes. The result is re-read and compared row by row with the input.
|
|
|
|
pallet_patch.py in.db2 out.db2 rows.json # rows.json: {"table":"Faction","id":1014,"set":{"ReputationClassMask":[...]}}
|
|
"""
|
|
import json, struct, sys
|
|
from pathlib import Path
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'claude_recipe_parity'))
|
|
import dbd # noqa: E402
|
|
|
|
HDR = struct.Struct('<4I2I2I I 2H 7I')
|
|
|
|
|
|
def u32(v):
|
|
return v & 0xffffffff
|
|
|
|
|
|
def patch(raw, table, rid, values):
|
|
t = dbd.table_bytes(table, raw) if hasattr(dbd, 'table_bytes') else None
|
|
import tempfile, os
|
|
if t is None:
|
|
with tempfile.NamedTemporaryFile(delete=False, suffix='.db2') as f:
|
|
f.write(raw); tmp = f.name
|
|
try: t = dbd.table(table, tmp)
|
|
finally: os.unlink(tmp)
|
|
tt = t['t']; h = tt['header']; info = tt['info']; names = t['names']
|
|
row = next(r for r in tt['rows'] if r['id'] == rid)
|
|
pal_at = 136 + HDR.size + 40 * h['section_count'] + 4 * h['field_count'] + 24 * h['field_count']
|
|
# column pallet offsets
|
|
offs = []; at = pal_at
|
|
for f in info:
|
|
offs.append(at); at += f[2] if f[3] in (3, 4) else 0
|
|
inserts = [] # (file_offset, bytes, field_index)
|
|
new_index = {}
|
|
for name, value in values.items():
|
|
fi = names.index(name); bo, bs, add, typ, a, b, c = info[fi]
|
|
if typ != 4: raise ValueError(f'{name}: not a pallet-array column (type {typ})')
|
|
if len(value) != c: raise ValueError(f'{name}: needs {c} values')
|
|
vals = [u32(v) for v in value]
|
|
pal = list(struct.unpack_from(f'<{add // 4}I', raw, offs[fi]))
|
|
arrs = [pal[i * c:(i + 1) * c] for i in range(len(pal) // c)]
|
|
if vals in arrs:
|
|
idx = arrs.index(vals)
|
|
else:
|
|
idx = len(arrs)
|
|
if idx >= 1 << bs: raise ValueError(f'{name}: pallet full ({idx} entries, {bs} bits)')
|
|
inserts.append((offs[fi] + add, struct.pack(f'<{c}I', *vals), fi))
|
|
new_index[fi] = idx
|
|
out = bytearray(raw)
|
|
# record bits first (record offsets are before the shift)
|
|
ro = row['ro']; rs = h['record_size']
|
|
rec = int.from_bytes(out[ro:ro + rs], 'little')
|
|
for fi, idx in new_index.items():
|
|
bo, bs = info[fi][0], info[fi][1]
|
|
rec = (rec & ~(((1 << bs) - 1) << bo)) | (idx << bo)
|
|
out[ro:ro + rs] = rec.to_bytes(rs, 'little')
|
|
# insert pallet bytes from the back so earlier offsets stay valid
|
|
total = 0
|
|
for off, data, fi in sorted(inserts, key=lambda x: -x[0]):
|
|
out[off:off] = data; total += len(data)
|
|
ia = 136 + HDR.size + 40 * h['section_count'] + 4 * h['field_count'] + 24 * fi
|
|
f = list(struct.unpack_from('<HHII3I', out, ia)); f[2] += len(data); struct.pack_into('<HHII3I', out, ia, *f)
|
|
if total:
|
|
hv = list(HDR.unpack_from(out, 136)); hv[dbd_names().index('pallet_size')] += total; HDR.pack_into(out, 136, *hv)
|
|
for si in range(h['section_count']):
|
|
sa = 136 + HDR.size + 40 * si
|
|
s = list(struct.unpack_from('<Q8I', out, sa))
|
|
s[1] += total
|
|
if s[4]: s[4] += total
|
|
struct.pack_into('<Q8I', out, sa, *s)
|
|
return bytes(out), dict(inserted_bytes=total, indices={names[k]: v for k, v in new_index.items()})
|
|
|
|
|
|
def dbd_names():
|
|
return list(dbd.w.NAMES)
|
|
|
|
|
|
def rows_of(table, data):
|
|
import tempfile, os
|
|
with tempfile.NamedTemporaryFile(delete=False, suffix='.db2') as f:
|
|
f.write(data); tmp = f.name
|
|
try: return dbd.table(table, tmp)['rows']
|
|
finally: os.unlink(tmp)
|
|
|
|
|
|
def main():
|
|
src, dst, spec = map(Path, sys.argv[1:4])
|
|
s = json.loads(spec.read_text()); raw = src.read_bytes()
|
|
new, rep = patch(raw, s['table'], s['id'], s['set'])
|
|
a = rows_of(s['table'], raw); b = rows_of(s['table'], new)
|
|
assert a.keys() == b.keys(), 'row set changed'
|
|
changed = [k for k in a if a[k] != b[k]]
|
|
assert changed == [s['id']], f'unexpected rows changed: {changed[:10]}'
|
|
for name, value in s['set'].items():
|
|
got = [v - (1 << 32) if v >> 31 else v for v in b[s['id']][name]]
|
|
assert got == value, (name, got, value)
|
|
dst.write_bytes(new)
|
|
print(json.dumps(dict(rep, rows=len(a), changed_rows=changed, bytes_in=len(raw), bytes_out=len(new))))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|