From 603d53eb367a2e35745e2b9cc194f290dca9b3d2 Mon Sep 17 00:00:00 2001 From: Hiiva <32042291+Hiiva@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:18:11 +0200 Subject: [PATCH] ASSET-539: Preserve extra UV sets during ped assembly (#6604) Squash-merged after diff review of PR #6604 --- docs/character_models.md | 7 + tests/test_ped_extra_uvs.py | 312 ++++++++++++++++++++++++++++++++++++ tools/ped_assemble.py | 33 ++++ 3 files changed, 352 insertions(+) create mode 100644 tests/test_ped_extra_uvs.py diff --git a/docs/character_models.md b/docs/character_models.md index 8a686874a..ff1fe1dee 100644 --- a/docs/character_models.md +++ b/docs/character_models.md @@ -348,6 +348,13 @@ Character geometry uses GPU meshlets (16-byte headers, up to 128 local vertices | `3`, `4`, `14`, `15` | `0x28` / `0x42` | 4–8 B each | Four UV channels (`UV0` albedo, `UV1` tattoo/suntan/damage, `UV2` wrinkle/micro-detail, `UV3` morphable-model) | | `17` | `0x84` | 16 B | Per-vertex basis / blend-shape / ML-deformer stream | +The ped importer and exporter preserve authored `TEXCOORD_1` and higher sets alongside +`TEXCOORD_0`, including normalized integer input accessors. Ped JSON stores these extra +sets in `uvs_extra`, an object whose keys are the positive set indices (`"1"`, `"2"`, +and so on); `uvs` remains set 0. Overlap culling and vertex compaction keep each set +aligned with the surviving vertices. This preserves vertex data without expanding +the material importer's supported texture-coordinate bindings. + ### 3-tier LOD budgets and thresholds Modular ped drawables in `packs.rpf` stream three separate dictionary tiers per item name plus a diff --git a/tests/test_ped_extra_uvs.py b/tests/test_ped_extra_uvs.py new file mode 100644 index 000000000..52e210a40 --- /dev/null +++ b/tests/test_ped_extra_uvs.py @@ -0,0 +1,312 @@ +"""Preserve authored UV sets through the actual skinned producer and ped CLIs. + +All geometry and skin streams are synthetic. glTF defines TEXCOORD_n as VEC2 +float or normalized unsigned byte/short attributes with consecutive set indices: +https://github.com/KhronosGroup/glTF/blob/5b00b913b74c8f0260c64578b98a09ef2dde0b41/specification/2.0/Specification.adoc#meshes-attributes + + python -I tests/test_ped_extra_uvs.py +""" +import hashlib +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tests")) + +import glb_writer +import ped_assemble as pa +import skinned_glb +import test_skinned_glb as skin_fixture + + +POSITIONS = [(0, 0, 0), (1, 0, 0), (0, 1, 0), + (2, 0, 0), (3, 0, 0), (2, 1, 0)] +UV0 = [(0, 0), (1, 0), (0, 1), (0.25, 0), (0.75, 0), (0.25, 1)] +EXTRA = { + 1: [(i / 8, 0.5 + i / 16) for i in range(6)], + 2: [((10 + 30 * i) / 255, (240 - 20 * i) / 255) for i in range(6)], + 3: [((1000 + 4000 * i) / 65535, (62000 - 5000 * i) / 65535) for i in range(6)], +} + + +def write_json(path, value): + path.write_text(json.dumps(value) + "\n", encoding="utf-8", newline="\n") + + +def encode_glb(doc, blob): + raw = json.dumps(doc, separators=(",", ":")).encode("utf-8") + raw += b" " * (-len(raw) % 4) + blob = bytes(blob) + b"\0" * (-len(blob) % 4) + return (struct.pack("<4sII", b"glTF", 2, 28 + len(raw) + len(blob)) + + struct.pack(" 1 tris", result.stdout) + part = json.loads(culled.read_text(encoding="utf-8")) + self.assertEqual(part["positions"], [list(row) for row in POSITIONS[3:]]) + self.assertEqual(part["triangles"], [[0, 1, 2]]) + self.assertEqual(part.get("uvs_extra"), + {str(key): [list(row) for row in rows[3:]] for key, rows in EXTRA.items()}) + # Supply the source skin's joint order so the normal ped skin-remapping + # path is exercised as well. This assertion concerns vertex data only. + joint_names = [producer_doc["nodes"][index]["name"] + for index in producer_doc["skins"][0]["joints"]] + manifest = self.root / "manifest.json" + write_json(manifest, {"parts": [part], "skeleton": { + "coord_space": "y-up", "joints": [{"name": name} for name in joint_names], + }}) + assembled = self.root / "assembled.glb" + self.cli("ped_assemble.py", "assemble", "--manifest", manifest, "-o", assembled, + "--source-space", "y-up", "--no-cull", "--no-standing-offset") + out_doc, after = attributes(assembled) + self.assertEqual(len(out_doc["skins"][0]["joints"]), len(joint_names)) + for name in ("POSITION", "NORMAL", "TEXCOORD_0", "TEXCOORD_1", "TEXCOORD_2", "TEXCOORD_3", + "JOINTS_0", "JOINTS_1", "WEIGHTS_0", "WEIGHTS_1"): + self.assertEqual(after[name], f32_rows(before[name][3:]), name) + self.assertEqual(after["indices"], [(0,), (1,), (2,)]) + direct = self.root / "culled.glb" + self.cli("ped_assemble.py", "cull-overlap", *options, "-o", direct) + _, direct_data = attributes(direct) + self.assertEqual(direct_data, after) + self.assertTrue(all(hashlib.sha256(path.read_bytes()).digest() == digest + for path, digest in originals.items())) + + def test_no_extra_sets_keep_existing_json_and_attributes(self): + source = self.root / "primary.glb" + write_geometry(source, extra=False) + loaded = pa.read_glb_parts(str(source))[0] + self.assertEqual(loaded.uvs_extra, {}) + self.assertNotIn("uvs_extra", pa.part_to_dict(loaded)) + output = self.root / "primary-out.glb" + self.cli("ped_assemble.py", "assemble", source, "-o", output, + "--source-space", "y-up", "--no-cull", "--no-standing-offset") + _, before = attributes(source) + _, after = attributes(output) + self.assertEqual(before, after) + + def test_sparse_extra_sets_use_the_same_precheck_and_overrides(self): + source = self.root / "sparse.glb" + write_geometry(source) + doc, blob = skinned_glb.read_glb(str(source)) + blob = bytearray(blob) + attrs = doc["meshes"][0]["primitives"][0]["attributes"] + + def add_view(data): + blob.extend(b"\0" * (-len(blob) % 4)) + index = len(doc["bufferViews"]) + doc["bufferViews"].append({"buffer": 0, "byteOffset": len(blob), "byteLength": len(data)}) + blob.extend(data) + return index + + first = doc["accessors"][attrs["TEXCOORD_1"]] + first.pop("bufferView") + first.pop("byteOffset") + first["sparse"] = {"count": 2, + "indices": {"bufferView": add_view(bytes((1, 4))), "componentType": 5121}, + "values": {"bufferView": add_view(struct.pack("<4f", .25, .75, .125, .875))}} + doc["accessors"][attrs["TEXCOORD_2"]]["sparse"] = { + "count": 2, "indices": {"bufferView": add_view(bytes((0, 5))), "componentType": 5121}, + "values": {"bufferView": add_view(bytes((77, 33, 199, 22)))}, + } + doc["buffers"][0]["byteLength"] = len(blob) + source.write_bytes(encode_glb(doc, blob)) + original = source.read_bytes() + output = self.root / "sparse-out.glb" + self.cli("ped_assemble.py", "assemble", source, "-o", output, + "--source-space", "y-up", "--no-cull", "--no-standing-offset") + _, data = attributes(output) + expected1 = [(0, 0), (.25, .75), (0, 0), (0, 0), (.125, .875), (0, 0)] + expected2 = EXTRA[2].copy() + expected2[0], expected2[5] = (77 / 255, 33 / 255), (199 / 255, 22 / 255) + for channel, rows in ((1, expected1), (2, expected2), (3, EXTRA[3])): + self.assertIn(f"TEXCOORD_{channel}", data) + self.assertEqual(data[f"TEXCOORD_{channel}"], f32_rows(rows)) + self.assertEqual(source.read_bytes(), original) + + first["type"] = "VEC3" + malformed = self.root / "wrong-shape.glb" + malformed.write_bytes(encode_glb(doc, blob)) + rejected_output = self.root / "must-not-exist.glb" + result = subprocess.run([sys.executable, "-I", str(ROOT / "tools/ped_assemble.py"), + "assemble", str(malformed), "-o", str(rejected_output)], + capture_output=True, text=True, timeout=30) + self.assertEqual(result.returncode, 2, result.stdout + result.stderr) + self.assertIn("expected VEC2", result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertFalse(rejected_output.exists()) + + def test_extra_implicit_rows_share_the_import_budget_across_instances(self): + source = self.root / "zero.glb" + write_geometry(source) + doc, blob = skinned_glb.read_glb(str(source)) + attrs = doc["meshes"][0]["primitives"][0]["attributes"] + for channel in (1, 2, 3): + doc["accessors"][attrs[f"TEXCOORD_{channel}"]] = { + "componentType": 5126, "count": 6, "type": "VEC2", + } + for instances in (1, 2): + with self.subTest(instances=instances): + doc["nodes"] = [{"name": f"instance_{i}", "mesh": 0} for i in range(instances)] + doc["scenes"] = [{"nodes": list(range(instances))}] + source.write_bytes(encode_glb(doc, blob)) + # A small test-only cap exercises the same per-file boundary without + # allocating a million Python rows. Every fixture is valid glTF. + rows = 18 * instances + with mock.patch.object(pa, "MAX_IMPLICIT_ACCESSOR_ROWS", rows): + parts = pa.read_glb_parts(str(source)) + self.assertEqual(len(parts), instances) + for part in parts: + self.assertEqual(part.uvs_extra, {key: [(0.0, 0.0)] * 6 for key in (1, 2, 3)}) + with mock.patch.object(pa, "MAX_IMPLICIT_ACCESSOR_ROWS", rows - 1): + with self.assertRaisesRegex(pa.PedAssembleError, "implicit accessor rows"): + pa.read_glb_parts(str(source)) + + def test_extra_indices_cannot_replace_primary_or_leave_gaps(self): + for extra in ({0: UV0}, {2: UV0}, {1.0: UV0}, {True: UV0}, {1: UV0[:-1]}): + with self.subTest(extra=list(extra)): + part = pa.MeshPart("invalid", POSITIONS, [(0, 1, 2)], coord_space="y-up", + uvs=UV0, uvs_extra=extra) + with self.assertRaises(pa.PedAssembleError): + pa.build_assembled_glb([part], apply_standing=False) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ped_assemble.py b/tools/ped_assemble.py index ad35083bb..28efb9ed6 100644 --- a/tools/ped_assemble.py +++ b/tools/ped_assemble.py @@ -980,6 +980,15 @@ def _part_from_dict(raw: dict, *, default_name: str, default_space: str, base_di triangles = _normalize_triangles(raw.get("triangles", raw.get("indices", []))) normals = [(float(n[0]), float(n[1]), float(n[2])) for n in raw["normals"]] if raw.get("normals") else None uvs = [(float(u[0]), float(u[1])) for u in raw["uvs"]] if raw.get("uvs") else None + raw_extra = raw.get("uvs_extra", {}) + if not isinstance(raw_extra, dict) or any( + re.fullmatch(r"[1-9][0-9]{0,8}", str(key)) is None for key in raw_extra + ): + raise PedAssembleError(f"{name}: uvs_extra keys must be positive texture coordinate set indices") + uvs_extra = { + int(key): [(float(u[0]), float(u[1])) for u in values] + for key, values in raw_extra.items() + } colors = None if raw.get("colors"): colors = [ @@ -1001,6 +1010,7 @@ def _part_from_dict(raw: dict, *, default_name: str, default_space: str, base_di translation=(float(trans[0]), float(trans[1]), float(trans[2])), normals=normals, uvs=uvs, + uvs_extra=uvs_extra, colors=colors, joints_0=joints_0, weights_0=weights_0, @@ -1050,6 +1060,9 @@ def part_to_dict(part: MeshPart) -> dict: out["normals"] = [list(n) for n in part.normals] if part.uvs is not None: out["uvs"] = [list(u) for u in part.uvs] + if part.uvs_extra: + out["uvs_extra"] = {str(key): [list(u) for u in values] + for key, values in sorted(part.uvs_extra.items())} if part.colors is not None: out["colors"] = [list(c) for c in part.colors] if part.joints_0 is not None: @@ -1242,6 +1255,9 @@ def _check_glb_document(doc: object, bin_chunk: bytes, path: str) -> None: for name, allowed in _GLB_ATTRIBUTE_TYPES.items(): if name in attrs: check_accessor(attrs[name], f"{where}.{name}", allowed) + for name, index in attrs.items(): + if re.fullmatch(r"TEXCOORD_[1-9][0-9]{0,8}", name): + check_accessor(index, f"{where}.{name}", ("VEC2",)) if "indices" in prim: check_accessor(prim["indices"], f"{where}.indices", ("SCALAR",)) if "material" not in prim: @@ -1473,6 +1489,12 @@ def read_glb_parts(path: str) -> list[MeshPart]: [tuple(float(x) for x in u) for u in read_accessor(attrs["TEXCOORD_0"])] if "TEXCOORD_0" in attrs else None ) + uvs_extra = { + int(semantic[9:]): [tuple(float(x) for x in u) + for u in read_accessor(accessor)] + for semantic, accessor in attrs.items() + if re.fullmatch(r"TEXCOORD_[1-9][0-9]{0,8}", semantic) + } colors = None if "COLOR_0" in attrs: raw_c = read_accessor(attrs["COLOR_0"]) @@ -1541,6 +1563,7 @@ def read_glb_parts(path: str) -> list[MeshPart]: translation=trans, normals=normals, uvs=uvs, + uvs_extra=uvs_extra, colors=colors, joints_0=joints_0, weights_0=weights_0, @@ -1945,6 +1968,16 @@ def build_assembled_glb( uv_bv = _append_bv(bin_buf, buffer_views, uv_bytes, target=TARGET_ARRAY_BUFFER) attrs["TEXCOORD_0"] = _append_accessor(accessors, uv_bv, COMPONENT_FLOAT, n_verts, "VEC2") + if any(type(key) is not int or not 1 <= key <= 999999999 for key in aligned.uvs_extra): + raise PedAssembleError(f"{part.name}: uvs_extra keys must be positive texture coordinate set indices") + for key, values in sorted(aligned.uvs_extra.items()): + if f"TEXCOORD_{key - 1}" not in attrs: + raise PedAssembleError(f"{part.name}: texture coordinate sets must start at 0 without gaps") + if len(values) != n_verts or any(len(u) != 2 for u in values): + raise PedAssembleError(f"{part.name}: TEXCOORD_{key} must contain one VEC2 per vertex") + uv_bv = _append_bv(bin_buf, buffer_views, _pack_f32_vec(values, 2), target=TARGET_ARRAY_BUFFER) + attrs[f"TEXCOORD_{key}"] = _append_accessor(accessors, uv_bv, COMPONENT_FLOAT, n_verts, "VEC2") + if aligned.colors is not None and len(aligned.colors) == n_verts: col_bytes = _pack_f32_vec(aligned.colors, 4) col_bv = _append_bv(bin_buf, buffer_views, col_bytes, target=TARGET_ARRAY_BUFFER)