223 lines
14 KiB
Python
223 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Verified M2 track component for the shared equipment conversion pipeline.
|
|
|
|
Source256 flat/range tracks -> native array-of-array tracks. Not a complete
|
|
model converter or installer. The paired ZG shield confirms inclusive bone
|
|
range ends and bit-identical scale timestamps/keys; do not apply this contract
|
|
to events, whose distinct range/timing structures need separate handling.
|
|
"""
|
|
import math
|
|
import struct
|
|
|
|
|
|
def duplicate_native_sequence_slot(body, at, sequence_count, source_index,
|
|
append, *, global_sequence_count=0,
|
|
timestamps_only=False):
|
|
"""Reuse an existing inline curve for a materialized playable default.
|
|
|
|
Only descriptor arrays grow. Global-clock tracks and empty tracks remain
|
|
unchanged; no timestamp or key is generated, interpolated, or reencoded.
|
|
"""
|
|
width = 12 if timestamps_only else 20
|
|
if not isinstance(body, bytearray) or not 304 <= at <= len(body)-width:
|
|
raise ValueError('Bounded native inline track header required')
|
|
interpolation, global_id, count, offset = struct.unpack_from('<HhII', body, at)
|
|
if interpolation not in (0, 1) or global_id < -1 or global_id >= global_sequence_count:
|
|
raise ValueError('Unreviewed native inline track mode')
|
|
pairs = [(count, offset)]
|
|
if not timestamps_only:
|
|
pairs.append(struct.unpack_from('<II', body, at+12))
|
|
if pairs[0][0] != pairs[1][0]:
|
|
raise ValueError('Native time/key sequence counts differ')
|
|
audit = dict(header_offset=at, timestamps_only=timestamps_only,
|
|
global_sequence=global_id, source_slot=source_index,
|
|
timestamp_and_key_payloads_preserved=True, changed=False)
|
|
if global_id >= 0 or not count:
|
|
return audit
|
|
if not 0 <= source_index < sequence_count == count:
|
|
raise ValueError('Complete existing per-sequence descriptor arrays required')
|
|
for index, (n, off) in enumerate(pairs):
|
|
if off < 304 or off+n*8 > len(body):
|
|
raise ValueError('Native sequence descriptor extent')
|
|
descriptors = bytes(body[off:off+n*8])
|
|
extra = descriptors[source_index*8:(source_index+1)*8]
|
|
new_offset = append(descriptors+extra)
|
|
struct.pack_into('<II', body, at+4+index*8, n+1, new_offset)
|
|
audit.update(changed=True, old_sequence_slots=count, new_sequence_slots=count+1)
|
|
return audit
|
|
|
|
|
|
def _read(raw,at,count,stride):
|
|
if type(at)is not int or type(count)is not int or not 0<=count<=100000 or (count and (at<324 or at>len(raw)or count>(len(raw)-at)//stride)):
|
|
raise ValueError('Legacy track extent bound')
|
|
return raw[at:at+count*stride] if count else b''
|
|
|
|
|
|
def convert_track(raw,at,kind,animation_windows,output,*,global_sequence_count=0,downgrade_untangented_hermite=False,resample_step_visibility=False,editor_preview_resample_pre_window=False):
|
|
"""Append native payload arrays and return its20-byte track header + audit.
|
|
|
|
Source non-global key timestamps are in the supplied animation windows;
|
|
subtract each actual start. Global-sequence timestamps stay global. Extra
|
|
trailing(0,0) default ranges are retained in the audit, never mistaken for
|
|
an additional animation. Unsupported interpolation is rejected explicitly.
|
|
All offsets are relative to the caller's MD20 body, including output bytes.
|
|
"""
|
|
# float32/uint16 are the scalar ribbon tracks (height above/below, texture slot); same range/timestamp contract.
|
|
strides={'vec3':12,'quaternion':16,'quat32':16,'fixed16':2,'visibility':1,'float32':4,'uint16':2}
|
|
if (kind not in strides or not isinstance(raw,bytes)or not 324<=len(raw)<=67108864 or
|
|
raw[:4]!=b'MD20' or struct.unpack_from('<I',raw,4)[0] not in (256,257)):
|
|
raise ValueError('Reviewed source256/257 track/key kind required')
|
|
if not isinstance(output,bytearray)or not 304<=len(output)<=67108864:
|
|
raise ValueError('Bounded native MD20 output buffer required')
|
|
if not isinstance(animation_windows,list)or not 1<=len(animation_windows)<=4096:
|
|
raise ValueError('Actual source animation windows required')
|
|
if any(not isinstance(w,tuple)or len(w)!=2 or any(type(v)is not int or not 0<=v<=0xffffffff for v in w)or w[1]<w[0]for w in animation_windows):
|
|
raise ValueError('Invalid source animation window')
|
|
if type(global_sequence_count)is not int or not 0<=global_sequence_count<=4096:
|
|
raise ValueError('Global sequence count bound')
|
|
header=_read(raw,at,1,28)
|
|
interpolation,global_id,nr,ro,nt,to,nk,ko=struct.unpack('<Hh6I',header)
|
|
hermite_downgraded=False
|
|
if interpolation in(2,3):
|
|
# Source256 Hermite/Bezier tracks in this content carry no tangent
|
|
# arrays: the key array holds exactly one value per timestamp (nk==nt),
|
|
# so there is nothing to interpolate as a spline. Represent the same
|
|
# keyframes with native linear interpolation when opted in; a track
|
|
# that actually stores 3 values per key still needs a real spline
|
|
# conversion and stays refused.
|
|
if not(downgrade_untangented_hermite and nk==nt):
|
|
raise ValueError('Hermite/Bezier track requires a separate key conversion')
|
|
interpolation=1;hermite_downgraded=True
|
|
elif interpolation not in(0,1):
|
|
raise ValueError('Reviewed source track interpolation required')
|
|
if global_id < -1 or global_id>=global_sequence_count:
|
|
raise ValueError('Track global sequence not present')
|
|
ranges=list(struct.iter_unpack('<II',_read(raw,ro,nr,8)))
|
|
times=list(struct.unpack('<'+'I'*nt,_read(raw,to,nt,4)))
|
|
keys=_read(raw,ko,nk,strides[kind])
|
|
source_keys=keys
|
|
if nt!=nk:raise ValueError('Timestamp/key count mismatch')
|
|
audit=dict(kind=kind,source_range_count=nr,source_key_count=nk,
|
|
global_sequence=global_id,unused_default_ranges=[],
|
|
quaternion_max_quantization_error=0.0,complete_model_converted=False,hermite_downgraded_to_linear=hermite_downgraded)
|
|
if not nt:
|
|
if nr:raise ValueError('Nonempty ranges without track keys')
|
|
return struct.pack('<Hh4I',interpolation,global_id,0,0,0,0),audit
|
|
if kind in('vec3','quaternion','quat32','float32'):
|
|
floats=struct.unpack('<'+'f'*(len(keys)//4),keys)
|
|
if not all(math.isfinite(v)for v in floats):raise ValueError('Nonfinite legacy track key')
|
|
if kind=='quaternion':
|
|
encoded=[];errors=[]
|
|
for q in floats:
|
|
if not -1<=q<=1:raise ValueError('Quaternion component outside representable range')
|
|
value=round(q*32767-32768 if q>=0 else q*32767+32767)
|
|
if not -32768<=value<=32767:raise ValueError('Compressed quaternion range')
|
|
decoded=(value+32768)/32767 if value<0 else(value-32767)/32767
|
|
encoded.append(value);errors.append(abs(q-decoded))
|
|
keys=struct.pack('<'+'h'*len(encoded),*encoded)
|
|
audit['quaternion_max_quantization_error']=max(errors,default=0)
|
|
elif kind=='visibility' and any(v not in(0,1)for v in keys):
|
|
raise ValueError('Unreviewed visibility key')
|
|
stride=8 if kind=='quaternion'else strides[kind]
|
|
if resample_step_visibility and kind=='visibility' and interpolation==0 and global_id<0:
|
|
# Step on/off track (particle enabled, ribbon visibility). Source ranges here are inclusive with one guard key
|
|
# in the next animation, or absent. A step value at time t is the last key <= t (first key before any key),
|
|
# so each window is exact as: value held at its start at local 0, then the keys strictly inside it.
|
|
if any(a>b for a,b in zip(times,times[1:])):raise ValueError('Unordered legacy timestamps')
|
|
seqs=[]
|
|
for ws,we in animation_windows:
|
|
held=[k for k,v in enumerate(times) if v<=ws]; k0=held[-1] if held else 0
|
|
inside=[k for k,v in enumerate(times) if ws<v<=we]
|
|
idx=[k0]+inside
|
|
seqs.append((struct.pack('<'+'I'*len(idx),0,*(times[k]-ws for k in inside)),b''.join(keys[k:k+1] for k in idx)))
|
|
audit['step_visibility_resampled']=True
|
|
return _emit(seqs,interpolation,global_id,output,stride,audit)
|
|
# One key and no ranges: FindKey falls back to the whole one-key array, so the value is constant at any time
|
|
# (the Octo BE scrying orb colour has its key at t=333). Same native form as the t=0 case.
|
|
static_default=(global_id==-1 and nr==0 and nt==1)
|
|
if global_id>=0:
|
|
if ranges:raise ValueError('Global track with per-animation ranges unreviewed')
|
|
spans=[(0,nt-1)];starts=[0]
|
|
elif static_default:
|
|
# Original Source5875 FindKey (0x713d50) falls back to the whole key
|
|
# array when this sequence has no range. With one key it returns that
|
|
# same index twice before reading time, including skeletal tracks.
|
|
# Express the same value at local time0 in every native sequence;
|
|
# retain the strict gate for multi-key and nonzero-time tracks.
|
|
spans=[(0,0)]*len(animation_windows);starts=[0]*len(animation_windows)
|
|
audit['static_default_animation_count']=len(animation_windows)
|
|
else:
|
|
if nr>len(animation_windows) and all(r==(0,0) for r in ranges[len(animation_windows):]):
|
|
# Trailing (0,0) ranges past the last animation are never selected (torch/teleporter carry 2 extra).
|
|
audit['unused_default_ranges']=[list(r) for r in ranges[len(animation_windows):]];del ranges[len(animation_windows):]
|
|
if len(ranges)!=len(animation_windows):raise ValueError('Per-animation track range count differs')
|
|
spans=ranges;starts=[w[0]for w in animation_windows]
|
|
seqs=[]
|
|
for i,((begin,end),start)in enumerate(zip(spans,starts)):
|
|
# Inclusive end is established by the actual paired3-key shield track.
|
|
if not 0<=begin<=end<nt:raise ValueError('Invalid inclusive legacy track range')
|
|
selected=times[begin:end+1]
|
|
if any(a>b for a,b in zip(selected,selected[1:])):raise ValueError('Unordered legacy timestamps')
|
|
if global_id<0 and not static_default and any(not animation_windows[i][0]<=v<=animation_windows[i][1]for v in selected):
|
|
window_end=animation_windows[i][1]
|
|
if (editor_preview_resample_pre_window and kind in ('vec3','quaternion') and interpolation==1 and
|
|
len(selected)>=2 and selected[0]<=start<=window_end<=selected[-1] and
|
|
all(a<b for a,b in zip(selected,selected[1:]))):
|
|
components=3 if kind=='vec3' else 4
|
|
points=sorted({start,window_end,*[v for v in selected if start<v<window_end]})
|
|
values=[]
|
|
for t in points:
|
|
left_index=max(j for j,v in enumerate(selected) if v<=t)
|
|
right_index=min(left_index+1,len(selected)-1)
|
|
fraction=(t-selected[left_index])/(selected[right_index]-selected[left_index]) if right_index!=left_index else 0
|
|
left=struct.unpack_from('<'+'f'*components,source_keys,(begin+left_index)*components*4)
|
|
right=struct.unpack_from('<'+'f'*components,source_keys,(begin+right_index)*components*4)
|
|
blended=[a+(b-a)*fraction for a,b in zip(left,right)]
|
|
if kind=='quaternion':
|
|
length=math.sqrt(sum(v*v for v in blended))
|
|
if not length:raise ValueError('Zero editor preview quaternion')
|
|
blended=[v/length for v in blended]
|
|
values.append(struct.pack('<4h',*(round(v*32767-32768 if v>=0 else v*32767+32767) for v in blended)))
|
|
else:values.append(struct.pack('<3f',*blended))
|
|
seqs.append((struct.pack('<'+'I'*len(points),*(v-start for v in points)),b''.join(values)))
|
|
audit.setdefault('editor_preview_resampled',[]).append(dict(animation=i,source_window=[start,window_end],
|
|
source_span=[selected[0],selected[-1]],new_keys=len(points)))
|
|
continue
|
|
# Original Source5875 FindKey chooses bracketing keys without a
|
|
# sequence-window clamp. Identical keys covering the whole window
|
|
# evaluate to the same value; at an exact final endpoint the next
|
|
# global key has factor0. Require a strictly later guard to avoid
|
|
# an unproved zero-denominator case. Never interpolate new values.
|
|
key_stride=strides[kind]
|
|
first=source_keys[begin*key_stride:(begin+1)*key_stride]
|
|
same=all(source_keys[k*key_stride:(k+1)*key_stride]==first for k in range(begin,end+1))
|
|
window=animation_windows[i]
|
|
if (kind in('vec3','quaternion')and same and selected[0]<=window[0]<=window[1]<=selected[-1]and
|
|
all(a<b for a,b in zip(selected,selected[1:]))and
|
|
(end+1==nt or times[end+1]>selected[-1])):
|
|
seqs.append((bytes(4),keys[begin*stride:(begin+1)*stride]))
|
|
audit.setdefault('constant_bracket_sequences',[]).append(dict(
|
|
animation=i,source_inclusive_range=[begin,end],source_window=list(window),
|
|
source_bracket_times=[selected[0],selected[-1]],native_constant_time=0,
|
|
source_keys_byte_identical=True,values_resampled=False))
|
|
continue
|
|
raise ValueError('Track timestamps outside actual source animation window')
|
|
seqs.append((struct.pack('<'+'I'*len(selected),*(v-start for v in selected)),keys[begin*stride:(end+1)*stride]))
|
|
return _emit(seqs,interpolation,global_id,output,stride,audit)
|
|
|
|
|
|
def _emit(seqs,interpolation,global_id,output,stride,audit):
|
|
# Build privately first: a rejected input must not partially mutate caller.
|
|
staged=bytearray();base=len(output)
|
|
def append(data):
|
|
staged.extend(bytes((-len(staged)-base)%4));offset=base+len(staged);staged.extend(data);return offset
|
|
ts=[];ks=[]
|
|
for timestamps,values in seqs:
|
|
ts.append((len(timestamps)//4,append(timestamps)))
|
|
ks.append((len(values)//stride,append(values)))
|
|
ts_offset=append(b''.join(struct.pack('<II',*a)for a in ts))
|
|
ks_offset=append(b''.join(struct.pack('<II',*a)for a in ks))
|
|
if len(output)+len(staged)>67108864:raise ValueError('Native track output bound')
|
|
output.extend(staged);audit['native_sequence_count']=len(seqs)
|
|
return struct.pack('<Hh4I',interpolation,global_id,len(ts),ts_offset,len(ks),ks_offset),audit
|