296 lines
13 KiB
Python
296 lines
13 KiB
Python
"""Validate animation references in an inventory of already selected, exported model files."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from collections import Counter
|
|
from pathlib import Path
|
|
import struct
|
|
|
|
from m2_sequence_contract import ALIAS, sequence_records, sequence_table
|
|
|
|
|
|
# Native formats written by m2_equipment_convert.py. These components select
|
|
# the active sequence through their track arrays. Their bone/texture IDs and
|
|
# particle lifetime tables do not index the model's sequence table.
|
|
COMPONENTS = (
|
|
('attachment', 240, 40, (('visibility', 20),)),
|
|
('ribbon', 288, 176, (('color', 36), ('alpha', 56), ('height_above', 76),
|
|
('height_below', 96), ('texture_slot', 132), ('visibility', 152))),
|
|
('particle', 296, 492, (('speed', 52), ('variation', 72), ('vertical', 92),
|
|
('horizontal', 112), ('gravity', 132), ('lifespan', 152),
|
|
('rate', 176), ('length', 200), ('width', 220),
|
|
('source_z', 240), ('enabled', 456))),
|
|
)
|
|
|
|
|
|
def array(body, field, stride):
|
|
count, start = struct.unpack_from('<II', body, field)
|
|
if count and (start > len(body) or count > (len(body) - start) // stride):
|
|
raise ValueError(f'Array at header field {field} exceeds model body')
|
|
return count, start
|
|
|
|
|
|
def model_body(raw):
|
|
if raw[:4] == b'MD20':
|
|
return memoryview(raw), False
|
|
at = 0
|
|
body = None
|
|
external = False
|
|
while at < len(raw):
|
|
tag, size = struct.unpack_from('<4sI', raw, at)
|
|
at += 8
|
|
if at + size > len(raw):
|
|
raise ValueError('Incomplete model chunk')
|
|
if tag == b'MD21':
|
|
if body is not None:
|
|
raise ValueError('Multiple model bodies')
|
|
body = memoryview(raw)[at:at + size]
|
|
if tag == b'SKID':
|
|
external = True
|
|
at += size
|
|
if body is None:
|
|
raise ValueError('Model body missing')
|
|
return body, external
|
|
|
|
|
|
def check_track(body, at, field, sequences, clocks, observations, issues):
|
|
_, clock = struct.unpack_from('<Hh', body, at)
|
|
if clock < -1 or clock >= clocks:
|
|
issues.append(dict(field=field + '.globalSequence', value=clock, global_sequences=clocks))
|
|
return
|
|
for kind, delta in (('timestamps', 4), ('values', 12)):
|
|
count, pos = array(body, at + delta, 8)
|
|
if clock != -1 or count <= sequences:
|
|
continue
|
|
# A track slot is implicit. Extra nonempty slots are unaddressable by
|
|
# those sequences; this alone cannot establish a bad runtime selection.
|
|
for index in range(sequences, count):
|
|
keys, = struct.unpack_from('<I', body, pos + index * 8)
|
|
if keys:
|
|
observations.append(dict(field=f'{field}.{kind}', unused_slot=index, keys=keys))
|
|
|
|
|
|
def cycles(table, field):
|
|
visited = set()
|
|
found = []
|
|
for start in range(len(table)):
|
|
order = {}
|
|
at = start
|
|
while 0 <= at < len(table) and at not in visited:
|
|
if field == 'alias_next' and not table[at]['flags'] & ALIAS:
|
|
break
|
|
if at in order:
|
|
found.append(list(order)[order[at]:])
|
|
break
|
|
order[at] = len(order)
|
|
at = table[at][field]
|
|
visited.update(order)
|
|
return found
|
|
|
|
|
|
class NativeSequenceLookup:
|
|
"""Pinned 70334 RVA1df4d40: empty-table linear fallback, otherwise
|
|
cumulative-square probes (1df4f7e..1df5040), with uint32 addition wrap.
|
|
A repeated slot alone is NOT a cycle: the next step is reader state too.
|
|
Budget exhaustion is unknown, never proof of a client loop.
|
|
"""
|
|
def __init__(self, ids, slots):
|
|
self.ids, self.slots = ids, slots
|
|
self.first = {}
|
|
for index, ident in enumerate(ids):
|
|
self.first.setdefault(ident, index)
|
|
self.closed = bool(slots) and all(index != 0xffff and index < len(ids) for index in slots)
|
|
self.represented = {ids[index] for index in slots if index != 0xffff and index < len(ids)}
|
|
|
|
def query(self, animation, probe_budget=4096):
|
|
if probe_budget < 0:
|
|
raise ValueError('Negative lookup analysis budget')
|
|
if not self.slots:
|
|
index = self.first.get(animation, 0xffff)
|
|
return dict(status='found' if index != 0xffff else 'unreachable',
|
|
index=index, probes=0, reason='empty_hash_linear_search')
|
|
if self.closed and animation not in self.represented:
|
|
# Every possible slot is valid, nonempty, and the wrong ID: there
|
|
# is no return/assert branch regardless of the probe trajectory.
|
|
return dict(status='nonterminating', probes=0,
|
|
reason='no_terminal_slot_for_query')
|
|
slot, step, seen = animation % len(self.slots), 1, set()
|
|
for probe in range(probe_budget):
|
|
state = (slot, step)
|
|
if state in seen:
|
|
return dict(status='nonterminating', probes=probe,
|
|
reason='repeated_complete_reader_state')
|
|
seen.add(state)
|
|
index = self.slots[slot]
|
|
if index == 0xffff:
|
|
return dict(status='unreachable', index=index, probes=probe + 1,
|
|
reason='empty_slot_before_match')
|
|
if index >= len(self.ids):
|
|
return dict(status='out_of_range', index=index, probes=probe + 1,
|
|
reason='reader_sequence_index_assertion')
|
|
if self.ids[index] == animation:
|
|
return dict(status='found', index=index, probes=probe + 1)
|
|
slot = ((slot + step * step) & 0xffffffff) % len(self.slots)
|
|
step = (step + 1) & 0xffffffff
|
|
return dict(status='hold', probes=probe_budget, reason='probe_budget_exhausted')
|
|
|
|
|
|
def check_reachability(table, slots, issues, observations, total_budget=262144):
|
|
reader = NativeSequenceLookup([row['animation'] for row in table], slots)
|
|
# Only authored IDs are required. No Stand requirement is invented.
|
|
for animation in reader.first:
|
|
result = reader.query(animation, probe_budget=min(4096, total_budget))
|
|
total_budget -= result['probes']
|
|
if result['status'] == 'found':
|
|
continue
|
|
report = dict(field='sequence_lookup_reachability', animation=animation, **result)
|
|
(observations if result['status'] == 'hold' else issues).append(report)
|
|
|
|
|
|
def check_sequences(body, lookup_at, table, issues, observations):
|
|
count = len(table)
|
|
for row in table:
|
|
for field, minimum in (('variation_next', -1), ('alias_next', 0)):
|
|
value = row[field]
|
|
if minimum <= value < count:
|
|
continue
|
|
report = dict(field=field, sequence=row['index'], value=value)
|
|
# Non-alias records can have an inactive backlink. It does not
|
|
# become a traversed alias just because its numeric value is large.
|
|
if field == 'alias_next' and not row['flags'] & ALIAS:
|
|
observations.append(report)
|
|
else:
|
|
issues.append(report)
|
|
for field in ('variation_next', 'alias_next'):
|
|
issues.extend(dict(field=field, cycle=cycle) for cycle in cycles(table, field))
|
|
slots, pos = array(body, lookup_at, 2)
|
|
entries = 0
|
|
lookup = []
|
|
for slot in range(slots):
|
|
index, = struct.unpack_from('<H', body, pos + slot * 2)
|
|
lookup.append(index)
|
|
if index != 0xffff:
|
|
entries += 1
|
|
if index >= count:
|
|
issues.append(dict(field='sequence_lookup', slot=slot, value=index))
|
|
check_reachability(table, lookup, issues, observations)
|
|
return entries
|
|
|
|
|
|
def inspect_model(raw):
|
|
body, external = model_body(raw)
|
|
if body[:4] != b'MD20' or len(body) < 304:
|
|
raise ValueError('Missing modern model header')
|
|
version, = struct.unpack_from('<I', body, 4)
|
|
if version not in (272, 273, 274):
|
|
raise ValueError(f'Unsupported model version {version}')
|
|
if external:
|
|
raise ValueError('External skeleton requires its own sequence authority')
|
|
table = sequence_table(body)
|
|
count = len(table)
|
|
clock_count, _ = array(body, 20, 4)
|
|
issues, observations = [], []
|
|
entries = check_sequences(body, 36, table, issues, observations)
|
|
components = {}
|
|
for name, header, stride, tracks in COMPONENTS:
|
|
total, start = array(body, header, stride)
|
|
components[name] = total
|
|
for i in range(total):
|
|
for label, offset in tracks:
|
|
check_track(body, start + i * stride + offset, f'{name}[{i}].{label}',
|
|
count, clock_count, observations, issues)
|
|
return dict(version=version, sequences=count, global_sequences=clock_count,
|
|
lookup_entries=entries, components=components, issues=issues, observations=observations,
|
|
lookup_reachability_complete=not any(x.get('status') == 'hold' for x in observations))
|
|
|
|
|
|
def inspect_skeleton(raw):
|
|
chunks = {}
|
|
at = 0
|
|
while at < len(raw):
|
|
tag, size = struct.unpack_from('<4sI', raw, at)
|
|
at += 8
|
|
if at + size > len(raw) or tag in chunks:
|
|
raise ValueError('Invalid skeleton chunk')
|
|
chunks[tag] = memoryview(raw)[at:at + size]
|
|
at += size
|
|
body = chunks[b'SKS1']
|
|
clocks, _ = array(body, 0, 4)
|
|
count, start = array(body, 8, 64)
|
|
table = sequence_records(body, start, count)
|
|
issues, observations = [], []
|
|
entries = check_sequences(body, 16, table, issues, observations)
|
|
attachments = 0
|
|
if b'SKA1' in chunks:
|
|
tracks = chunks[b'SKA1']
|
|
attachments, pos = array(tracks, 0, 40)
|
|
for i in range(attachments):
|
|
check_track(tracks, pos + 40 * i + 20, f'attachment[{i}].visibility',
|
|
count, clocks, observations, issues)
|
|
parent = struct.unpack_from('<I', chunks[b'SKPD'], 8)[0] if b'SKPD' in chunks else None
|
|
return dict(sequences=count, global_sequences=clocks, lookup_entries=entries, attachments=attachments,
|
|
issues=issues, observations=observations, parent_fdid=parent,
|
|
lookup_reachability_complete=not any(x.get('status') == 'hold' for x in observations))
|
|
|
|
|
|
def read_selected(root, row):
|
|
raw = (root / row['file']).read_bytes()
|
|
if hashlib.sha256(raw).hexdigest() != row['sha256'] or hashlib.md5(raw).hexdigest() != row['ckey'].lower():
|
|
raise ValueError(f'Member {row["fdid"]} differs from its selected inventory')
|
|
return raw
|
|
|
|
|
|
def skeleton_survey(manifest_path):
|
|
manifest = json.loads(manifest_path.read_bytes())
|
|
results = {}
|
|
for row in manifest['skeletons']:
|
|
result = inspect_skeleton(read_selected(manifest_path.parent, row))
|
|
if (result['parent_fdid'] or None) != row.get('parent_fdid'):
|
|
raise ValueError('Skeleton parent disagrees with inventory')
|
|
results[row['fdid']] = result
|
|
return dict(build=manifest['build'], skeletons=results, unavailable=manifest['held'],
|
|
scope='Local SKS1 and SKA1 indices in each available skeleton. Inherited composition requires parent resolution and is outside this walk.')
|
|
|
|
|
|
def survey(manifest_path):
|
|
manifest = json.loads(manifest_path.read_bytes())
|
|
by_id = {}
|
|
totals = Counter()
|
|
for row in manifest['models']:
|
|
fdid = int(row['fdid'])
|
|
if fdid in by_id:
|
|
raise ValueError(f'Duplicate model {fdid}')
|
|
raw = read_selected(manifest_path.parent, row)
|
|
result = dict(ckey=row['ckey'], sha256=row['sha256'], roles=row['roles'])
|
|
try:
|
|
data = inspect_model(raw)
|
|
result.update(data)
|
|
totals['models_walked'] += 1
|
|
totals['models_with_reference_issues'] += bool(data['issues'])
|
|
totals['models_with_observations'] += bool(data['observations'])
|
|
totals['models_with_lookup_holds'] += not data['lookup_reachability_complete']
|
|
totals['sequence_records'] += data['sequences']
|
|
totals['populated_lookup_entries'] += data['lookup_entries']
|
|
totals.update(data['components'])
|
|
except (ValueError, struct.error) as exc:
|
|
result['held'] = str(exc)
|
|
totals['models_held'] += 1
|
|
by_id[fdid] = result
|
|
return dict(inventory_sha256=hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
|
|
totals=dict(totals), models=by_id)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('manifest', type=Path)
|
|
parser.add_argument('output', type=Path)
|
|
parser.add_argument('--skeletons', action='store_true', help='Read a first-party selected skeleton inventory')
|
|
args = parser.parse_args()
|
|
result = skeleton_survey(args.manifest) if args.skeletons else survey(args.manifest)
|
|
args.output.write_text(json.dumps(result, sort_keys=True, separators=(',', ':')) + '\n')
|
|
print(json.dumps(result.get('totals', {'skeletons': len(result.get('skeletons', {}))}), sort_keys=True))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|