367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
251 lines
11 KiB
Python
251 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Native 70334 Light hotfix rows for Source maps that have no native lights.
|
|
|
|
REA (runtime/continuation-20261111/wmo-outdoor): native Light.db2 has no row
|
|
for ContinentID 820 (Windhorn Canyon). Outdoors the converted canyon WMO is
|
|
drawn, but it renders entirely in fog colour, and so does the player model.
|
|
Interior groups, which do not take the outdoor light, render textured. The
|
|
Source Light.dbc does define map 820 (row 573, a copy of Kalimdor row 204).
|
|
|
|
Conversion contract, checked against Light rows that both tables share:
|
|
native X = 17066.666 - src.z / 36, Y = 17066.666 - src.x / 36, Z = src.y / 36,
|
|
falloff start/end = src / 36.
|
|
Native LightParams were renumbered per slot. Each (slot, Source LightParams
|
|
ID) pair maps to the native ID in that slot of the same Light row ID (with
|
|
matching coordinates and continent), by majority vote. If any nonzero Source param has
|
|
no vote, its row is held and never guessed.
|
|
|
|
A Source map that has no global light (all-zero coordinates) also gets one
|
|
native global row. It copies the params of the Source light with the widest
|
|
falloff. Without it, any position outside every positional falloff falls
|
|
back to the native no-light state (the fog-coloured scene).
|
|
|
|
Offline tool only: the rows are added to an existing hotfix package through
|
|
map_row_compat.merge_rows.
|
|
"""
|
|
import argparse
|
|
import collections
|
|
import hashlib
|
|
import json
|
|
import struct
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'ops'))
|
|
import map_row_compat as mrc # noqa: E402
|
|
|
|
LIGHT_TABLE = 0x5CCAA0BA
|
|
LIGHT_LAYOUT = 0x5F16BC84
|
|
# Light.db2 LAYOUT 5F16BC84 field storage (1.60.1.70334): 96/32/32/16/128 bits.
|
|
LIGHT_SCHEMA = (('GameCoords', 'float', 32, False, 3), ('GameFalloffStart', 'float', 32, False, 1),
|
|
('GameFalloffEnd', 'float', 32, False, 1), ('ContinentID', 'int', 16, False, 1),
|
|
('LightParamsID', 'int', 16, False, 8))
|
|
CENTER = 17066.666
|
|
POLICY = 'source-map-light-v1'
|
|
SOURCE_PARAMS = 5
|
|
|
|
|
|
def read_wdc5(raw):
|
|
"""Minimal WDC5 reader (none/bitpacked/common/pallet/array storage), unencrypted sections only."""
|
|
if raw[:4] != b'WDC5':
|
|
raise ValueError('WDC5 required')
|
|
h = struct.unpack_from('<4I2I2I I 2H 7I', raw, 136)
|
|
fc, rs, table, layout, flags, idx, sections = h[1], h[2], h[4], h[5], h[9], h[10], h[17]
|
|
at = 136 + 68
|
|
secs = [struct.unpack_from('<Q8I', raw, at + 40 * i) for i in range(sections)]
|
|
at += 40 * sections + 4 * fc
|
|
info = [struct.unpack_from('<HHI I 3I', raw, at + 24 * i) for i in range(fc)]
|
|
at += 24 * fc
|
|
pallets = []
|
|
for f in info:
|
|
n = f[2] // 4 if f[3] in (3, 4) else 0
|
|
pallets.append(struct.unpack_from('<%dI' % n, raw, at))
|
|
at += 4 * n
|
|
common = []
|
|
for f in info:
|
|
values = {}
|
|
if f[3] == 2:
|
|
for k in range(f[2] // 8):
|
|
key, value = struct.unpack_from('<II', raw, at + 8 * k)
|
|
values[key] = value
|
|
at += f[2]
|
|
common.append(values)
|
|
rows = {}
|
|
copies = []
|
|
for tact, offset, count, strings, _end, id_size, _rel, _omc, _copy in secs:
|
|
if tact:
|
|
continue
|
|
ids = struct.unpack_from('<%dI' % count, raw, offset + count * rs + strings) if id_size else None
|
|
for i in range(count):
|
|
base = offset + i * rs
|
|
bits_all = int.from_bytes(raw[base:base + rs], 'little')
|
|
values = []
|
|
for n, (f, pal) in enumerate(zip(info, pallets)):
|
|
bits = (bits_all >> f[0]) & ((1 << f[1]) - 1)
|
|
if f[3] == 0:
|
|
values.append(raw[base + f[0] // 8:base + (f[0] + f[1]) // 8])
|
|
elif f[3] == 1:
|
|
values.append(bits)
|
|
elif f[3] == 5:
|
|
values.append(bits - (1 << f[1]) if bits >> (f[1] - 1) else bits)
|
|
elif f[3] == 2:
|
|
values.append(common[n].get(ids[i] if ids else None, f[4]))
|
|
elif f[3] == 3:
|
|
values.append(pal[bits])
|
|
elif f[3] == 4:
|
|
values.append(list(pal[bits * f[6]:(bits + 1) * f[6]]))
|
|
else:
|
|
raise ValueError('Unsupported storage')
|
|
rows[ids[i] if ids else values[idx]] = values
|
|
if _omc and _copy:
|
|
raise ValueError('WDC5 copies with offset maps are not supported')
|
|
copy_at = offset + count * rs + strings + id_size + _rel
|
|
for i in range(_copy):
|
|
copies.append(struct.unpack_from('<II', raw, copy_at + 8 * i))
|
|
for new_id, source_id in copies:
|
|
if source_id not in rows or new_id in rows:
|
|
raise ValueError('Invalid WDC5 copy row')
|
|
rows[new_id] = list(rows[source_id])
|
|
return dict(table=table, layout=layout, max_id=h[7], rows=rows)
|
|
|
|
|
|
def native_lights(raw):
|
|
t = read_wdc5(raw)
|
|
if (t['table'], t['layout']) != (LIGHT_TABLE, LIGHT_LAYOUT):
|
|
raise ValueError('Native Light table/layout differs')
|
|
out = {}
|
|
for rid, v in t['rows'].items():
|
|
out[rid] = dict(ID=rid, GameCoords=list(struct.unpack('<3f', v[0])),
|
|
GameFalloffStart=struct.unpack('<f', v[1])[0], GameFalloffEnd=struct.unpack('<f', v[2])[0],
|
|
ContinentID=struct.unpack('<h', v[3])[0], LightParamsID=list(struct.unpack('<8H', v[4])))
|
|
return out, t['max_id']
|
|
|
|
|
|
def source_lights(raw):
|
|
if raw[:4] != b'WDBC':
|
|
raise ValueError('WDBC required')
|
|
n, fields, size, _ = struct.unpack_from('<4I', raw, 4)
|
|
if fields != 12 or size != 48:
|
|
raise ValueError('Source Light.dbc layout differs')
|
|
out = {}
|
|
for i in range(n):
|
|
r = struct.unpack_from('<2I5f5I', raw, 20 + i * size)
|
|
out[r[0]] = dict(ID=r[0], ContinentID=r[1], coords=r[2:5], start=r[5], end=r[6], params=list(r[7:12]))
|
|
return out
|
|
|
|
|
|
def to_native(src):
|
|
x, y, z = src['coords']
|
|
if (x, y, z) == (0, 0, 0):
|
|
coords = [0.0, 0.0, 0.0]
|
|
else:
|
|
coords = [CENTER - z / 36, CENTER - x / 36, y / 36]
|
|
return dict(GameCoords=coords, GameFalloffStart=src['start'] / 36, GameFalloffEnd=src['end'] / 36,
|
|
ContinentID=src['ContinentID'])
|
|
|
|
|
|
def _same_place(a, b, tolerance=1.0):
|
|
return (a['ContinentID'] == b['ContinentID'] and
|
|
all(abs(p - q) <= tolerance for p, q in zip(a['GameCoords'], b['GameCoords'])) and
|
|
abs(a['GameFalloffEnd'] - b['GameFalloffEnd']) <= tolerance)
|
|
|
|
|
|
def params_mapping(source, native):
|
|
"""(slot, Source LightParams ID) -> native ID by vote over identical Light rows."""
|
|
votes = collections.defaultdict(collections.Counter)
|
|
for rid, s in source.items():
|
|
n = native.get(rid)
|
|
if n is None or not _same_place(to_native(s), n):
|
|
continue
|
|
for slot in range(SOURCE_PARAMS):
|
|
if s['params'][slot]:
|
|
votes[(slot, s['params'][slot])][n['LightParamsID'][slot]] += 1
|
|
mapping = {}
|
|
for p, c in votes.items():
|
|
(best, count), *rest = c.most_common(2) + [(None, 0)]
|
|
if best and count > rest[0][1]:
|
|
mapping[p] = best
|
|
return mapping, votes
|
|
|
|
|
|
def map_rows(source, native, mapping, next_id, maps=None):
|
|
"""Native rows for every Source continent that has zero native Light rows."""
|
|
have = collections.Counter(n['ContinentID'] for n in native.values())
|
|
by_map = collections.defaultdict(list)
|
|
for s in sorted(source.values(), key=lambda s: s['ID']):
|
|
if have[s['ContinentID']] == 0 and (maps is None or s['ContinentID'] in maps):
|
|
by_map[s['ContinentID']].append(s)
|
|
rows, held, report = [], [], {}
|
|
for m in sorted(by_map):
|
|
made = []
|
|
for s in by_map[m]:
|
|
missing = [p for k, p in enumerate(s['params']) if p and (k, p) not in mapping]
|
|
if missing:
|
|
held.append(dict(source_id=s['ID'], map=m, unmapped_params=missing))
|
|
continue
|
|
rec = dict(to_native(s), LightParamsID=[mapping.get((k, p), 0) for k, p in enumerate(s['params'])] + [0] * 3)
|
|
made.append((s, rec))
|
|
if made and not any(s['coords'] == (0, 0, 0) for s, _ in made):
|
|
widest = max(made, key=lambda sr: (sr[0]['end'], -sr[0]['ID']))[1]
|
|
made.append((None, dict(GameCoords=[0.0, 0.0, 0.0], GameFalloffStart=0.0, GameFalloffEnd=0.0,
|
|
ContinentID=m, LightParamsID=list(widest['LightParamsID']))))
|
|
for s, rec in made:
|
|
rec['ID'] = next_id
|
|
rows.append(dict(rec, source_id=s['ID'] if s else None))
|
|
next_id += 1
|
|
report[m] = dict(source=len(by_map[m]), rows=len(made), held=len(by_map[m]) - sum(1 for s, _ in made if s))
|
|
return rows, held, report
|
|
|
|
|
|
def package_rows(rows):
|
|
out = []
|
|
for r in rows:
|
|
rec = {k: r[k] for k in ('ID', 'GameCoords', 'GameFalloffStart', 'GameFalloffEnd', 'ContinentID', 'LightParamsID')}
|
|
body = mrc.composer.encode(rec, LIGHT_SCHEMA)
|
|
if len(body) != 38:
|
|
raise ValueError('Light hotfix body size')
|
|
out.append(mrc.package_row('Light', LIGHT_TABLE, rec['ID'], rec, body, POLICY))
|
|
return out
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
p.add_argument('--source-dbc', type=Path, required=True, help='Source Light.dbc')
|
|
p.add_argument('--native-db2', type=Path, required=True, help='native 70334 Light.db2')
|
|
p.add_argument('--package', type=Path, required=True)
|
|
p.add_argument('--package-sha256')
|
|
p.add_argument('--map', type=int, action='append', help='limit to these Source map IDs')
|
|
p.add_argument('--output', type=Path, required=True)
|
|
p.add_argument('--report', type=Path, required=True)
|
|
a = p.parse_args()
|
|
raw = a.package.read_bytes()
|
|
if a.package_sha256 and hashlib.sha256(raw).hexdigest() != a.package_sha256:
|
|
raise SystemExit('package sha256 differs')
|
|
pkg = json.loads(raw)
|
|
source = source_lights(a.source_dbc.read_bytes())
|
|
native, max_id = native_lights(a.native_db2.read_bytes())
|
|
taken = {r['id'] for r in pkg['rows'] if int(r['table_hash'], 16) == LIGHT_TABLE}
|
|
next_id = max([max_id] + list(taken)) + 1
|
|
mapping, votes = params_mapping(source, native)
|
|
rows, held, per_map = map_rows(source, native, mapping, next_id, set(a.map) if a.map else None)
|
|
cand, _, replaced = mrc.merge_rows(pkg, package_rows(rows))
|
|
if replaced:
|
|
raise SystemExit('unexpected replacement')
|
|
text = json.dumps(cand, separators=(',', ':')) + '\n'
|
|
a.output.write_text(text)
|
|
sha = hashlib.sha256(text.encode()).hexdigest()
|
|
a.output.with_name('package.sha256').write_text(sha + '\n')
|
|
used = {(k, p) for s in source.values() if s['ContinentID'] in per_map for k, p in enumerate(s['params']) if p}
|
|
report = dict(policy=POLICY, package_sha256=sha, rows=rows, held=held, per_map=per_map,
|
|
denominators=dict(source_rows=len(source), source_maps_without_native=len(per_map),
|
|
rows_emitted=len(rows), source_rows_held=len(held),
|
|
params_used=len(used), params_mapped=len(used & set(mapping)),
|
|
params_unmapped=[list(x) for x in sorted(used - set(mapping))]))
|
|
a.report.write_text(json.dumps(report, indent=1) + '\n')
|
|
print('maps', len(per_map), 'rows', len(rows), 'held', len(held), 'params', len(used & set(mapping)), '/', len(used))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|