yuchi233 commited on
Commit
4adb06a
·
verified ·
1 Parent(s): 32773e7

Upload scripts/run_primitive_collision_proxy.py with huggingface_hub

Browse files
scripts/run_primitive_collision_proxy.py ADDED
@@ -0,0 +1,777 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Generate primitive collision proxies from visual OBJ meshes.
4
+
5
+ This tool complements CoACD convex decomposition for thin rod / rack / grid
6
+ assets. It keeps raw assets untouched and writes derived outputs under:
7
+
8
+ assets/<source>/derived/primitive_collision_proxies/<category>/<asset_id>_<variant>/
9
+
10
+ The generated JSON is the source of truth. MuJoCo and cuRobo fragments are both
11
+ exported from that same JSON so downstream planning and simulation can share the
12
+ same collision approximation.
13
+ """
14
+
15
+ import argparse
16
+ import csv
17
+ import hashlib
18
+ import json
19
+ import math
20
+ import re
21
+ from collections import defaultdict
22
+ from dataclasses import asdict, dataclass
23
+ from datetime import date
24
+ from pathlib import Path
25
+
26
+
27
+ ROOT = Path(__file__).resolve().parents[1]
28
+ MANIFEST = ROOT / "manifest" / "assets.jsonl"
29
+ Vec3 = tuple[float, float, float]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class CuboidProxy:
34
+ name: str
35
+ source_mesh: str
36
+ pos: Vec3
37
+ size: Vec3
38
+ component: int
39
+ segment: int
40
+ category: str
41
+
42
+ @property
43
+ def dims(self):
44
+ return tuple(2.0 * v for v in self.size)
45
+
46
+
47
+ class DisjointSet:
48
+ def __init__(self, n):
49
+ self.parent = list(range(n))
50
+ self.rank = [0] * n
51
+
52
+ def find(self, x):
53
+ while self.parent[x] != x:
54
+ self.parent[x] = self.parent[self.parent[x]]
55
+ x = self.parent[x]
56
+ return x
57
+
58
+ def union(self, a, b):
59
+ ra = self.find(a)
60
+ rb = self.find(b)
61
+ if ra == rb:
62
+ return
63
+ if self.rank[ra] < self.rank[rb]:
64
+ ra, rb = rb, ra
65
+ self.parent[rb] = ra
66
+ if self.rank[ra] == self.rank[rb]:
67
+ self.rank[ra] += 1
68
+
69
+
70
+ def parse_simple_yaml(path):
71
+ data = {}
72
+ current_key = None
73
+ for raw in path.read_text().splitlines():
74
+ if not raw.strip() or raw.lstrip().startswith("#"):
75
+ continue
76
+ if raw.startswith(" - ") and current_key:
77
+ data.setdefault(current_key, []).append(raw.strip()[2:].strip())
78
+ continue
79
+ if ":" in raw and not raw.startswith(" "):
80
+ key, value = raw.split(":", 1)
81
+ key = key.strip()
82
+ value = value.strip()
83
+ current_key = key
84
+ if value == "":
85
+ data[key] = []
86
+ elif value in {"[]", "{}"}:
87
+ data[key] = [] if value == "[]" else {}
88
+ else:
89
+ data[key] = value.strip('"').strip("'")
90
+ return data
91
+
92
+
93
+ def yaml_scalar(value):
94
+ if isinstance(value, bool):
95
+ return "true" if value else "false"
96
+ if value is None:
97
+ return "null"
98
+ if isinstance(value, (int, float)):
99
+ return str(value)
100
+ text = str(value)
101
+ if text == "":
102
+ return '""'
103
+ if any(ch in text for ch in [":", "#", "{", "}", "[", "]", ",", '"', "'", "\n"]) or text.startswith(" ") or text.endswith(" "):
104
+ return json.dumps(text, ensure_ascii=False)
105
+ return text
106
+
107
+
108
+ def dump_yaml(mapping, indent=0):
109
+ lines = []
110
+ pad = " " * indent
111
+ for key, value in mapping.items():
112
+ if isinstance(value, dict):
113
+ lines.append(f"{pad}{key}:")
114
+ lines.extend(dump_yaml(value, indent + 2))
115
+ elif isinstance(value, list):
116
+ if not value:
117
+ lines.append(f"{pad}{key}: []")
118
+ else:
119
+ lines.append(f"{pad}{key}:")
120
+ for item in value:
121
+ if isinstance(item, dict):
122
+ lines.append(f"{pad} -")
123
+ lines.extend(dump_yaml(item, indent + 4))
124
+ else:
125
+ lines.append(f"{pad} - {yaml_scalar(item)}")
126
+ else:
127
+ lines.append(f"{pad}{key}: {yaml_scalar(value)}")
128
+ return lines
129
+
130
+
131
+ def xml_escape(value):
132
+ return (
133
+ str(value)
134
+ .replace("&", "&amp;")
135
+ .replace('"', "&quot;")
136
+ .replace("<", "&lt;")
137
+ .replace(">", "&gt;")
138
+ )
139
+
140
+
141
+ def safe_name(text):
142
+ text = Path(text).stem if "/" in text else text
143
+ text = re.sub(r"[^0-9A-Za-z_]+", "_", text)
144
+ text = re.sub(r"_+", "_", text).strip("_")
145
+ if not text:
146
+ text = "mesh"
147
+ if text[0].isdigit():
148
+ text = f"m_{text}"
149
+ return text
150
+
151
+
152
+ def rel_to_root(path):
153
+ resolved = path.resolve()
154
+ try:
155
+ return resolved.relative_to(ROOT).as_posix()
156
+ except ValueError:
157
+ return resolved.as_posix()
158
+
159
+
160
+ def sha256_file(path):
161
+ h = hashlib.sha256()
162
+ with path.open("rb") as f:
163
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
164
+ h.update(chunk)
165
+ return h.hexdigest()
166
+
167
+
168
+ def require_raw_asset(raw_asset_dir):
169
+ raw_asset_dir = raw_asset_dir.resolve()
170
+ try:
171
+ raw_rel = raw_asset_dir.relative_to(ROOT / "assets")
172
+ except ValueError as exc:
173
+ raise SystemExit("raw_asset_dir must be under this repository's assets/ directory") from exc
174
+
175
+ parts = raw_rel.parts
176
+ if len(parts) < 5 or parts[1] != "raw":
177
+ raise SystemExit("raw_asset_dir must be under assets/<source>/raw/<asset_type>/<category>/<asset_id>")
178
+ return raw_asset_dir, parts[0], parts[2], parts[3], parts[4]
179
+
180
+
181
+ def discover_meshes(raw_asset_dir, patterns):
182
+ meshes = []
183
+ for pattern in patterns:
184
+ meshes.extend(raw_asset_dir.glob(pattern))
185
+ return sorted({p.resolve() for p in meshes if p.is_file()})
186
+
187
+
188
+ def resolve_mesh_args(raw_asset_dir, mesh_args, patterns):
189
+ if mesh_args:
190
+ meshes = []
191
+ for item in mesh_args:
192
+ path = Path(item).expanduser()
193
+ if not path.is_absolute():
194
+ path = raw_asset_dir / path
195
+ if not path.exists():
196
+ raise SystemExit(f"mesh does not exist: {path}")
197
+ meshes.append(path.resolve())
198
+ return meshes
199
+ meshes = discover_meshes(raw_asset_dir, patterns)
200
+ if not meshes:
201
+ raise SystemExit("no mesh found. Pass --mesh or adjust --mesh-glob.")
202
+ return meshes
203
+
204
+
205
+ def parse_obj(path):
206
+ vertices = []
207
+ faces = []
208
+ for line in path.read_text(errors="ignore").splitlines():
209
+ if line.startswith("v "):
210
+ parts = line.split()
211
+ vertices.append((float(parts[1]), float(parts[2]), float(parts[3])))
212
+ elif line.startswith("f "):
213
+ indices = []
214
+ for token in line.split()[1:]:
215
+ raw = token.split("/")[0]
216
+ if not raw:
217
+ continue
218
+ idx = int(raw)
219
+ if idx < 0:
220
+ idx = len(vertices) + idx + 1
221
+ indices.append(idx - 1)
222
+ if len(indices) >= 2:
223
+ faces.append(indices)
224
+ if not vertices:
225
+ raise RuntimeError(f"no OBJ vertices found: {path}")
226
+ return vertices, faces
227
+
228
+
229
+ def connected_vertex_components(vertices, faces):
230
+ dsu = DisjointSet(len(vertices))
231
+ for face in faces:
232
+ first = face[0]
233
+ for idx in face[1:]:
234
+ dsu.union(first, idx)
235
+ groups = defaultdict(list)
236
+ for idx in range(len(vertices)):
237
+ groups[dsu.find(idx)].append(idx)
238
+ return sorted(groups.values(), key=lambda group: (-len(group), min(group)))
239
+
240
+
241
+ def bbox(points):
242
+ mins = [min(p[i] for p in points) for i in range(3)]
243
+ maxs = [max(p[i] for p in points) for i in range(3)]
244
+ return (mins[0], mins[1], mins[2]), (maxs[0], maxs[1], maxs[2])
245
+
246
+
247
+ def padded_cuboid(name, source_mesh, points, component, segment, padding, min_half_extent, category):
248
+ mins, maxs = bbox(points)
249
+ pos = tuple((mins[i] + maxs[i]) * 0.5 for i in range(3))
250
+ size = tuple(max((maxs[i] - mins[i]) * 0.5 + padding, min_half_extent) for i in range(3))
251
+ return CuboidProxy(
252
+ name=name,
253
+ source_mesh=source_mesh,
254
+ pos=pos,
255
+ size=size,
256
+ component=component,
257
+ segment=segment,
258
+ category=category,
259
+ )
260
+
261
+
262
+ def split_component_to_cuboids(
263
+ component_id,
264
+ vertex_ids,
265
+ vertices,
266
+ source_mesh,
267
+ name_prefix,
268
+ segment_length,
269
+ padding,
270
+ min_half_extent,
271
+ min_segment_vertices,
272
+ ):
273
+ points = [vertices[i] for i in vertex_ids]
274
+ mins, maxs = bbox(points)
275
+ lengths = [maxs[i] - mins[i] for i in range(3)]
276
+ axis = max(range(3), key=lambda i: lengths[i])
277
+ if lengths[axis] <= segment_length:
278
+ return [
279
+ padded_cuboid(
280
+ f"{name_prefix}_c{component_id:03d}_s000",
281
+ source_mesh,
282
+ points,
283
+ component_id,
284
+ 0,
285
+ padding,
286
+ min_half_extent,
287
+ "forbidden",
288
+ )
289
+ ]
290
+
291
+ segment_count = max(1, math.ceil(lengths[axis] / segment_length))
292
+ cuboids = []
293
+ for segment_id in range(segment_count):
294
+ lo = mins[axis] + lengths[axis] * segment_id / segment_count
295
+ hi = mins[axis] + lengths[axis] * (segment_id + 1) / segment_count
296
+ if segment_id == segment_count - 1:
297
+ hi += 1e-12
298
+ segment_points = [p for p in points if lo <= p[axis] < hi]
299
+ if len(segment_points) < min_segment_vertices:
300
+ continue
301
+ cuboids.append(
302
+ padded_cuboid(
303
+ f"{name_prefix}_c{component_id:03d}_s{segment_id:03d}",
304
+ source_mesh,
305
+ segment_points,
306
+ component_id,
307
+ segment_id,
308
+ padding,
309
+ min_half_extent,
310
+ "forbidden",
311
+ )
312
+ )
313
+ return cuboids
314
+
315
+
316
+ def distance(a, b):
317
+ return math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(3)))
318
+
319
+
320
+ def mark_allowed_contact(cuboids, target, radius):
321
+ if target is None:
322
+ return cuboids
323
+ marked = []
324
+ for cuboid in cuboids:
325
+ category = "allowed_contact" if distance(cuboid.pos, target) <= radius else cuboid.category
326
+ marked.append(
327
+ CuboidProxy(
328
+ name=cuboid.name,
329
+ source_mesh=cuboid.source_mesh,
330
+ pos=cuboid.pos,
331
+ size=cuboid.size,
332
+ component=cuboid.component,
333
+ segment=cuboid.segment,
334
+ category=category,
335
+ )
336
+ )
337
+ return marked
338
+
339
+
340
+ def build_for_mesh(mesh_path, raw_asset_dir, args):
341
+ vertices, faces = parse_obj(mesh_path)
342
+ components = connected_vertex_components(vertices, faces)
343
+ kept_components = [c for c in components if len(c) >= args.min_component_vertices]
344
+ mesh_stem = safe_name(mesh_path.stem)
345
+ rel_mesh = mesh_path.relative_to(raw_asset_dir).as_posix()
346
+ name_prefix = safe_name(f"{args.name_prefix}_{mesh_stem}") if args.name_prefix else mesh_stem
347
+
348
+ cuboids = []
349
+ for component_id, vertex_ids in enumerate(kept_components):
350
+ cuboids.extend(
351
+ split_component_to_cuboids(
352
+ component_id,
353
+ vertex_ids,
354
+ vertices,
355
+ rel_mesh,
356
+ name_prefix,
357
+ args.segment_length,
358
+ args.padding,
359
+ args.min_half_extent,
360
+ args.min_segment_vertices,
361
+ )
362
+ )
363
+ cuboids = mark_allowed_contact(cuboids, args.allowed_contact_target, args.allowed_contact_radius)
364
+ mins, maxs = bbox(vertices)
365
+ stats = {
366
+ "mesh": rel_mesh,
367
+ "sha256": sha256_file(mesh_path),
368
+ "vertices": len(vertices),
369
+ "faces": len(faces),
370
+ "components_total": len(components),
371
+ "components_kept": len(kept_components),
372
+ "cuboids_total": len(cuboids),
373
+ "forbidden_cuboids": sum(c.category == "forbidden" for c in cuboids),
374
+ "allowed_contact_cuboids": sum(c.category == "allowed_contact" for c in cuboids),
375
+ "bbox_min": mins,
376
+ "bbox_max": maxs,
377
+ "bbox_size": tuple(maxs[i] - mins[i] for i in range(3)),
378
+ }
379
+ return cuboids, stats
380
+
381
+
382
+ def write_proxy_json(path, cuboids, stats, params):
383
+ payload = {
384
+ "format": "placement_assets.primitive_collision_proxy.v1",
385
+ "created_at": str(date.today()),
386
+ "params": params,
387
+ "stats": stats,
388
+ "cuboids": [{**asdict(c), "dims": c.dims} for c in cuboids],
389
+ }
390
+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
391
+
392
+
393
+ def write_mjcf_files(mjcf_dir, asset_id, cuboids, class_name, rgba_forbidden, rgba_allowed, group, contype, conaffinity):
394
+ mjcf_dir.mkdir(parents=True, exist_ok=True)
395
+ attrs = []
396
+ if class_name:
397
+ attrs.append(f'class="{xml_escape(class_name)}"')
398
+ if group:
399
+ attrs.append(f'group="{xml_escape(group)}"')
400
+ if contype:
401
+ attrs.append(f'contype="{xml_escape(contype)}"')
402
+ if conaffinity:
403
+ attrs.append(f'conaffinity="{xml_escape(conaffinity)}"')
404
+ common = " ".join(attrs)
405
+ common = f" {common}" if common else ""
406
+
407
+ lines = [
408
+ "<!-- Include this file inside the target body to add primitive collision geoms. -->",
409
+ "<mujocoinclude>",
410
+ ]
411
+ for c in cuboids:
412
+ pos = " ".join(f"{v:.8f}" for v in c.pos)
413
+ size = " ".join(f"{v:.8f}" for v in c.size)
414
+ rgba = rgba_allowed if c.category == "allowed_contact" else rgba_forbidden
415
+ lines.append(
416
+ f' <geom type="box" name="{xml_escape(c.name)}" pos="{pos}" size="{size}" '
417
+ f'quat="1 0 0 0" rgba="{xml_escape(rgba)}"{common}/>'
418
+ )
419
+ lines.extend(["</mujocoinclude>", ""])
420
+ (mjcf_dir / "primitive_geoms_include.xml").write_text("\n".join(lines))
421
+
422
+ body_name = safe_name(f"{asset_id}_primitive_collision")
423
+ combo = [
424
+ "<!-- Convenience include for preview or standalone loading.",
425
+ " For integration into an existing object, include primitive_geoms_include.xml",
426
+ " inside the target body instead. -->",
427
+ "<mujocoinclude>",
428
+ " <worldbody>",
429
+ f' <body name="{xml_escape(body_name)}">',
430
+ ' <include file="primitive_geoms_include.xml"/>',
431
+ " </body>",
432
+ " </worldbody>",
433
+ "</mujocoinclude>",
434
+ "",
435
+ ]
436
+ (mjcf_dir / "primitive_collision_include.xml").write_text("\n".join(combo))
437
+
438
+
439
+ def write_curobo_world(path, cuboids):
440
+ path.parent.mkdir(parents=True, exist_ok=True)
441
+ lines = ["# Generated cuRobo cuboid fragment. Allowed-contact cuboids are omitted."]
442
+ lines.append("cuboid:")
443
+ for c in cuboids:
444
+ if c.category != "forbidden":
445
+ continue
446
+ pose = [*c.pos, 1.0, 0.0, 0.0, 0.0]
447
+ lines.append(f" {c.name}:")
448
+ lines.append(" pose: [" + ", ".join(f"{v:.8f}" for v in pose) + "]")
449
+ lines.append(" dims: [" + ", ".join(f"{v:.8f}" for v in c.dims) + "]")
450
+ path.write_text("\n".join(lines) + "\n")
451
+
452
+
453
+ def write_summary_csv(path, cuboids):
454
+ path.parent.mkdir(parents=True, exist_ok=True)
455
+ with path.open("w", newline="") as f:
456
+ writer = csv.DictWriter(
457
+ f,
458
+ fieldnames=[
459
+ "name",
460
+ "source_mesh",
461
+ "category",
462
+ "component",
463
+ "segment",
464
+ "pos_x",
465
+ "pos_y",
466
+ "pos_z",
467
+ "size_x",
468
+ "size_y",
469
+ "size_z",
470
+ "dim_x",
471
+ "dim_y",
472
+ "dim_z",
473
+ ],
474
+ )
475
+ writer.writeheader()
476
+ for c in cuboids:
477
+ writer.writerow(
478
+ {
479
+ "name": c.name,
480
+ "source_mesh": c.source_mesh,
481
+ "category": c.category,
482
+ "component": c.component,
483
+ "segment": c.segment,
484
+ "pos_x": c.pos[0],
485
+ "pos_y": c.pos[1],
486
+ "pos_z": c.pos[2],
487
+ "size_x": c.size[0],
488
+ "size_y": c.size[1],
489
+ "size_z": c.size[2],
490
+ "dim_x": c.dims[0],
491
+ "dim_y": c.dims[1],
492
+ "dim_z": c.dims[2],
493
+ }
494
+ )
495
+
496
+
497
+ def write_report(path, raw_asset_dir, derived_dir, mesh_stats, cuboids):
498
+ largest = sorted(cuboids, key=lambda c: max(c.size), reverse=True)[:12]
499
+ lines = [
500
+ "# Primitive Collision Proxy Report",
501
+ "",
502
+ "## Summary",
503
+ "",
504
+ f"- Raw asset: `{rel_to_root(raw_asset_dir)}`",
505
+ f"- Derived asset: `{rel_to_root(derived_dir)}`",
506
+ f"- Meshes: `{len(mesh_stats)}`",
507
+ f"- Cuboids: `{len(cuboids)}` total, `{sum(c.category == 'forbidden' for c in cuboids)}` forbidden, `{sum(c.category == 'allowed_contact' for c in cuboids)}` allowed-contact",
508
+ "",
509
+ "## Mesh Stats",
510
+ "",
511
+ "| mesh | vertices | faces | components kept / total | cuboids | bbox size |",
512
+ "|---|---:|---:|---:|---:|---:|",
513
+ ]
514
+ for stat in mesh_stats:
515
+ lines.append(
516
+ f"| `{stat['mesh']}` | `{stat['vertices']}` | `{stat['faces']}` | "
517
+ f"`{stat['components_kept']} / {stat['components_total']}` | "
518
+ f"`{stat['cuboids_total']}` | "
519
+ f"`{tuple(round(v, 6) for v in stat['bbox_size'])}` |"
520
+ )
521
+ lines.extend(
522
+ [
523
+ "",
524
+ "## Largest Cuboids",
525
+ "",
526
+ "| name | category | pos | half-size |",
527
+ "|---|---|---:|---:|",
528
+ ]
529
+ )
530
+ for c in largest:
531
+ lines.append(
532
+ f"| `{c.name}` | `{c.category}` | "
533
+ f"`{tuple(round(v, 6) for v in c.pos)}` | "
534
+ f"`{tuple(round(v, 6) for v in c.size)}` |"
535
+ )
536
+ lines.extend(
537
+ [
538
+ "",
539
+ "## Review Checklist",
540
+ "",
541
+ "- Inspect `mjcf/primitive_geoms_include.xml` visually before downstream use.",
542
+ "- Use `proxy/primitive_collision_proxy.json` as the source of truth.",
543
+ "- Keep allowed-contact cuboids out of cuRobo forbidden worlds.",
544
+ "- Verify task-specific start, goal, swept path, and allowed-contact penetration separately.",
545
+ ]
546
+ )
547
+ path.write_text("\n".join(lines) + "\n")
548
+
549
+
550
+ def append_manifest(row):
551
+ MANIFEST.parent.mkdir(parents=True, exist_ok=True)
552
+ existing = []
553
+ if MANIFEST.exists():
554
+ existing = [line for line in MANIFEST.read_text().splitlines() if line.strip()]
555
+ path = row["path"]
556
+ for line in existing:
557
+ try:
558
+ old = json.loads(line)
559
+ except json.JSONDecodeError:
560
+ continue
561
+ if old.get("path") == path:
562
+ raise SystemExit(f"manifest already contains path: {path}")
563
+ with MANIFEST.open("a") as f:
564
+ f.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
565
+
566
+
567
+ def parse_allowed_contact_target(values):
568
+ if values is None:
569
+ return None
570
+ if len(values) != 3:
571
+ raise SystemExit("--allowed-contact-target requires exactly 3 numbers")
572
+ return tuple(float(v) for v in values)
573
+
574
+
575
+ def parse_args():
576
+ parser = argparse.ArgumentParser(description="Generate primitive box collision proxies from visual OBJ meshes.")
577
+ parser.add_argument("raw_asset_dir", help="Raw asset directory under assets/<source>/raw/...")
578
+ parser.add_argument("--mesh", action="append", default=[], help="Mesh path relative to raw_asset_dir or absolute. Repeatable.")
579
+ parser.add_argument(
580
+ "--mesh-glob",
581
+ action="append",
582
+ default=["visuals/rack1.obj"],
583
+ help="Glob relative to raw_asset_dir used when --mesh is omitted. Repeatable.",
584
+ )
585
+ parser.add_argument("--variant", default="primitive_boxes_v1", help="Derived asset suffix.")
586
+ parser.add_argument(
587
+ "--output-dir",
588
+ type=Path,
589
+ default=None,
590
+ help="Optional explicit output directory for inspection. Defaults to the canonical derived asset path.",
591
+ )
592
+ parser.add_argument("--overwrite", action="store_true", help="Allow writing into an existing derived directory.")
593
+ parser.add_argument("--register-manifest", action="store_true", help="Append the derived asset to manifest/assets.jsonl.")
594
+ parser.add_argument("--name-prefix", default="proxy", help="Prefix for generated geom/cuboid names.")
595
+ parser.add_argument("--segment-length", type=float, default=0.03, help="Max component segment length before splitting AABBs.")
596
+ parser.add_argument("--padding", type=float, default=0.001, help="Extra half-extent added to each generated cuboid.")
597
+ parser.add_argument("--min-half-extent", type=float, default=0.0015, help="Minimum half-extent per cuboid axis.")
598
+ parser.add_argument("--min-component-vertices", type=int, default=4, help="Discard smaller connected components.")
599
+ parser.add_argument("--min-segment-vertices", type=int, default=2, help="Discard split segments with fewer vertices.")
600
+ parser.add_argument("--allowed-contact-target", nargs=3, metavar=("X", "Y", "Z"), help="OBJ-local point used to mark nearby cuboids as allowed contact.")
601
+ parser.add_argument("--allowed-contact-radius", type=float, default=0.03, help="Radius around allowed-contact target.")
602
+ parser.add_argument("--class-name", default="primitive_collision", help="MJCF geom class name. Empty string disables class attr.")
603
+ parser.add_argument("--rgba-forbidden", default="0.8 0.1 0.1 0.45", help="MJCF rgba for forbidden cuboids.")
604
+ parser.add_argument("--rgba-allowed", default="0.1 0.6 1 0.45", help="MJCF rgba for allowed-contact cuboids.")
605
+ parser.add_argument("--group", default="0", help="MJCF geom group. Empty string disables group attr.")
606
+ parser.add_argument("--contype", default="", help="MJCF geom contype. Empty string uses MuJoCo default.")
607
+ parser.add_argument("--conaffinity", default="", help="MJCF geom conaffinity. Empty string uses MuJoCo default.")
608
+ return parser.parse_args()
609
+
610
+
611
+ def main():
612
+ args = parse_args()
613
+ args.allowed_contact_target = parse_allowed_contact_target(args.allowed_contact_target)
614
+
615
+ raw_asset_dir, source, _raw_asset_type, category, source_asset_id = require_raw_asset(Path(args.raw_asset_dir))
616
+ raw_meta_path = raw_asset_dir / "metadata.yaml"
617
+ raw_meta = parse_simple_yaml(raw_meta_path) if raw_meta_path.exists() else {}
618
+ meshes = resolve_mesh_args(raw_asset_dir, args.mesh, args.mesh_glob)
619
+
620
+ derived_asset_id = f"{source_asset_id}_{args.variant}"
621
+ explicit_output_dir = args.output_dir is not None
622
+ derived_dir = args.output_dir.resolve() if explicit_output_dir else (
623
+ ROOT / "assets" / source / "derived" / "primitive_collision_proxies" / category / derived_asset_id
624
+ )
625
+ if derived_dir.exists() and not args.overwrite:
626
+ raise SystemExit(f"destination already exists: {derived_dir}. Use --overwrite only if you intend to replace files inside it.")
627
+ work_dir = derived_dir
628
+ if not args.overwrite:
629
+ work_dir = derived_dir.parent / f".{derived_dir.name}.tmp"
630
+ if work_dir.exists():
631
+ raise SystemExit(f"temporary output already exists from a previous failed run: {work_dir}")
632
+
633
+ (work_dir / "proxy").mkdir(parents=True, exist_ok=True)
634
+ (work_dir / "mjcf").mkdir(parents=True, exist_ok=True)
635
+ (work_dir / "curobo").mkdir(parents=True, exist_ok=True)
636
+ (work_dir / "logs").mkdir(parents=True, exist_ok=True)
637
+
638
+ all_cuboids = []
639
+ mesh_stats = []
640
+ for mesh_path in meshes:
641
+ cuboids, stats = build_for_mesh(mesh_path, raw_asset_dir, args)
642
+ all_cuboids.extend(cuboids)
643
+ mesh_stats.append(stats)
644
+
645
+ params = {
646
+ "mesh_glob": args.mesh_glob,
647
+ "variant": args.variant,
648
+ "segment_length": args.segment_length,
649
+ "padding": args.padding,
650
+ "min_half_extent": args.min_half_extent,
651
+ "min_component_vertices": args.min_component_vertices,
652
+ "min_segment_vertices": args.min_segment_vertices,
653
+ "allowed_contact_target": args.allowed_contact_target,
654
+ "allowed_contact_radius": args.allowed_contact_radius,
655
+ }
656
+ write_proxy_json(work_dir / "proxy" / "primitive_collision_proxy.json", all_cuboids, mesh_stats, params)
657
+ write_mjcf_files(
658
+ work_dir / "mjcf",
659
+ source_asset_id,
660
+ all_cuboids,
661
+ args.class_name,
662
+ args.rgba_forbidden,
663
+ args.rgba_allowed,
664
+ args.group,
665
+ args.contype,
666
+ args.conaffinity,
667
+ )
668
+ write_curobo_world(work_dir / "curobo" / "primitive_world.yml", all_cuboids)
669
+ write_summary_csv(work_dir / "logs" / "cuboids_summary.csv", all_cuboids)
670
+ write_report(work_dir / "REPORT.md", raw_asset_dir, derived_dir, mesh_stats, all_cuboids)
671
+
672
+ license_name = raw_meta.get("license", "unknown")
673
+ origin_url = raw_meta.get("origin_url", "")
674
+ global_asset_id = f"{source}.primitive_collision_proxies.{category}.{derived_asset_id}"
675
+ metadata = {
676
+ "asset_id": global_asset_id,
677
+ "source": source,
678
+ "source_asset_id": source_asset_id,
679
+ "asset_type": "primitive_collision_proxies",
680
+ "category": category,
681
+ "format": "json_mjcf_curobo_collision_proxy",
682
+ "entry_file": "proxy/primitive_collision_proxy.json",
683
+ "license": license_name,
684
+ "origin_url": origin_url,
685
+ "path": rel_to_root(derived_dir),
686
+ "storage_mode": "derived",
687
+ "derived_from": [rel_to_root(raw_asset_dir)],
688
+ "derivation_method": "primitive_collision_proxy",
689
+ "proxy_tool": "run_primitive_collision_proxy.py",
690
+ "proxy_params_file": "logs/proxy_generation.json",
691
+ "validation_status": "generated",
692
+ "tags": [source, "primitive_collision_proxy", "collision", "mujoco", "curobo"],
693
+ }
694
+ if "readiness_level" in raw_meta:
695
+ metadata["readiness_level"] = raw_meta["readiness_level"]
696
+ if "source_commit" in raw_meta:
697
+ metadata["source_commit"] = raw_meta["source_commit"]
698
+ (work_dir / "metadata.yaml").write_text("\n".join(dump_yaml(metadata)) + "\n")
699
+
700
+ source_refs = {
701
+ "raw_asset": rel_to_root(raw_asset_dir),
702
+ "raw_entry_file": rel_to_root(raw_asset_dir / raw_meta.get("entry_file", "model.xml"))
703
+ if (raw_asset_dir / raw_meta.get("entry_file", "model.xml")).exists()
704
+ else "",
705
+ "raw_meshes": [rel_to_root(p) for p in meshes],
706
+ }
707
+ (work_dir / "source_refs.yaml").write_text("\n".join(dump_yaml(source_refs)) + "\n")
708
+ log = {
709
+ "tool": "run_primitive_collision_proxy.py",
710
+ "created_at": str(date.today()),
711
+ "raw_asset": rel_to_root(raw_asset_dir),
712
+ "derived_asset": rel_to_root(derived_dir),
713
+ "params": params,
714
+ "inputs": mesh_stats,
715
+ "outputs": {
716
+ "proxy_json": "proxy/primitive_collision_proxy.json",
717
+ "mjcf_geoms_include": "mjcf/primitive_geoms_include.xml",
718
+ "mjcf_standalone_include": "mjcf/primitive_collision_include.xml",
719
+ "curobo_world": "curobo/primitive_world.yml",
720
+ "cuboids_summary": "logs/cuboids_summary.csv",
721
+ "report": "REPORT.md",
722
+ },
723
+ "cuboids_total": len(all_cuboids),
724
+ "forbidden_cuboids": sum(c.category == "forbidden" for c in all_cuboids),
725
+ "allowed_contact_cuboids": sum(c.category == "allowed_contact" for c in all_cuboids),
726
+ }
727
+ (work_dir / "logs" / "proxy_generation.json").write_text(json.dumps(log, indent=2, ensure_ascii=False) + "\n")
728
+
729
+ readme = f"""# Primitive collision proxy: {source_asset_id}
730
+
731
+ Source asset:
732
+
733
+ ```text
734
+ {rel_to_root(raw_asset_dir)}
735
+ ```
736
+
737
+ This derived asset stores box primitive collision proxies generated from visual OBJ meshes.
738
+ It is intended for thin rod, rack, shelf, and grid-like structures where convex decomposition
739
+ or coarse hand-authored collision blocks can close physically real gaps.
740
+
741
+ Use `proxy/primitive_collision_proxy.json` as the source of truth. The MuJoCo and cuRobo
742
+ fragments are generated from the same proxy data.
743
+ """
744
+ (work_dir / "README.md").write_text(readme)
745
+
746
+ if work_dir != derived_dir:
747
+ work_dir.rename(derived_dir)
748
+
749
+ if args.register_manifest:
750
+ row = {
751
+ "asset_id": global_asset_id,
752
+ "asset_type": "primitive_collision_proxies",
753
+ "category": category,
754
+ "entry_file": "proxy/primitive_collision_proxy.json",
755
+ "format": "json_mjcf_curobo_collision_proxy",
756
+ "license": license_name,
757
+ "origin_url": origin_url,
758
+ "path": rel_to_root(derived_dir),
759
+ "source": source,
760
+ "source_asset_id": source_asset_id,
761
+ "tags": [source, "primitive_collision_proxy", "collision", "mujoco", "curobo"],
762
+ }
763
+ append_manifest(row)
764
+
765
+ print(rel_to_root(derived_dir))
766
+ print(
767
+ f"meshes={len(meshes)} cuboids={len(all_cuboids)} "
768
+ f"forbidden={sum(c.category == 'forbidden' for c in all_cuboids)} "
769
+ f"allowed_contact={sum(c.category == 'allowed_contact' for c in all_cuboids)}"
770
+ )
771
+ if not args.register_manifest:
772
+ print("manifest_status=not_registered; rerun with --register-manifest when this derived asset should be indexed")
773
+ return 0
774
+
775
+
776
+ if __name__ == "__main__":
777
+ raise SystemExit(main())