Upload third-party source (skip LFS pointer assets) (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/__init__.pyAdded+1
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/g1_robot.pyAdded+391
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/__init__.pyAdded+3
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/factory_arena.pyAdded+14
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/ground_arena.pyAdded+13
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/lab_arena.pyAdded+12
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/__init__.pyAdded+1
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/camera_utils.pyAdded+246
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/config_utils.pyAdded+63
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/cotrain_utils.pyAdded+25
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dataset_registry.pyAdded+352
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dexmg_utils.pyAdded+99
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/env_utils.pyAdded+105
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/__init__.pyAdded+4
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/gymnasium_basic.pyAdded+417
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/__init__.pyAdded+3
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/file_utils.pyAdded+35
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/fixture_template.xmlAdded+27
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/install_vhacd.shAdded+21
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/log_utils.pyAdded+46
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_gen_utils.pyAdded+800
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_obj.pyAdded+251
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mtl_utils.pyAdded+198
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_play_env.pyAdded+250
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_template.xmlAdded+15
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/parser_utils.pyAdded+61
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/object_utils.pyAdded+621
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/placement_samplers.pyAdded+711
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/postprocess_xml_utils.pyAdded+78
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/__init__.pyAdded
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/configs.pyAdded+126
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/scene.pyAdded+146
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/success_criteria.pyAdded+157
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/texture_swap.pyAdded+670
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/transform_utils.pyAdded+56
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/README.mdAdded+30
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/__init__.pyAdded+4
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/component.pyAdded+429
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/demo.pyAdded+58
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter.pyAdded+403
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter_test.pyAdded+71
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/shapes.pyAdded+138
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/utils.pyAdded+27
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/visuals_utls.pyAdded+31
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/__init__.pyAdded+1
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/ik_wrapper.pyAdded+226
- third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/setup.pyAdded+29
- third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.bashrcAdded+163
- third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.tmux.confAdded+84
- third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/70-manus-hid.rulesAdded+5
1from .g1_robot import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391import numpy as npfrom robosuite.models.robots.manipulators.legged_manipulator_model import ( LeggedManipulatorModel,)from robosuite.robots import register_robot_classfrom robosuite.utils.mjcf_utils import find_elements, xml_path_completion
import robocasa.models
@register_robot_class("LeggedRobot")class G1(LeggedManipulatorModel): """ G1 is a mobile manipulator robot created by Unitree.
Args: idn (int or str): Number or some other unique identification string for this robot instance """
arms = ["right", "left"]
def __init__(self, idn: int = 0): super().__init__( xml_path_completion( "robots/unitree_g1/g1_29dof_rev_1_0.xml", root=robocasa.models.assets_root, ), idn=idn, )
def _print_joint_info(self): """Print formatted information about joints""" # ANSI color codes BLUE = "\033[94m" GREEN = "\033[92m" RED = "\033[91m" ENDC = "\033[0m" BOLD = "\033[1m"
print(f"\n{BOLD}{BLUE}================ joints info ================{ENDC}")
# Print joints by category categories = { "Arms": self._arms_joints, "Base": self._base_joints, "Torso": self._torso_joints, "Head": self._head_joints, "Legs": self._legs_joints, }
for category, joints in categories.items(): if joints: print(f"{GREEN}{category} ({len(joints)}){ENDC}: {', '.join(joints)}") else: print(f"{RED}{category} (disabled){ENDC}") print()
def _print_actuator_info(self): """Print formatted information about actuators""" # ANSI color codes BLUE = "\033[94m" GREEN = "\033[92m" RED = "\033[91m" ENDC = "\033[0m" BOLD = "\033[1m"
print(f"\n{BOLD}{BLUE}================ actuators info ================{ENDC}")
# Print actuators by category categories = { "Arms": self._arms_actuators, "Base": self._base_actuators, "Torso": self._torso_actuators, "Head": self._head_actuators, "Legs": self._legs_actuators, }
for category, actuators in categories.items(): if actuators: print(f"{GREEN}{category} ({len(actuators)}){ENDC}: {', '.join(actuators)}") else: print(f"{RED}{category} (disabled){ENDC}") print()
def update_joints(self): """internal function to update joint lists""" for joint in self.all_joints: if "waist" in joint: self.torso_joints.append(joint) elif "base" in joint: self.base_joints.append(joint) elif "knee" in joint or "hip" in joint or "ankle" in joint: self.legs_joints.append(joint)
for joint in self.all_joints: if ( joint not in self._base_joints and joint not in self._torso_joints and joint not in self._head_joints and joint not in self._legs_joints ): self._arms_joints.append(joint)
# adjust the order of the joints, make sure the right arm joints are before the left arm joints self._arms_joints = [joint for joint in self._arms_joints if "right" in joint] + [ joint for joint in self._arms_joints if "left" in joint ]
# self._print_joint_info()
def update_actuators(self): """internal function to update actuator lists""" for actuator in self.all_actuators: if "waist" in actuator: self.torso_actuators.append(actuator) elif "base" in actuator: self.base_actuators.append(actuator) elif "knee" in actuator or "hip" in actuator or "ankle" in actuator: self.legs_actuators.append(actuator)
for actuator in self.all_actuators: if ( actuator not in self._base_actuators and actuator not in self._torso_actuators and actuator not in self._head_actuators and actuator not in self._legs_actuators ): self._arms_actuators.append(actuator)
# adjust the order of the actuators, make sure the right arm actuators are before the left arm actuators self._arms_actuators = [ actuator for actuator in self._arms_actuators if "right" in actuator ] + [actuator for actuator in self._arms_actuators if "left" in actuator] # self._print_actuator_info()
@property def default_base(self): return "NullBase" # return "NoActuationBase"
@property def default_gripper(self): # return {"right": None, "left": None} return {"right": "G1ThreeFingerRightHand", "left": "G1ThreeFingerLeftHand"}
@property def init_qpos(self): DEFAULT_DOF_ANGLES = { "left_hip_pitch_joint": -0.1, "left_hip_roll_joint": 0.0, "left_hip_yaw_joint": 0.0, "left_knee_joint": 0.3, "left_ankle_pitch_joint": -0.2, "left_ankle_roll_joint": 0.0, "right_hip_pitch_joint": -0.1, "right_hip_roll_joint": 0.0, "right_hip_yaw_joint": 0.0, "right_knee_joint": 0.3, "right_ankle_pitch_joint": -0.2, "right_ankle_roll_joint": 0.0, "waist_yaw_joint": 0.0, "waist_roll_joint": 0.0, "waist_pitch_joint": 0.0, "left_shoulder_pitch_joint": 0.0, "left_shoulder_roll_joint": 0.0, # 0.3, "left_shoulder_yaw_joint": 0.0, "left_elbow_joint": 0.0, # 1.0, "left_wrist_roll_joint": 0.0, "left_wrist_pitch_joint": 0.0, "left_wrist_yaw_joint": 0.0, "right_shoulder_pitch_joint": 0.0, "right_shoulder_roll_joint": 0.0, # -0.3, "right_shoulder_yaw_joint": 0.0, "right_elbow_joint": 0.0, # 1.0, "right_wrist_roll_joint": 0.0, "right_wrist_pitch_joint": 0.0, "right_wrist_yaw_joint": 0.0, }
joints = self.worldbody.findall(".//joint") joints = [joint for joint in joints if joint.get("name").startswith("robot")] init_qpos = np.array([0.0] * len(joints)) for joint_id, joint in enumerate(joints): init_qpos[joint_id] = DEFAULT_DOF_ANGLES[ joint.get("name")[joint.get("name").find("_") + 1 :] ] return init_qpos
@property def base_xpos_offset(self): return { "bins": (-0.30, -0.1, 0.95), "empty": (-0.29, 0, 0.95), "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.95), }
@property def top_offset(self): return np.array((0, 0, 1.0))
@property def _horizontal_radius(self): return 0.5
@property def arm_type(self): return "bimanual"
@property def _eef_name(self): return {"right": "right_eef", "left": "left_eef"}
@property def torso_body(self): return ["torso_link"]
def get_camera_configs(self): _cam_config = {}
# egoview camera egoview_mount_body = find_elements( root=self.root, tags="body", attribs={"name": f"{self.naming_prefix}torso_link"}, ) if egoview_mount_body is not None: # realsense D435i, 1920 * 1080, 69° × 42° _cam_config[f"{self.naming_prefix}rs_egoview"] = dict( pos=[0.07555294, 0.02579919, 0.49719054], # quat=[0.69263989, 0.16169103, -0.19008497, -0.67673754], quat=[0.67876761, 0.20864099, -0.20567003, -0.67338199], camera_attribs=dict(fovy="40"), parent_body=f"{self.naming_prefix}torso_link", )
# OAK-D W, OV9782, 640*480 _cam_config[f"{self.naming_prefix}oak_egoview"] = dict( pos=[0.10209156, -0.00937542, 0.42446595], quat=[0.64367383, 0.26523914, -0.27106013, -0.66472446], camera_attribs=dict(fovy="79.5"), parent_body=f"{self.naming_prefix}torso_link", )
_cam_config[f"{self.naming_prefix}oak_left_monoview"] = dict( pos=[0.10209156, 0.02857542, 0.42446595], quat=[0.64367383, 0.26523914, -0.27106013, -0.66472446], camera_attribs=dict(fovy="79.5"), parent_body=f"{self.naming_prefix}torso_link", )
_cam_config[f"{self.naming_prefix}oak_right_monoview"] = dict( pos=[0.10209156, -0.04657542, 0.42446595], quat=[0.64367383, 0.26523914, -0.27106013, -0.66472446], camera_attribs=dict(fovy="79.5"), parent_body=f"{self.naming_prefix}torso_link", )
# tppview camera tpp_mount_body = find_elements( root=self.root, tags="body", attribs={"name": f"{self.naming_prefix}pelvis"}, ) if tpp_mount_body is not None: _cam_config[f"{self.naming_prefix}rs_tppview"] = dict( pos=[-1.131, -0.626, 1.247 - 0.793], quat=[0.67953146, 0.46872971, -0.3204774, -0.46456828], camera_attribs=dict(fovy="60"), parent_body=f"{self.naming_prefix}pelvis", )
return _cam_config
def _disable_collisions(self, body_parts): """ Disable collision detection for specified body parts by setting contype="0" and conaffinity="0" for all collision geometries in those parts.
Args: body_parts (list): List of strings identifying body parts to disable collisions for. Examples: ["hip", "knee", "ankle"], ["waist"], ["shoulder"], etc. """ # Find all body elements in the worldbody for body in self.worldbody.findall(".//body"): body_name = body.get("name", "") # Check if this body belongs to specified body parts if any(part in body_name for part in body_parts): # Find all geom elements in this body for geom in body.findall(".//geom"): # Check if this is a collision geom (doesn't have contype="0" and conaffinity="0") contype = geom.get("contype") conaffinity = geom.get("conaffinity")
# If contype and conaffinity are not already "0", set them to disable collision if contype != "0" or conaffinity != "0": geom.set("contype", "0") geom.set("conaffinity", "0")
@register_robot_class("LeggedRobot")class G1FixedBase(G1): def __init__(self, idn: int = 0): super().__init__(idn=idn)
# Remove base actuation self._remove_free_joint()
@register_robot_class("LeggedRobot")class G1FixedLowerBody(G1): def __init__(self, idn: int = 0): super().__init__(idn=idn)
# Remove lower body actuation self._remove_joint_actuation("knee") self._remove_joint_actuation("hip") self._remove_joint_actuation("ankle")
self._remove_free_joint()
@register_robot_class("LeggedRobot")class G1ArmsOnly(G1): def __init__(self, idn: int = 0): super().__init__(idn=idn)
# Remove lower body actuation self._remove_joint_actuation("knee") self._remove_joint_actuation("hip") self._remove_joint_actuation("ankle")
# Remove spine & head actuation self._remove_joint_actuation("waist")
self._remove_free_joint()
@register_robot_class("LeggedRobot")class G1ArmsOnlyFloating(G1): def __init__(self, idn: int = 0): super().__init__(idn=idn)
# Remove lower body actuation self._remove_joint_actuation("knee") self._remove_joint_actuation("hip") self._remove_joint_actuation("ankle")
# Remove spine & head actuation self._remove_joint_actuation("waist")
self._remove_free_joint()
@property def default_base(self): return "FloatingLeggedBase"
@property def base_xpos_offset(self): return { "bins": (-0.30, -0.1, 0.97), "empty": (-0.29, 0, 0.97), "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.97), }
@register_robot_class("LeggedRobot")class G1FloatingBody(G1): def __init__(self, idn: int = 0): super().__init__(idn=idn)
# Remove lower body actuation self._remove_joint_actuation("knee") self._remove_joint_actuation("hip") self._remove_joint_actuation("ankle")
# Disable collision detection for lower body parts self._disable_collisions(["hip", "knee", "ankle"])
self._remove_free_joint()
@property def default_base(self): return "FloatingLeggedBase"
@property def base_xpos_offset(self): return { "bins": (-0.30, -0.1, 0.97), "empty": (-0.29, 0, 0.97), "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.97), }123from .ground_arena import GroundArenafrom .lab_arena import LabArenafrom .factory_arena import FactoryArena1234567891011121314from robosuite.models.arenas import Arenafrom robosuite.utils.mjcf_utils import xml_path_completionimport robocasa
class FactoryArena(Arena): """Factory workspace."""
def __init__(self): super().__init__( xml_path_completion( "arenas/gear_factory/gear_factory.xml", root=robocasa.models.assets_root ) )12345678910111213from robosuite.models.arenas import Arenafrom robosuite.utils.mjcf_utils import xml_path_completion
import robocasa
class GroundArena(Arena): """Empty workspace."""
def __init__(self): super().__init__( xml_path_completion("arenas/ground_arena.xml", root=robocasa.models.assets_root) )123456789101112from robosuite.models.arenas import Arenafrom robosuite.utils.mjcf_utils import xml_path_completionimport robocasa
class LabArena(Arena): """Lab workspace."""
def __init__(self): super().__init__( xml_path_completion("arenas/gear_lab/gear_lab.xml", root=robocasa.models.assets_root) )1from robosuite.utils import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246"""Collection of constants for cameras / robots / etcin kitchen environments"""
import numpy as npimport matplotlib.pyplot as plt
# https://github.com/yusukeurakami/mujoco_2d_projectiondef global2label(obj_pos, cam_pos, cam_ori, output_size=[64, 64], fov=90, s=1): """ :param obj_pos: 3D coordinates of the joint from MuJoCo in nparray [m] :param cam_pos: 3D coordinates of the camera from MuJoCo in nparray [m] :param cam_ori: camera 3D rotation (Rotation order of x->y->z) from MuJoCo in nparray [rad] :param fov: field of view in integer [degree] :return: Heatmap of the object in the 2D pixel space. """
e = np.array([output_size[0] / 2, output_size[1] / 2, 1]) fov = np.array([fov])
# Converting the MuJoCo coordinate into typical computer vision coordinate. cam_ori_cv = np.array([cam_ori[1], cam_ori[0], -cam_ori[2]]) obj_pos_cv = np.array([obj_pos[1], obj_pos[0], -obj_pos[2]]) cam_pos_cv = np.array([cam_pos[1], cam_pos[0], -cam_pos[2]])
obj_pos_in_2D, obj_pos_from_cam = get_2D_from_3D(obj_pos_cv, cam_pos_cv, cam_ori_cv, fov, e) label = gkern( output_size[0], output_size[1], (obj_pos_in_2D[1], output_size[0] - obj_pos_in_2D[0]), sigma=s, ) return label
def get_2D_from_3D(a, c, theta, fov, e): """ :param a: 3D coordinates of the joint in nparray [m] :param c: 3D coordinates of the camera in nparray [m] :param theta: camera 3D rotation (Rotation order of x->y->z) in nparray [rad] :param fov: field of view in integer [degree] :param e: :return: - (bx, by) ==> 2D coordinates of the obj [pixel] - d ==> 3D coordinates of the joint (relative to the camera) [m] """
# Get the vector from camera to object in global coordinate. ac_diff = a - c
# Rotate the vector in to camera coordinate x_rot = np.array( [ [1, 0, 0], [0, np.cos(theta[0]), np.sin(theta[0])], [0, -np.sin(theta[0]), np.cos(theta[0])], ] )
y_rot = np.array( [ [np.cos(theta[1]), 0, -np.sin(theta[1])], [0, 1, 0], [np.sin(theta[1]), 0, np.cos(theta[1])], ] )
z_rot = np.array( [ [np.cos(theta[2]), np.sin(theta[2]), 0], [-np.sin(theta[2]), np.cos(theta[2]), 0], [0, 0, 1], ] )
transform = z_rot.dot(y_rot.dot(x_rot)) d = transform.dot(ac_diff)
# scaling of projection plane using fov fov_rad = np.deg2rad(fov) e[2] *= e[0] * 1 / np.tan(fov_rad / 2.0)
# Projection from d to 2D bx = e[2] * d[0] / (d[2]) + e[0] by = e[2] * d[1] / (d[2]) + e[1]
return (bx, by), d
def gkern(h, w, center, sigma=1): x = np.arange(0, w, 1, float) y = np.arange(0, h, 1, float) y = y[:, np.newaxis] x0 = center[0] y0 = center[1] return np.exp(-1 * ((x - x0) ** 2 + (y - y0) ** 2) / sigma**2)
def compute_2d_projection( obj_pos=np.array([0.2, 0.25, 1.0]), cam_pos=np.array([0.7, 0, 1.5]), cam_ori=np.array([0.2, 1.2, 1.57]), fov=90, output_size=[64, 64],): e = np.array([output_size[0] / 2, output_size[1] / 2, 1]) fov = np.array([fov])
# Converting the MuJoCo coordinate into typical computer vision coordinate. cam_ori_cv = np.array([cam_ori[1], cam_ori[0], -cam_ori[2]]) obj_pos_cv = np.array([obj_pos[1], obj_pos[0], -obj_pos[2]]) cam_pos_cv = np.array([cam_pos[1], cam_pos[0], -cam_pos[2]])
obj_pos_in_2D, obj_pos_from_cam = get_2D_from_3D(obj_pos_cv, cam_pos_cv, cam_ori_cv, fov, e)
return obj_pos_in_2D[1], output_size[0] - obj_pos_in_2D[0]
def global2label(obj_pos, cam_pos, cam_ori, output_size=[64, 64], fov=90, s=1): """ :param obj_pos: 3D coordinates of the joint from MuJoCo in nparray [m] :param cam_pos: 3D coordinates of the camera from MuJoCo in nparray [m] :param cam_ori: camera 3D rotation (Rotation order of x->y->z) from MuJoCo in nparray [rad] :param fov: field of view in integer [degree] :return: Heatmap of the object in the 2D pixel space. """
e = np.array([output_size[0] / 2, output_size[1] / 2, 1]) fov = np.array([fov])
# Converting the MuJoCo coordinate into typical computer vision coordinate. cam_ori_cv = np.array([cam_ori[1], cam_ori[0], -cam_ori[2]]) obj_pos_cv = np.array([obj_pos[1], obj_pos[0], -obj_pos[2]]) cam_pos_cv = np.array([cam_pos[1], cam_pos[0], -cam_pos[2]])
obj_pos_in_2D, obj_pos_from_cam = get_2D_from_3D(obj_pos_cv, cam_pos_cv, cam_ori_cv, fov, e) label = gkern( output_size[0], output_size[1], (obj_pos_in_2D[1], output_size[0] - obj_pos_in_2D[0]), sigma=s, ) return label
def visualize_2d_projection( obj_pos=np.array([0.2, 0.25, 1.0]), cam_pos=np.array([0.7, 0, 1.5]), cam_ori=np.array([0.2, 1.2, 1.57]), fov=90, output_size=[64, 64],): s = 1 # std for heapmap signal label = global2label(obj_pos, cam_pos, cam_ori, output_size, fov=fov, s=s) plt.imshow(label) plt.show()
# default free cameras for different kitchen layoutsLAYOUT_CAMS = { 0: dict( lookat=[2.26593463, -1.00037131, 1.38769295], distance=3.0505089839567323, azimuth=90.71563812375285, elevation=-12.63948837207208, ), 1: dict( lookat=[2.66147999, -1.00162429, 1.2425155], distance=3.7958766287746255, azimuth=89.75784013699234, elevation=-15.177406642875091, ), 2: dict( lookat=[3.02344359, -1.48874618, 1.2412914], distance=3.6684844368165512, azimuth=51.67880851867874, elevation=-13.302619131542388, ), # 3: dict( # lookat=[11.44842548, -11.47664723, 11.24115989], # distance=43.923271794728187, # azimuth=227.12928449329333, # elevation=-16.495686334624907, # ), 4: dict( lookat=[1.6, -1.0, 1.0], distance=5, azimuth=89.70301806083651, elevation=-18.02177994296577, ),}
DEFAULT_LAYOUT_CAM = { "lookat": [2.25, -1, 1.05312667], "distance": 5, "azimuth": 89.70301806083651, "elevation": -18.02177994296577,}
CAM_CONFIGS = dict( robot0_agentview_center=dict( pos=[-0.6, 0.0, 1.15], quat=[ 0.636945903301239, 0.3325185477733612, -0.3199238181114197, -0.6175596117973328, ], parent_body="mobilebase0_support", ), robot0_agentview_left=dict( pos=[-0.5, 0.35, 1.05], quat=[0.55623853, 0.29935253, -0.37678665, -0.6775092], camera_attribs=dict(fovy="60"), parent_body="mobilebase0_support", ), robot0_agentview_right=dict( pos=[-0.5, -0.35, 1.05], quat=[ 0.6775091886520386, 0.3767866790294647, -0.2993525564670563, -0.55623859167099, ], camera_attribs=dict(fovy="60"), parent_body="mobilebase0_support", ), robot0_frontview=dict( pos=[-0.50, 0, 0.95], quat=[ 0.6088936924934387, 0.3814677894115448, -0.3673907518386841, -0.5905545353889465, ], camera_attribs=dict(fovy="60"), parent_body="mobilebase0_support", ), robot0_eye_in_hand=dict( pos=[0.05, 0, 0], quat=[0, 0.707107, 0.707107, 0], parent_body="robot0_right_hand", ),)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import copyimport osimport pathlibimport robosuitefrom robosuite.controllers import load_composite_controller_config
def is_stale_controller_config(config: dict): """ Checks if a controller config is in the format from robosuite versions <= 1.4.1. Does not check for config validity, only the format type. Args: config (dict): Controller configuration Returns: bool: True if the config is in the old format, False otherwise """
OLD_CONTROLLER_TYPES = [ "JOINT_VELOCITY", "JOINT_TORQUE", "JOINT_POSITION", "OSC_POSITION", "OSC_POSE", "IK_POSE", ] if ( "body_parts" not in config or "body_parts_controller_configs" not in config ) and "type" in config: return config["type"] in OLD_CONTROLLER_TYPES return False
def refactor_composite_controller_config(controller_config, robot_type, arms): """ Checks if a controller config is in the format from robosuite versions <= 1.4.1. If this is the case, converts the controller config to the new composite controller config format in robosuite versions >= 1.5. If the robot has a default controller config use that and override the arms with the old controller config. If not just use the old controller config for arms. Args: old_controller_config (dict): Old controller config Returns: dict: New controller config """ if not is_stale_controller_config(controller_config): return controller_config
config_dir = pathlib.Path(robosuite.__file__).parent / "controllers/config/robots/" name = robot_type.lower() configs = os.listdir(config_dir) if f"default_{name}.json" in configs: new_controller_config = load_composite_controller_config(robot=name) else: new_controller_config = {} new_controller_config["type"] = "BASIC" new_controller_config["body_parts"] = {}
for arm in arms: new_arm_config = copy.deepcopy(controller_config) if "gripper" not in new_arm_config: new_arm_config["gripper"] = {"type": "GRIP"} new_controller_config["body_parts"][arm] = new_arm_config return new_controller_config12345678910111213141516171819202122232425"""Utility functions and constants for co-training with real robot."""
from robosuite.models.robots.manipulators.gr1_robot import GR1
# Initial pose configuration for co-training with real robotCOTRAIN_REAL_MATCHED_ROBOT_INITIAL_POSE = { GR1: { "robot0_r_shoulder_pitch": -0.22963779, "robot0_r_shoulder_roll": -0.38363408, "robot0_r_shoulder_yaw": 0.14360377, "robot0_r_elbow_pitch": -1.5289252, "robot0_r_wrist_yaw": -0.2897802, "robot0_r_wrist_roll": -0.07134621, "robot0_r_wrist_pitch": -0.04550289, "robot0_l_shoulder_pitch": -0.10933163, "robot0_l_shoulder_roll": 0.43292055, "robot0_l_shoulder_yaw": -0.15983289, "robot0_l_elbow_pitch": -1.48233023, "robot0_l_wrist_yaw": 0.2359135, "robot0_l_wrist_roll": 0.26184522, "robot0_l_wrist_pitch": 0.00830735, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352import osfrom collections import OrderedDictfrom copy import deepcopyfrom pathlib import Path
import robocasaimport robocasa.macros as macros
SINGLE_STAGE_TASK_DATASETS = OrderedDict( PnPCounterToCab=dict( horizon=500, human_path="v0.1/single_stage/kitchen_pnp/PnPCounterToCab/2024-04-24", mg_path="v0.1/single_stage/kitchen_pnp/PnPCounterToCab/mg/2024-05-04-22-12-27_and_2024-05-07-07-39-33", download_links=dict( human_raw="https://utexas.box.com/shared/static/c0a0vdyqeqh6o9z4c57sk61aypladizj.hdf5", human_im="https://utexas.box.com/shared/static/gznii250ip99731ii2r0ml6be7gzt2cp.hdf5", mg_im="https://utexas.box.com/shared/static/7y9csrcx6uhhq4p3yctmm2df3rjqpw6g.hdf5", ), ), PnPCabToCounter=dict( horizon=500, human_path="v0.1/single_stage/kitchen_pnp/PnPCabToCounter/2024-04-24", mg_path="v0.1/single_stage/kitchen_pnp/PnPCabToCounter/mg/2024-07-12-04-33-29", download_links=dict( human_raw="https://utexas.box.com/shared/static/fgd165p91ts9qurfb496ubi1xdqgrz97.hdf5", human_im="https://utexas.box.com/shared/static/pdfh88slq4bazfglixaw80whvbtlbw6r.hdf5", mg_im="https://utexas.box.com/shared/static/mfltre5w8qi8ps1fqicblx40p008425z.hdf5", ), ), PnPCounterToSink=dict( horizon=700, human_path="v0.1/single_stage/kitchen_pnp/PnPCounterToSink/2024-04-25", mg_path="v0.1/single_stage/kitchen_pnp/PnPCounterToSink/mg/2024-05-04-22-14-06_and_2024-05-07-07-40-17", download_links=dict( human_raw="https://utexas.box.com/shared/static/nc0x55xwlgs4acj97ngdj1q6pv450ooo.hdf5", human_im="https://utexas.box.com/shared/static/0z1wr8iwfusfqqpp56j3vfxvvse1x0vc.hdf5", mg_im="https://utexas.box.com/shared/static/5vkb2fpthnw554q888fynk3zqwsgk2e5.hdf5", ), ), PnPSinkToCounter=dict( horizon=500, human_path="v0.1/single_stage/kitchen_pnp/PnPSinkToCounter/2024-04-26_2", mg_path="v0.1/single_stage/kitchen_pnp/PnPSinkToCounter/mg/2024-05-04-22-14-34_and_2024-05-07-07-40-21", download_links=dict( human_raw="https://utexas.box.com/shared/static/uyhepwjyr0880a5q03fc61qmhbrhwy7k.hdf5", human_im="https://utexas.box.com/shared/static/pe03k5qvcuq1nzbpfag5pfo2t8fzvl9i.hdf5", mg_im="https://utexas.box.com/shared/static/ppj3j8jnxkpusi7ft44f5ut7szkmu8yr.hdf5", ), ), PnPCounterToMicrowave=dict( horizon=600, human_path="v0.1/single_stage/kitchen_pnp/PnPCounterToMicrowave/2024-04-27", mg_path="v0.1/single_stage/kitchen_pnp/PnPCounterToMicrowave/mg/2024-05-04-22-13-21_and_2024-05-07-07-41-17", download_links=dict( human_raw="https://utexas.box.com/shared/static/z1qwxsuczjmv68p7267nylbv9ebc6g4p.hdf5", human_im="https://utexas.box.com/shared/static/2kun70ehqzanl5h0hbgpdezrfrvuimq8.hdf5", mg_im="https://utexas.box.com/shared/static/vdm6pzl68xqqxvk9iy7i3l62j37t3sbp.hdf5", ), ), PnPMicrowaveToCounter=dict( horizon=500, human_path="v0.1/single_stage/kitchen_pnp/PnPMicrowaveToCounter/2024-04-26", mg_path="v0.1/single_stage/kitchen_pnp/PnPMicrowaveToCounter/mg/2024-05-04-22-14-26_and_2024-05-07-07-41-42", download_links=dict( human_raw="https://utexas.box.com/shared/static/emnl5i3s621sf5smgek5lu4twbc326jt.hdf5", human_im="https://utexas.box.com/shared/static/z2t1kyto32thprw7xvq3r4tjvkdz0dl2.hdf5", mg_im="https://utexas.box.com/shared/static/3gs5cvp5qyzvk7gplmp0lkwfs1x1mkrj.hdf5", ), ), PnPCounterToStove=dict( horizon=500, human_path="v0.1/single_stage/kitchen_pnp/PnPCounterToStove/2024-04-26", mg_path="v0.1/single_stage/kitchen_pnp/PnPCounterToStove/mg/2024-05-04-22-14-20", download_links=dict( human_raw="https://utexas.box.com/shared/static/9z2k5iqspwdo2153yuutcvqb9zzzvtdu.hdf5", human_im="https://utexas.box.com/shared/static/penrv5sysn192gxwj7n7f6k0gjceovfn.hdf5", mg_im="https://utexas.box.com/shared/static/1ytpoks6mp9f56wh36ni8k02fz0kbvmb.hdf5", ), ), PnPStoveToCounter=dict( horizon=500, human_path="v0.1/single_stage/kitchen_pnp/PnPStoveToCounter/2024-05-01", mg_path="v0.1/single_stage/kitchen_pnp/PnPStoveToCounter/mg/2024-05-04-22-14-40", download_links=dict( human_raw="https://utexas.box.com/shared/static/1m3v1rkh7gna5ujt0vcwzej7stv5rdio.hdf5", human_im="https://utexas.box.com/shared/static/rht9bfh38gaue5ig17ubpsibb4jrgtyv.hdf5", mg_im="https://utexas.box.com/shared/static/uvrx2d7zxungplafbn9kg6rbe23ysund.hdf5", ), ), OpenSingleDoor=dict( horizon=500, human_path="v0.1/single_stage/kitchen_doors/OpenSingleDoor/2024-04-24", mg_path="v0.1/single_stage/kitchen_doors/OpenSingleDoor/mg/2024-05-04-22-37-39", download_links=dict( human_raw="https://utexas.box.com/shared/static/hjukxdpqvnrghtbjbhin28idzkysq7oa.hdf5", human_im="https://utexas.box.com/shared/static/vhvlbuza3g1lpqa9m6zvmbzh8xquvqy8.hdf5", mg_im="https://utexas.box.com/shared/static/ekf6qwp9s07jnkpazbohlv03d6b73vth.hdf5", ), ), CloseSingleDoor=dict( horizon=500, human_path="v0.1/single_stage/kitchen_doors/CloseSingleDoor/2024-04-24", mg_path="v0.1/single_stage/kitchen_doors/CloseSingleDoor/mg/2024-05-04-22-34-56", download_links=dict( human_raw="https://utexas.box.com/shared/static/gea28p5mrvj9lnw1s6c8fqvzxk5f779i.hdf5", human_im="https://utexas.box.com/shared/static/2wnm0u1x9fp9ni02pmzqzhpjsb1kgfrr.hdf5", mg_im="https://utexas.box.com/shared/static/5mg9vkhilkaxza83l48aht3sk76086tm.hdf5", ), ), OpenDoubleDoor=dict( horizon=1000, human_path="v0.1/single_stage/kitchen_doors/OpenDoubleDoor/2024-04-26", mg_path="v0.1/single_stage/kitchen_doors/OpenDoubleDoor/mg/2024-05-04-22-35-53", download_links=dict( human_raw="https://utexas.box.com/shared/static/xl23utiszzdbjdqlveq1mxxca9m3kbvw.hdf5", human_im="https://utexas.box.com/shared/static/8swihowjd5fdk1vpf0k94gl72f8nbjeb.hdf5", mg_im="https://utexas.box.com/shared/static/5djutjyyksic6qpl2uuq9cvzj3r78jvf.hdf5", ), ), CloseDoubleDoor=dict( horizon=700, human_path="v0.1/single_stage/kitchen_doors/CloseDoubleDoor/2024-04-29", mg_path="v0.1/single_stage/kitchen_doors/CloseDoubleDoor/mg/2024-05-04-22-22-42_and_2024-05-08-06-02-36", download_links=dict( human_raw="https://utexas.box.com/shared/static/zozyctzejc2nrlpjwqjq4w761830kq45.hdf5", human_im="https://utexas.box.com/shared/static/14f2ssfhwfhyo9cvj0s3kq303bv38g6t.hdf5", mg_im="https://utexas.box.com/shared/static/7t269kmcrsycc4wz5wonw62ijopjhyv7.hdf5", ), ), OpenDrawer=dict( horizon=500, human_path="v0.1/single_stage/kitchen_drawer/OpenDrawer/2024-05-03", mg_path="v0.1/single_stage/kitchen_drawer/OpenDrawer/mg/2024-05-04-22-38-42", download_links=dict( human_raw="https://utexas.box.com/shared/static/990d2f339zvalvlw50s4s1l6sfvt018m.hdf5", human_im="https://utexas.box.com/shared/static/d8a0g5827kbm4ufk3p1tbuz3idstgum8.hdf5", mg_im="https://utexas.box.com/shared/static/t0sio5vrdax5bdfqkumfh63inq6o9b88.hdf5", ), ), CloseDrawer=dict( horizon=500, human_path="v0.1/single_stage/kitchen_drawer/CloseDrawer/2024-04-30", mg_path="v0.1/single_stage/kitchen_drawer/CloseDrawer/mg/2024-05-09-09-32-19", download_links=dict( human_raw="https://utexas.box.com/shared/static/ooekd1zdy02hfu234xm5h63f7mzbez4b.hdf5", human_im="https://utexas.box.com/shared/static/4r5w0a6i4jtgv5qmqx09fnqh5d7c45oi.hdf5", mg_im="https://utexas.box.com/shared/static/aohabqltp8c6ze61u4h2uhtc9p9w35zb.hdf5", ), ), TurnOnSinkFaucet=dict( horizon=500, human_path="v0.1/single_stage/kitchen_sink/TurnOnSinkFaucet/2024-04-25", mg_path="v0.1/single_stage/kitchen_sink/TurnOnSinkFaucet/mg/2024-05-04-22-17-46", download_links=dict( human_raw="https://utexas.box.com/shared/static/7vogk85ed3sm1o1vo8fzast9rs8zshgk.hdf5", human_im="https://utexas.box.com/shared/static/f0brygtzwgmmwccg58b6m82yapa4jnji.hdf5", mg_im="https://utexas.box.com/shared/static/p8x9njpsf5j9fkmnu7lwajupzm1t7aap.hdf5", ), ), TurnOffSinkFaucet=dict( horizon=500, human_path="v0.1/single_stage/kitchen_sink/TurnOffSinkFaucet/2024-04-25", mg_path="v0.1/single_stage/kitchen_sink/TurnOffSinkFaucet/mg/2024-05-04-22-17-26", download_links=dict( human_raw="https://utexas.box.com/shared/static/ukkycoa2c6k5d6bpt1cdplzk2nrg879t.hdf5", human_im="https://utexas.box.com/shared/static/ceewfn4ydhprupdcdppfe8wu4x61oxdg.hdf5", mg_im="https://utexas.box.com/shared/static/r392ma0dje2t5ov4dug4vbqhn0z6hblk.hdf5", ), ), TurnSinkSpout=dict( horizon=500, human_path="v0.1/single_stage/kitchen_sink/TurnSinkSpout/2024-04-29", mg_path="v0.1/single_stage/kitchen_sink/TurnSinkSpout/mg/2024-05-09-09-31-12", download_links=dict( human_raw="https://utexas.box.com/shared/static/zxop70u9s6rl4udz7fhp4besrvu508pj.hdf5", human_im="https://utexas.box.com/shared/static/nnojt3760k143fxwhf2u0kzh1i56n7x1.hdf5", mg_im="https://utexas.box.com/shared/static/34l1y45xquau66nk8j7hrpfvlad4b9fg.hdf5", ), ), TurnOnStove=dict( horizon=500, human_path="v0.1/single_stage/kitchen_stove/TurnOnStove/2024-05-02", mg_path="v0.1/single_stage/kitchen_stove/TurnOnStove/mg/2024-05-08-09-20-31", download_links=dict( human_raw="https://utexas.box.com/shared/static/ow4npc933yty4blxg8rc2pgjp6f1yc36.hdf5", human_im="https://utexas.box.com/shared/static/dewbngq5wk6dipb29x6984x6dygu2gck.hdf5", mg_im="https://utexas.box.com/shared/static/7gzolvj3fyzhhfjoxswmmpjpxu5q4too.hdf5", ), ), TurnOffStove=dict( horizon=500, human_path="v0.1/single_stage/kitchen_stove/TurnOffStove/2024-05-02", mg_path="v0.1/single_stage/kitchen_stove/TurnOffStove/mg/2024-05-08-09-20-45", download_links=dict( human_raw="https://utexas.box.com/shared/static/vp6u3huv9c2vg5r09105gkbmwguycnn0.hdf5", human_im="https://utexas.box.com/shared/static/8tukea09szcjb2ncbe43zt65n7dzg4eh.hdf5", mg_im="https://utexas.box.com/shared/static/6rv14y77hfknrwfbwn5qtlfdydkr8tog.hdf5", ), ), CoffeeSetupMug=dict( horizon=600, human_path="v0.1/single_stage/kitchen_coffee/CoffeeSetupMug/2024-04-25", mg_path="v0.1/single_stage/kitchen_coffee/CoffeeSetupMug/mg/2024-05-04-22-22-13_and_2024-05-08-05-52-13", download_links=dict( human_raw="https://utexas.box.com/shared/static/zxytzos86xes7jo8z0gp7lklawbiyo8g.hdf5", human_im="https://utexas.box.com/shared/static/pv2i49t4p7238gp34txhm7jcl7domw58.hdf5", mg_im="https://utexas.box.com/shared/static/uagjbu3y2ds0hzm7789nuj0ppxp9dxxl.hdf5", ), ), CoffeeServeMug=dict( horizon=600, human_path="v0.1/single_stage/kitchen_coffee/CoffeeServeMug/2024-05-01", mg_path="v0.1/single_stage/kitchen_coffee/CoffeeServeMug/mg/2024-05-04-22-21-50", download_links=dict( human_raw="https://utexas.box.com/shared/static/tse3mkxx913pf4d4ij7fplchtv1rchkq.hdf5", human_im="https://utexas.box.com/shared/static/ts3537f93dzjpkux19syy0pndw5re231.hdf5", mg_im="https://utexas.box.com/shared/static/ikkr7qu89v9e0o1kwiqttkxllaxvv2n4.hdf5", ), ), CoffeePressButton=dict( horizon=300, human_path="v0.1/single_stage/kitchen_coffee/CoffeePressButton/2024-04-25", mg_path="v0.1/single_stage/kitchen_coffee/CoffeePressButton/mg/2024-05-04-22-21-32", download_links=dict( human_raw="https://utexas.box.com/shared/static/t6oblmeilexe9ndca4ccaxdclw1tzps5.hdf5", human_im="https://utexas.box.com/shared/static/l5dnmcfd0r36vhdqgjchxo20vajt7ohl.hdf5", mg_im="https://utexas.box.com/shared/static/y5zm9mlslfg8p4jkpwnxlizcsvsca1mb.hdf5", ), ), TurnOnMicrowave=dict( horizon=500, human_path="v0.1/single_stage/kitchen_microwave/TurnOnMicrowave/2024-04-25", mg_path="v0.1/single_stage/kitchen_microwave/TurnOnMicrowave/mg/2024-05-04-22-40-00", download_links=dict( human_raw="https://utexas.box.com/shared/static/o1sp7qrcd97b6jo68olx58l35wffpbna.hdf5", human_im="https://utexas.box.com/shared/static/t6eromogy5is2no3s1e5bk1nb2hgab2k.hdf5", mg_im="https://utexas.box.com/shared/static/t1n5oijudf8yn85bj8v64b1codde7kye.hdf5", ), ), TurnOffMicrowave=dict( horizon=500, human_path="v0.1/single_stage/kitchen_microwave/TurnOffMicrowave/2024-04-25", mg_path="v0.1/single_stage/kitchen_microwave/TurnOffMicrowave/mg/2024-05-04-22-39-23", download_links=dict( human_raw="https://utexas.box.com/shared/static/m2exfytqjd0496y70b3ou2i8993ryb50.hdf5", human_im="https://utexas.box.com/shared/static/0drm2h7fgd5857x8xgcj1lph23srpbj1.hdf5", mg_im="https://utexas.box.com/shared/static/7c8bku46us9a8sddwg3zk6z3p4ce6ya0.hdf5", ), ), NavigateKitchen=dict( horizon=500, human_path="v0.1/single_stage/kitchen_navigate/NavigateKitchen/2024-05-09", mg_path=None, download_links=dict( human_raw="https://utexas.box.com/shared/static/pzvzuvmkla74kro84yw13uwjr2g89z8m.hdf5", human_im="https://utexas.box.com/shared/static/mbi6011svy2zb436wsf2hhc337aduwmw.hdf5", ), ),)
MULTI_STAGE_TASK_DATASETS = OrderedDict( ArrangeVegetables=dict( human_path="v0.1/multi_stage/chopping_food/ArrangeVegetables/2024-05-11", horizon=1200, activity="chopping_food", download_links=dict( human_raw="https://utexas.box.com/shared/static/hiwbv68h3vty9ksqsdhcw2xhuvkwcf3o.hdf5", human_im="https://utexas.box.com/shared/static/ovzt0bod4nrrack6dak12jn1fx2cnwbw.hdf5", ), ), MicrowaveThawing=dict( human_path="v0.1/multi_stage/defrosting_food/MicrowaveThawing/2024-05-11", horizon=1000, activity="defrosting_food", download_links=dict( human_raw="https://utexas.box.com/shared/static/wreambog4jak8og9nbhm0nr2t6w5ygdt.hdf5", human_im="https://utexas.box.com/shared/static/ehwo6728r3qyi8g0h70zhawijojqotnm.hdf5", ), ), RestockPantry=dict( human_path="v0.1/multi_stage/restocking_supplies/RestockPantry/2024-05-10", horizon=1000, activity="restocking_supplies", download_links=dict( human_raw="https://utexas.box.com/shared/static/t2g6rdyh006bw09cxxxamd7thton5grl.hdf5", human_im="https://utexas.box.com/shared/static/35yr2xmsmwq0xkknvlmlivh9ifste71q.hdf5", ), ), PreSoakPan=dict( human_path="v0.1/multi_stage/washing_dishes/PreSoakPan/2024-05-10", horizon=1500, activity="washing_dishes", download_links=dict( human_raw="https://utexas.box.com/shared/static/d4vg2pag7465xp99vej1skk3frmohzk1.hdf5", human_im="https://utexas.box.com/shared/static/etotr8tn0z57ttb311bibh0mdmc65j96.hdf5", ), ), PrepareCoffee=dict( human_path="v0.1/multi_stage/brewing/PrepareCoffee/2024-05-07", horizon=1000, activity="brewing", download_links=dict( human_raw="https://utexas.box.com/shared/static/qhtle2ccvm17g65ecg2vrudpkl9v5wkk.hdf5", human_im="https://utexas.box.com/shared/static/qq3p4ctlmiv751jx5av92aaz9dxylw76.hdf5", ), ),)
def get_ds_path(task, ds_type, return_info=False): if task in SINGLE_STAGE_TASK_DATASETS: ds_config = SINGLE_STAGE_TASK_DATASETS[task] elif task in MULTI_STAGE_TASK_DATASETS: ds_config = MULTI_STAGE_TASK_DATASETS[task] else: raise ValueError
if ds_type == "human_raw": folder = ds_config["human_path"] fname = "demo.hdf5" elif ds_type == "human_im": folder = ds_config["human_path"] if task in SINGLE_STAGE_TASK_DATASETS: fname = "demo_gentex_im128_randcams.hdf5" elif task in MULTI_STAGE_TASK_DATASETS: fname = "demo_im128.hdf5" elif ds_type == "mg_im": # mg dataset is not available for all tasks folder = ds_config.get("mg_path", None) fname = "demo_gentex_im128_randcams.hdf5" else: raise ValueError
# if dataset type is not registered, return None if folder is None: ret = (None, None) if return_info is True else None return ret
if macros.DATASET_BASE_PATH is None: ds_base_path = os.path.join(Path(robocasa.__path__[0]).parent.absolute(), "datasets") else: ds_base_path = macros.DATASET_BASE_PATH ds_path = os.path.join(ds_base_path, folder, fname)
if return_info is False: return ds_path
ds_info = {} ds_info["url"] = ds_config["download_links"][ds_type] ds_info["horizon"] = ds_config["horizon"] return ds_path, ds_info123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899class DexMGConfigHelper: """ Helper class for multi-inheritance scenarios, specifically designed to support task configuration and environment interaction in robotic manipulation tasks.
Example Usage: This class is intended to be used in multi-inheritance cases such as: class PnPCounterToSink(Kitchen, DexMGConfigHelper) which will automatically generate a new configuration class: class PnPCounterToSink_Config(MG_Config)
Behavior: 1. In the implementation of the MG_RoboSuiteHumanoidGeneric class: - `self.env` will be an instance of PnPCounterToSink, enabling access to: - `self.env.get_object()` to retrieve key objects. - `self.env.get_subtask_term_signals()` to obtain signal information. 2. In the implementation of PnPCounterToSink_Config: - `self.task_config()` delegates to `PnPCounterToSink.task_config`, which defines subtask divisions based on objects and signals.
Attributes: subclasses (list): A list storing tuples of subclass names and their respective classes. """
class AttrDict(dict): def __getattr__(self, key): if key not in self: self[key] = ( DexMGConfigHelper.AttrDict() ) # Create a new AttrDict if key doesn't exist return self[key]
def __setattr__(self, key, value): self[key] = value
def to_dict(self): """Recursively converts AttrDict to a normal dictionary""" return { key: (value.to_dict() if isinstance(value, DexMGConfigHelper.AttrDict) else value) for key, value in self.items() }
subclasses = []
def __init_subclass__(cls, **kwargs): """ Automatically registers each subclass of DexMGConfigHelper.
Args: cls: The subclass being registered. kwargs: Additional keyword arguments. """ super().__init_subclass__(**kwargs) DexMGConfigHelper.subclasses.append((cls.__name__, cls))
def __init__(self): """ Initialize a DexMGConfigHelper instance. Note: This is an abstract class and should not be instantiated directly. """ pass
# Misc functions copied from dexmimicgen.mimicgen.env_interfaces.robosuite_humanoid def get_grippers(self): """ Get grippers for the environment. """ return self.robots[0].gripper["right"], self.robots[0].gripper["left"]
def get_object(self): """ Retrieve a key object required for the task. This method must be implemented in subclasses.
Raises: NotImplementedError: If the method is not overridden in a subclass. """ raise NotImplementedError
def get_subtask_term_signals(self): """ Retrieve signals used to define subtask termination conditions. This method must be implemented in subclasses.
Raises: NotImplementedError: If the method is not overridden in a subclass. """ raise NotImplementedError
@staticmethod def task_config(): """ Define the configuration for dividing a task into subtasks. This method must be implemented in subclasses.
Raises: NotImplementedError: If the method is not overridden in a subclass. """ raise NotImplementedError123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105from robocasa.utils.dataset_registry import ( get_ds_path, SINGLE_STAGE_TASK_DATASETS, MULTI_STAGE_TASK_DATASETS,)from robocasa.scripts.playback_dataset import get_env_metadata_from_datasetfrom robosuite.controllers import load_composite_controller_configimport osimport robosuiteimport imageioimport numpy as npfrom tqdm import tqdmfrom termcolor import colored
def create_env( env_name, # robosuite-related configs robots="PandaOmron", camera_names=[ "robot0_agentview_left", "robot0_agentview_right", "robot0_eye_in_hand", ], camera_widths=128, camera_heights=128, seed=None, # robocasa-related configs obj_instance_split=None, generative_textures=None, randomize_cameras=False, layout_and_style_ids=None, layout_ids=None, style_ids=None,): controller_config = load_composite_controller_config( controller=None, robot=robots if isinstance(robots, str) else robots[0], )
env_kwargs = dict( env_name=env_name, robots=robots, controller_configs=controller_config, camera_names=camera_names, camera_widths=camera_widths, camera_heights=camera_heights, has_renderer=False, has_offscreen_renderer=True, ignore_done=True, use_object_obs=True, use_camera_obs=True, camera_depths=False, seed=seed, obj_instance_split=obj_instance_split, generative_textures=generative_textures, randomize_cameras=randomize_cameras, layout_and_style_ids=layout_and_style_ids, layout_ids=layout_ids, style_ids=style_ids, translucent_robot=False, )
env = robosuite.make(**env_kwargs) return env
def run_random_rollouts(env, num_rollouts, num_steps, video_path=None): video_writer = None if video_path is not None: video_writer = imageio.get_writer(video_path, fps=20)
info = {} num_success_rollouts = 0 for rollout_i in tqdm(range(num_rollouts)): obs = env.reset() for step_i in range(num_steps): # sample and execute random action action = np.random.uniform(low=env.action_spec[0], high=env.action_spec[1]) obs, _, _, _ = env.step(action)
if video_writer is not None: video_img = env.sim.render( height=512, width=512, camera_name="robot0_agentview_center" )[::-1] video_writer.append_data(video_img)
if env._check_success(): num_success_rollouts += 1 break
if video_writer is not None: video_writer.close() print(colored(f"Saved video of rollouts to {video_path}", color="yellow"))
info["num_success_rollouts"] = num_success_rollouts
return info
if __name__ == "__main__": # select random task to run rollouts for env_name = np.random.choice(list(SINGLE_STAGE_TASK_DATASETS) + list(MULTI_STAGE_TASK_DATASETS)) env = create_eval_env(env_name=env_name) info = run_random_rollouts(env, num_rollouts=3, num_steps=100, video_path="/tmp/test.mp4")1234from .gymnasium_basic import RoboCasaEnv # noqa: F401
# from .gymnasium_gearbc import GearBCRoboCasaEnv # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417import datetime, uuidfrom copy import deepcopyimport gymnasium as gymimport h5pyimport numpy as npimport osimport robocasa.utils.transform_utils as Timport robosuitefrom gymnasium import spacesfrom robocasa.models.robots import ( GR00T_ROBOCASA_ENVS_GR1_ARMS_ONLY, GR00T_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST, GR00T_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY, gather_robot_observations, make_key_converter,)from robosuite.controllers import load_composite_controller_configfrom robosuite.controllers.composite.composite_controller import HybridMobileBasefrom robocasa.wrappers.ik_wrapper import IKWrapper
ALLOWED_LANGUAGE_CHARSET = ( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.\n\t[]{}()!?'_:")
def create_env_robosuite( env_name, # robosuite-related configs robots="PandaOmron", controller_configs=None, camera_names=[ "egoview", "robot0_eye_in_left_hand", "robot0_eye_in_right_hand", ], camera_widths=128, camera_heights=128, render_camera=None, enable_render=True, seed=None, # robocasa-related configs obj_instance_split=None, generative_textures=None, randomize_cameras=False, layout_and_style_ids=None, layout_ids=None, style_ids=None, onscreen=False, renderer="mujoco", translucent_robot=False, control_freq=20,): if controller_configs is None: controller_configs = load_composite_controller_config( controller=None, robot=robots if isinstance(robots, str) else robots[0], ) env_kwargs = dict( env_name=env_name, robots=robots, controller_configs=controller_configs, camera_names=camera_names, camera_widths=camera_widths, camera_heights=camera_heights, has_renderer=onscreen, has_offscreen_renderer=enable_render, renderer=renderer, ignore_done=True, use_object_obs=True, use_camera_obs=enable_render, camera_depths=False, seed=seed, translucent_robot=translucent_robot, control_freq=control_freq, render_camera=render_camera, randomize_cameras=randomize_cameras, )
env = robosuite.make(**env_kwargs) return env, env_kwargs
class RoboCasaEnv(gym.Env): def __init__( self, env_name=None, robots_name=None, camera_names=None, camera_widths=None, camera_heights=None, enable_render=True, render_camera=None, onscreen=False, dump_rollout_dataset_dir=None, rollout_hdf5=None, rollout_trainset=None, controller_configs=None, ik_indicator=False, **kwargs, # Accept additional kwargs ): self.key_converter = make_key_converter(robots_name) ( _, camera_names, default_camera_widths, default_camera_heights, ) = self.key_converter.get_camera_config()
if camera_widths is None: camera_widths = default_camera_widths if camera_heights is None: camera_heights = default_camera_heights
if controller_configs is not None: controller_configs = os.path.join( os.path.dirname(os.path.abspath(__file__)), "../../../", controller_configs, ) controller_configs = load_composite_controller_config( controller=controller_configs, robot=robots_name.split("_")[0], ) if ( robots_name in GR00T_ROBOCASA_ENVS_GR1_ARMS_ONLY or robots_name in GR00T_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST or robots_name in GR00T_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY ): controller_configs["type"] = "BASIC" controller_configs["composite_controller_specific_configs"] = {} controller_configs["control_delta"] = False
self.env, self.env_kwargs = create_env_robosuite( env_name=env_name, robots=robots_name.split("_"), controller_configs=controller_configs, camera_names=camera_names, camera_widths=camera_widths, camera_heights=camera_heights, render_camera=render_camera, enable_render=enable_render, onscreen=onscreen, **kwargs, # Forward kwargs to create_env_robosuite )
if ik_indicator: self.env = IKWrapper(self.env, ik_indicator=True)
# TODO: the following info should be output by gr00trobocasa self.camera_names = camera_names self.camera_widths = camera_widths self.camera_heights = camera_heights self.enable_render = enable_render and not onscreen self.render_obs_key = f"{camera_names[0]}_image" self.render_cache = None
# setup spaces action_space = spaces.Dict() for robot in self.env.robots: cc = robot.composite_controller pf = robot.robot_model.naming_prefix for part_name, controller in cc.part_controllers.items(): min_value, max_value = -1, 1 start_idx, end_idx = cc._action_split_indexes[part_name] shape = [end_idx - start_idx] this_space = spaces.Box( low=min_value, high=max_value, shape=shape, dtype=np.float32 ) action_space[f"{pf}{part_name}"] = this_space if isinstance(cc, HybridMobileBase): this_space = spaces.Discrete(2) action_space[f"{pf}base_mode"] = this_space
action_space = spaces.Dict(action_space) self.action_space = action_space
# Calling env._get_observations(force_update=True) will pollute the observables. # This is safe because it is only called from the constructor and will be overwritten later in reset(). obs = ( self.env.viewer._get_observations(force_update=True) if self.env.viewer_get_obs else self.env._get_observations(force_update=True) ) obs.update(gather_robot_observations(self.env)) observation_space = spaces.Dict() for obs_name, obs_value in obs.items(): shape = list(obs_value.shape) if obs_name.endswith("_image"): continue min_value, max_value = -1, 1 this_space = spaces.Box(low=min_value, high=max_value, shape=shape, dtype=np.float32) observation_space[obs_name] = this_space
for camera_name in camera_names: shape = [camera_heights, camera_widths, 3] this_space = spaces.Box(low=0, high=255, shape=shape, dtype=np.uint8) observation_space[f"{camera_name}_image"] = this_space
observation_space["language"] = spaces.Text( max_length=256, charset=ALLOWED_LANGUAGE_CHARSET )
self.observation_space = observation_space
self.dump_rollout_dataset_dir = dump_rollout_dataset_dir self.gr00t_exporter = None self.np_exporter = None
self.rollout_hdf5 = rollout_hdf5 self.rollout_trainset = rollout_trainset self.rollout_initial_state = {}
def begin_rollout_dataset_dump(self): if self.dump_rollout_dataset_dir is not None: gr00t_env_meta = dict( env_name=self.env_kwargs["env_name"], env_version=robosuite.__version__, type=1, env_kwargs=deepcopy(self.env_kwargs), ) gr00t_dir = os.path.join( self.dump_rollout_dataset_dir, self.env_kwargs["env_name"] + "_" + "_".join(robot.name for robot in self.env.robots) + "_Env", f"{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}-{str(uuid.uuid4())[:8]}", ) if not os.path.exists(gr00t_dir): os.makedirs(gr00t_dir, exist_ok=True) self.gr00t_exporter = Gr00tExporter( gr00t_dir, self.env, gr00t_env_meta, ) self.np_exporter = {} self.np_exporter["success"] = [] for signal in self.env.get_subtask_term_signals(): self.np_exporter[signal] = []
def process_rollout_dataset_dump_before_step(self, env_action): if self.gr00t_exporter is not None: self.gr00t_exporter.add_record_before_step(self.env, env_action) self.np_exporter["success"].append(self.env.reward()) for signal, value in self.env.get_subtask_term_signals().items(): self.np_exporter[signal].append(value)
def process_rollout_dataset_dump_after_step(self, env_action): if self.gr00t_exporter is not None: self.gr00t_exporter.add_record_after_step(self.env, env_action)
def complete_rollout_dataset_dump(self): if self.gr00t_exporter is not None and self.np_exporter is not None: data = {k: np.array(v, dtype=np.float32) for k, v in self.np_exporter.items()} np.savez(os.path.join(self.gr00t_exporter.gr00t_dir, "rewards.npz"), **data) self.gr00t_exporter.finish() self.np_exporter = None self.gr00t_exporter = None
def get_basic_observation(self, raw_obs): raw_obs.update(gather_robot_observations(self.env))
# Image are in (H, W, C), flip it upside down def process_img(img): return np.copy(img[::-1, :, :])
for obs_name, obs_value in raw_obs.items(): if obs_name.endswith("_image"): # image observations raw_obs[obs_name] = process_img(obs_value) else: # non-image observations raw_obs[obs_name] = obs_value.astype(np.float32)
# Return black image if rendering is disabled if not self.enable_render: for name in self.camera_names: raw_obs[f"{name}_image"] = np.zeros( (self.camera_heights, self.camera_widths, 3), dtype=np.uint8 )
self.render_cache = raw_obs[self.render_obs_key] raw_obs["language"] = self.env.get_ep_meta().get("lang", "")
return raw_obs
def reset(self, seed=None, options=None): if seed is not None and self.rollout_trainset is not None and seed < self.rollout_trainset: if seed not in self.rollout_initial_state: f = h5py.File(self.rollout_hdf5, "r") demos = list(f["data"].keys()) inds = np.argsort([int(elem[5:]) for elem in demos]) demos = [demos[i] for i in inds] ep = demos[seed] self.rollout_initial_state[seed] = { "states": f["data/{}/states".format(ep)][0], "ep_meta": f["data/{}".format(ep)].attrs.get("ep_meta", None), "model": f["data/{}".format(ep)].attrs["model_file"], } reset_to(self.env, self.rollout_initial_state[seed]) obs = None else: # NOTE: self.env can be either a robosuite environment or ik wrapper if isinstance(self.env, IKWrapper): self.env.unwrapped.seed = seed self.env.unwrapped.rng = np.random.default_rng(seed=seed) else: self.env.seed = seed self.env.rng = np.random.default_rng(seed=seed) raw_obs = self.env.reset() obs = self.get_basic_observation(raw_obs)
info = {} info["success"] = False info["intermediate_signals"] = {}
self.complete_rollout_dataset_dump() self.begin_rollout_dataset_dump()
return obs, info
def step(self, action_dict): env_action = [] for robot in self.env.robots: cc = robot.composite_controller pf = robot.robot_model.naming_prefix action = np.zeros(cc.action_limits[0].shape) for part_name, controller in cc.part_controllers.items(): start_idx, end_idx = cc._action_split_indexes[part_name] act = action_dict.pop(f"{pf}{part_name}") action[start_idx:end_idx] = act
# set external torque compensation if available if "gripper" not in part_name and controller.use_external_torque_compensation: controller.external_torque_compensation = action_dict.pop( f"{pf}{part_name}_tau" ) if isinstance(cc, HybridMobileBase): action[-1] = action_dict.pop(f"{pf}base_mode") env_action.append(action)
env_action = np.concatenate(env_action)
self.process_rollout_dataset_dump_before_step(env_action) raw_obs, reward, done, info = self.env.step(env_action) self.process_rollout_dataset_dump_after_step(env_action)
obs = self.get_basic_observation(raw_obs)
truncated = False
info["success"] = reward > 0 info["intermediate_signals"] = {} if hasattr(self.env, "_get_intermediate_signals"): info["intermediate_signals"] = self.env._get_intermediate_signals()
if hasattr(self.env, "_get_auxiliary_states"): info["auxiliary_states"] = self.env._get_auxiliary_states()
if hasattr(self.env, "obj_body_id"): for obj_name in self.env.obj_body_id.keys(): info[f"{obj_name}_pos"] = list( self.env.sim.data.body_xpos[self.env.obj_body_id[obj_name]] ) info[f"{obj_name}_quat_xyzw"] = list( T.convert_quat( np.array(self.env.sim.data.body_xquat[self.env.obj_body_id[obj_name]]), to="xyzw", ) )
return obs, reward, done, truncated, info
def render(self): if self.render_cache is None: raise RuntimeError("Must run reset or step before render.") return self.render_cache
def close(self): self.complete_rollout_dataset_dump() self.env.close()
def get_actuator_names(self): joint_names = self.get_joint_names()
model = self.env.sim.model
actuated_joint_names = [] for ii in range(model.nu): joint_id = model.actuator_trnid[ii, 0] actuated_joint_names.append(model.joint(joint_id).name)
actuator_names = {} actuator_indices = {} for part_name, _joint_names in joint_names.items(): actuator_names[part_name] = [] actuator_indices[part_name] = [] for _jn in _joint_names: if _jn in actuated_joint_names: actuator_names[part_name].append(_jn) actuator_indices[part_name].append(actuated_joint_names.index(_jn)) actuator_names[part_name] = ( np.array(actuator_names[part_name])[np.argsort(actuator_indices[part_name])] ).tolist() return actuator_names
def get_joint_names(self): joint_names = {} for _robot in self.env.robots: cc = _robot.composite_controller for part_name, part_controller in cc.part_controllers.items(): if "gripper" in part_name: joint_names[part_name] = part_controller.joint_index else: joint_names[part_name] = part_controller.joint_names return joint_names123import os
assets_root = os.path.join(os.path.dirname(__file__), "assets")1234567891011121314151617181920212223242526272829303132333435from pathlib import Path
# import robosuite_model_zooimport osimport shutil
def get_ext(path): return Path(path).suffix
def get_stem(path): return Path(path).stem
def get_name(path): return Path(path).name
def make_asset_path(base_asset_path, model_prefix, model_name): if base_asset_path is None: base_asset_path = os.path.join( os.path.dirname(robosuite_model_zoo.__file__), "assets_private", ) if model_prefix is not None: base_asset_path = os.path.join(base_asset_path, model_prefix) asset_path = os.path.join(base_asset_path, model_name)
if os.path.exists(asset_path): shutil.rmtree(asset_path)
os.makedirs(asset_path)
return asset_path123456789101112131415161718192021222324252627<mujoco model=""> <asset> </asset> <default> <default class="visual"> <geom conaffinity="0" contype="0" group="1" type="mesh"/> </default> <default class="collision"> <geom group="0" rgba="0.5 0 0 0.5"/> </default> </default> <worldbody> <body> <!-- exterior bounding box points --> <site rgba="0 0 0 1" size="0.01" pos="0 0 0" name="ext_p0"/> <site rgba="1 0 0 1" size="0.01" pos="0 0 0" name="ext_px"/> <site rgba="0 1 0 1" size="0.01" pos="0 0 0" name="ext_py"/> <site rgba="0 0 1 1" size="0.01" pos="0 0 0" name="ext_pz"/>
<!-- interior bounding box points --> <site rgba="0.5 0.5 0.5 1" size="0.01" pos="0 0 0" name="int_p0"/> <site rgba="1 1 0 1" size="0.01" pos="0 0 0" name="int_px"/> <site rgba="0 1 1 1" size="0.01" pos="0 0 0" name="int_py"/> <site rgba="1 0 1 1" size="0.01" pos="0 0 0" name="int_pz"/> </body> </worldbody></mujoco>123456789101112131415161718192021#!/bin/bash## Install V-HACD 4.0.# Adapted from https://github.com/kevinzakka/obj2mjcf/blob/main/install_vhacd.sh
# Check that cmake is installed.t=`which cmake`if [ -z "$t" ]; then echo "You need cmake to install V-HACD." 1>&2 exit 1fi
# Clone and build executable.# TODO(kevin): Peg to a 4.0 release when available, see #113.git clone https://github.com/kmammou/v-hacd.gitcd v-hacd/appcmake CMakeLists.txtcmake --build .
# Add executable to /usr/local/bin.sudo ln -s "$PWD/TestVHACD" /usr/local/bin/TestVHACD12345678910111213141516171819202122232425262728293031323334353637383940414243444546import jsonimport numpy as npfrom termcolor import coloredfrom copy import deepcopyimport osimport sysimport textwrap
class NumpyEncoder(json.JSONEncoder): """ Special json encoder for numpy types From https://stackoverflow.com/a/49677241 """
def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj)
def maybe_log_info(message, log=False, color="yellow", indent=False): if log: if indent: message = textwrap.indent(message, " " * 5) print(colored(message, color))
def save_meta(args, asset_path): # get args meta = vars(args)
# get relative path of running script script_path = os.path.abspath(sys.argv[0]) path_list = script_path.split("/") # idx = len(path_list) - 1 - path_list[::-1].index("robosuite_model_zoo") # meta["script"] = "/".join(path_list[idx:]) meta["cmd"] = "python " + " ".join(sys.argv)
# save meta data with open(os.path.join(asset_path, "meta.json"), "w") as outfile: json.dump(meta, outfile, indent=4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800import numpy as npimport trimeshimport osimport robosuiteimport xml.etree.ElementTree as ETimport shutilimport jsonfrom termcolor import coloredfrom copy import deepcopyfrom pathlib import Path
# import robosuite_model_zoofrom robosuite.utils.transform_utils import mat2quatimport robocasa.utils.model_zoo.log_utils as LogUtilsimport robocasa.utils.model_zoo.mtl_utils as MtlUtils
from robosuite.utils.mjcf_utils import array_to_string, string_to_array
def parse_model_info( model_path, model_name, coll_model_path, asset_path, obj_path=None, verbose=False, center=False, prescale=False, rot=None, transform=None,): """ Extract visual and collision geoms from main model file and collision model file """
LogUtils.maybe_log_info("Parsing input models...", log=verbose)
geoms, textures, materials, transform = parse_model( model_path, model_name, asset_path, obj_path=obj_path, center=center, prescale=prescale, rot=rot, transform=transform, # visual_only=(coll_model_path is None), visual_only=True, verbose=verbose, )
coll_geoms, bb_info = parse_coll_model( coll_model_path, asset_path, verbose=verbose, transform=transform, )
if coll_geoms is not None: geoms = geoms + coll_geoms
geoms_to_print = deepcopy(geoms) for g in geoms_to_print: if "rot_orig" in g: del g["rot_orig"] LogUtils.maybe_log_info( "parsed geoms:\n" + json.dumps(geoms_to_print, indent=4, cls=LogUtils.NumpyEncoder), log=verbose, indent=True, )
model_info = dict( geoms=geoms, textures=textures, materials=materials, bb=bb_info, )
return model_info
def parse_model( model_path, model_name, asset_path, obj_path=None, visual_only=False, center=False, prescale=False, rot=None, transform=None, verbose=False,): """ Extract meshes from main model file """
LogUtils.maybe_log_info( "parsing (main) model: {}".format(model_path), log=verbose, indent=True, )
# load the model if obj_path is None: obj_files = [ os.path.join(model_path, name) for name in os.listdir(model_path) if name.endswith(".obj") ] obj_file = obj_files[0] else: obj_file = obj_path
geoms, textures, materials = [], [], [] vis_path = os.path.join(asset_path, "visual") coll_path = os.path.join(asset_path, "collision")
if not os.path.isdir(vis_path): os.makedirs(vis_path) if not os.path.isdir(coll_path): os.makedirs(coll_path)
resolver = trimesh.resolvers.FilePathResolver(os.path.dirname(obj_file)) model = trimesh.load( obj_file, resolver=resolver, split_object=True, # group_material=True, process=False, maintain_order=False, )
# If transform is passed as an argument, center and prescale must be False. Rotation is applied afterward regardless. if transform is not None: assert center is False and prescale is False
if center: mat_t = np.eye((4)) center = (model.bounds[0] + model.bounds[1]) / 2 mat_t[:3, 3] = -center transform = mat_t
if prescale: mat_s = np.eye((4)) scale_factor = 1 / np.max(model.bounds[1] - model.bounds[0]) mat_s *= scale_factor
if transform is None: transform = mat_s else: transform = np.matmul(mat_s, transform)
rot = rot or [] for r in rot: mat_R = np.eye(4)
if r in ["x", "x90"]: mat_R[:3, :3] = [[1, 0, 0], [0, 0, -1], [0, 1, 0]] elif r in ["x180"]: mat_R[:3, :3] = [[1, 0, 0], [0, -1, 0], [0, 0, -1]] elif r in ["x270"]: mat_R[:3, :3] = [[1, 0, 0], [0, 0, 1], [0, -1, 0]]
elif r in ["y", "y90"]: mat_R[:3, :3] = [[0, 0, 1], [0, 1, 0], [-1, 0, 0]] elif r in ["y180"]: mat_R[:3, :3] = [[-1, 0, 0], [0, 1, 0], [0, 0, -1]] elif r in ["y270"]: mat_R[:3, :3] = [[0, 0, -1], [0, 1, 0], [1, 0, 0]]
elif r in ["z", "z90"]: mat_R[:3, :3] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]] elif r in ["z180"]: mat_R[:3, :3] = [[-1, 0, 0], [0, -1, 0], [0, 0, 1]] elif r in ["z270"]: mat_R[:3, :3] = [[0, 1, 0], [-1, 0, 0], [0, 0, 1]] elif r in ["z60"]: mat_R[:3, :3] = [ [0.5000000, -0.8660254, 0.0000000], [0.8660254, 0.5000000, 0.0000000], [0, 0, 1], ]
else: raise ValueError("Invalid choice of rotation {}".format(r))
if transform is None: transform = mat_R else: transform = np.matmul(mat_R, transform)
if transform is not None: if isinstance(model, trimesh.base.Trimesh): model.apply_transform(transform) else: for k in model.geometry: model.geometry[k].apply_transform(transform)
# debugging # model.show() # exit()
mtls = MtlUtils.get_mtls(obj_file, work_dir=vis_path)
""" save mtl info. this section adapted from obj2mjf (credit: Kevin Zakka) """ for mtl in mtls: if mtl.map_Kd is not None: # Create the texture asset. texture_path = Path(mtl.map_Kd) texture = dict( type="2d", name=texture_path.stem, file=os.path.join("visual", texture_path.name), ) # Reference the texture asset in a material asset. material = dict( name=mtl.name, texture=texture_path.stem, specular=mtl.mjcf_specular(), shininess=mtl.mjcf_shininess(), )
textures.append(texture) materials.append(material) else: material = dict( name=mtl.name, specular=mtl.mjcf_specular(), shininess=mtl.mjcf_shininess(), rgba=mtl.mjcf_rgba(), ) materials.append(material)
submodels = []
if isinstance(model, trimesh.base.Trimesh): submodels = [(materials[-1]["name"], model)] else: submodels = list(model.geometry.items())
for sm_i, (sm_name, sm) in enumerate(submodels): # ch_mesh = sm.convex_hull # bb_mesh = sm.bounding_box_oriented
# set visual geom path, copy to visual folder # model_file = os.path.basename(model_path) obj_name = os.path.basename(obj_file)[:-4] vis_geom_path = os.path.join(vis_path, "{}_{}.obj".format(obj_name, sm_i)) # shutil.copyfile( # obj_file, # vis_geom_path, # ) sm.export(vis_geom_path)
vis_geom = dict( obj_type="visual", geom_type="mesh", path=vis_geom_path, name="{}_{}_vis".format(obj_name, sm_i), material=sm_name, # **get_bb_info(sm.bounding_box_oriented) ) geoms.append(vis_geom)
if visual_only: continue
ch_mesh = sm.convex_hull # bb_mesh = ch_mesh.bounding_box_oriented
# obj_name = os.path.basename(obj_file)[:-3] coll_geom_path = os.path.join(coll_path, "{}_{}.obj".format(obj_name, sm_i)) coll_geom = dict( obj_type="collision", geom_type="mesh", # path=os.path.join(coll_path, "{}_ch.stl".format(model_name)), path=coll_geom_path, name="{}_{}_coll".format(obj_name, sm_i), **get_bb_info(ch_mesh.bounding_box_oriented), ) geoms.append(coll_geom) ch_mesh.export(coll_geom["path"])
return geoms, textures, materials, transform
def parse_coll_model( coll_model_path, asset_path, verbose=False, transform=None,): """ Extract list of primitive geoms from collision model file """
if coll_model_path is None: return None, None
LogUtils.maybe_log_info( "parsing collision model: {}".format(coll_model_path), log=verbose, indent=True, )
# load the model obj_files = [ os.path.join(coll_model_path, name) for name in os.listdir(coll_model_path) if name.endswith(".obj") ]
geoms = [] coll_path = os.path.join(asset_path, "collision")
scene = trimesh.scene.scene.Scene()
for obj_file in obj_files: resolver = trimesh.resolvers.FilePathResolver(os.path.dirname(obj_file)) model = trimesh.load(obj_file, resolver=resolver)
if transform is not None: model.apply_transform(transform) model.export(obj_file)
# ch_mesh = model.convex_hull # bb_mesh = ch_mesh.bounding_box_oriented
scene.add_geometry(model)
if not os.path.isdir(coll_path): os.makedirs(coll_path)
# set visual geom path, copy to visual folder # model_file = os.path.basename(model_path) obj_name = os.path.basename(obj_file)[:-3] coll_geom_path = os.path.join(coll_path, os.path.basename(obj_file)) # shutil.copyfile( # obj_file, # coll_geom_path, # )
# obj_name = os.path.basename(obj_file)[:-3] coll_geom = dict( obj_type="collision", geom_type="mesh", # path=os.path.join(coll_path, "{}_ch.stl".format(model_name)), path=coll_geom_path, name="{}_coll".format(obj_name), # **get_bb_info(bb_mesh) ) geoms.append(coll_geom)
bb_info = get_bb_info(scene.bounding_box)
# f = open(coll_model_path, "r") # lines = f.readlines() # f.close()
# geoms = []
# start_inds = [i for (i, line) in enumerate(lines) if line.startswith("o ")]
# num_coll_meshes = 0 # for start, end in zip(start_inds, start_inds[1:] + [len(lines)]): # obj_lines = lines[start:end]
# # filter out lines corresponding to faces # obj_lines_filtered = [line for line in obj_lines if not line.startswith("f ")]
# geom = dict()
# tmp = tempfile.NamedTemporaryFile(suffix=".obj") # with open(tmp.name, "w") as f: # [f.write(line) for line in obj_lines_filtered]
# mesh = trimesh.load(tmp.name)
# bb_mesh = mesh.bounding_box_oriented
# geom.update( # obj_name=obj_lines[0], # obj_type="collision", # **get_bb_info(bb_mesh) # )
# obj_type_substr = obj_lines_filtered[0][2:] # if obj_type_substr.startswith("Cube"): # geom_type = "box" # elif obj_type_substr.startswith("Cylinder"): # geom_type = "cylinder"
# """ # post-process size and orientation of cylinder # """
# pos = geom["pos"] # quat = geom["quat"] # size = geom["size"]
# T = bb_mesh.primitive.transform
# trans_mesh = mesh.copy() # trans_mesh.apply_transform(np.linalg.inv(T))
# V = np.array(trans_mesh.vertices) # n = len(V) # number of vertices # th = 1e-5 # threshold for checking vertices
# upright_axis = None # for idx in [0, 1, 2]: # V = np.take(V, indices=np.argsort(V, axis=0)[:,idx], axis=0)
# if np.std(V[:n//2,idx]) < th and np.std(V[-n//2:,idx]) < th: # upright_axis = idx
# assert upright_axis is not None # circle_axes = np.delete(np.arange(3), upright_axis) # assert np.abs(size[circle_axes][1] - size[circle_axes][0]) < 0.01, ( # "Detected elliptic cylinder! " # "Mujoco only accepts circular cylinders." # )
# if upright_axis == 0: # geom["quat"] = mat2quat( # np.linalg.inv( # np.matmul( # np.array([ # [0, 0, 1], # [0, 1, 0], # [-1, 0, 0], # ]), # np.linalg.inv(geom["rot_orig"]) # ) # ) # )[[3,0,1,2]] # elif upright_axis == 1: # raise NotImplementedError
# geom["size"] = [np.mean(size[circle_axes]), size[upright_axis]]
# elif obj_type_substr.startswith("Sphere"): # geom_type = "ellipsoid" # else: # raise ValueError( # "Detected non-primitive object in collision model:", # obj_lines_filtered[0] # )
# geom["geom_type"] = geom_type
# geoms.append(geom)
return geoms, bb_info
def get_geom_element(model_name, geom_info, sc=1.0, show_if_coll_geom=False): """ Generate xml element for mjcf geom """
if geom_info.get("hide", False): return None
elem = ET.Element("geom")
elem.attrib["solimp"] = "0.998 0.998 0.001" elem.attrib["solref"] = "0.001 1" elem.attrib["density"] = "100" elem.attrib["friction"] = "0.95 0.3 0.1"
if geom_info["geom_type"] == "mesh": elem.attrib["type"] = "mesh" elem.attrib["mesh"] = geom_info["name"] else: raise NotImplementedError elem.attrib["type"] = geom_info["geom_type"] elem.attrib["pos"] = " ".join(["{:.5f}".format(v * sc) for v in geom_info["pos"]]) elem.attrib["quat"] = " ".join(["{:.5f}".format(v) for v in geom_info["quat"]]) size = geom_info["size"] elem.attrib["size"] = " ".join(["{:.5f}".format(v * sc / 2) for v in size])
if geom_info["obj_type"] == "visual": elem.attrib["conaffinity"] = "0" elem.attrib["contype"] = "0" elem.attrib["group"] = "1" elem.attrib["material"] = geom_info.get("material", model_name) elif geom_info["obj_type"] == "collision": elem.attrib["group"] = "0" # elem.attrib["condim"] = "4"
if show_if_coll_geom: elem.attrib["rgba"] = "0.8 0.8 0.8 0.3" else: elem.attrib["rgba"] = "0.8 0.8 0.8 0.0"
return elem
def get_texture_element(texture_info): elem = ET.Element("texture")
for k, v in texture_info.items(): elem.attrib[k] = str(v)
return elem
def get_material_element(material_info): elem = ET.Element("material")
for k, v in material_info.items(): elem.attrib[k] = str(v)
return elem
def get_mesh_element(geom_info, sc=1.0): """ Generate xml element for mjcf mesh asset """ assert geom_info["geom_type"] == "mesh"
if geom_info.get("hide", False): return None
elem = ET.Element("mesh")
elem.attrib["file"] = "/".join(geom_info["path"].split("/")[-2:]) elem.attrib["name"] = geom_info["name"] elem.attrib["scale"] = "{sc} {sc} {sc}".format(sc=sc)
return elem
def generate_mjcf( asset_path, model_name, model_info, sc=1.0, texture_path=None, hide_vis_geoms=False, show_coll_geoms=False, show_sites=False, verbose=False,): """ Generate mjcf model for object """
LogUtils.maybe_log_info("Generating MJCF...", log=verbose)
geoms = model_info["geoms"] textures = model_info["textures"] materials = model_info["materials"] bb_info = model_info["bb"]
### for now, assume mtl doesn't contain texture #### # texture_from_mtl = False # if texture_path is None: # # get the texture used in the mtl file # mtl_path = model_path[:-3] + 'mtl' # texture_dict = {} # with open(mtl_path, "r") as f: # for i, line in enumerate(f.readlines()): # if len(line) > 1: # key, value = line.split(" ", 1) # texture_dict[key] = value.strip() # # if "map_Kd" in texture_dict: # texture_path = texture_dict["map_Kd"] # texture_from_mtl = True
# load template xml tree = ET.parse( os.path.join(os.path.dirname(os.path.realpath(__file__)), "object_template.xml") ) root = tree.getroot()
# set model name root.attrib["model"] = model_name
# add mesh assets asset = root.find("asset") for geom in geoms: if geom["geom_type"] == "mesh": mesh_elem = get_mesh_element(geom, sc=sc) if mesh_elem is not None: asset.append(mesh_elem)
# update default texture and material assets texture = asset.find("texture") texture.attrib["name"] = texture.attrib["name"].replace("template", model_name) if texture_path is not None: texture.attrib["file"] = "/".join(texture_path.split("/")[-1:]) else: texture.attrib["file"] = os.path.join( os.path.dirname(robosuite.__file__), "models/assets/textures/ceramic.png" ) material = asset.find("material") for k in ["name", "texture"]: material.attrib[k] = material.attrib[k].replace("template", model_name)
# add textures for texture in textures: texture_elem = get_texture_element(texture) if texture_elem is not None: asset.append(texture_elem)
# add materials for material in materials: material_elem = get_material_element(material) if material_elem is not None: asset.append(material_elem)
# add geoms worldbody = root.find("worldbody") body = worldbody.find("body").find("body") for geom in geoms: if geom["obj_type"] == "visual" and hide_vis_geoms: continue
geom_elem = get_geom_element( model_name, geom, sc=sc, show_if_coll_geom=show_coll_geoms, ) if geom_elem is not None: body.append(geom_elem)
sites = worldbody.find("body").findall("site")
if show_sites: object_body = worldbody.find("body").find("body") vis_site_strings = [ """<site rgba="1 0 0 1" size="0.005" pos="0 0 0" name="bottom_site"/>""", """<site rgba="0 1 0 1" size="0.005" pos="0 0 0" name="top_site"/>""", """<site rgba="0 0 1 1" size="0.005" pos="0 0 0" name="horizontal_radius_site"/>""", ] for s in vis_site_strings: object_body.append(ET.fromstring(s))
# for debugging vis_sites = object_body.findall("site") sites = sites + vis_sites
if bb_info is not None: for site in sites: if site.get("name") == "horizontal_radius_site": pos = bb_info["pos"].copy() pos[0] += bb_info["size"][0] / 2 pos[1] += bb_info["size"][1] / 2 pos = np.array([pos[0], pos[1], pos[2]]) site.set("pos", array_to_string(pos * sc)) elif site.get("name") == "bottom_site": pos = bb_info["pos"].copy() pos[2] -= bb_info["size"][2] / 2 pos = np.array([pos[0], pos[1], pos[2]]) site.set("pos", array_to_string(pos * sc)) elif site.get("name") == "top_site": pos = bb_info["pos"].copy() pos[2] += bb_info["size"][2] / 2 pos = np.array([pos[0], pos[1], pos[2]]) site.set("pos", array_to_string(pos * sc))
# save xml for new model mjcf_path = os.path.join(asset_path, "model.xml") tree.write(mjcf_path, encoding="utf-8") LogUtils.maybe_log_info("Wrote MJCF to: {}".format(mjcf_path), log=verbose, indent=True)
# LogUtils.maybe_log_info( # "\nTest generated MJCF with robosuite:\npython {base_path}/scripts/object_play.py --device spacemouse --mjcf_path {mjcf_path}".format( # base_path=os.path.dirname(robosuite_model_zoo.__file__), # mjcf_path=mjcf_path, # ), # log=True, # color="green" # )
return mjcf_path
def get_file_name_and_type(path): """ Extract name of object model file and file format """ split_name = os.path.basename(path).split(".") assert len(split_name) == 2 return split_name[0], split_name[1]
def get_bb_info(bb_mesh): """ Extract size, position, and orientation (quat) from bounding box mesh """ ext = np.array(bb_mesh.primitive.extents) transform = np.array(bb_mesh.primitive.transform)
center = transform[:-1, 3] rot = transform[:3, :3] quat = mat2quat(rot)[[3, 0, 1, 2]]
return dict( pos=center, quat=quat, size=ext, rot_orig=rot, )
def decompose_convex( filename, work_dir, # V-HACD params max_output_convex_hulls=32, voxel_resolution=100000, volume_error_percent=1.0, max_hull_vert_count=64,): """ Adapted from https://github.com/kevinzakka/obj2mjcf/blob/main/obj2mjcf/_cli.py """
_VHACD_EXECUTABLE = shutil.which("TestVHACD") _VHACD_OUTPUTS = ["decomp.obj", "decomp.stl"]
obj_file = filename.resolve()
import tempfile import subprocess from pathlib import Path import enum
with tempfile.TemporaryDirectory() as tmpdirname: prev_dir = os.getcwd() os.chdir(tmpdirname)
# Copy the obj file to the temporary directory. shutil.copy(obj_file, tmpdirname)
# Call V-HACD, suppressing output. ret = subprocess.run( [ f"{_VHACD_EXECUTABLE}", obj_file.name, "-o", "obj", "-h", f"{max_output_convex_hulls}", # max_output_convex_hulls "-r", f"{voxel_resolution}", # voxel_resolution "-e", f"{volume_error_percent}", # volume_error_percent "-d", f"{14}", # max_recursion_depth "-s", f"{int(not False)}", # disable_shrink_wrap # "-f", # f"{enum.auto().name.lower()}", # fill_mode.name.lower() "-v", f"{max_hull_vert_count}", # max_hull_vert_count "-a", f"{int(not False)}", # disable_async "-l", f"{2}", # min_edge_length "-p", f"{int(False)}", # split_hull ], # stdout=subprocess.DEVNULL, # stderr=subprocess.STDOUT, check=True, ) # if ret.returncode != 0: # logging.error(f"V-HACD failed on {filename}") # return False
# Remove the original obj file and the V-HACD output files. for name in _VHACD_OUTPUTS + [obj_file.name]: file_to_delete = Path(tmpdirname) / name if file_to_delete.exists(): file_to_delete.unlink()
os.chdir(prev_dir)
# Get list of sorted collisions. collisions = list(Path(tmpdirname).glob("*.obj")) collisions.sort(key=lambda x: x.stem)
os.makedirs(work_dir.resolve(), exist_ok=True)
for i, filename in enumerate(collisions): savename = str(work_dir / f"{obj_file.stem}_collision_{i}.obj") shutil.move(str(filename), savename)
return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251import osimport timeimport numpy as npimport tempfileimport randomimport stringimport xml.etree.ElementTree as ET
import robosuite
from robosuite.models.objects import MujocoXMLObjectfrom robosuite.utils.mjcf_utils import array_to_string, string_to_array
import robosuite.utils.transform_utils as T
import robosuite_model_zoo
def postprocess_model_xml(xml_str): """ New version of postprocess model xml that only replaces robosuite file paths if necessary (otherwise there is an error with the "max" operation), and also replaces robosuite-model-zoo file paths if necessary. """
path = os.path.split(robosuite.__file__)[0] path_split = path.split("/")
# replace mesh and texture file paths tree = ET.fromstring(xml_str) root = tree asset = root.find("asset") meshes = asset.findall("mesh") textures = asset.findall("texture") all_elements = meshes + textures
for elem in all_elements: old_path = elem.get("file") if old_path is None: continue
old_path_split = old_path.split("/") # maybe replace all paths to robosuite assets check_lst = [loc for loc, val in enumerate(old_path_split) if val == "robosuite"] if len(check_lst) > 0: ind = max(check_lst) # last occurrence index new_path_split = path_split + old_path_split[ind + 1 :] new_path = "/".join(new_path_split) elem.set("file", new_path)
# maybe replace all paths to robosuite model zoo assets check_lst = [ loc for loc, val in enumerate(old_path_split) if val == "robosuite-model-zoo-dev" ] if len(check_lst) > 0: ind = max(check_lst) # last occurrence index new_path_split = ( os.path.split(robosuite_model_zoo.__file__)[0].split("/")[:-1] + old_path_split[ind + 1 :] ) new_path = "/".join(new_path_split) elem.set("file", new_path)
return ET.tostring(root, encoding="utf8").decode("utf8")
class MJCFObject(MujocoXMLObject): """ Blender object with support for changing the scaling """
def __init__( self, name, mjcf_path, scale=1.0, solimp=(0.998, 0.998, 0.001), solref=(0.001, 1), density=100, friction=(0.95, 0.3, 0.1), margin=None, rgba=None, priority=None, ): # get scale in x, y, z if isinstance(scale, float): scale = [scale, scale, scale] elif isinstance(scale, tuple) or isinstance(scale, list): assert len(scale) == 3 scale = tuple(scale) else: raise Exception("got invalid scale: {}".format(scale)) scale = np.array(scale)
self.solimp = solimp self.solref = solref self.density = density self.friction = friction self.margin = margin
self.priority = priority
self.rgba = rgba
# read default xml xml_path = mjcf_path folder = os.path.dirname(xml_path) tree = ET.parse(xml_path) root = tree.getroot()
# modify mesh scales asset = root.find("asset") meshes = asset.findall("mesh") for mesh in meshes: # if a scale already exists, multiply the scales scale_to_set = scale existing_scale = mesh.get("scale") if existing_scale is not None: scale_to_set = string_to_array(existing_scale) * scale mesh.set("scale", array_to_string(scale_to_set))
# modify sites for collision (assumes we can just scale up the locations - may or may not work) for n in ["bottom_site", "top_site", "horizontal_radius_site"]: site = root.find("worldbody/body/site[@name='{}']".format(n)) pos = string_to_array(site.get("pos")) pos = scale * pos site.set("pos", array_to_string(pos))
""" # disable collision geoms worldbody = root.find("worldbody") from robosuite.utils.mjcf_utils import find_elements geoms = find_elements( root=worldbody, tags="geom", attribs={"group": "0"}, return_first=False ) for g in geoms: # g.set("group", "1") g.set("mass", "0.0001") g.set("conaffinity", "2") g.set("contype", "2") """
# write modified xml (and make sure to postprocess any paths just in case) xml_str = ET.tostring(root, encoding="utf8").decode("utf8") xml_str = postprocess_model_xml(xml_str) time_str = str(time.time()).replace(".", "_") new_xml_path = os.path.join(folder, "{}_{}.xml".format(time_str, os.getpid())) f = open(new_xml_path, "w") f.write(xml_str) f.close() # print(f"Write to {new_xml_path}")
# initialize object with new xml we wrote super().__init__( # xml_path_completion("objects/{}.xml".format(obj_name)), fname=new_xml_path, name=name, joints=[dict(type="free", damping="0.0005")], # joints=None, obj_type="all", duplicate_collision_geoms=False, )
# clean up xml - we don't need it anymore if os.path.exists(new_xml_path): os.remove(new_xml_path)
def _get_geoms(self, root, _parent=None): """ Helper function to recursively search through element tree starting at @root and returns a list of (parent, child) tuples where the child is a geom element
Args: root (ET.Element): Root of xml element tree to start recursively searching through _parent (ET.Element): Parent of the root element tree. Should not be used externally; only set during the recursive call
Returns: list: array of (parent, child) tuples where the child element is a geom type """ geom_pairs = super(MJCFObject, self)._get_geoms(root=root, _parent=_parent)
# modify geoms according to the attributes for i, (parent, element) in enumerate(geom_pairs): element.set("solref", array_to_string(self.solref)) element.set("solimp", array_to_string(self.solimp)) element.set("density", str(self.density)) element.set("friction", array_to_string(self.friction)) if self.margin is not None: element.set("margin", str(self.margin))
if (self.rgba is not None) and (element.get("group") == "1"): element.set("rgba", array_to_string(self.rgba))
if self.priority is not None: # set high priorit element.set("priority", str(self.priority))
return geom_pairs
@property def horizontal_radius(self): horizontal_radius_site = self.worldbody.find( "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) ) site_values = string_to_array(horizontal_radius_site.get("pos")) return np.linalg.norm(site_values[0:2])
def get_bbox_points(self, trans=None, rot=None): """ Get the full 8 bounding box points of the object rot: a rotation matrix """ bbox_offsets = []
bottom_offset = self.bottom_offset top_offset = self.top_offset horizontal_radius_site = self.worldbody.find( "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) ) horiz_radius = string_to_array(horizontal_radius_site.get("pos"))[:2]
center = np.mean([bottom_offset, top_offset], axis=0) half_size = [horiz_radius[0], horiz_radius[1], top_offset[2] - center[2]]
# center = np.array([0, 0, 0]) # half_size = np.array([0.01, 0.01, 0.01])
bbox_offsets = [ center + half_size * np.array([-1, -1, -1]), # p0 center + half_size * np.array([1, -1, -1]), # px center + half_size * np.array([-1, 1, -1]), # py center + half_size * np.array([-1, -1, 1]), # pz center + half_size * np.array([1, 1, 1]), center + half_size * np.array([-1, 1, 1]), center + half_size * np.array([1, -1, 1]), center + half_size * np.array([1, 1, -1]), ]
if trans is None: trans = np.array([0, 0, 0]) if rot is not None: rot = T.quat2mat(rot) else: rot = np.eye(3)
points = [(np.matmul(rot, p) + trans) for p in bbox_offsets] return points123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""Much of this code is directly copied from obj2mjcf:https://github.com/kevinzakka/obj2mjcf/blob/main/obj2mjcf/_cli.py
Credit: Kevin Zakka"""
from dataclasses import dataclassfrom typing import Optional, Sequencefrom PIL import Imagefrom pathlib import Path
import osimport shutil
# MTL fields relevant to MuJoCo._MTL_FIELDS = ( # Ambient, diffuse and specular colors. "Ka", "Kd", "Ks", # d or Tr are used for the rgba transparency. "d", "Tr", # Shininess. "Ns", # References a texture file. "map_Kd",)
# Character used to denote a comment in an MTL file._MTL_COMMENT_CHAR = "#"
@dataclassclass Material: name: str Ka: Optional[str] = None Kd: Optional[str] = None Ks: Optional[str] = None d: Optional[str] = None Tr: Optional[str] = None Ns: Optional[str] = None map_Kd: Optional[str] = None
@staticmethod def from_string(lines: Sequence[str]) -> "Material": """Construct a Material object from a string.""" attrs = {"name": lines[0].split(" ")[1].strip()} for line in lines[1:]: for attr in _MTL_FIELDS: if line.startswith(attr): elems = line.split(" ")[1:] elems = [elem for elem in elems if elem != ""] attrs[attr] = " ".join(elems) break return Material(**attrs)
def mjcf_rgba(self) -> str: Kd = self.Kd or "1.0 1.0 1.0" if self.d is not None: # alpha alpha = self.d elif self.Tr is not None: # 1 - alpha alpha = str(1.0 - float(self.Tr)) else: alpha = "1.0" # alpha = "1.0" # TODO(kevin): Figure out how to use Ka for computing rgba. return f"{Kd} {alpha}"
def mjcf_shininess(self) -> str: if self.Ns is not None: # Normalize Ns value to [0, 1]. Ns values normally range from 0 to 1000. Ns = float(self.Ns) / 1_000 else: Ns = 0.5 return f"{Ns}"
def mjcf_specular(self) -> str: if self.Ks is not None: # Take the average of the specular RGB values. Ks = sum(list(map(float, self.Ks.split(" ")))) / 3 else: Ks = 0.5 return f"{Ks}"
def get_mtls(filename, work_dir): filename = Path(filename) work_dir = Path(work_dir)
process_mtl = False with open(filename, "r") as f: for line in f.readlines(): if line.startswith("mtllib"): # Deals with commented out lines. process_mtl = True name = line.split()[1] break
sub_mtls: List[List[str]] = [] mtls: List[Material] = [] if process_mtl: # Make sure the MTL file exists. The MTL filepath is relative to the OBJ's. mtl_filename = filename.parent / name if not mtl_filename.exists(): raise RuntimeError( f"The MTL file {mtl_filename.resolve()} referenced in the OBJ file " f"{filename} does not exist" ) # logging.info(f"Found MTL file: {mtl_filename}")
# Parse the MTL file into separate materials. with open(mtl_filename, "r") as f: lines = f.readlines() # Remove comments. lines = [line for line in lines if not line.startswith(_MTL_COMMENT_CHAR)] # Remove empty lines. lines = [line for line in lines if line.strip()] # Remove trailing whitespace. lines = [line.strip() for line in lines] # Split at each new material definition. for line in lines: if line.startswith("newmtl"): sub_mtls.append([]) sub_mtls[-1].append(line) for sub_mtl in sub_mtls: mtls.append(Material.from_string(sub_mtl))
# Process each material. for mtl in mtls: # logging.info(f"Found material: {mtl.name}") if mtl.map_Kd is not None: texture_path = Path(mtl.map_Kd) texture_name = texture_path.name src_filename = filename.parent / texture_path if not src_filename.exists(): raise RuntimeError( f"The texture file {src_filename} referenced in the MTL file " f"{mtl.name} does not exist" ) # We want a flat directory structure in work_dir. dst_filename = work_dir / texture_name shutil.copy(src_filename, dst_filename) # MuJoCo only supports PNG textures ¯\_(ツ)_/¯. if texture_path.suffix.lower() in [".jpg", ".jpeg"]: image = Image.open(dst_filename) os.remove(dst_filename) dst_filename = (work_dir / texture_path.stem).with_suffix(".png") image.save(dst_filename) texture_name = dst_filename.name mtl.map_Kd = texture_name resize_texture(dst_filename, 1.0) # logging.info("Done processing MTL file")
return mtls
def resize_texture(filename: Path, resize_percent) -> None: """Resize a texture to a percentage of its original size.""" if resize_percent == 1.0: return image = Image.open(filename) new_width = int(image.size[0] * resize_percent) new_height = int(image.size[1] * resize_percent) logging.info(f"Resizing {filename} to {new_width}x{new_height}") image = image.resize((new_width, new_height), Image.LANCZOS) image.save(filename)
def get_image_paths(mtl_path): image_paths = []
# Parse the MTL file into separate materials. with open(mtl_path, "r") as f: lines = f.readlines() # Remove comments. lines = [line for line in lines if not line.startswith(_MTL_COMMENT_CHAR)] # Remove empty lines. lines = [line for line in lines if line.strip()] # Remove trailing whitespace. lines = [line.strip() for line in lines] # Split at each new material definition.
sub_mtls = []
for line in lines: if line.startswith("newmtl"): sub_mtls.append([]) sub_mtls[-1].append(line) for sub_mtl in sub_mtls: # print(sub_mtl)
path = Material.from_string(sub_mtl).map_Kd
if path is not None: image_paths.append(path)
return image_paths123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250import numpy as np
from robosuite.environments.manipulation.single_arm_env import SingleArmEnvfrom robosuite.models.arenas import TableArenafrom robosuite.models.tasks import ManipulationTaskfrom robosuite.utils.placement_samplers import UniformRandomSampler
from robocasa.utils.model_zoo.mjcf_obj import MJCFObjectfrom robosuite.models.objects import BoxObject
import robosuite.utils.transform_utils as T
class ObjectPlayEnv(SingleArmEnv): def __init__( self, robots, obj_mjcf_path, obj_scale=1.0, env_configuration="default", controller_configs=None, gripper_types="default", initialization_noise="default", table_full_size=(0.8, 0.8, 0.05), table_friction=(1.0, 5e-3, 1e-4), use_camera_obs=True, use_object_obs=True, reward_scale=1.0, reward_shaping=False, placement_initializer=None, has_renderer=False, has_offscreen_renderer=True, render_camera="frontview", render_collision_mesh=False, render_visual_mesh=True, render_gpu_device_id=-1, control_freq=20, horizon=1000, ignore_done=False, hard_reset=True, camera_names="agentview", camera_heights=256, camera_widths=256, camera_depths=False, x_range=(-0.03, 0.03), y_range=(-0.03, 0.03), rotation=None, num_objects=1, ): # settings for table top self.table_full_size = table_full_size self.table_friction = table_friction self.table_offset = np.array((0, 0, 0.8))
# reward configuration self.reward_scale = reward_scale self.reward_shaping = reward_shaping
# whether to use ground-truth object states self.use_object_obs = use_object_obs
# object placement initializer self.placement_initializer = placement_initializer
self._obj_mjcf_path = obj_mjcf_path self._obj_scale = obj_scale self._x_range = x_range self._y_range = y_range self._rotation = rotation self._num_objects = num_objects
self._cam_configs = dict( agentview=dict( pos=[0, -0.5, 1.35], quat=T.convert_quat( np.array([0.3826834, 0, 0, 0.9238795]), to="wxyz", ), ), )
super().__init__( robots=robots, env_configuration=env_configuration, controller_configs=controller_configs, mount_types="default", gripper_types=gripper_types, initialization_noise=initialization_noise, use_camera_obs=use_camera_obs, has_renderer=has_renderer, has_offscreen_renderer=has_offscreen_renderer, render_camera=render_camera, render_collision_mesh=render_collision_mesh, render_visual_mesh=render_visual_mesh, render_gpu_device_id=render_gpu_device_id, control_freq=control_freq, horizon=horizon, ignore_done=ignore_done, hard_reset=hard_reset, camera_names=camera_names, camera_heights=camera_heights, camera_widths=camera_widths, camera_depths=camera_depths, )
def reward(self, action=None): reward = 0.0
return reward
def _load_model(self): """ Loads an xml model, puts it in self.model """ super()._load_model()
# Adjust base pose accordingly # xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) # self.robots[0].robot_model.set_base_xpos(xpos) ### logic copied from kitchen.py to rotate robot around ### for robot, rotation, offset in zip(self.robots, (-np.pi / 2,), (0,)): xpos = robot.robot_model.base_xpos_offset["table"](self.table_full_size[0]) rot = np.array((0, 0, rotation)) xpos = T.euler2mat(rot) @ np.array(xpos) xpos += np.array((0, offset, 0)) robot.robot_model.set_base_xpos(xpos) robot.robot_model.set_base_ori(rot)
# load model for table top workspace self.mujoco_arena = TableArena( table_full_size=self.table_full_size, table_friction=self.table_friction, table_offset=self.table_offset, )
# Arena always gets set to zero origin self.mujoco_arena.set_origin([0, 0, 0])
self.set_cameras()
objects = [] for obj_num in range(self._num_objects): if self._obj_mjcf_path == "cube": # debugging case using primitive geom obj = BoxObject( name="cube_{}".format(obj_num), size_min=[0.020, 0.020, 0.020], # [0.015, 0.015, 0.015], size_max=[0.022, 0.022, 0.022], # [0.018, 0.018, 0.018]) rgba=[1, 0, 0, 1], ) else: obj = MJCFObject( name="MCJFObj_{}".format(obj_num), mjcf_path=self._obj_mjcf_path, scale=self._obj_scale, )
objects.append(obj)
# Create placement initializer if self.placement_initializer is not None: self.placement_initializer.reset() self.placement_initializer.add_objects(objects) else: self.placement_initializer = UniformRandomSampler( name="ObjectSampler", mujoco_objects=objects, x_range=self._x_range, y_range=self._y_range, rotation=self._rotation, ensure_object_boundary_in_range=False, ensure_valid_placement=True, reference_pos=self.table_offset, z_offset=0.01, # # for debugging # x_range=(0, 0), # y_range=(0, 0), # rotation=(0, 0), )
# task includes arena, robot, and objects of interest self.model = ManipulationTask( mujoco_arena=self.mujoco_arena, mujoco_robots=[robot.robot_model for robot in self.robots], mujoco_objects=objects, )
# def _setup_references(self): # """ # Sets up references to important components. A reference is typically an # index or a list of indices that point to the corresponding elements # in a flatten array, which is how MuJoCo stores physical simulation data. # """ # super()._setup_references()
# # Additional object references from this env # self.obj_body_id = self.sim.model.body_name2id(self.mjcf_obj.root_body)
def set_cameras(self): """ copied from environments/manipulation/kitchen.py """ for cam_name, cam_cfg in self._cam_configs.items(): if cam_cfg.get("parent_body", None) is not None: continue
self.mujoco_arena.set_camera( camera_name=cam_name, pos=cam_cfg["pos"], quat=cam_cfg["quat"] )
def _reset_internal(self): """ Resets simulation internal configurations. """ super()._reset_internal()
# Reset all object positions using initializer sampler if we're not directly loading from an xml if not self.deterministic_reset:
# Sample from the placement initializer for all objects object_placements = self.placement_initializer.sample()
# Loop through all objects and reset their positions for obj_pos, obj_quat, obj in object_placements.values(): # self.sim.model.body_pos[self.sim.model.body_name2id(obj.root_body)] = obj_pos # self.sim.model.body_quat[self.sim.model.body_name2id(obj.root_body)] = obj_quat
self.sim.data.set_joint_qpos( obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)]), )
# def visualize(self, vis_settings): # """ # In addition to super call, visualize gripper site proportional to the distance to the cube. # # Args: # vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific # component should be visualized. Should have "grippers" keyword as well as any other relevant # options specified. # """ # # Run superclass method first # super().visualize(vis_settings=vis_settings) # # # Color the gripper visualization site according to its distance to the cube # if vis_settings["grippers"]: # self._visualize_gripper_to_target(gripper=self.robots[0].gripper, target=self.cube)
def _check_success(self): return False123456789101112131415<mujoco model="template"> <asset> <texture file="template.png" name="tex-template" type="2d"/> <material name="template" reflectance="0.5" texrepeat="1 1" texture="tex-template" texuniform="false"/> </asset> <worldbody> <body> <body name="object"> </body> <site rgba="0 0 0 0" size="0.005" pos="0 0 -0.06" name="bottom_site"/> <site rgba="0 0 0 0" size="0.005" pos="0 0 0.04" name="top_site"/> <site rgba="0 0 0 0" size="0.005" pos="0.025 0.025 0" name="horizontal_radius_site"/> </body> </worldbody></mujoco>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import argparse
def get_base_parser(): parser = argparse.ArgumentParser() parser.add_argument( "--base_asset_path", type=str, help="(optional) base asset path where model files are stored. " "Defaults to robosuite_model_zoo/assets_private folder.", ) parser.add_argument( "--model_folder", type=str, help="(optional) folder to store model (relative to base asset path). " "Defaults to None.", ) parser.add_argument( "--model_name", type=str, help="(optional) name of saved mjcf model. " "Defaults to name from --model_path.", ) parser.add_argument( "--scale", type=float, default=1.0, help="1d scaling of input model", ) parser.add_argument( "--show_sites", action="store_true", help="show model bounds sites", ) parser.add_argument( "--verbose", action="store_true", help="print detailed information for debugging", )
### V-HACD settings ### parser.add_argument( "--vhacd_max_output_convex_hulls", type=float, default=32, ) parser.add_argument( "--vhacd_voxel_resolution", type=float, default=100000, ) parser.add_argument( "--vhacd_volume_error_percent", type=float, default=1.0, ) parser.add_argument( "--vhacd_max_hull_vert_count", type=float, default=64, )
return parser123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621import numpy as npimport mujoco as mjimport robosuite.utils.transform_utils as Tfrom robosuite.utils.mjcf_utils import array_to_string
from robocasa.models.objects.objects import MJCFObject
def obj_inside_of(env, obj_name, fixture_id, partial_check=False): """ whether an object (another mujoco object) is inside of fixture. applies for most fixtures """ from robocasa.models.fixtures import Fixture
obj = env.objects[obj_name] fixture = env.get_fixture(fixture_id) assert isinstance(obj, MJCFObject) assert isinstance(fixture, Fixture)
# step 1: calculate fxiture points fixtr_p0, fixtr_px, fixtr_py, fixtr_pz = fixture.get_int_sites(relative=False) u = fixtr_px - fixtr_p0 v = fixtr_py - fixtr_p0 w = fixtr_pz - fixtr_p0
# get the position and quaternion of object obj_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[obj.name]]) obj_quat = T.convert_quat(env.sim.data.body_xquat[env.obj_body_id[obj.name]], to="xyzw")
if partial_check: obj_points_to_check = [obj_pos] th = 0.0 else: # calculate 8 boundary points of object obj_points_to_check = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) # threshold to mitigate false negatives: even if the bounding box point is out of bounds, th = 0.05
inside_of = True for obj_p in obj_points_to_check: check1 = np.dot(u, fixtr_p0) - th <= np.dot(u, obj_p) <= np.dot(u, fixtr_px) + th check2 = np.dot(v, fixtr_p0) - th <= np.dot(v, obj_p) <= np.dot(v, fixtr_py) + th check3 = np.dot(w, fixtr_p0) - th <= np.dot(w, obj_p) <= np.dot(w, fixtr_pz) + th
if not (check1 and check2 and check3): inside_of = False break
return inside_of
# used for cabinets, cabinet panels, counters, etc.def set_geom_dimensions(sizes, positions, geoms, rotated=False): """ set the dimensions of geoms in a fixture
Args: sizes (dict): dictionary of sizes for each side
positions (dict): dictionary of positions for each side
geoms (dict): dictionary of geoms for each side
rotated (bool): whether the fixture is rotated. Fixture may be rotated to make texture appear uniform due to mujoco texture conventions """ if rotated: # rotation trick to make texture appear uniform # see .xml file for side in sizes.keys(): # not the best detection method, TODO: check euler if "door" in side or "trim" in side: sizes[side] = [sizes[side][i] for i in [0, 2, 1]]
# set sizes and positions of all geoms for side in positions.keys(): for geom in geoms[side]: if geom is None: raise ValueError("Did not find geom:", side) geom.set("pos", array_to_string(positions[side])) geom.set("size", array_to_string(sizes[side]))
def get_rel_transform(fixture_A, fixture_B): """ Gets fixture_B's position and rotation relative to fixture_A's frame """ A_trans = np.array(fixture_A.pos) B_trans = np.array(fixture_B.pos)
A_rot = np.array([0, 0, fixture_A.rot]) B_rot = np.array([0, 0, fixture_B.rot])
A_mat = T.euler2mat(A_rot) B_mat = T.euler2mat(B_rot)
T_WA = np.vstack((np.hstack((A_mat, A_trans[:, None])), [0, 0, 0, 1])) T_WB = np.vstack((np.hstack((B_mat, B_trans[:, None])), [0, 0, 0, 1]))
T_AB = np.matmul(np.linalg.inv(T_WA), T_WB)
return T_AB[:3, 3], T_AB[:3, :3]
def compute_rel_transform(A_pos, A_mat, B_pos, B_mat): """ Gets B's position and rotation relative to A's frame """ T_WA = np.vstack((np.hstack((A_mat, A_pos[:, None])), [0, 0, 0, 1])) T_WB = np.vstack((np.hstack((B_mat, B_pos[:, None])), [0, 0, 0, 1]))
T_AB = np.matmul(np.linalg.inv(T_WA), T_WB)
return T_AB[:3, 3], T_AB[:3, :3]
def get_fixture_to_point_rel_offset(fixture, point): """ get offset relative to fixture's frame, given a global point """ global_offset = point - fixture.pos T_WF = T.euler2mat([0, 0, fixture.rot]) rel_offset = np.matmul(np.linalg.inv(T_WF), global_offset) return rel_offset
def get_pos_after_rel_offset(fixture, offset): """ get global position of a fixture, after applying offset relative to center of fixture """ fixture_rot = np.array([0, 0, fixture.rot]) fixture_mat = T.euler2mat(fixture_rot)
return fixture.pos + np.dot(fixture_mat, offset)
def project_point_to_line(P, A, B): """ logic copied from here: https://stackoverflow.com/a/61342198 """ AP = P - A AB = B - A result = A + np.dot(AP, AB) / np.dot(AB, AB) * AB
return result
def point_in_fixture(point, fixture, only_2d=False): """ check if point is inside of the exterior bounding boxes of the fixture
Args: point (np.array): point to check
fixture (Fixture): fixture object
only_2d (bool): whether to check only in 2D """ p0, px, py, pz = fixture.get_ext_sites(relative=False) th = 0.00 u = px - p0 v = py - p0 w = pz - p0 check1 = np.dot(u, p0) - th <= np.dot(u, point) <= np.dot(u, px) + th check2 = np.dot(v, p0) - th <= np.dot(v, point) <= np.dot(v, py) + th check3 = np.dot(w, p0) - th <= np.dot(w, point) <= np.dot(w, pz) + th
if only_2d: return check1 and check2 else: return check1 and check2 and check3
def obj_in_region( obj, obj_pos, obj_quat, p0, px, py, pz=None,): """ check if object is in the region defined by the points. Uses either the objects bounding box or the object's horizontal radius """ from robocasa.models.fixtures import Fixture
if isinstance(obj, MJCFObject) or isinstance(obj, Fixture): obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) else: radius = obj.horizontal_radius obj_points = obj_pos + np.array( [ [radius, 0, 0], [-radius, 0, 0], [0, radius, 0], [0, -radius, 0], ] )
u = px - p0 v = py - p0 w = pz - p0 if pz is not None else None
for point in obj_points: check1 = np.dot(u, p0) <= np.dot(u, point) <= np.dot(u, px) check2 = np.dot(v, p0) <= np.dot(v, point) <= np.dot(v, py)
if not check1 or not check2: return False
if w is not None: check3 = np.dot(w, p0) <= np.dot(w, point) <= np.dot(w, pz) if not check3: return False
return True
def obj_in_region_with_keypoints( obj, obj_pos, obj_quat, region_points, min_num_points=3, region_type="box"): """ check if object is in the region defined by the keypoints. Only min_num_points points need to be in the region to return True. Keypoints include the points of the object's bounding box and the center of the object. region can be a box or a cylinder or a sphere TODO: support plane region """ from robocasa.models.fixtures import Fixture
if isinstance(obj, MJCFObject) or isinstance(obj, Fixture): obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) else: radius = obj.horizontal_radius obj_points = obj_pos + np.array( [ [radius, 0, 0], [-radius, 0, 0], [0, radius, 0], [0, -radius, 0], ] )
# center points of object for each plane obj_u = obj_points[1] - obj_points[0] obj_v = obj_points[2] - obj_points[0] obj_w = obj_points[3] - obj_points[0] centers = []
# Front and back XY planes center_xy_front = obj_points[0] + 0.5 * obj_u + 0.5 * obj_v center_xy_back = center_xy_front + obj_w centers.extend([center_xy_front, center_xy_back])
if obj_w is not None: # Left and right XZ planes center_xz_left = obj_points[0] + 0.5 * obj_u + 0.5 * obj_w center_xz_right = center_xz_left + obj_v centers.extend([center_xz_left, center_xz_right])
# Top and bottom YZ planes center_yz_top = obj_points[0] + 0.5 * obj_v + 0.5 * obj_w center_yz_bottom = center_yz_top + obj_u centers.extend([center_yz_top, center_yz_bottom])
center_point = np.mean(obj_points, axis=0) centers.append(center_point) obj_points = np.concatenate([obj_points, centers])
# Erode the bounding box by pulling points 10% closer to the center # Avoids false negatives when object is near the edge of the region obj_points = obj_points * 0.8 + center_point * 0.2
if region_type == "box": if len(region_points) == 4: p0, px, py, pz = region_points elif len(region_points) == 3: p0, px, py = region_points pz = None else: raise ValueError(f"Invalid number of region points: {len(region_points)}") return obj_in_box_region(obj_points, p0, px, py, pz, min_num_points) elif region_type == "cylinder": p0, axis_vector, radius = region_points return obj_in_cylinder_region(obj_points, p0, axis_vector, radius, min_num_points) elif region_type == "sphere": p0, radius = region_points return obj_in_sphere_region(obj_points, p0, radius, min_num_points)
def fixture_pairwise_dist(f1, f2): """ Gets the distance between two fixtures by finding the minimum distance between their exterior bounding box points """ f1_points = f1.get_ext_sites(all_points=True, relative=False) f2_points = f2.get_ext_sites(all_points=True, relative=False)
all_dists = [np.linalg.norm(p1 - p2) for p1 in f1_points for p2 in f2_points] return np.min(all_dists)
def objs_intersect( obj, obj_pos, obj_quat, other_obj, other_obj_pos, other_obj_quat,): """ check if two objects intersect """ from robocasa.models.fixtures import Fixture
bbox_check = (isinstance(obj, MJCFObject) or isinstance(obj, Fixture)) and ( isinstance(other_obj, MJCFObject) or isinstance(other_obj, Fixture) ) if bbox_check: obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) other_obj_points = other_obj.get_bbox_points(trans=other_obj_pos, rot=other_obj_quat)
face_normals = [ obj_points[1] - obj_points[0], obj_points[2] - obj_points[0], obj_points[3] - obj_points[0], other_obj_points[1] - other_obj_points[0], other_obj_points[2] - other_obj_points[0], other_obj_points[3] - other_obj_points[0], ]
intersect = True
# noramlize length of normals for normal in face_normals: normal = np.array(normal) / np.linalg.norm(normal)
obj_projs = [np.dot(p, normal) for p in obj_points] other_obj_projs = [np.dot(p, normal) for p in other_obj_points]
# see if gap detected if np.min(other_obj_projs) > np.max(obj_projs) or np.min(obj_projs) > np.max( other_obj_projs ): intersect = False break else: """ old code from placement_samplers.py """ obj_x, obj_y, obj_z = obj_pos other_obj_x, other_obj_y, other_obj_z = other_obj_pos xy_collision = ( np.linalg.norm((obj_x - other_obj_x, obj_y - other_obj_y)) <= other_obj.horizontal_radius + obj.horizontal_radius ) if obj_z > other_obj_z: z_collision = obj_z - other_obj_z <= other_obj.top_offset[-1] - obj.bottom_offset[-1] else: z_collision = other_obj_z - obj_z <= obj.top_offset[-1] - other_obj.bottom_offset[-1]
if xy_collision and z_collision: intersect = True else: intersect = False
return intersect
def normalize_joint_value(raw, joint_min, joint_max): """ normalize raw value to be between 0 and 1 """ return (raw - joint_min) / (joint_max - joint_min)
def get_highest_spawn_region(env, receptacle): """ Get the highest spawn region of a receptacle. """ return max( receptacle.spawns, key=lambda x: env.sim.data.geom_xpos[env.sim.model.geom_name2id(x.get("name"))][2], )
def calculate_spawn_region(env, spawn): """ Calculates the corner points of the spawn region.
Parameters: env: The simulation/environment object. spawn: The spawn geom.
Returns: For box: (p0, px, py, pz) For cylinder: (p0, axis_vector, radius) For sphere: (center, radius) """ # Get spawn parameters from the simulation. spawn_name = spawn.get("name") spawn_id = env.sim.model.geom_name2id(spawn_name)
spawn_pos = env.sim.data.get_geom_xpos(spawn_name) spawn_xmat = env.sim.data.get_geom_xmat(spawn_name) spawn_size = env.sim.model.geom_size[spawn_id] spawn_type = env.sim.model.geom_type[spawn_id] assert spawn_type in [ mj.mjtGeom.mjGEOM_BOX, mj.mjtGeom.mjGEOM_CYLINDER, mj.mjtGeom.mjGEOM_SPHERE, ], "Spawn region only supports box, cylinder and sphere geometries."
if spawn_type == mj.mjtGeom.mjGEOM_BOX: # Box geometry - return corners as before p0 = ( spawn_pos - spawn_size[0] * spawn_xmat[:, 0] - spawn_size[1] * spawn_xmat[:, 1] - spawn_size[2] * spawn_xmat[:, 2] ) px = p0 + 2 * spawn_size[0] * spawn_xmat[:, 0] py = p0 + 2 * spawn_size[1] * spawn_xmat[:, 1] pz = p0 + 2 * spawn_size[2] * spawn_xmat[:, 2] return p0, px, py, pz elif spawn_type == mj.mjtGeom.mjGEOM_CYLINDER: # Cylinder geometry - return (base_center, axis_vector, radius) height = spawn_size[1] * 2 radius = spawn_size[0] axis_vector = height * spawn_xmat[:, 2] return spawn_pos, axis_vector, radius elif spawn_type == mj.mjtGeom.mjGEOM_SPHERE: # Sphere geometry - return (center, radius) radius = spawn_size[0] return spawn_pos, radius else: raise ValueError(f"Invalid spawn type: {spawn_type}")
def check_obj_in_receptacle( env, obj_name, receptacle_name, th=None, spawn_check=True, spawn_regions=None): """ check if object is in receptacle object based on spawn regions or threshold """ obj = env.objects[obj_name] recep = env.objects[receptacle_name] obj_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[obj_name]]) obj_quat = T.convert_quat( np.array(env.sim.data.body_xquat[env.obj_body_id[obj_name]]), to="xyzw" ) recep_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[receptacle_name]])
if len(recep.spawns) > 0 and spawn_check: if spawn_regions is None: spawn_regions = recep.spawns
for spawn in spawn_regions: region_points = calculate_spawn_region(env, spawn)
if obj_in_region_with_keypoints( obj, obj_pos, obj_quat, region_points, min_num_points=2, region_type=spawn.get("type"), ): return True return False else: if th is None: th = recep.horizontal_radius * 0.7 obj_in_recep = ( env.check_contact(obj, recep) and np.linalg.norm(obj_pos[:2] - recep_pos[:2]) < th ) return obj_in_recep
def check_obj_fixture_contact(env, obj_name, fixture_name): """ check if object is in contact with fixture """ obj = env.objects[obj_name] fixture = env.get_fixture(fixture_name) return env.check_contact(obj, fixture)
def gripper_obj_far(env, obj_name="obj", th=0.25): """ check if gripper is far from object based on distance defined by threshold """ return gripper_obj_far_by_side(env=env, obj_name=obj_name, gripper_side="right", th=th)[1]
def any_gripper_obj_far(env, obj_name="obj", th=0.25): """ check if all grippers are far from object based on distance defined by threshold """ left_is_far = gripper_obj_far_by_side(env=env, obj_name=obj_name, gripper_side="left", th=th)[1] right_is_far = gripper_obj_far_by_side(env=env, obj_name=obj_name, gripper_side="right", th=th)[ 1 ] return left_is_far and right_is_far
def gripper_obj_far_by_side(env, obj_name: str, gripper_side: str, th: float = 0.25): """ check if gripper is far from object based on distance defined by threshold """ obj_pos = env.sim.data.body_xpos[env.obj_body_id[obj_name]] gripper_site_pos = env.sim.data.site_xpos[env.robots[0].eef_site_id[gripper_side]] dist = np.linalg.norm(gripper_site_pos - obj_pos) return dist, dist > th
def obj_cos(env, obj_name="obj", ref=(0, 0, 1)): def cos(u, v): return np.dot(u, v) / max(np.linalg.norm(u) * np.linalg.norm(v), 1e-10)
obj_id = env.obj_body_id[obj_name] obj_quat = T.convert_quat(np.array(env.sim.data.body_xquat[obj_id]), to="xyzw") obj_mat = T.quat2mat(obj_quat)
return cos(obj_mat[:, 2], np.array(ref))
def check_obj_upright(env, obj_name, threshold=0.8, symmetric: bool = False): """ Check if an object is upright based on its z-axis orientation """ obj_id = env.obj_body_id[obj_name] obj_quat = T.convert_quat(np.array(env.sim.data.body_xquat[obj_id]), to="xyzw") obj_mat = T.quat2mat(obj_quat) z_alignment = obj_mat[:, 2][2] z_alignment = abs(z_alignment) if symmetric else z_alignment return z_alignment > threshold
def obj_in_box_region(obj_points, p0, px, py, pz, min_num_points): """ Check if enough object points are inside a box region defined by corner points.
Args: obj_points (np.array): Points to check p0 (np.array): Origin corner point px (np.array): X-axis corner point py (np.array): Y-axis corner point pz (np.array): Z-axis corner point (optional) min_num_points (int): Minimum number of points that need to be in region
Returns: bool: True if enough points are inside the region """ u = px - p0 v = py - p0 w = pz - p0 if pz is not None else None
num_points_in_region = 0 for point in obj_points: check1 = np.dot(u, p0) <= np.dot(u, point) <= np.dot(u, px) check2 = np.dot(v, p0) <= np.dot(v, point) <= np.dot(v, py)
if w is not None: check3 = np.dot(w, p0) <= np.dot(w, point) <= np.dot(w, pz) if check1 and check2 and check3: num_points_in_region += 1 else: if check1 and check2: num_points_in_region += 1
return num_points_in_region >= min_num_points
def obj_in_cylinder_region(obj_points, p0, axis_vector, radius, min_num_points): """ Check if enough object points are inside a cylinder region defined by base point, height vector and radius
Args: obj_points (np.array): Points to check p0 (np.array): Base center point of cylinder axis_vector (np.array): Vector from base center to top center, defines cylinder axis and height radius (float): Radius of cylinder min_num_points (int): Minimum number of points that need to be in region """ num_points_in_region = 0 # Normalize height vector to get axis direction axis = axis_vector / np.linalg.norm(axis_vector) height_magnitude = np.linalg.norm(axis_vector)
for point in obj_points: # Project point onto cylinder axis point_rel = point - p0 height_proj = np.dot(point_rel, axis)
# Check height bounds if 0 <= height_proj <= height_magnitude: # Check radius by removing height component radius_vec = point_rel - height_proj * axis if np.linalg.norm(radius_vec) <= radius: num_points_in_region += 1
return num_points_in_region >= min_num_points
def obj_in_sphere_region(obj_points, p0, radius, min_num_points): """ Check if enough object points are inside a sphere region defined by center and radius
Args: obj_points (np.array): Points to check p0 (np.array): Center point of sphere radius (float): Radius of sphere min_num_points (int): Minimum number of points that need to be in region """ num_points_in_region = 0 for point in obj_points: if np.linalg.norm(point - p0) <= radius: num_points_in_region += 1
return num_points_in_region >= min_num_points123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711import collectionsfrom copy import copy
import numpy as np
from robocasa.models.objects.objects import MJCFObjectfrom robosuite.models.objects import MujocoObjectfrom robosuite.utils import RandomizationErrorfrom robosuite.utils.transform_utils import ( convert_quat, euler2mat, mat2quat, quat_multiply, rotate_2d_point,)
from robocasa.utils.object_utils import ( obj_in_region, objs_intersect, obj_in_region_with_keypoints,)
class ObjectPositionSampler: """ Base class of object placement sampler.
Args: name (str): Name of this sampler.
mujoco_objects (None or MujocoObject or list of MujocoObject): single model or list of MJCF object models
ensure_object_boundary_in_range (bool): If True, will ensure that the object is enclosed within a given boundary (should be implemented by subclass)
ensure_valid_placement (bool): If True, will check for correct (valid) object placements
reference_pos (3-array): global (x,y,z) position relative to which sampling will occur
z_offset (float): Add a small z-offset to placements. This is useful for fixed objects that do not move (i.e. no free joint) to place them above the table. """
def __init__( self, name, mujoco_objects=None, ensure_object_boundary_in_range=True, ensure_valid_placement=True, reference_pos=(0, 0, 0), reference_rot=0, z_offset=0.0, rng=None, ): if rng is None: rng = np.random.default_rng() self.rng = rng
# Setup attributes self.name = name if mujoco_objects is None: self.mujoco_objects = [] else: # Shallow copy the list so we don't modify the inputted list but still keep the object references self.mujoco_objects = ( [mujoco_objects] if isinstance(mujoco_objects, MujocoObject) else copy(mujoco_objects) ) self.ensure_object_boundary_in_range = ensure_object_boundary_in_range self.ensure_valid_placement = ensure_valid_placement self.reference_pos = reference_pos self.reference_rot = reference_rot self.z_offset = z_offset
def add_objects(self, mujoco_objects): """ Add additional objects to this sampler. Checks to make sure there's no identical objects already stored.
Args: mujoco_objects (MujocoObject or list of MujocoObject): single model or list of MJCF object models """ mujoco_objects = ( [mujoco_objects] if isinstance(mujoco_objects, MujocoObject) else mujoco_objects ) for obj in mujoco_objects: assert obj not in self.mujoco_objects, "Object '{}' already in sampler!".format( obj.name ) self.mujoco_objects.append(obj)
def reset(self): """ Resets this sampler. Removes all mujoco objects from this sampler. """ self.mujoco_objects = []
def sample(self, fixtures=None, reference=None, on_top=True): """ Uniformly sample on a surface (not necessarily table surface).
Args: fixtures (dict): dictionary of current object placements in the scene as well as any other relevant obstacles that should not be in contact with newly sampled objects. Used to make sure newly generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject)
reference (str or 3-tuple or None): if provided, sample relative placement. Can either be a string, which corresponds to an existing object found in @fixtures, or a direct (x,y,z) value. If None, will sample relative to this sampler's `'reference_pos'` value.
on_top (bool): if True, sample placement on top of the reference object.
Return: dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the placements specified in @fixtures. Note quat is in (w,x,y,z) form """ raise NotImplementedError
@property def sides_combinations(self): return { "left": ["front_left", "back_left"], "right": ["front_right", "back_right"], "front": ["front_left", "front_right"], "back": ["back_left", "back_right"], "all": ["front_left", "front_right", "back_left", "back_right"], }
@property def valid_sides(self): return set( [ "left", "right", "front", "back", "all", "front_left", "front_right", "back_left", "back_right", ] )
class UniformRandomSampler(ObjectPositionSampler): """ Places all objects within the table uniformly random.
Args: name (str): Name of this sampler.
mujoco_objects (None or MujocoObject or list of MujocoObject): single model or list of MJCF object models
x_range (2-array of float): Specify the (min, max) relative x_range used to uniformly place objects
y_range (2-array of float): Specify the (min, max) relative y_range used to uniformly place objects
rotation (None or float or Iterable): :`None`: Add uniform random random rotation :`Iterable (a,b)`: Uniformly randomize rotation angle between a and b (in radians) :`value`: Add fixed angle rotation
rotation_axis (str): Can be 'x', 'y', or 'z'. Axis about which to apply the requested rotation
ensure_object_boundary_in_range (bool): :`True`: The center of object is at position: [uniform(min x_range + radius, max x_range - radius)], [uniform(min x_range + radius, max x_range - radius)] :`False`: [uniform(min x_range, max x_range)], [uniform(min x_range, max x_range)]
ensure_valid_placement (bool): If True, will check for correct (valid) object placements
reference_pos (3-array): global (x,y,z) position relative to which sampling will occur
z_offset (float): Add a small z-offset to placements. This is useful for fixed objects that do not move (i.e. no free joint) to place them above the table.
num_attempts (int): Number of attempts to sample an object before giving up. """
def __init__( self, name, mujoco_objects=None, x_range=(0, 0), y_range=(0, 0), rotation=None, rotation_axis="z", ensure_object_boundary_in_range=True, ensure_valid_placement=True, ensure_object_in_ref_region=False, ensure_object_out_of_ref_region=False, reference_pos=(0, 0, 0), reference_rot=0, z_offset=0.0, rng=None, side="all", num_attempts=5000, ): """Uniformly sample the position of the object.
Args: ensure_object_in_ref_region (bool, optional): If True, we need to ensure the object be placed within the reference region. Not need to be fully in the region, but at least the center of the object. ensure_object_out_of_ref_region (bool, optional): If True, we need to ensure the object be placed outside the reference region. Need to be fully outside the region. """ self.x_range = x_range self.y_range = y_range self.rotation = rotation self.rotation_axis = rotation_axis self.num_attempts = num_attempts if side not in self.valid_sides: raise ValueError("Invalid value for side, must be one of:", self.valid_sides)
super().__init__( name=name, mujoco_objects=mujoco_objects, ensure_object_boundary_in_range=ensure_object_boundary_in_range, ensure_valid_placement=ensure_valid_placement, reference_pos=reference_pos, reference_rot=reference_rot, z_offset=z_offset, rng=rng, ) self.ensure_object_in_ref_region = ensure_object_in_ref_region self.ensure_object_out_of_ref_region = ensure_object_out_of_ref_region
def _sample_x(self): """ Samples the x location for a given object
Returns: float: sampled x position """ minimum, maximum = self.x_range return self.rng.uniform(high=maximum, low=minimum)
def _sample_y(self): """ Samples the y location for a given object
Returns: float: sampled y position """ minimum, maximum = self.y_range return self.rng.uniform(high=maximum, low=minimum)
def _sample_quat(self): """ Samples the orientation for a given object
Returns: np.array: sampled object quaternion in (w,x,y,z) form
Raises: ValueError: [Invalid rotation axis] """ if self.rotation is None: rot_angle = self.rng.uniform(high=2 * np.pi, low=0) elif isinstance(self.rotation, collections.abc.Iterable): if isinstance(self.rotation[0], collections.abc.Iterable): rotation = self.rng.choice(self.rotation) else: rotation = self.rotation rot_angle = self.rng.uniform(high=max(rotation), low=min(rotation)) else: rot_angle = self.rotation
# Return angle based on axis requested if self.rotation_axis == "x": return np.array([np.cos(rot_angle / 2), np.sin(rot_angle / 2), 0, 0]) elif self.rotation_axis == "y": return np.array([np.cos(rot_angle / 2), 0, np.sin(rot_angle / 2), 0]) elif self.rotation_axis == "z": return np.array([np.cos(rot_angle / 2), 0, 0, np.sin(rot_angle / 2)]) else: # Invalid axis specified, raise error raise ValueError( "Invalid rotation axis specified. Must be 'x', 'y', or 'z'. Got: {}".format( self.rotation_axis ) )
def sample(self, placed_objects=None, reference=None, neg_reference=None, on_top=True): """ Uniformly sample relative to this sampler's reference_pos or @reference (if specified).
Args: placed_objects (dict): dictionary of current object placements in the scene as well as any other relevant obstacles that should not be in contact with newly sampled objects. Used to make sure newly generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject)
reference (str, tuple, or None, optional): Defines the reference for relative placement. It can be an object name found in `fixtures`, a tuple specifying an object and its site ID, or a direct (x, y, z) coordinate. If not provided, placement is sampled relative to this sampler's `reference_pos`.
on_top (bool): if True, sample placement on top of the reference object. This corresponds to a sampled z-offset of the current sampled object's bottom_offset + the reference object's top_offset (if specified)
Return: dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the placements specified in @fixtures. Note quat is in (w,x,y,z) form
Raises: RandomizationError: [Cannot place all objects] AssertionError: [Reference object name does not exist, invalid inputs] """ # Standardize inputs placed_objects = {} if placed_objects is None else copy(placed_objects) spawn_ref_obj = None
if reference is None: base_offset = self.reference_pos elif type(reference) is str: assert ( reference in placed_objects ), "Invalid reference received. Current options are: {}, requested: {}".format( placed_objects.keys(), reference ) ref_pos, _, ref_obj = placed_objects[reference] base_offset = np.array(ref_pos) if on_top: base_offset += np.array((0, 0, ref_obj.top_offset[-1])) # Handle shelf object references # If the reference is provided as a tuple (object_key: str, spawn_id: int), # then we treat it as a reference to a specific shelf level elif type(reference) is tuple and len(reference) == 2: (reference, spawn_id) = reference assert ( reference in placed_objects ), "Invalid reference received. Current options are: {}, requested: {}".format( placed_objects.keys(), reference ) ref_pos, _, ref_obj = placed_objects[reference] assert isinstance( ref_obj, MJCFObject ), "Invalid reference received. Should be of type MJCFObject" if spawn_id == -1: spawn_id, site = ref_obj.get_random_spawn(self.rng, exclude_disabled=True) else: site = ref_obj.spawns[spawn_id] ref_obj.set_spawn_active(spawn_id, False)
base_offset = np.array(ref_pos) base_offset += ref_obj.get_spawn_bottom_offset(site) spawn_ref_obj = ref_obj else: base_offset = np.array(reference) assert ( base_offset.shape[0] == 3 ), "Invalid reference received. Should be (x,y,z) 3-tuple, but got: {}".format( base_offset )
# Sample pos and quat for all objects assigned to this sampler for obj in self.mujoco_objects: # First make sure the currently sampled object hasn't already been sampled assert obj.name not in placed_objects, "Object '{}' has already been sampled!".format( obj.name )
success = False
# get reference rotation ref_quat = convert_quat(mat2quat(euler2mat([0, 0, self.reference_rot])), to="wxyz")
### get boundary points ### region_points = np.array( [ [self.x_range[0], self.y_range[0], 0], [self.x_range[1], self.y_range[0], 0], [self.x_range[0], self.y_range[1], 0], ] ) for i in range(len(region_points)): region_points[i][0:2] = rotate_2d_point( region_points[i][0:2], rot=self.reference_rot ) region_points += base_offset
for i in range(self.num_attempts): # sample object coordinates relative_x = self._sample_x() relative_y = self._sample_y()
# apply rotation object_x, object_y = rotate_2d_point( [relative_x, relative_y], rot=self.reference_rot )
object_x = object_x + base_offset[0] object_y = object_y + base_offset[1] object_z = self.z_offset + base_offset[2] if on_top: object_z -= obj.bottom_offset[-1]
# random rotation quat = self._sample_quat() # multiply this quat by the object's initial rotation if it has the attribute specified if hasattr(obj, "init_quat"): quat = quat_multiply(quat, obj.init_quat) quat = convert_quat( quat_multiply( convert_quat(ref_quat, to="xyzw"), convert_quat(quat, to="xyzw"), ), to="wxyz", )
location_valid = True
# ensure object placed fully in region if self.ensure_object_boundary_in_range and not obj_in_region( obj, obj_pos=[object_x, object_y, object_z], obj_quat=convert_quat(quat, to="xyzw"), p0=region_points[0], px=region_points[1], py=region_points[2], ): location_valid = False continue
# objects cannot overlap if self.ensure_valid_placement: for (x, y, z), other_quat, other_obj in placed_objects.values(): if spawn_ref_obj and other_obj == spawn_ref_obj: if not objs_intersect( obj=obj, obj_pos=[object_x, object_y, object_z], obj_quat=convert_quat(quat, to="xyzw"), other_obj=other_obj, other_obj_pos=[x, y, z], other_obj_quat=convert_quat(other_quat, to="xyzw"), ): location_valid = False break else: if objs_intersect( obj=obj, obj_pos=[object_x, object_y, object_z], obj_quat=convert_quat(quat, to="xyzw"), other_obj=other_obj, other_obj_pos=[x, y, z], other_obj_quat=convert_quat(other_quat, to="xyzw"), ): location_valid = False break
# ensure at least one point of the object should be in the region if self.ensure_object_in_ref_region and reference is not None: _ref_pos, _ref_quat, _ref_obj = placed_objects[reference] if not obj_in_region_with_keypoints( obj=obj, obj_pos=[object_x, object_y, object_z], obj_quat=convert_quat(quat, to="xyzw"), region_points=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[:3], min_num_points=3, ): location_valid = False break
if self.ensure_object_out_of_ref_region and neg_reference is not None: for nf in neg_reference: assert ( nf in placed_objects ), "Invalid negative reference received. Current options are: {}, requested: {}".format( placed_objects.keys(), nf ) _ref_pos, _ref_quat, _ref_obj = placed_objects[nf] if obj_in_region( obj=obj, obj_pos=[object_x, object_y, object_z], obj_quat=convert_quat(quat, to="xyzw"), p0=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[0], px=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[1], py=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[2], ): location_valid = False break
if location_valid: # location is valid, put the object down pos = (object_x, object_y, object_z) placed_objects[obj.name] = (pos, quat, obj) success = True break
if not success: raise RandomizationError(f"Cannot place object: {obj.name}")
return placed_objects
class SequentialCompositeSampler(ObjectPositionSampler): """ Samples position for each object sequentially. Allows chaining multiple placement initializers together - so that object locations can be sampled on top of other objects or relative to other object placements.
Args: name (str): Name of this sampler. """
def __init__(self, name, rng=None): # Samplers / args will be filled in later self.samplers = collections.OrderedDict() self.sample_args = collections.OrderedDict() self.sampler_optional = collections.OrderedDict()
super().__init__(name=name, rng=rng)
def append_sampler(self, sampler, sample_args=None, optional=False): """ Adds a new placement initializer with corresponding @sampler and arguments
Args: sampler (ObjectPositionSampler): sampler to add sample_args (None or dict): If specified, should be additional arguments to pass to @sampler's sample() call. Should map corresponding sampler's arguments to values (excluding @fixtures argument) optional (bool): If True, do not raise an error if the sampler fails to place all objects. This parameter is for handling optional clutter generation. When True, clutter objects that can't be placed due to space constraints are silently skipped.
Raises: AssertionError: [Object name in samplers] """ # Verify that all added mujoco objects haven't already been added, and add to this sampler's objects dict for obj in sampler.mujoco_objects: assert ( obj not in self.mujoco_objects ), f"Object '{obj.name}' already has sampler associated with it!" self.mujoco_objects.append(obj) self.samplers[sampler.name] = sampler self.sample_args[sampler.name] = sample_args self.sampler_optional[sampler.name] = optional
def hide(self, mujoco_objects): """ Helper method to remove an object from the workspace.
Args: mujoco_objects (MujocoObject or list of MujocoObject): Object(s) to hide """ sampler = UniformRandomSampler( name="HideSampler", mujoco_objects=mujoco_objects, x_range=[-10, -20], y_range=[-10, -20], rotation=[0, 0], rotation_axis="z", z_offset=10, ensure_object_boundary_in_range=False, ensure_valid_placement=False, rng=self.rng, ) self.append_sampler(sampler=sampler)
def add_objects(self, mujoco_objects): """ Override super method to make sure user doesn't call this (all objects should implicitly belong to sub-samplers) """ raise AttributeError("add_objects() should not be called for SequentialCompsiteSamplers!")
def add_objects_to_sampler(self, sampler_name, mujoco_objects): """ Adds specified @mujoco_objects to sub-sampler with specified @sampler_name.
Args: sampler_name (str): Existing sub-sampler name mujoco_objects (MujocoObject or list of MujocoObject): Object(s) to add """ # First verify that all mujoco objects haven't already been added, and add to this sampler's objects dict mujoco_objects = ( [mujoco_objects] if isinstance(mujoco_objects, MujocoObject) else mujoco_objects ) for obj in mujoco_objects: assert ( obj not in self.mujoco_objects ), f"Object '{obj.name}' already has sampler associated with it!" self.mujoco_objects.append(obj) # Make sure sampler_name exists assert ( sampler_name in self.samplers.keys() ), "Invalid sub-sampler specified, valid options are: {}, " "requested: {}".format( self.samplers.keys(), sampler_name ) # Add the mujoco objects to the requested sub-sampler self.samplers[sampler_name].add_objects(mujoco_objects)
def reset(self): """ Resets this sampler. In addition to base method, iterates over all sub-samplers and resets them """ super().reset() for sampler in self.samplers.values(): sampler.reset()
def sample(self, placed_objects=None, reference=None, on_top=True): """ Sample from each placement initializer sequentially, in the order that they were appended.
Args: placed_objects (dict): dictionary of current object placements in the scene as well as any other relevant obstacles that should not be in contact with newly sampled objects. Used to make sure newly generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject)
reference (str or 3-tuple or None): if provided, sample relative placement. This will override each sampler's @reference argument if not already specified. Can either be a string, which corresponds to an existing object found in @fixtures, or a direct (x,y,z) value. If None, will sample relative to this sampler's `'reference_pos'` value.
on_top (bool): if True, sample placement on top of the reference object. This will override each sampler's @on_top argument if not already specified. This corresponds to a sampled z-offset of the current sampled object's bottom_offset + the reference object's top_offset (if specified)
Return: dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the placements specified in @fixtures. Note quat is in (w,x,y,z) form
Raises: RandomizationError: [Cannot place all objects] """ # Standardize inputs placed_objects = {} if placed_objects is None else copy(placed_objects)
# Iterate through all samplers to sample for sampler, s_args in zip(self.samplers.values(), self.sample_args.values()): # Pre-process sampler args if s_args is None: s_args = {} for arg_name, arg in zip(("reference", "on_top"), (reference, on_top)): if arg_name not in s_args: s_args[arg_name] = arg # Run sampler try: new_placements = sampler.sample( placed_objects=placed_objects or s_args.pop("placed_objects", {}), **s_args, ) except RandomizationError: if self.sampler_optional[sampler.name]: continue else: raise # Update placements placed_objects.update(new_placements)
# only return placements for newly placed objects sampled_obj_names = [ obj.name for sampler in self.samplers.values() for obj in sampler.mujoco_objects ] return {k: v for (k, v) in placed_objects.items() if k in sampled_obj_names}
class MultiRegionSampler(ObjectPositionSampler): def __init__( self, name, regions, side="all", mujoco_objects=None, rotation=None, rotation_axis="z", ensure_object_boundary_in_range=True, ensure_valid_placement=True, ensure_object_in_ref_region=False, rng=None, z_offset=0.0, ): if len(regions) != 4: raise ValueError("Exactly four sites (one for each quadrant) must be provided.") if side not in self.valid_sides: raise ValueError("Invalid value for side, must be one of:", self.valid_sides)
# initialize sides and regions if side in self.sides_combinations: self.sides = self.sides_combinations[side] else: self.sides = [side] self.regions = regions
# create a list of uniform samplers (one for each site) self.samplers = list() for s in self.sides: site = self.regions[s] sampler = UniformRandomSampler( name=name, mujoco_objects=mujoco_objects, reference_pos=site["pos"], x_range=site["x_range"], y_range=site["y_range"], rotation=rotation, rotation_axis=rotation_axis, ensure_object_boundary_in_range=ensure_object_boundary_in_range, ensure_valid_placement=ensure_valid_placement, ensure_object_in_ref_region=ensure_object_in_ref_region, z_offset=z_offset, rng=rng, ) self.samplers.append(sampler)
def sample(self, fixtures=None, reference=None, on_top=True): # randomly picks a sampler and calls its sample function sampler = self.rng.choice(self.samplers) return sampler.sample(fixtures=fixtures, reference=reference, on_top=on_top)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import h5pyimport jsonimport argparseimport osfrom shutil import copyfileimport robosuiteimport xml.etree.ElementTree as ETfrom tqdm import tqdmimport numpy as np
def get_eef_panda_site(prefix): """ Helper function for new element added in robosuite v1.5 """
eef_panda_site = ( """<site name="right_center" pos="0 0 0" size="0.01" rgba="1 0.3 0.3 1" group="2"/> """ )
tree = ET.ElementTree(ET.fromstring(eef_panda_site)) root = tree.getroot() for elem in root.iter(): elem.attrib["name"] = "{}_{}".format(prefix, elem.get("name"))
return tree
def update_gripper_name(gripper_name: str): tokens = gripper_name.split("_") tokens.insert(1, "right") return "_".join(tokens)
def convert_xml(xml_str): """ Postprocess xml string generated by robosuite to be compatible with robosuite v1.5 This script should not the xml string if it was already generated using robosuite v1.5 Args: xml_str (str): xml string to process (from robosuite v1.4.1) """
root = ET.fromstring(xml_str) worldbody = root.find("worldbody") bodies_to_process = []
for body in worldbody.iter("body"): body_name = body.get("name") if "link0" in body_name: if body not in bodies_to_process: bodies_to_process.append(body)
# add elements introduced in v1.5 for body in bodies_to_process: prefix = body.get("name").split("_")[0] eef_tree = get_eef_panda_site(prefix) body.append(eef_tree.getroot())
assets = root.find("asset")
# change path from mounts to bases for asset in assets.iter("mesh"): path = asset.get("file") assert "robosuite/models/assets" in path or "robocasa/models/assets" in path, print(path) if "mounts" in path: assert not "robot" in path new_path = path.replace( "robosuite/models/assets/mounts", "robosuite/models/assets/bases" ) asset.set("file", new_path)
# update naming prefixes for elem in root.iter(): for attr, value in elem.attrib.items(): if value.startswith("mount"): elem.set(attr, value.replace("mount", "fixed_base", 1)) elif value.startswith("gripper"): elem.set(attr, update_gripper_name(value))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126from __future__ import annotations
from dataclasses import dataclassfrom enum import Enumfrom typing import TYPE_CHECKING, Any, Optional, Union
import numpy as np
from robocasa.utils.scene.success_criteria import SuccessCriteria
if TYPE_CHECKING: from robocasa.utils.scene.scene import SceneObject
@dataclass(frozen=True)class ReferenceConfig: obj: Optional[SceneObject] spawn_id: Optional[int] = None on_top: bool = True
def to_dict(self) -> Optional[dict[str, Any]]: if self.obj is None: return None if self.spawn_id is None: return {"reference": self.obj.cfg.name, "on_top": self.on_top} else: return {"reference": (self.obj.cfg.name, self.spawn_id)}
@dataclass(frozen=True)class SamplingConfig: x_range: np.ndarray = np.zeros(2) y_range: np.ndarray = np.zeros(2) rotation: np.ndarray = np.zeros(2) reference_pos: np.ndarray = np.zeros(3) z_offset: float = 0 reference: Optional[ReferenceConfig] = None
@property def sampling_args(self) -> Optional[dict]: if self.reference is None: return None return self.reference.to_dict()
@dataclass(frozen=True)class ObjectConfig: mjcf_path: str name: str static: bool = False scale: float = 1.0 density: int = 100 friction: tuple[float, float, float] = (1, 1, 1) margin: Optional[float] = None rgba: Optional[tuple[float, float, float, float]] = None sampler_config: SamplingConfig = SamplingConfig()
@dataclass(frozen=True)class SceneConfig: objects: list[SceneObject] success: SuccessCriteria instruction: str
class SceneHandedness(Enum): UNIVERSAL = "UNIVERSAL" LEFT = "LEFT" RIGHT = "RIGHT"
@dataclass(frozen=True)class SceneScaleConfig: planar_scale: Union[float, tuple[float, float]] = 1.0 vertical_scale: float = 1.0 handedness: SceneHandedness = SceneHandedness.UNIVERSAL handedness_axis: int = 1
def get_ref_pos(self, pos: np.ndarray) -> np.ndarray: pos = pos.astype(float, copy=True) # ensure float pos[self.handedness_axis] *= float(self._handedness_factor) pos[:2] = pos[:2] * np.array(self._scale, dtype=float) pos[2] *= float(self.vertical_scale) return pos
def get_rotation(self, rot: Optional[np.ndarray]) -> Optional[np.ndarray]: if rot is None: return None rot = rot.astype(float, copy=True) rot *= float(self._handedness_factor) return rot
def get_ranges(self, x_range: np.ndarray, y_range: np.ndarray) -> tuple[np.ndarray, np.ndarray]: x_range = x_range.astype(float, copy=True) y_range = y_range.astype(float, copy=True)
if self.handedness_axis == 0: x_range *= float(self._handedness_factor) x_range.sort() elif self.handedness_axis == 1: y_range *= float(self._handedness_factor) y_range.sort() return x_range, y_range
def get_z_offset(self, z_offset: float) -> float: return float(z_offset) * float(self.vertical_scale)
@property def _handedness_factor(self) -> float: if self.handedness == "LEFT": # replace with enum comparison return -1.0 else: return 1.0
@property def _scale(self) -> tuple[float, float]: if isinstance(self.planar_scale, tuple) and len(self.planar_scale) == 2: return float(self.planar_scale[0]), float(self.planar_scale[1]) elif isinstance(self.planar_scale, (float, int)): scale = float(self.planar_scale) return scale, scale else: raise ValueError( f"Invalid type for 'planar_scale': expected float or tuple[float, float], " f"but got {type(self.planar_scale).__name__}" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146from graphlib import CycleError, TopologicalSorterfrom pathlib import Path
import numpy as npfrom robosuite.environments import MujocoEnvfrom robosuite.utils import transform_utils as Tfrom robosuite.utils.mjcf_utils import xml_path_completion
import robocasafrom robocasa.models.objects.objects import MJCFObjectfrom robocasa.utils.placement_samplers import ( ObjectPositionSampler, SequentialCompositeSampler, UniformRandomSampler,)from robocasa.utils.scene.configs import ( ObjectConfig, SceneConfig, SceneScaleConfig,)
class SceneObject: def __init__(self, cfg: ObjectConfig): self.cfg = cfg self._mujoco_object = self._get_object()
@property def mj_obj(self) -> MJCFObject: return self._mujoco_object
def get_sampler_with_args( self, env: MujocoEnv, scene_scale: SceneScaleConfig ) -> tuple[ObjectPositionSampler, dict]: return ( self._get_sampler(self._mujoco_object, env, scene_scale), self.cfg.sampler_config.sampling_args, )
def _get_object(self) -> MJCFObject: abs_mjcf_path = ( self.cfg.mjcf_path if Path(self.cfg.mjcf_path).is_absolute() else xml_path_completion(self.cfg.mjcf_path, root=robocasa.models.assets_root) ) return MJCFObject( name=self.cfg.name, mjcf_path=abs_mjcf_path, scale=self.cfg.scale, solimp=(0.998, 0.998, 0.001), solref=(0.001, 1), density=self.cfg.density, friction=self.cfg.friction, margin=self.cfg.margin, static=self.cfg.static, rgba=self.cfg.rgba, )
def _get_sampler( self, obj: MJCFObject, env: MujocoEnv, scene_scale: SceneScaleConfig ) -> ObjectPositionSampler: x_range, y_range = scene_scale.get_ranges( self.cfg.sampler_config.x_range, self.cfg.sampler_config.y_range ) z_offset = scene_scale.get_z_offset(self.cfg.sampler_config.z_offset) rotation = scene_scale.get_rotation(self.cfg.sampler_config.rotation) reference_pos = scene_scale.get_ref_pos(self.cfg.sampler_config.reference_pos) return UniformRandomSampler( name=f"{self.cfg.name}_sampler", mujoco_objects=obj, x_range=x_range, y_range=y_range, rotation=rotation, rng=env.rng, rotation_axis="z", ensure_object_boundary_in_range=False, ensure_valid_placement=False, reference_pos=reference_pos, z_offset=z_offset, )
class Scene: def __init__(self, env: MujocoEnv, config: SceneConfig, scene_scale: SceneScaleConfig): self._env = env self._config = config self._scene_scale = scene_scale self._scene_objects: dict[MJCFObject, SceneObject] = {} for scene_obj in self._config.objects: self._scene_objects[scene_obj.mj_obj] = scene_obj self._scene_sampler = self._get_sampler()
@property def mujoco_objects(self) -> list[MJCFObject]: return list(self._scene_objects.keys())
@property def instruction(self) -> str: return self._config.instruction
def reset(self) -> None: sim = self._env.sim object_placements = self._scene_sampler.sample() for obj_pos, obj_quat, obj in object_placements.values(): scene_obj = self._scene_objects[obj] if scene_obj.cfg.static: body_id = sim.model.body_name2id(obj.root_body) sim.model.body_pos[body_id] = obj_pos sim.model.body_quat[body_id] = obj_quat obj.set_pos(obj_pos) obj.set_euler(T.mat2euler(T.quat2mat(T.convert_quat(obj_quat, "xyzw")))) else: joint_name = next(j for j in obj.joints if np.size(sim.data.get_joint_qpos(j)) == 7) qpos = np.concatenate([np.array(obj_pos), np.array(obj_quat)]) # Set qpos0 to support robust mujoco environment reset start_i, end_i = sim.model.get_joint_qpos_addr(joint_name) sim.data.model.qpos0[start_i:end_i] = qpos # Set qpos sim.data.set_joint_qpos( joint_name, qpos, )
def success(self) -> bool: return self._config.success.is_true(self._env)
def _get_sampler(self) -> SequentialCompositeSampler: sorted_objects = self._sort_scene_objects(list(self._scene_objects.values()))
scene_sampler = SequentialCompositeSampler(name="SceneSampler", rng=self._env.rng) for obj in sorted_objects: sampler, args = obj.get_sampler_with_args(self._env, self._scene_scale) scene_sampler.append_sampler(sampler=sampler, sample_args=args)
return scene_sampler
@staticmethod def _sort_scene_objects(scene_objects: list[SceneObject]) -> list[SceneObject]: ts = TopologicalSorter() for obj in scene_objects: ref = obj.cfg.sampler_config.reference.obj if obj.cfg.sampler_config.reference else None ts.add(obj, *([ref] if ref else [])) try: return list(ts.static_order()) except CycleError: raise ValueError("Circular reference detected")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157from __future__ import annotations
from abc import ABC, abstractmethodfrom typing import TYPE_CHECKING, Optional
import numpy as npfrom robosuite.environments import MujocoEnvfrom robosuite.environments.manipulation.manipulation_env import ManipulationEnv
from robocasa.utils import object_utils as OU
if TYPE_CHECKING: from robocasa.utils.scene.scene import SceneObject
class SuccessCriteria(ABC): @abstractmethod def is_true(self, env: MujocoEnv) -> bool: raise NotImplementedError
class IsUpright(SuccessCriteria): def __init__(self, obj: SceneObject, threshold=0.8, symmetric: bool = False): self._obj = obj self._threshold = threshold self._symmetric = symmetric
def is_true(self, env: MujocoEnv) -> bool: return OU.check_obj_upright( env, obj_name=self._obj.mj_obj.name, threshold=self._threshold, symmetric=self._symmetric, )
class IsClose(SuccessCriteria): def __init__( self, obj_a: SceneObject, obj_b: SceneObject, max_distance: float, use_xy_only: bool = False, ): self._obj_a = obj_a self._obj_b = obj_b self._max_distance = max_distance self._use_xy_only = use_xy_only
def is_true(self, env: MujocoEnv) -> bool: pos_a = env.sim.data.body_xpos[env.obj_body_id[self._obj_a.mj_obj.name]] pos_b = env.sim.data.body_xpos[env.obj_body_id[self._obj_b.mj_obj.name]] if self._use_xy_only: pos_a = pos_a[:2] pos_b = pos_b[:2] return np.linalg.norm(pos_a - pos_b) <= self._max_distance
class IsInContact(SuccessCriteria): def __init__(self, obj_a: SceneObject, obj_b: SceneObject): self._obj_a = obj_a self._obj_b = obj_b
def is_true(self, env: MujocoEnv) -> bool: return env.check_contact(self._obj_a.mj_obj, self._obj_b.mj_obj)
class IsGripperFar(SuccessCriteria): def __init__(self, obj: SceneObject, threshold: float = 0.4): self._threshold = threshold self._obj = obj
def is_true(self, env: MujocoEnv) -> bool: return OU.any_gripper_obj_far(env, obj_name=self._obj.mj_obj.name, th=self._threshold)
class IsGrasped(SuccessCriteria): _GRIPPERS = {"left", "right"}
def __init__(self, obj: SceneObject, gripper: Optional[str] = None): self._obj = obj self._grippers = {gripper} if gripper in self._GRIPPERS else self._GRIPPERS
def is_true(self, env: MujocoEnv) -> bool: assert isinstance(env, ManipulationEnv), "Expected a ManipulationEnv instance." robot = env.robots[0] return any(env._check_grasp(robot.gripper[g], self._obj.mj_obj) for g in self._grippers)
class IsRobotInRange(SuccessCriteria): def __init__(self, target: SceneObject, threshold: float, planar: bool): self._target = target self._threshold = threshold self._planar = planar
def is_true(self, env: MujocoEnv) -> bool: robot = env.robots[0] robot_pos = env.sim.data.get_body_xpos(robot.robot_model.root_body) obj_pos = env.sim.data.body_xpos[env.obj_body_id[self._target.mj_obj.name]] if self._planar: robot_pos = robot_pos[:2] obj_pos = obj_pos[:2] return np.linalg.norm(robot_pos - obj_pos) <= self._threshold
class IsPositionInRange(SuccessCriteria): def __init__( self, target: SceneObject, axis_index: int, min_val: Optional[float] = None, max_val: Optional[float] = None, ): self._target = target self._axis = axis_index self._min = min_val or float("-inf") self._max = max_val or float("inf")
def is_true(self, env: MujocoEnv) -> bool: pos = env.sim.data.body_xpos[env.obj_body_id[self._target.mj_obj.name]] return self._min <= pos[self._axis] <= self._max
class IsJointQposInRange(SuccessCriteria): def __init__(self, obj: SceneObject, joint_id: int, min_val: float, max_val: float): self._obj = obj self._joint_id = joint_id self._min = min_val self._max = max_val
def is_true(self, env: MujocoEnv) -> bool: qpos = env.sim.data.get_joint_qpos(self._obj.mj_obj.joints[self._joint_id]) return self._min <= qpos <= self._max
class NotCriteria(SuccessCriteria): def __init__(self, criteria: SuccessCriteria): self.criteria = criteria
def is_true(self, env: MujocoEnv) -> bool: return not self.criteria.is_true(env)
class AllCriteria(SuccessCriteria): def __init__(self, *criteria: SuccessCriteria): self.criteria = criteria
def is_true(self, env: MujocoEnv) -> bool: return all(c.is_true(env) for c in self.criteria)
class AnyCriteria(SuccessCriteria): def __init__(self, *criteria: SuccessCriteria): self.criteria = criteria
def is_true(self, env: MujocoEnv) -> bool: return any(c.is_true(env) for c in self.criteria)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670import inspectimport osimport randomfrom copy import deepcopyfrom pathlib import Path
import numpy as npfrom lxml import etree as ETfrom robosuite.utils.mjcf_utils import find_elements
import robocasa
TEXTURES_DIR = Path(inspect.getfile(robocasa)).parent / "models" / "assets" / "generative_textures"
CABINET_TEX_NAMES = [ "flat copy 26.png", "196415a6-3c0f-4a1f-a644-fc54a6801223.png", "2a310e7f-8005-4dba-8dea-edb1484e1e28.png", "flat copy 37.png", "1fb8c016-b655-48ab-ad53-d6238a745065.png", "f80067c5-9967-4607-880f-1c4002d400cb.png", "00846c84-f900-4bdd-897f-3928e7d87dce.png", "flat copy 38.png", "54c4d59e-c0b1-4608-a953-568e9ae13409.png", "flat copy 2.png", "flat copy 23.png", "flat copy 16.png", "251695ed-d413-48fe-817e-c3e02b3ee117.png", "18338c06-57fc-4882-ad44-b5f3b3846806.png", "flat copy 40.png", "36a1e6cb-98a1-4ada-a14e-8c04f135c5ee.png", "f06bca10-a7ce-4a4a-92f6-973d7400fe8a.png", "flat copy 41.png", "397c17e0-e91b-4fa6-98d9-97e6d2f009ed.png", "532a9660-8c7a-488b-8930-9134a9479afa.png", "flat copy 33.png", "d0299fe2-026b-4727-85e1-cb5de303e315.png", "68a933bc-df0c-4891-bd41-2c05e4fde504.png", "6698bb80-52f7-4e5b-ad6a-4a8122504f9a.png", "99f0113d-8cb4-40b6-9670-b4be4c1fc475.png", "flat copy 32.png", "flat copy 34.png", "c1ad279c-9093-469e-aa20-b73af0fc8db4.png", "518ddc39-55c2-4b18-8bf6-e9c4f0806760.png", "flat copy 8.png", "860cab10-089c-4d99-ae89-3e4f87df5d9c.png", "f29d41e9-d285-47e4-ad29-f04423533802.png", "flat copy 13.png", "flat copy 12.png", "e6420ee4-14f0-404f-9cd7-abc9a69da621.png", "flat copy 4.png", "de7f86d5-56c9-4331-a9aa-655687dc354b.png", "flat copy 35.png", "flat.png", "b6abcb20-8b90-42d3-9175-ba6b4d53a7a9.png", "d29a6530-28d6-4dbe-bce5-9014d613ae5e.png", "992f49b2-3f7c-4c54-a4d6-75af4693353b.png", "flat copy 27.png", "fd195b15-b98c-47c9-b608-de4157f6ceba.png", "flat copy 10.png", "flat copy 15.png", "af993127-4ec6-4fa3-9a27-018af985a4a0.png", "8de5fd51-b7b5-4014-a892-f0498c35fec2.png", "flat copy 3.png", "flat copy 11.png", "flat copy 30.png", "edc5b189-60a3-4aa0-a68d-cc35009f3648.png", "flat copy 20.png", "flat copy 19.png", "9fe8882d-3aa9-4d2b-8de3-d9d220ea526c.png", "flat copy 7.png", "flat copy 46.png", "flat copy 9.png", "230e3f37-02d7-4be9-b6a8-1e4fb3acd368.png", "flat copy 45.png", "7f426b18-12ee-492b-9c69-dfa8ccbc42cc.png", "flat copy 49.png", "flat copy 22.png", "7fe6e2dc-615f-432e-92d4-0a4f17a9ac49.png", "flat copy 47.png", "flat copy 42.png", "34c9cf7b-5b5d-4c81-bb95-6d5743d25a18.png", "aae9ec57-7df1-4af7-8e40-62962b90cce4.png", "flat copy 36.png", "flat copy 25.png", "5a34b72d-3b7e-4a9a-9a0f-f73f2230fe28.png", "e2e0160d-9809-48d2-b018-416ee0254fc0.png", "a6bb714e-0f35-46d6-b7e8-3c18232a4801.png", "a86a130e-04a3-44b0-99b7-44ce0a63cc2b.png", "01f783e0-38de-497d-8ebe-c8d8a47e520a.png", "flat copy 44.png", "e0e2d63e-900b-4ecb-8df9-28115a58c3a2.png", "flat copy 50.png", "flat copy 5.png", "flat copy 18.png", "1aac54cf-8bf3-428c-93cd-1d3c258ff6b4.png", "flat copy 14.png", "11717454-440d-4b32-85c3-bf0013c66c61.png", "67d50012-cba6-4525-8e00-b71124861f7e.png", "25436e21-3140-4875-89a9-d14c5ce20f31.png", "e4a28073-2252-4603-8c4b-75527a8c5ae9.png", "flat copy 17.png", "flat copy 48.png", "flat copy 6.png", "28d31de4-53f8-434a-ac57-4d5d27f5ab2f.png", "flat copy.png", "flat copy 39.png", "flat copy 43.png", "flat copy 24.png", "6a13b80d-83c7-4fe1-8412-4fc07eefaa35.png", "43a60b06-97b9-4119-b416-c7fc6783aa81.png", "flat copy 21.png", "flat copy 28.png", "flat copy 31.png", "flat copy 29.png",]
COUNTER_TOP_TEX_NAMES = [ "5065776e-1fbc-4a70-a786-9a2ec6ee5aa0.png", "e7f151aa-2354-48d0-94e8-071462f16ca7.png", "b6618923-8455-44c3-8ae6-b766f34267cc.png", "71d72043-3d97-4ea6-82f0-3ccbb53e0534.png", "deb1e565-5c29-4285-aef8-f904c2b41dfb.png", "ecf23b20-3db2-476a-bc06-442754ba5e76.png", "39be4639-f28b-4bfa-8c1e-4b37e40395be.png", "8bafdd4c-a44c-4bc0-8978-e7bc0abcedb4.png", "3b958a28-0807-484a-92e7-f17b4c6dcbeb.png", "ecd3c3fb-c4f2-4021-86d8-665e92b2735e.png", "014ac251-0435-41c2-9dee-c664ee268327.png", "0171bbba-6293-4117-b0ad-bc4b98d1c20e.png", "0bd64a61-e098-4d06-ba3f-0a12269d3584.png", "d5db5c5c-779b-4de0-ac66-31856239d488.png", "9c47a3ac-2e56-47c1-86d4-006f98e21987.png", "133b4eaf-bb93-4655-844c-a02278dfc032.png", "58bcfa8c-6e11-494f-8fc5-d5a32ac7b3de.png", "276de88a-374b-4dde-ac45-c52d651044b3.png", "f52f1aaa-c061-42c0-8bdd-d2edb4af8736.png", "1ccd1303-2e23-44c4-bb21-0dd474b0d899.png", "761d55a2-5858-4d02-ab13-0bb272a67eed.png", "c9d714cd-b00b-4d96-b6a6-cdc9e01c1b71.png", "06da7e0e-c12c-4da7-a56b-9a3c82d87809.png", "e5d1c208-34ad-49a7-8151-c0d55ecff952.png", "9ccbd07a-887c-48c8-a806-0fac93606bb0.png", "3d48ef42-02d9-41ed-bef6-f5c0dd47cdfa.png", "9e1fd142-1d1c-4a82-a961-681db31b343f.png", "5259cbe7-d956-4a0a-99d1-d7c7d391488f.png", "94bdb3c5-faa2-4274-9337-ca5b9fabce88.png", "e572f3d8-9ef2-4cd2-83c1-8acb766dbc4b.png", "956782b3-ca4b-49e8-8939-6c50e87b9609.png", "258270ae-3af4-4644-a031-176efac2c3f9.png", "1fa52c2f-7474-4aa9-9ff9-0e411a78daac.png", "f1299a54-59e5-42ea-9f53-e9f11fd6ca3c.png", "6a6a86a2-bbba-422a-9620-5b90adaaf7a3.png", "771c03d6-f0c8-4e3e-b734-0a07fff03c22.png", "8c6ed656-6d1c-4707-82a2-cbff87a589f7.png", "6a4f994f-293f-4a8a-8f8d-ac99f8e58adf.png", "da90fb4d-3dfb-4a17-8ecc-95e82ab69b32.png", "1563c9ee-30ab-44cc-b21f-fab5ad8df99d.png", "932f5612-9058-4923-820d-894d630190cb.png", "5e2958ab-c27d-41c8-8167-de9053f79038.png", "2408cfed-ad91-43e2-9295-fdafafb76c8d.png", "8549466d-50fe-4cb9-9001-e93532e7938c.png", "00e4b598-2dd0-4ff9-b0a4-46e223a9296e.png", "0666bf9a-4625-4132-bd7f-0079dace8c8c.png", "ceb18b7d-1dcf-4aa2-adae-0e0aae1c5eeb.png", "a4903060-7bfd-4bd5-b8d6-b916d172a82b.png", "f5f4cf81-db71-42c7-b889-c25c145132c6.png", "bf277536-38a6-41cd-a278-bd68e25816fd.png", "a1cfe2ab-12cd-4d43-9ffc-77d48d0493f3.png", "1c72f7db-374f-47db-8424-9526d4e7fa7a.png", "3dc423ca-b351-429f-9842-1bd17e3ce360.png", "2a8aea9d-218c-4601-8e8d-b98eb93fa461.png", "451b6b8b-5d86-44ad-853b-e99153ba48e1.png", "25d4c91a-c831-4249-b78e-a4b25d0b1ea1.png", "b4f0036f-f2e7-4167-bbc4-708ee783052f.png", "db04923e-96ac-41db-a16c-901f10a41bf0.png", "65e832aa-974a-4ca8-9dd8-e90a96d75b6c.png", "f66bf802-8273-4df7-a58a-faa8ba6ed46f.png", "827976d2-dbab-47a3-905f-602e945a6b30.png", "124bd263-2b8a-4057-9211-b36869047fd2.png", "f69e2027-7163-4a53-8361-6050e5679242.png", "d366b33d-335e-4a76-91f5-a5ce14266c89.png", "adcb6ab3-7ecf-47f9-a11e-6a505ad23d98.png", "2cea6a36-7053-4808-be22-fc5cc76b5531.png", "ac3491a2-e817-4f5e-8453-ce34cb78a8a9.png", "a875270b-fd82-409d-9bed-1d567657ff8e.png", "f29cfb8b-d640-48a4-ae5e-02395ed7c6db.png", "8c165058-abec-4ea9-9990-19b7eff4df4f.png", "1c6ea15c-1cad-4a0c-838a-5eee8f99cfc9.png", "897d7c04-f1bd-4bb1-bffb-bfada23a5b58.png", "1b23c19f-7e79-4b96-a744-42615a72d722.png", "f921b606-5363-41c2-aa93-dc8ec1475fda.png", "efca4079-dd9f-4d54-8943-216d6c02e70a.png", "040ff758-026f-4313-b390-ec86d3690f9d.png", "0104c474-6473-4e05-b789-6bdb59f55da7.png", "f73ed4a7-c1b1-4660-9eba-00f2ba25977b.png", "0b184f66-ba4f-4fcd-9556-bea9f58dc9c6.png", "7f638e9b-10e8-448c-a2f9-a75ae414dcfa.png", "e563fd4b-656f-45f1-b803-df0d6dcb8bd3.png", "0ed8ccf8-33e5-45a2-9200-4dc1a5565494.png", "1ab263d2-ea24-4fe7-9383-f227aadc8c47.png", "561d2d94-ec96-4246-974a-d9abc6f2297a.png", "9af6ae6e-a842-4baa-a01e-cec57045c367.png", "1c6fc0f3-d4ef-423b-9bba-d4a5d59c05df.png", "76a72b39-24ec-4044-aad8-49f381939063.png", "08ca0b3f-17e9-476e-9c17-ff81616c6bd7.png", "9b637968-8173-44da-8f41-3943c4d182f9.png", "725eb22a-2c4b-44b0-8aaf-bef282232601.png", "3e81b87f-10ee-4f74-8ba8-1b724df383fb.png", "fc9c7e5a-7abb-4ff6-84f2-9fce43bc200f.png", "a8f33495-cd01-4b66-9c7e-3ba5edec6565.png", "8585099d-cf7f-4c1c-8f36-937939dba42e.png", "fe8afe85-5153-48cb-80e0-88de2a577f0c.png", "46c59505-7dec-48f2-a0d1-c36ac213890e.png", "95b636b0-8afb-4430-8f6a-1f4e0f4eb808.png", "5ab4d96a-5401-45d8-977c-b3fef4e55ca9.png", "8c8dd1cd-6c84-4fa8-b51b-ac736fda7a6c.png", "76c7b19f-b375-48db-a1df-d79485a86d94.png",]
FLOOR_TEX_NAMES = [ "8e4ea598-7170-4d24-ad12-42d45ef17a3b.png", "9d7e7eac-9d81-4b04-8a07-ec35f9e7b58d.png", "83c7c8bf-9277-4f59-88bd-1a4f428262ef.png", "28359684-bb12-4b99-86b2-8c0998ee8fec.png", "8ebc0bbe-1656-465e-b31e-766d1aceaec2.png", "ada4e736-880d-4372-b148-218dc114c7fe.png", "8a12dcf7-fc25-4341-9ea0-e583f1cc3d71.png", "28f34ad5-b4f1-4b81-99cc-b04ed28d653b.png", "b5350f4e-9521-4af1-a03f-a39e5d8b1796.png", "14b4a5c3-69e0-425c-b8c5-ce495ab87409.png", "022ec5c1-324e-4217-9f03-92b0e2f9c74f.png", "9f345d0f-a768-4def-bebf-b818cf0c68dc.png", "49de13f1-9488-4893-8398-48b0a5f27453.png", "a938167f-6cb2-4e87-94f5-185eac06ff21.png", "2aa2a926-fe72-4221-bd30-16e0a0cc9324.png", "1671701f-60d2-4c71-95cc-8bdbb9f57ff9.png", "8b24233c-7658-4d52-809d-a6fc71f37554.png", "9582e8cc-89f5-464f-b183-2f21b8f0f267.png", "8184ce85-7db2-4b23-908b-1170cc6830cf.png", "32a18f41-8e7c-4a9d-b5ac-a7ba19a9ed35.png", "56c9fb44-a8ee-469d-85d4-6d419f9dcba3.png", "7ff039e9-7563-4ef0-b2ec-ce3d0d259a99.png", "dbdd0778-8700-4967-bb52-75bbfa7eb29c.png", "50578da0-60d8-4e12-800e-3df2fbf1bd5a.png", "cedd99bd-8f8f-4d60-98e8-75e0af9b7e4f.png", "b6c12637-3bd8-41d4-a787-3c2c271f4221.png", "22c6be8e-a027-47dc-b2a1-3284cf5baad0.png", "ed301cb6-fc33-4a6a-a2fd-4ce27a1f5bac.png", "fc6bffaf-b9fd-4d51-a795-cb95d280dcab.png", "310661bb-e74a-4b55-b999-ae1e2855990f.png", "c327867a-02ea-4629-8059-181d3f341dc2.png", "67a6f678-5f4b-4999-88fd-d0587299eb90.png", "c65c9338-2903-4c6a-8015-dc606d24e659.png", "e584ce4a-ff4d-461f-989e-5e4d21da42de.png", "8776902b-74c1-4a54-94f2-320b4e89b5df.png", "b588fa60-819c-4ae7-84bb-8f3de009ee1b.png", "bdddfbd0-acc5-4e73-becb-c91f69986201.png", "1f13ee23-d3f8-4fe4-b24d-97c4dece35c5.png", "447fc81b-73c3-4502-8de7-9db654e62902.png", "f78f9be1-385c-43ed-a89b-a4f11d45695f.png", "c82d1a06-f78d-4e79-9b3e-23c4756d555d.png", "573d34d2-a045-455c-b525-34a8571808eb.png", "07f74135-07ab-4e29-bb00-4782f15ab59f.png", "bec253e6-b2f0-48f2-afba-9207388a7937.png", "0139f959-a4a8-4504-b6d2-f9351afd5941.png", "8373a547-a792-438e-b941-f01ca1f0fb5d.png", "b37ff2ac-f755-42f1-bdd4-a3a0f30fbfc6.png", "f068688f-4b20-4d2f-b33a-9732b5050f72.png", "c707d14d-3089-4a3e-a5b2-1088eda621bc.png", "81ea9eea-29ea-4516-9e0d-e7ed0df98f5d.png", "9aa36664-4ac6-4a50-b0e0-05c96f52c58e.png", "c85db92d-b5a4-4fc8-aabd-9d4c82f3f444.png", "df431f5c-699e-47ff-9161-b6e264a82163.png", "4d8ea3e7-4a0b-4015-802c-cbbd0b12ba2e.png", "3a34566d-b31f-4d3d-a86a-8038fde33b8c.png", "83c6fd2f-caa2-4d53-b4d2-e19a7f12e6b4.png", "ef044eea-9ebe-475e-bc05-d4e9d9255e39.png", "02b897ed-2381-403a-aef1-095096993039.png", "bb9ea1a0-7bfb-4aa2-85ee-0dbdb5001fa3.png", "2afa8673-57cc-4953-b178-b57eedd9ad0a.png", "2066e385-7798-47b3-89cc-1eaad15c75c4.png", "45639cb9-7ac7-4d8c-a8a1-719d3a53d531.png", "8f7fabcb-6875-4437-9d9c-27a2552c10dd.png", "ce8ccc5f-20b9-4d06-aee6-fe85a6c02eaa.png", "11fa953e-c11d-4dad-8e51-47cc6dc67aeb.png", "8f51e06a-7bd0-4d2f-9a20-7821a975559a.png", "1ef4cfa4-cf52-4efd-9fb3-6698650ee239.png", "4d974231-cd17-4da5-ad9a-7faf83c2d683.png", "cadaada3-e8f1-4bc7-af71-342215edbbb1.png", "fb9b36a4-d87a-4c7f-a06c-a1e94869b96b.png", "5daabcbd-0ce4-4dba-9342-c74d3da4fadf.png", "612b00d2-819f-46ac-a599-38672184c842.png", "0b5b5a9a-1435-4dfe-b6f4-19f4dbae1e8e.png", "11f6a3bb-c36c-45c2-a429-501ac0cabc02.png", "cf96c697-41f0-4d3c-a1d4-17d0d82719d0.png", "81d9e9f2-8ff4-4d45-b1dd-d3afd3c62fb0.png", "82036c07-5321-47c8-974c-27d58e526ba1.png", "e793023f-7e5f-4211-9724-9022d3c8f920.png", "0c01c256-4779-4093-a0b9-3347c31ef53f.png", "9db099e2-56cb-4bec-becc-eb69c298866e.png", "05f75518-7b70-4098-8983-aca459f33ddb.png", "7c935010-badd-4fa4-8089-4fc9728dfe96.png", "f9d057b1-5843-4b68-a58b-9fe87291a72f.png", "9354be03-5a87-4ce8-85bc-8b0157abeb1c.png", "9bfe963b-6d17-4704-8a9f-c2de48491b70.png", "3b70d093-e264-4550-b5e5-f750ba577b78.png", "67837bbb-05ae-4665-90e5-572130b7fc86.png", "d339c422-36d0-40f3-8393-24076abb279c.png", "5ccc395f-efd5-44af-b5f9-885789e26661.png", "6d58d55a-34cc-455f-8b4c-004fabef6e11.png", "5729f1d0-0796-4d82-99f7-76a171266fae.png", "1e6da165-23cb-4426-91cf-450b3ac74e49.png", "86ae5f3b-1a9c-4895-87eb-b526b403f332.png", "4e53b13b-317a-484c-9b8b-7417453e45ff.png", "8ddb08c1-facb-4fb1-841b-bde4e47fe584.png", "41c3dbec-db54-4417-bb76-f51a4349943e.png", "a2881fcf-1af3-46e9-87b0-c198fad703d1.png", "808ec0fb-fcf8-4629-9296-38530521a95e.png", "7c411449-a3c6-48e4-ab30-d08bca5938d6.png", "0df28fee-6cef-48ae-9e8e-c0f0f3482412.png",]
WALL_TEX_NAMES = [ "plain copy 49.png", "18a6abbd-8ca1-43d9-9a0a-8424a7d1e016.png", "plain copy 2.png", "0882d081-d8be-49c0-aad6-3f5eff92265b.png", "plain copy 39.png", "7a19bf00-4f43-4e39-8fe6-977df7c6d147.png", "plain copy 8.png", "9b6f9830-a89d-4a42-965f-581dd0a12617.png", "bcf9bf9b-ac75-408e-ab2e-516391c39d8e.png", "plain copy 51.png", "845424a1-4603-47d7-892c-426c2d427f0d.png", "6e961263-5c90-41f9-87d3-b9e132c9583a.png", "c72ea705-e088-4665-9683-6a8685758aef.png", "plain copy 22.png", "plain copy 44.png", "plain copy 10.png", "df17f0f3-68bb-46e2-ae9f-86cf84f48b04.png", "plain copy 53.png", "0906d773-7c22-4173-9edc-efc6e2da88e0.png", "8995f82f-2435-4395-8ecd-a00824edd923.png", "0adf5feb-6a2f-4417-811a-b7d70d42fb34.png", "plain copy 5.png", "536410ee-0460-43b0-9e8e-799e96439a0d.png", "plain copy 11.png", "plain copy 19.png", "plain copy 17.png", "plain copy.png", "plain copy 31.png", "Lance_Z._white_square_tiles_texture_image_ikea_high_quality_rea_f41b5937-af3e-4df8-b19d-ae4fa942f741.png", "f6353155-1a10-41a1-be1d-149368938757.png", "b1a7c75f-6b03-4b10-99cd-3299d7b6beb5.png", "plain copy 52.png", "7844f4b6-7d34-46b4-8ea4-19ab954ca58f.png", "0dd40625-0cf8-4523-92cd-063c96108a23.png", "plain copy 40.png", "plain copy 21.png", "plain copy 36.png", "plain copy 37.png", "plain copy 41.png", "plain copy 23.png", "1b8b8a44-ce4e-4156-978b-ad66bf4a6f45.png", "plain copy 46.png", "d208d65f-4d99-4963-8140-d54180844c8c.png", "0aa2c331-8025-4417-a157-91467143c85b.png", "d4775c13-15ea-496d-b5fc-19d2a9cab128.png", "11760e4b-5f86-46cb-82ae-c87cc6f434d1.png", "plain copy 3.png", "plain copy 30.png", "plain copy 9.png", "0af727bd-14b4-4f7d-9fee-19f7f001ad34.png", "67d1229f-7689-4dd6-ab2b-d003e0cd3cb7.png", "plain copy 33.png", "plain copy 4.png", "2149f068-ca27-40ed-b53d-07e53210e678.png", "plain copy 38.png", "6b215002-fd31-4f1a-859a-d5d98a2a0c52.png", "4fe97e2e-ae88-4dc9-8321-3529a2108508.png", "Lance_Z._white_square_tiles_ikea_high_quality_realistic_ec4bd31e-d76d-4512-8b0d-a86dd8dd6aad.png", "plain copy 6.png", "plain copy 13.png", "0d7afefe-58c8-4161-bf56-0974c7e806a2.png", "plain copy 28.png", "314f4070-0b2f-4433-98e7-dbdf18a8bff2.png", "plain copy 18.png", "dae6863d-b653-4998-8239-c6a6bb24362c.png", "497cbc0b-a80a-42b3-8f5e-3bc97c145255.png", "plain copy 20.png", "4874a0d3-f5f2-46ea-a1d3-824b2f56f8ce.png", "plain copy 50.png", "plain copy 12.png", "7c7c9950-576a-45fd-b3d1-74cca30f6fe7.png", "8474c563-65b7-408b-976f-b19b38a44f90.png", "Lance_Z._white_square_tiles_texture_image_ikea_high_quality_rea_ce2dcd92-29d7-4176-b7fa-79d91dab133b.png", "738a1240-97f3-4fa6-97df-0ecc4b7aac26.png", "plain copy 32.png", "plain copy 29.png", "a4046f8f-a2d6-4ef4-aa39-2ec541cbd246.png", "plain copy 25.png", "cbf05cdc-5d1c-472b-9891-0e4802553359.png", "plain copy 16.png", "plain copy 47.png", "4bb0ad30-b60a-44a6-a259-058fab19b422.png", "77abb443-a1b8-4b02-96de-1a7bc68d4f3f.png", "plain copy 27.png", "plain copy 24.png", "plain copy 43.png", "35ded0fe-73a7-4e82-8c01-32f79f5214a3.png", "4b9d5219-38a0-4303-8837-29c4c51eed54.png", "8949ad7c-2b89-444c-a758-b513f25937e1.png", "plain copy 48.png", "plain copy 45.png", "plain copy 35.png", "plain copy 26.png", "plain copy 42.png", "f7c0d850-4b56-484f-85ce-e9c4bd01ec22.png", "9ec0b130-598a-4471-99ee-f68ee49a4a9f.png", "b1dcb5d2-434e-4bd1-9329-eb1c2a6c039d.png", "cf0d9763-3596-48de-af34-5f3647d812df.png", "plain copy 14.png", "fda88519-7a09-466d-84a2-19b216562dcb.png",]
def get_random_textures(rng, frac=1.0): """ This function returns a dictionary of random textures for cabinet, counter top, floor, and wall.
Args: rng (np.random.Generator): Random number generator used for texture selection
frac (float): Fraction of textures to select from the list of available textures Default: 1.0 (select from all textures)
Returns: textures (dict): Dictionary of texture paths """
end_ind = int(frac * 100) ind = rng.integers(0, end_ind)
textures = dict( cab_tex=os.path.join(TEXTURES_DIR, "cabinet", CABINET_TEX_NAMES[ind]), counter_tex=os.path.join(TEXTURES_DIR, "counter", COUNTER_TOP_TEX_NAMES[ind]), floor_tex=os.path.join(TEXTURES_DIR, "floor", FLOOR_TEX_NAMES[ind]), wall_tex=os.path.join(TEXTURES_DIR, "wall", WALL_TEX_NAMES[ind]), )
return textures
def replace_counter_top_texture(rng, initial_state: str, new_counter_top_texture_file: str = None): """ This function replaces the counter top textures during playback.
Args: rng (np.random.Generator): Random number generator used for texture selection
initial_state (str): Initial env XML string
new_counter_top_texture_file (str): New texture file for counter top: i.e "marble/dark_marble.png" If None (default), will replace with a random texture from marble directory """
root = ET.fromstring(initial_state) asset = root.find("asset")
if new_counter_top_texture_file is None: new_counter_top_texture_file = get_random_textures(rng)["counter_tex"] else: new_counter_top_texture_file = os.path.join(TEXTURES_DIR, new_counter_top_texture_file)
# step 1: find the name of texture that will be replaced counter_tex_name = None for mat in asset.findall("material"): name = mat.get("name") if "counter_top" in name: counter_tex_name = mat.get("texture") break assert counter_tex_name is not None
# step 2: find and replace texture element CTOP_TEX_NAME = "counter_top_replacement_texture" for tex in asset.findall("texture"): name = tex.get("name") if name == counter_tex_name: tex.set("name", CTOP_TEX_NAME) tex.set("file", str(new_counter_top_texture_file))
# step 3: reference new textures in materials for mat in asset.findall("material"): name = mat.get("name") if "counter_top" in name: mat.set("texture", CTOP_TEX_NAME)
return ET.tostring(root).decode("utf-8")
def replace_cab_textures(rng, initial_state: str, new_cab_texture_file: str = None): """ This function replaces the cabinet and counter base textures during playback.
Args: rng (np.random.Generator): Random number generator used for texture selection
initial_state (str): Initial env XML string
new_cab_texture_file (str): New texture file for counter base and cabinets: i.e "cabinet/..." If None (default), will replace with a random texture from flat or wood directories """
root = ET.fromstring(initial_state) asset = root.find("asset")
if new_cab_texture_file is None: new_cab_texture_file = get_random_textures(rng)["cab_tex"] else: new_cab_texture_file = os.path.join(TEXTURES_DIR, new_cab_texture_file)
CAB_TEX_NAME_2D = "cab_replacement_texture_2d" tex_2d = find_elements( asset, tags="texture", attribs={"name": CAB_TEX_NAME_2D}, return_first=True ) if tex_2d is not None: tex_2d.set("file", str(new_cab_texture_file)) else: tex_2d = ET.Element( "texture", type="2d", name=CAB_TEX_NAME_2D, file=str(new_cab_texture_file) ) asset.append(tex_2d)
CAB_TEX_NAME_CUBE = "cab_replacement_texture_cube" tex_cube = find_elements( asset, tags="texture", attribs={"name": CAB_TEX_NAME_CUBE}, return_first=True ) if tex_cube is not None: tex_cube.set("file", str(new_cab_texture_file)) else: tex_cube = ET.Element( "texture", type="cube", name=CAB_TEX_NAME_CUBE, file=str(new_cab_texture_file), ) asset.append(tex_cube)
for mat in asset.findall("material"): name = mat.get("name") if "counter_base" in name: mat.set("texture", CAB_TEX_NAME_CUBE) elif "housing" in name: mat.set("texture", CAB_TEX_NAME_CUBE) elif ( "stack" in name or "cab" in name or "shelves" in name or "bottom" in name or ("top" in name and "counter" not in name and "stove" not in name) ): if "handle" in name or "transparent" in name: continue elif "door" in name: mat.set("texture", CAB_TEX_NAME_2D) elif "shelves" in name: mat.set("texture", CAB_TEX_NAME_2D) else: mat.set("texture", CAB_TEX_NAME_CUBE)
return ET.tostring(root).decode("utf-8")
def replace_floor_texture(rng, initial_state: str, new_floor_texture_file: str = None): """ This function replaces the counter top textures during playback.
Args: rng (np.random.Generator): Random number generator used for texture selection
initial_state (str): Initial env XML string
new_floor_texture_file (str): New texture file for counter top: i.e "wood/dark_wood_planks_2.png" If None (default), will replace with a random texture from wood directory """
root = ET.fromstring(initial_state) asset = root.find("asset")
if new_floor_texture_file is None: new_floor_texture_file = get_random_textures(rng)["floor_tex"] else: new_floor_texture_file = os.path.join(TEXTURES_DIR, new_floor_texture_file)
# step 1: find the name of texture that will be replaced floor_tex_name = None for mat in asset.findall("material"): name = mat.get("name") if "floor" in name and "backing" not in name: floor_tex_name = mat.get("texture") break assert floor_tex_name is not None
# step 2: find and replace texture element FLOOR_TEX_NAME = "floor_replacement_texture" for tex in asset.findall("texture"): name = tex.get("name") if name == floor_tex_name: tex.set("name", FLOOR_TEX_NAME) tex.set("file", str(new_floor_texture_file)) tex.set("type", "2d")
# step 3: reference new textures in materials for mat in asset.findall("material"): name = mat.get("name") if "floor" in name and "backing" not in name: mat.set("texture", FLOOR_TEX_NAME) mat.set("texrepeat", "2 2")
return ET.tostring(root).decode("utf-8")
def replace_wall_texture(rng, initial_state: str, new_wall_texture_file: str = None): """ This function replaces the counter top textures during playback.
Args: rng (np.random.Generator): Random number generator used for texture selection
initial_state (str): Initial env XML string
new_wall_texture_file (str): New texture file for counter top: i.e "wood/dark_wood_planks_2.png" If None (default), will replace with a random texture from wood directory """
root = ET.fromstring(initial_state) asset = root.find("asset")
if new_wall_texture_file is None: new_wall_texture_file = get_random_textures(rng)["wall_tex"] else: new_wall_texture_file = os.path.join(TEXTURES_DIR, new_wall_texture_file)
# step 1: find the name of texture that will be replaced wall_tex_name = None for mat in asset.findall("material"): name = mat.get("name") if "wall" in name and "floor" not in name and "backing" not in name: wall_tex_name = mat.get("texture") break assert wall_tex_name is not None
# step 2: add new texture element WALL_TEX_NAME = "wall_replacement_texture" for tex in asset.findall("texture"): name = tex.get("name") if name == wall_tex_name: tex.set("name", WALL_TEX_NAME) tex.set("file", str(new_wall_texture_file)) tex.set("type", "2d")
# step 3: reference new textures in materials for mat in asset.findall("material"): name = mat.get("name") if "wall" in name and "floor" not in name and "backing" not in name: mat.set("texture", WALL_TEX_NAME) mat.set("texrepeat", "3 3")
return ET.tostring(root).decode("utf-8")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556from robosuite.utils.transform_utils import *
def unmake_pose(pose): """ Split homogenous pose matrices back into translation vectors and rotation matrices.
Args: pose (np.array): batch of pose matrices with last 2 dimensions of (4, 4)
Returns: pos (np.array): batch of position vectors with last dimension of 3 rot (np.array): batch of rotation matrices with last 2 dimensions of (3, 3) """ return pose[..., :3, 3], pose[..., :3, :3]
def standardize_quat(quaternions): """ Convert a unit quaternion to a standard form: one in which the real part is non negative.
Args: quaternions: Quaternions with real part last (e.g. xyzw), as tensor of shape (..., 4).
Returns: Standardized quaternions as tensor of shape (..., 4). """ # if isinstance(quaternions, torch.Tensor): # return torch.where(quaternions[..., 3:4] < 0, -quaternions, quaternions) return np.where(quaternions[..., 3:4] < 0, -quaternions, quaternions)
def pose_in_world_to_pose_in_ref(pos_in_world, rot_in_world, ref_pos, ref_rot): """ Takes a pose in world frame and a reference pose (in world frame) and transforms the pose to be with respect to the reference frame. """
# Let O be the frame of the item of interest, R be the reference frame, # and W be the world frame. Then, # # T^O_R = (T^R_W)^-1 T^O_W pose_in_world = make_pose(pos_in_world, rot_in_world) ref_pose = make_pose(ref_pos, ref_rot) world_in_ref = pose_inv(ref_pose) return np.matmul(world_in_ref, pose_in_world)
def extract_top_down_angle(rotation_matrix): """ Gets top-down angle about z-axis for a given 3D rotation matrix, assuming that the rotation matrix corresponds to a simple rotation about z-axis. """ return np.arctan2(rotation_matrix[1, 0], rotation_matrix[0, 0])123456789101112131415161718192021222324252627282930# MuJoCo USD Integration
USD is file format originally introduced by Pixar to compose 3D scenes in virtual worlds. We implement the ability to export MuJoCo models and trajectories as USD files for visualization with external renderers such as NVIDIA Omniverse and Blender.
## Installation
We assume that users have already installed MuJoCo either directly with pip or from source. For information on how to build MuJoCo from source, please visit this [reference](https://mujoco.readthedocs.io/en/stable/python.html#building-from-source). We also assume Python>=3.8.
Using the USD bridge functionality requires the installation of additional libraries. Specifically, we utilize the `open3d` and `usd-core` packages. These can be installed directly using pip.
```bashpip install open3dpip install usd-core```
## Getting Started
We provide a demo script to get started with generating USD files. This demo script is located at `python/mujoco/usd/demo.py`. In this script, we load a the `cards.xml` model and step through it for a given number of steps. At each step, we make a call to the USD exporter to store information for any state changes including the positions and orientations of geoms in the scene.
## TODOs and Known Bugs
TODOs:
- Include tendons and contact forces in USD file- Include references to third party materials for NVIDIA Omniverse in USD file- Including custom defined matrials for NVIDIA Omniverse- Bridge for modeling environments and assets from third party modeling engines to MuJoCo
Known issues 🐛: - Texture mapping for non-UV objects not consistent with MuJoCo renderer when ported to new renderers1234from .component import *from .exporter import *from .shapes import *from .utils import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429# Copyright 2024 DeepMind Technologies Limited## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ==============================================================================from typing import List, Optional, Tuple
import mujocoimport numpy as np
# TODO: b/288149332 - Remove once USD Python Binding works well with pytype.# pytype: disable=module-attr# from open3d import open3d as o3d# import open3d as o3dfrom pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade, Vt
import robocasa.utils.usd.shapes as shapes_componentimport robocasa.utils.usd.utils as utils_component
class USDMesh: def __init__( self, stage: Usd.Stage, model: mujoco.MjModel, geom: mujoco.MjvGeom, obj_name: str, dataid: int, rgba: np.ndarray = np.array([1, 1, 1, 1]), texture_file: Optional[str] = None, ): self.stage = stage self.model = model self.geom = geom self.obj_name = obj_name self.rgba = rgba self.dataid = dataid self.texture_file = texture_file
xform_path = f"/World/Mesh_Xform_{obj_name}" mesh_path = f"{xform_path}/Mesh_{obj_name}" self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) self.usd_mesh = UsdGeom.Mesh.Define(stage, mesh_path) self.usd_prim = stage.GetPrimAtPath(mesh_path)
# setting mesh structure properties mesh_vert, mesh_face, mesh_facenum = self._get_mesh_geometry() self.usd_mesh.GetPointsAttr().Set(mesh_vert) self.usd_mesh.GetFaceVertexCountsAttr().Set([3 for _ in range(mesh_facenum)]) self.usd_mesh.GetFaceVertexIndicesAttr().Set(mesh_face)
# setting mesh uv properties mesh_texcoord, mesh_facetexcoord = self._get_uv_geometry() self.texcoords = UsdGeom.PrimvarsAPI(self.usd_mesh).CreatePrimvar( "UVMap", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying ) self.texcoords.Set(mesh_texcoord) self.texcoords.SetIndices(Vt.IntArray(mesh_facetexcoord.tolist()))
self._attach_material()
# defining ops required by update function self.transform_op = self.usd_xform.AddTransformOp()
def get_facetexcoord_ranges(self, nmesh, arr): facetexcoords_ranges = [0] running_sum = 0 for i in range(nmesh): running_sum += arr[i] * 3 facetexcoords_ranges.append(running_sum) return facetexcoords_ranges
def _get_uv_geometry(self): mesh_texcoord_adr_from = self.model.mesh_texcoordadr[self.dataid] mesh_texcoord_adr_to = ( self.model.mesh_texcoordadr[self.dataid + 1] if self.dataid < self.model.nmesh - 1 else len(self.model.mesh_texcoord) ) mesh_texcoord = self.model.mesh_texcoord[mesh_texcoord_adr_from:mesh_texcoord_adr_to]
mesh_facetexcoord_ranges = self.get_facetexcoord_ranges( self.model.nmesh, self.model.mesh_facenum )
mesh_facetexcoord = self.model.mesh_facetexcoord.flatten() mesh_facetexcoord = mesh_facetexcoord[ mesh_facetexcoord_ranges[self.dataid] : mesh_facetexcoord_ranges[self.dataid + 1] ]
mesh_facetexcoord[mesh_facetexcoord == len(mesh_texcoord)] = 0
return mesh_texcoord, mesh_facetexcoord
def _get_mesh_geometry(self): mesh_vert_adr_from = self.model.mesh_vertadr[self.dataid] mesh_vert_adr_to = ( self.model.mesh_vertadr[self.dataid + 1] if self.dataid < self.model.nmesh - 1 else len(self.model.mesh_vert) ) mesh_vert = self.model.mesh_vert[mesh_vert_adr_from:mesh_vert_adr_to]
mesh_face_adr_from = self.model.mesh_faceadr[self.dataid] mesh_face_adr_to = ( self.model.mesh_faceadr[self.dataid + 1] if self.dataid < self.model.nmesh - 1 else len(self.model.mesh_face) ) mesh_face = self.model.mesh_face[mesh_face_adr_from:mesh_face_adr_to]
mesh_facenum = self.model.mesh_facenum[self.dataid]
return mesh_vert, mesh_face, mesh_facenum
def _attach_material(self): mtl_path = Sdf.Path(f"/World/_materials/Material_{self.obj_name}") mtl = UsdShade.Material.Define(self.stage, mtl_path)
if self.texture_file: bsdf_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Principled_BSDF")) image_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Image_Texture")) uvmap_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("uvmap"))
# setting the bsdf shader attributes bsdf_shader.CreateIdAttr("UsdPreviewSurface") bsdf_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource( image_shader.ConnectableAPI(), "rgb" ) bsdf_shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(float(self.rgba[-1])) bsdf_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(self.geom.shininess) bsdf_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( 1.0 - self.geom.shininess )
mtl.CreateSurfaceOutput().ConnectToSource(bsdf_shader.ConnectableAPI(), "surface")
self.usd_mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(self.usd_mesh).Bind(mtl)
# setting the image texture attributes image_shader.CreateIdAttr("UsdUVTexture") image_shader.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.texture_file) image_shader.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set("sRGB") image_shader.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") image_shader.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") image_shader.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource( uvmap_shader.ConnectableAPI(), "result" ) image_shader.CreateOutput("rgb", Sdf.ValueTypeNames.Float3)
# setting uvmap shader attributes uvmap_shader.CreateIdAttr("UsdPrimvarReader_float2") uvmap_shader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set("UVMap") uvmap_shader.CreateOutput("results", Sdf.ValueTypeNames.Float2) else: bsdf_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Principled_BSDF"))
# settings the bsdf shader attributes bsdf_shader.CreateIdAttr("UsdPreviewSurface")
bsdf_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set( tuple(self.rgba[0:3]) ) bsdf_shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(float(self.rgba[-1])) bsdf_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(self.geom.shininess) bsdf_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( 1.0 - self.geom.shininess )
mtl.CreateSurfaceOutput().ConnectToSource(bsdf_shader.ConnectableAPI(), "surface")
self.usd_mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(self.usd_mesh).Bind(mtl)
def update(self, pos: np.ndarray, mat: np.ndarray, visible: bool, frame: int): transformation_mat = utils_component.create_transform_matrix( rotation_matrix=mat, translation_vector=pos ).T self.transform_op.Set(Gf.Matrix4d(transformation_mat.tolist()), frame) self.update_visibility(visible, frame)
def update_visibility(self, visible: bool, frame: int): if visible: self.usd_prim.GetAttribute("visibility").Set("inherited", frame) else: self.usd_prim.GetAttribute("visibility").Set("invisible", frame)
class USDPrimitiveMesh: def __init__( self, mesh_config: List[dict], stage: Usd.Stage, geom: mujoco.MjvGeom, obj_name: str, rgba: np.ndarray = np.array([1, 1, 1, 1]), texture_file: Optional[str] = None, ): self.mesh_config = mesh_config self.stage = stage self.geom = geom self.obj_name = obj_name self.rgba = rgba self.texture_file = texture_file
self.usd_prim = Usd.Prim() self.usd_mesh = UsdGeom.Mesh() self.prim_mesh = None self.transform_op = Gf.Matrix4d(1.0)
_, self.prim_mesh = shapes_component.mesh_generator(mesh_config)
xform_path = f"/World/{self.obj_name}_Xform" mesh_path = f"{xform_path}/{obj_name}" self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) self.usd_mesh = UsdGeom.Mesh.Define(stage, mesh_path) self.usd_prim = stage.GetPrimAtPath(mesh_path)
self.prim_mesh.translate(-self.prim_mesh.get_center())
mesh_vert, mesh_face, mesh_facenum = self._get_mesh_geometry() self.usd_mesh.GetPointsAttr().Set(mesh_vert) self.usd_mesh.GetFaceVertexCountsAttr().Set([3 for _ in range(mesh_facenum)]) self.usd_mesh.GetFaceVertexIndicesAttr().Set(mesh_face)
# setting mesh uv properties mesh_texcoord, mesh_facetexcoord = self._get_uv_geometry() self.texcoords = UsdGeom.PrimvarsAPI(self.usd_mesh).CreatePrimvar( "UVMap", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying )
self.texcoords.Set(mesh_texcoord) self.texcoords.SetIndices(Vt.IntArray([i for i in range(mesh_facenum * 3)]))
self._set_refinement_properties()
# setting attributes for the shape self._attach_material()
# defining ops required by update function self.transform_op = self.usd_xform.AddTransformOp()
def _set_refinement_properties(self): self.usd_prim.GetAttribute("subdivisionScheme").Set("none")
def _get_uv_geometry(self):
assert self.prim_mesh
x_scale, y_scale = self.geom.texrepeat
mesh_texcoord = np.array(self.prim_mesh.triangle_uvs) mesh_facetexcoord = np.asarray(self.prim_mesh.triangles)
x_multiplier, y_multiplier = 1, 1 if self.geom.texuniform: x_multiplier, y_multiplier = self.geom.size[:2]
mesh_texcoord[:, 0] *= x_scale * x_multiplier mesh_texcoord[:, 1] *= y_scale * y_multiplier
return mesh_texcoord, mesh_facetexcoord.flatten()
def _get_mesh_geometry(self):
assert self.prim_mesh
# get mesh geometry from the open3d mesh model mesh_vert = np.asarray(self.prim_mesh.vertices) mesh_face = np.asarray(self.prim_mesh.triangles)
return mesh_vert, mesh_face, len(mesh_face)
def _attach_material(self): mtl_path = Sdf.Path(f"/World/_materials/Material_{self.obj_name}") mtl = UsdShade.Material.Define(self.stage, mtl_path) if self.texture_file: bsdf_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Principled_BSDF")) image_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Image_Texture")) uvmap_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("uvmap"))
# setting the bsdf shader attributes bsdf_shader.CreateIdAttr("UsdPreviewSurface") bsdf_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource( image_shader.ConnectableAPI(), "rgb" ) bsdf_shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(float(self.rgba[-1])) bsdf_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(self.geom.shininess) bsdf_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( 1.0 - self.geom.shininess )
mtl.CreateSurfaceOutput().ConnectToSource(bsdf_shader.ConnectableAPI(), "surface")
self.usd_mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(self.usd_mesh).Bind(mtl)
# setting the image texture attributes image_shader.CreateIdAttr("UsdUVTexture") image_shader.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.texture_file) image_shader.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set("sRGB") image_shader.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") image_shader.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") image_shader.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource( uvmap_shader.ConnectableAPI(), "result" ) image_shader.CreateOutput("rgb", Sdf.ValueTypeNames.Float3)
# setting uvmap shader attributes uvmap_shader.CreateIdAttr("UsdPrimvarReader_float2") uvmap_shader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set("UVMap") uvmap_shader.CreateOutput("results", Sdf.ValueTypeNames.Float2) else: bsdf_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Principled_BSDF"))
# settings the bsdf shader attributes bsdf_shader.CreateIdAttr("UsdPreviewSurface") bsdf_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set( tuple(self.rgba[:3]) ) bsdf_shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(float(self.rgba[-1])) bsdf_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(self.geom.shininess) bsdf_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( 1.0 - self.geom.shininess )
mtl.CreateSurfaceOutput().ConnectToSource(bsdf_shader.ConnectableAPI(), "surface")
self.usd_mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(self.usd_mesh).Bind(mtl)
def update(self, pos: np.ndarray, mat: np.ndarray, visible: bool, frame: int): transformation_mat = utils_component.create_transform_matrix( rotation_matrix=mat, translation_vector=pos ).T self.transform_op.Set(Gf.Matrix4d(transformation_mat.tolist()), frame) self.update_visibility(visible, frame)
def update_visibility(self, visible: bool, frame: int): if visible: self.usd_prim.GetAttribute("visibility").Set("inherited", frame) else: self.usd_prim.GetAttribute("visibility").Set("invisible", frame)
class USDSphereLight: def __init__(self, stage: Usd.Stage, obj_name: str, radius: Optional[float] = 0.3): self.stage = stage
xform_path = f"/World/Light_Xform_{obj_name}" light_path = f"{xform_path}/Light_{obj_name}" self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) self.usd_light = UsdLux.SphereLight.Define(stage, light_path) self.usd_prim = stage.GetPrimAtPath(light_path)
# we assume in mujoco that all lights are point lights self.usd_light.GetRadiusAttr().Set(radius) self.usd_light.GetTreatAsPointAttr().Set(False) self.usd_light.GetNormalizeAttr().Set(True)
# defining ops required by update function self.translate_op = self.usd_xform.AddTranslateOp()
def update(self, pos: np.ndarray, intensity: int, color: np.ndarray, frame: int): self.translate_op.Set(Gf.Vec3d(pos.tolist()), frame)
if not np.any(pos): intensity = 0
self.usd_light.GetIntensityAttr().Set(intensity) self.usd_light.GetColorAttr().Set(Gf.Vec3d(color.tolist()))
class USDDomeLight: def __init__(self, stage: Usd.Stage, obj_name: str): self.stage = stage
xform_path = f"/World/Light_Xform_{obj_name}" light_path = f"{xform_path}/Light_{obj_name}" self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) self.usd_light = UsdLux.DomeLight.Define(stage, light_path) self.usd_prim = stage.GetPrimAtPath(light_path)
# we assume in mujoco that all lights are point lights self.usd_light.GetNormalizeAttr().Set(True)
def update(self, intensity: int, color: np.ndarray, frame: int): self.usd_light.GetIntensityAttr().Set(intensity) self.usd_light.GetExposureAttr().Set(0.0) self.usd_light.GetColorAttr().Set(Gf.Vec3d(color.tolist()))
class USDCamera: def __init__(self, stage: Usd.Stage, obj_name: str): self.stage = stage
xform_path = f"/World/Camera_Xform_{obj_name}" camera_path = f"{xform_path}/Camera_{obj_name}" self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) self.usd_camera = UsdGeom.Camera.Define(stage, camera_path) self.usd_prim = stage.GetPrimAtPath(camera_path)
# defining ops required by update function self.transform_op = self.usd_xform.AddTransformOp()
# self.usd_camera.CreateFocalLengthAttr().Set(18.14756) # default in omniverse self.usd_camera.CreateFocalLengthAttr().Set(12) self.usd_camera.CreateFocusDistanceAttr().Set(400)
self.usd_camera.GetHorizontalApertureAttr().Set(12)
self.usd_camera.GetClippingRangeAttr().Set(Gf.Vec2f(1e-4, 1e6))
def update(self, cam_pos: np.ndarray, cam_mat: np.ndarray, frame: int):
transformation_mat = utils_component.create_transform_matrix( rotation_matrix=cam_mat, translation_vector=cam_pos ).T self.transform_op.Set(Gf.Matrix4d(transformation_mat.tolist()), frame)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import argparsefrom pathlib import Path
import mujocofrom tqdm import tqdm
from robocasa.utils.usd import exporter
def generate_usd_trajectory(args):
# load a model to mujoco model_path = args.model_path m = mujoco.MjModel.from_xml_path(model_path) d = mujoco.MjData(m)
# create an instance of the USDExporter exp = exporter.USDExporter( model=m, output_directory_name=Path(args.model_path).stem, output_directory_root=args.output_directory_root, camera_names=args.camera_names, )
# step through the model for length steps for i in tqdm(range(args.length)): mujoco.mj_step(m, d) exp.update_scene(d)
exp.save_scene(filetype=args.export_extension)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--model_path", type=str, required=True, help="path to mjcf xml model")
parser.add_argument("--length", type=int, default=100, help="length of trajectory to render")
parser.add_argument( "--output_directory_root", type=str, default="../usd_trajectories/", help="location where to create usd files", )
parser.add_argument("--camera_names", type=str, nargs="+", help="cameras to include in usd")
parser.add_argument( "--export_extension", type=str, default="usd", help="extension of exported file (can be usd, usda, or usdc)", )
args = parser.parse_args() generate_usd_trajectory(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403# Copyright 2024 DeepMind Technologies Limited## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ==============================================================================import osfrom typing import List, Optional, Tuple, Union
import mujocoimport numpy as npimport scipyimport termcolorimport tqdmfrom PIL import Image as imfrom PIL import ImageOps
# TODO: b/288149332 - Remove once USD Python Binding works well with pytype.# pytype: disable=module-attrfrom pxr import Sdf, Usd, UsdGeom
import robocasa.utils.usd.component as component_moduleimport robocasa.utils.usd.shapes as shapes_module
class USDExporter: def __init__( self, model: mujoco.MjModel, height: int = 480, width: int = 480, max_geom: int = 10000, output_directory_name: str = "mujoco_usdpkg", output_directory_root: str = "./", light_intensity: int = 10000, camera_names: Optional[List[str]] = None, specialized_materials_file: Optional[str] = None, verbose: bool = True, ): """Initializes a new USD Exporter
Args: model: an MjModel instance. height: image height in pixels. width: image width in pixels. max_geom: Optional integer specifying the maximum number of geoms that can be rendered in the same scene. If None this will be chosen automatically based on the estimated maximum number of renderable geoms in the model. output_directory_name: name of root directory to store outputted frames and assets generated by the USD renderer. output_directory_root: path to root directory storing generated frames and assets by the USD renderer. verbose: decides whether to print updates. """
buffer_width = model.vis.global_.offwidth buffer_height = model.vis.global_.offheight
if width > buffer_width: raise ValueError( f""" Image width {width} > framebuffer width {buffer_width}. Either reduce the image width or specify a larger offscreen framebuffer in the model XML using the clause: <visual> <global offwidth="my_width"/> </visual>""".lstrip() )
if height > buffer_height: raise ValueError( f""" Image height {height} > framebuffer height {buffer_height}. Either reduce the image height or specify a larger offscreen framebuffer in the model XML using the clause: <visual> <global offheight="my_height"/> </visual>""".lstrip() )
self.model = model self.height = height self.width = width self.max_geom = max_geom self.output_directory_name = output_directory_name self.output_directory_root = output_directory_root self.light_intensity = light_intensity self.camera_names = camera_names self.specialized_materials_file = specialized_materials_file self.verbose = verbose
self.frame_count = 0 # maintains how many times we have saved the scene self.updates = 0
self.geom_name2usd = {}
# initializing rendering requirements self.renderer = mujoco.Renderer(model, height, width, max_geom) self._initialize_usd_stage() self._scene_option = mujoco.MjvOption() # using default scene option
# initializing output_directories self._initialize_output_directories()
# loading required textures for the scene self._load_textures()
@property def usd(self): return self.stage.GetRootLayer().ExportToString()
@property def scene(self): return self.renderer.scene
def _initialize_usd_stage(self): self.stage = Usd.Stage.CreateInMemory() UsdGeom.SetStageUpAxis(self.stage, UsdGeom.Tokens.z) self.stage.SetStartTimeCode(0) # add as user input self.stage.SetTimeCodesPerSecond(60.0)
default_prim = UsdGeom.Xform.Define(self.stage, Sdf.Path("/World")).GetPrim() self.stage.SetDefaultPrim(default_prim)
def _initialize_output_directories(self): self.output_directory_path = os.path.join( self.output_directory_root, self.output_directory_name ) if not os.path.exists(self.output_directory_path): os.makedirs(self.output_directory_path)
self.frames_directory = os.path.join(self.output_directory_path, "frames") if not os.path.exists(self.frames_directory): os.makedirs(self.frames_directory)
self.assets_directory = os.path.join(self.output_directory_path, "assets") if not os.path.exists(self.assets_directory): os.makedirs(self.assets_directory)
if self.verbose: print( termcolor.colored( "Writing output frames and assets to" f" {self.output_directory_path}", "green", ) )
def update_scene( self, data: mujoco.MjData, scene_option: Optional[mujoco.MjvOption] = None, ): """Updates the scene with latest sim data
Args: data: structure storing current simulation state scene_option: we use this to determine which geom groups to activate """
self.frame_count += 1
scene_option = scene_option or self._scene_option
# update the mujoco renderer self.renderer.update_scene(data, scene_option=scene_option)
# TODO: update scene options if self.updates == 0: self._initialize_usd_stage()
self._load_lights() self._load_cameras()
self._update_geoms() self._update_lights() self._update_cameras(data, scene_option=scene_option)
self.updates += 1
def _load_textures(self): # TODO: remove code once added internally to mujoco data_adr = 0 self.texture_files = [] for texture_id in tqdm.tqdm(range(self.model.ntex)): texture_height = self.model.tex_height[texture_id] texture_width = self.model.tex_width[texture_id] pixels = 3 * texture_height * texture_width img = im.fromarray( self.model.tex_rgb[data_adr : data_adr + pixels].reshape( texture_height, texture_width, 3 ) ) img = ImageOps.flip(img)
texture_file_name = f"texture_{texture_id}.png"
img.save(os.path.join(self.assets_directory, texture_file_name))
relative_path = os.path.relpath(self.assets_directory, self.frames_directory) img_path = os.path.join( relative_path, texture_file_name ) # relative path, TODO: switch back to this
self.texture_files.append(img_path)
data_adr += pixels
if self.verbose: print( termcolor.colored( f"Completed writing {self.model.ntex} textures to" f" {self.assets_directory}", "green", ) )
def _load_geom(self, geom: mujoco.MjvGeom):
geom_name = self._get_geom_name(geom.objtype, geom.objid)
assert geom_name not in self.geom_name2usd
texture_file = self.texture_files[geom.texid] if geom.texid != -1 else None
if geom.type == mujoco.mjtGeom.mjGEOM_MESH: usd_geom = component_module.USDMesh( stage=self.stage, model=self.model, geom=geom, obj_name=geom_name, dataid=self.model.geom_dataid[geom.objid], rgba=geom.rgba, texture_file=texture_file, ) else: mesh_config = shapes_module.mesh_config_generator( name=geom_name, geom_type=geom.type, size=geom.size ) usd_geom = component_module.USDPrimitiveMesh( mesh_config=mesh_config, stage=self.stage, geom=geom, obj_name=geom_name, rgba=geom.rgba, texture_file=texture_file, )
self.geom_name2usd[geom_name] = usd_geom
def _update_geoms(self):
geom_names = set(self.geom_name2usd.keys())
for i in range(self.scene.ngeom): geom = self.scene.geoms[i] geom_name = mujoco.mj_id2name(self.model, geom.objtype, geom.objid) if not geom_name: geom_name = "None" geom_name += f"_{geom.objid}"
# iterate through all geoms in the scene and makes update for i in range(self.scene.ngeom): geom = self.scene.geoms[i] geom_name = self._get_geom_name(geom.objtype, geom.objid)
if geom_name not in self.geom_name2usd: self._load_geom(geom) if self.geom_name2usd[geom_name]: self.geom_name2usd[geom_name].update_visibility(False, 0)
if self.geom_name2usd[geom_name]: self.geom_name2usd[geom_name].update( pos=geom.pos, mat=geom.mat, visible=geom.rgba[3] > 0, frame=self.updates, ) if geom_name in geom_names: geom_names.remove(geom_name)
for geom_name in geom_names: if self.geom_name2usd[geom_name]: self.geom_name2usd[geom_name].update_visibility(False, self.updates)
def _load_lights(self): # initializes an usd light object for every light in the scene self.usd_lights = [] for i in range(self.scene.nlight): light = self.scene.lights[i] if not np.allclose(light.pos, [0, 0, 0]): self.usd_lights.append (component_module.USDSphereLight(stage=self.stage, obj_name=str(i))) else: self.usd_lights.append(None)
def _update_lights(self): for i in range(self.scene.nlight): light = self.scene.lights[i]
if np.allclose(light.pos, [0, 0, 0]): continue
if i >= len(self.usd_lights) or self.usd_lights[i] is None: continue
self.usd_lights[i].update( pos=light.pos, intensity=self.light_intensity, color=light.diffuse, frame=self.updates, )
def _load_cameras(self): self.usd_cameras = [] if self.camera_names is not None: for name in self.camera_names: self.usd_cameras.append(component_module.USDCamera(stage=self.stage, obj_name=name))
def _update_cameras( self, data: mujoco.MjData, scene_option: Optional[mujoco.MjvOption] = None, ): for i in range(len(self.usd_cameras)):
camera = self.usd_cameras[i] camera_name = self.camera_names[i]
self.renderer.update_scene(data, scene_option=scene_option, camera=camera_name)
avg_camera = mujoco.mjv_averageCamera(self.scene.camera[0], self.scene.camera[1])
forward = avg_camera.forward up = avg_camera.up right = np.cross(forward, up)
R = np.eye(3) R[:, 0] = right R[:, 1] = up R[:, 2] = -forward
camera.update(cam_pos=avg_camera.pos, cam_mat=R, frame=self.updates)
def add_light( self, pos: List[float], intensity: int, objid: int, radius: Optional[float] = 1.0, color: Optional[np.ndarray] = np.array([0.3, 0.3, 0.3]), obj_name: Optional[str] = "light_1", light_type: Optional[str] = "sphere", ):
if light_type == "sphere": new_light = component_module.USDSphereLight( stage=self.stage, obj_name=str(objid), radius=radius )
new_light.update(pos=np.array(pos), intensity=intensity, color=color, frame=0) elif light_type == "dome": new_light = component_module.USDDomeLight(stage=self.stage, obj_name=str(objid))
new_light.update(intensity=intensity, color=color, frame=0)
def add_camera( self, pos: List[float], rotation_xyz: List[float], objid: int, obj_name: Optional[str] = "camera_1", ): new_camera = component_module.USDCamera(stage=self.stage, obj_name=str(objid))
r = scipy.spatial.transform.Rotation.from_euler("xyz", rotation_xyz, degrees=True) new_camera.update(cam_pos=np.array(pos), cam_mat=r.as_matrix(), frame=0)
def save_scene(self, filetype: str = "usd"): assert filetype in ["usd", "usda", "usdc"] self.stage.SetEndTimeCode(self.frame_count) self.stage.Export( f"{self.output_directory_root}/{self.output_directory_name}/frames/frame_{self.frame_count}_.{filetype}" ) if self.verbose: print( termcolor.colored(f"Completed writing frame_{self.frame_count}.{filetype}", "green") )
def _get_geom_name(self, objtype, objid): geom_name = mujoco.mj_id2name(self.model, objtype, objid) if not geom_name: geom_name = "None" geom_name += f"_{objid}" return geom_name1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# Copyright 2024 DeepMind Technologies Limited## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# =============================================================================="""Tests for the MuJoCo USD Exporter."""
import loggingimport os
import mujocofrom absl.testing import absltestfrom etils import epath
# Open3D and USD are not fully supported on all MuJoCo architectures.# pylint: disable=python.style(g-import-not-at-top)execute_test = Truetry: from pxr import Usd
from robocasa.utils.usd import exporter as exporter_moduleexcept ImportError: logging.warning("Skipping test due to missing import") execute_test = False# pylint: enable=python.style(g-import-not-at-top)
class ExporterTest(absltest.TestCase): def test_usd_export(self): if not execute_test: return
output_dir = os.getenv("TEST_UNDECLARED_OUTPUTS_DIR") xml = """<mujoco> <worldbody> <camera name="closeup" pos="0 -6 0" xyaxes="1 0 0 0 1 100"/> <geom name="white_box" type="box" size="1 1 1" rgba="1 1 1 1"/> </worldbody></mujoco>""" model = mujoco.MjModel.from_xml_string(xml) data = mujoco.MjData(model) exporter = exporter_module.USDExporter( model, output_directory_name="mujoco_usdpkg", output_directory_root=output_dir, ) exporter.update_scene(data) exporter.save_scene("export.usda")
with open( os.path.join(output_dir, "mujoco_usdpkg/frames", "frame_1_.export.usda"), "r", ) as f: golden_path = os.path.join(epath.resource_path("mujoco"), "testdata", "usd_golden.usda") with open(golden_path, "r") as golden_file: self.assertEqual(f.read(), golden_file.read())
if __name__ == "__main__": absltest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138import copyimport pprint
import mujocoimport numpy as npimport open3d as o3d
def create_hemisphere( radius: float, resolution: int = 20, theta_steps: int = 50, phi_steps: int = 50):
points = [] for i in range(phi_steps + 1): phi = np.pi / 2 * i / phi_steps for j in range(theta_steps + 1): theta = 2 * np.pi * j / theta_steps x = radius * np.sin(phi) * np.cos(theta) y = radius * np.sin(phi) * np.sin(theta) z = radius * np.cos(phi) points.append([x, y, z])
pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(points)
mesh = pcd.compute_convex_hull()[0]
return mesh
def mesh_config_generator(name: str, geom_type: mujoco.mjtGeom, size: np.ndarray):
if geom_type == mujoco.mjtGeom.mjGEOM_PLANE: return { "name": name, "box": { "width": size[0] * 2 if size[0] > 0 else 100, "height": size[1] * 2 if size[1] > 0 else 100, "depth": 0.001, "map_texture_to_each_face": True, }, } elif geom_type == mujoco.mjtGeom.mjGEOM_SPHERE: return {"name": name, "sphere": {"radius": float(size[0])}} elif geom_type == mujoco.mjtGeom.mjGEOM_CAPSULE: cylinder = mesh_config_generator(name, mujoco.mjtGeom.mjGEOM_CYLINDER, size) return { "name": name, "cylinder": cylinder["cylinder"], "left_hemisphere": { "radius": size[0], "transform": {"translate": (0, 0, -size[2]), "rotate": (np.pi, 0, 0)}, }, "right_hemisphere": { "radius": size[0], "transform": {"translate": (0, 0, size[2])}, }, } elif geom_type == mujoco.mjtGeom.mjGEOM_ELLIPSOID: sphere = mesh_config_generator(name, mujoco.mjtGeom.mjGEOM_SPHERE, [1.0]) sphere["sphere"]["transform"] = {"scale": tuple(size)} return { "name": name, "sphere": sphere["sphere"], } elif geom_type == mujoco.mjtGeom.mjGEOM_CYLINDER: return { "name": name, "cylinder": { "radius": size[0], "height": size[2] * 2, }, } elif geom_type == mujoco.mjtGeom.mjGEOM_BOX: return { "name": name, "box": { "width": size[0] * 2, "height": size[1] * 2, "depth": size[2] * 2, }, } else: raise NotImplemented( f"{geom_type} primitive geom type not implemented with USD integration" )
def mesh_generator(mesh_config: dict):
assert "name" in mesh_config
mesh = None
for shape, config in mesh_config.items():
if shape == "name": continue
if "box" in shape: prim_mesh = o3d.geometry.TriangleMesh.create_box( width=mesh_config[shape]["width"], height=mesh_config[shape]["height"], depth=mesh_config[shape]["depth"], create_uv_map=True, map_texture_to_each_face=True, ) elif "hemisphere" in shape: prim_mesh = create_hemisphere(radius=mesh_config[shape]["radius"]) elif "sphere" in shape: prim_mesh = o3d.geometry.TriangleMesh.create_sphere( radius=mesh_config[shape]["radius"], create_uv_map=True ) elif "cylinder" in shape: prim_mesh = o3d.geometry.TriangleMesh.create_cylinder( radius=mesh_config[shape]["radius"], height=mesh_config[shape]["height"], create_uv_map=True, )
if "transform" in config:
if "rotate" in config["transform"]: R = mesh.get_rotation_matrix_from_xyz(config["transform"]["rotate"]) prim_mesh.rotate(R, center=(0, 0, 0)) if "scale" in config["transform"]: prim_mesh.vertices = o3d.utility.Vector3dVector( np.asarray(prim_mesh.vertices) * np.array(config["transform"]["scale"]) ) if "translate" in config["transform"]: prim_mesh.translate(config["transform"]["translate"])
if not mesh: mesh = prim_mesh else: mesh += prim_mesh
return mesh_config["name"], mesh123456789101112131415161718192021222324252627# Copyright 2024 DeepMind Technologies Limited## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ==============================================================================import numpy as np
def create_transform_matrix(rotation_matrix, translation_vector): # Ensure rotation_matrix and translation_vector are NumPy arrays rotation_matrix = np.array(rotation_matrix) translation_vector = np.array(translation_vector)
transform_matrix = np.eye(4) transform_matrix[:3, :3] = rotation_matrix transform_matrix[:3, 3] = translation_vector
return transform_matrix12345678910111213141516171819202122232425262728293031from dataclasses import dataclass
import numpy as np
from robocasa.models.objects.objects import MJCFObject
@dataclass(frozen=True)class Gradient: rgba_a: np.ndarray = np.array([0, 0, 0, 1]) rgba_b: np.ndarray = np.array([1, 1, 1, 1])
def sample_linear(self, t: float) -> np.ndarray: return (1 - t) * self.rgba_a + t * self.rgba_b
def sample_per_channel(self, t: tuple[float, float, float, float]): return [np.interp(t[i], [0, 1], [self.rgba_a[i], self.rgba_b[i]]) for i in range(4)]
def randomize_materials_rgba( rng: np.random.Generator, mjcf_obj: MJCFObject, gradient: Gradient, linear: bool): for asset in mjcf_obj.asset: if asset.tag == "material": if linear: t = rng.uniform(0, 1) rgba = gradient.sample_linear(t) else: t = rng.uniform(low=[0, 0, 0, 1], high=[1, 1, 1, 1]).tolist() rgba = gradient.sample_per_channel(t) asset.set("rgba", f"{rgba[0]:.3f} {rgba[1]:.3f} {rgba[2]:.3f} {rgba[3]:.3f}")1from robocasa.wrappers.ik_wrapper import IKWrapper123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226import xml.etree.ElementTree as ETfrom copy import deepcopy
import numpy as np
from robocasa.models.grippers import G1ThreeFingerLeftHand, G1ThreeFingerRightHandfrom robosuite.examples.third_party_controller.mink_controller import IKSolverMinkfrom robosuite.models.grippers import InspireLeftHand, InspireRightHandfrom robosuite.models.grippers import FourierLeftHand, FourierRightHandfrom robosuite.utils.mjcf_utils import new_body, new_geom, new_sitefrom robosuite.wrappers import VisualizationWrapperimport robosuite.utils.transform_utils as T
class IKWrapper(VisualizationWrapper): def __init__(self, env, indicator_configs=None, ik_indicator=False): self.ik_indicator = ik_indicator if ik_indicator: indicator_configs = [] for i in range(2): indicator_configs.append( { "name": f"indicator_x_{i}", "type": "capsule", "pos": [0.012, 0, 0], "size": [0.003, 0.012], "rgba": [1, 0.5, 0.5, 0.8], "quat": [0, 0.7071, 0, 0.7071], } ) indicator_configs.append( { "name": f"indicator_y_{i}", "type": "capsule", "pos": [0, 0.012, 0], "size": [0.003, 0.012], "rgba": [0.5, 1, 0.5, 0.8], "quat": [0, 0, 0.7071, 0.7071], } ) indicator_configs.append( { "name": f"indicator_z_{i}", "type": "capsule", "pos": [0, 0, 0.012], "size": [0.003, 0.012], "rgba": [0.5, 0.5, 1, 0.8], } ) super().__init__(env, indicator_configs=indicator_configs) else: # Fall back to VisualizationWrapper super().__init__env, indicator_configs()
def step(self, action): if self.ik_indicator: composite_controller = self.robots[0].composite_controller if composite_controller.name == "BASIC": # indicators will be set by calling `set_target_poses_outside_env` pass elif composite_controller.name in [ "WHOLE_BODY_MINK_IK", "WHOLE_BODY_EXTERNAL_IK", "HYBRID_WHOLE_BODY_MINK_IK", ]: assert composite_controller.joint_action_policy.input_ref_frame == "base" input_action = action[: composite_controller.joint_action_policy.control_dim] input_action = input_action.reshape( len(composite_controller.joint_action_policy.site_names), -1 ) input_pos = input_action[:, :3] input_ori = input_action[:, 3:] input_quat_wxyz = np.array( [np.roll(T.axisangle2quat(input_ori[i]), 1) for i in range(len(input_ori))] ) base_pos = self.sim.data.body_xpos[self.sim.model.body_name2id("robot0_base")] base_ori = self.sim.data.body_xmat[ self.sim.model.body_name2id("robot0_base") ].reshape(3, 3) base_pose = T.make_pose(base_pos, base_ori) for _, name in enumerate(self.get_indicator_names()): # indicators for x,y,z-axis share the same pose i = int(name.split("_")[-1]) input_pose = T.make_pose( input_pos[i], T.quat2mat(np.roll(input_quat_wxyz[i], -1)) ) target_pose = np.dot(base_pose, input_pose) self.set_indicator_pos(name, target_pose[:3, 3]) self.set_indicator_ori(name, target_pose[:3, :3]) else: assert ( False ), f"Unsupported composite controller {composite_controller.name} for IKWrapper"
ret = super().step(action)
return ret
def set_target_poses_outside_env(self, input_poses): if self.env.robots[0].robot_model.default_base in ["NullBase", "NoActuationBase"]: base_name = "robot0_base" elif self.env.robots[0].robot_model.default_base == "FloatingLeggedBase": base_name = "mobilebase0_support" else: assert False, f"Unsupported base type: {self.env.robots[0].robot_model.default_base}" base_id = self.sim.model.body_name2id(base_name) base_pos = self.sim.data.body_xpos[base_id] base_ori = self.sim.data.body_xmat[base_id].reshape(3, 3) base_pose = T.make_pose(base_pos, base_ori) for _, name in enumerate(self.get_indicator_names()): i = int(name.split("_")[-1]) input_pose = input_poses[i].copy() input_pose[3, 3] = 1 target_pose = np.dot(base_pose, input_pose) self.set_indicator_pos(name, target_pose[:3, 3]) self.set_indicator_ori(name, target_pose[:3, :3])
# TODO: this will fix the duplicated body issue in the public robosuite repo def _add_indicators_to_model(self, xml): """ Adds indicators to the mujoco simulation model
Args: xml (string): MJCF model in xml format, for the current simulation to be loaded """ if self.indicator_configs is not None: root = ET.fromstring(xml) worldbody = root.find("worldbody")
from robosuite.utils.mjcf_utils import ( find_elements, find_parent, new_element, )
for arm in ["right", "left"]: gripper = self.env.robots[0].gripper[arm] if ( not isinstance(gripper, InspireLeftHand) and not isinstance(gripper, InspireRightHand) and not isinstance(gripper, FourierLeftHand) and not isinstance(gripper, FourierRightHand) and not isinstance(gripper, G1ThreeFingerLeftHand) and not isinstance(gripper, G1ThreeFingerRightHand) ): continue
eef = find_elements( root=worldbody, tags="body", attribs={"name": f"gripper0_{arm}_eef"}, return_first=True, ) mount = find_parent(worldbody, eef) for i in range(4): elem = find_elements( root=worldbody, tags="site", attribs={"name": f"robot0_{arm}_pinch_spheres_{i}"}, return_first=True, ) if elem is not None: continue if ( isinstance(gripper, InspireLeftHand) or isinstance(gripper, InspireRightHand) or isinstance(gripper, FourierLeftHand) or isinstance(gripper, FourierRightHand) ): mount.append( new_element( tag="site", name=f"robot0_{arm}_pinch_spheres_{i}", pos=f"-0.09 -0.10 {-0.03 + i * 0.02}", size="0.01 0.01 0.01", rgba="1 0.5 0.5 1", type="sphere", group="1", ) ) else: if arm == "right": mount.append( new_element( tag="site", name=f"robot0_{arm}_pinch_spheres_{i}", pos=f"0.15 0.05 {-0.03 + i * 0.02}", size="0.01 0.01 0.01", rgba="1 0.5 0.5 1", type="sphere", group="1", ) ) else: mount.append( new_element( tag="site", name=f"robot0_{arm}_pinch_spheres_{i}", pos=f"0.15 -0.05 {-0.03 + i * 0.02}", size="0.01 0.01 0.01", rgba="1 0.5 0.5 1", type="sphere", group="1", ) )
for indicator_config in self.indicator_configs: config = deepcopy(indicator_config)
from robosuite.utils.mjcf_utils import find_elements
body = find_elements( root=worldbody, tags="body", attribs={"name": config["name"] + "_body"}, ) if body is not None: continue
indicator_body = new_body(name=config["name"] + "_body") indicator_body.append(new_site(**config)) worldbody.append(indicator_body)
xml = ET.tostring(root, encoding="utf8").decode("utf8")
return xml1234567891011121314151617181920212223242526272829from setuptools import find_packages, setup
setup( name="robocasa", packages=[package for package in find_packages() if package.startswith("robocasa")], install_requires=[ "numpy==1.26.4", "numba==0.61.0", "scipy>=1.2.3", "mujoco==3.2.6", "pygame", "Pillow", "opencv-python", "pyyaml", "pynput", "tqdm", "termcolor", "imageio", "h5py", "lxml", "hidapi", ], eager_resources=["*"], include_package_data=True, python_requires=">=3", description="Gr00t RoboCasa for loco-manipulation", version="0.2.0",)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163# ~/.bashrc: executed by bash(1) for non-login shells.# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)# for examples
# If not running interactively, don't do anythingcase $- in *i*) ;; *) return;;esac
# don't put duplicate lines or lines starting with space in the history.# See bash(1) for more optionsHISTCONTROL=ignoreboth
# append to the history file, don't overwrite itshopt -s histappend
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)HISTSIZE=1000HISTFILESIZE=2000
# check the window size after each command and, if necessary,# update the values of LINES and COLUMNS.shopt -s checkwinsize
# If set, the pattern "**" used in a pathname expansion context will# match all files and zero or more directories and subdirectories.#shopt -s globstar
# make less more friendly for non-text input files, see lesspipe(1)[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then debian_chroot=$(cat /etc/debian_chroot)fi
# set a fancy prompt (non-color, unless we know we "want" color)case "$TERM" in xterm-color|*-256color) color_prompt=yes;;esac
# uncomment for a colored prompt, if the terminal has the capability; turned# off by default to not distract the user: the focus in a terminal window# should be on the output of commands, not on the promptforce_color_prompt=yes
if [ -n "$force_color_prompt" ]; then if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then # We have color support; assume it's compliant with Ecma-48 # (ISO/IEC-6429). (Lack of such support is extremely rare, and such # a case would tend to support setf rather than setaf.) color_prompt=yes else color_prompt= fifi
if [ "$color_prompt" = yes ]; then PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ 'else PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ 'fiunset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dircase "$TERM" inxterm*|rxvt*) PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1" ;;*) ;;esac
# enable color support of ls and also add handy aliasesif [ -x /usr/bin/dircolors ]; then test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" alias ls='ls --color=auto' #alias dir='dir --color=auto' #alias vdir='vdir --color=auto'
alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto'fi
# colored GCC warnings and errorsexport GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
# Set terminal type for color supportexport TERM=xterm-256color
# some more ls aliasesalias ll='ls -alF'alias la='ls -A'alias l='ls -CF'
# Add an "alert" alias for long running commands. Use like so:# sleep 10; alertalias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
# Alias definitions.# You may want to put all your additions into a separate file like# ~/.bash_aliases, instead of adding them here directly.# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then . ~/.bash_aliasesfi
# enable programmable completion features (you don't need to enable# this, if it's already enabled in /etc/bash.bashrc and /etc/profile# sources /etc/bash.bashrc).if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fifi
# useful commandsbind '"\e[A": history-search-backward'bind '"\e[B": history-search-forward'
# Store the last 10 directories in a history fileCD_HISTFILE=~/.cd_historyCD_HISTSIZE=10
cd() { local histfile="${CD_HISTFILE:-$HOME/.cd_history}" local max="${CD_HISTSIZE:-10}"
case "$1" in --) [ -f "$histfile" ] && tac "$histfile" | nl -w2 -s' ' || echo "No directory history yet."; return ;; -[0-9]*) local idx=${1#-} local dir=$(tac "$histfile" 2>/dev/null | sed -n "${idx}p") [ -n "$dir" ] && builtin cd "$dir" || echo "Invalid selection: $1" return ;; esac
builtin cd "$@" || return
[[ $(tail -n1 "$histfile" 2>/dev/null) != "$PWD" ]] && echo "$PWD" >> "$histfile" tail -n "$max" "$histfile" > "${histfile}.tmp" && mv "${histfile}.tmp" "$histfile"}
# Make decoupled_wbc importableexport PYTHONPATH="${DECOUPLED_WBC_DIR}:${PYTHONPATH}"
# Manus to LD_LIBRARY_PATHexport LD_LIBRARY_PATH=$DECOUPLED_WBC_DIR/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/lib:$LD_LIBRARY_PATH
# CUDA supportexport LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:/usr/lib:/lib/x86_64-linux-gnu:/lib64:/lib:$LD_LIBRARY_PATH
# decoupled_wbc aliasesalias dg="python $DECOUPLED_WBC_DIR/decoupled_wbc/scripts/deploy_g1.py"alias rsl="python $DECOUPLED_WBC_DIR/decoupled_wbc/control/main/teleop/run_sim_loop.py"alias rgcl="python $DECOUPLED_WBC_DIR/decoupled_wbc/control/main/teleop/run_g1_control_loop.py"alias rtpl="python $DECOUPLED_WBC_DIR/decoupled_wbc/control/main/teleop/run_teleop_policy_loop.py"alias tgcl="pytest $DECOUPLED_WBC_DIR/decoupled_wbc/tests/control/main/teleop/test_g1_control_loop.py -s"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Enable mouse modeset -g mouse on
# Start window numbering at 0 (default)set -g base-index 0setw -g pane-base-index 0
# Increase scrollback buffer sizeset -g history-limit 50000
# Use Alt-arrow keys without prefix key to switch panesbind -n M-Left select-pane -Lbind -n M-Right select-pane -Rbind -n M-Up select-pane -Ubind -n M-Down select-pane -D
# Use Alt-1,2,3... to switch windowsbind -n M-1 select-window -t 1bind -n M-2 select-window -t 2bind -n M-3 select-window -t 3bind -n M-4 select-window -t 4bind -n M-5 select-window -t 5bind -n M-6 select-window -t 6bind -n M-7 select-window -t 7bind -n M-8 select-window -t 8bind -n M-9 select-window -t 9
# Split panes using Alt-| and Alt--bind -n M-| split-window -hbind -n M-- split-window -v
# Easy config reloadbind -n M-r source-file ~/.tmux.conf \; display-message "Config reloaded!"
# Status bar customizationset -g status-style bg=colour240,fg=colour255set -g status-left "#[fg=colour255,bg=colour240] #S #[fg=colour240,bg=colour238]"set -g status-right "#[fg=colour255,bg=colour240] %H:%M #[fg=colour240,bg=colour238]"
# Window status formatsetw -g window-status-format "#[fg=colour255,bg=colour238] #I:#W "setw -g window-status-current-format "#[fg=colour238,bg=colour255]#[fg=colour238,bg=colour255] #I:#W #[fg=colour255,bg=colour238]"
# Pane border colorsset -g pane-border-style fg=colour240set -g pane-active-border-style fg=colour255
# Message textset -g message-style bg=colour238,fg=colour255
# Clock modesetw -g clock-mode-colour colour255
# Enable focus eventsset -g focus-events on
# Increase escape timeset -sg escape-time 0
# Enable true color supportset -ga terminal-overrides ",*256col*:Tc"
# Set default terminal mode to 256 colorsset -g default-terminal "screen-256color"
# Display a message when a window is createdset -g display-time 4000
# Automatically set window titlesetw -g automatic-rename onset -g set-titles onset -g set-titles-string "#T"
# Enable clipboard integrationset -g @plugin 'tmux-plugins/tmux-yank'
# List of pluginsset -g @plugin 'tmux-plugins/tpm'set -g @plugin 'tmux-plugins/tmux-sensible'set -g @plugin 'tmux-plugins/tmux-resurrect'set -g @plugin 'tmux-plugins/tmux-continuum'
# Initialize TMUX plugin manager (keep this line at the very bottom of tmux.conf)run '~/.tmux/plugins/tpm/tpm' 12345 # HIDAPI/libusb SUBSYSTEMS=="usb", ATTRS{idVendor}=="3325", MODE:="0666"
# HIDAPI/hidraw KERNEL=="hidraw*", ATTRS{idVendor}=="3325", MODE:="0666"third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/__init__.pyAdded+1
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/g1_robot.pyAdded+391
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/__init__.pyAdded+3
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/factory_arena.pyAdded+14
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/ground_arena.pyAdded+13
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/lab_arena.pyAdded+12
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/__init__.pyAdded+1
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/camera_utils.pyAdded+246
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/config_utils.pyAdded+63
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/cotrain_utils.pyAdded+25
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dataset_registry.pyAdded+352
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dexmg_utils.pyAdded+99
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/env_utils.pyAdded+105
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/__init__.pyAdded+4
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/gymnasium_basic.pyAdded+417
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/__init__.pyAdded+3
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/file_utils.pyAdded+35
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/fixture_template.xmlAdded+27
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/install_vhacd.shAdded+21
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/log_utils.pyAdded+46
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_gen_utils.pyAdded+800
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_obj.pyAdded+251
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mtl_utils.pyAdded+198
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_play_env.pyAdded+250
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_template.xmlAdded+15
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/parser_utils.pyAdded+61
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/object_utils.pyAdded+621
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/placement_samplers.pyAdded+711
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/postprocess_xml_utils.pyAdded+78
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/__init__.pyAdded
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/configs.pyAdded+126
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/scene.pyAdded+146
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/success_criteria.pyAdded+157
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/texture_swap.pyAdded+670
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/transform_utils.pyAdded+56
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/README.mdAdded+30
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/__init__.pyAdded+4
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/component.pyAdded+429
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/demo.pyAdded+58
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter.pyAdded+403
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter_test.pyAdded+71
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/shapes.pyAdded+138
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/utils.pyAdded+27
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/visuals_utls.pyAdded+31
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/__init__.pyAdded+1
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/ik_wrapper.pyAdded+226
third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/setup.pyAdded+29
third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.bashrcAdded+163
third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.tmux.confAdded+84
third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/70-manus-hid.rulesAdded+5