"""Synthetic-data tests for tools/anim_glb.py (skinned part + skeleton + clips -> animated GLB). python -I tests/test_anim_glb.py Every byte is built here: a synthetic skeleton drawable, a synthetic skinned part drawable (system and graphics pages) and a synthetic anim.rpf from test_anim_clips' encoders. No game file, value or name is used. """ import json import math import os import struct import subprocess import sys import tempfile import unittest import zlib from unittest.mock import patch ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOL = os.path.join(ROOT, "tools", "anim_glb.py") sys.path.insert(0, os.path.join(ROOT, "tools")) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import anim_clips # noqa: E402 import anim_glb # noqa: E402 from anim_index import joaat32 # noqa: E402 import test_anim_clips as clips_fixture # noqa: E402 SYSTEM, GRAPHICS = 0x50000000, 0x60000000 # Three joints: the clip fixture animates skel_a and skel_b (rotation) and skel_c (translation). NAMES = ("SKEL_A", "SKEL_B", "SKEL_C") PARENTS = (None, 0, 1) ROTATIONS = ((0.0, 0.0, math.sqrt(0.5), math.sqrt(0.5)), (0.0, 0.0, 0.0, 1.0), (0.5, 0.5, 0.5, 0.5)) TRANSLATIONS = ((0.0, 0.0, 1.0), (0.5, 0.0, 0.0), (0.0, 0.25, 0.0)) class Page: """System or graphics page builder; `base` is 0x50000000 or 0x60000000.""" def __init__(self, base=SYSTEM, head=0x100): self.b = bytearray(head) self.base = base def alloc(self, data, align=16): self.b += bytes((-len(self.b)) % align) at = len(self.b) self.b += data return at def ptr(self, at, target, base=None): struct.pack_into(" 4 else 1 # 8 influences use slots 16/17 and 20/21 for k in range(sets): weights, bones = bytearray(), bytearray() for pairs in skin: pairs = (pairs + [(0, 0)] * 8)[4 * k:4 * k + 4] weights += bytes(w for _b, w in pairs) bones += bytes(b for b, _w in pairs) if layout == "u8x4" else \ b"".join(struct.pack(" offsets.""" out, offsets = bytearray(0x1000), [] for pages in resources: offsets.append(len(out) + 16) for k, page in enumerate(pages): if k == 0: out += bytes(16) out += zlib.compress(page) out += bytes((-len(out)) % 16) out += bytes((-len(out)) % 0x1000) with open(path, "wb") as f: f.write(out) return offsets def read_glb(path): with open(path, "rb") as f: data = f.read() magic, version, total = struct.unpack_from("<4sII", data, 0) assert magic == b"glTF" and version == 2 and total == len(data) jlen, _ = struct.unpack_from(" a for a, b in zip(times, times[1:]))) def test_bone_hash_zero_drives_the_mover(self): out, _ = self.channels(0.0, 4 / 30, 1.0) self.assertIn(("mover", "translation"), out) out, tally = self.channels(0.0, 4 / 30, 1.0, root_motion=False) self.assertNotIn(("mover", "translation"), out) self.assertEqual(tally["tracks_mover_skipped"], 1) def test_single_frame_pose_window_keeps_only_that_frame(self): anim_clips.decode_animation = lambda _s, _anim: ( {0: [(float(k), 0.0, 0.0, 1.0) for k in range(5)], 1: [(float(k * 10), 0.0, 0.0) for k in range(5)]}, 5, ) out, _ = self.channels(2 / 30, 2 / 30, 1.0) self.assertEqual(out[("mover", "translation")], [(0.0, (20.0, 0.0, 0.0))]) # Off-grid start == end windows pick the nearest frame instead of falling back to frame 0. out_mid, _ = self.channels(0.075, 0.075, 1.0) self.assertEqual(out_mid[("mover", "translation")], [(0.0, (20.0, 0.0, 0.0))]) out_hi, _ = self.channels(0.095, 0.095, 1.0) self.assertEqual(out_hi[("mover", "translation")], [(0.0, (30.0, 0.0, 0.0))]) # Even when start == end sits slightly before a frame within 1e-4, timestamp stays 0.0. self.anim["duration"] = 4 / 32 t = 2 / 32 - 2**-14 out_tol, _ = self.channels(t, t, 1 / 1024) self.assertEqual(out_tol[("mover", "translation")], [(0.0, (20.0, 0.0, 0.0))]) def test_select_clips_handles_non_hex_0x_names_and_bad_selectors(self): d = { "clips": [ {"kind": "clip", "name": "other.clip", "hash": 0x11111111}, {"kind": "clip", "name": "0x_intro.clip", "hash": 0x22222222}, ] } self.assertEqual([c["hash"] for c in anim_glb.select_clips(d, ["0x_intro"])], [0x22222222]) with self.assertRaisesRegex(anim_glb.ExportError, "0xbad"): anim_glb.select_clips(d, ["0xbad"]) class SamplerTimeTest(unittest.TestCase): def test_fractional_time_bounds_match_the_binary_accessor(self) -> None: skeleton = skeleton_resource() joints, _ = anim_glb.read_skeleton(skeleton, anim_glb.drawable_at(skeleton, None)) keys = [(1 / 30, (0.0, 0.0, 0.0)), (2 / 30, (1.0, 0.0, 0.0))] glb, _ = anim_glb.build(joints, [], [("sample", {(0, "translation"): keys})]) with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "sampler.glb") with open(path, "wb") as out: out.write(glb) gltf, binary = read_glb(path) sampler = gltf["animations"][0]["samplers"][0] index = sampler["input"] min_time, max_time = accessor_values(gltf, binary, index) self.assertEqual(gltf["accessors"][index]["min"], list(min_time)) self.assertEqual(gltf["accessors"][index]["max"], list(max_time)) def test_keys_that_collapse_to_one_stored_time_are_refused(self) -> None: skeleton = skeleton_resource() joints, _ = anim_glb.read_skeleton(skeleton, anim_glb.drawable_at(skeleton, None)) keys = [(1.0, (0.0, 0.0, 0.0)), (1.0 + 2 ** -25, (1.0, 0.0, 0.0))] with self.assertRaisesRegex(ValueError, "key times are not increasing"): anim_glb.build(joints, [], [("sample", {(0, "translation"): keys})]) class ExportTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.packs = os.path.join(self.tmp.name, "packs.rpf") self.anim = os.path.join(self.tmp.name, "anim.rpf") palette = [joaat32("skel_c"), joaat32("skel_a")] skin = [[(0, 200), (1, 55)], [(1, 255)], [(0, 128), (1, 127)], [(1, 255)]] self.offsets = write_archive(self.packs, [[skeleton_resource()], list(part_resource(palette, "u8x4", skin))]) self.dict_offset = clips_fixture.write_rpf(self.anim, [clips_fixture.two_sequence_dictionary("first@dict")])[0] def tearDown(self): self.tmp.cleanup() def run_tool(self, *args): return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) def export(self, *extra): out = os.path.join(self.tmp.name, "out.glb") report = os.path.join(self.tmp.name, "report.json") r = self.run_tool(self.packs, out, "--skeleton", hex(self.offsets[0]), "--part", hex(self.offsets[1]), "--anim", self.anim, "--dictionary", hex(self.dict_offset), "--report", report, *extra) self.assertEqual(r.returncode, 0, r.stderr) with open(report, encoding="utf-8") as f: return read_glb(out), json.load(f) def test_export_writes_skin_joints_and_clip(self): (gltf, binary), report = self.export() self.assertEqual(gltf["nodes"][0]["rotation"], anim_glb.Z_UP_TO_Y_UP) skin = gltf["skins"][0] self.assertEqual([gltf["nodes"][i]["name"] for i in skin["joints"]], list(NAMES)) ibm = accessor_values(gltf, binary, skin["inverseBindMatrices"]) world = world_transforms() for got, (q, t) in zip(ibm, world): for a, b in zip(got, inverse_bind(q, t)): self.assertAlmostEqual(a, b, places=5) prim = gltf["meshes"][0]["primitives"][0] joints = accessor_values(gltf, binary, prim["attributes"]["JOINTS_0"]) weights = accessor_values(gltf, binary, prim["attributes"]["WEIGHTS_0"]) self.assertEqual(joints[0][:2], (2, 0)) for row in weights: self.assertAlmostEqual(sum(row), 1.0, places=5) # skinned mesh nodes sit at the scene root, outside the turned skeleton mesh_node = next(n for n in gltf["nodes"] if "mesh" in n) self.assertNotIn("rotation", mesh_node) self.assertEqual(mesh_node["skin"], 0) # the fixture clip: rotation on skel_a and skel_b, translation on skel_c, two control tracks left out (animation,) = gltf["animations"] targets = sorted((gltf["nodes"][c["target"]["node"]]["name"], c["target"]["path"]) for c in animation["channels"]) self.assertEqual(targets, [("SKEL_A", "rotation"), ("SKEL_B", "rotation"), ("SKEL_C", "translation")]) self.assertEqual(report["clips"][0]["tracks_other_type"], 2) # the sampled values are the decoded ones s, d = anim_glb.load_dictionary(self.anim, self.dict_offset) tracks, frames = anim_clips.decode_animation(s, d["packs"][0]["animations"][0]) channel = next(c for c in animation["channels"] if gltf["nodes"][c["target"]["node"]]["name"] == "SKEL_A") sampler = animation["samplers"][channel["sampler"]] times = accessor_values(gltf, binary, sampler["input"]) values = accessor_values(gltf, binary, sampler["output"]) self.assertEqual(len(times), frames) self.assertAlmostEqual(times[-1][0], (frames - 1) / 30.0, places=5) for got, want in zip(values, tracks[0]): for a, b in zip(got, want): self.assertAlmostEqual(a, b, places=5) def test_cloth_bones_outside_the_skeleton_export_as_extra_joints(self): # Two clothing parts share one unknown cloth bone; the second also has one of its own. cloth, own = 0x12345678, 0x0BADF00D part_a = list(part_resource([joaat32("skel_c"), cloth], "u8x4", [[(0, 100), (1, 155)]] * 4)) part_b = list(part_resource([cloth, own], "u8x4", [[(0, 128), (1, 127)]] * 4)) packs = os.path.join(self.tmp.name, "cloth.rpf") offsets = write_archive(packs, [[skeleton_resource()], part_a, part_b]) out, report_path = os.path.join(self.tmp.name, "cloth.glb"), os.path.join(self.tmp.name, "cloth.json") r = self.run_tool(packs, out, "--skeleton", hex(offsets[0]), "--part", hex(offsets[1]), "--part", hex(offsets[2]), "--report", report_path) self.assertEqual(r.returncode, 0, r.stderr) gltf, binary = read_glb(out) with open(report_path, encoding="utf-8") as f: self.assertEqual(json.load(f)["counts"]["extra_joints"], 2) (skin,) = gltf["skins"] names = [gltf["nodes"][i]["name"] for i in skin["joints"]] self.assertEqual(names, [*NAMES, f"bone_0x{cloth:08x}", f"bone_0x{own:08x}"]) ibm = accessor_values(gltf, binary, skin["inverseBindMatrices"]) self.assertEqual(len(ibm), 5) children = {n["name"]: n.get("children", []) for n in gltf["nodes"] if "name" in n} for k in (3, 4): node = gltf["nodes"][skin["joints"][k]] self.assertEqual((node["rotation"], node["translation"]), ([0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0])) self.assertIn(skin["joints"][k], children["SKEL_A"]) # a child of the skeleton root for a, b in zip(ibm[k], ibm[0]): # the root's inverse bind: the rest pose holds self.assertAlmostEqual(a, b, places=6) for mesh, expected in zip(gltf["meshes"], ((2, 3), (3, 4))): attributes = mesh["primitives"][0]["attributes"] joints = accessor_values(gltf, binary, attributes["JOINTS_0"]) self.assertEqual({v for row in joints for v in row[:2]}, set(expected)) check = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "glb_skinning.py"), out], capture_output=True, text=True) self.assertEqual(check.returncode, 0, check.stdout + check.stderr) def test_dictionary_lookup_stops_before_adjacent_resource(self): data = clips_fixture.two_sequence_dictionary() _, selected, _ = clips_fixture.write_rpf(self.anim, [data] * 3) with patch.object(anim_glb.anim_index, "classify", wraps=anim_glb.anim_index.classify) as classify: system, _dictionary = anim_glb.load_dictionary(self.anim, selected) self.assertEqual(system.d, data) self.assertEqual([call.args[1] for call in classify.call_args_list], [selected]) def test_export_reads_page_map_on_sixth_page(self): data = bytearray(clips_fixture.two_sequence_dictionary()) page_map = len(data) data.extend(bytes(96)) struct.pack_into("