milimlee commited on
Commit
15ed62c
·
verified ·
1 Parent(s): 8ebc895

Upload 32 files

Browse files
Files changed (32) hide show
  1. LICENSE +14 -0
  2. attribution/objaverse_asset_attribution.csv.gz +3 -0
  3. data/objaverse_data_intelligence_datatable.parquet +3 -0
  4. readme_files/images/anim_1.gif +3 -0
  5. readme_files/images/anim_2.gif +3 -0
  6. readme_files/images/anim_3.gif +3 -0
  7. readme_files/images/anim_4.gif +3 -0
  8. readme_files/images/anim_5.gif +3 -0
  9. readme_files/images/anim_6.gif +3 -0
  10. readme_files/images/decomposition_count.png +3 -0
  11. readme_files/images/has_color_material.png +3 -0
  12. readme_files/images/has_hidden_interior.png +3 -0
  13. readme_files/images/has_texture.png +3 -0
  14. readme_files/images/has_transparency.png +3 -0
  15. readme_files/images/hidden_interior_detection.png +3 -0
  16. readme_files/images/json_metadata.png +3 -0
  17. readme_files/images/json_metadata_special_case.png +3 -0
  18. readme_files/images/large_plane.png +3 -0
  19. readme_files/images/large_sphere_cube.png +3 -0
  20. readme_files/images/raw_scan.png +3 -0
  21. readme_files/images/requires_mesh_separation.png +3 -0
  22. readme_files/images/structural_decomposition_count_n_mapping.png +3 -0
  23. readme_files/images/uid_grid_8x7_half_half.png +3 -0
  24. readme_files/images/uses_default_material.png +3 -0
  25. readme_files/stats/analysis_time_range_distribution.png +3 -0
  26. readme_files/stats/decomposition_type_modified.png +3 -0
  27. readme_files/stats/material_percentages.png +3 -0
  28. readme_files/stats/mesh_separation_percentage.png +3 -0
  29. readme_files/stats/object_count_range_distribution.png +3 -0
  30. readme_files/stats/poly_count_range_distribution.png +3 -0
  31. readme_files/stats/scene_quality_type_percentages.png +3 -0
  32. scripts/apply_decomposition_from_json.py +980 -0
LICENSE ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Open Data Commons Attribution License (ODC-By) v1.0
2
+
3
+ This dataset is licensed under the Open Data Commons Attribution License.
4
+
5
+ You are free to:
6
+ - Share
7
+ - Create
8
+ - Adapt
9
+
10
+ As long as you:
11
+ - Attribute the source appropriately.
12
+
13
+ Full license text:
14
+ https://opendatacommons.org/licenses/by/1-0/
attribution/objaverse_asset_attribution.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1e803c94964cd5025cac57c958a884a4e489830eb8a5e026590e36406bf86774
3
+ size 40852079
data/objaverse_data_intelligence_datatable.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bacfbf3a006f92bdba20185898ad9f522b71e0a8c999abea9b5b3c6da84f98fb
3
+ size 31915265
readme_files/images/anim_1.gif ADDED

Git LFS Details

  • SHA256: 5ef1e1734ab9904800337ae03c3380a800355a7fa0cc4d7053dfb6d90cc4e701
  • Pointer size: 133 Bytes
  • Size of remote file: 10.9 MB
readme_files/images/anim_2.gif ADDED

Git LFS Details

  • SHA256: c7e6678d054be1926504d97f9c55b4c3dae3cee3eace8c7431211f3a257e04f4
  • Pointer size: 133 Bytes
  • Size of remote file: 17.6 MB
readme_files/images/anim_3.gif ADDED

Git LFS Details

  • SHA256: b42b37b3d0249afea8d111f822b7155cac06b474702a13702ba69b1a87f90015
  • Pointer size: 133 Bytes
  • Size of remote file: 14.2 MB
readme_files/images/anim_4.gif ADDED

Git LFS Details

  • SHA256: f03146b299c86b63908475809f21da381fb2a47e462d3cfba384075b3e2da21e
  • Pointer size: 133 Bytes
  • Size of remote file: 14 MB
readme_files/images/anim_5.gif ADDED

Git LFS Details

  • SHA256: 33a388718c62f4906bc983d128a64431edce363e47667b012fc79534a64b0df3
  • Pointer size: 133 Bytes
  • Size of remote file: 14.5 MB
readme_files/images/anim_6.gif ADDED

Git LFS Details

  • SHA256: 93cfce669d0ae8d85c9df3a7979dc7a70a89d9454e8d20cab754c687d92fbd0e
  • Pointer size: 133 Bytes
  • Size of remote file: 14.9 MB
readme_files/images/decomposition_count.png ADDED

Git LFS Details

  • SHA256: d08090a450852bf03ed566db5e3dd63e6da701fa05d7578709ccf7ee3c12aecd
  • Pointer size: 132 Bytes
  • Size of remote file: 3.15 MB
readme_files/images/has_color_material.png ADDED

Git LFS Details

  • SHA256: dc3209d0acde007ca9ef16840429b0bb3cdb4cd58ee75acf9b53d731c073ab3e
  • Pointer size: 132 Bytes
  • Size of remote file: 1.37 MB
readme_files/images/has_hidden_interior.png ADDED

Git LFS Details

  • SHA256: b23a03c70dba7bd76cfe75f0e3bc1109dd0b6dcefb4d17c910058e4829a416ac
  • Pointer size: 132 Bytes
  • Size of remote file: 2.92 MB
readme_files/images/has_texture.png ADDED

Git LFS Details

  • SHA256: 4cca4b8dc626cb193082dc68b9658348a18e19f73d364ebd807618e081a65bde
  • Pointer size: 132 Bytes
  • Size of remote file: 1.29 MB
readme_files/images/has_transparency.png ADDED

Git LFS Details

  • SHA256: 63ad68e0d31830a29238dbd55c605d3bf8c03308d14d7e855dcf204a6d372817
  • Pointer size: 132 Bytes
  • Size of remote file: 1.15 MB
readme_files/images/hidden_interior_detection.png ADDED

Git LFS Details

  • SHA256: f98cf839db05149cd4716bbb12c36ce6edef489b47dce95eb9e01a1ca41a82d4
  • Pointer size: 132 Bytes
  • Size of remote file: 1.5 MB
readme_files/images/json_metadata.png ADDED

Git LFS Details

  • SHA256: 028f55a9dd7af8a5b97215783ee104c4e96a48f35f4ec915dd4100427ed39f52
  • Pointer size: 132 Bytes
  • Size of remote file: 1.59 MB
readme_files/images/json_metadata_special_case.png ADDED

Git LFS Details

  • SHA256: a76532238fff6ebc9f2962bac6d9ede9d4cb9220b1088ed556c5c4bad8a4f2bf
  • Pointer size: 131 Bytes
  • Size of remote file: 251 kB
readme_files/images/large_plane.png ADDED

Git LFS Details

  • SHA256: 771251b56d7b1f348f04bb2d0ed091358fc3d5487082e21cdea4f7ab78af26e4
  • Pointer size: 132 Bytes
  • Size of remote file: 1.79 MB
readme_files/images/large_sphere_cube.png ADDED

Git LFS Details

  • SHA256: b6c04888dca2edd3d340e60a396845b20c392cd53957fe6d98b114e7922c136c
  • Pointer size: 132 Bytes
  • Size of remote file: 1.27 MB
readme_files/images/raw_scan.png ADDED

Git LFS Details

  • SHA256: 0748949c2993861cafd49df04e294a9ae5a97a19b84ba5fd9ce90f3181a9f573
  • Pointer size: 132 Bytes
  • Size of remote file: 2.63 MB
readme_files/images/requires_mesh_separation.png ADDED

Git LFS Details

  • SHA256: a68cd8f7a3ad0d35b9acb69c8d69ecccbee0fa1882b2c5ec9621196dcdf0e259
  • Pointer size: 132 Bytes
  • Size of remote file: 3.15 MB
readme_files/images/structural_decomposition_count_n_mapping.png ADDED

Git LFS Details

  • SHA256: 4bb7bb0a42cdf08471bfb3fe6cde16d4f68b4be21e150a8c2a7c9a9d87477f04
  • Pointer size: 132 Bytes
  • Size of remote file: 1.24 MB
readme_files/images/uid_grid_8x7_half_half.png ADDED

Git LFS Details

  • SHA256: bf2198a20f26b0ed2f0336805e43299e5853a034a967a8d5f6c1dd6fbbb557f9
  • Pointer size: 132 Bytes
  • Size of remote file: 2.63 MB
readme_files/images/uses_default_material.png ADDED

Git LFS Details

  • SHA256: 89dff793535760af33f1a9010117dbb65cd551c0dc6a1481ae37f7649d07bd29
  • Pointer size: 131 Bytes
  • Size of remote file: 900 kB
readme_files/stats/analysis_time_range_distribution.png ADDED

Git LFS Details

  • SHA256: 14b0d0e27fadd147e997375727d51966135ebaffd71e78a5f2eacfe8de8a6d8c
  • Pointer size: 131 Bytes
  • Size of remote file: 143 kB
readme_files/stats/decomposition_type_modified.png ADDED

Git LFS Details

  • SHA256: d5f0dfb66a108bc229a23ef57286a9e378d216b3bcd78db8b2b0bc3399fd53de
  • Pointer size: 131 Bytes
  • Size of remote file: 124 kB
readme_files/stats/material_percentages.png ADDED

Git LFS Details

  • SHA256: a7bc3706ed1f0b8a2d7e106211223b38286a8932b349357e9a99f8489d0bb909
  • Pointer size: 131 Bytes
  • Size of remote file: 166 kB
readme_files/stats/mesh_separation_percentage.png ADDED

Git LFS Details

  • SHA256: 2e5eb8cfd82c32234a8aa2b0ce16b7cd13dc832b60cab9121c80712bc0c864af
  • Pointer size: 130 Bytes
  • Size of remote file: 72.9 kB
readme_files/stats/object_count_range_distribution.png ADDED

Git LFS Details

  • SHA256: a366e9a02901a65fbf35b42d1c51fa31d5c4dcda677c210d2ce3de662c262047
  • Pointer size: 131 Bytes
  • Size of remote file: 147 kB
readme_files/stats/poly_count_range_distribution.png ADDED

Git LFS Details

  • SHA256: 9d31c5700623cb883267e3914047593d99c47f03063fe5585b3ce4c7dedd6006
  • Pointer size: 131 Bytes
  • Size of remote file: 113 kB
readme_files/stats/scene_quality_type_percentages.png ADDED

Git LFS Details

  • SHA256: 55fb64707012cd6dcaa14597627c2d9eb974fd1e728ade353d225ed669f44d1d
  • Pointer size: 131 Bytes
  • Size of remote file: 186 kB
scripts/apply_decomposition_from_json.py ADDED
@@ -0,0 +1,980 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # HOW TO RUN - Verified in Blender v5.0.1
3
+ # =============================================================================
4
+ # This script must be executed through Blender, not standard Python.
5
+ #
6
+ # Example:
7
+ # blender --background --python apply_decomposition_from_json.py -- \
8
+ # --glb "path/to/scene.glb" \
9
+ # --json "path/to/decomposition.json" \
10
+ # --out_blend "path/to/output.blend"
11
+ #
12
+ # IMPORTANT:
13
+ # The "--" separator is required. Everything after it is passed to this script.
14
+ #
15
+ # Inputs:
16
+ # --glb Path to the source GLB/GLTF file
17
+ # --json Path to decomposition_mapping JSON file
18
+ # --out_blend Output .blend file with decomposition colors applied
19
+ #
20
+ # Optional:
21
+ # --tolerance (default: 1e-5) Matching tolerance for static meshes
22
+ # --report_json Output path for match report JSON
23
+ # =============================================================================
24
+
25
+ import bpy
26
+ import json
27
+ import random
28
+ import argparse
29
+ from mathutils import Vector
30
+
31
+ import sys
32
+ import os
33
+
34
+ # Optional local package path for Blender Python environments.
35
+ if "APPDATA" in os.environ:
36
+ pkg = os.path.join(os.environ["APPDATA"], "blender_packages")
37
+ sys.path.insert(0, pkg)
38
+
39
+
40
+ # =============================================================================
41
+ # Public tool configuration
42
+ # =============================================================================
43
+
44
+ NORMALISE_CONTAINER_NAME = "NORMALISE_CONTAINER"
45
+ EMISSION_STRENGTH = 0.6
46
+ DEFAULT_TOLERANCE = 1e-5
47
+ DEFAULT_REPORT_PATH_SUFFIX = ".decomposition_report.json"
48
+
49
+
50
+ # =============================================================================
51
+ # Logging / scene setup
52
+ # =============================================================================
53
+
54
+ def log(msg):
55
+ """Print a namespaced message so command-line output is easy to scan."""
56
+ print(f"[apply_decomposition_from_json] {msg}")
57
+
58
+
59
+ def reset_scene():
60
+ """
61
+ Clear the current Blender scene before importing the target GLB/GLTF.
62
+
63
+ This makes every run deterministic and prevents objects/materials from a
64
+ previous file from contaminating the decomposition mapping process.
65
+ """
66
+ if bpy.ops.object.mode_set.poll():
67
+ try:
68
+ bpy.ops.object.mode_set(mode="OBJECT")
69
+ except Exception:
70
+ pass
71
+
72
+ if bpy.ops.object.select_all.poll():
73
+ bpy.ops.object.select_all(action="SELECT")
74
+ bpy.ops.object.delete(use_global=False)
75
+
76
+ for datablock_collection in (
77
+ bpy.data.meshes,
78
+ bpy.data.materials,
79
+ bpy.data.images,
80
+ bpy.data.textures,
81
+ bpy.data.curves,
82
+ bpy.data.armatures,
83
+ bpy.data.cameras,
84
+ bpy.data.lights,
85
+ bpy.data.node_groups,
86
+ ):
87
+ for datablock in list(datablock_collection):
88
+ if datablock.users == 0:
89
+ try:
90
+ datablock_collection.remove(datablock)
91
+ except Exception:
92
+ pass
93
+
94
+
95
+ # =============================================================================
96
+ # Import / hierarchy helpers
97
+ # =============================================================================
98
+
99
+ def import_glb(glb_path):
100
+ """Import a GLB/GLTF file into the clean Blender scene."""
101
+ bpy.ops.import_scene.gltf(filepath=glb_path)
102
+
103
+
104
+ def scene_bounds():
105
+ """
106
+ Return the full scene bounds in world space.
107
+
108
+ Returns:
109
+ min_co: world-space minimum corner
110
+ max_co: world-space maximum corner
111
+ centre: world-space center
112
+ longest_side: longest scene dimension, clamped above zero
113
+ """
114
+ corners = []
115
+
116
+ for obj in [o for o in bpy.context.scene.objects if o.type == "MESH"]:
117
+ for corner in obj.bound_box:
118
+ corners.append(obj.matrix_world @ Vector(corner))
119
+
120
+ if not corners:
121
+ zero = Vector((0.0, 0.0, 0.0))
122
+ return zero, zero, zero, 1.0
123
+
124
+ mn = Vector(map(min, zip(*corners)))
125
+ mx = Vector(map(max, zip(*corners)))
126
+ centre = (mn + mx) / 2.0
127
+ longest = max((mx - mn).x, (mx - mn).y, (mx - mn).z)
128
+
129
+ return mn, mx, centre, max(longest, 1e-6)
130
+
131
+
132
+ def normalise_scene():
133
+ """
134
+ Center and uniformly scale the whole imported scene using a parent container.
135
+
136
+ Important:
137
+ The transform is applied to the container only, not directly to meshes.
138
+ This avoids breaking armatures, constraints, parent relationships, and
139
+ animated/rigged objects.
140
+ """
141
+ _, _, centre, longest = scene_bounds()
142
+ scale_factor = 1.0 / longest
143
+
144
+ scene = bpy.context.scene
145
+ root_objects = [o for o in scene.objects if o.parent is None]
146
+
147
+ bpy.ops.object.empty_add(type="PLAIN_AXES", location=(0, 0, 0))
148
+ container = bpy.context.active_object
149
+ container.name = NORMALISE_CONTAINER_NAME
150
+
151
+ for obj in root_objects:
152
+ obj.parent = container
153
+
154
+ container.location = -centre * scale_factor
155
+ container.scale = (scale_factor, scale_factor, scale_factor)
156
+
157
+ bpy.context.view_layer.update()
158
+ return container
159
+
160
+
161
+ def all_descendants(root):
162
+ """Return every descendant object below a root object."""
163
+ stack = list(root.children)
164
+ result = []
165
+
166
+ while stack:
167
+ obj = stack.pop()
168
+ result.append(obj)
169
+ stack.extend(list(obj.children))
170
+
171
+ return result
172
+
173
+
174
+ def collect_meshes_under_container(root):
175
+ """Return all mesh objects below NORMALISE_CONTAINER."""
176
+ return [obj for obj in all_descendants(root) if obj.type == "MESH"]
177
+
178
+
179
+ # =============================================================================
180
+ # Animated / rigged mesh protection
181
+ # =============================================================================
182
+
183
+ def is_connected_to_rig_or_animation(obj):
184
+ """
185
+ Return True if a mesh should be treated as animated/rigged.
186
+
187
+ Animated/rigged meshes are protected from loose-part separation and from
188
+ metadata-nearest approximation. They are resolved by object name instead.
189
+ """
190
+ if obj is None or obj.type != "MESH":
191
+ return False
192
+
193
+ if any(mod.type == "ARMATURE" for mod in obj.modifiers):
194
+ return True
195
+
196
+ if obj.parent and obj.parent.type == "ARMATURE":
197
+ return True
198
+
199
+ if obj.parent_type == "BONE":
200
+ return True
201
+
202
+ if obj.animation_data:
203
+ if obj.animation_data.action:
204
+ return True
205
+ if obj.animation_data.nla_tracks:
206
+ return True
207
+
208
+ parent = obj.parent
209
+ while parent is not None:
210
+ if parent.animation_data:
211
+ if parent.animation_data.action:
212
+ return True
213
+ if parent.animation_data.nla_tracks:
214
+ return True
215
+ parent = parent.parent
216
+
217
+ if obj.data and obj.data.shape_keys and obj.data.shape_keys.animation_data:
218
+ if obj.data.shape_keys.animation_data.action:
219
+ return True
220
+ if obj.data.shape_keys.animation_data.nla_tracks:
221
+ return True
222
+
223
+ for constraint in obj.constraints:
224
+ if hasattr(constraint, "target") and constraint.target:
225
+ return True
226
+
227
+ return False
228
+
229
+
230
+ def split_static_and_animated_meshes(root):
231
+ """
232
+ Split visible meshes under NORMALISE_CONTAINER into static and animated lists.
233
+
234
+ Static meshes:
235
+ Safe for loose separation and geometry-metadata matching.
236
+
237
+ Animated/rigged meshes:
238
+ Protected from loose separation and matched by object name only.
239
+ """
240
+ static_meshes = []
241
+ anim_meshes = []
242
+
243
+ for obj in collect_meshes_under_container(root):
244
+ if obj.hide_viewport or obj.hide_render:
245
+ continue
246
+
247
+ if not obj.visible_get():
248
+ continue
249
+
250
+ if is_connected_to_rig_or_animation(obj):
251
+ anim_meshes.append(obj)
252
+ else:
253
+ static_meshes.append(obj)
254
+
255
+ return static_meshes, anim_meshes
256
+
257
+
258
+ # =============================================================================
259
+ # Loose separation
260
+ # =============================================================================
261
+
262
+ def separate_loose_parts_under_normalise_container(protected_meshes=None, blockers=None):
263
+ """
264
+ Separate static meshes into loose parts under NORMALISE_CONTAINER.
265
+
266
+ Animated/rigged meshes are passed through protected_meshes and skipped.
267
+ This prevents skinned or animated meshes from being broken into pieces.
268
+
269
+ Args:
270
+ protected_meshes:
271
+ Meshes that must not be loose-separated. Usually animated/rigged meshes.
272
+ blockers:
273
+ Optional meshes to skip, such as large planes or environment spheres.
274
+
275
+ Returns:
276
+ List of newly created mesh objects generated by Blender's loose separation.
277
+ """
278
+ protected_meshes = protected_meshes or []
279
+ blockers = blockers or []
280
+
281
+ root = bpy.data.objects.get(NORMALISE_CONTAINER_NAME)
282
+ if root is None:
283
+ log("NORMALISE_CONTAINER not found.")
284
+ return []
285
+
286
+ exclude_ptrs = {obj.as_pointer() for obj in protected_meshes if obj is not None}
287
+ exclude_ptrs.update(obj.as_pointer() for obj in blockers if obj is not None)
288
+
289
+ target_meshes = []
290
+ for obj in root.children_recursive:
291
+ if obj.type != "MESH":
292
+ continue
293
+ if obj.as_pointer() in exclude_ptrs:
294
+ continue
295
+ if is_connected_to_rig_or_animation(obj):
296
+ continue
297
+ target_meshes.append(obj)
298
+
299
+ if not target_meshes:
300
+ log("No static target meshes found for LOOSE separation.")
301
+ return []
302
+
303
+ view_layer = bpy.context.view_layer
304
+ created_objects = []
305
+
306
+ active_obj = view_layer.objects.active
307
+ if active_obj is not None and bpy.ops.object.mode_set.poll():
308
+ try:
309
+ bpy.ops.object.mode_set(mode="OBJECT")
310
+ except Exception:
311
+ pass
312
+
313
+ if bpy.ops.object.select_all.poll():
314
+ bpy.ops.object.select_all(action="DESELECT")
315
+
316
+ log(f"Perform LOOSE only on static meshes. target_mesh_count={len(target_meshes)}")
317
+
318
+ for idx, obj in enumerate(target_meshes, start=1):
319
+ if obj.name not in bpy.data.objects:
320
+ continue
321
+
322
+ prev_hide_viewport = obj.hide_viewport
323
+ prev_hide_render = obj.hide_render
324
+ prev_hide_select = obj.hide_select
325
+
326
+ try:
327
+ obj.hide_viewport = False
328
+ obj.hide_select = False
329
+
330
+ if bpy.ops.object.select_all.poll():
331
+ bpy.ops.object.select_all(action="DESELECT")
332
+
333
+ obj.select_set(True)
334
+ view_layer.objects.active = obj
335
+
336
+ before_ptrs = {
337
+ o.as_pointer()
338
+ for o in bpy.data.objects
339
+ if o.type == "MESH"
340
+ }
341
+
342
+ if bpy.ops.object.mode_set.poll():
343
+ bpy.ops.object.mode_set(mode="EDIT")
344
+ else:
345
+ log(f"Failed on {obj.name}: cannot enter EDIT mode")
346
+ continue
347
+
348
+ bpy.ops.mesh.select_all(action="SELECT")
349
+ bpy.ops.mesh.separate(type="LOOSE")
350
+
351
+ if bpy.ops.object.mode_set.poll():
352
+ bpy.ops.object.mode_set(mode="OBJECT")
353
+
354
+ new_objs = [
355
+ o for o in bpy.data.objects
356
+ if o.type == "MESH" and o.as_pointer() not in before_ptrs
357
+ ]
358
+ created_objects.extend(new_objs)
359
+
360
+ if idx % 25 == 0 or idx == len(target_meshes):
361
+ log(f"LOOSE progress: {idx}/{len(target_meshes)}")
362
+
363
+ except Exception as exc:
364
+ log(f"Failed on {obj.name}: {exc}")
365
+ try:
366
+ if bpy.ops.object.mode_set.poll():
367
+ bpy.ops.object.mode_set(mode="OBJECT")
368
+ except Exception:
369
+ pass
370
+
371
+ finally:
372
+ if obj.name in bpy.data.objects:
373
+ obj.hide_viewport = prev_hide_viewport
374
+ obj.hide_render = prev_hide_render
375
+ obj.hide_select = prev_hide_select
376
+
377
+ return created_objects
378
+
379
+
380
+ # =============================================================================
381
+ # Geometry metadata helpers
382
+ # =============================================================================
383
+
384
+ def world_bbox_min_max(obj):
385
+ """Return world-space bounding box min/max corners for one object."""
386
+ corners = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
387
+ mn = Vector((min(v.x for v in corners), min(v.y for v in corners), min(v.z for v in corners)))
388
+ mx = Vector((max(v.x for v in corners), max(v.y for v in corners), max(v.z for v in corners)))
389
+ return mn, mx
390
+
391
+
392
+ def bbox_size(obj):
393
+ """Return world-space bounding box size for one object."""
394
+ mn, mx = world_bbox_min_max(obj)
395
+ return mx - mn
396
+
397
+
398
+ def object_center_world(obj, precision=6):
399
+ """Return rounded world-space bounding box center."""
400
+ mn, mx = world_bbox_min_max(obj)
401
+ center = (mn + mx) * 0.5
402
+ return [round(float(center.x), precision), round(float(center.y), precision), round(float(center.z), precision)]
403
+
404
+
405
+ def object_bbox_size_world(obj, precision=6):
406
+ """Return rounded world-space bounding box size."""
407
+ size = bbox_size(obj)
408
+ return [round(float(size.x), precision), round(float(size.y), precision), round(float(size.z), precision)]
409
+
410
+
411
+ def object_poly_count(obj):
412
+ """Return polygon count for a mesh object."""
413
+ if obj is None or obj.type != "MESH" or obj.data is None:
414
+ return 0
415
+ return int(len(obj.data.polygons))
416
+
417
+
418
+ def object_vertex_count(obj):
419
+ """Return vertex count for a mesh object."""
420
+ if obj is None or obj.type != "MESH" or obj.data is None:
421
+ return 0
422
+ return int(len(obj.data.vertices))
423
+
424
+
425
+ def object_bbox_diag_world(obj):
426
+ """Return rounded world-space bounding box diagonal length."""
427
+ size = bbox_size(obj)
428
+ return round(float(size.length), 6)
429
+
430
+
431
+ def object_bbox_size_world_sorted(obj, precision=6):
432
+ """Return sorted bbox dimensions, useful when axes are not semantically important."""
433
+ size = object_bbox_size_world(obj, precision=precision)
434
+ return sorted(size)
435
+
436
+
437
+ def mapping_entry_with_metadata(value):
438
+ """
439
+ Convert a Blender object or object name into a JSON-style decomposition entry.
440
+
441
+ This mirrors the metadata used in Objaverse Data Intelligence decomposition
442
+ mapping. The key "is_rigged_or_animated" helps users understand why some
443
+ meshes are name-matched instead of geometry-approximated.
444
+ """
445
+ obj = value if hasattr(value, "name") else bpy.data.objects.get(str(value))
446
+ name = obj.name if obj is not None else str(value)
447
+
448
+ if obj is None or obj.type != "MESH":
449
+ return {
450
+ "name": name,
451
+ "center": None,
452
+ "bbox_size": None,
453
+ "poly_count": 0,
454
+ "vertex_count": 0,
455
+ "bbox_diag": 0.0,
456
+ "bbox_size_sorted": None,
457
+ "is_rigged_or_animated": False,
458
+ }
459
+
460
+ return {
461
+ "name": name,
462
+ "center": object_center_world(obj),
463
+ "bbox_size": object_bbox_size_world(obj),
464
+ "poly_count": object_poly_count(obj),
465
+ "vertex_count": object_vertex_count(obj),
466
+ "bbox_diag": object_bbox_diag_world(obj),
467
+ "bbox_size_sorted": object_bbox_size_world_sorted(obj),
468
+ "is_rigged_or_animated": is_connected_to_rig_or_animation(obj),
469
+ }
470
+
471
+
472
+ # =============================================================================
473
+ # Matching helpers
474
+ # =============================================================================
475
+
476
+ def _vec_diff_sq(a, b):
477
+ """Squared difference between two numeric vectors."""
478
+ return sum((float(x) - float(y)) ** 2 for x, y in zip(a, b))
479
+
480
+
481
+ def _maybe_vec_diff_sq(a, b, missing_penalty=1e12):
482
+ """Squared vector difference with a large penalty for missing metadata."""
483
+ if a is None or b is None:
484
+ return missing_penalty
485
+ return _vec_diff_sq(a, b)
486
+
487
+
488
+ def _maybe_abs_diff(a, b, missing_penalty=1e12):
489
+ """Absolute scalar difference with a large penalty for missing metadata."""
490
+ if a is None or b is None:
491
+ return missing_penalty
492
+ return abs(float(a) - float(b))
493
+
494
+
495
+ def metadata_score(candidate_meta, target_meta):
496
+ """
497
+ Approximate similarity score between candidate metadata and target metadata.
498
+
499
+ Lower is better.
500
+
501
+ Important:
502
+ This approximation is used only for static meshes. Animated/rigged
503
+ meshes are intentionally excluded from this path.
504
+ """
505
+ score = 0.0
506
+
507
+ if target_meta.get("poly_count") is not None:
508
+ score += abs(int(candidate_meta.get("poly_count", 0)) - int(target_meta["poly_count"])) * 1000000.0
509
+
510
+ if target_meta.get("vertex_count") is not None:
511
+ score += abs(int(candidate_meta.get("vertex_count", 0)) - int(target_meta["vertex_count"])) * 10000.0
512
+
513
+ score += _maybe_abs_diff(candidate_meta.get("bbox_diag"), target_meta.get("bbox_diag")) * 100.0
514
+ score += _maybe_vec_diff_sq(candidate_meta.get("center"), target_meta.get("center"))
515
+ score += _maybe_vec_diff_sq(candidate_meta.get("bbox_size"), target_meta.get("bbox_size"))
516
+ score += _maybe_vec_diff_sq(candidate_meta.get("bbox_size_sorted"), target_meta.get("bbox_size_sorted"))
517
+
518
+ return score
519
+
520
+
521
+ def metadata_exact_match(candidate_meta, target_meta, tolerance=DEFAULT_TOLERANCE):
522
+ """
523
+ Return True when candidate metadata exactly matches target metadata.
524
+
525
+ Integer fields must match exactly. Floating-point geometry fields may differ
526
+ within tolerance.
527
+ """
528
+ required_exact_int_fields = ("poly_count", "vertex_count")
529
+
530
+ for field in required_exact_int_fields:
531
+ target_val = target_meta.get(field)
532
+ if target_val is not None and candidate_meta.get(field) != target_val:
533
+ return False
534
+
535
+ vec_fields = ("center", "bbox_size", "bbox_size_sorted")
536
+
537
+ for field in vec_fields:
538
+ target_vec = target_meta.get(field)
539
+ cand_vec = candidate_meta.get(field)
540
+
541
+ if target_vec is None:
542
+ continue
543
+
544
+ if cand_vec is None:
545
+ return False
546
+
547
+ for a, b in zip(cand_vec, target_vec):
548
+ if abs(float(a) - float(b)) > tolerance:
549
+ return False
550
+
551
+ target_diag = target_meta.get("bbox_diag")
552
+ cand_diag = candidate_meta.get("bbox_diag")
553
+
554
+ if target_diag is not None:
555
+ if cand_diag is None or abs(float(cand_diag) - float(target_diag)) > tolerance:
556
+ return False
557
+
558
+ return True
559
+
560
+
561
+ def build_candidate_pool(meshes):
562
+ """
563
+ Build a one-use candidate pool.
564
+
565
+ Each decomposition mapping entry consumes one candidate object. This avoids
566
+ accidentally applying the same object to multiple decomposition components.
567
+ """
568
+ pool = []
569
+
570
+ for obj in meshes:
571
+ meta = mapping_entry_with_metadata(obj)
572
+ pool.append({
573
+ "object": obj,
574
+ "meta": meta,
575
+ "used": False,
576
+ })
577
+
578
+ return pool
579
+
580
+
581
+ def _entry_has_any_geometry_metadata(entry):
582
+ """Return True if a mapping entry contains usable geometry metadata."""
583
+ if not isinstance(entry, dict):
584
+ return False
585
+
586
+ return any(
587
+ entry.get(k) is not None
588
+ for k in ("center", "bbox_size", "poly_count", "vertex_count", "bbox_diag", "bbox_size_sorted")
589
+ )
590
+
591
+
592
+ def _entry_requests_animated_mesh(entry):
593
+ """
594
+ Return True when the JSON entry explicitly says this is animated/rigged.
595
+ """
596
+ return isinstance(entry, dict) and bool(entry.get("is_rigged_or_animated", False))
597
+
598
+
599
+ def find_name_match_for_animated_entry(entry, animated_pool):
600
+ """
601
+ Match an animated/rigged mesh by object name only.
602
+
603
+ Animated/rigged meshes should not be loose-separated and should not use
604
+ geometry-nearest approximation because animation, armature, constraints,
605
+ or shape-key state can make location/bbox metadata less reliable.
606
+ """
607
+ target_name = entry.get("name") if isinstance(entry, dict) else str(entry)
608
+
609
+ if not target_name:
610
+ return None, "animated_name_missing", 0, None
611
+
612
+ matches = [
613
+ item for item in animated_pool
614
+ if (not item["used"]) and item["object"].name == target_name
615
+ ]
616
+
617
+ if len(matches) == 1:
618
+ matches[0]["used"] = True
619
+ return matches[0]["object"], "animated_name", len(matches), matches[0]["meta"]
620
+
621
+ if len(matches) > 1:
622
+ matches.sort(key=lambda item: item["object"].name)
623
+ matches[0]["used"] = True
624
+ return matches[0]["object"], "animated_name_collision", len(matches), matches[0]["meta"]
625
+
626
+ return None, "animated_name_not_found", 0, None
627
+
628
+
629
+ def find_static_match_for_entry(entry, static_pool, tolerance=DEFAULT_TOLERANCE):
630
+ """
631
+ Match a static mesh using metadata first, then name fallback.
632
+
633
+ Matching order:
634
+ 1. Exact metadata match
635
+ 2. Metadata tie-break by object name
636
+ 3. Metadata tie-break by score
637
+ 4. Metadata-nearest approximation
638
+ 5. Name fallback if no metadata exists
639
+
640
+ This function must only receive static meshes.
641
+ """
642
+ has_metadata = _entry_has_any_geometry_metadata(entry)
643
+
644
+ if has_metadata:
645
+ exact = []
646
+
647
+ for item in static_pool:
648
+ if item["used"]:
649
+ continue
650
+
651
+ if metadata_exact_match(item["meta"], entry, tolerance=tolerance):
652
+ exact.append(item)
653
+
654
+ if len(exact) == 1:
655
+ exact[0]["used"] = True
656
+ return exact[0]["object"], "metadata_exact_unique", len(exact), exact[0]["meta"]
657
+
658
+ if len(exact) > 1:
659
+ preferred_name = entry.get("name") if isinstance(entry, dict) else str(entry)
660
+ same_name = [item for item in exact if item["object"].name == preferred_name]
661
+
662
+ if len(same_name) == 1:
663
+ same_name[0]["used"] = True
664
+ return same_name[0]["object"], "metadata_exact_tiebreak_name", len(exact), same_name[0]["meta"]
665
+
666
+ ranked = sorted(exact, key=lambda item: (metadata_score(item["meta"], entry), item["object"].name))
667
+ ranked[0]["used"] = True
668
+ return ranked[0]["object"], "metadata_exact_tiebreak_score", len(exact), ranked[0]["meta"]
669
+
670
+ ranked_all = []
671
+
672
+ for item in static_pool:
673
+ if item["used"]:
674
+ continue
675
+ ranked_all.append((metadata_score(item["meta"], entry), item))
676
+
677
+ if ranked_all:
678
+ ranked_all.sort(key=lambda x: (x[0], x[1]["object"].name))
679
+ best_score, best = ranked_all[0]
680
+ near_mode = "metadata_nearest" if best_score < 1e12 else "metadata_missing_fallback"
681
+ best["used"] = True
682
+ return best["object"], near_mode, 0, best["meta"]
683
+
684
+ target_name = entry.get("name") if isinstance(entry, dict) else str(entry)
685
+
686
+ by_name = [
687
+ item for item in static_pool
688
+ if (not item["used"]) and item["object"].name == target_name
689
+ ]
690
+
691
+ if by_name:
692
+ by_name[0]["used"] = True
693
+ return by_name[0]["object"], "name", len(by_name), by_name[0]["meta"]
694
+
695
+ return None, "not_found", 0, None
696
+
697
+
698
+ def find_match_for_entry(entry, static_pool, animated_pool, tolerance=DEFAULT_TOLERANCE):
699
+ """
700
+ Main object-recovery function.
701
+
702
+ Public behavior:
703
+ - Animated/rigged objects are recovered by object name.
704
+ - Static objects are recovered by geometry metadata.
705
+ - Metadata-nearest approximation is never applied to animated/rigged meshes.
706
+ """
707
+ if _entry_requests_animated_mesh(entry):
708
+ return find_name_match_for_animated_entry(entry, animated_pool)
709
+
710
+ anim_obj, anim_mode, anim_count, anim_meta = find_name_match_for_animated_entry(entry, animated_pool)
711
+
712
+ if anim_obj is not None:
713
+ return anim_obj, anim_mode, anim_count, anim_meta
714
+
715
+ return find_static_match_for_entry(entry, static_pool, tolerance=tolerance)
716
+
717
+
718
+ # =============================================================================
719
+ # Coloring helpers
720
+ # =============================================================================
721
+
722
+ def random_component_color(component_id):
723
+ """
724
+ Create a deterministic soft pastel color for a decomposition component.
725
+ Lower saturation/value keeps the verification view less blown out.
726
+ """
727
+ rng = random.Random(str(component_id))
728
+
729
+ return (
730
+ rng.uniform(0.25, 0.65),
731
+ rng.uniform(0.25, 0.65),
732
+ rng.uniform(0.25, 0.65),
733
+ 1.0,
734
+ )
735
+
736
+
737
+ def ensure_emission_material(component_id, color, strength=EMISSION_STRENGTH):
738
+ """
739
+ Create or reuse a simple emission material for decomposition preview.
740
+ """
741
+ mat_name = f"VERIFY_DECOMP_{component_id}"
742
+ mat = bpy.data.materials.get(mat_name)
743
+
744
+ if mat is None:
745
+ mat = bpy.data.materials.new(name=mat_name)
746
+
747
+ mat.use_nodes = True
748
+ nt = mat.node_tree
749
+ nodes = nt.nodes
750
+ links = nt.links
751
+ nodes.clear()
752
+
753
+ emission = nodes.new(type="ShaderNodeEmission")
754
+ output = nodes.new(type="ShaderNodeOutputMaterial")
755
+ emission.inputs["Color"].default_value = color
756
+ emission.inputs["Strength"].default_value = strength
757
+ links.new(emission.outputs["Emission"], output.inputs["Surface"])
758
+
759
+ return mat
760
+
761
+
762
+ def apply_material_to_object(obj, mat):
763
+ """Replace the object's visible material slots with the verification material."""
764
+ if obj.data is None:
765
+ return
766
+
767
+ if len(obj.data.materials) == 0:
768
+ obj.data.materials.append(mat)
769
+ else:
770
+ for i in range(len(obj.data.materials)):
771
+ obj.data.materials[i] = mat
772
+
773
+
774
+ # =============================================================================
775
+ # JSON loading
776
+ # =============================================================================
777
+
778
+ def load_decomposition_mapping_from_json(json_path):
779
+ """
780
+ Load decomposition_mapping from supported JSON formats.
781
+
782
+ Supported:
783
+ 1. Direct scene JSON:
784
+ {"decomposition_mapping": {...}}
785
+
786
+ 2. UID-wrapped JSON:
787
+ {"<uid>": {"decomposition_mapping": {...}}}
788
+ """
789
+ with open(json_path, "r", encoding="utf-8") as f:
790
+ data = json.load(f)
791
+
792
+ if isinstance(data, dict) and "decomposition_mapping" in data:
793
+ return data["decomposition_mapping"], data
794
+
795
+ if isinstance(data, dict) and len(data) == 1:
796
+ first_val = next(iter(data.values()))
797
+
798
+ if isinstance(first_val, dict) and "decomposition_mapping" in first_val:
799
+ return first_val["decomposition_mapping"], first_val
800
+
801
+ raise ValueError("Could not find decomposition_mapping in JSON.")
802
+
803
+
804
+ # =============================================================================
805
+ # Main public function
806
+ # =============================================================================
807
+
808
+ def apply_decomposition_from_json(glb_path, json_path, out_blend_path, tolerance=DEFAULT_TOLERANCE, report_path=None):
809
+ """
810
+ Apply/recover Objaverse Data Intelligence decomposition mapping on a GLB/GLTF.
811
+
812
+ Inputs:
813
+ glb_path:
814
+ Source GLB/GLTF file.
815
+
816
+ json_path:
817
+ JSON file containing decomposition_mapping.
818
+
819
+ out_blend_path:
820
+ Output .blend path. The saved blend contains colored decomposition
821
+ components.
822
+
823
+ tolerance:
824
+ Floating-point tolerance for exact metadata matching.
825
+
826
+ report_path:
827
+ Optional output report JSON path.
828
+
829
+ Output:
830
+ - A colored .blend file for visual inspection.
831
+ - A JSON report showing match modes, collisions, matched entries, and
832
+ unmatched entries.
833
+ """
834
+ reset_scene()
835
+ import_glb(glb_path)
836
+ container = normalise_scene()
837
+
838
+ decomposition_mapping, raw_json = load_decomposition_mapping_from_json(json_path)
839
+ requires_mesh_separation = bool(raw_json.get("summary", {}).get("requires_mesh_separation", True))
840
+
841
+ static_before_loose, animated_before_loose = split_static_and_animated_meshes(container)
842
+ log(f"Initial mesh split: static={len(static_before_loose)}, animated_or_rigged={len(animated_before_loose)}")
843
+
844
+ if requires_mesh_separation:
845
+ separate_loose_parts_under_normalise_container(
846
+ protected_meshes=animated_before_loose,
847
+ blockers=[],
848
+ )
849
+ else:
850
+ log("JSON summary says requires_mesh_separation=False. Skipping LOOSE separation.")
851
+
852
+ static_meshes, animated_meshes = split_static_and_animated_meshes(container)
853
+ static_pool = build_candidate_pool(static_meshes)
854
+ animated_pool = build_candidate_pool(animated_meshes)
855
+
856
+ log(f"Candidate pools after LOOSE: static={len(static_pool)}, animated_or_rigged={len(animated_pool)}")
857
+
858
+ report = {
859
+ "total_components": len(decomposition_mapping),
860
+ "total_entries": 0,
861
+ "matched_entries": 0,
862
+ "unmatched_entries": 0,
863
+ "match_modes": {},
864
+ "collision_entries": 0,
865
+ "static_candidate_count": len(static_pool),
866
+ "animated_candidate_count": len(animated_pool),
867
+ "requires_mesh_separation": requires_mesh_separation,
868
+ "component_reports": {},
869
+ }
870
+
871
+ for component_id, entries in decomposition_mapping.items():
872
+ color = random_component_color(component_id)
873
+ mat = ensure_emission_material(component_id, color)
874
+ component_report = []
875
+
876
+ if not isinstance(entries, list):
877
+ entries = [entries]
878
+
879
+ for entry in entries:
880
+ report["total_entries"] += 1
881
+
882
+ match_obj, mode, candidate_count, matched_meta = find_match_for_entry(
883
+ entry,
884
+ static_pool=static_pool,
885
+ animated_pool=animated_pool,
886
+ tolerance=tolerance,
887
+ )
888
+
889
+ report["match_modes"][mode] = report["match_modes"].get(mode, 0) + 1
890
+
891
+ item_name = entry.get("name") if isinstance(entry, dict) else str(entry)
892
+
893
+ row = {
894
+ "requested": item_name,
895
+ "mode": mode,
896
+ "candidate_count": candidate_count,
897
+ "matched_object": match_obj.name if match_obj else None,
898
+ "requested_meta": entry if isinstance(entry, dict) else {"name": str(entry)},
899
+ "matched_meta": matched_meta,
900
+ }
901
+
902
+ if candidate_count > 1:
903
+ report["collision_entries"] += 1
904
+
905
+ if match_obj is not None:
906
+ apply_material_to_object(match_obj, mat)
907
+ report["matched_entries"] += 1
908
+ else:
909
+ report["unmatched_entries"] += 1
910
+
911
+ component_report.append(row)
912
+
913
+ report["component_reports"][component_id] = component_report
914
+
915
+ bpy.ops.wm.save_as_mainfile(filepath=out_blend_path)
916
+
917
+ if report_path is None:
918
+ report_path = out_blend_path + DEFAULT_REPORT_PATH_SUFFIX
919
+
920
+ with open(report_path, "w", encoding="utf-8") as f:
921
+ json.dump(report, f, indent=2, ensure_ascii=False)
922
+
923
+ log(f"Saved blend file: {out_blend_path}")
924
+ log(f"Saved report: {report_path}")
925
+ log(f"Matched {report['matched_entries']} / {report['total_entries']} mapping entries")
926
+ log(f"Collision entries: {report['collision_entries']}")
927
+ log(f"Match modes: {report['match_modes']}")
928
+
929
+ return report
930
+
931
+
932
+ # =============================================================================
933
+ # CLI
934
+ # =============================================================================
935
+
936
+ def parse_args(argv=None):
937
+ parser = argparse.ArgumentParser(
938
+ description=(
939
+ "Apply Objaverse Data Intelligence decomposition_mapping JSON to a "
940
+ "GLB/GLTF scene and save a colored Blender verification file."
941
+ )
942
+ )
943
+
944
+ parser.add_argument("--glb", required=True, help="Source GLB/GLTF path")
945
+ parser.add_argument("--json", required=True, help="JSON file containing decomposition_mapping")
946
+ parser.add_argument("--out_blend", required=True, help="Output .blend path")
947
+ parser.add_argument(
948
+ "--tolerance",
949
+ type=float,
950
+ default=DEFAULT_TOLERANCE,
951
+ help="Metadata comparison tolerance for static meshes",
952
+ )
953
+ parser.add_argument(
954
+ "--report_json",
955
+ default=None,
956
+ help="Optional output JSON report path. Default: <out_blend>.decomposition_report.json",
957
+ )
958
+
959
+ return parser.parse_args(argv)
960
+
961
+
962
+ def main():
963
+ argv = []
964
+
965
+ if "--" in sys.argv:
966
+ argv = sys.argv[sys.argv.index("--") + 1:]
967
+
968
+ args = parse_args(argv)
969
+
970
+ apply_decomposition_from_json(
971
+ glb_path=args.glb,
972
+ json_path=args.json,
973
+ out_blend_path=args.out_blend,
974
+ tolerance=args.tolerance,
975
+ report_path=args.report_json,
976
+ )
977
+
978
+
979
+ if __name__ == "__main__":
980
+ main()