"""Synthetic tests for tools/anim_clips.py. python -I tests/test_anim_clips.py Every byte here is built by the test: a fake RPF9 data area holding clip-dictionary resources made by the encoder below (dictionary root, clip, animation pack, animation, sequences and every decoded channel type, including a type-10 channel). No game file or game asset name is used. """ import collections import json import math import os import struct import subprocess import sys import tempfile import unittest import zlib ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOL = os.path.join(ROOT, "tools", "anim_clips.py") sys.path.insert(0, os.path.join(ROOT, "tools")) import anim_clips # noqa: E402 from anim_index import joaat32 # noqa: E402 SYSTEM = 0x50000000 BONEROTATION = joaat32("bonerotation") BONETRANSLATION = joaat32("bonetranslation") GENERICCONTROL = joaat32("genericcontrol") # ---------------------------------------------------------------- encoders class Bits: """LSB-first bit writer.""" def __init__(self): self.value, self.n = 0, 0 def put(self, x, k): assert 0 <= x < (1 << k) or k == 0 and x == 0 self.value |= x << self.n self.n += k def bytes(self, length=None): length = (self.n + 7) // 8 if length is None else length return self.value.to_bytes(length, "little") def zz(v): return 2 * v if v >= 0 else -2 * v - 1 def encode_delta2(ints, quantum, offset): """Type-10 channel for non-negative integers `ints` (value = int * quantum + offset).""" nf = len(ints) nc = (nf + 63) // 64 starts = [ints[64 * c] for c in range(nc)] raw = [] for c in range(nc): v = 0 for j in range(64): f = 64 * c + j + 1 if f >= nf: break step = ints[f] - ints[f - 1] raw.append(zz(step - v)) v = step assert len(raw) == nf - 1 raw += [0] * ((-len(raw)) % 8) widths = [max(x.bit_length() for x in raw[g:g + 8]) for g in range(0, len(raw), 8)] total = sum(widths) c3 = (total + 31) // 32 positions, acc = [], 0 for c in range(nc): positions.append(acc) acc += sum(widths[8 * c:8 * c + 8]) c1 = max(1, max(positions).bit_length()) c2 = max(1, max(starts).bit_length()) front = Bits() for p in positions: front.put(p, c1) for s in starts: front.put(s, c2) for k in widths: front.put(0, k) front.put(1, 1) lanes = [Bits() for _ in range(8)] for g, k in enumerate(widths): for j in range(8): lanes[j].put(raw[8 * g + j], k) front_bytes = front.bytes(((front.n + 31) // 32) * 4) words = [] lane_words = [lanes[j].value.to_bytes(4 * c3, "little") for j in range(8)] for w in range(c3): for j in range(8): words.append(lane_words[j][4 * w:4 * w + 4]) blob = front_bytes + b"".join(words) head = struct.pack("> 7) & 1, control h & 0x7F return obj def motion_matcher(p, name, refs=True, pose_rows=True): """A `.motionmatcher` with two records: record 0 is the dictionary's own `.clip` (hash 1), record 1 a clip that is not in the archive. Its own key is (3, joaat32(name)).""" m = p.alloc(bytes(0x190)) p.ptr(m + 0x20, features(p, pose_rows)) # the feature object p.b[m + 0x28:m + 0x38] = bytes(range(0x80, 0x90)) # 16-byte id; +0x30 is not a pointer p.string(m + 0x38, "pack:/one.motionmatcher") records = struct.pack(" child k motion = self.motion(children=[(1, 2), (3, 4)], axis=([joaat32("speed")], [(0, 0.0), (1, 1.0)], 0.0, 1.0), sample_lists=[[(0, 1.0, 1.0), (1, 1.0, 1.0)], [(1, 1.0, 1.0)]]) stats = anim_clips.new_stats() anim_clips.count_motion_blend(motion, stats) self.assertEqual((stats["motion_samples:3:sample_k_is_child_k"], stats["motion_samples:3:every_list_one_item"], stats["motion_samples:3:every_child_sampled"]), (0, 0, 1)) def test_malformed_node_keeps_the_time_table(self): times = [(1.5, 1.5, [(0.0, 0.0), (1.5, 1.5)])] motion = self.motion(children=[(1, 2)], times=times, node=(8, [(1, 0, 0)], 1), node_axis_count=0xFFFF) self.assertIsNone(motion["node"]) # the axis array runs past the page self.assertEqual(len(motion["times"]), 1) def test_child_out_of_range_is_counted(self): motion = self.motion(children=[(1, 2)], axis=([joaat32("speed")], [(0, 0.0)], 0.0, 0.0), sample_lists=[[(5, 1.0, 1.0)]]) stats = anim_clips.new_stats() anim_clips.count_motion_blend(motion, stats) self.assertEqual((stats["motion_samples:3:children_in_range"], stats["motion_samples:3:every_child_sampled"]), (0, 0)) def test_multi_axis_nodes(self): for kind, n_axes in ((4, 2), (5, 3), (6, 4), (8, 5)): axes = [(joaat32("speed") if i == 0 else 0xABC0 + i, i, 1) for i in range(n_axes)] lists = [[(i % 2, 1.0, 1.0)] for i in range(4)] motion = self.motion(children=[(1, 2), (3, 4)], node=(kind, axes, 4), sample_lists=lists) k, axis = motion["node"] self.assertEqual((k, axis["names"], axis["slots"], axis["sample_count"]), (kind, [a[0] for a in axes], [(i, 1) for i in range(n_axes)], 4)) self.assertNotIn("samples", axis) stats = anim_clips.new_stats() anim_clips.count_motion_blend(motion, stats) self.assertEqual((stats[f"motion_node_axes:{kind}:{n_axes}"], stats[f"motion_node_axis_name:{kind}:speed"], stats[f"motion_node_axis_name:{kind}:unresolved"], stats[f"motion_samples:{kind}:lists_equal_node_samples"], stats[f"motion_samples:{kind}:every_child_sampled"], stats["motion_axes"]), (1, 1, n_axes - 1, 1, 1, 0)) def test_multi_axis_pairs(self): motion = self.motion(children=[(1, 2)], node=(6, [(1, 0, 0)] * 4, 1), node_pairs=[(0xAA, 0xBB), (0xCC, 0xDD)]) self.assertEqual(motion["node"][1]["pairs"], [(0xAA, 0xBB), (0xCC, 0xDD)]) stats = anim_clips.new_stats() anim_clips.count_motion_blend(motion, stats) self.assertEqual(stats["motion_node_pairs:6:2"], 1) motion = self.motion(children=[(1, 2)], node=(4, [(1, 0, 0)] * 2, 1)) # null +0x20 self.assertIsNone(motion["node"][1]["pairs"]) stats = anim_clips.new_stats() anim_clips.count_motion_blend(motion, stats) self.assertEqual(stats["motion_node_pairs:4:null"], 1) def test_type1_node(self): motion = self.motion(children=[(1, 2)], node=(1, [], 1), sample_lists=[[(0, 1.0, 1.0)]]) self.assertEqual(motion["node"], (1, {"names": [], "slots": [], "sample_count": 1})) stats = anim_clips.new_stats() anim_clips.count_motion_blend(motion, stats) self.assertEqual((stats["motion_node_type:1"], stats["motion_node_axes:1:0"], stats["motion_samples:1:sample_k_is_child_k"]), (1, 1, 1)) def test_sample_lists_of_a_two_node_motion_are_not_counted(self): motion = self.motion(children=[(1, 2)], parameters=2, node=(1, [], 1), sample_lists=[[(0, 1.0, 1.0)]] * 3) self.assertEqual(len(motion["samples"]), 3) stats = anim_clips.new_stats() anim_clips.count_motion_blend(motion, stats) self.assertFalse([k for k in stats if k.startswith("motion_samples:")]) def test_delta2_round_trip(self): for n in (1, 2, 8, 9, 63, 64, 65, 129, 200): ints = [(7 * f * f) % 1000 + 20 * (f % 3) for f in range(n)] blob = encode_delta2(ints, 0.5, -3.0) + bytes(8) stats = anim_clips.new_stats() values, size = anim_clips.decode_delta2(blob, 0, n, stats) self.assertEqual(size, len(blob) - 8) self.assertEqual(values, [x * 0.5 - 3.0 for x in ints], n) self.assertEqual(stats["delta2_boundaries"], (n - 1) // 64) self.assertEqual(stats["delta2_boundaries_closed"], stats["delta2_boundaries"]) def test_tracks(self): anim = self.d["packs"][0]["animations"][0] stats = anim_clips.new_stats() tracks, total = anim_clips.decode_animation(self.s, anim, stats) self.assertEqual(total, NF) self.assertEqual(stats["frames_sum_matches"], 1) for f in (0, 39, 40, 41, NF - 1): x, y, z = X_INTS[f] * 0.002 - 0.05, 0.25, Z_INTS[f] * 0.002 - 0.1 w = math.sqrt(1 - x * x - y * y - z * z) for got, want in zip(tracks[0][f], (x, y, z, w)): self.assertAlmostEqual(got, want, places=5) self.assertEqual(len(tracks[1][f]), 4) for got in tracks[1][f]: self.assertAlmostEqual(got, 0.5, places=6) self.assertEqual(tracks[2][f], (1.0, 2.0, 3.0)) self.assertAlmostEqual(tracks[3][f][0], TABLE[f % 4] * 0.1 + 1.0, places=5) self.assertEqual(tracks[4][f][0], f * 1.5) self.assertEqual(stats["boundary_quaternions"], stats["boundary_quaternions_same_rotation"]) self.assertEqual(stats["boundary_values"], stats["boundary_values_within_1e-3"]) self.assertEqual(stats["channel:10_delta2_float"], 2) self.assertEqual(stats["channel:03_raw_float"], 2) def test_rebuilt_component_goes_to_the_type7_position(self): seq = encode_sequence(1, [(2, 0, 0, 0.1), (2, 0, 1, 0.2), (2, 0, 2, 0.3), (7, 0, 1, None)]) s = anim_clips.System(dictionary("p", [seq], 1, TRACKS[:1])) anim = anim_clips.parse_dictionary(s)["packs"][0]["animations"][0] tracks, _ = anim_clips.decode_animation(s, anim) w = math.sqrt(1 - 0.01 - 0.04 - 0.09) for got, want in zip(tracks[0][0], (0.1, w, 0.2, 0.3)): self.assertAlmostEqual(got, want, places=6) def test_definitions_must_end_at_the_frame_data(self): seq = bytearray(encode_sequence(3, [(2, 0, 0, 1.0), (2, 0, 1, 2.0)])) struct.pack_into("= 16) at the very end of the page so u64(+0x30) fits while d[+0x3F] is OOB. p = Page() pm = p.alloc(bytes(16)) p.b[pm + 8], p.b[pm + 9] = 1, 0 p.ptr(8, pm) p.string(0x38, "trunc@clip") struct.pack_into(" (32 * words) // 1 = 8.5B with self.assertRaisesRegex(anim_clips.DecodeError, "type-5"): anim_clips.decode_sequence(anim_clips.System(bytes(seq)), 0) # Smaller type-5 word count that still overruns frame_offset into frame bits. seq2 = bytearray(encode_sequence(2, [(5, 0, 0, (2, 4, TABLE, 0.1, 1.0, [0, 1]))])) struct.pack_into(" 1 word allocated before frame_offset with self.assertRaisesRegex(anim_clips.DecodeError, "type-5"): anim_clips.decode_sequence(anim_clips.System(bytes(seq2)), 0) # Type-10 word count overrunning frame_offset into frame bits / counts. seq3 = bytearray(encode_sequence(4, [(10, 0, 0, (0.5, 0.0, [1, 2, 3, 4]))])) words = struct.unpack_from(" None: data = bytearray(two_sequence_dictionary("six-pages@dict")) page_map = struct.unpack_from("= 64 for page in pages)) path = os.path.join(self.tmp.name, "six-pages.rpf") root, *_ = write_rpf(path, pages) _, summary = anim_clips.scan(path) self.assertEqual(summary["pages"], {"6": 1}) self.assertEqual(summary["counts"]["animations_decoded"], 1) result = subprocess.run( [sys.executable, "-I", TOOL, path, "--decode", str(root), "--frames", "3"], capture_output=True, text=True, errors="replace", check=False, ) self.assertEqual(result.returncode, 0, result.stderr) animation = json.loads(result.stdout)["packs"][0]["animations"][0] self.assertEqual(animation["decoded_frames"], NF) self.assertEqual(animation["decoded"]["2"], [[1.0, 2.0, 3.0]] * 3) self.assertEqual(animation["decoded"]["4"], [[0.0], [1.5], [3.0]]) def test_decode_page_counts_on_or_across_sixth_page(self): data = bytearray(two_sequence_dictionary()) pm = len(data) data.extend(bytes(96)) struct.pack_into("