Download scripts/run_primitive_collision_proxy.py from yuchi233/Placement_Assets: direct link, hf CLI and curl.
- Browser
- Download file 29 kB
-
https://huggingface.co/datasets/yuchi233/Placement_Assets/resolve/main/scripts/run_primitive_collision_proxy.py
- Command line
-
hf download hf://datasets/yuchi233/Placement_Assets/scripts/run_primitive_collision_proxy.py
-
curl -L -o run_primitive_collision_proxy.py https://huggingface.co/datasets/yuchi233/Placement_Assets/resolve/main/scripts/run_primitive_collision_proxy.py
29 kB
| #!/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] | |
| class CuboidProxy: | |
| name: str | |
| source_mesh: str | |
| pos: Vec3 | |
| size: Vec3 | |
| component: int | |
| segment: int | |
| category: str | |
| 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("&", "&") | |
| .replace('"', """) | |
| .replace("<", "<") | |
| .replace(">", ">") | |
| ) | |
| 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()) | |