"""Synthetic tests for tools/skinned_glb.py. python -I tests/test_skinned_glb.py Every model, skeleton, skin stream and GLB here is built by the test. No game file, value or name is used. The fixture is a three-bone ped skeleton, a two-entry drawable palette and a three-vertex 8-influence skin buffer. """ import contextlib import hashlib import io import json import math import os import struct import subprocess import sys import tempfile import unittest from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) import glb_writer # noqa: E402 import skinned_glb # noqa: E402 def _matrix(translation=(0.0, 0.0, 0.0)): return [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, float(translation[0]), float(translation[1]), float(translation[2]), 1.0] def _write_json(path, value): with open(path, "w", encoding="utf-8") as handle: json.dump(value, handle, indent=2) def _write_glb(path): primitive = { "positions": [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], "normals": [(0.0, 0.0, 1.0)] * 3, "uvs": [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], "indices": [0, 1, 2], } with open(path, "wb") as handle: handle.write(glb_writer.build_glb([primitive])) def _read(path): with open(path, "rb") as handle: return handle.read() def _section_word(offset, fmt): return ((offset // 2) << 8) | fmt def _skin_buffer(j0, j1, w0, w1, *, omit_slot=None, formats=None, offsets=None, size=0x160): """Graphics buffer with the measured 23-word section header and per-slot rows.""" formats = {6: 0x26, 7: 0x26, 8: 0x25, 9: 0x25, **(formats or {})} offsets = {6: 0x100, 7: 0x110, 8: 0x120, 9: 0x130, **(offsets or {})} data = {6: w0, 7: w1, 8: j0, 9: j1} blob = bytearray(size) for slot in (6, 7, 8, 9): if slot == omit_slot: continue struct.pack_into(" len(blob): raise ValueError("test skin stream does not fit its buffer") blob[offsets[slot]:end] = data[slot] return bytes(blob) def _packed_indices(rows): """Pack four u8 joint indices per vertex into the 0x8C four-u32 layout. Bits 12-31 get a recognisable pattern, including bits 12-15, so a decoder that masks 16 bits instead of 12 fails instead of passing. """ return b"".join( struct.pack("<4I", *(0xA5CFF000 | index for index in row)) for row in rows ) def _packed_buffer(j0_rows, j1_rows): _j0, _j1, w0, w1 = _streams() return _skin_buffer( _packed_indices(j0_rows), _packed_indices(j1_rows), w0, w1, formats={8: 0x8C, 9: 0x8C}, offsets={8: 0x120, 9: 0x160}, size=0x1A0, ) def _skeleton(): """A three-bone RAGE Z-up bind pose: root, spine, left upper arm.""" return [ {"index": 0, "name": "SKEL_ROOT", "parent": None, "bind_matrix": _matrix()}, {"index": 1, "name": "SKEL_Spine", "parent": 0, "bind_matrix": _matrix((0.0, 0.0, 1.0))}, {"index": 2, "name": "SKEL_L_UpperArm", "parent": 1, "bind_matrix": _matrix((1.0, 0.0, 1.0))}, ] def _palette(): return [ skinned_glb.joaat32("SKEL_Spine"), skinned_glb.joaat32("GM_TEST_L_UpperArm01_O"), ] def _streams(): j0 = bytes([0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]) j1 = bytes(12) w0 = bytes([64, 191, 0, 0, 128, 127, 0, 0, 255, 0, 0, 0]) w1 = bytes(12) return j0, j1, w0, w1 def _component(root, *, own_skeleton=None, omit_slot=None, buffer=None, mesh_blob=None): directory = os.path.join(root, "component") os.makedirs(os.path.join(directory, "buffers")) if buffer is None: j0, j1, w0, w1 = _streams() buffer = _skin_buffer(j0, j1, w0, w1, omit_slot=omit_slot) with open(os.path.join(directory, "buffers", "01_0.bin"), "wb") as handle: handle.write(buffer) _write_glb(os.path.join(directory, "model.glb")) model = { "buffer_files": ["buffers/01_0.bin"], "glb": "model.glb", "vertex_count": 3, "drawable": { "name": "synthetic", "buffers": [{"bytes": len(buffer), "gfx_off": 0}], "geometries": [{"vertex_buffer": 0, "index_buffer": 0}], "models": [{"bone_palette": _palette()}], "strings": ["GM_TEST_L_UpperArm01_O"], }, "meshes": [{ "geometry": 0, "model": 0, "name": "synthetic_mesh", "vertex_count": 3, "skinned": True, "skin_influences": 8, }], } if own_skeleton is not None: model["drawable"]["skeleton"] = own_skeleton if mesh_blob is not None: model["drawable"]["buffers"][0]["mesh_blob"] = mesh_blob _write_json(os.path.join(directory, "model.json"), model) return directory def _read_model(directory): with open(os.path.join(directory, "model.json"), encoding="utf-8") as handle: return json.load(handle) def _skeleton_dir(root): directory = os.path.join(root, "skeleton") os.makedirs(directory) _write_json(os.path.join(directory, "model.json"), { "drawable": {"skeleton": _skeleton()}, }) return directory def _accessor(gltf, binary, index): payload, accessor = skinned_glb.accessor_bytes(gltf, binary, index) return payload, accessor def _world_matrices(gltf): nodes = gltf["nodes"] parent = {} for index, node in enumerate(nodes): for child in node.get("children", []): parent[child] = index cache = {} def world(index): if index in cache: return cache[index] matrix = nodes[index].get( "matrix", [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]) if index in parent: matrix = skinned_glb.mat_mul(world(parent[index]), matrix) cache[index] = matrix return matrix return world def _transform(matrix, point): return [ sum(matrix[column * 4 + row] * point[column] for column in range(3)) + matrix[12 + row] for row in range(3) ] class InterleavedAccessorTest(unittest.TestCase): def test_last_attribute_can_end_at_the_last_bin_byte(self) -> None: gltf = { "bufferViews": [{"buffer": 0, "byteStride": 24, "byteLength": 48}], "accessors": [{"bufferView": 0, "byteOffset": 12, "componentType": 5126, "count": 2, "type": "VEC3"}], } vertices = struct.pack("<12f", 1, 2, 3, 0, 1, 0, 4, 5, 6, 0, 0, 1) normals, _ = skinned_glb.accessor_bytes(gltf, vertices, 0) self.assertEqual(normals, struct.pack("<6f", 0, 1, 0, 0, 0, 1)) with self.assertRaisesRegex(skinned_glb.SkinError, "outside the BIN chunk"): skinned_glb.accessor_bytes(gltf, vertices[:-1], 0) class SkinnedGlbTest(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.root = self.temp.name def tearDown(self): self.temp.cleanup() def _build(self): skeleton = _skeleton_dir(self.root) component = _component(self.root) payload, stats = skinned_glb.build_skinned_glb(skeleton, [component]) gltf, binary = skinned_glb.read_glb(self._write(payload)) return gltf, binary, stats def _write(self, payload): path = os.path.join(self.root, "out.glb") with open(path, "wb") as handle: handle.write(payload) return path def test_joint_count_and_palette_resolution(self): _gltf, _binary, stats = self._build() self.assertEqual(stats["ped_joints"], 3) self.assertEqual(stats["component_joints"], 1) self.assertEqual(stats["joints"], 4) self.assertEqual(stats["vertices"], 3) self.assertEqual(stats["triangles"], 1) self.assertEqual(stats["source_weight_sum_min"], 255) self.assertEqual(stats["source_weight_sum_max"], 255) def test_local_child_listed_before_its_parent_keeps_the_own_skeleton_link(self): skeleton = _skeleton_dir(self.root) component = _component(self.root) model = _read_model(component) model["drawable"]["skeleton"] = [ {"name": "HelperParent", "parent_name": "SKEL_Spine", "bind_matrix": _matrix((0.0, 0.0, 2.0))}, {"name": "HelperChild", "parent_name": "HelperParent", "bind_matrix": _matrix((0.0, 0.0, 3.0))}, ] model["drawable"]["models"][0]["bone_palette"] = [ skinned_glb.joaat32("HelperChild"), skinned_glb.joaat32("HelperParent"), ] _write_json(os.path.join(component, "model.json"), model) payload, stats = skinned_glb.build_skinned_glb(skeleton, [component]) gltf, _binary = skinned_glb.read_glb(self._write(payload)) self.assertEqual(stats["component_joints"], 2) by_name = {node.get("name"): index for index, node in enumerate(gltf["nodes"])} parent, child = by_name["HelperParent"], by_name["HelperChild"] self.assertIn(child, gltf["nodes"][parent].get("children", [])) self.assertIn(parent, gltf["nodes"][by_name["SKEL_Spine"]].get("children", [])) def test_local_child_under_a_parent_the_palette_never_lists(self): skeleton = _skeleton_dir(self.root) component = _component(self.root) model = _read_model(component) model["drawable"]["skeleton"] = [ {"name": "HelperParent", "parent_name": "SKEL_Spine", "bind_matrix": _matrix((0.0, 0.0, 2.0))}, {"name": "HelperMiddle", "parent": 0, "bind_matrix": _matrix((0.0, 0.0, 3.0))}, {"name": "HelperChild", "parent": 1, "bind_matrix": _matrix((0.0, 0.0, 4.0))}, ] model["drawable"]["models"][0]["bone_palette"] = [ skinned_glb.joaat32("HelperChild"), skinned_glb.joaat32("GM_TEST_L_UpperArm01_O"), ] _write_json(os.path.join(component, "model.json"), model) payload, stats = skinned_glb.build_skinned_glb(skeleton, [component]) gltf, _binary = skinned_glb.read_glb(self._write(payload)) self.assertEqual(stats["component_joints"], 4) by_name = {node.get("name"): index for index, node in enumerate(gltf["nodes"])} parent, middle, child = (by_name["HelperParent"], by_name["HelperMiddle"], by_name["HelperChild"]) self.assertIn(middle, gltf["nodes"][parent].get("children", [])) self.assertIn(child, gltf["nodes"][middle].get("children", [])) self.assertIn(parent, gltf["nodes"][by_name["SKEL_Spine"]].get("children", [])) def test_normalized_byte_uvs_have_aligned_output_rows(self) -> None: from anim_glb import pack_glb skeleton = _skeleton_dir(self.root) component = _component(self.root) source_path = os.path.join(component, "model.glb") source, source_bin = skinned_glb.read_glb(source_path) uv_index = source["meshes"][0]["primitives"][0]["attributes"]["TEXCOORD_0"] uv_accessor = source["accessors"][uv_index] uv_view = source["bufferViews"][uv_accessor["bufferView"]] uv_accessor.update(componentType=5121, normalized=True) uv_view.update(byteStride=4, byteLength=12) offset = uv_view["byteOffset"] rows = bytes((0, 255, 0, 0, 64, 128, 0, 0, 255, 0, 0, 0)) source_bin = source_bin[:offset] + rows + source_bin[offset + len(rows):] with open(source_path, "wb") as handle: handle.write(pack_glb(source, source_bin)) payload, _ = skinned_glb.build_skinned_glb(skeleton, [component]) gltf, binary = skinned_glb.read_glb(self._write(payload)) index = gltf["meshes"][0]["primitives"][0]["attributes"]["TEXCOORD_0"] accessor = gltf["accessors"][index] view = gltf["bufferViews"][accessor["bufferView"]] self.assertEqual((accessor["componentType"], accessor["normalized"]), (5121, True)) self.assertEqual((view.get("byteStride"), view["byteLength"]), (4, 12)) start = view["byteOffset"] self.assertEqual(binary[start:start + view["byteLength"]], rows) self.assertEqual(_accessor(gltf, binary, index)[0], bytes((0, 255, 64, 128, 255, 0))) def test_weight_sums_are_one(self): gltf, binary, _stats = self._build() primitive = gltf["meshes"][0]["primitives"][0] w0, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_0"]) w1, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_1"]) for vertex in range(3): values = struct.unpack_from("<4f", w0, 16 * vertex) + \ struct.unpack_from("<4f", w1, 16 * vertex) self.assertAlmostEqual(sum(values), 1.0, places=6) self.assertGreater(values[0], 0.0) def test_joint_indices_are_in_skin_range(self): gltf, binary, _stats = self._build() joint_count = len(gltf["skins"][0]["joints"]) self.assertEqual(joint_count, 4) primitive = gltf["meshes"][0]["primitives"][0] j0, _ = _accessor(gltf, binary, primitive["attributes"]["JOINTS_0"]) j1, _ = _accessor(gltf, binary, primitive["attributes"]["JOINTS_1"]) for vertex in range(3): indices = struct.unpack_from("<4H", j0, 8 * vertex) + \ struct.unpack_from("<4H", j1, 8 * vertex) for index in indices: self.assertLess(index, joint_count) # The second palette entry is the added helper joint (index 3). self.assertEqual(struct.unpack_from("<4H", j0, 0), (1, 3, 0, 0)) def test_inverse_bind_round_trip(self): gltf, binary, _stats = self._build() skin = gltf["skins"][0] ibm_payload, ibm_accessor = _accessor(gltf, binary, skin["inverseBindMatrices"]) self.assertEqual(ibm_accessor["count"], len(skin["joints"])) inverse_binds = [struct.unpack_from("<16f", ibm_payload, 64 * index) for index in range(len(skin["joints"]))] world = _world_matrices(gltf) for joint, inverse_bind in zip(skin["joints"], inverse_binds): product = skinned_glb.mat_mul(world(joint), inverse_bind) expected = [1.0 if index in (0, 5, 10, 15) else 0.0 for index in range(16)] for actual, wanted in zip(product, expected): self.assertAlmostEqual(actual, wanted, places=5) primitive = gltf["meshes"][0]["primitives"][0] positions, _ = _accessor(gltf, binary, primitive["attributes"]["POSITION"]) j0, _ = _accessor(gltf, binary, primitive["attributes"]["JOINTS_0"]) j1, _ = _accessor(gltf, binary, primitive["attributes"]["JOINTS_1"]) w0, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_0"]) w1, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_1"]) for vertex in range(3): point = struct.unpack_from("<3f", positions, 12 * vertex) indices = struct.unpack_from("<4H", j0, 8 * vertex) + \ struct.unpack_from("<4H", j1, 8 * vertex) weights = struct.unpack_from("<4f", w0, 16 * vertex) + \ struct.unpack_from("<4f", w1, 16 * vertex) result = [0.0, 0.0, 0.0] for index, weight in zip(indices, weights): matrix = skinned_glb.mat_mul(world(skin["joints"][index]), inverse_binds[index]) moved = _transform(matrix, point) for axis in range(3): result[axis] += weight * moved[axis] for actual, wanted in zip(result, point): self.assertAlmostEqual(actual, wanted, places=5) def test_numpy_and_stdlib_weight_paths_agree(self): if skinned_glb._np is None: self.skipTest("numpy is not importable, so the optional path cannot be compared") j0, j1, w0, w1 = _streams() j0 = bytearray(j0) j0[2] = 200 # zero-weight component outside the two-entry palette j0 = bytes(j0) with_numpy = skinned_glb.normalise_weights(j0, j1, w0, w1, 3, 2, [1, 3], 4) saved = skinned_glb._np try: skinned_glb._np = None without_numpy = skinned_glb.normalise_weights(j0, j1, w0, w1, 3, 2, [1, 3], 4) finally: skinned_glb._np = saved for key in ("j0", "j1", "w0", "w1"): self.assertEqual(with_numpy[key], without_numpy[key], key) self.assertEqual(with_numpy["sum_min"], without_numpy["sum_min"]) self.assertEqual(with_numpy["sum_max"], without_numpy["sum_max"]) self.assertAlmostEqual(struct.unpack_from("<4f", with_numpy["w0"], 0)[0], 64 / 255, delta=1e-6) def test_only_weighted_joint_indices_must_fit_unsigned_short(self): backends = [None] if skinned_glb._np is None else [None, skinned_glb._np] palette = [65536, 65535] for backend in backends: with self.subTest(backend=backend), mock.patch.object(skinned_glb, "_np", backend): for second_set in (False, True): w0, w1 = bytes([255, 0, 0, 0]), bytes(4) if second_set: w0, w1 = w1, w0 with self.subTest(second_set=second_set): with self.assertRaisesRegex(skinned_glb.SkinError, "UNSIGNED_SHORT"): skinned_glb.normalise_weights(bytes(4), bytes(4), w0, w1, 1, 2, palette, 65537) joints = bytes([1, 0, 0, 0]) out = skinned_glb.normalise_weights(joints, joints, w0, w1, 1, 2, palette, 65537) weighted, unused = ("j1", "j0") if second_set else ("j0", "j1") self.assertEqual(struct.unpack("<4H", out[weighted]), (65535, 0, 0, 0)) self.assertEqual(out[unused], bytes(8)) def test_full_export_without_numpy(self): skeleton = _skeleton_dir(self.root) component = _component(self.root) saved = skinned_glb._np try: skinned_glb._np = None payload, stats = skinned_glb.build_skinned_glb(skeleton, [component]) finally: skinned_glb._np = saved gltf, binary = skinned_glb.read_glb(self._write(payload)) self.assertEqual(stats["joints"], 4) primitive = gltf["meshes"][0]["primitives"][0] w0, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_0"]) for vertex in range(3): self.assertAlmostEqual(sum(struct.unpack_from("<4f", w0, 16 * vertex)), 1.0, places=6) def test_packed_joint_stream_decodes_to_four_u8_indices(self): j0_rows = [(1, 2, 0, 0), (1, 2, 0, 0), (2, 1, 0, 0)] j1_rows = [(3, 0, 0, 0)] * 3 component = _component(self.root, buffer=_packed_buffer(j0_rows, j1_rows)) model = _read_model(component) streams = skinned_glb.read_skin_streams(component, model, model["meshes"][0]) self.assertEqual(streams["j0"], bytes([1, 2, 0, 0, 1, 2, 0, 0, 2, 1, 0, 0])) self.assertEqual(streams["j1"], bytes([3, 0, 0, 0] * 3)) def test_packed_joint_index_above_u8_is_rejected(self): j0_rows = [(1, 2, 0, 0), (1, 2, 0, 0), (256, 0, 0, 0)] j1_rows = [(3, 0, 0, 0)] * 3 component = _component(self.root, buffer=_packed_buffer(j0_rows, j1_rows)) model = _read_model(component) with self.assertRaisesRegex(skinned_glb.SkinError, "does not fit u8"): skinned_glb.read_skin_streams(component, model, model["meshes"][0]) def test_short_packed_joint_stream_is_rejected(self): j0 = _packed_indices([(1, 2, 0, 0)] * 3)[:47] j1 = _packed_indices([(3, 0, 0, 0)] * 3) _j0, _j1, w0, w1 = _streams() buffer = _skin_buffer( j0, j1, w0, w1, formats={8: 0x8C, 9: 0x8C}, offsets={8: 0x150, 9: 0x120}, size=0x17F, ) component = _component(self.root, buffer=buffer) model = _read_model(component) with self.assertRaisesRegex(skinned_glb.SkinError, "outside its graphics buffer"): skinned_glb.read_skin_streams(component, model, model["meshes"][0]) def test_missing_joint_stream_is_rejected(self): component = _component(self.root, omit_slot=8) skeleton = _skeleton_dir(self.root) with self.assertRaises(skinned_glb.SkinError): skinned_glb.build_skinned_glb(skeleton, [component]) def test_malformed_gfx_off_and_none_default(self): component = _component(self.root) for bad in ("abc", "", False, True, float("inf"), 1.5, []): model = _read_model(component) model["drawable"]["buffers"][0]["gfx_off"] = bad with self.subTest(gfx_off=bad), self.assertRaisesRegex( skinned_glb.SkinError, "vertex buffer offset is not an integer" ): skinned_glb.read_skin_streams(component, model, model["meshes"][0]) model_none = _read_model(component) model_none["drawable"]["buffers"][0]["gfx_off"] = None streams = skinned_glb.read_skin_streams(component, model_none, model_none["meshes"][0]) self.assertIn("j0", streams) def test_bool_vertex_count_is_rejected(self): component = _component(self.root) for bad in (False, True): model = _read_model(component) model["meshes"][0]["vertex_count"] = bad with self.subTest(vertex_count=bad), self.assertRaisesRegex( skinned_glb.SkinError, "positive integer vertex_count" ): skinned_glb.read_skin_streams(component, model, model["meshes"][0]) def test_mesh_blob_sections_supply_the_stream_offsets(self): j0, j1, w0, w1 = _streams() buffer = bytearray(_skin_buffer(j0, j1, w0, w1)) for slot in (6, 7, 8, 9): struct.pack_into(" other for v in r] for r in self.rows]) def __eq__(self, other): return _FakeMask([[v == other for v in r] for r in self.rows]) def __ge__(self, other): return _FakeMask([[v >= other for v in r] for r in self.rows]) def __itruediv__(self, col): for r, d in zip(self.rows, col.vals): for i in range(len(r)): r[i] = r[i] / d return self def __getitem__(self, key): if isinstance(key, _FakeMask): return _FakeVec([v for r, mr in zip(self.rows, key.rows) for v, m in zip(r, mr) if m]) if isinstance(key, tuple) and len(key) == 2 and key[0] == slice(None): return _FakeArray([r[key[1]] for r in self.rows]) raise TypeError(key) def __setitem__(self, key, value): assert isinstance(key, _FakeMask) for r, mr in zip(self.rows, key.rows): for i, m in enumerate(mr): if m: r[i] = value def tobytes(self): if self.rows and isinstance(self.rows[0][0], float): return b"".join(struct.pack(".tmp must stay intact after exporting . skeleton = _skeleton_dir(self.root) component = _component(self.root) old_buf = os.path.join(component, "buffers", "01_0.bin") new_buf_rel = "buffers/export.glb.tmp" new_buf = os.path.join(component, "buffers", "export.glb.tmp") os.replace(old_buf, new_buf) model_json_path = os.path.join(component, "model.json") with open(model_json_path, "r", encoding="utf-8") as handle: model = json.load(handle) model["buffer_files"] = [new_buf_rel] _write_json(model_json_path, model) before_hash = hashlib.sha256(_read(new_buf)).hexdigest() out = os.path.join(component, "buffers", "export.glb") result = subprocess.run( [sys.executable, "-I", os.path.join(ROOT, "tools", "skinned_glb.py"), out, "--skeleton", skeleton, "--component", component], capture_output=True, text=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue(_read(out).startswith(b"glTF")) self.assertTrue(os.path.exists(new_buf)) self.assertEqual(hashlib.sha256(_read(new_buf)).hexdigest(), before_hash) class ValidationHardeningTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.root = self.temp.name def tearDown(self): self.temp.cleanup() def test_read_glb_rejects_bad_version_chunk_types_and_truncation(self): good_json = b'{"asset":{"version":"2.0"}} ' good_bin = b"\x00\x01\x02\x03" def _make(version=2, total=None, jlen=None, jtype=skinned_glb.CHUNK_JSON, blen=None, btype=skinned_glb.CHUNK_BIN, tail=None): if jlen is None: jlen = len(good_json) if tail is None: if blen is None: blen = len(good_bin) tail = struct.pack("= count 3 with open(glb_path, "wb") as handle: handle.write(pack_glb(source, bytes(mut))) with self.assertRaisesRegex(skinned_glb.SkinError, "out of range"): skinned_glb.build_skinned_glb(skeleton, [c_oob]) # 3) Non-SCALAR index accessor and float index componentType. c_bad_idx = _component(os.path.join(self.root, "idx_type")) glb_path = os.path.join(c_bad_idx, "model.glb") source, source_bin = skinned_glb.read_glb(glb_path) idx_acc_i = source["meshes"][0]["primitives"][0]["indices"] source["accessors"][idx_acc_i]["componentType"] = skinned_glb.COMPONENT_FLOAT # Expand BIN so accessor_bytes succeeds and _validate_indices rejects float indices. idx_view = source["bufferViews"][source["accessors"][idx_acc_i]["bufferView"]] idx_view["byteOffset"] = len(source_bin) idx_view["byteLength"] = 12 with open(glb_path, "wb") as handle: handle.write(pack_glb(source, source_bin + b"\x00" * 12)) with self.assertRaisesRegex(skinned_glb.SkinError, "unsupported source index component type"): skinned_glb.build_skinned_glb(skeleton, [c_bad_idx]) # 4) Near-singular bind matrix whose inverse overflows float32 -> SkinError (not OverflowError). sk_ovf = os.path.join(self.root, "sk_ovf") os.makedirs(sk_ovf) tiny = [1e-4, 0.0, 0.0, 0.0, 0.0, 1e-4, 0.0, 0.0, 0.0, 0.0, 1e-4, 0.0, 1e36, 0.0, 0.0, 1.0] _write_json(os.path.join(sk_ovf, "model.json"), { "drawable": {"skeleton": [ {"index": 0, "name": "SKEL_ROOT", "parent": None, "bind_matrix": tiny}, ]}, }) c_ok = _component(os.path.join(self.root, "c_ok")) with self.assertRaisesRegex(skinned_glb.SkinError, "overflows float32"): skinned_glb.build_skinned_glb(sk_ovf, [c_ok]) # 5) Non-dict drawable in skeleton model.json raises SkinError (not AttributeError). sk_bad = os.path.join(self.root, "sk_bad") os.makedirs(sk_bad) _write_json(os.path.join(sk_bad, "model.json"), {"drawable": []}) with self.assertRaisesRegex(skinned_glb.SkinError, "no drawable object"): skinned_glb.build_skinned_glb(sk_bad, [c_ok]) def test_cli_rejects_output_directory_upfront(self): skeleton = _skeleton_dir(self.root) component = _component(self.root) out_dir = os.path.join(self.root, "existing_dir") os.makedirs(out_dir) err = io.StringIO() with mock.patch.object(skinned_glb, "write_skinned_glb", side_effect=AssertionError("should not build GLB")): with contextlib.redirect_stderr(err): rc = skinned_glb.main([out_dir, "--skeleton", skeleton, "--component", component]) self.assertEqual(rc, 2) self.assertIn("output path is a directory", err.getvalue()) if __name__ == "__main__": unittest.main()