Files
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

273 lines
14 KiB
Python

"""Add missing native split-ADT WMO footprint references without reimporting geometry.
Native 70334 Stormwind UID10047 is listed in MODF in every one of its16
AABB-overlapping ADTs. Its MCNK MCRW masks are narrower than that AABB;
callers must supply separately proven cell masks, never derive them from the
placement bounds. Reuse adt_obj1's established MLMD/MLMX serialization.
"""
import math
import struct
from collections.abc import Mapping
import adt_obj1
TILE_SIZE = 1600 / 3
CELL_SIZE = TILE_SIZE / 16
def placement_tiles(row):
"""Return the in-map tile footprint of one numeric64-byte native MODF."""
if not isinstance(row, bytes) or len(row) != 64:
raise ValueError('Exactly one native64-byte MODF required')
if not struct.unpack_from('<H', row, 56)[0] & 8:
raise ValueError('Numeric FileDataID MODF required')
values = struct.unpack_from('<12f', row, 8)
if not all(math.isfinite(v) for v in values):
raise ValueError('Finite MODF transform and bounds required')
low, high = values[6:9], values[9:12]
if any(a > b for a, b in zip(low, high)):
raise ValueError('Ordered MODF bounds required')
ranges = [(max(0, math.floor(low[i] / TILE_SIZE)),
min(63, math.floor(high[i] / TILE_SIZE))) for i in (0, 2)]
return {(x, y) for y in range(ranges[1][0], ranges[1][1] + 1)
for x in range(ranges[0][0], ranges[0][1] + 1)}
def oriented_root_cell_mask(bounds, placement, tile):
"""Intersect a unit-scale, fully rotated MOHD box with native MCNK cells.
This oriented model-box relationship matches all16 pinned native
Stormwind masks and50 selected native controls, including5 tilted
placements. It is not a MODF world-AABB fill or geometry equivalence claim.
"""
if (not isinstance(bounds, (tuple, list)) or len(bounds) != 6 or
any(type(v) not in (int, float) or not math.isfinite(v) for v in bounds) or
any(bounds[i] > bounds[i + 3] for i in range(3))):
raise ValueError('Six finite ordered MOHD bound coordinates required')
if (not isinstance(placement, bytes) or len(placement) != 64 or
not struct.unpack_from('<H', placement, 56)[0] & 8):
raise ValueError('One numeric64-byte MODF placement required')
if (not isinstance(tile, (tuple, list)) or len(tile) != 2 or
any(type(v) is not int or not 0 <= v < 64 for v in tile)):
raise ValueError('Exact in-map tile required')
pos = struct.unpack_from('<3f', placement, 8)
rot = struct.unpack_from('<3f', placement, 20)
flags, scale = struct.unpack_from('<H', placement, 56)[0], struct.unpack_from('<H', placement, 62)[0]
if not all(math.isfinite(v) for v in (*pos, *rot)):
raise ValueError('Finite placement transform required')
if (scale / 1024 if flags & 4 else 1) != 1:
raise ValueError('Nonunit root-box scale is not qualified')
lo, hi = bounds[:3], bounds[3:]
# Use the established ADT rotation order/axis mapping, not a new Euler
# convention. Tilted boxes project to the hull of all eight3D corners.
matrix = adt_obj1._rotation(rot)
projected = [(pos[0] - sum(matrix[1][i]*v[i] for i in range(3)),
pos[2] - sum(matrix[0][i]*v[i] for i in range(3)))
for v in ((x, y, z) for x in (lo[0], hi[0])
for y in (lo[1], hi[1]) for z in (lo[2], hi[2]))]
if not all(math.isfinite(v) for point in projected for v in point):
raise ValueError('Finite projected root box required')
points = sorted(set(projected))
def cross(o, a, b):
return (a[0] - o[0])*(b[1] - o[1]) - (a[1] - o[1])*(b[0] - o[0])
def half(sequence):
result = []
for point in sequence:
while len(result) >= 2 and cross(result[-2], result[-1], point) <= 0:
result.pop()
result.append(point)
return result
polygon = points if len(points) < 2 else half(points)[:-1] + half(reversed(points))[:-1]
axes = [(1, 0), (0, 1)] + [(polygon[(i + 1) % len(polygon)][1] - polygon[i][1],
polygon[i][0] - polygon[(i + 1) % len(polygon)][0])
for i in range(len(polygon))]
result = []
for cell in range(256):
x = tile[0]*TILE_SIZE + (cell % 16)*CELL_SIZE
y = tile[1]*TILE_SIZE + (cell // 16)*CELL_SIZE
box = [(x, y), (x + CELL_SIZE, y), (x + CELL_SIZE, y + CELL_SIZE), (x, y + CELL_SIZE)]
# No tolerance/nearest-cell rule: edge touches count as intersections.
for a, b in axes:
p = [a*px + b*py for px, py in polygon]
q = [a*px + b*py for px, py in box]
if max(p) < min(q) or max(q) < min(p):
break
else:
result.append(cell)
return result
def _records(raw):
return [(tag[::-1], data) for tag, data in adt_obj1._chunks(raw)]
def _pack(records):
return b''.join(adt_obj1._chunk(tag, data) for tag, data in records)
def _single(records, tag):
rows = [data for name, data in records if name == tag]
if len(rows) != 1:
raise ValueError('Exactly one ' + tag.decode() + ' required')
return rows[0]
def rewrite_cell_references(obj0, masks_by_existing_MODF_index, *, replace_indices=()):
"""Append proved MCRW refs; remove only for explicit replacement indices.
MODF/MDDF, unrelated refs and their order, and opaque chunks are preserved.
Callers own the evidence for each mask. No placement is created or changed.
"""
if not isinstance(obj0, bytes) or not isinstance(masks_by_existing_MODF_index, Mapping):
raise ValueError('Native obj0 bytes and an existing-index mask mapping required')
records = _records(obj0)
if _single(records, b'MVER') != struct.pack('<I', 18):
raise ValueError('Native v18 obj0 required')
modf = _single(records, b'MODF')
if len(modf) % 64:
raise ValueError('Whole existing MODF placements required')
count = len(modf) // 64
masks = {}
for index, cells in masks_by_existing_MODF_index.items():
if type(index) is not int or not 0 <= index < count or index in masks:
raise ValueError('Distinct existing MODF indices required')
if (not isinstance(cells, (tuple, list, set, frozenset)) or len(cells) > 256 or
any(type(v) is not int or not 0 <= v < 256 for v in cells) or
len(cells) != len(set(cells))):
raise ValueError('Distinct MCNK ordinal mask required')
masks[index] = set(cells)
if (not isinstance(replace_indices, (tuple, list, set, frozenset)) or
any(type(v) is not int or v not in masks for v in replace_indices) or
len(replace_indices) != len(set(replace_indices))):
raise ValueError('Distinct replacement indices must have supplied masks')
replace = set(replace_indices)
out, changed, added, removed, cell = [], [], 0, 0, 0
for tag, data in records:
if tag == b'MCNK':
if cell >= 256:
raise ValueError('Complete256 native object MCNKs required')
children = _records(data)
payloads = [value for name, value in children if name == b'MCRW']
if len(payloads) > 1 or (payloads and len(payloads[0]) % 4):
raise ValueError('Whole unique MCRW required')
refs = [v for (v,) in struct.iter_unpack('<I', payloads[0] if payloads else b'')]
if any(v >= count for v in refs) or len(refs) != len(set(refs)):
raise ValueError('Distinct cell WMO references within existing MODF required')
kept = [v for v in refs if v not in replace or cell in masks[v]]
extra = [v for v in sorted(masks) if cell in masks[v] and v not in kept]
new = kept + extra
if new != refs:
changed.append(cell); added += len(extra); removed += len(refs) - len(kept)
payload = struct.pack('<' + 'I'*len(new), *new)
if payloads:
# The native split writer omits an empty reference list.
# Do not introduce an unqualified size-zero MCRW chunk.
children = [(name, payload if name == b'MCRW' else value)
for name, value in children if name != b'MCRW' or payload]
else:
children.append((b'MCRW', payload))
data = _pack(children)
cell += 1
out.append((tag, data))
if cell != 256:
raise ValueError('Complete256 native object MCNKs required')
audit = dict(cell_references_added=added, cell_references_removed=removed,
changed_cells=changed, changed_cell_count=len(changed),
replace_indices=sorted(replace), MODF_MDDF_preserved=True,
other_references_and_order_preserved=True, opaque_chunks_preserved=True)
return (_pack(out) if changed else obj0), audit
def add_placements(obj0, obj1, tile, placements):
"""Return(obj0,obj1,audit), preserving existing records and optional chunks.
placements is an iterable of (native MODF bytes, proven MCNK indices or
None). None deliberately writes no invented cell references and reports a
native-cell-mask hold. A MODF identity is its uniqueId; conflicting duplicate
identities are rejected. Cells are ordinal y*16+x in the existing256 MCNKs.
"""
if (not isinstance(tile, tuple) or len(tile) != 2 or
any(type(v) is not int or not 0 <= v < 64 for v in tile)):
raise ValueError('Exact in-map tile required')
c0, c1 = _records(obj0), _records(obj1)
if (_single(c0, b'MVER') != struct.pack('<I', 18) or
_single(c1, b'MVER') != struct.pack('<I', 18)):
raise ValueError('Native v18 object pair required')
old = _single(c0, b'MODF')
mlmd, mlmx = _single(c1, b'MLMD'), _single(c1, b'MLMX')
if len(old) % 64 or len(mlmd) % 40 or len(mlmx) != len(mlmd) // 40 * 28:
raise ValueError('Whole paired WMO placement extents required')
old_rows = [old[at:at + 64] for at in range(0, len(old), 64)]
projections = sorted(row[:32] + row[56:] for row in old_rows)
if projections != sorted(mlmd[at:at + 40] for at in range(0, len(mlmd), 40)):
raise ValueError('Existing obj0/obj1 WMO identities differ')
by_uid = {}
for row in old_rows:
uid = struct.unpack_from('<I', row, 4)[0]
if uid in by_uid:
raise ValueError('Duplicate existing MODF uniqueId')
by_uid[uid] = row
additions = []
for row, cells in placements:
if tile not in placement_tiles(row):
raise ValueError('Placement footprint does not include target tile')
uid = struct.unpack_from('<I', row, 4)[0]
if uid in by_uid:
if by_uid[uid] != row:
raise ValueError('Conflicting MODF uniqueId')
continue
if cells is not None:
if (not isinstance(cells, (tuple, list)) or len(cells) != len(set(cells)) or
any(type(c) is not int or not 0 <= c < 256 for c in cells)):
raise ValueError('Proven distinct MCNK ordinal mask required')
cells = tuple(sorted(cells))
additions.append((row, cells)); by_uid[uid] = row
additions.sort(key=lambda pair: struct.unpack_from('<I', pair[0], 4)[0])
newrefs = [[] for _ in range(256)]
holds = []
for i, (row, cells) in enumerate(additions, len(old_rows)):
if cells is None:
holds.append(struct.unpack_from('<I', row, 4)[0])
else:
for c in cells:
newrefs[c].append(i)
out0, ci = [], 0
for tag, data in c0:
if tag == b'MODF':
data += b''.join(row for row, _ in additions)
elif tag == b'MCNK':
if ci >= 256:
raise ValueError('Too many native object MCNKs')
children = _records(data)
refs = [v for name, v in children if name == b'MCRW']
if len(refs) > 1 or (refs and len(refs[0]) % 4):
raise ValueError('Whole unique MCRW required')
if refs and any(i >= len(old_rows) for (i,) in struct.iter_unpack('<I', refs[0])):
raise ValueError('Existing cell WMO reference outside MODF')
extra = struct.pack('<' + 'I' * len(newrefs[ci]), *newrefs[ci])
if extra:
if refs:
children = [(name, v + extra if name == b'MCRW' else v) for name, v in children]
else:
children.append((b'MCRW', extra))
data = _pack(children)
ci += 1
out0.append((tag, data))
if ci != 256:
raise ValueError('Complete256 native object MCNKs required')
if not additions:
return obj0, obj1, dict(added=0, cell_references_added=0, held_cell_mask_uids=[])
objects = [(mlmd[40*i:40*i+40], mlmx[28*i:28*i+28]) for i in range(len(mlmd)//40)]
for row, _ in additions:
box = adt_obj1.extents_world_box(struct.unpack_from('<6f', row, 32))
objects.append((row[:32] + row[56:], struct.pack('<7f', *box, adt_obj1._radius(box))))
if any(not all(math.isfinite(x) for x in struct.unpack('<7f', box)) for _, box in objects):
raise ValueError('Finite object bounds/radii required')
objects.sort(key=lambda pair: -struct.unpack_from('<f', pair[1], 24)[0])
out1 = [(tag, b''.join(pair[0] for pair in objects) if tag == b'MLMD' else
b''.join(pair[1] for pair in objects) if tag == b'MLMX' else data) for tag, data in c1]
return _pack(out0), _pack(out1), dict(added=len(additions),
cell_references_added=sum(map(len, newrefs)), held_cell_mask_uids=holds,
old_MODF_prefix_preserved=True, existing_MCRW_values_preserved=True,
existing_obj1_WMO_pairs_preserved=True, M2_and_unknown_chunks_preserved=True)