File size: 28,972 Bytes
4adb06a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2140288
 
4adb06a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
#!/usr/bin/env python3
"""
Generate primitive collision proxies from visual OBJ meshes.

This tool complements CoACD convex decomposition for thin rod / rack / grid
assets. It keeps raw assets untouched and writes derived outputs under:

  assets/<source>/derived/primitive_collision_proxies/<category>/<asset_id>_<variant>/

The generated JSON is the source of truth. MuJoCo and cuRobo fragments are both
exported from that same JSON so downstream planning and simulation can share the
same collision approximation.
"""

import argparse
import csv
import hashlib
import json
import math
import re
from collections import defaultdict
from dataclasses import asdict, dataclass
from datetime import date
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
MANIFEST = ROOT / "manifest" / "assets.jsonl"
Vec3 = tuple[float, float, float]


@dataclass(frozen=True)
class CuboidProxy:
    name: str
    source_mesh: str
    pos: Vec3
    size: Vec3
    component: int
    segment: int
    category: str

    @property
    def dims(self):
        return tuple(2.0 * v for v in self.size)


class DisjointSet:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra = self.find(a)
        rb = self.find(b)
        if ra == rb:
            return
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1


def parse_simple_yaml(path):
    data = {}
    current_key = None
    for raw in path.read_text().splitlines():
        if not raw.strip() or raw.lstrip().startswith("#"):
            continue
        if raw.startswith("  - ") and current_key:
            data.setdefault(current_key, []).append(raw.strip()[2:].strip())
            continue
        if ":" in raw and not raw.startswith(" "):
            key, value = raw.split(":", 1)
            key = key.strip()
            value = value.strip()
            current_key = key
            if value == "":
                data[key] = []
            elif value in {"[]", "{}"}:
                data[key] = [] if value == "[]" else {}
            else:
                data[key] = value.strip('"').strip("'")
    return data


def yaml_scalar(value):
    if isinstance(value, bool):
        return "true" if value else "false"
    if value is None:
        return "null"
    if isinstance(value, (int, float)):
        return str(value)
    text = str(value)
    if text == "":
        return '""'
    if any(ch in text for ch in [":", "#", "{", "}", "[", "]", ",", '"', "'", "\n"]) or text.startswith(" ") or text.endswith(" "):
        return json.dumps(text, ensure_ascii=False)
    return text


def dump_yaml(mapping, indent=0):
    lines = []
    pad = " " * indent
    for key, value in mapping.items():
        if isinstance(value, dict):
            lines.append(f"{pad}{key}:")
            lines.extend(dump_yaml(value, indent + 2))
        elif isinstance(value, list):
            if not value:
                lines.append(f"{pad}{key}: []")
            else:
                lines.append(f"{pad}{key}:")
                for item in value:
                    if isinstance(item, dict):
                        lines.append(f"{pad}  -")
                        lines.extend(dump_yaml(item, indent + 4))
                    else:
                        lines.append(f"{pad}  - {yaml_scalar(item)}")
        else:
            lines.append(f"{pad}{key}: {yaml_scalar(value)}")
    return lines


def xml_escape(value):
    return (
        str(value)
        .replace("&", "&amp;")
        .replace('"', "&quot;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
    )


def safe_name(text):
    text = Path(text).stem if "/" in text else text
    text = re.sub(r"[^0-9A-Za-z_]+", "_", text)
    text = re.sub(r"_+", "_", text).strip("_")
    if not text:
        text = "mesh"
    if text[0].isdigit():
        text = f"m_{text}"
    return text


def rel_to_root(path):
    resolved = path.resolve()
    try:
        return resolved.relative_to(ROOT).as_posix()
    except ValueError:
        return resolved.as_posix()


def sha256_file(path):
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def require_raw_asset(raw_asset_dir):
    raw_asset_dir = raw_asset_dir.resolve()
    try:
        raw_rel = raw_asset_dir.relative_to(ROOT / "assets")
    except ValueError as exc:
        raise SystemExit("raw_asset_dir must be under this repository's assets/ directory") from exc

    parts = raw_rel.parts
    if len(parts) < 5 or parts[1] != "raw":
        raise SystemExit("raw_asset_dir must be under assets/<source>/raw/<asset_type>/<category>/<asset_id>")
    return raw_asset_dir, parts[0], parts[2], parts[3], parts[4]


def discover_meshes(raw_asset_dir, patterns):
    meshes = []
    for pattern in patterns:
        meshes.extend(raw_asset_dir.glob(pattern))
    return sorted({p.resolve() for p in meshes if p.is_file()})


def resolve_mesh_args(raw_asset_dir, mesh_args, patterns):
    if mesh_args:
        meshes = []
        for item in mesh_args:
            path = Path(item).expanduser()
            if not path.is_absolute():
                path = raw_asset_dir / path
            if not path.exists():
                raise SystemExit(f"mesh does not exist: {path}")
            meshes.append(path.resolve())
        return meshes
    meshes = discover_meshes(raw_asset_dir, patterns)
    if not meshes:
        raise SystemExit("no mesh found. Pass --mesh or adjust --mesh-glob.")
    return meshes


def parse_obj(path):
    vertices = []
    faces = []
    for line in path.read_text(errors="ignore").splitlines():
        if line.startswith("v "):
            parts = line.split()
            vertices.append((float(parts[1]), float(parts[2]), float(parts[3])))
        elif line.startswith("f "):
            indices = []
            for token in line.split()[1:]:
                raw = token.split("/")[0]
                if not raw:
                    continue
                idx = int(raw)
                if idx < 0:
                    idx = len(vertices) + idx + 1
                indices.append(idx - 1)
            if len(indices) >= 2:
                faces.append(indices)
    if not vertices:
        raise RuntimeError(f"no OBJ vertices found: {path}")
    return vertices, faces


def connected_vertex_components(vertices, faces):
    dsu = DisjointSet(len(vertices))
    for face in faces:
        first = face[0]
        for idx in face[1:]:
            dsu.union(first, idx)
    groups = defaultdict(list)
    for idx in range(len(vertices)):
        groups[dsu.find(idx)].append(idx)
    return sorted(groups.values(), key=lambda group: (-len(group), min(group)))


def bbox(points):
    mins = [min(p[i] for p in points) for i in range(3)]
    maxs = [max(p[i] for p in points) for i in range(3)]
    return (mins[0], mins[1], mins[2]), (maxs[0], maxs[1], maxs[2])


def padded_cuboid(name, source_mesh, points, component, segment, padding, min_half_extent, category):
    mins, maxs = bbox(points)
    pos = tuple((mins[i] + maxs[i]) * 0.5 for i in range(3))
    size = tuple(max((maxs[i] - mins[i]) * 0.5 + padding, min_half_extent) for i in range(3))
    return CuboidProxy(
        name=name,
        source_mesh=source_mesh,
        pos=pos,
        size=size,
        component=component,
        segment=segment,
        category=category,
    )


def split_component_to_cuboids(
    component_id,
    vertex_ids,
    vertices,
    source_mesh,
    name_prefix,
    segment_length,
    padding,
    min_half_extent,
    min_segment_vertices,
):
    points = [vertices[i] for i in vertex_ids]
    mins, maxs = bbox(points)
    lengths = [maxs[i] - mins[i] for i in range(3)]
    axis = max(range(3), key=lambda i: lengths[i])
    if lengths[axis] <= segment_length:
        return [
            padded_cuboid(
                f"{name_prefix}_c{component_id:03d}_s000",
                source_mesh,
                points,
                component_id,
                0,
                padding,
                min_half_extent,
                "forbidden",
            )
        ]

    segment_count = max(1, math.ceil(lengths[axis] / segment_length))
    cuboids = []
    for segment_id in range(segment_count):
        lo = mins[axis] + lengths[axis] * segment_id / segment_count
        hi = mins[axis] + lengths[axis] * (segment_id + 1) / segment_count
        if segment_id == segment_count - 1:
            hi += 1e-12
        segment_points = [p for p in points if lo <= p[axis] < hi]
        if len(segment_points) < min_segment_vertices:
            continue
        cuboids.append(
            padded_cuboid(
                f"{name_prefix}_c{component_id:03d}_s{segment_id:03d}",
                source_mesh,
                segment_points,
                component_id,
                segment_id,
                padding,
                min_half_extent,
                "forbidden",
            )
        )
    return cuboids


def distance(a, b):
    return math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(3)))


def mark_allowed_contact(cuboids, target, radius):
    if target is None:
        return cuboids
    marked = []
    for cuboid in cuboids:
        category = "allowed_contact" if distance(cuboid.pos, target) <= radius else cuboid.category
        marked.append(
            CuboidProxy(
                name=cuboid.name,
                source_mesh=cuboid.source_mesh,
                pos=cuboid.pos,
                size=cuboid.size,
                component=cuboid.component,
                segment=cuboid.segment,
                category=category,
            )
        )
    return marked


def build_for_mesh(mesh_path, raw_asset_dir, args):
    vertices, faces = parse_obj(mesh_path)
    components = connected_vertex_components(vertices, faces)
    kept_components = [c for c in components if len(c) >= args.min_component_vertices]
    mesh_stem = safe_name(mesh_path.stem)
    rel_mesh = mesh_path.relative_to(raw_asset_dir).as_posix()
    name_prefix = safe_name(f"{args.name_prefix}_{mesh_stem}") if args.name_prefix else mesh_stem

    cuboids = []
    for component_id, vertex_ids in enumerate(kept_components):
        cuboids.extend(
            split_component_to_cuboids(
                component_id,
                vertex_ids,
                vertices,
                rel_mesh,
                name_prefix,
                args.segment_length,
                args.padding,
                args.min_half_extent,
                args.min_segment_vertices,
            )
        )
    cuboids = mark_allowed_contact(cuboids, args.allowed_contact_target, args.allowed_contact_radius)
    mins, maxs = bbox(vertices)
    stats = {
        "mesh": rel_mesh,
        "sha256": sha256_file(mesh_path),
        "vertices": len(vertices),
        "faces": len(faces),
        "components_total": len(components),
        "components_kept": len(kept_components),
        "cuboids_total": len(cuboids),
        "forbidden_cuboids": sum(c.category == "forbidden" for c in cuboids),
        "allowed_contact_cuboids": sum(c.category == "allowed_contact" for c in cuboids),
        "bbox_min": mins,
        "bbox_max": maxs,
        "bbox_size": tuple(maxs[i] - mins[i] for i in range(3)),
    }
    return cuboids, stats


def write_proxy_json(path, cuboids, stats, params):
    payload = {
        "format": "placement_assets.primitive_collision_proxy.v1",
        "created_at": str(date.today()),
        "params": params,
        "stats": stats,
        "cuboids": [{**asdict(c), "dims": c.dims} for c in cuboids],
    }
    path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")


def write_mjcf_files(mjcf_dir, asset_id, cuboids, class_name, rgba_forbidden, rgba_allowed, group, contype, conaffinity):
    mjcf_dir.mkdir(parents=True, exist_ok=True)
    attrs = []
    if class_name:
        attrs.append(f'class="{xml_escape(class_name)}"')
    if group:
        attrs.append(f'group="{xml_escape(group)}"')
    if contype:
        attrs.append(f'contype="{xml_escape(contype)}"')
    if conaffinity:
        attrs.append(f'conaffinity="{xml_escape(conaffinity)}"')
    common = " ".join(attrs)
    common = f" {common}" if common else ""

    lines = [
        "<!-- Include this file inside the target body to add primitive collision geoms. -->",
        "<mujocoinclude>",
    ]
    for c in cuboids:
        pos = " ".join(f"{v:.8f}" for v in c.pos)
        size = " ".join(f"{v:.8f}" for v in c.size)
        rgba = rgba_allowed if c.category == "allowed_contact" else rgba_forbidden
        lines.append(
            f'  <geom type="box" name="{xml_escape(c.name)}" pos="{pos}" size="{size}" '
            f'quat="1 0 0 0" rgba="{xml_escape(rgba)}"{common}/>'
        )
    lines.extend(["</mujocoinclude>", ""])
    (mjcf_dir / "primitive_geoms_include.xml").write_text("\n".join(lines))

    body_name = safe_name(f"{asset_id}_primitive_collision")
    combo = [
        "<!-- Convenience include for preview or standalone loading.",
        "     For integration into an existing object, include primitive_geoms_include.xml",
        "     inside the target body instead. -->",
        "<mujocoinclude>",
        "  <worldbody>",
        f'    <body name="{xml_escape(body_name)}">',
        '      <include file="primitive_geoms_include.xml"/>',
        "    </body>",
        "  </worldbody>",
        "</mujocoinclude>",
        "",
    ]
    (mjcf_dir / "primitive_collision_include.xml").write_text("\n".join(combo))


def write_curobo_world(path, cuboids):
    path.parent.mkdir(parents=True, exist_ok=True)
    lines = ["# Generated cuRobo cuboid fragment. Allowed-contact cuboids are omitted."]
    lines.append("cuboid:")
    for c in cuboids:
        if c.category != "forbidden":
            continue
        pose = [*c.pos, 1.0, 0.0, 0.0, 0.0]
        lines.append(f"  {c.name}:")
        lines.append("    pose: [" + ", ".join(f"{v:.8f}" for v in pose) + "]")
        lines.append("    dims: [" + ", ".join(f"{v:.8f}" for v in c.dims) + "]")
    path.write_text("\n".join(lines) + "\n")


def write_summary_csv(path, cuboids):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", newline="") as f:
        writer = csv.DictWriter(
            f,
            fieldnames=[
                "name",
                "source_mesh",
                "category",
                "component",
                "segment",
                "pos_x",
                "pos_y",
                "pos_z",
                "size_x",
                "size_y",
                "size_z",
                "dim_x",
                "dim_y",
                "dim_z",
            ],
        )
        writer.writeheader()
        for c in cuboids:
            writer.writerow(
                {
                    "name": c.name,
                    "source_mesh": c.source_mesh,
                    "category": c.category,
                    "component": c.component,
                    "segment": c.segment,
                    "pos_x": c.pos[0],
                    "pos_y": c.pos[1],
                    "pos_z": c.pos[2],
                    "size_x": c.size[0],
                    "size_y": c.size[1],
                    "size_z": c.size[2],
                    "dim_x": c.dims[0],
                    "dim_y": c.dims[1],
                    "dim_z": c.dims[2],
                }
            )


def write_report(path, raw_asset_dir, derived_dir, mesh_stats, cuboids):
    largest = sorted(cuboids, key=lambda c: max(c.size), reverse=True)[:12]
    lines = [
        "# Primitive Collision Proxy Report",
        "",
        "## Summary",
        "",
        f"- Raw asset: `{rel_to_root(raw_asset_dir)}`",
        f"- Derived asset: `{rel_to_root(derived_dir)}`",
        f"- Meshes: `{len(mesh_stats)}`",
        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",
        "",
        "## Mesh Stats",
        "",
        "| mesh | vertices | faces | components kept / total | cuboids | bbox size |",
        "|---|---:|---:|---:|---:|---:|",
    ]
    for stat in mesh_stats:
        lines.append(
            f"| `{stat['mesh']}` | `{stat['vertices']}` | `{stat['faces']}` | "
            f"`{stat['components_kept']} / {stat['components_total']}` | "
            f"`{stat['cuboids_total']}` | "
            f"`{tuple(round(v, 6) for v in stat['bbox_size'])}` |"
        )
    lines.extend(
        [
            "",
            "## Largest Cuboids",
            "",
            "| name | category | pos | half-size |",
            "|---|---|---:|---:|",
        ]
    )
    for c in largest:
        lines.append(
            f"| `{c.name}` | `{c.category}` | "
            f"`{tuple(round(v, 6) for v in c.pos)}` | "
            f"`{tuple(round(v, 6) for v in c.size)}` |"
        )
    lines.extend(
        [
            "",
            "## Review Checklist",
            "",
            "- Inspect `mjcf/primitive_geoms_include.xml` visually before downstream use.",
            "- Use `proxy/primitive_collision_proxy.json` as the source of truth.",
            "- Keep allowed-contact cuboids out of cuRobo forbidden worlds.",
            "- Verify task-specific start, goal, swept path, and allowed-contact penetration separately.",
        ]
    )
    path.write_text("\n".join(lines) + "\n")


def append_manifest(row):
    MANIFEST.parent.mkdir(parents=True, exist_ok=True)
    existing = []
    if MANIFEST.exists():
        existing = [line for line in MANIFEST.read_text().splitlines() if line.strip()]
    path = row["path"]
    for line in existing:
        try:
            old = json.loads(line)
        except json.JSONDecodeError:
            continue
        if old.get("path") == path:
            raise SystemExit(f"manifest already contains path: {path}")
    with MANIFEST.open("a") as f:
        f.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")


def parse_allowed_contact_target(values):
    if values is None:
        return None
    if len(values) != 3:
        raise SystemExit("--allowed-contact-target requires exactly 3 numbers")
    return tuple(float(v) for v in values)


def parse_args():
    parser = argparse.ArgumentParser(description="Generate primitive box collision proxies from visual OBJ meshes.")
    parser.add_argument("raw_asset_dir", help="Raw asset directory under assets/<source>/raw/...")
    parser.add_argument("--mesh", action="append", default=[], help="Mesh path relative to raw_asset_dir or absolute. Repeatable.")
    parser.add_argument(
        "--mesh-glob",
        action="append",
        default=["visuals/rack1.obj"],
        help="Glob relative to raw_asset_dir used when --mesh is omitted. Repeatable.",
    )
    parser.add_argument("--variant", default="primitive_boxes_v1", help="Derived asset suffix.")
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help="Optional explicit output directory for inspection. Defaults to the canonical derived asset path.",
    )
    parser.add_argument("--overwrite", action="store_true", help="Allow writing into an existing derived directory.")
    parser.add_argument("--register-manifest", action="store_true", help="Append the derived asset to manifest/assets.jsonl.")
    parser.add_argument("--name-prefix", default="proxy", help="Prefix for generated geom/cuboid names.")
    parser.add_argument("--segment-length", type=float, default=0.03, help="Max component segment length before splitting AABBs.")
    parser.add_argument("--padding", type=float, default=0.001, help="Extra half-extent added to each generated cuboid.")
    parser.add_argument("--min-half-extent", type=float, default=0.0015, help="Minimum half-extent per cuboid axis.")
    parser.add_argument("--min-component-vertices", type=int, default=4, help="Discard smaller connected components.")
    parser.add_argument("--min-segment-vertices", type=int, default=2, help="Discard split segments with fewer vertices.")
    parser.add_argument("--allowed-contact-target", nargs=3, metavar=("X", "Y", "Z"), help="OBJ-local point used to mark nearby cuboids as allowed contact.")
    parser.add_argument("--allowed-contact-radius", type=float, default=0.03, help="Radius around allowed-contact target.")
    parser.add_argument("--class-name", default="primitive_collision", help="MJCF geom class name. Empty string disables class attr.")
    parser.add_argument("--rgba-forbidden", default="0.8 0.1 0.1 0.45", help="MJCF rgba for forbidden cuboids.")
    parser.add_argument("--rgba-allowed", default="0.1 0.6 1 0.45", help="MJCF rgba for allowed-contact cuboids.")
    parser.add_argument("--group", default="0", help="MJCF geom group. Empty string disables group attr.")
    parser.add_argument("--contype", default="", help="MJCF geom contype. Empty string uses MuJoCo default.")
    parser.add_argument("--conaffinity", default="", help="MJCF geom conaffinity. Empty string uses MuJoCo default.")
    return parser.parse_args()


def main():
    args = parse_args()
    args.allowed_contact_target = parse_allowed_contact_target(args.allowed_contact_target)

    raw_asset_dir, source, _raw_asset_type, category, source_asset_id = require_raw_asset(Path(args.raw_asset_dir))
    raw_meta_path = raw_asset_dir / "metadata.yaml"
    raw_meta = parse_simple_yaml(raw_meta_path) if raw_meta_path.exists() else {}
    meshes = resolve_mesh_args(raw_asset_dir, args.mesh, args.mesh_glob)

    derived_asset_id = f"{source_asset_id}_{args.variant}"
    explicit_output_dir = args.output_dir is not None
    if explicit_output_dir and args.register_manifest:
        raise SystemExit("--output-dir is for inspection only and cannot be used with --register-manifest. Use the canonical derived path for registered assets.")
    derived_dir = args.output_dir.resolve() if explicit_output_dir else (
        ROOT / "assets" / source / "derived" / "primitive_collision_proxies" / category / derived_asset_id
    )
    if derived_dir.exists() and not args.overwrite:
        raise SystemExit(f"destination already exists: {derived_dir}. Use --overwrite only if you intend to replace files inside it.")
    work_dir = derived_dir
    if not args.overwrite:
        work_dir = derived_dir.parent / f".{derived_dir.name}.tmp"
        if work_dir.exists():
            raise SystemExit(f"temporary output already exists from a previous failed run: {work_dir}")

    (work_dir / "proxy").mkdir(parents=True, exist_ok=True)
    (work_dir / "mjcf").mkdir(parents=True, exist_ok=True)
    (work_dir / "curobo").mkdir(parents=True, exist_ok=True)
    (work_dir / "logs").mkdir(parents=True, exist_ok=True)

    all_cuboids = []
    mesh_stats = []
    for mesh_path in meshes:
        cuboids, stats = build_for_mesh(mesh_path, raw_asset_dir, args)
        all_cuboids.extend(cuboids)
        mesh_stats.append(stats)

    params = {
        "mesh_glob": args.mesh_glob,
        "variant": args.variant,
        "segment_length": args.segment_length,
        "padding": args.padding,
        "min_half_extent": args.min_half_extent,
        "min_component_vertices": args.min_component_vertices,
        "min_segment_vertices": args.min_segment_vertices,
        "allowed_contact_target": args.allowed_contact_target,
        "allowed_contact_radius": args.allowed_contact_radius,
    }
    write_proxy_json(work_dir / "proxy" / "primitive_collision_proxy.json", all_cuboids, mesh_stats, params)
    write_mjcf_files(
        work_dir / "mjcf",
        source_asset_id,
        all_cuboids,
        args.class_name,
        args.rgba_forbidden,
        args.rgba_allowed,
        args.group,
        args.contype,
        args.conaffinity,
    )
    write_curobo_world(work_dir / "curobo" / "primitive_world.yml", all_cuboids)
    write_summary_csv(work_dir / "logs" / "cuboids_summary.csv", all_cuboids)
    write_report(work_dir / "REPORT.md", raw_asset_dir, derived_dir, mesh_stats, all_cuboids)

    license_name = raw_meta.get("license", "unknown")
    origin_url = raw_meta.get("origin_url", "")
    global_asset_id = f"{source}.primitive_collision_proxies.{category}.{derived_asset_id}"
    metadata = {
        "asset_id": global_asset_id,
        "source": source,
        "source_asset_id": source_asset_id,
        "asset_type": "primitive_collision_proxies",
        "category": category,
        "format": "json_mjcf_curobo_collision_proxy",
        "entry_file": "proxy/primitive_collision_proxy.json",
        "license": license_name,
        "origin_url": origin_url,
        "path": rel_to_root(derived_dir),
        "storage_mode": "derived",
        "derived_from": [rel_to_root(raw_asset_dir)],
        "derivation_method": "primitive_collision_proxy",
        "proxy_tool": "run_primitive_collision_proxy.py",
        "proxy_params_file": "logs/proxy_generation.json",
        "validation_status": "generated",
        "tags": [source, "primitive_collision_proxy", "collision", "mujoco", "curobo"],
    }
    if "readiness_level" in raw_meta:
        metadata["readiness_level"] = raw_meta["readiness_level"]
    if "source_commit" in raw_meta:
        metadata["source_commit"] = raw_meta["source_commit"]
    (work_dir / "metadata.yaml").write_text("\n".join(dump_yaml(metadata)) + "\n")

    source_refs = {
        "raw_asset": rel_to_root(raw_asset_dir),
        "raw_entry_file": rel_to_root(raw_asset_dir / raw_meta.get("entry_file", "model.xml"))
        if (raw_asset_dir / raw_meta.get("entry_file", "model.xml")).exists()
        else "",
        "raw_meshes": [rel_to_root(p) for p in meshes],
    }
    (work_dir / "source_refs.yaml").write_text("\n".join(dump_yaml(source_refs)) + "\n")
    log = {
        "tool": "run_primitive_collision_proxy.py",
        "created_at": str(date.today()),
        "raw_asset": rel_to_root(raw_asset_dir),
        "derived_asset": rel_to_root(derived_dir),
        "params": params,
        "inputs": mesh_stats,
        "outputs": {
            "proxy_json": "proxy/primitive_collision_proxy.json",
            "mjcf_geoms_include": "mjcf/primitive_geoms_include.xml",
            "mjcf_standalone_include": "mjcf/primitive_collision_include.xml",
            "curobo_world": "curobo/primitive_world.yml",
            "cuboids_summary": "logs/cuboids_summary.csv",
            "report": "REPORT.md",
        },
        "cuboids_total": len(all_cuboids),
        "forbidden_cuboids": sum(c.category == "forbidden" for c in all_cuboids),
        "allowed_contact_cuboids": sum(c.category == "allowed_contact" for c in all_cuboids),
    }
    (work_dir / "logs" / "proxy_generation.json").write_text(json.dumps(log, indent=2, ensure_ascii=False) + "\n")

    readme = f"""# Primitive collision proxy: {source_asset_id}

Source asset:

```text
{rel_to_root(raw_asset_dir)}
```

This derived asset stores box primitive collision proxies generated from visual OBJ meshes.
It is intended for thin rod, rack, shelf, and grid-like structures where convex decomposition
or coarse hand-authored collision blocks can close physically real gaps.

Use `proxy/primitive_collision_proxy.json` as the source of truth. The MuJoCo and cuRobo
fragments are generated from the same proxy data.
"""
    (work_dir / "README.md").write_text(readme)

    if work_dir != derived_dir:
        work_dir.rename(derived_dir)

    if args.register_manifest:
        row = {
            "asset_id": global_asset_id,
            "asset_type": "primitive_collision_proxies",
            "category": category,
            "entry_file": "proxy/primitive_collision_proxy.json",
            "format": "json_mjcf_curobo_collision_proxy",
            "license": license_name,
            "origin_url": origin_url,
            "path": rel_to_root(derived_dir),
            "source": source,
            "source_asset_id": source_asset_id,
            "tags": [source, "primitive_collision_proxy", "collision", "mujoco", "curobo"],
        }
        append_manifest(row)

    print(rel_to_root(derived_dir))
    print(
        f"meshes={len(meshes)} cuboids={len(all_cuboids)} "
        f"forbidden={sum(c.category == 'forbidden' for c in all_cuboids)} "
        f"allowed_contact={sum(c.category == 'allowed_contact' for c in all_cuboids)}"
    )
    if not args.register_manifest:
        print("manifest_status=not_registered; rerun with --register-manifest when this derived asset should be indexed")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())