objaverse.data.intelligence / scripts /apply_decomposition_from_json.py
milimlee's picture
Simplified the overall decomposition workflow.
dd55b12 verified
Raw History Blame Contribute Delete
32.9 kB
# =============================================================================
# HOW TO RUN - Verified in Blender v5.0.1
# =============================================================================
# This script must be executed through Blender, not standard Python.
#
# Example:
# blender --background --python apply_decomposition_from_json.py -- \
# --glb "path/to/scene.glb" \
# --json "path/to/decomposition.json" \
# --out_blend "path/to/output.blend"
#
# IMPORTANT:
# The "--" separator is required. Everything after it is passed to this script.
#
# Inputs:
# --glb Path to the source GLB/GLTF file
# --json Path to decomposition_mapping JSON file
# --out_blend Output .blend file with decomposition colors applied
#
# Optional:
# --tolerance (default: 1e-5) Matching tolerance for static meshes
# --report_json Output path for match report JSON
# =============================================================================
import bpy
import json
import random
import argparse
from mathutils import Vector
import sys
import os
# Optional local package path for Blender Python environments.
if "APPDATA" in os.environ:
pkg = os.path.join(os.environ["APPDATA"], "blender_packages")
sys.path.insert(0, pkg)
# =============================================================================
# Public tool configuration
# =============================================================================
NORMALISE_CONTAINER_NAME = "NORMALISE_CONTAINER"
EMISSION_STRENGTH = 0.6
DEFAULT_TOLERANCE = 1e-5
DEFAULT_REPORT_PATH_SUFFIX = ".decomposition_report.json"
# =============================================================================
# Logging / scene setup
# =============================================================================
def log(msg):
"""Print a namespaced message so command-line output is easy to scan."""
print(f"[apply_decomposition_from_json] {msg}")
def reset_scene():
"""
Clear the current Blender scene before importing the target GLB/GLTF.
This makes every run deterministic and prevents objects/materials from a
previous file from contaminating the decomposition mapping process.
"""
if bpy.ops.object.mode_set.poll():
try:
bpy.ops.object.mode_set(mode="OBJECT")
except Exception:
pass
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action="SELECT")
bpy.ops.object.delete(use_global=False)
for datablock_collection in (
bpy.data.meshes,
bpy.data.materials,
bpy.data.images,
bpy.data.textures,
bpy.data.curves,
bpy.data.armatures,
bpy.data.cameras,
bpy.data.lights,
bpy.data.node_groups,
):
for datablock in list(datablock_collection):
if datablock.users == 0:
try:
datablock_collection.remove(datablock)
except Exception:
pass
# =============================================================================
# Import / hierarchy helpers
# =============================================================================
def import_glb(glb_path):
"""Import a GLB/GLTF file into the clean Blender scene."""
bpy.ops.import_scene.gltf(filepath=glb_path)
def scene_bounds():
"""
Return the full scene bounds in world space.
Returns:
min_co: world-space minimum corner
max_co: world-space maximum corner
centre: world-space center
longest_side: longest scene dimension, clamped above zero
"""
corners = []
for obj in [o for o in bpy.context.scene.objects if o.type == "MESH"]:
for corner in obj.bound_box:
corners.append(obj.matrix_world @ Vector(corner))
if not corners:
zero = Vector((0.0, 0.0, 0.0))
return zero, zero, zero, 1.0
mn = Vector(map(min, zip(*corners)))
mx = Vector(map(max, zip(*corners)))
centre = (mn + mx) / 2.0
longest = max((mx - mn).x, (mx - mn).y, (mx - mn).z)
return mn, mx, centre, max(longest, 1e-6)
def normalise_scene():
"""
Center and uniformly scale the whole imported scene using a parent container.
Important:
The transform is applied to the container only, not directly to meshes.
This avoids breaking armatures, constraints, parent relationships, and
animated/rigged objects.
"""
_, _, centre, longest = scene_bounds()
scale_factor = 1.0 / longest
scene = bpy.context.scene
root_objects = [o for o in scene.objects if o.parent is None]
bpy.ops.object.empty_add(type="PLAIN_AXES", location=(0, 0, 0))
container = bpy.context.active_object
container.name = NORMALISE_CONTAINER_NAME
for obj in root_objects:
obj.parent = container
container.location = -centre * scale_factor
container.scale = (scale_factor, scale_factor, scale_factor)
bpy.context.view_layer.update()
return container
def all_descendants(root):
"""Return every descendant object below a root object."""
stack = list(root.children)
result = []
while stack:
obj = stack.pop()
result.append(obj)
stack.extend(list(obj.children))
return result
def collect_meshes_under_container(root):
"""Return all mesh objects below NORMALISE_CONTAINER."""
return [obj for obj in all_descendants(root) if obj.type == "MESH"]
# =============================================================================
# Animated / rigged mesh protection
# =============================================================================
def split_static_and_animated_meshes(root, anim_rig_names=None):
"""
Split visible meshes under NORMALISE_CONTAINER into static and animated lists.
Animated/rigged object names come exclusively from the JSON's ``anim_rig``
key (via ``anim_rig_names``). If that set is empty, all meshes are static.
Args:
root: The NORMALISE_CONTAINER object.
anim_rig_names: frozenset of object names from
``decomposition_mapping["anim_rig"]``.
"""
anim_rig_names = anim_rig_names or frozenset()
visible = [
o for o in collect_meshes_under_container(root)
if not o.hide_viewport and not o.hide_render and o.visible_get()
]
anim_meshes = [o for o in visible if o.name in anim_rig_names]
static_meshes = [o for o in visible if o.name not in anim_rig_names]
return static_meshes, anim_meshes
# =============================================================================
# Loose separation
# =============================================================================
def separate_loose_parts_under_normalise_container(protected_meshes=None, blockers=None, anim_rig_names=None):
"""
Separate static meshes into loose parts under NORMALISE_CONTAINER.
Animated/rigged meshes (identified by name via ``anim_rig_names``) and any
explicitly protected or blocker meshes are skipped.
Args:
protected_meshes:
Meshes that must not be loose-separated. Usually animated/rigged meshes.
blockers:
Optional meshes to skip, such as large planes or environment spheres.
anim_rig_names:
frozenset of object names from ``decomposition_mapping["anim_rig"]``.
Returns:
List of newly created mesh objects generated by Blender's loose separation.
"""
protected_meshes = protected_meshes or []
blockers = blockers or []
anim_rig_names = anim_rig_names or frozenset()
root = bpy.data.objects.get(NORMALISE_CONTAINER_NAME)
if root is None:
log("NORMALISE_CONTAINER not found.")
return []
exclude_ptrs = {obj.as_pointer() for obj in protected_meshes + blockers if obj is not None}
target_meshes = [
obj for obj in root.children_recursive
if obj.type == "MESH"
and obj.as_pointer() not in exclude_ptrs
and obj.name not in anim_rig_names
]
if not target_meshes:
log("No static target meshes found for LOOSE separation.")
return []
view_layer = bpy.context.view_layer
created_objects = []
active_obj = view_layer.objects.active
if active_obj is not None and bpy.ops.object.mode_set.poll():
try:
bpy.ops.object.mode_set(mode="OBJECT")
except Exception:
pass
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action="DESELECT")
log(f"Perform LOOSE only on static meshes. target_mesh_count={len(target_meshes)}")
for idx, obj in enumerate(target_meshes, start=1):
if obj.name not in bpy.data.objects:
continue
prev_hide_viewport = obj.hide_viewport
prev_hide_render = obj.hide_render
prev_hide_select = obj.hide_select
try:
obj.hide_viewport = False
obj.hide_select = False
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
view_layer.objects.active = obj
before_ptrs = {
o.as_pointer()
for o in bpy.data.objects
if o.type == "MESH"
}
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode="EDIT")
else:
log(f"Failed on {obj.name}: cannot enter EDIT mode")
continue
bpy.ops.mesh.select_all(action="SELECT")
bpy.ops.mesh.separate(type="LOOSE")
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode="OBJECT")
new_objs = [
o for o in bpy.data.objects
if o.type == "MESH" and o.as_pointer() not in before_ptrs
]
created_objects.extend(new_objs)
if idx % 25 == 0 or idx == len(target_meshes):
log(f"LOOSE progress: {idx}/{len(target_meshes)}")
except Exception as exc:
log(f"Failed on {obj.name}: {exc}")
try:
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode="OBJECT")
except Exception:
pass
finally:
if obj.name in bpy.data.objects:
obj.hide_viewport = prev_hide_viewport
obj.hide_render = prev_hide_render
obj.hide_select = prev_hide_select
return created_objects
# =============================================================================
# Geometry metadata helpers
# =============================================================================
def world_bbox_min_max(obj):
"""Return world-space bounding box min/max corners for one object."""
corners = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
mn = Vector((min(v.x for v in corners), min(v.y for v in corners), min(v.z for v in corners)))
mx = Vector((max(v.x for v in corners), max(v.y for v in corners), max(v.z for v in corners)))
return mn, mx
def bbox_size(obj):
"""Return world-space bounding box size for one object."""
mn, mx = world_bbox_min_max(obj)
return mx - mn
def object_center_world(obj, precision=6):
"""Return rounded world-space bounding box center."""
mn, mx = world_bbox_min_max(obj)
center = (mn + mx) * 0.5
return [round(float(center.x), precision), round(float(center.y), precision), round(float(center.z), precision)]
def object_bbox_size_world(obj, precision=6):
"""Return rounded world-space bounding box size."""
size = bbox_size(obj)
return [round(float(size.x), precision), round(float(size.y), precision), round(float(size.z), precision)]
def object_poly_count(obj):
"""Return polygon count for a mesh object."""
if obj is None or obj.type != "MESH" or obj.data is None:
return 0
return int(len(obj.data.polygons))
def object_vertex_count(obj):
"""Return vertex count for a mesh object."""
if obj is None or obj.type != "MESH" or obj.data is None:
return 0
return int(len(obj.data.vertices))
def object_bbox_diag_world(obj):
"""Return rounded world-space bounding box diagonal length."""
size = bbox_size(obj)
return round(float(size.length), 6)
def object_bbox_size_world_sorted(obj, precision=6):
"""Return sorted bbox dimensions, useful when axes are not semantically important."""
size = object_bbox_size_world(obj, precision=precision)
return sorted(size)
def mapping_entry_with_metadata(value, anim_rig_names=None):
"""
Convert a Blender object or object name into a JSON-style decomposition entry.
This mirrors the metadata used in Objaverse Data Intelligence decomposition
mapping. The key "is_rigged_or_animated" helps users understand why some
meshes are name-matched instead of geometry-approximated.
Args:
value: A Blender object or an object name string.
anim_rig_names: frozenset of object names from
``decomposition_mapping["anim_rig"]``.
"""
anim_rig_names = anim_rig_names or frozenset()
obj = value if hasattr(value, "name") else bpy.data.objects.get(str(value))
name = obj.name if obj is not None else str(value)
if obj is None or obj.type != "MESH":
return {
"name": name,
"center": None,
"bbox_size": None,
"poly_count": 0,
"vertex_count": 0,
"bbox_diag": 0.0,
"bbox_size_sorted": None,
"is_rigged_or_animated": False,
}
return {
"name": name,
"center": object_center_world(obj),
"bbox_size": object_bbox_size_world(obj),
"poly_count": object_poly_count(obj),
"vertex_count": object_vertex_count(obj),
"bbox_diag": object_bbox_diag_world(obj),
"bbox_size_sorted": object_bbox_size_world_sorted(obj),
"is_rigged_or_animated": name in anim_rig_names,
}
# =============================================================================
# Matching helpers
# =============================================================================
def _vec_diff_sq(a, b):
"""Squared difference between two numeric vectors."""
return sum((float(x) - float(y)) ** 2 for x, y in zip(a, b))
def _maybe_vec_diff_sq(a, b, missing_penalty=1e12):
"""Squared vector difference with a large penalty for missing metadata."""
if a is None or b is None:
return missing_penalty
return _vec_diff_sq(a, b)
def _maybe_abs_diff(a, b, missing_penalty=1e12):
"""Absolute scalar difference with a large penalty for missing metadata."""
if a is None or b is None:
return missing_penalty
return abs(float(a) - float(b))
def metadata_score(candidate_meta, target_meta):
"""
Approximate similarity score between candidate metadata and target metadata.
Lower is better.
Important:
This approximation is used only for static meshes. Animated/rigged
meshes are intentionally excluded from this path.
"""
score = 0.0
if target_meta.get("poly_count") is not None:
score += abs(int(candidate_meta.get("poly_count", 0)) - int(target_meta["poly_count"])) * 1000000.0
if target_meta.get("vertex_count") is not None:
score += abs(int(candidate_meta.get("vertex_count", 0)) - int(target_meta["vertex_count"])) * 10000.0
score += _maybe_abs_diff(candidate_meta.get("bbox_diag"), target_meta.get("bbox_diag")) * 100.0
score += _maybe_vec_diff_sq(candidate_meta.get("center"), target_meta.get("center"))
score += _maybe_vec_diff_sq(candidate_meta.get("bbox_size"), target_meta.get("bbox_size"))
score += _maybe_vec_diff_sq(candidate_meta.get("bbox_size_sorted"), target_meta.get("bbox_size_sorted"))
return score
def metadata_exact_match(candidate_meta, target_meta, tolerance=DEFAULT_TOLERANCE):
"""
Return True when candidate metadata exactly matches target metadata.
Integer fields must match exactly. Floating-point geometry fields may differ
within tolerance.
"""
required_exact_int_fields = ("poly_count", "vertex_count")
for field in required_exact_int_fields:
target_val = target_meta.get(field)
if target_val is not None and candidate_meta.get(field) != target_val:
return False
vec_fields = ("center", "bbox_size", "bbox_size_sorted")
for field in vec_fields:
target_vec = target_meta.get(field)
cand_vec = candidate_meta.get(field)
if target_vec is None:
continue
if cand_vec is None:
return False
for a, b in zip(cand_vec, target_vec):
if abs(float(a) - float(b)) > tolerance:
return False
target_diag = target_meta.get("bbox_diag")
cand_diag = candidate_meta.get("bbox_diag")
if target_diag is not None:
if cand_diag is None or abs(float(cand_diag) - float(target_diag)) > tolerance:
return False
return True
def build_candidate_pool(meshes):
"""
Build a one-use candidate pool.
Each decomposition mapping entry consumes one candidate object. This avoids
accidentally applying the same object to multiple decomposition components.
"""
pool = []
for obj in meshes:
meta = mapping_entry_with_metadata(obj)
pool.append({
"object": obj,
"meta": meta,
"used": False,
})
return pool
def _entry_has_any_geometry_metadata(entry):
"""Return True if a mapping entry contains usable geometry metadata."""
if not isinstance(entry, dict):
return False
return any(
entry.get(k) is not None
for k in ("center", "bbox_size", "poly_count", "vertex_count", "bbox_diag", "bbox_size_sorted")
)
def _entry_requests_animated_mesh(entry):
"""
Return True when the JSON entry explicitly says this is animated/rigged.
"""
return isinstance(entry, dict) and bool(entry.get("is_rigged_or_animated", False))
def find_name_match_for_animated_entry(entry, animated_pool):
"""
Match an animated/rigged mesh by object name only.
Animated/rigged meshes should not be loose-separated and should not use
geometry-nearest approximation because animation, armature, constraints,
or shape-key state can make location/bbox metadata less reliable.
"""
target_name = entry.get("name") if isinstance(entry, dict) else str(entry)
if not target_name:
return None, "animated_name_missing", 0, None
matches = [
item for item in animated_pool
if (not item["used"]) and item["object"].name == target_name
]
if len(matches) == 1:
matches[0]["used"] = True
return matches[0]["object"], "animated_name", len(matches), matches[0]["meta"]
if len(matches) > 1:
matches.sort(key=lambda item: item["object"].name)
matches[0]["used"] = True
return matches[0]["object"], "animated_name_collision", len(matches), matches[0]["meta"]
return None, "animated_name_not_found", 0, None
def find_static_match_for_entry(entry, static_pool, tolerance=DEFAULT_TOLERANCE):
"""
Match a static mesh using metadata first, then name fallback.
Matching order:
1. Exact metadata match
2. Metadata tie-break by object name
3. Metadata tie-break by score
4. Metadata-nearest approximation
5. Name fallback if no metadata exists
This function must only receive static meshes.
"""
has_metadata = _entry_has_any_geometry_metadata(entry)
if has_metadata:
exact = []
for item in static_pool:
if item["used"]:
continue
if metadata_exact_match(item["meta"], entry, tolerance=tolerance):
exact.append(item)
if len(exact) == 1:
exact[0]["used"] = True
return exact[0]["object"], "metadata_exact_unique", len(exact), exact[0]["meta"]
if len(exact) > 1:
preferred_name = entry.get("name") if isinstance(entry, dict) else str(entry)
same_name = [item for item in exact if item["object"].name == preferred_name]
if len(same_name) == 1:
same_name[0]["used"] = True
return same_name[0]["object"], "metadata_exact_tiebreak_name", len(exact), same_name[0]["meta"]
ranked = sorted(exact, key=lambda item: (metadata_score(item["meta"], entry), item["object"].name))
ranked[0]["used"] = True
return ranked[0]["object"], "metadata_exact_tiebreak_score", len(exact), ranked[0]["meta"]
ranked_all = []
for item in static_pool:
if item["used"]:
continue
ranked_all.append((metadata_score(item["meta"], entry), item))
if ranked_all:
ranked_all.sort(key=lambda x: (x[0], x[1]["object"].name))
best_score, best = ranked_all[0]
near_mode = "metadata_nearest" if best_score < 1e12 else "metadata_missing_fallback"
best["used"] = True
return best["object"], near_mode, 0, best["meta"]
target_name = entry.get("name") if isinstance(entry, dict) else str(entry)
by_name = [
item for item in static_pool
if (not item["used"]) and item["object"].name == target_name
]
if by_name:
by_name[0]["used"] = True
return by_name[0]["object"], "name", len(by_name), by_name[0]["meta"]
return None, "not_found", 0, None
def find_match_for_entry(entry, static_pool, animated_pool, tolerance=DEFAULT_TOLERANCE):
"""
Main object-recovery function.
Public behavior:
- Animated/rigged objects are recovered by object name.
- Static objects are recovered by geometry metadata.
- Metadata-nearest approximation is never applied to animated/rigged meshes.
"""
if _entry_requests_animated_mesh(entry):
return find_name_match_for_animated_entry(entry, animated_pool)
anim_obj, anim_mode, anim_count, anim_meta = find_name_match_for_animated_entry(entry, animated_pool)
if anim_obj is not None:
return anim_obj, anim_mode, anim_count, anim_meta
return find_static_match_for_entry(entry, static_pool, tolerance=tolerance)
# =============================================================================
# Coloring helpers
# =============================================================================
def random_component_color(component_id):
"""
Create a deterministic soft pastel color for a decomposition component.
Lower saturation/value keeps the verification view less blown out.
"""
rng = random.Random(str(component_id))
return (
rng.uniform(0.25, 0.65),
rng.uniform(0.25, 0.65),
rng.uniform(0.25, 0.65),
1.0,
)
def ensure_emission_material(component_id, color, strength=EMISSION_STRENGTH):
"""
Create or reuse a simple emission material for decomposition preview.
"""
mat_name = f"VERIFY_DECOMP_{component_id}"
mat = bpy.data.materials.get(mat_name)
if mat is None:
mat = bpy.data.materials.new(name=mat_name)
mat.use_nodes = True
nt = mat.node_tree
nodes = nt.nodes
links = nt.links
nodes.clear()
emission = nodes.new(type="ShaderNodeEmission")
output = nodes.new(type="ShaderNodeOutputMaterial")
emission.inputs["Color"].default_value = color
emission.inputs["Strength"].default_value = strength
links.new(emission.outputs["Emission"], output.inputs["Surface"])
return mat
def apply_material_to_object(obj, mat):
"""Replace the object's visible material slots with the verification material."""
if obj.data is None:
return
if len(obj.data.materials) == 0:
obj.data.materials.append(mat)
else:
for i in range(len(obj.data.materials)):
obj.data.materials[i] = mat
# =============================================================================
# JSON loading
# =============================================================================
def load_decomposition_mapping_from_json(json_path):
"""
Load decomposition_mapping from supported JSON formats.
Supported:
1. Direct scene JSON:
{"decomposition_mapping": {...}}
2. UID-wrapped JSON:
{"<uid>": {"decomposition_mapping": {...}}}
"""
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict) and "decomposition_mapping" in data:
return data["decomposition_mapping"], data
if isinstance(data, dict) and len(data) == 1:
first_val = next(iter(data.values()))
if isinstance(first_val, dict) and "decomposition_mapping" in first_val:
return first_val["decomposition_mapping"], first_val
raise ValueError("Could not find decomposition_mapping in JSON.")
# =============================================================================
# Main public function
# =============================================================================
def apply_decomposition_from_json(glb_path, json_path, out_blend_path, tolerance=DEFAULT_TOLERANCE, report_path=None):
"""
Apply/recover Objaverse Data Intelligence decomposition mapping on a GLB/GLTF.
Inputs:
glb_path:
Source GLB/GLTF file.
json_path:
JSON file containing decomposition_mapping.
out_blend_path:
Output .blend path. The saved blend contains colored decomposition
components.
tolerance:
Floating-point tolerance for exact metadata matching.
report_path:
Optional output report JSON path.
Output:
- A colored .blend file for visual inspection.
- A JSON report showing match modes, collisions, matched entries, and
unmatched entries.
"""
reset_scene()
import_glb(glb_path)
container = normalise_scene()
decomposition_mapping, raw_json = load_decomposition_mapping_from_json(json_path)
requires_mesh_separation = bool(raw_json.get("summary", {}).get("requires_mesh_separation", True))
# Build the authoritative set of anim/rig object names from the JSON.
# The analysis pipeline that produced the JSON already inspected every
# Blender property; we use its conclusion directly instead of re-running
# property checks at apply time.
anim_rig_names = frozenset(decomposition_mapping.get("anim_rig", []))
if anim_rig_names:
log(f"JSON anim_rig objects ({len(anim_rig_names)}): {sorted(anim_rig_names)}")
else:
log("No anim_rig entries in decomposition_mapping; falling back to Blender property inspection.")
static_before_loose, animated_before_loose = split_static_and_animated_meshes(
container, anim_rig_names=anim_rig_names
)
log(f"Initial mesh split: static={len(static_before_loose)}, animated_or_rigged={len(animated_before_loose)}")
if requires_mesh_separation:
separate_loose_parts_under_normalise_container(
protected_meshes=animated_before_loose,
blockers=[],
anim_rig_names=anim_rig_names,
)
else:
log("JSON summary says requires_mesh_separation=False. Skipping LOOSE separation.")
static_meshes, animated_meshes = split_static_and_animated_meshes(
container, anim_rig_names=anim_rig_names
)
static_pool = build_candidate_pool(static_meshes)
animated_pool = build_candidate_pool(animated_meshes)
log(f"Candidate pools after LOOSE: static={len(static_pool)}, animated_or_rigged={len(animated_pool)}")
report = {
"total_components": len(decomposition_mapping),
"total_entries": 0,
"matched_entries": 0,
"unmatched_entries": 0,
"match_modes": {},
"collision_entries": 0,
"static_candidate_count": len(static_pool),
"animated_candidate_count": len(animated_pool),
"requires_mesh_separation": requires_mesh_separation,
"component_reports": {},
}
for component_id, entries in decomposition_mapping.items():
color = random_component_color(component_id)
mat = ensure_emission_material(component_id, color)
component_report = []
if not isinstance(entries, list):
entries = [entries]
for entry in entries:
report["total_entries"] += 1
match_obj, mode, candidate_count, matched_meta = find_match_for_entry(
entry,
static_pool=static_pool,
animated_pool=animated_pool,
tolerance=tolerance,
)
report["match_modes"][mode] = report["match_modes"].get(mode, 0) + 1
item_name = entry.get("name") if isinstance(entry, dict) else str(entry)
row = {
"requested": item_name,
"mode": mode,
"candidate_count": candidate_count,
"matched_object": match_obj.name if match_obj else None,
"requested_meta": entry if isinstance(entry, dict) else {"name": str(entry)},
"matched_meta": matched_meta,
}
if candidate_count > 1:
report["collision_entries"] += 1
if match_obj is not None:
apply_material_to_object(match_obj, mat)
report["matched_entries"] += 1
else:
report["unmatched_entries"] += 1
component_report.append(row)
report["component_reports"][component_id] = component_report
bpy.ops.wm.save_as_mainfile(filepath=out_blend_path)
if report_path is None:
report_path = out_blend_path + DEFAULT_REPORT_PATH_SUFFIX
with open(report_path, "w", encoding="utf-8") as f:
json.dump(report, f, indent=2, ensure_ascii=False)
log(f"Saved blend file: {out_blend_path}")
log(f"Saved report: {report_path}")
log(f"Matched {report['matched_entries']} / {report['total_entries']} mapping entries")
log(f"Collision entries: {report['collision_entries']}")
log(f"Match modes: {report['match_modes']}")
return report
# =============================================================================
# CLI
# =============================================================================
def parse_args(argv=None):
parser = argparse.ArgumentParser(
description=(
"Apply Objaverse Data Intelligence decomposition_mapping JSON to a "
"GLB/GLTF scene and save a colored Blender verification file."
)
)
parser.add_argument("--glb", required=True, help="Source GLB/GLTF path")
parser.add_argument("--json", required=True, help="JSON file containing decomposition_mapping")
parser.add_argument("--out_blend", required=True, help="Output .blend path")
parser.add_argument(
"--tolerance",
type=float,
default=DEFAULT_TOLERANCE,
help="Metadata comparison tolerance for static meshes",
)
parser.add_argument(
"--report_json",
default=None,
help="Optional output JSON report path. Default: <out_blend>.decomposition_report.json",
)
return parser.parse_args(argv)
def main():
argv = []
if "--" in sys.argv:
argv = sys.argv[sys.argv.index("--") + 1:]
args = parse_args(argv)
apply_decomposition_from_json(
glb_path=args.glb,
json_path=args.json,
out_blend_path=args.out_blend,
tolerance=args.tolerance,
report_path=args.report_json,
)
if __name__ == "__main__":
main()