Skip to content

Official Codebase of 3DCodeVerse

Python

texturing: a GLB node finds its plan part by conventions.part_key — a single Arm-2 is textured, an instanced Leg_0 is normalised

gaoypengbf5642d4815f
diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.py
index 937d48c7..96a96b2d 100644
--- a/harness/codeverse3d/conventions.py
+++ b/harness/codeverse3d/conventions.py
@@ -21,7 +21,7 @@ Frames
from __future__ import annotations
import re
-from collections.abc import Sequence
+from collections.abc import Collection, Sequence
from dataclasses import dataclass
from enum import StrEnum
from typing import TYPE_CHECKING
@@ -204,6 +204,21 @@ def split_instance(name: str) -> tuple[str, str]:
return (m.group("base"), m.group("idx")) if m else (name, "")
+#: a URDF link's geometry pieces are exported as ``<link>__<i>`` nodes under the link node
+#: (``spatial/joints_export``); ``spatial/measure`` merges them back into the link's part.
+LINK_PIECE_SEP = "__"
+
+
+def part_key(node: str, plan_keys: Collection[str]) -> str | None:
+ """The plan part (a snake key in ``plan_keys``) a GLB node belongs to, or None: the
+ node's own name, else its link (``Link__2`` → ``link``), else that name's instance base
+ (``Leg_0`` / ``Arm-2`` / ``Handle.001`` → ``leg`` / ``arm`` / ``handle``, one copy or
+ many). The texture pass and the material normaliser both read it; the contract gate's
+ ``match_parts`` applies the same :func:`split_instance` rule."""
+ own = to_snake(node.split(LINK_PIECE_SEP, 1)[0])
+ return next((k for k in (to_snake(node), own, split_instance(own)[0]) if k in plan_keys), None)
+
+
def to_pascal(name: str) -> str:
"""``seat_cushion`` / ``seat cushion`` → ``SeatCushion``; a name that is already
PascalCase (no underscore) comes back unchanged, so ``TVStand`` stays ``TVStand``.
diff --git a/harness/codeverse3d/spatial/joints_export.py b/harness/codeverse3d/spatial/joints_export.py
index 7db8c95d..c5b3c3cc 100644
--- a/harness/codeverse3d/spatial/joints_export.py
+++ b/harness/codeverse3d/spatial/joints_export.py
@@ -19,7 +19,7 @@ import numpy as np
import trimesh
from codeverse3d.contracts.artifacts import RenderSet
-from codeverse3d.conventions import ARTICULATION_VIEWS, ViewPreset
+from codeverse3d.conventions import ARTICULATION_VIEWS, LINK_PIECE_SEP, ViewPreset
from codeverse3d.spatial._render_common import out_directory
from codeverse3d.spatial.joints_model import Joint, Robot, fk, resolve_q
from codeverse3d.spatial.joints_poses import limit_poses
@@ -80,7 +80,7 @@ def robot_scene(robot: Robot, pose: dict[str, float] | None = None) -> trimesh.S
else: # several materials: link node + one geometry child per piece (names stay unique)
scene.graph.update(frame_to=name, frame_from=parent_node, matrix=local, metadata=extras)
for i, piece in enumerate(pieces):
- scene.add_geometry(piece.copy(), node_name=f"{name}__{i}", geom_name=f"{name}__{i}", parent_node_name=name,
+ scene.add_geometry(piece.copy(), node_name=f"{name}{LINK_PIECE_SEP}{i}", geom_name=f"{name}{LINK_PIECE_SEP}{i}", parent_node_name=name,
transform=np.eye(4))
scene.metadata.update(meta)
return scene
diff --git a/harness/codeverse3d/spatial/measure.py b/harness/codeverse3d/spatial/measure.py
index be62c869..fd3b1c32 100644
--- a/harness/codeverse3d/spatial/measure.py
+++ b/harness/codeverse3d/spatial/measure.py
@@ -32,7 +32,7 @@ import numpy as np
import trimesh
from codeverse3d.contracts.artifacts import Measurement, PartMeasure
-from codeverse3d.conventions import split_instance
+from codeverse3d.conventions import LINK_PIECE_SEP, split_instance
__all__ = [
"load_scene",
@@ -208,7 +208,7 @@ def part_meshes(scene: trimesh.Scene) -> OrderedDict[str, trimesh.Trimesh | None
if isinstance(links, list) and links and all(str(link) in nodes for link in links):
for link in links:
link = str(link)
- own = [n for n in _subtree_nodes(scene, link) if n == link or str(n).startswith(link + "__")]
+ own = [n for n in _subtree_nodes(scene, link) if n == link or str(n).startswith(link + LINK_PIECE_SEP)]
meshes = [m for n in own if (m := _world_mesh(scene, n)) is not None]
out[link] = trimesh.util.concatenate(meshes) if meshes else None
return out
diff --git a/harness/codeverse3d/texturing/apply.py b/harness/codeverse3d/texturing/apply.py
index 5aa07e6b..e1c2a4aa 100644
--- a/harness/codeverse3d/texturing/apply.py
+++ b/harness/codeverse3d/texturing/apply.py
@@ -37,8 +37,8 @@ from PIL import Image, ImageFilter
from pydantic import BaseModel, Field
from codeverse3d.contracts.plan import StaticPlan
-from codeverse3d.conventions import to_snake
-from codeverse3d.spatial.measure import GlbLoadError, instance_groups, load_scene
+from codeverse3d.conventions import part_key, to_snake
+from codeverse3d.spatial.measure import GlbLoadError, load_scene
from codeverse3d.texturing.materials import (
COARSE_TO_FINE,
FamilyMatch,
@@ -334,19 +334,8 @@ class ApplyReport(BaseModel):
def node_part_lookup(node_names: list[str], plan_parts: dict[str, TexturePart]) -> dict[str, TexturePart | None]:
- """Map scene node names to plan parts: exact (snake) → instance base (``Leg_0`` →
- ``Leg``) → link piece (``Link__2`` → ``Link``)."""
- groups = instance_groups(list(node_names))
- base_of: dict[str, str] = {}
- for base, members in groups.items():
- for m in members:
- base_of[m] = base
- out: dict[str, TexturePart | None] = {}
- for n in node_names:
- cands = [to_snake(n), to_snake(base_of.get(n, n)), to_snake(n.split("__", 1)[0])]
- hit = next((plan_parts[c] for c in cands if c in plan_parts), None)
- out[n] = hit
- return out
+ """Map scene node names to plan parts by :func:`conventions.part_key`."""
+ return {n: plan_parts[k] if (k := part_key(n, plan_parts)) else None for n in node_names}
def _material(part: TexturePart, image: Image.Image) -> trimesh.visual.material.PBRMaterial:
@@ -634,8 +623,8 @@ def normalise_materials(
seen[id(mat)] = None
continue
metallic, roughness = _factors(mat)
- snake = to_snake(node)
- plan_text = plan_mats.get(snake) or plan_mats.get(to_snake(node.split("__", 1)[0])) or ""
+ key = part_key(node, plan_mats)
+ plan_text = plan_mats[key] if key else ""
verdict = classify(node, str(getattr(mat, "name", "") or ""), plan_text, metallic, roughness,
_base_rgb(mat))
if verdict is None:
diff --git a/harness/tests/core/test_names.py b/harness/tests/core/test_names.py
index cc9db3ef..a3484a92 100644
--- a/harness/tests/core/test_names.py
+++ b/harness/tests/core/test_names.py
@@ -10,7 +10,7 @@ from pathlib import Path
from codeverse3d.contracts.common import Track
from codeverse3d.contracts.plan import StaticPlan
-from codeverse3d.conventions import PASCAL_RE, split_instance, to_pascal, to_snake
+from codeverse3d.conventions import PASCAL_RE, part_key, split_instance, to_pascal, to_snake
from codeverse3d.languages.blender import lint_blender_source
from codeverse3d.languages.cadquery import lint_cadquery_source
from codeverse3d.languages.urdf import _IDENT as URDF_LINK_RE
@@ -108,3 +108,17 @@ def test_one_instance_rule_for_every_reader():
["Leg", "Shelf", "Shelf2", "Cart_800006", "Cart_801"]
assert _instance_base("DonkeyCart_800006") == "DonkeyCart_800006" and _instance_base("") == "overall"
assert _canon_target("leg_1", {"leg": "Leg"}) == "Leg_1"
+
+
+def test_one_part_rule_for_the_texture_pass_and_the_normaliser():
+ """N4: the texture pass stripped an instance suffix only when 2+ copies existed and the
+ normaliser never did, so a single ``Arm-2`` the contract gate accepts went untextured and
+ instanced legs kept their default factors. Both read ``conventions.part_key`` now."""
+ from codeverse3d.texturing.apply import node_part_lookup
+
+ plan = {"leg", "seat", "arm", "handle", "link", "cpu_2"}
+ rows = {"Leg_0": "leg", "Arm-2": "arm", "Handle.001": "handle", "Link__2": "link", "Leg_0__1": "leg",
+ "Seat": "seat", "CPU_2": "cpu_2", "Shelf": None}
+ assert {n: part_key(n, plan) for n in rows} == rows
+ parts = {k: k.upper() for k in plan}
+ assert node_part_lookup(list(rows), parts)["Arm-2"] == "ARM"
diff --git a/harness/tests/texturing/test_normalise.py b/harness/tests/texturing/test_normalise.py
index 71831c8b..d6187112 100644
--- a/harness/tests/texturing/test_normalise.py
+++ b/harness/tests/texturing/test_normalise.py
@@ -87,3 +87,14 @@ def test_nothing_to_do_writes_nothing_and_a_texture_is_never_second_guessed(tmp_
scene.export(textured)
rep = normalise_materials(textured, tmp_path / "out.glb")
assert not rep.changed() and rep.n_unchanged == 1
+
+
+def test_an_instanced_part_reads_its_plan_material(tmp_path: Path):
+ """N4: the normaliser matched a node to its plan part by exact name or link piece only, so
+ ``Leg_0`` never read the plan's "solid oak" and kept the untouched default."""
+ from types import SimpleNamespace as NS
+
+ glb = _glb(tmp_path, [("Leg_0", "Mat0", 0.0, 0.5, (150, 100, 60, 255))])
+ plan = NS(parts=[NS(name="Leg", material="solid oak", description="leg")])
+ rep = normalise_materials(glb, tmp_path / "out.glb", plan=plan)
+ assert [(c.node, c.family) for c in rep.changes] == [("Leg_0", "hardwood")]