Download bosch800/source/cache_dump.py from shu4dev/dishsim-assets: direct link, hf CLI and curl.
- Browser
- Download file 9.14 kB
-
https://huggingface.co/datasets/shu4dev/dishsim-assets/resolve/main/bosch800/source/cache_dump.py
- Command line
-
hf download hf://datasets/shu4dev/dishsim-assets/bosch800/source/cache_dump.py
-
curl -L -o cache_dump.py https://huggingface.co/datasets/shu4dev/dishsim-assets/resolve/main/bosch800/source/cache_dump.py
9.14 kB
| # Copyright (c) 2026, dishsim project. | |
| # | |
| # SPDX-License-Identifier: BSD-3-Clause | |
| """Kit-side extraction of the collision-world cache (``dump_cache``). | |
| Verbatim from ``code/src/dishsim/geometry.py`` (moved here on 2026-10-21; the cache format and its readers stay in | |
| the code repo's ``dishsim.geometry``). Only ``extract_geometry.py`` imports it, after Kit has booted. | |
| """ | |
| import json | |
| import os | |
| import numpy as np | |
| from dishsim import config | |
| from dishsim.geometry import MANIFEST, MESH_DIR, config_hash | |
| from dishsim.quats import wxyz_to_xyzw | |
| #: dishwasher rigid bodies to extract (body-frame meshes + world poses); machines with a | |
| #: third rack extend this via :func:`dishwasher_bodies` | |
| DISHWASHER_BODIES = ["E_body_5", "E_door_4", "E_shelf_03", "E_shelf_1_04"] | |
| def dishwasher_bodies() -> list[str]: | |
| """The active machine's extractable rigid bodies (adds the third rack when present).""" | |
| return DISHWASHER_BODIES + (["E_shelf_third"] if config.HAS_THIRD_RACK else []) | |
| # --------------------------------------------------------------------------------------------- | |
| # Kit-side extraction | |
| # --------------------------------------------------------------------------------------------- | |
| #: Geom prim types the extractor understands (Isaac Lab 2.1 ships no ``utils.mesh`` — the | |
| #: 3.0 helpers this replaces returned exactly these plus ``Mesh``). | |
| _GEOM_TYPES = ("Cube", "Sphere", "Cylinder", "Capsule", "Cone") | |
| def _mesh_prims_under(prim): | |
| import isaaclab.sim as sim_utils # noqa: PLC0415 | |
| return sim_utils.get_all_matching_child_prims( | |
| prim.GetPath(), lambda p: p.GetTypeName() in _GEOM_TYPES + ("Mesh",) | |
| ) | |
| def _trimesh_from_geom_prim(mesh_prim) -> "object": | |
| """A ``trimesh.Trimesh`` of one Mesh/primitive geom prim, in the prim's LOCAL frame.""" | |
| import numpy as _np # noqa: PLC0415 | |
| import trimesh # noqa: PLC0415 | |
| from pxr import UsdGeom # noqa: PLC0415 | |
| t = mesh_prim.GetTypeName() | |
| if t == "Mesh": | |
| geom = UsdGeom.Mesh(mesh_prim) | |
| pts = _np.asarray(geom.GetPointsAttr().Get() or [], dtype=float) | |
| counts = _np.asarray(geom.GetFaceVertexCountsAttr().Get() or [], dtype=int) | |
| idx = _np.asarray(geom.GetFaceVertexIndicesAttr().Get() or [], dtype=int) | |
| if len(pts) == 0 or len(counts) == 0: | |
| return None | |
| faces, o = [], 0 | |
| for c in counts: # fan-triangulate n-gons | |
| for k in range(1, c - 1): | |
| faces.append((idx[o], idx[o + k], idx[o + k + 1])) | |
| o += c | |
| return trimesh.Trimesh(vertices=pts, faces=_np.asarray(faces, dtype=int), process=False) | |
| if t == "Cube": | |
| size = float(UsdGeom.Cube(mesh_prim).GetSizeAttr().Get()) | |
| return trimesh.creation.box(extents=(size, size, size)) | |
| axis_rot = {"X": [0.0, 1.0, 0.0, 90.0], "Y": [1.0, 0.0, 0.0, -90.0], "Z": None} | |
| if t == "Sphere": | |
| return trimesh.creation.icosphere(radius=float(UsdGeom.Sphere(mesh_prim).GetRadiusAttr().Get())) | |
| if t in ("Cylinder", "Capsule", "Cone"): | |
| geom = {"Cylinder": UsdGeom.Cylinder, "Capsule": UsdGeom.Capsule, "Cone": UsdGeom.Cone}[t](mesh_prim) | |
| r, h = float(geom.GetRadiusAttr().Get()), float(geom.GetHeightAttr().Get()) | |
| if t == "Cylinder": | |
| m = trimesh.creation.cylinder(radius=r, height=h) | |
| elif t == "Capsule": | |
| m = trimesh.creation.capsule(radius=r, height=h) | |
| else: | |
| m = trimesh.creation.cone(radius=r, height=h) | |
| m.apply_translation((0.0, 0.0, -h / 2.0)) # USD cones are center-origin | |
| rot = axis_rot[str(geom.GetAxisAttr().Get() or "Z")] | |
| if rot is not None: | |
| m.apply_transform(trimesh.transformations.rotation_matrix( | |
| _np.radians(rot[3]), rot[:3])) | |
| return m | |
| return None | |
| def extract_prim_mesh(body_prim, stage) -> "object": | |
| """Concatenate all meshes under a rigid-body prim into one trimesh in the BODY frame. | |
| Returns: | |
| A ``trimesh.Trimesh`` (body-frame vertices [m]) or None if no meshes found. | |
| """ | |
| import trimesh # noqa: PLC0415 | |
| from pxr import Usd, UsdGeom # noqa: PLC0415 | |
| cache = UsdGeom.XformCache(Usd.TimeCode.Default()) | |
| inv_body = cache.GetLocalToWorldTransform(body_prim).GetInverse() | |
| parts = [] | |
| for mesh_prim in _mesh_prims_under(body_prim): | |
| mesh = _trimesh_from_geom_prim(mesh_prim) | |
| if mesh is None or len(mesh.vertices) == 0: | |
| continue | |
| # full mesh->body transform (scale included); Gf matrices are row-vector, transpose | |
| # to the column convention trimesh/make_T use | |
| rel = cache.GetLocalToWorldTransform(mesh_prim) * inv_body | |
| mesh.apply_transform(np.array(rel, dtype=float).T) | |
| parts.append(mesh) | |
| if not parts: | |
| return None | |
| return trimesh.util.concatenate(parts) if len(parts) > 1 else parts[0] | |
| def dump_cache(scene, sim, cache_dir: str = config.CACHE_DIR) -> str: | |
| """Dump body-frame meshes + the scene_state.json manifest from the LIVE settled scene. | |
| Must run with ``use_fabric=False`` (stale-transform trap) after the scene has settled at | |
| the static state. | |
| Returns: | |
| Path to the manifest. | |
| """ | |
| import trimesh # noqa: PLC0415 | |
| from dishsim.transforms import T_inv, make_T # noqa: PLC0415 | |
| stage = scene.stage | |
| mesh_dir = os.path.join(cache_dir, MESH_DIR) | |
| os.makedirs(mesh_dir, exist_ok=True) | |
| T_w_base = make_T(config.ROBOT_BASE_POS_W, config.ROBOT_BASE_QUAT_W) | |
| T_base_w = T_inv(T_w_base) | |
| manifest: dict = { | |
| "frame_convention": config.FRAME_CONVENTION, | |
| "config_hash": config_hash(), | |
| "object_name": config.OBJECT_NAME, | |
| "statics": {}, | |
| } | |
| def body_pose_w(articulation, body_name): | |
| ids, _ = articulation.find_bodies(body_name) | |
| pos = articulation.data.body_link_pos_w[0, ids[0]].cpu().numpy() | |
| quat = wxyz_to_xyzw(articulation.data.body_link_quat_w[0, ids[0]].cpu().numpy()) | |
| return make_T(pos, quat) | |
| def save_mesh(name, mesh): | |
| path = os.path.join(mesh_dir, f"{name}.obj") | |
| mesh.export(path) | |
| return f"{MESH_DIR}/{name}.obj" | |
| # -- dishwasher bodies (static in v0) ------------------------------------------------------ | |
| dw = scene["dishwasher"] | |
| env_path = "/World/envs/env_0" | |
| for body in dishwasher_bodies(): | |
| prim = None | |
| for cand in stage.Traverse(): | |
| if cand.GetName() == body and str(cand.GetPath()).startswith(f"{env_path}/Dishwasher"): | |
| prim = cand | |
| break | |
| assert prim is not None, f"dishwasher body prim {body} not found" | |
| mesh = extract_prim_mesh(prim, stage) | |
| assert mesh is not None, f"no meshes under {body}" | |
| if body in config.RACK_GEN: | |
| # earliest Kit-stage guard against a scale/pre-compensation bug: the extracted | |
| # (USD-round-tripped) rack must match the generator's design-space geometry | |
| import rack_gen # noqa: PLC0415 (this folder) | |
| ref = rack_gen.merged_mesh(rack_gen.build(config.RACK_GEN[body])) | |
| dev = np.abs(np.asarray(mesh.bounds) - np.asarray(ref.bounds)).max() | |
| assert dev < 2e-3, f"{body}: extracted bounds deviate {dev * 1e3:.2f} mm from rack_gen" | |
| T_base_body = T_base_w @ body_pose_w(dw, body) | |
| manifest["statics"][body] = { | |
| "mesh": save_mesh(body, mesh), | |
| "T_base_body": T_base_body.tolist(), | |
| "coacd": True, | |
| } | |
| # -- pedestal + ground (procedural boxes; base frame poses from config) ------------------- | |
| ped = trimesh.creation.box(extents=config.PEDESTAL_SIZE) | |
| T_base_ped = T_base_w @ make_T(config.PEDESTAL_POS_W, (0, 0, 0, 1)) | |
| manifest["statics"]["pedestal"] = { | |
| "mesh": save_mesh("pedestal", ped), | |
| "T_base_body": T_base_ped.tolist(), | |
| "coacd": False, | |
| } | |
| ground = trimesh.creation.box(extents=(4.0, 4.0, 0.02)) | |
| T_base_ground = T_base_w @ make_T((0.4, 0.0, -0.01), (0, 0, 0, 1)) | |
| manifest["statics"]["ground"] = { | |
| "mesh": save_mesh("ground", ground), | |
| "T_base_body": T_base_ground.tolist(), | |
| "coacd": False, | |
| } | |
| # -- object mesh (body frame, Kit-free source) --------------------------------------------- | |
| # every class ships a body-frame OBJ beside its physics USD (the same file | |
| # planning stack collides) — no live extraction needed for a free object | |
| obj_mesh = trimesh.load( | |
| os.path.join(config.ASSETS_DIR, "bosch_props", "meshes", f"{config.ACTIVE_OBJECT}.obj"), | |
| force="mesh") | |
| manifest["object"] = { | |
| "mesh": save_mesh("object", obj_mesh), | |
| "coacd": True, | |
| } | |
| # -- static machine state + scenario (recorded for review; not part of config_hash) ------- | |
| from dishsim import scene as _s # noqa: PLC0415 | |
| manifest["statics_state"] = _s.statics_report(scene) | |
| manifest["scenario"] = config.SCENARIO_NAME | |
| path = os.path.join(cache_dir, MANIFEST) | |
| with open(path, "w") as f: | |
| json.dump(manifest, f, indent=2) | |
| print(f"[INFO] cache manifest written to {path} (hash {manifest['config_hash']})") | |
| return path | |