Files
WoW-Hybrid-gateway/ops/m2_sequence_contract.py

280 lines
14 KiB
Python

"""Native 70334 M2 sequence-table contract post-pass for converted models.
REA (runtime/continuation-20261110/map-wdt/rea-m2-sequence-contract.private.json,
66 native Uldaman doodads, 205 sequences): within one animation ID, in table
order, variationIndex (+2) equals the record's rank (186/186 IDs) and
variationNext (+60) links to the next record of that ID, or -1 for the last one
(186/186). aliasNext (+62) is the record's own index unless the record is an
alias (flag 0x40, aliasNext = target) or the target of one (aliasNext = alias,
whose own aliasNext points back). Converted models had duplicate
variationIndex values and aliasNext 0.
Duration REA (runtime/continuation-20261112/creature-seq/rea-zero-duration
.private.json, 3987 native creature models): 1 of 216984 records has duration
0 and all 40147 alias records carry their target's duration. Source single-pose
sequences (start == end) convert to duration 0; the native animation update
divides by it (FLT_DIVIDE_BY_ZERO at 0x141df6184 in M2 Animate, kodorider
8573369). A zero duration becomes one 30 fps frame, or the target's duration
for an alias. Only those fields are rewritten.
"""
import struct
from collections import defaultdict
ALIAS = 0x40
MIN_DURATION = 33
def _md20_span(raw):
if raw[:4] == b'MD20':
return 0, len(raw)
at = 0
while at + 8 <= len(raw):
size = struct.unpack_from('<I', raw, at + 4)[0]
if raw[at:at + 4] == b'MD21':
return at + 8, size
at += 8 + size
raise ValueError('MD21/MD20 model body required')
def _chunk_tags(raw):
tags, at = set(), 0
if raw[:4] == b'MD20':
return tags
while at + 8 <= len(raw):
tags.add(raw[at:at + 4]); at += 8 + struct.unpack_from('<I', raw, at + 4)[0]
return tags
def sequence_table(raw):
base, size = _md20_span(raw)
count, offset = struct.unpack_from('<II', raw, base + 28)
if offset + 64 * count > size:
raise ValueError('Sequence table outside model body')
return sequence_records(raw, base + offset, count)
def sequence_records(raw, start, count):
"""Decode an already located modern model or skeleton sequence array."""
if start < 0 or count < 0 or start + 64 * count > len(raw):
raise ValueError('Sequence records outside data')
out = []
for i in range(count):
at = start + 64 * i
animation, variation = struct.unpack_from('<HH', raw, at)
out.append(dict(index=i, at=at, animation=animation, variation=variation,
duration=struct.unpack_from('<I', raw, at + 4)[0],
flags=struct.unpack_from('<I', raw, at + 12)[0],
variation_next=struct.unpack_from('<h', raw, at + 60)[0],
alias_next=struct.unpack_from('<H', raw, at + 62)[0]))
return out
def expected_sequence_fields(table):
count = len(table); by = defaultdict(list)
for s in table:
by[s['animation']].append(s['index'])
want = {}
for ids in by.values():
for rank, i in enumerate(ids):
want[i] = dict(variation=rank, variation_next=ids[rank + 1] if rank + 1 < len(ids) else -1)
for s in table:
i, target = s['index'], s['alias_next']
if s['flags'] & ALIAS:
if not 0 <= target < count or target == i:
raise ValueError('Alias sequence target outside table')
alias = target
elif (0 <= target < count and target != i and table[target]['flags'] & ALIAS
and table[target]['alias_next'] == i):
alias = target # native alias-target back pointer
else:
alias = i
want[i]['alias_next'] = alias
for s in table:
if not s['duration']:
target = table[want[s['index']]['alias_next']] if s['flags'] & ALIAS else s
want[s['index']]['duration'] = target['duration'] or MIN_DURATION
return want
def normalize_m2_sequences(raw):
"""Rewrite variationIndex/variationNext/aliasNext and zero durations to the native contract."""
table = sequence_table(raw); want = expected_sequence_fields(table)
changed = [s['index'] for s in table if any(s[k] != v for k, v in want[s['index']].items())]
if changed and any(s['variation'] != want[s['index']]['variation'] for s in table) and b'AFID' in _chunk_tags(raw):
raise ValueError('External .anim (AFID) keyed by variation; renumbering held')
output = bytearray(raw)
for s in table:
w = want[s['index']]
struct.pack_into('<H', output, s['at'] + 2, w['variation'])
struct.pack_into('<h', output, s['at'] + 60, w['variation_next'])
struct.pack_into('<H', output, s['at'] + 62, w['alias_next'])
if 'duration' in w:
struct.pack_into('<I', output, s['at'] + 4, w['duration'])
return bytes(output), dict(sequences=len(table), changed_sequences=changed,
zero_durations=[s['index'] for s in table if 'duration' in want[s['index']]])
# Native Stand-for-missing-Stand layout (REA: the 13 converted doodads without
# animation 0 vs their native counterparts, e.g. Crate02 199634, Chest02,
# TrollDungeonPottery01, AlteracLadder01). Native adds a Stand record carrying
# the curve of one existing sequence S. S becomes an alias (flag 0x40,
# aliasNext -> Stand) and Stand's aliasNext points back to S. Stand's flags are
# S's flags without 0x01/0x40. S is animation 147 when present, else 26, else
# the first record (single-sequence AlteracLadder01: 169). Native stores Stand
# just before S. Here it is appended so existing sequence indices and track
# slots keep their positions; the alias relationship is the same.
STAND_SOURCE_PRIORITY = (147, 26)
_TRACKS = ((44, 88, (16, 36, 56), False), (72, 40, (0, 20), False), (88, 20, (0,), False),
(96, 60, (0, 20, 40), False), (240, 40, (20,), False), (256, 36, (24,), True),
(264, 156, tuple(16 + 20 * k for k in range(7)), False))
# #70: particle emitter M2Tracks (speed, variation, vertical/horizontal range, gravity, lifespan, emission rate,
# area length/width, z source, enabled); layout as m2_sequence_refs.COMPONENTS. Only insert_stand extends them.
_STAND_EXTRA_TRACKS = ((296, 492, (52, 72, 92, 112, 132, 152, 176, 200, 220, 240, 456), False),)
# Value strides of the inline native tracks in _TRACKS order (bone translation/
# compressed rotation/scale, colour/alpha, transparency, texture transform,
# attachment visibility, light). Event tracks carry no values.
_TRACK_STRIDES = {44: (12, 8, 12), 72: (12, 2), 88: (2,), 96: (12, 16, 12), 240: (1,),
264: (12, 4, 12, 4, 4, 4, 1)}
def distinct_key_times(times, duration):
"""Indices to keep and their timestamps so no two keys share a time.
REA (runtime/continuation-20261112/creature-seq/rea-dup-keys.private.json):
0 of 1820366 inline native creature key arrays hold coincident timestamps;
converted models had 2244 (Source keys outside the animation window clamped
onto its edge, or authored step pairs). Native interpolation divides by the
key interval (FLT_DIVIDE_BY_ZERO 0x141df6184, kodorider Stand keys
2667/2667). A run on the window start keeps its last key (nearest the
window), a run on the end its first; an inner step pair keeps both values
one millisecond apart when the next key leaves room.
"""
keep, out, i, n = [], [], 0, len(times)
while i < n:
j = i
while j + 1 < n and times[j + 1] == times[i]:
j += 1
t = times[i]
if j == i or (t and t >= duration):
keep.append(i); out.append(t)
elif not t:
keep.append(j); out.append(t)
else:
keep.append(i); out.append(t)
if (times[j + 1] if j + 1 < n else duration) > t + 1:
keep.append(j); out.append(t + 1)
i = j + 1
return keep, out
def dedupe_track_keys(raw):
"""Remove coincident key timestamps from inline native tracks, in place."""
base, size = _md20_span(raw)
output = bytearray(raw); table = sequence_table(raw)
gcount, goff = struct.unpack_from('<II', raw, base + 20)
globals_ = struct.unpack_from('<%dI' % gcount, raw, base + goff)
arrays = removed = 0; done = {}
for header, record, tracks, events in _TRACKS:
if events:
continue
count, offset = struct.unpack_from('<II', raw, base + header)
for item in range(count):
for track, stride in zip(tracks, _TRACK_STRIDES[header]):
at = base + offset + record * item + track
gid = struct.unpack_from('<h', raw, at + 2)[0]
nt, ot, nv, ov = struct.unpack_from('<4I', raw, at + 4)
if nt != nv or ot + 8 * nt > size or ov + 8 * nv > size:
raise ValueError('Track slot tables differ')
for slot in range(nt):
k, ko = struct.unpack_from('<II', raw, base + ot + 8 * slot)
kv, vo = struct.unpack_from('<II', raw, base + ov + 8 * slot)
if k < 2:
continue
if gid >= 0:
if gid >= gcount:
raise ValueError('Track global sequence not present')
duration = globals_[gid]
elif slot < len(table):
if table[slot]['flags'] & ALIAS or not table[slot]['flags'] & 0x20:
continue # keys of the alias target / external .anim
duration = table[slot]['duration']
else:
continue
if kv != k or ko + 4 * k > size or vo + stride * k > size:
raise ValueError('Track key extent')
times = struct.unpack_from('<%dI' % k, raw, base + ko)
keep, new = distinct_key_times(times, duration)
if len(keep) == k:
continue
if done.setdefault((ko, vo), (k, stride)) != (k, stride):
raise ValueError('Shared key array with differing layout')
struct.pack_into('<%dI' % len(new), output, base + ko, *new)
values = b''.join(raw[base + vo + stride * i:base + vo + stride * (i + 1)] for i in keep)
output[base + vo:base + vo + len(values)] = values
struct.pack_into('<I', output, base + ot + 8 * slot, len(keep))
struct.pack_into('<I', output, base + ov + 8 * slot, len(keep))
arrays += 1; removed += k - len(keep)
return bytes(output), dict(key_arrays=arrays, keys_removed=removed)
def stand_source_index(table):
ids = [s['animation'] for s in table]
for animation in STAND_SOURCE_PRIORITY:
if animation in ids:
return ids.index(animation)
return 0
def insert_stand(raw):
"""Add a native-style aliased Stand (animation 0) to a model that has none."""
from m2_track_convert import duplicate_native_sequence_slot
from m2_sequence_hash import native_sequence_hash
table = sequence_table(raw)
if any(s['animation'] == 0 for s in table):
return raw, dict(changed=False)
if not table:
raise ValueError('Model without sequences; Stand source held')
base, size = _md20_span(raw)
body = bytearray(raw[base:base + size])
if struct.unpack_from('<I', body, 4)[0] not in (272, 274):
raise ValueError('Native 272/274 model body required')
for header in (272, 288):
if struct.unpack_from('<I', body, header)[0]:
raise ValueError('Camera/ribbon tracks need a reviewed Stand slot')
count = len(table); k = stand_source_index(table); source = table[k]
if source['flags'] & ALIAS or not source['flags'] & 0x20:
raise ValueError('Inline non-alias Stand source required')
offset = struct.unpack_from('<I', body, 32)[0]
records = bytearray(body[offset:offset + 64 * count])
stand = bytearray(records[64 * k:64 * k + 64])
struct.pack_into('<HH', stand, 0, 0, 0)
struct.pack_into('<I', stand, 12, source['flags'] & ~(0x01 | ALIAS))
struct.pack_into('<hH', stand, 60, -1, k)
struct.pack_into('<I', records, 64 * k + 12, source['flags'] | ALIAS)
struct.pack_into('<H', records, 64 * k + 62, count)
def append(data):
body.extend(bytes((-len(body)) % 16)); at = len(body); body.extend(data); return at
struct.pack_into('<II', body, 28, count + 1, append(bytes(records) + bytes(stand)))
globals_count = struct.unpack_from('<I', body, 20)[0]; tracks = 0
for header, stride, positions, time_only in _TRACKS + _STAND_EXTRA_TRACKS:
n, at = struct.unpack_from('<II', body, header)
for i in range(n):
for rel in positions:
tracks += duplicate_native_sequence_slot(body, at + i * stride + rel, count, k, append,
global_sequence_count=globals_count,
timestamps_only=time_only)['changed']
# This is a native animation-ID hash, not a direct ID-indexed array.
# Adding Stand can fill a formerly valid two-slot hash; slot zero can also
# legitimately hold another animation. Rebuild after all appended tracks
# using the pinned reader's probe order and a terminating empty slot.
body, _ = native_sequence_hash(body)
if base:
out = raw[:base - 4] + struct.pack('<I', len(body)) + bytes(body) + raw[base + size:]
else:
out = bytes(body)
return out, dict(changed=True, stand_index=count, aliased_source_index=k,
aliased_animation=source['animation'], extended_tracks=tracks)