diff --git a/.gitattributes b/.gitattributes index 018010d21238474966a97cac788c8ade1e395efc..b696d1d30394fadbfe96a7069ad0087f36df0ddb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -169,3 +169,6 @@ simulation/assets/g1/configuration/g1_29dof_rev_1_0_with_inspire_hand_retarget_i simulation/modules/IsaacLab/source/isaaclab/isaaclab/assets/articulation/__pycache__/base_articulation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text simulation/modules/IsaacLab/source/isaaclab/isaaclab/envs/mdp/__pycache__/events.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text simulation/modules/IsaacLab/source/isaaclab_physx/isaaclab_physx/assets/articulation/__pycache__/articulation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/ClientPlatformSpecific.o filter=lfs diff=lfs merge=lfs -text +third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/Main.o filter=lfs diff=lfs merge=lfs -text +third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/SDKClient.o filter=lfs diff=lfs merge=lfs -text diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand.xml new file mode 100644 index 0000000000000000000000000000000000000000..a53cd991faf3a296bf67acbf78cd702ce15c31d0 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand.xml @@ -0,0 +1,748 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand_rev_1_0_activatedfinger.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand_rev_1_0_activatedfinger.xml new file mode 100644 index 0000000000000000000000000000000000000000..b508fe4cc13dac807c94af2b115c034e88e69b0f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand_rev_1_0_activatedfinger.xml @@ -0,0 +1,669 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --> + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/lift_box_43dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/lift_box_43dof.xml new file mode 100644 index 0000000000000000000000000000000000000000..3ac8a3f5cc0fbf2c34c374cec1448cee00b0ce41 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/lift_box_43dof.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_bottle_43dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_bottle_43dof.xml new file mode 100644 index 0000000000000000000000000000000000000000..cf4d4da2fff09f0d8205335dfdacbe82cc1b3ccb --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_bottle_43dof.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_cube_43dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_cube_43dof.xml new file mode 100644 index 0000000000000000000000000000000000000000..cb61b70167dfeb6786d911b6bdb34f4dd91ef8a4 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/pnp_cube_43dof.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof.xml new file mode 100644 index 0000000000000000000000000000000000000000..0b60f2f83228277ea83ebea17a0ede1eb7a5383b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof_activated3dex.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof_activated3dex.xml new file mode 100644 index 0000000000000000000000000000000000000000..2916dfb9ecf0566ebd2def70c03155be1ce91edb --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_29dof_activated3dex.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_43dof.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_43dof.xml new file mode 100644 index 0000000000000000000000000000000000000000..d66b23dce5da38aa29ff78d153ac86bf406740e5 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/model_data/g1/scene_43dof.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/robot_model.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/robot_model.py new file mode 100644 index 0000000000000000000000000000000000000000..27a1ed5c66b73cddeb6f3f7dce5a3276e83871fc --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/robot_model.py @@ -0,0 +1,772 @@ +from typing import List, Optional, Set, Union + +import numpy as np +import pinocchio as pin + +from decoupled_wbc.control.robot_model.supplemental_info import RobotSupplementalInfo + + +class RobotModel: + def __init__( + self, + urdf_path, + asset_path, + set_floating_base=False, + supplemental_info: Optional[RobotSupplementalInfo] = None, + ): + self.pinocchio_wrapper = pin.RobotWrapper.BuildFromURDF( + filename=urdf_path, + package_dirs=[asset_path], + root_joint=pin.JointModelFreeFlyer() if set_floating_base else None, + ) + self.is_floating_base_model = set_floating_base + + self.joint_to_dof_index = {} + # Assume we only have single-dof joints + # First two names correspond to universe and floating base joints + names = ( + self.pinocchio_wrapper.model.names[2:] + if set_floating_base + else self.pinocchio_wrapper.model.names[1:] + ) + for name in names: + j_id = self.pinocchio_wrapper.model.getJointId(name) + jmodel = self.pinocchio_wrapper.model.joints[j_id] + self.joint_to_dof_index[name] = jmodel.idx_q + + # Store joint limits only for actual joints (excluding floating base) + # if set floating base is true and the robot can move in the world + # then we don't want to impose joint limits for the 7 dofs corresponding + # to the floating base dofs. + root_nq = 7 if set_floating_base else 0 + self.upper_joint_limits = self.pinocchio_wrapper.model.upperPositionLimit[root_nq:].copy() + self.lower_joint_limits = self.pinocchio_wrapper.model.lowerPositionLimit[root_nq:].copy() + + # Set up supplemental info if provided + self.supplemental_info = supplemental_info + if self.supplemental_info is not None: + # Cache indices for body and hand actuated joints separately + self._body_actuated_joint_indices = [ + self.dof_index(name) for name in self.supplemental_info.body_actuated_joints + ] + self._left_hand_actuated_joint_indices = [ + self.dof_index(name) for name in self.supplemental_info.left_hand_actuated_joints + ] + self._right_hand_actuated_joint_indices = [ + self.dof_index(name) for name in self.supplemental_info.right_hand_actuated_joints + ] + self._hand_actuated_joint_indices = ( + self._left_hand_actuated_joint_indices + self._right_hand_actuated_joint_indices + ) + + # Cache indices for joint groups, handling nested groups + self._joint_group_indices = {} + for group_name, group_info in self.supplemental_info.joint_groups.items(): + indices = [] + # Add indices for direct joints + indices.extend([self.dof_index(name) for name in group_info["joints"]]) + # Add indices from subgroups + for subgroup_name in group_info["groups"]: + indices.extend(self.get_joint_group_indices(subgroup_name)) + self._joint_group_indices[group_name] = sorted(set(indices)) + + # Update joint limits from supplemental info if available + if ( + hasattr(self.supplemental_info, "joint_limits") + and self.supplemental_info.joint_limits + ): + for joint_name, limits in self.supplemental_info.joint_limits.items(): + if joint_name in self.joint_to_dof_index: + idx = self.joint_to_dof_index[joint_name] - root_nq + self.lower_joint_limits[idx] = limits[0] + self.upper_joint_limits[idx] = limits[1] + + # Initialize default body pose + self.default_body_pose = self.q_zero.copy() + + # Update with supplemental info if available + if self.supplemental_info is not None: + default_joint_q = self.supplemental_info.default_joint_q + for joint, joint_values in default_joint_q.items(): + # Get the joint name mapping for this type + joint_mapping = self.supplemental_info.joint_name_mapping[joint] + + # Handle both single joint names and left/right mappings + if isinstance(joint_mapping, str): + # Single joint (e.g., waist joints) + if joint_mapping in self.joint_to_dof_index: + joint_idx = self.dof_index(joint_mapping) + self.default_body_pose[joint_idx] = ( + joint_values # joint_values is the value for single joints + ) + else: + # Left/right mapping (e.g., arm joints) + for side, value in joint_values.items(): + if side in joint_mapping and joint_mapping[side] in self.joint_to_dof_index: + joint_idx = self.dof_index(joint_mapping[side]) + self.default_body_pose[joint_idx] = value + + # Initialize initial body pose + self.initial_body_pose = self.default_body_pose.copy() + + @property + def num_dofs(self) -> int: + """Get the number of degrees of freedom of the robot (floating base pose + joints).""" + return self.pinocchio_wrapper.model.nq + + @property + def q_zero(self) -> np.ndarray: + """Get the zero pose of the robot.""" + return self.pinocchio_wrapper.q0 + + @property + def joint_names(self) -> List[str]: + """Get the names of the joints of the robot.""" + return list(self.joint_to_dof_index.keys()) + + @property + def num_joints(self) -> int: + """Get the number of joints of the robot.""" + return len(self.joint_to_dof_index) + + def dof_index(self, joint_name: str) -> int: + """ + Get the index in the degrees of freedom vector corresponding + to the single-DoF joint with name `joint_name`. + """ + if joint_name not in self.joint_to_dof_index: + raise ValueError( + f"Unknown joint name: '{joint_name}'. " + f"Available joints: {list(self.joint_to_dof_index.keys())}" + ) + return self.joint_to_dof_index[joint_name] + + def get_body_actuated_joint_indices(self) -> List[int]: + """ + Get the indices of body actuated joints in the full configuration. + Ordering is that of the actuated joints as defined in the supplemental info. + Requires supplemental_info to be provided. + """ + if self.supplemental_info is None: + raise ValueError("supplemental_info must be provided to use this method") + return self._body_actuated_joint_indices + + def get_hand_actuated_joint_indices(self, side: str = "both") -> List[int]: + """ + Get the indices of hand actuated joints in the full configuration. + Ordering is that of the actuated joints as defined in the supplemental info. + Requires supplemental_info to be provided. + + Args: + side: String specifying which hand to get indices for ('left', 'right', or 'both') + """ + if self.supplemental_info is None: + raise ValueError("supplemental_info must be provided to use this method") + + if side.lower() == "both": + return self._hand_actuated_joint_indices + elif side.lower() == "left": + return self._left_hand_actuated_joint_indices + elif side.lower() == "right": + return self._right_hand_actuated_joint_indices + else: + raise ValueError("side must be 'left', 'right', or 'both'") + + def get_joint_group_indices(self, group_names: Union[str, Set[str]]) -> List[int]: + """ + Get the indices of joints in one or more groups in the full configuration. + Requires supplemental_info to be provided. + The returned indices are sorted in ascending order, so that the joint ordering + of the full model is preserved. + + Args: + group_names: Either a single group name (str) or a set of group names (Set[str]) + + Returns: + List of joint indices in sorted order with no duplicates + """ + if self.supplemental_info is None: + raise ValueError("supplemental_info must be provided to use this method") + + # Convert single string to set for uniform handling + if isinstance(group_names, str): + group_names = {group_names} + + # Collect indices from all groups + all_indices = set() + for group_name in group_names: + if group_name not in self._joint_group_indices: + raise ValueError(f"Unknown joint group: {group_name}") + all_indices.update(self._joint_group_indices[group_name]) + + return sorted(all_indices) + + def cache_forward_kinematics(self, q: np.ndarray, auto_clip=True) -> None: + """ + Perform forward kinematics to update the pose of every joint and frame + in the Pinocchio data structures for the given configuration `q`. + + :param q: A numpy array of shape (num_dofs,) representing the robot configuration. + """ + if q.shape[0] != self.num_dofs: + raise ValueError(f"Expected q of length {self.num_dofs}, got {q.shape[0]} instead.") + + # Apply auto-clip if enabled + if auto_clip: + q = self.clip_configuration(q) + + pin.framesForwardKinematics(self.pinocchio_wrapper.model, self.pinocchio_wrapper.data, q) + + def compute_gravity_compensation_torques( + self, q: np.ndarray, joint_groups: Union[str, List[str], Set[str]] = None, auto_clip=True + ) -> np.ndarray: + """ + Compute gravity compensation torques for specified joint groups using pinocchio. + + :param q: Robot configuration (joint positions) + :param joint_groups: Joint groups to compensate (e.g., "arms", ["left_arm", "waist"], + {"left_arm", "waist"}). If None, compensates all joints + :param auto_clip: Whether to automatically clip joint values to limits + :return: Array of gravity compensation torques for all DOFs (zero for non-compensated joints) + """ + if q.shape[0] != self.num_dofs: + raise ValueError(f"Expected q of length {self.num_dofs}, got {q.shape[0]} instead.") + + # Apply auto-clip if enabled + if auto_clip: + q = self.clip_configuration(q) + + try: + # Cache forward kinematics for the current configuration + self.cache_forward_kinematics(q, auto_clip=False) # Already clipped if needed + + # Compute gravity vector using RNEA with zero velocity and acceleration + v = np.zeros(self.num_dofs) + a = np.zeros(self.num_dofs) + + gravity_torques_full = pin.rnea( + self.pinocchio_wrapper.model, self.pinocchio_wrapper.data, q, v, a + ) + + # If no joint groups specified, return full gravity torques + if joint_groups is None: + return gravity_torques_full + + # Convert list to set for get_joint_group_indices compatibility + if isinstance(joint_groups, list): + joint_groups = set(joint_groups) + + # Get joint indices for specified groups - get_joint_group_indices handles str and Set[str] + try: + compensated_joint_indices = self.get_joint_group_indices(joint_groups) + except ValueError as e: + raise ValueError(f"Error resolving joint groups {joint_groups}: {e}") + + # Create mask for joints that should receive gravity compensation + compensation_mask = np.zeros(self.num_dofs, dtype=bool) + for joint_idx in compensated_joint_indices: + if 0 <= joint_idx < len(compensation_mask): + compensation_mask[joint_idx] = True + + # Apply mask to only compensate specified joints + compensated_torques = np.zeros_like(gravity_torques_full) + compensated_torques[compensation_mask] = gravity_torques_full[compensation_mask] + + return compensated_torques + + except Exception as e: + raise RuntimeError(f"Error computing gravity compensation: {e}") + + def clip_configuration(self, q: np.ndarray, margin: float = 1e-6) -> np.ndarray: + """ + Clip the configuration to stay within joint limits with a small tolerance. + + :param q: Configuration to clip + :param margin: Tolerance to keep away from joint limits + :return: Clipped configuration + """ + q_clipped = q.copy() + + # Only clip joint positions, not floating base + root_nq = 7 if self.is_floating_base_model else 0 + q_clipped[root_nq:] = np.clip( + q[root_nq:], self.lower_joint_limits + margin, self.upper_joint_limits - margin + ) + + return q_clipped + + def frame_placement(self, frame_name: str) -> pin.SE3: + """ + Returns the SE3 transform of the specified frame in the world coordinate system. + Note: make sure cache_forward_kinematics() has been previously called. + + :param frame_name: Name of the frame, e.g. "link_elbow_frame", "hand_imu_frame", etc. + :return: A pin.SE3 object representing the pose of the frame. + """ + model = self.pinocchio_wrapper.model + data = self.pinocchio_wrapper.data + + frame_id = model.getFrameId(frame_name) + if frame_id < 0 or frame_id >= len(model.frames): + valid_frames = [f.name for f in model.frames] + raise ValueError(f"Unknown frame '{frame_name}'. Valid frames: {valid_frames}") + + # Pinocchio's data.oMf[frame_id] is a pin.SE3. + return data.oMf[frame_id].copy() + + def get_body_actuated_joints(self, q: np.ndarray) -> np.ndarray: + """ + Get the configuration of body actuated joints from a full configuration. + + :param q: Configuration in full space + :return: Configuration of body actuated joints + """ + indices = self.get_body_actuated_joint_indices() + + return q[indices] + + def get_hand_actuated_joints(self, q: np.ndarray, side: str = "both") -> np.ndarray: + """ + Get the configuration of hand actuated joints from a full configuration. + + Args: + q: Configuration in full space + side: String specifying which hand to get joints for ('left', 'right', or 'both') + """ + indices = self.get_hand_actuated_joint_indices(side) + return q[indices] + + def get_configuration_from_actuated_joints( + self, + body_actuated_joint_values: np.ndarray, + hand_actuated_joint_values: Optional[np.ndarray] = None, + left_hand_actuated_joint_values: Optional[np.ndarray] = None, + right_hand_actuated_joint_values: Optional[np.ndarray] = None, + ) -> np.ndarray: + """ + Get the full configuration from the body and hand actuated joint configurations. + Can specify either both hands together or left and right hands separately. + + Args: + body_actuated_joint_values: Configuration of body actuated joints + hand_actuated_joint_values: Configuration of both hands' actuated joints (optional) + left_hand_actuated_joint_values: Configuration of left hand actuated joints (optional) + right_hand_actuated_joint_values: Configuration of right hand actuated joints (optional) + + Returns: + Full configuration including body and hand joints + """ + q = self.pinocchio_wrapper.q0.copy() + q[self.get_body_actuated_joint_indices()] = body_actuated_joint_values + + # Handle hand configurations + if hand_actuated_joint_values is not None: + # Use combined hand configuration + q[self.get_hand_actuated_joint_indices("both")] = hand_actuated_joint_values + else: + # Use separate hand configurations + if left_hand_actuated_joint_values is not None: + q[self.get_hand_actuated_joint_indices("left")] = left_hand_actuated_joint_values + if right_hand_actuated_joint_values is not None: + q[self.get_hand_actuated_joint_indices("right")] = right_hand_actuated_joint_values + + return q + + def reset_forward_kinematics(self) -> None: + """ + Reset the forward kinematics to the initial configuration. + """ + self.cache_forward_kinematics(self.q_zero) + + def get_initial_upper_body_pose(self) -> np.ndarray: + """ + Get the initial upper body pose of the robot. + """ + return self.initial_body_pose[self.get_joint_group_indices("upper_body")] + + def get_default_body_pose(self) -> np.ndarray: + """ + Get the default body pose of the robot. + """ + return self.default_body_pose + + def set_initial_body_pose(self, q: np.ndarray, q_idx=None) -> None: + """ + Set the initial body pose of the robot. + """ + if q_idx is None: + self.initial_body_pose = q + else: + self.initial_body_pose[q_idx] = q + + +class ReducedRobotModel(RobotModel): + """ + A class that creates a reduced order robot model by fixing certain joints. + This class maintains a mapping between the reduced state space and the full state space. + """ + + def __init__( + self, + full_robot_model: RobotModel, + fixed_joints: List[str], + fixed_values: Optional[List[float]] = None, + ): + """ + Create a reduced order robot model by fixing specified joints. + + :param full_robot_model: The original robot model + :param fixed_joints: List of joint names to fix + :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial + joint positions (q0) from the full robot model. + """ + self.full_robot = full_robot_model + self.supplemental_info = full_robot_model.supplemental_info + + # If fixed_values is None, use q0 from the full robot model + if fixed_values is None: + fixed_values = [] + for joint_name in fixed_joints: + full_idx = full_robot_model.dof_index(joint_name) + fixed_values.append(full_robot_model.pinocchio_wrapper.q0[full_idx]) + elif len(fixed_joints) != len(fixed_values): + raise ValueError("fixed_joints and fixed_values must have the same length") + + # Store fixed joints and their values + self.fixed_joints = fixed_joints + self.fixed_values = fixed_values + + # Create mapping between reduced and full state spaces + self.reduced_to_full = [] + self.full_to_reduced = {} + + # Initialize with floating base indices if present + if full_robot_model.is_floating_base_model: + self.reduced_to_full.extend(range(7)) # Floating base indices + for i in range(7): + self.full_to_reduced[i] = i + + # Add active joint indices + for joint_name in full_robot_model.joint_names: + if joint_name not in fixed_joints: + full_idx = full_robot_model.dof_index(joint_name) + reduced_idx = len(self.reduced_to_full) + self.reduced_to_full.append(full_idx) + self.full_to_reduced[full_idx] = reduced_idx + + # Create a reduced Pinocchio model using buildReducedModel + # First, get the list of joint IDs to lock + locked_joint_ids = [] + for joint_name in fixed_joints: + joint_id = full_robot_model.pinocchio_wrapper.model.getJointId(joint_name) + if (full_robot_model.is_floating_base_model and joint_id > 1) or ( + not full_robot_model.is_floating_base_model and joint_id > 0 + ): + locked_joint_ids.append(joint_id) + + # First build the reduced kinematic model + reduced_model = pin.buildReducedModel( + full_robot_model.pinocchio_wrapper.model, + locked_joint_ids, + full_robot_model.pinocchio_wrapper.q0, + ) + + # Then build the reduced geometry models using the reduced kinematic model + self.pinocchio_wrapper = pin.RobotWrapper( + model=reduced_model, + ) + + # Create joint to dof index mapping + self.joint_to_dof_index = {} + # Assume we only have single-dof joints + # First two names correspond to universe and floating base joints + names = ( + self.pinocchio_wrapper.model.names[2:] + if self.full_robot.is_floating_base_model + else self.pinocchio_wrapper.model.names[1:] + ) + for name in names: + j_id = self.pinocchio_wrapper.model.getJointId(name) + jmodel = self.pinocchio_wrapper.model.joints[j_id] + self.joint_to_dof_index[name] = jmodel.idx_q + + # Initialize joint limits + root_nq = 7 if self.full_robot.is_floating_base_model else 0 + self.lower_joint_limits = self.pinocchio_wrapper.model.lowerPositionLimit[root_nq:].copy() + self.upper_joint_limits = self.pinocchio_wrapper.model.upperPositionLimit[root_nq:].copy() + + # Update joint limits from supplemental info if available + if self.supplemental_info is not None: + if ( + hasattr(self.supplemental_info, "joint_limits") + and self.supplemental_info.joint_limits + ): + for joint_name, limits in self.supplemental_info.joint_limits.items(): + if joint_name in self.joint_to_dof_index: + idx = self.joint_to_dof_index[joint_name] - root_nq + self.lower_joint_limits[idx] = limits[0] + self.upper_joint_limits[idx] = limits[1] + + # Get full indices for body and hand actuated joints + full_body_indices = full_robot_model.get_body_actuated_joint_indices() + full_hand_indices = full_robot_model.get_hand_actuated_joint_indices("both") + full_left_hand_indices = full_robot_model.get_hand_actuated_joint_indices("left") + full_right_hand_indices = full_robot_model.get_hand_actuated_joint_indices("right") + + # Map to reduced indices + self._body_actuated_joint_indices = [] + for idx in full_body_indices: + if idx in self.full_to_reduced: + self._body_actuated_joint_indices.append(self.full_to_reduced[idx]) + + self._hand_actuated_joint_indices = [] + for idx in full_hand_indices: + if idx in self.full_to_reduced: + self._hand_actuated_joint_indices.append(self.full_to_reduced[idx]) + + self._left_hand_actuated_joint_indices = [] + for idx in full_left_hand_indices: + if idx in self.full_to_reduced: + self._left_hand_actuated_joint_indices.append(self.full_to_reduced[idx]) + + self._right_hand_actuated_joint_indices = [] + for idx in full_right_hand_indices: + if idx in self.full_to_reduced: + self._right_hand_actuated_joint_indices.append(self.full_to_reduced[idx]) + + # Cache indices for joint groups in reduced space + self._joint_group_indices = {} + for group_name in self.supplemental_info.joint_groups: + full_indices = full_robot_model.get_joint_group_indices(group_name) + reduced_indices = [] + for idx in full_indices: + if idx in self.full_to_reduced: + reduced_indices.append(self.full_to_reduced[idx]) + self._joint_group_indices[group_name] = sorted(set(reduced_indices)) + + # Initialize default body pose in reduced space + self.default_body_pose = self.full_to_reduced_configuration( + full_robot_model.default_body_pose + ) + + # Initialize initial body pose in reduced space + self.initial_body_pose = self.full_to_reduced_configuration( + full_robot_model.initial_body_pose + ) + + @property + def num_joints(self) -> int: + """Get the number of active joints in the reduced model.""" + return len(self.joint_names) + + @property + def joint_names(self) -> List[str]: + """Get the names of the active joints in the reduced model.""" + return [name for name in self.full_robot.joint_names if name not in self.fixed_joints] + + @classmethod + def from_fixed_groups( + cls, + full_robot_model: RobotModel, + fixed_group_names: List[str], + fixed_values: Optional[List[float]] = None, + ) -> "ReducedRobotModel": + """ + Create a reduced order robot model by fixing all joints in specified groups. + + :param full_robot_model: The original robot model + :param fixed_group_names: List of joint group names to fix + :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial + joint positions (q0) from the full robot model. + :return: A ReducedRobotModel instance + """ + if full_robot_model.supplemental_info is None: + raise ValueError("supplemental_info must be provided to use this method") + + # Get all joints in the groups, including those from subgroups + fixed_joints = set() # Use a set to avoid duplicates + + for group_name in fixed_group_names: + if group_name not in full_robot_model.supplemental_info.joint_groups: + raise ValueError(f"Unknown joint group: {group_name}") + + group_info = full_robot_model.supplemental_info.joint_groups[group_name] + + # Add direct joints + fixed_joints.update(group_info["joints"]) + + # Add joints from subgroups + for subgroup_name in group_info["groups"]: + subgroup_joints = full_robot_model.get_joint_group_indices(subgroup_name) + fixed_joints.update([full_robot_model.joint_names[idx] for idx in subgroup_joints]) + + # Convert set back to list for compatibility with the original constructor + return cls(full_robot_model, list(fixed_joints), fixed_values) + + @classmethod + def from_fixed_group( + cls, + full_robot_model: RobotModel, + fixed_group_name: str, + fixed_values: Optional[List[float]] = None, + ) -> "ReducedRobotModel": + """ + Create a reduced order robot model by fixing all joints in a specified group. + This is a convenience method that calls from_fixed_groups with a single group. + + :param full_robot_model: The original robot model + :param fixed_group_name: Name of the joint group to fix + :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial + joint positions (q0) from the full robot model. + :return: A ReducedRobotModel instance + """ + return cls.from_fixed_groups(full_robot_model, [fixed_group_name], fixed_values) + + @classmethod + def from_active_group( + cls, + full_robot_model: RobotModel, + active_group_name: str, + fixed_values: Optional[List[float]] = None, + ) -> "ReducedRobotModel": + """ + Create a reduced order robot model by fixing all joints EXCEPT those in the specified group. + This is a convenience method that calls from_active_groups with a single group. + + :param full_robot_model: The original robot model + :param active_group_name: Name of the joint group to keep active (all other joints will be fixed) + :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial + joint positions (q0) from the full robot model. + :return: A ReducedRobotModel instance + """ + return cls.from_active_groups(full_robot_model, [active_group_name], fixed_values) + + @classmethod + def from_active_groups( + cls, + full_robot_model: RobotModel, + active_group_names: List[str], + fixed_values: Optional[List[float]] = None, + ) -> "ReducedRobotModel": + """ + Create a reduced order robot model by fixing all joints EXCEPT those in the specified groups. + This is useful when you want to keep multiple groups active and fix everything else. + + :param full_robot_model: The original robot model + :param active_group_names: List of joint group names to keep active (all other joints will be fixed) + :param fixed_values: Optional list of values to fix the joints to. If None, uses the initial + joint positions (q0) from the full robot model. + :return: A ReducedRobotModel instance + """ + if full_robot_model.supplemental_info is None: + raise ValueError("supplemental_info must be provided to use this method") + + # Get all joints in the active groups, including those from subgroups + active_joints = set() + + def add_group_joints(group_name: str): + if group_name not in full_robot_model.supplemental_info.joint_groups: + raise ValueError(f"Unknown joint group: {group_name}") + + group_info = full_robot_model.supplemental_info.joint_groups[group_name] + + # Add direct joints + if "joints" in group_info: + active_joints.update(group_info["joints"]) + + # Add joints from subgroups + if "groups" in group_info: + for subgroup_name in group_info["groups"]: + add_group_joints(subgroup_name) + + for group_name in active_group_names: + add_group_joints(group_name) + + # Get all joints from the model + all_joints = set(full_robot_model.joint_names) + + # The fixed joints are all joints minus the active joints + fixed_joints = list(all_joints - active_joints) + + return cls(full_robot_model, fixed_joints, fixed_values) + + def reduced_to_full_configuration(self, q_reduced: np.ndarray) -> np.ndarray: + """ + Convert a reduced configuration to the full configuration space. + + :param q_reduced: Configuration in reduced space + :return: Configuration in full space with fixed joints set to their fixed values + """ + if q_reduced.shape[0] != self.num_dofs: + raise ValueError( + f"Expected q_reduced of length {self.num_dofs}, got {q_reduced.shape[0]} instead" + ) + + q_full = np.zeros(self.full_robot.num_dofs) + + # Set active joints + for reduced_idx, full_idx in enumerate(self.reduced_to_full): + q_full[full_idx] = q_reduced[reduced_idx] + + # Set fixed joints + for joint_name, value in zip(self.fixed_joints, self.fixed_values): + full_idx = self.full_robot.dof_index(joint_name) + q_full[full_idx] = value + + return q_full + + def full_to_reduced_configuration(self, q_full: np.ndarray) -> np.ndarray: + """ + Convert a full configuration to the reduced configuration space. + + :param q_full: Configuration in full space + :return: Configuration in reduced space + """ + if q_full.shape[0] != self.full_robot.num_dofs: + raise ValueError( + f"Expected q_full of length {self.full_robot.num_dofs}, got {q_full.shape[0]} instead" + ) + + q_reduced = np.zeros(self.num_dofs) + + # Copy active joints + for reduced_idx, full_idx in enumerate(self.reduced_to_full): + q_reduced[reduced_idx] = q_full[full_idx] + + return q_reduced + + def cache_forward_kinematics(self, q_reduced: np.ndarray, auto_clip=True) -> None: + """ + Perform forward kinematics using the reduced configuration. + + :param q_reduced: Configuration in reduced space + """ + # First update the full robot's forward kinematics + q_full = self.reduced_to_full_configuration(q_reduced) + self.full_robot.cache_forward_kinematics(q_full, auto_clip) + + # Then update the reduced model's forward kinematics + pin.framesForwardKinematics( + self.pinocchio_wrapper.model, self.pinocchio_wrapper.data, q_reduced + ) + + def clip_configuration(self, q_reduced: np.ndarray, margin: float = 1e-6) -> np.ndarray: + """ + Clip the reduced configuration to stay within joint limits with a small tolerance. + + :param q_reduced: Configuration to clip + :param margin: Tolerance to keep away from joint limits + :return: Clipped configuration + """ + q_full = self.reduced_to_full_configuration(q_reduced) + q_full_clipped = self.full_robot.clip_configuration(q_full, margin) + return self.full_to_reduced_configuration(q_full_clipped) + + def reset_forward_kinematics(self): + """ + Reset the forward kinematics to the initial configuration. + """ + # Reset full robot's forward kinematics + self.full_robot.reset_forward_kinematics() + # Reset reduced model's forward kinematics + self.cache_forward_kinematics(self.q_zero) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d2e1e650777c31d84ac48f823e9a1b864a65132 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/__init__.py @@ -0,0 +1,5 @@ +from decoupled_wbc.control.robot_model.supplemental_info.robot_supplemental_info import ( + RobotSupplementalInfo, +) + +__all__ = ["RobotSupplementalInfo"] diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/g1_supplemental_info.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/g1_supplemental_info.py new file mode 100644 index 0000000000000000000000000000000000000000..da7dc659fa4a531f57a897df23ea886d6e8934df --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/g1/g1_supplemental_info.py @@ -0,0 +1,330 @@ +from dataclasses import dataclass +from enum import Enum + +import numpy as np + +from decoupled_wbc.control.robot_model.supplemental_info.robot_supplemental_info import ( + RobotSupplementalInfo, +) + + +class WaistLocation(Enum): + """Enum for waist location configuration.""" + + LOWER_BODY = "lower_body" + UPPER_BODY = "upper_body" + LOWER_AND_UPPER_BODY = "lower_and_upper_body" + + +class ElbowPose(Enum): + """Enum for elbow pose configuration.""" + + LOW = "low" + HIGH = "high" + + +@dataclass +class G1SupplementalInfo(RobotSupplementalInfo): + """ + Supplemental information for the G1 robot. + + Args: + waist_location: Where to place waist joints in the joint groups + elbow_pose: Which elbow pose configuration to use for default joint positions + """ + + def __init__( + self, + waist_location: WaistLocation = WaistLocation.LOWER_BODY, + elbow_pose: ElbowPose = ElbowPose.LOW, + ): + name = "G1_G1ThreeFinger" + + # Define all actuated joints + body_actuated_joints = [ + # Left leg + "left_hip_pitch_joint", + "left_hip_roll_joint", + "left_hip_yaw_joint", + "left_knee_joint", + "left_ankle_pitch_joint", + "left_ankle_roll_joint", + # Right leg + "right_hip_pitch_joint", + "right_hip_roll_joint", + "right_hip_yaw_joint", + "right_knee_joint", + "right_ankle_pitch_joint", + "right_ankle_roll_joint", + # Waist + "waist_yaw_joint", + "waist_roll_joint", + "waist_pitch_joint", + # Left arm + "left_shoulder_pitch_joint", + "left_shoulder_roll_joint", + "left_shoulder_yaw_joint", + "left_elbow_joint", + "left_wrist_roll_joint", + "left_wrist_pitch_joint", + "left_wrist_yaw_joint", + # Right arm + "right_shoulder_pitch_joint", + "right_shoulder_roll_joint", + "right_shoulder_yaw_joint", + "right_elbow_joint", + "right_wrist_roll_joint", + "right_wrist_pitch_joint", + "right_wrist_yaw_joint", + ] + + left_hand_actuated_joints = [ + # Left hand + "left_hand_thumb_0_joint", + "left_hand_thumb_1_joint", + "left_hand_thumb_2_joint", + "left_hand_index_0_joint", + "left_hand_index_1_joint", + "left_hand_middle_0_joint", + "left_hand_middle_1_joint", + ] + + right_hand_actuated_joints = [ + # Right hand + "right_hand_thumb_0_joint", + "right_hand_thumb_1_joint", + "right_hand_thumb_2_joint", + "right_hand_index_0_joint", + "right_hand_index_1_joint", + "right_hand_middle_0_joint", + "right_hand_middle_1_joint", + ] + + # Define joint limits from URDF + joint_limits = { + # Left leg + "left_hip_pitch_joint": [-2.5307, 2.8798], + "left_hip_roll_joint": [-0.5236, 2.9671], + "left_hip_yaw_joint": [-2.7576, 2.7576], + "left_knee_joint": [-0.087267, 2.8798], + "left_ankle_pitch_joint": [-0.87267, 0.5236], + "left_ankle_roll_joint": [-0.2618, 0.2618], + # Right leg + "right_hip_pitch_joint": [-2.5307, 2.8798], + "right_hip_roll_joint": [-2.9671, 0.5236], + "right_hip_yaw_joint": [-2.7576, 2.7576], + "right_knee_joint": [-0.087267, 2.8798], + "right_ankle_pitch_joint": [-0.87267, 0.5236], + "right_ankle_roll_joint": [-0.2618, 0.2618], + # Waist + "waist_yaw_joint": [-2.618, 2.618], + "waist_roll_joint": [-0.52, 0.52], + "waist_pitch_joint": [-0.52, 0.52], + # Left arm + "left_shoulder_pitch_joint": [-3.0892, 2.6704], + "left_shoulder_roll_joint": [0.19, 2.2515], + "left_shoulder_yaw_joint": [-2.618, 2.618], + "left_elbow_joint": [-1.0472, 2.0944], + "left_wrist_roll_joint": [-1.972222054, 1.972222054], + "left_wrist_pitch_joint": [-1.614429558, 1.614429558], + "left_wrist_yaw_joint": [-1.614429558, 1.614429558], + # Right arm + "right_shoulder_pitch_joint": [-3.0892, 2.6704], + "right_shoulder_roll_joint": [-2.2515, -0.19], + "right_shoulder_yaw_joint": [-2.618, 2.618], + "right_elbow_joint": [-1.0472, 2.0944], + "right_wrist_roll_joint": [-1.972222054, 1.972222054], + "right_wrist_pitch_joint": [-1.614429558, 1.614429558], + "right_wrist_yaw_joint": [-1.614429558, 1.614429558], + # Left hand + "left_hand_thumb_0_joint": [-1.04719755, 1.04719755], + "left_hand_thumb_1_joint": [-0.72431163, 1.04719755], + "left_hand_thumb_2_joint": [0, 1.74532925], + "left_hand_index_0_joint": [-1.57079632, 0], + "left_hand_index_1_joint": [-1.74532925, 0], + "left_hand_middle_0_joint": [-1.57079632, 0], + "left_hand_middle_1_joint": [-1.74532925, 0], + # Right hand + "right_hand_thumb_0_joint": [-1.04719755, 1.04719755], + "right_hand_thumb_1_joint": [-0.72431163, 1.04719755], + "right_hand_thumb_2_joint": [0, 1.74532925], + "right_hand_index_0_joint": [-1.57079632, 0], + "right_hand_index_1_joint": [-1.74532925, 0], + "right_hand_middle_0_joint": [-1.57079632, 0], + "right_hand_middle_1_joint": [-1.74532925, 0], + } + + # Define joint groups + joint_groups = { + # Body groups + "waist": { + "joints": ["waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint"], + "groups": [], + }, + # Leg groups + "left_leg": { + "joints": [ + "left_hip_pitch_joint", + "left_hip_roll_joint", + "left_hip_yaw_joint", + "left_knee_joint", + "left_ankle_pitch_joint", + "left_ankle_roll_joint", + ], + "groups": [], + }, + "right_leg": { + "joints": [ + "right_hip_pitch_joint", + "right_hip_roll_joint", + "right_hip_yaw_joint", + "right_knee_joint", + "right_ankle_pitch_joint", + "right_ankle_roll_joint", + ], + "groups": [], + }, + "legs": {"joints": [], "groups": ["left_leg", "right_leg"]}, + # Arm groups + "left_arm": { + "joints": [ + "left_shoulder_pitch_joint", + "left_shoulder_roll_joint", + "left_shoulder_yaw_joint", + "left_elbow_joint", + "left_wrist_roll_joint", + "left_wrist_pitch_joint", + "left_wrist_yaw_joint", + ], + "groups": [], + }, + "right_arm": { + "joints": [ + "right_shoulder_pitch_joint", + "right_shoulder_roll_joint", + "right_shoulder_yaw_joint", + "right_elbow_joint", + "right_wrist_roll_joint", + "right_wrist_pitch_joint", + "right_wrist_yaw_joint", + ], + "groups": [], + }, + "arms": {"joints": [], "groups": ["left_arm", "right_arm"]}, + # Hand groups + "left_hand": { + "joints": [ + "left_hand_index_0_joint", + "left_hand_index_1_joint", + "left_hand_middle_0_joint", + "left_hand_middle_1_joint", + "left_hand_thumb_0_joint", + "left_hand_thumb_1_joint", + "left_hand_thumb_2_joint", + ], + "groups": [], + }, + "right_hand": { + "joints": [ + "right_hand_index_0_joint", + "right_hand_index_1_joint", + "right_hand_middle_0_joint", + "right_hand_middle_1_joint", + "right_hand_thumb_0_joint", + "right_hand_thumb_1_joint", + "right_hand_thumb_2_joint", + ], + "groups": [], + }, + "hands": {"joints": [], "groups": ["left_hand", "right_hand"]}, + # Full body groups + "lower_body": {"joints": [], "groups": ["waist", "legs"]}, + "upper_body_no_hands": {"joints": [], "groups": ["arms"]}, + "body": {"joints": [], "groups": ["lower_body", "upper_body_no_hands"]}, + "upper_body": {"joints": [], "groups": ["upper_body_no_hands", "hands"]}, + } + + # Define joint name mapping from generic types to robot-specific names + joint_name_mapping = { + # Waist joints + "waist_pitch": "waist_pitch_joint", + "waist_roll": "waist_roll_joint", + "waist_yaw": "waist_yaw_joint", + # Shoulder joints + "shoulder_pitch": { + "left": "left_shoulder_pitch_joint", + "right": "right_shoulder_pitch_joint", + }, + "shoulder_roll": { + "left": "left_shoulder_roll_joint", + "right": "right_shoulder_roll_joint", + }, + "shoulder_yaw": { + "left": "left_shoulder_yaw_joint", + "right": "right_shoulder_yaw_joint", + }, + # Elbow joints + "elbow_pitch": {"left": "left_elbow_joint", "right": "right_elbow_joint"}, + # Wrist joints + "wrist_pitch": {"left": "left_wrist_pitch_joint", "right": "right_wrist_pitch_joint"}, + "wrist_roll": {"left": "left_wrist_roll_joint", "right": "right_wrist_roll_joint"}, + "wrist_yaw": {"left": "left_wrist_yaw_joint", "right": "right_wrist_yaw_joint"}, + } + + root_frame_name = "pelvis" + + hand_frame_names = {"left": "left_wrist_yaw_link", "right": "right_wrist_yaw_link"} + + elbow_calibration_joint_angles = {"left": 0.0, "right": 0.0} + + hand_rotation_correction = np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]]) + + # Configure default joint positions based on elbow pose + if elbow_pose == ElbowPose.HIGH: + default_joint_q = { + "shoulder_roll": {"left": 0.5, "right": -0.5}, + "shoulder_pitch": {"left": -0.2, "right": -0.2}, + "shoulder_yaw": {"left": -0.5, "right": 0.5}, + "wrist_roll": {"left": -0.5, "right": 0.5}, + "wrist_yaw": {"left": 0.5, "right": -0.5}, + "wrist_pitch": {"left": -0.2, "right": -0.2}, + } + else: # ElbowPose.LOW + default_joint_q = { + "shoulder_roll": {"left": 0.2, "right": -0.2}, + } + + teleop_upper_body_motion_scale = 1.0 + + # Configure joint groups based on waist location + modified_joint_groups = joint_groups.copy() + if waist_location == WaistLocation.UPPER_BODY: + # Move waist from lower_body to upper_body_no_hands + modified_joint_groups["lower_body"] = {"joints": [], "groups": ["legs"]} + modified_joint_groups["upper_body_no_hands"] = { + "joints": [], + "groups": ["arms", "waist"], + } + elif waist_location == WaistLocation.LOWER_AND_UPPER_BODY: + # Add waist to upper_body_no_hands while keeping it in lower_body + modified_joint_groups["upper_body_no_hands"] = { + "joints": [], + "groups": ["arms", "waist"], + } + # For LOWER_BODY, keep default joint_groups as is + + super().__init__( + name=name, + body_actuated_joints=body_actuated_joints, + left_hand_actuated_joints=left_hand_actuated_joints, + right_hand_actuated_joints=right_hand_actuated_joints, + joint_limits=joint_limits, + joint_groups=modified_joint_groups, + root_frame_name=root_frame_name, + hand_frame_names=hand_frame_names, + elbow_calibration_joint_angles=elbow_calibration_joint_angles, + joint_name_mapping=joint_name_mapping, + hand_rotation_correction=hand_rotation_correction, + default_joint_q=default_joint_q, + teleop_upper_body_motion_scale=teleop_upper_body_motion_scale, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/robot_supplemental_info.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/robot_supplemental_info.py new file mode 100644 index 0000000000000000000000000000000000000000..d4d66cfe71bbe1b0b26a19297477126a794b863f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/robot_model/supplemental_info/robot_supplemental_info.py @@ -0,0 +1,91 @@ +from dataclasses import dataclass +from typing import Dict, List, Union + +import numpy as np + + +@dataclass +class RobotSupplementalInfo: + """ + Base class for robot-specific information that is not easily extractable from URDF. + This includes information about actuated joints, joint hierarchies, etc. + """ + + name: str + + # List of body actuated joint names (excluding hands) + body_actuated_joints: List[str] + + # List of left hand actuated joint names + left_hand_actuated_joints: List[str] + + # List of right hand actuated joint names + right_hand_actuated_joints: List[str] + + # Dictionary of joint groups, where each group is a dictionary with: + # - "joints": list of joint names + # - "groups": list of subgroup names (optional) + # Example: { + # "right_arm": { + # "joints": ["right_shoulder_pitch_joint", "right_shoulder_roll_joint", "right_elbow_joint"], + # "groups": [] + # }, + # "left_arm": { + # "joints": ["left_shoulder_pitch_joint", "left_shoulder_roll_joint", "left_elbow_joint"], + # "groups": [] + # }, + # "upper_body": { + # "joints": ["torso_pitch_joint", "torso_yaw_joint", "torso_roll_joint"], + # "groups": ["right_arm", "left_arm"] + # } + # } + joint_groups: Dict[str, Dict[str, List[str]]] + + # Name of the root frame + root_frame_name: str + + # Dictionary of hand frame names + # Example: { + # "left": "left_hand_frame", + # "right": "right_hand_frame" + # } + hand_frame_names: Dict[str, str] + + # Dictionary of joint limits + # Example: { + # "left_shoulder_pitch_joint": [-np.pi / 2, np.pi / 2], + # "right_shoulder_pitch_joint": [-np.pi / 2, np.pi / 2] + # } + joint_limits: Dict[str, List[float]] + + # Dictionary of elbow calibration joint angles + # Example: { + # "left": -90.0, + # "right": -90.0 + # } + elbow_calibration_joint_angles: Dict[str, float] + + # Dictionary of joint name mapping from generic types to robot-specific names + # Example: { + # "waist_pitch": "waist_pitch_joint", + # "shoulder_pitch": { + # "left": "left_shoulder_pitch_joint", + # "right": "right_shoulder_pitch_joint" + # }, + # "elbow_pitch": { + # "left": "left_elbow_pitch_joint", + # "right": "right_elbow_pitch_joint" + # } + # } + joint_name_mapping: Dict[str, Union[str, Dict[str, str]]] + + # Maps from generic joint names to robot-specific joint values + # Example: { + # "waist_roll": 0.2, + # "elbow_pitch": {"left": 1.0, "right": 1.0} + # } + default_joint_q: Dict[str, Union[float, Dict[str, float]]] + + hand_rotation_correction: np.ndarray + + teleop_upper_body_motion_scale: float diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/composed_camera.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/composed_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..675a93563148b01926222c5854149b09d82317b3 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/composed_camera.py @@ -0,0 +1,440 @@ +from collections import deque +from dataclasses import dataclass +import queue +import threading +import time +from typing import Any, Dict, Optional + +# we need to import these first in this order to avoid TSL segmentation fault +# caused by zed and oak libraries +try: + import cv2 # noqa + import depthai as dai # noqa + import pyzed.sl as sl # noqa +except ImportError: + print( + """ + Some of the camera specific dependencies are not installed. If you are + not running this on the robot, having these libraries is optional. + """ + ) + +import numpy as np # noqa + +from decoupled_wbc.control.base.sensor import Sensor +from decoupled_wbc.control.sensor.sensor_server import ( + ImageMessageSchema, + SensorClient, + SensorServer, + CameraMountPosition, +) + + +def read_qr_code(data): + current_time = time.monotonic() + detector = cv2.QRCodeDetector() + for key, img in data["images"].items(): + decoded_time, bbox, _ = detector.detectAndDecode(img) + if bbox is not None and decoded_time: + print(f"{key} latency: {(current_time - float(decoded_time)) * 1e3:.1f} ms") + else: + print(f"{key} QR code not detected.") + + +@dataclass +class ComposedCameraConfig: + """Camera configuration for composed camera""" + + ego_view_camera: Optional[str] = "oak" + """Camera type for ego view: oak, realsense, zed, or None""" + + ego_view_device_id: Optional[str] = None + """Device ID for ego view camera (optional, used for OAK cameras)""" + + head_camera: Optional[str] = None + """Camera type for head view: oak, oak_mono, realsense, zed or None""" + + head_device_id: Optional[str] = None + """Device ID for head camera (optional, used for OAK cameras)""" + + left_wrist_camera: Optional[str] = None + """Camera type for left wrist view: oak, realsense, zed or None""" + + left_wrist_device_id: Optional[str] = None + """Device ID for left wrist camera (optional, used for OAK cameras)""" + + right_wrist_camera: Optional[str] = None + """Camera type for right wrist view: oak, realsense, zed or None""" + + right_wrist_device_id: Optional[str] = None + """Device ID for right wrist camera (optional, used for OAK cameras)""" + + fps: int = 30 + """Rate at which the composed camera will publish the images. Since composed camera + can read from multiple cameras, it will publish all the images. + Note that OAK can only run at 30 FPS. 20 FPS will cause large latency. + """ + + # Server configuration + run_as_server: bool = True + """Whether to run as server or client""" + + server: bool = True + """Whether to run the camera as a server""" + + port: int = 5555 + """Port number for server/client communication""" + + test_latency: bool = False + """Whether to test latency""" + + # Queue configuration + queue_size: int = 3 + """Size of each camera's image queue""" + + def __post_init__(self): + # runyu: Note that this is a hack to make the config work with G1 camera server in orin + # we should not use this hack in the future + self.run_as_server: bool = self.server + + +class ComposedCameraSensor(Sensor, SensorServer): + + def __init__(self, config: ComposedCameraConfig): + self.config = config + self.camera_queues: Dict[str, queue.Queue] = {} + self.camera_threads: Dict[str, threading.Thread] = {} + self.shutdown_events: Dict[str, threading.Event] = {} + self.error_events: Dict[str, threading.Event] = {} + self.error_messages: Dict[str, str] = {} + self._observation_spaces: Dict[str, Any] = {} + + camera_configs = self._get_camera_configs() + + # Then create worker threads + for mount_position, camera_config in camera_configs.items(): + # Create queue and shutdown event for this camera + camera_queue = queue.Queue(maxsize=config.queue_size) + shutdown_event = threading.Event() + error_event = threading.Event() + + self.camera_queues[mount_position] = camera_queue + self.shutdown_events[mount_position] = shutdown_event + self.error_events[mount_position] = error_event + + # Start camera thread + thread = threading.Thread( + target=self._camera_worker_wrapper, + args=( + mount_position, + camera_config["camera_type"], + camera_config["device_id"], + camera_queue, + shutdown_event, + error_event, + ), + ) + thread.start() + self.camera_threads[mount_position] = thread + + if config.run_as_server: + self.start_server(config.port) + + def _get_camera_configs(self) -> Dict[str, str]: + """Get camera configurations as mount_position -> camera_type mapping""" + camera_configs = {} + + if self.config.ego_view_camera is not None: + camera_configs[CameraMountPosition.EGO_VIEW.value] = { + "camera_type": self.config.ego_view_camera, + "device_id": self.config.ego_view_device_id, + } + + if self.config.head_camera is not None: + camera_configs[CameraMountPosition.HEAD.value] = { + "camera_type": self.config.head_camera, + "device_id": self.config.head_device_id, + } + + if self.config.left_wrist_camera is not None: + camera_configs[CameraMountPosition.LEFT_WRIST.value] = { + "camera_type": self.config.left_wrist_camera, + "device_id": self.config.left_wrist_device_id, + } + + if self.config.right_wrist_camera is not None: + camera_configs[CameraMountPosition.RIGHT_WRIST.value] = { + "camera_type": self.config.right_wrist_camera, + "device_id": self.config.right_wrist_device_id, + } + + return camera_configs + + def _camera_worker_wrapper( + self, + mount_position: str, + camera_type: str, + device_id: Optional[str], + image_queue: queue.Queue, + shutdown_event: threading.Event, + error_event: threading.Event, + ): + """Worker thread that continuously captures from a single camera""" + try: + camera = self._instantiate_camera(mount_position, camera_type, device_id) + self._observation_spaces[mount_position] = camera.observation_space() + + consecutive_failures = 0 + max_consecutive_failures = 5 + + while not shutdown_event.is_set(): + frame = camera.read() + if frame: + consecutive_failures = 0 # Reset on successful read + # Non-blocking queue put with frame dropping + try: + image_queue.put_nowait(frame) + except queue.Full: + # Remove oldest frame and add new one + try: + image_queue.get_nowait() + image_queue.put_nowait(frame) + except queue.Empty: + pass + else: + consecutive_failures += 1 + if consecutive_failures >= max_consecutive_failures: + error_msg = ( + f"Camera {mount_position} ({camera_type}) dropped: " + f"failed to read {consecutive_failures} consecutive frames" + ) + print(f"[ERROR] {error_msg}") + self.error_messages[mount_position] = error_msg + error_event.set() + break + + camera.close() + + except Exception as e: + error_msg = f"Camera {mount_position} ({camera_type}) error: {str(e)}" + print(f"[ERROR] {error_msg}") + self.error_messages[mount_position] = error_msg + error_event.set() + + def _instantiate_camera( + self, mount_position: str, camera_type: str, device_id: Optional[str] = None + ) -> Sensor: + """ + Instantiate a camera sensor based on the camera type. + + Args: + camera_type: Type of camera ("oak", "oak_mono", "realsense", "zed") + device_id: Optional device ID for the camera (used for OAK cameras) + + Returns: + Sensor instance for the specified camera type + """ + if camera_type in ("oak", "oak_mono"): + from decoupled_wbc.control.sensor.oak import OAKConfig, OAKSensor + + oak_config = OAKConfig() + if camera_type == "oak_mono": + oak_config.enable_mono_cameras = True + print("Initializing OAK sensor for camera type: ", camera_type) + return OAKSensor(config=oak_config, mount_position=mount_position, device_id=device_id) + elif camera_type == "realsense": + from decoupled_wbc.control.sensor.realsense import RealSenseSensor + + print("Initializing RealSense sensor for camera type: ", camera_type) + return RealSenseSensor(mount_position=mount_position) + elif camera_type == "zed": + from decoupled_wbc.control.sensor.zed import ZEDSensor + + print("Initializing ZED sensor for camera type: ", camera_type) + return ZEDSensor(mount_position=mount_position) + elif camera_type.endswith(".mp4"): + from decoupled_wbc.control.sensor.dummy import ReplayDummySensor + + print("Initializing Replay Dummy Sensor for camera type: ", camera_type) + return ReplayDummySensor(video_path=camera_type) + else: + raise ValueError(f"Unsupported camera type: {camera_type}") + + def _check_for_errors(self): + """Check if any camera thread has encountered an error and raise exception if so.""" + for mount_position, error_event in self.error_events.items(): + if error_event.is_set(): + error_msg = self.error_messages.get( + mount_position, f"Camera {mount_position} encountered an unknown error" + ) + raise RuntimeError(error_msg) + + def read(self): + """Read frames from all cameras.""" + # Check for errors from camera threads + self._check_for_errors() + + message = {} + for mount_position, camera_queue in self.camera_queues.items(): + frame = self._get_latest_from_queue(camera_queue) + if frame is not None: + message[mount_position] = frame + return message + + def _get_latest_from_queue(self, camera_queue: queue.Queue) -> Optional[Dict[str, Any]]: + """Get most recent frame, discard older ones""" + latest = None + try: + while True: + latest = camera_queue.get_nowait() + except queue.Empty: + pass + return latest + + def close(self): + """Close all cameras.""" + # Signal all worker threads to shutdown + for shutdown_event in self.shutdown_events.values(): + shutdown_event.set() + + # Wait for all threads to finish + for thread in self.camera_threads.values(): + thread.join(timeout=5.0) + + # Clear queues + for camera_queue in self.camera_queues.values(): + try: + while True: + camera_queue.get_nowait() + except queue.Empty: + pass + + # Stop server if running + if self.config.run_as_server: + self.stop_server() + + def serialize_message(self, message: Dict[str, Any]) -> Dict[str, Any]: + """Merge all camera data into a single ImageMessageSchema.""" + all_timestamps = {} + all_images = {} + + for _, camera_data in message.items(): + all_timestamps.update(camera_data.get("timestamps", {})) + all_images.update(camera_data.get("images", {})) + + # Create a single ImageMessageSchema with all data + img_schema = ImageMessageSchema(timestamps=all_timestamps, images=all_images) + return img_schema.serialize() + + def run_server(self): + """Run the server.""" + idx = 0 + server_start_time = time.monotonic() + fps_print_time = time.monotonic() + frame_interval = 1.0 / self.config.fps + + while True: + # Calculate when this frame should ideally complete + target_time = server_start_time + (idx + 1) * frame_interval + + message = self.read() + if message: + if self.config.test_latency: + read_qr_code(message) + + serialized_message = self.serialize_message(message) + self.send_message(serialized_message) + idx += 1 + + if idx % 10 == 0: + print(f"Image sending FPS: {10 / (time.monotonic() - fps_print_time):.2f}") + fps_print_time = time.monotonic() + + # Sleep to maintain precise timing + current_time = time.monotonic() + sleep_time = target_time - current_time + if sleep_time > 0: + time.sleep(sleep_time) + else: + # If we're behind, increment idx to stay on schedule + if not message: + idx += 1 + + def observation_space(self): + """Return the observation space.""" + import gymnasium as gym + + return gym.spaces.Dict(self._observation_spaces) + + +class ComposedCameraClientSensor(Sensor, SensorClient): + """Class that serves as client for multiple different cameras.""" + + def __init__(self, server_ip: str = "localhost", port: int = 5555): + self.start_client(server_ip, port) + + # Initialize tracking variables + self._latest_message = {} + self._avg_time_per_frame = deque(maxlen=20) + self._msg_received_time = 0 + self._start_time = 0.0 # Initialize _start_time + self.idx = 0 + + print("Initialized composed camera client sensor") + + def read(self, **kwargs) -> Optional[Dict[str, Any]]: + self._start_time = time.time() + message = self.receive_message() + if not message: + return None + self.idx += 1 + + self._latest_message = ImageMessageSchema.deserialize(message).asdict() + + # if self.idx % 10 == 0: + # for image_key, image_time in self._latest_message["timestamps"].items(): + # image_latency = (time.time() - image_time) * 1000 + # print(f"Image latency for {image_key}: {image_latency:.2f} ms") + + self._msg_received_time = time.time() + self._avg_time_per_frame.append(self._msg_received_time - self._start_time) + + return self._latest_message + + def close(self): + """Close the client connection.""" + self.stop_client() + + def fps(self) -> float: + """Get the current FPS of the client.""" + if len(self._avg_time_per_frame) == 0: + return 0.0 + return float(1 / np.mean(self._avg_time_per_frame)) + + +if __name__ == "__main__": + """Test function for ComposedCamera.""" + import tyro + + config = tyro.cli(ComposedCameraConfig) + + if config.run_as_server: + composed_camera = ComposedCameraSensor(config) + print("Running composed camera server...") + composed_camera.run_server() + + else: + # Client mode + composed_client = ComposedCameraClientSensor(server_ip="localhost", port=config.port) + + try: + while True: + data = composed_client.read() + if data is not None: + print(f"FPS: {composed_client.fps():.2f}") + if "timestamp" in data: + print(f"Timestamp: {data['timestamp']}") + time.sleep(0.1) + except KeyboardInterrupt: + print("Stopping client...") + composed_client.close() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/oak.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/oak.py new file mode 100644 index 0000000000000000000000000000000000000000..ae7b532b8f03135e262801c42ad254bf49dca5d2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/oak.py @@ -0,0 +1,324 @@ +import time +from typing import Any, Dict, Optional, Tuple + +import cv2 +import depthai as dai +import gymnasium as gym +import numpy as np + +from decoupled_wbc.control.base.sensor import Sensor +from decoupled_wbc.control.sensor.sensor_server import ( + CameraMountPosition, + ImageMessageSchema, + SensorServer, +) + + +class OAKConfig: + """Configuration for the OAK camera.""" + + color_image_dim: Tuple[int, int] = (640, 480) # RGB camera resolution + monochrome_image_dim: Tuple[int, int] = (640, 480) # Monochrome camera resolution + fps: int = 30 + enable_color: bool = True # Enable CAM_A (RGB) + enable_mono_cameras: bool = False # Enable CAM_B & CAM_C (Monochrome stereo pair) + mount_position: str = CameraMountPosition.EGO_VIEW.value + + +class OAKSensor(Sensor, SensorServer): + """Sensor for the OAK camera family.""" + + def __init__( + self, + run_as_server: bool = False, + port: int = 5555, + config: OAKConfig = OAKConfig(), + device_id: Optional[str] = None, + mount_position: str = CameraMountPosition.EGO_VIEW.value, + ): + """Initialize the OAK camera.""" + self.config = config + self.mount_position = mount_position + self._run_as_server = run_as_server + + device_infos = dai.Device.getAllAvailableDevices() + assert len(device_infos) > 0, f"No OAK devices found for {mount_position}" + print(f"Device infos: {device_infos}") + if device_id is not None: + device_found = False + for device_info in device_infos: + if device_info.getDeviceId() == device_id: + self.device = dai.Device(device_info) + device_found = True + break + if not device_found: + raise ValueError(f"Device with ID {device_id} not found") + else: + self.device = dai.Device() + + print(f"Connected to OAK device: {self.device.getDeviceName(), self.device.getDeviceId()}") + print(f"Device ID: {self.device.getDeviceId()}") + + sockets: list[dai.CameraBoardSocket] = self.device.getConnectedCameras() + print(f"Available cameras: {[str(s) for s in sockets]}") + + # Create pipeline (without context manager to persist across method calls) + self.pipeline = dai.Pipeline(self.device) + self.output_queues = {} + + # Configure RGB camera (CAM_A) + if config.enable_color and dai.CameraBoardSocket.CAM_A in sockets: + self.cam_rgb = self.pipeline.create(dai.node.Camera) + cam_socket = dai.CameraBoardSocket.CAM_A + self.cam_rgb = self.cam_rgb.build(cam_socket) + # Create RGB output queue + self.output_queues["color"] = self.cam_rgb.requestOutput( + config.color_image_dim, + fps=config.fps, + ).createOutputQueue() + print("Enabled CAM_A (RGB)") + + # Configure Monochrome cameras (CAM_B & CAM_C) + if config.enable_mono_cameras: + if dai.CameraBoardSocket.CAM_B in sockets: + self.cam_mono_left = self.pipeline.create(dai.node.Camera) + cam_socket = dai.CameraBoardSocket.CAM_B + self.cam_mono_left = self.cam_mono_left.build(cam_socket) + # Create mono left output queue + self.output_queues["mono_left"] = self.cam_mono_left.requestOutput( + config.monochrome_image_dim, + fps=config.fps, + ).createOutputQueue() + print("Enabled CAM_B (Monochrome Left)") + + if dai.CameraBoardSocket.CAM_C in sockets: + self.cam_mono_right = self.pipeline.create(dai.node.Camera) + cam_socket = dai.CameraBoardSocket.CAM_C + self.cam_mono_right = self.cam_mono_right.build(cam_socket) + # Create mono right output queue + self.output_queues["mono_right"] = self.cam_mono_right.requestOutput( + config.monochrome_image_dim, + fps=config.fps, + ).createOutputQueue() + print("Enabled CAM_C (Monochrome Right)") + + assert len(self.output_queues) > 0, "No output queues enabled" + # auto exposure compensation, for CoRL demo + # cam_q_in = self.cam_rgb.inputControl.createInputQueue() + # ctrl = dai.CameraControl() + # ctrl.setAutoExposureEnable() + # ctrl.setAutoExposureCompensation(-2) + # cam_q_in.send(ctrl) + + # Start pipeline on device + self.pipeline.start() + + if run_as_server: + self.start_server(port) + + def read(self) -> Optional[Dict[str, Any]]: + """Read images from the camera.""" + if not self.pipeline.isRunning(): + print(f"[ERROR] OAK pipeline stopped for {self.mount_position}") + return None + + # Check if device is still connected + if not self.device.isPipelineRunning(): + print(f"[ERROR] OAK device disconnected for {self.mount_position}") + return None + + timestamps = {} + images = {} + rgb_frame_time = None + + # Get color frame if enabled + if "color" in self.output_queues: + try: + rgb_frame = self.output_queues["color"].get() + rgb_frame_time = rgb_frame.getTimestamp() + if rgb_frame is not None: + images[self.mount_position] = rgb_frame.getCvFrame()[..., ::-1] # BGR to RGB + timestamps[self.mount_position] = ( + rgb_frame_time - dai.Clock.now() + ).total_seconds() + time.time() + except Exception as e: + print(f"[ERROR] Failed to read color frame from {self.mount_position}: {e}") + return None + + # Get mono frames if enabled + if "mono_left" in self.output_queues: + try: + mono_left_frame = self.output_queues["mono_left"].get() + mono_left_frame_time = mono_left_frame.getTimestamp() + if mono_left_frame is not None: + key = f"{self.mount_position}_left_mono" + images[key] = mono_left_frame.getCvFrame() + timestamps[key] = ( + mono_left_frame_time - dai.Clock.now() + ).total_seconds() + time.time() + except Exception as e: + print(f"[ERROR] Failed to read mono_left frame from {self.mount_position}: {e}") + return None + + if "mono_right" in self.output_queues: + try: + mono_right_frame = self.output_queues["mono_right"].get() + mono_right_frame_time = mono_right_frame.getTimestamp() + if mono_right_frame is not None: + key = f"{self.mount_position}_right_mono" + images[key] = mono_right_frame.getCvFrame() + timestamps[key] = ( + mono_right_frame_time - dai.Clock.now() + ).total_seconds() + time.time() + except Exception as e: + print(f"[ERROR] Failed to read mono_right frame from {self.mount_position}: {e}") + return None + + if ( + rgb_frame_time is not None + and (rgb_frame_time - dai.Clock.now()).total_seconds() <= -0.2 + ): + print( + f"[{self.mount_position}] OAK latency too large: " + f"{(dai.Clock.now() - rgb_frame_time).total_seconds() * 1000}ms" + ) + + return { + "timestamps": timestamps, + "images": images, + } + + def serialize(self, data: Dict[str, Any]) -> Dict[str, Any]: + """Serialize data using ImageMessageSchema.""" + serialized_msg = ImageMessageSchema(timestamps=data["timestamps"], images=data["images"]) + return serialized_msg.serialize() + + def observation_space(self) -> gym.Space: + spaces = {} + + if self.config.enable_color: + spaces["color_image"] = gym.spaces.Box( + low=0, + high=255, + shape=(self.config.color_image_dim[1], self.config.color_image_dim[0], 3), + dtype=np.uint8, + ) + + if self.config.enable_mono_cameras: + spaces["mono_left_image"] = gym.spaces.Box( + low=0, + high=255, + shape=(self.config.monochrome_image_dim[1], self.config.monochrome_image_dim[0]), + dtype=np.uint8, + ) + spaces["mono_right_image"] = gym.spaces.Box( + low=0, + high=255, + shape=(self.config.monochrome_image_dim[1], self.config.monochrome_image_dim[0]), + dtype=np.uint8, + ) + + return gym.spaces.Dict(spaces) + + def close(self): + """Close the camera connection.""" + if self._run_as_server: + self.stop_server() + if hasattr(self, "pipeline") and self.pipeline.isRunning(): + self.pipeline.stop() + self.device.close() + + def run_server(self): + """Run the server.""" + if not self._run_as_server: + raise ValueError("This function is only available when run_as_server is True") + + while True: + frame = self.read() + if frame is None: + continue + + msg = self.serialize(frame) + self.send_message({self.mount_position: msg}) + + def __del__(self): + self.close() + + +if __name__ == "__main__": + """Test function for OAK camera.""" + + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--server", action="store_true", help="Run as server") + parser.add_argument("--client", action="store_true", help="Run as client") + parser.add_argument("--host", type=str, default="localhost", help="Server IP address") + parser.add_argument("--port", type=int, default=5555, help="Port number") + parser.add_argument("--device-id", type=str, default=None, help="Specific device ID") + parser.add_argument( + "--enable-mono", action="store_true", help="Enable monochrome cameras (CAM_B & CAM_C)" + ) + parser.add_argument("--mount-position", type=str, default="ego_view", help="Mount position") + parser.add_argument("--show-image", action="store_true", help="Display images") + args = parser.parse_args() + + oak_config = OAKConfig() + if args.enable_mono: + oak_config.enable_mono_cameras = True + + if args.server: + # Run as server + oak = OAKSensor( + run_as_server=True, + port=args.port, + config=oak_config, + device_id=args.device_id, + mount_position=args.mount_position, + ) + print(f"Starting OAK server on port {args.port}") + oak.run_server() + + else: + # Run standalone + oak = OAKSensor(run_as_server=False, config=oak_config, device_id=args.device_id) + print("Running OAK camera in standalone mode") + + while True: + frame = oak.read() + if frame is None: + print("Waiting for frame...") + time.sleep(0.5) + continue + + if "color_image" in frame: + print(f"Color image shape: {frame['color_image'].shape}") + if "mono_left_image" in frame: + print(f"Mono left image shape: {frame['mono_left_image'].shape}") + if "mono_right_image" in frame: + print(f"Mono right image shape: {frame['mono_right_image'].shape}") + if "depth_image" in frame: + print(f"Depth image shape: {frame['depth_image'].shape}") + + if args.show_image: + if "color_image" in frame: + cv2.imshow("Color Image", frame["color_image"]) + + if "mono_left_image" in frame: + cv2.imshow("Mono Left", frame["mono_left_image"]) + if "mono_right_image" in frame: + cv2.imshow("Mono Right", frame["mono_right_image"]) + + if "depth_image" in frame: + depth_colormap = cv2.applyColorMap( + cv2.convertScaleAbs(frame["depth_image"], alpha=0.03), cv2.COLORMAP_JET + ) + cv2.imshow("Depth Image", depth_colormap) + + if cv2.waitKey(1) == ord("q"): + break + + time.sleep(0.01) + + cv2.destroyAllWindows() + oak.close() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/sensor_server.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/sensor_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28453377963567928c5a54c9e44662bfa9650df2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/sensor/sensor_server.py @@ -0,0 +1,128 @@ +import base64 +from dataclasses import dataclass +from enum import Enum +from typing import Any, Dict + +import cv2 +import msgpack +import msgpack_numpy as m +import numpy as np +import zmq + + +@dataclass +class ImageMessageSchema: + """ + This is a standardized message schema for image data. + Any camera should use this schema to serialize (send to queue) and + deserialize (receive from queue) the image data. + + """ + + timestamps: Dict[str, float] + """Dictionary of timestamps, keyed by image identifier (e.g., {"ego_view": 123.45})""" + images: Dict[str, np.ndarray] + """Dictionary of images, keyed by image identifier (e.g., {"ego_view": array, "ego_view_left_mono": array})""" + + def serialize(self) -> Dict[str, Any]: + """Serialize the message for transmission.""" + serialized_msg = {"timestamps": self.timestamps, "images": {}} + for key, image in self.images.items(): + serialized_msg["images"][key] = ImageUtils.encode_image(image) + return serialized_msg + + @staticmethod + def deserialize(data: Dict[str, Any]) -> "ImageMessageSchema": + """Deserialize received message data.""" + timestamps = data.get("timestamps", {}) + images = {} + for key, value in data.get("images", {}).items(): + if isinstance(value, str): + images[key] = ImageUtils.decode_image(value) + else: + images[key] = value + return ImageMessageSchema(timestamps=timestamps, images=images) + + def asdict(self) -> Dict[str, Any]: + """Convert to dictionary format.""" + return {"timestamps": self.timestamps, "images": self.images} + + +class SensorServer: + def start_server(self, port: int): + self.context = zmq.Context() + self.socket = self.context.socket(zmq.PUB) + self.socket.setsockopt(zmq.SNDHWM, 20) # high water mark + self.socket.setsockopt(zmq.LINGER, 0) + self.socket.bind(f"tcp://*:{port}") + print(f"Sensor server running at tcp://*:{port}") + + self.message_sent = 0 + self.message_dropped = 0 + + def stop_server(self): + self.socket.close() + self.context.term() + + def send_message(self, data: Dict[str, Any]): + try: + packed = msgpack.packb(data, use_bin_type=True) + self.socket.send(packed, flags=zmq.NOBLOCK) + except zmq.Again: + self.message_dropped += 1 + print(f"[Warning] message dropped: {self.message_dropped}") + self.message_sent += 1 + + if self.message_sent % 100 == 0: + print( + f"[Sensor server] Message sent: {self.message_sent}, message dropped: {self.message_dropped}" + ) + + +class SensorClient: + def start_client(self, server_ip: str, port: int): + self.context = zmq.Context() + self.socket = self.context.socket(zmq.SUB) + self.socket.setsockopt_string(zmq.SUBSCRIBE, "") + self.socket.setsockopt(zmq.CONFLATE, True) # last msg only. + self.socket.setsockopt(zmq.RCVHWM, 3) # queue size 3 for receive buffer + self.socket.connect(f"tcp://{server_ip}:{port}") + + def stop_client(self): + self.socket.close() + self.context.term() + + def receive_message(self): + packed = self.socket.recv() + return msgpack.unpackb(packed, object_hook=m.decode) + + +class CameraMountPosition(Enum): + EGO_VIEW = "ego_view" + HEAD = "head" + LEFT_WRIST = "left_wrist" + RIGHT_WRIST = "right_wrist" + + +class ImageUtils: + @staticmethod + def encode_image(image: np.ndarray) -> str: + _, color_buffer = cv2.imencode(".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), 80]) + return base64.b64encode(color_buffer).decode("utf-8") + + @staticmethod + def encode_depth_image(image: np.ndarray) -> str: + depth_compressed = cv2.imencode(".png", image)[1].tobytes() + return base64.b64encode(depth_compressed).decode("utf-8") + + @staticmethod + def decode_image(image: str) -> np.ndarray: + color_data = base64.b64decode(image) + color_array = np.frombuffer(color_data, dtype=np.uint8) + return cv2.imdecode(color_array, cv2.IMREAD_COLOR) + + @staticmethod + def decode_depth_image(image: str) -> np.ndarray: + depth_data = base64.b64decode(image) + depth_array = np.frombuffer(depth_data, dtype=np.uint8) + return cv2.imdecode(depth_array, cv2.IMREAD_UNCHANGED) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientLogging.hpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientLogging.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a7469d706945cadaa8bc238926d81406f130ad56 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientLogging.hpp @@ -0,0 +1,158 @@ +#ifndef __CLIENT_LOGGING_HPP__ +#define __CLIENT_LOGGING_HPP__ +#include +#include +#include +#include + +namespace ManusSDK +{ + class ClientLog + { + public: + //Simple + static void debug(const char* p_String) + { + std::cout << "DEBUG: " << p_String << std::endl; + } + + static void info(const char* p_String) + { + std::cout << "INFO: " << p_String << std::endl; + } + + static void warn(const char* p_String) + { + std::cout << "WARN: " << p_String << std::endl; + } + + static void error(const char* p_String) + { + std::cout << "ERROR: " << p_String << std::endl; + } + + static void print(const char* p_String) + { + std::cout << p_String << std::endl; + } + + //Templated + template + static void debug(const char* p_Format, Args &&...p_Args) + { + std::string formatted_string = p_Format; + replacePlaceholders(formatted_string, std::forward(p_Args)...); + std::cout << "DEBUG: " << formatted_string << std::endl; + } + + template + static void info(const char* p_Format, Args &&...p_Args) + { + std::string formatted_string = p_Format; + replacePlaceholders(formatted_string, std::forward(p_Args)...); + std::cout << "INFO: " << formatted_string << std::endl; + } + + template + static void warn(const char* p_Format, Args &&...p_Args) + { + std::string formatted_string = p_Format; + replacePlaceholders(formatted_string, std::forward(p_Args)...); + std::cout << "WARN: " << formatted_string << std::endl; + } + + template + static void error(const char* p_Format, Args &&...p_Args) + { + std::string formatted_string = p_Format; + replacePlaceholders(formatted_string, std::forward(p_Args)...); + std::cout << "ERROR: " << formatted_string << std::endl; + } + + template + static void print(const char* p_Format, Args &&...p_Args) + { + std::string formatted_string = p_Format; + replacePlaceholders(formatted_string, std::forward(p_Args)...); + std::cout << formatted_string << std::endl; + } + + template + static void printWithPadding(const char* p_Format, int p_Padding, Args &&...p_Args) + { + std::string formatted_string = p_Format; + replacePlaceholdersWithPadding(formatted_string, p_Padding, std::forward(p_Args)...); + std::cout << formatted_string << std::endl; + } + + private: + // Base case for recursion: no arguments left + static void replacePlaceholders(std::string&) { + // No more arguments, so nothing to replace + } + + // Replace placeholders {} with actual values (only supports empty curly brackets, no formatting) + template + static void replacePlaceholders(std::string& p_Format, T&& p_Value, Args&&... p_Args) { + size_t pos = p_Format.find("{}"); + if (pos != std::string::npos) { + p_Format.replace(pos, 2, to_string(std::forward(p_Value))); + replacePlaceholders(p_Format, std::forward(p_Args)...); + } + } + + // Base case for recursion: no arguments left + static void replacePlaceholdersWithPadding(std::string&, int p_Padding) { + // No more arguments, so nothing to replace + } + // Replace placeholders {} with actual values (only supports empty curly brackets, no formatting) + template + static void replacePlaceholdersWithPadding(std::string& p_Format, int p_Padding, T&& p_Value, Args&&... p_Args) { + size_t pos = p_Format.find("{}"); + if (pos != std::string::npos) { + std::ostringstream oss; + oss << std::setw(p_Padding) << to_string(std::forward(p_Value)); + p_Format.replace(pos, 2, oss.str()); + replacePlaceholdersWithPadding(p_Format, p_Padding, std::forward(p_Args)...); + } + } + + // Utility to convert various types to string + template + static std::string to_string(const T& p_Value) { + std::ostringstream oss; + oss << p_Value; + return oss.str(); + } + + // Specialization for uint8_t + static std::string to_string(const uint8_t& p_Value) { + std::ostringstream oss; + oss << static_cast(p_Value); + return oss.str(); + } + + // Specialization for uint16_t + static std::string to_string(const uint16_t& p_Value) { + std::ostringstream oss; + oss << static_cast(p_Value); + return oss.str(); + } + + // Specialization for uint32_t + static std::string to_string(const uint32_t& p_Value) { + std::ostringstream oss; + oss << std::hex << p_Value; + return oss.str(); + } + + // Specialization for bool + static std::string to_string(const bool& p_Value) { + std::ostringstream oss; + oss << std::setw(5) << (p_Value ? "true" : "false"); + return oss.str(); + } + }; +} + +#endif diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.cpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c702818fee1ea5a6edadae910d4962859af9394 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.cpp @@ -0,0 +1,559 @@ +#include "ClientPlatformSpecific.hpp" + +// signal types +#include +// std::filesystem +#include +// std::*fstream +#include +// CoreSdk_ShutDown +#include "ManusSDK.h" +// std::map +#include +// Ncurses terminal functions. +#include +// Termios terminal functions. +#include +#include +#include +// spdlog replacement +#include "ClientLogging.hpp" + +using namespace ManusSDK; + +/// @brief Reset a signal handler to its default, and then call it. +/// For signal types and explanation, see: +/// https://www.gnu.org/software/libc/manual/html_node/Standard-Signals.html +#define CALL_DEFAULT_SIGNAL_HANDLER(p_SignalType) \ + /* Reset the handler for this signal to the default. */ \ + signal(p_SignalType, SIG_DFL); \ + /* Re-raise this signal, causing the normal handler to run. */ \ + raise(p_SignalType); + +const std::string SDKClientPlatformSpecific::s_SlashForFilesystemPath = "/"; + +/// @brief Handle a signal telling the SDK client to quit. +/// A generic signal used to "politely ask a program to terminate". +/// On Linux, this can be sent by using the Gnome System Monitor and telling +/// the SDK client process to end. +static void HandleTerminationSignal(int p_Parameter) +{ + ClientLog::error( + "Termination signal sent with parameter {}.", + p_Parameter); + + CoreSdk_ShutDown(); + + CALL_DEFAULT_SIGNAL_HANDLER(SIGTERM); +} + +/// @brief Handle an interrupt signal. +/// Called when the INTR character is typed - usually ctrl + c. +static void HandleInterruptSignal(int p_Parameter) +{ + ClientLog::error( + "Interrupt signal sent with parameter {}.", + p_Parameter); + + CoreSdk_ShutDown(); + + CALL_DEFAULT_SIGNAL_HANDLER(SIGINT); +} + +/// @brief Handle a quit signal. +/// Called when the QUIT character is typed - usually ctrl + \. +static void HandleQuitSignal(int p_Parameter) +{ + ClientLog::error( + "Quit signal sent with parameter {}.", + p_Parameter); + + CoreSdk_ShutDown(); + + CALL_DEFAULT_SIGNAL_HANDLER(SIGQUIT); +} + +/// @brief Handle a hangup signal. +/// Called to report that the user's terminal has disconnected. +/// This can happen when connecting over the network, for example. +/// It also happens if the terminal window is closed while debugging. +static void HandleHangupSignal(int p_Parameter) +{ + ClientLog::error( + "Hang-up signal sent with parameter {}.", + p_Parameter); + + CoreSdk_ShutDown(); + + CALL_DEFAULT_SIGNAL_HANDLER(SIGHUP); +} + +/// @brief Initialise Ncurses so that we can check for input. +static bool InitializeNcurses(void) +{ + const WINDOW* const t_Window = initscr(); + if (!t_Window) + { + ClientLog::error("Failed to initialise the screen."); + + return false; + } + + // Don't buffer input until a newline or carriage return is typed. + if (cbreak() != OK) + { + ClientLog::error("Failed to make input unbuffered."); + + return false; + } + + // Don't echo input. + if (noecho() != OK) + { + ClientLog::error("Failed to disable input echoing."); + + return false; + } + + // Don't make newlines when the return key is pressed. + if (nonl() != OK) + { + ClientLog::error("Failed to disable newlines."); + + return false; + } + + // Do not flush the screen when interrupt/break/quit is pressed. + if (intrflush(stdscr, FALSE) != OK) + { + ClientLog::error("Failed to disable screen flushing."); + + return false; + } + + // Make getch non-blocking. + if (nodelay(stdscr, TRUE) != OK) + { + ClientLog::error("Failed to make nodelay non-blocking."); + + return false; + } + + // Enable handling the keypad ("function keys" like the arrow keys). + if (keypad(stdscr, TRUE) != OK) + { + ClientLog::error("Failed to enable keypad input."); + + return false; + } + + return true; +} + +/// @brief Initialise Termios so that terminal output is correct. +static bool InitializeTermios(void) +{ + // For some reason, printf and spdlog strings require a carriage return + // in addition to a newline after running initscr(). + // This code sets the "output modes" flag to treat newline characters + // as newline+carriage-return characters. + // https://arstechnica.com/civis/viewtopic.php?t=70699 + termios t_Settings; + if (tcgetattr(STDIN_FILENO, &t_Settings) != 0) + { + ClientLog::error("Failed to get Termios settings."); + + return false; + } + + t_Settings.c_oflag |= ONLCR; + if (tcsetattr(0, TCSANOW, &t_Settings) != 0) + { + ClientLog::error("Failed to set Termios settings."); + + return false; + } + + return true; +} + +/// @brief Register our signal handling functions. +static bool SetUpSignalHandlers(void) +{ + { + const __sighandler_t t_OldTerminationHandler = signal( + SIGTERM, + HandleTerminationSignal); + if (t_OldTerminationHandler == SIG_ERR) + { + ClientLog::error("Failed to set termination signal handler."); + return false; + } + } + + { + const __sighandler_t t_OldInterruptHandler = signal( + SIGINT, + HandleInterruptSignal); + if (t_OldInterruptHandler == SIG_ERR) + { + ClientLog::error("Failed to set interrupt signal handler."); + return false; + } + } + + { + const __sighandler_t t_OldQuitHandler = signal( + SIGQUIT, + HandleQuitSignal); + if (t_OldQuitHandler == SIG_ERR) + { + ClientLog::error("Failed to set quit signal handler."); + return false; + } + } + + { + const __sighandler_t t_OldHangupHandler = signal( + SIGHUP, + HandleHangupSignal); + if (t_OldHangupHandler == SIG_ERR) + { + ClientLog::error("Failed to set hang-up signal handler."); + return false; + } + } + + return true; +} + +/// @brief Handles keyboard input. +/// Requires things to be set up with Ncurses and Termios. +class ClientInput +{ +public: + /// @brief Update the state of the keyboard. + void Update(void) + { + // Reset the state of the last update. + for ( + InputMap_t::iterator t_Key = m_PressedLastUpdate.begin(); + t_Key != m_PressedLastUpdate.end(); + t_Key++) + { + t_Key->second = false; + } + + // Copy the current state to the last update's state, and clear the + // current state. + for ( + InputMap_t::iterator t_Key = m_CurrentlyPressed.begin(); + t_Key != m_CurrentlyPressed.end(); + t_Key++) + { + m_PressedLastUpdate[t_Key->first] = + t_Key->second; + t_Key->second = false; + } + + // Get the new state. + int t_Ch = getch(); + while (t_Ch != ERR) + { + if (t_Ch >= 'a' && t_Ch <= 'z') + { + // Unlike with Windows' GetAsyncKeyState(), upper case and + // lower case characters have different key numbers with + // getch(). + // Since all WasKeyPressed calls (as of writing this) use + // upper case, lower case keys need to be converted to work + // on Linux. + // Note that this does break the ability to check for lower + // case key presses. + t_Ch = toupper(t_Ch); + } + + m_CurrentlyPressed[t_Ch] = true; + + t_Ch = getch(); + } + } + + /// @brief Get the key's current state. + /// Note that unlike IsPressed(), this also stores the result for use in + /// the next key state check. + bool GetKey(const int p_Key) + { + bool t_IsPressed = IsPressed(p_Key); + m_PreviousKeyState[p_Key] = t_IsPressed; + + return t_IsPressed; + } + + /// @brief Was this key pressed since the last check? + /// Note that unlike WasJustPressed(), this checks if the key was pressed + /// since the last time a GetKey* function was called. + bool GetKeyDown(const int p_Key) + { + const bool t_IsPressed = IsPressed(p_Key); + + const auto t_PreviousState = m_PreviousKeyState.find(p_Key); + const bool t_PreviousValue = + t_PreviousState == m_PreviousKeyState.end() + ? false + : t_PreviousState->second; + + const bool t_Down = t_IsPressed && !t_PreviousValue; + m_PreviousKeyState[p_Key] = t_Down; + + return t_Down; + } + + /// @brief Was this key released since the last check? + /// Note that unlike WasJustReleased(), this checks if the key was released + /// since the last time a GetKey* function was called. + bool GetKeyUp(const int p_Key) + { + const bool t_IsPressed = IsPressed(p_Key); + + const auto t_PreviousState = m_PreviousKeyState.find(p_Key); + const bool t_PreviousValue = + t_PreviousState == m_PreviousKeyState.end() + ? false + : t_PreviousState->second; + + const bool t_Up = !t_IsPressed && t_PreviousValue; + m_PreviousKeyState[p_Key] = t_Up; + + return t_Up; + } + +private: + /// @brief Get the key's current state. + /// Note that unlike GetKey(), this does not store the result for use in + /// the next key state check. + bool IsPressed(const int p_Key) const + { + auto t_CurrentlyPressed = m_CurrentlyPressed.find(p_Key); + if (t_CurrentlyPressed == m_CurrentlyPressed.end()) + { + return false; + } + + return t_CurrentlyPressed->second; + } + + /// @brief Was this key pressed since the last input update? + /// Note that unlike GetKeyDown(), this function will return the same value + /// until the next keyboard state update. + bool WasJustPressed(const int p_Key) const + { + return !WasPressedLastUpdate(p_Key) && IsPressed(p_Key); + } + + /// @brief Was this key released since the last input update? + /// Note that unlike GetKeyUp(), this function will return the same value + /// until the next keyboard state update. + bool WasJustReleased(const int p_Key) const + { + return WasPressedLastUpdate(p_Key) && !IsPressed(p_Key); + } + + /// @brief Was this key pressed the previous input update? + bool WasPressedLastUpdate(const int p_Key) const + { + auto t_StateLastUpdate = m_PressedLastUpdate.find(p_Key); + if (t_StateLastUpdate == m_PressedLastUpdate.end()) + { + return false; + } + + return t_StateLastUpdate->second; + } + + typedef std::map InputMap_t; + InputMap_t m_CurrentlyPressed; + InputMap_t m_PressedLastUpdate; + // The Windows GetKey* functions only update the key state when a GetKey* + // function gets called. To make the Linux input work the same way, this + // map is used. + InputMap_t m_PreviousKeyState; +}; + +static ClientInput g_Input; + +bool SDKClientPlatformSpecific::PlatformSpecificInitialization(void) +{ + const bool t_NcursesResult = InitializeNcurses(); + const bool t_TermiosResult = InitializeTermios(); + const bool t_SignalResult = SetUpSignalHandlers(); + + return t_NcursesResult && t_TermiosResult && t_SignalResult; +} + +bool SDKClientPlatformSpecific::PlatformSpecificShutdown(void) +{ + // Ncurses. + endwin(); + + return true; +} + +void SDKClientPlatformSpecific::UpdateInput(void) +{ + g_Input.Update(); +} + +/*static*/ bool SDKClientPlatformSpecific::CopyString( + char* const p_Target, + const size_t p_MaxLengthThatWillFitInTarget, + const std::string& p_Source) +{ + if (!p_Target) + { + ClientLog::error( + "Tried to copy a string, but the target was null. The string was \"{}\".", + p_Source.c_str()); + + return false; + } + + if (p_MaxLengthThatWillFitInTarget == 0) + { + ClientLog::error( + "Tried to copy a string, but the target's size is zero. The string was \"{}\".", + p_Source.c_str()); + + return false; + } + + if (p_MaxLengthThatWillFitInTarget <= p_Source.length()) + { + ClientLog::error( + "Tried to copy a string that was longer than {} characters, which makes it too big for its target buffer. The string was \"{}\".", + p_MaxLengthThatWillFitInTarget, + p_Source.c_str()); + + return false; + } + + strcpy(p_Target, p_Source.c_str()); + + return true; +} + +bool SDKClientPlatformSpecific::ResizeWindow( + const short int p_ConsoleWidth, + const short int p_ConsoleHeight, + const short int p_ConsoleScrollback) +{ + // https://apple.stackexchange.com/questions/33736/can-a-terminal-window-be-resized-with-a-terminal-command/47841#47841 + // Use a control sequence to resize the window. + // Seems to be supported by the default terminal used in Gnome, as well + // as Mac OS. + // \\e[ -> ASCII ESC character (number 27, or 0x1B) + // -> control sequence introducer + // 8; -> resize the window + // y;xt -> The first number is the height, the second the width. + // Scrollback can't and doesn't need to be set here for Linux. + printf("\e[8;%d;%dt", p_ConsoleHeight, p_ConsoleWidth); + + ClearConsole(); + + // None of the ncurses functions for resizing the terminal actually + // seem to do anything. + /*if (resizeterm(180, 180) != OK) + { + return false; + }*/ + + return true; +} + +void SDKClientPlatformSpecific::ApplyConsolePosition( + const int p_ConsoleCurrentOffset) +{ + printf("\e[%d;1H", p_ConsoleCurrentOffset); +} + +/*static*/ void SDKClientPlatformSpecific::ClearConsole(void) +{ + // https://stackoverflow.com/questions/4062045/clearing-terminal-in-linux-with-c-code + // Use a control sequence to clear the terminal and move the cursor. + // Seems to be supported by the default terminal used in Gnome, + // as well as Mac OS. + // \\e[ -> ASCII ESC character (number 27, or 0x1B) -> control sequence introducer + // 2 -> the entire screen + // J -> clear the screen + //printf("\e[2J\n"); + + // Move the cursor to row 1 column 1. + //printf("\e[1;1H\n"); + + if (clear() != OK) + { + ClientLog::error("Failed to clear the screen."); + } + + refresh(); +} + +bool SDKClientPlatformSpecific::GetKey(const int p_Key) +{ + return g_Input.GetKey(p_Key); +} + +bool SDKClientPlatformSpecific::GetKeyDown(const int p_Key) +{ + return g_Input.GetKeyDown(p_Key); +} + +bool SDKClientPlatformSpecific::GetKeyUp(const int p_Key) +{ + return g_Input.GetKeyUp(p_Key); +} + +std::string SDKClientPlatformSpecific::GetDocumentsDirectoryPath_UTF8(void) +{ + const char* const t_Xdg = getenv("XDG_DOCUMENTS_DIR"); + + // Backup - the documents folder is usually going to be in $HOME/Documents. + const char* const t_Home = getenv("HOME"); + if (!t_Xdg && !t_Home) + { + return std::string(""); + } + + const std::string t_DocumentsDir = + (!t_Xdg || strlen(t_Xdg) == 0) + ? std::string(t_Home) + std::string("/Documents") + : std::string(t_Xdg); + + return t_DocumentsDir; +} + +std::ifstream SDKClientPlatformSpecific::GetInputFileStream( + std::string p_Path_UTF8) +{ + return std::ifstream(p_Path_UTF8, std::ifstream::binary); +} + +std::ofstream SDKClientPlatformSpecific::GetOutputFileStream( + std::string p_Path_UTF8) +{ + return std::ofstream(p_Path_UTF8, std::ofstream::binary); +} + +bool SDKClientPlatformSpecific::DoesFolderOrFileExist(std::string p_Path_UTF8) +{ + return std::filesystem::exists(p_Path_UTF8); +} + +void SDKClientPlatformSpecific::CreateFolderIfItDoesNotExist( + std::string p_Path_UTF8) +{ + if (!DoesFolderOrFileExist(p_Path_UTF8)) + { + std::filesystem::create_directory(p_Path_UTF8); + } +} diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.hpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4cbbe101555e2339a779aaac8c0243641a5734ea --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecific.hpp @@ -0,0 +1,90 @@ +#ifndef _CLIENT_PLATFORM_SPECIFIC_HPP_ +#define _CLIENT_PLATFORM_SPECIFIC_HPP_ + +#include "ClientPlatformSpecificTypes.hpp" + +// size_t +#include +// std::string +#include + +// Set up a Doxygen group. +/** @addtogroup SDKClient + * @{ + */ + +class SDKClientPlatformSpecific +{ +protected: + /// @brief Initialise things only needed for this platform. + bool PlatformSpecificInitialization(void); + + /// @brief Shut down things only needed for this platform. + bool PlatformSpecificShutdown(void); + + /// @brief Update the current keyboard state. + void UpdateInput(void); + + /// @brief Copy the given string into the given target. + static bool CopyString( + char* const p_Target, + const size_t p_MaxLengthThatWillFitInTarget, + const std::string& p_Source); + + /// @brief Resize the window, so the log messages will fit. + /// Make sure not to enter illegal sizes in here or SetConsoleWindowInfo + /// and SetConsoleScreenBufferSize can generate an error. + /// This is not code directly needed for the SDK to function, but its handy + /// for a quick and simple output for this client. + bool ResizeWindow( + const short int p_ConsoleWidth, + const short int p_ConsoleHeight, + const short int p_ConsoleScrollback); + + /// @brief Set the current console position. + /// This handles the platform-specific part of advancing the console + /// position. + void ApplyConsolePosition( + const int p_ConsoleCurrentOffset); + + /// @brief Clear the console window. + static void ClearConsole(void); + + /// @brief Gets key's current state. + /// True is pressed false is not pressed. + bool GetKey(const int p_Key); + + /// @brief Returns true first time it is called when key is pressed. + bool GetKeyDown(const int p_Key); + + /// @brief Returns true first time it is called when key is released. + bool GetKeyUp(const int p_Key); + + /// @brief Get the path to the user's Documents folder. + /// The string should be in UTF-8 format. + std::string GetDocumentsDirectoryPath_UTF8(void); + + /// @brief Get an input stream for the given file. + /// The file's path should be in UTF-8 format. + std::ifstream GetInputFileStream(std::string p_Path_UTF8); + + /// @brief Get an output stream for the given file. + /// The file's path should be in UTF-8 format. + std::ofstream GetOutputFileStream(std::string p_Path_UTF8); + + /// @brief Check if the given folder or file exists. + /// The folder path given should be in UTF-8 format. + bool DoesFolderOrFileExist(std::string p_Path_UTF8); + + /// @brief Create the given folder if it does not exist. + /// The folder path given should be in UTF-8 format. + void CreateFolderIfItDoesNotExist(std::string p_Path_UTF8); + + /// @brief The slash character that is used in the filesystem. + static const std::string s_SlashForFilesystemPath; +}; + +// Close the Doxygen group. +/** @} */ + +#endif diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecificTypes.hpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecificTypes.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2c994b3f541c22344033d0b879158f9761a3d2fb --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ClientPlatformSpecificTypes.hpp @@ -0,0 +1,48 @@ +#ifndef _CLIENT_PLATFORM_SPECIFIC_TYPES_HPP_ +#define _CLIENT_PLATFORM_SPECIFIC_TYPES_HPP_ + +#include + +// Set up a Doxygen group. +/** @addtogroup SDKClient + * @{ + */ + +// Virtual key code characters for WasKeyPressed(). +// Based on key codes used with GetAsyncKeyState(). +// Manually checked what values getch() returns for these keys. +// https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes +enum MicrosoftVirtualKeyCodes +{ + VK_TAB = 9, // ASCII tab character value + VK_RETURN = 13, // ASCII carriage return character value + VK_ESCAPE = 27, // ASCII ESC character value + VK_DOWN = 258, + VK_UP = 259, + VK_LEFT = 260, + VK_RIGHT = 261, + VK_HOME = 262, + VK_BACK = 263, + VK_F1 = 265, + VK_F2 = 266, + VK_F3 = 267, + VK_F4 = 268, + VK_F5 = 269, + VK_F6 = 270, + VK_F7 = 271, + VK_F8 = 272, + VK_F9 = 273, + VK_F10 = 274, + VK_F11 = 275, + VK_F12 = 276, + VK_DELETE = 330, + VK_INSERT = 331, + VK_NEXT = 338, + VK_PRIOR = 339, + VK_END = 360 +}; + +// Close the Doxygen group. +/** @} */ + +#endif diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Dockerfile b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7e127a7738f58c328e9167936aadc83214a03c85 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Dockerfile @@ -0,0 +1,88 @@ +# Copyright 2018 gRPC authors. +# +# 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.# +# +# Based on https://hub.docker.com/r/grpc/cxx. + +# To build +# docker build -f ./Dockerfile -t manus-linux . + +# To Run (Linux) +# docker run --net==host --privileged -v /dev:/dev -v /run/udev:/run/udev -i -t manus-linux /bin/bash + +# To Run (Windows) +# docker run -p 5000:5000 -i -t manus-linux /bin/bash + +# FROM ubuntu:jammy as build +FROM ubuntu:focal as build +LABEL description="Visual Studio Manus SDK Build container" + +ENV TZ=Europe/Amsterdam +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +RUN apt-get update && apt-get install -y \ + build-essential \ + # Required to install GRPC + git \ + libtool \ + libzmq3-dev \ + # Required for core integrated + libusb-1.0-0-dev \ + libudev-dev \ + # Only required for building the minimal client + libncurses5-dev \ + # Only required for visual studio debugging + gdb \ + && apt-get clean + +ENV GRPC_RELEASE_TAG="v1.28.1" + +RUN git clone -b ${GRPC_RELEASE_TAG} https://github.com/grpc/grpc /var/local/git/grpc && \ + cd /var/local/git/grpc && \ + git submodule update --init --recursive + +RUN echo "-- installing protobuf" && \ + cd /var/local/git/grpc/third_party/protobuf && \ + ./autogen.sh && ./configure --enable-shared && \ + make -j$(nproc) && make -j$(nproc) check && make install && make clean && ldconfig + +RUN echo "-- installing grpc" && \ + cd /var/local/git/grpc && \ + make -j$(nproc) && make install && make clean && ldconfig + +# configure SSH for communication with Visual Studio +RUN apt-get update && apt-get install -y openssh-server +RUN mkdir -p /var/run/sshd +RUN echo 'PasswordAuthentication yes' >> /etc/ssh/sshd_config && \ + ssh-keygen -A + +# please make sure to change the password +RUN id -u manus >/dev/null 2>&1 || useradd -m -d /home/manus -s /bin/bash -G sudo manus && \ +echo "manus:password" | chpasswd + +# copy dependencies to ~/ManusSDK/ directory +COPY ManusSDK /home/manus/ManusSDK + +# Add read/write permissions for manus devices +RUN apt-get update && apt-get install -y udev +RUN echo "# HIDAPI/libusb" > /etc/udev/rules.d/99-manus.rules && \ + echo "SUBSYSTEMS==\"usb\", ATTRS{idVendor}==\"3325\", MODE:=\"0666\"" >> /etc/udev/rules.d/99-manus.rules && \ + echo "# HIDAPI/hidraw" >> /etc/udev/rules.d/99-manus.rules && \ + echo "KERNEL==\"hidraw*\", ATTRS{idVendor}==\"3325\", MODE:=\"0666\"" >> /etc/udev/rules.d/99-manus.rules + +# change default SSH port to 5000 to not conflict with system ssh in host mode +RUN echo "Port 5000" >> /etc/ssh/sshd_config + +ENTRYPOINT service ssh start && service udev start && bin/bash + +EXPOSE 5000 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Dockerfile.Integrated b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Dockerfile.Integrated new file mode 100644 index 0000000000000000000000000000000000000000..0a810e80bb4b504d1bbc8d543ea148b75719e0f2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Dockerfile.Integrated @@ -0,0 +1,69 @@ +# Copyright 2018 gRPC authors. +# +# 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.# +# +# Based on https://hub.docker.com/r/grpc/cxx. + +# To build +# docker build -f ./Dockerfile.Integrated -t manus-linux-integrated . + +# To Run (Linux) +# docker run -p 5000:5000 --privileged -v /dev:/dev -v /run/udev:/run/udev -i -t manus-linux-integrated /bin/bash + +# To Run (Windows) +# docker run -p 5000:5000 -i -t manus-linux-integrated /bin/bash + +# FROM ubuntu:jammy as build +FROM ubuntu:focal as build +LABEL description="Visual Studio Manus SDK Build container" + +ENV TZ=Europe/Amsterdam +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +RUN apt-get update && apt-get install -y \ + build-essential \ + # Required for core integrated + libusb-1.0-0-dev \ + libudev-dev \ + # Only required for building the minimal client + libncurses5-dev \ + # Only required for visual studio debugging + gdb \ + && apt-get clean + +# configure SSH for communication with Visual Studio +RUN apt-get update && apt-get install -y openssh-server +RUN mkdir -p /var/run/sshd +RUN echo 'PasswordAuthentication yes' >> /etc/ssh/sshd_config && \ + ssh-keygen -A + +# please make sure to change the password +RUN id -u manus >/dev/null 2>&1 || useradd -m -d /home/manus -s /bin/bash -G sudo manus && \ +echo "manus:password" | chpasswd + +# copy dependencies to ~/ManusSDK/ directory +COPY ManusSDK /home/manus/ManusSDK + +# Add read/write permissions for manus devices +RUN apt-get update && apt-get install -y udev +RUN echo "# HIDAPI/libusb" > /etc/udev/rules.d/99-manus.rules && \ + echo "SUBSYSTEMS==\"usb\", ATTRS{idVendor}==\"3325\", MODE:=\"0666\"" >> /etc/udev/rules.d/99-manus.rules && \ + echo "# HIDAPI/hidraw" >> /etc/udev/rules.d/99-manus.rules && \ + echo "KERNEL==\"hidraw*\", ATTRS{idVendor}==\"3325\", MODE:=\"0666\"" >> /etc/udev/rules.d/99-manus.rules + +# change default SSH port to 5000 to not conflict with system ssh in host mode +RUN echo "Port 5000" >> /etc/ssh/sshd_config + +ENTRYPOINT service ssh start && service udev start && bin/bash + +EXPOSE 5000 \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Main.cpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3749ad2147148a99eec8b32359e7f32f1040fe22 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Main.cpp @@ -0,0 +1,52 @@ +// Set up a Doxygen group. +/** @addtogroup Main + * @{ + */ + +#include "ClientLogging.hpp" +#include "SDKClient.hpp" +#include +#include +#include +#include +#include +#include + +namespace py = pybind11; + + +ClientReturnCode t_Result; +SDKClient t_SDKClient; + +int init() { + t_SDKClient.Initialize(); + t_SDKClient.Run(); + while (output_map.size() == 0){ + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + return 0; +} + +py::dict get_latest_state() { + py::dict py_dict; + for (const auto& pair : output_map) { + py::list py_list; // Initialize a py::list for each vector + for (double value : pair.second) { + py_list.append(value); // Append each value from the vector to the py::list + } + py_dict[py::str(pair.first)] = py_list; // Assign the list to the dict with the string key + } + return py_dict; +} + +int shutdown() { + t_SDKClient.ShutDown(); + std::cout<<"Manus shutdown\n"; + return 0; +} + +PYBIND11_MODULE(ManusServer, m) { + m.def("init", &init); + m.def("get_latest_state", &get_latest_state); + m.def("shutdown", &shutdown); +} \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Makefile b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..a5acc7cf2ab356532b25382dfe50d80ab7e0cc79 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Makefile @@ -0,0 +1,59 @@ +CXX := g++ + +#CXXFLAGS := -pedantic-errors -Wall -Wextra -Werror -g --std=c++17 +# CXXFLAGS := -g --std=c++17 + +PYBIND11_INCLUDES := $(shell python3 -m pybind11 --includes) +PYBIND11_SUFFIX := $(shell python3-config --extension-suffix) +CXXFLAGS := -shared -g --std=c++17 -fPIC ${PYBIND11_INCLUDES} + +LDFLAGS := -L./ManusSDK/lib -lManusSDK -lncurses -lpthread -Wl,-rpath=./ManusSDK/lib +BUILD := ./ +OBJ_DIR := $(BUILD)/objects +APP_DIR := $(BUILD) + +# TARGET := SDKClient_Linux.out +TARGET := ManusServer$(PYBIND11_SUFFIX) + +INCLUDE := -I./ManusSDK/include +SRC := \ + $(wildcard *.cpp) + +OBJECTS := $(SRC:%.cpp=$(OBJ_DIR)/%.o) +DEPENDENCIES \ + := $(OBJECTS:.o=.d) + +all: build $(APP_DIR)/$(TARGET) + +$(OBJ_DIR)/%.o: %.cpp + @mkdir -p $(@D) + $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -MMD -o $@ + +$(APP_DIR)/$(TARGET): $(OBJECTS) + @mkdir -p $(@D) + $(CXX) $(CXXFLAGS) -o $(APP_DIR)/$(TARGET) $^ $(LDFLAGS) + +-include $(DEPENDENCIES) + +.PHONY: all build clean debug release info + +build: + @mkdir -p $(APP_DIR) + @mkdir -p $(OBJ_DIR) + +debug: CXXFLAGS += -DDEBUG -g +debug: all + +release: CXXFLAGS += -g +release: all + +clean: + -@rm $(TARGET) + -@rm -rvf $(OBJ_DIR)/* + +info: + @echo "[*] Application dir: ${APP_DIR} " + @echo "[*] Object dir: ${OBJ_DIR} " + @echo "[*] Sources: ${SRC} " + @echo "[*] Objects: ${OBJECTS} " + @echo "[*] Dependencies: ${DEPENDENCIES}" diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDK.h b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDK.h new file mode 100644 index 0000000000000000000000000000000000000000..173a8e39dd1d1a6dac8bdd0195e539831de877e8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDK.h @@ -0,0 +1,1058 @@ +#ifndef __MANUS_SDK_H__ +#define __MANUS_SDK_H__ + +// Set up a Doxygen group. +/** @addtogroup ManusSDK + * @{ + */ + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ManusSDKTypes.h" +#include "ManusSDKTypeInitializers.h" + +#include + +#ifdef MANUS_SDK_STATIC +#define CORESDK_API +#else +#ifdef _WIN32 + // MANUS_SDK_EXPORTS defines if the functions are exported to or + // imported from a DLL. +#ifdef MANUS_SDK_EXPORTS +#define CORESDK_API __declspec(dllexport) +#else +#define CORESDK_API __declspec(dllimport) +#endif +#elif defined(__linux__) +#define CORESDK_API +#else +#error Unrecognized platform. +#endif +#endif + + /****************************************************************************** + * Wrapper startup and shutdown. + *****************************************************************************/ + + /// @brief Initialize the wrapper. + /// Call this before using the wrapper. + /// @param p_TypeOfSession + /// @param p_Remote If set to true, this is essentially the same as calling the old CoreSdk_Initialize + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_FunctionCalledAtWrongTime if the function was not intended to be called at this time. + CORESDK_API SDKReturnCode CoreSdk_Initialize(SessionType p_TypeOfSession, bool p_Remote); + + /// @brief Shut down the wrapper. + /// This needs to be called last. + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_ShutDown(); + + /****************************************************************************** + * Utility functions. + *****************************************************************************/ + + /// @brief Check if the wrapper DLL was built in the debug configuration. + /// @param p_WasBuiltInDebugConfiguration + /// @return SDKReturnCode_Success if successful. + CORESDK_API SDKReturnCode CoreSdk_WasDllBuiltInDebugConfiguration(bool* p_WasBuiltInDebugConfiguration); + + /// @brief Gets the timestamp info (more readable form of timestamp). + /// @param p_Timestamp Timestamp to get info from + /// @param p_Info Info of the timestamp + /// @return SDKReturnCode_Success if successful. + CORESDK_API SDKReturnCode CoreSdk_GetTimestampInfo(ManusTimestamp p_Timestamp, ManusTimestampInfo* p_Info); + + /// @brief Sets the timestamp according to the info (more readable form of timestamp). + /// @param p_Timestamp the Timestamp to set info of + /// @param p_Info Info to get info from + /// @return SDKReturnCode_Success if successful. + CORESDK_API SDKReturnCode CoreSdk_SetTimestampInfo(ManusTimestamp* p_Timestamp, ManusTimestampInfo p_Info); + + + /****************************************************************************** + * Connection handling. + *****************************************************************************/ + + /// @brief Start a background task that looks for hosts running Manus Core. + /// Call this first when looking for hosts to connect to. + /// Underlying function will sleep for p_WaitSeconds to allow servers to reply. + /// @param p_WaitSeconds defines the time the function will sleep for to allow servers to reply, + /// @param p_LoopbackOnly if true it looks for hosts only locally, if false it looks for hosts anywhere in the network, + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_FunctionCalledAtWrongTime if the function was not intended to be called at this time. + CORESDK_API SDKReturnCode CoreSdk_LookForHosts(uint32_t p_WaitSeconds = 1, bool p_LoopbackOnly = false); + + /// @brief Get the number of hosts running Manus Core that were found. + /// This is the second function to call when looking for hosts to connect to. + /// @param p_NumberOfAvailableHostsFound + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_FunctionCalledAtWrongTime if the function was not intended to be called at this time. + CORESDK_API SDKReturnCode CoreSdk_GetNumberOfAvailableHostsFound(uint32_t* p_NumberOfAvailableHostsFound); + + /// @brief Fill the given array with information on the hosts that were found. + /// This is the third and final function to call when looking for hosts to + /// connect to. + /// @param p_AvailableHostsFound + /// @param p_NumberOfHostsThatFitInArray + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_FunctionCalledAtWrongTime if the function was not intended to be called at this time + /// SDKReturnCode_ArgumentSizeMismatch if p_NumberOfHostsThatFitInArray does not match the number of available hosts found in the network, + /// SDKReturnCode_InvalidArgument if the provided p_AvailableHostsFound is a null pointer, + /// SDKReturnCode_InternalError if the number of available hosts found is higher than the defined MAX_NUMBER_OF_HOSTS, + /// SDKReturnCode_UnsupportedStringSizeEncountered if the name of a host is higher than the defined MAX_NUM_CHARS_IN_HOST_NAME, + /// SDKReturnCode_Error if copying the string representing the host name was not successful, + /// SDKReturnCode_NullPointer if invalid host data was found. + CORESDK_API SDKReturnCode CoreSdk_GetAvailableHostsFound(ManusHost* p_AvailableHostsFound, const uint32_t p_NumberOfHostsThatFitInArray); + + + /// @brief Check if the wrapper is connected to ManusCore. + /// @param p_ConnectedToCore + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_GetIsConnectedToCore(bool* p_ConnectedToCore); + + /// @brief Connect to the preset GRPC address. + /// @return SDKReturnCode_Success + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_ConnectGRPC(); + + /// @brief Disconnects from the current host + /// @return SDKReturnCode_Success + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_Disconnect(); + + /// @brief Connect to a host using the given host information. + /// @param p_Host + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_SdkIsTerminating if the sdk is being terminated, + /// SDKReturnCode_FunctionCalledAtWrongTime if the function was not intended to be called at this time, + /// SDKReturnCode_NoCoordinateSystemSet if the user tried to connect without first setting up the coordinate system settings. + CORESDK_API SDKReturnCode CoreSdk_ConnectToHost(ManusHost p_Host); + + /// @brief Initialize a coordinate system of type CoordinateSystemVUH. (View Up Handedness) + /// This has to be called before a connection is made. + /// @param p_CoordinateSystem + /// @param p_UseWorldCoordinates if true all data will be defined with respect to a world coordinate system, + /// if false all data will be defined with respect to a local one, + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_InitializeCoordinateSystemWithVUH(CoordinateSystemVUH p_CoordinateSystem, bool p_UseWorldCoordinates); + + /// @brief Initialize a coordinate system of type CoordinateSystemDirection. + /// This has to be called before a connection is made. + /// @param p_CoordinateSystem + /// @param p_UseWorldCoordinates if true all data will be defined with respect to a world coordinate system, + /// if false all data will be defined with respect to a local one, + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_InitializeCoordinateSystemWithDirection(CoordinateSystemDirection p_CoordinateSystem, bool p_UseWorldCoordinates); + + /// @brief Get the SDK and Core version used and check if they are compatible with each other. + /// @param p_SdkVersion + /// @param p_CoreVersion + /// @param p_AreVersionsCompatible + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_GetVersionsAndCheckCompatibility(ManusVersion* p_SdkVersion, ManusVersion* p_CoreVersion, bool* p_AreVersionsCompatible); + + /// @brief Get the current session Id. + /// @param p_SessionId + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_InvalidID if the session id is zero, which means it was not correctly assigned. + CORESDK_API SDKReturnCode CoreSdk_GetSessionId(uint32_t* p_SessionId); + + /// @brief Register the callback function that is called when manus core gets connected to the sdk. + /// @param p_ConnectedCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForOnConnect(ConnectedToCoreCallback_t p_ConnectedCallback); + + /// @brief Register the callback function that is called when manus core gets disconnected from the sdk. + /// @param p_DisconnectedCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForOnDisconnect(DisconnectedFromCoreCallback_t p_DisconnectedCallback); + + /// @brief Register the callback function that is called when something is logged in the SDK. + /// @param p_LoggingCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForOnLog(LoggingCallback_t p_LoggingCallback); + + /// @brief Register the callback function that is called when skeleton data comes in. + /// @param p_SkeletonStreamCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForSkeletonStream(SkeletonStreamCallback_t p_SkeletonStreamCallback); + + /// @brief Register the callback function that is called when tracker data comes in. + /// @param p_TrackerStreamCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForTrackerStream(TrackerStreamCallback_t p_TrackerStreamCallback); + + /// @brief Register the callback function that is called when the landscape data comes in. + /// @param p_LandscapeStreamCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForLandscapeStream(LandscapeStreamCallback_t p_LandscapeStreamCallback); + + /// @brief Register the callback function that is called when core system related data comes in. + /// @param p_SystemStreamCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForSystemStream(SystemStreamCallback_t p_SystemStreamCallback); + + /// @brief Register the callback function that is called when ergonomics data comes in. + /// @param p_ErgonomicsStreamCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForErgonomicsStream(ErgonomicsStreamCallback_t p_ErgonomicsStreamCallback); + + /// @brief Register the callback function that is called when skeleton data comes in. + /// @param p_SkeletonStreamCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForRawSkeletonStream(RawSkeletonStreamCallback_t p_RawSkeletonStreamCallback); + + /// @brief Register the callback function that is called when gesture data comes in. + /// @param p_GestureStreamCallback + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_RegisterCallbackForGestureStream(GestureStreamCallback_t p_GestureStreamCallback); + + /****************************************************************************** + * Basic glove interaction. + *****************************************************************************/ + + /// @brief Try to pair a glove to a dongle + /// @param p_GloveID + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_PairGlove(uint32_t p_GloveID, bool* p_Result); + + /// @brief Try to unpair a glove to a dongle + /// @param p_GloveID + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available. + CORESDK_API SDKReturnCode CoreSdk_UnpairGlove(uint32_t p_GloveID, bool* p_Result); + + /// @brief Vibrate the motor on the given fingers of a haptic glove. + /// The order of the fingers is Thumb, Index, Middle, Ring, Pinky. + /// @param p_DongleId + /// @param p_HandType + /// @param p_Powers strength of the vibration, should be an array of 5 values + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core. + /// @deprecated Use CoreSdk_VibrateFingersForGlove or CoreSdk_VibrateFingersForSkeleton instead + [[deprecated("Use CoreSdk_VibrateFingersForGlove or CoreSdk_VibrateFingersForSkeleton instead")]] + CORESDK_API SDKReturnCode CoreSdk_VibrateFingers(uint32_t p_DongleId, Side p_HandType, const float* p_Powers); + + /// @brief Vibrate the motor on the given fingers of a haptic glove. + /// The order of the fingers is Thumb, Index, Middle, Ring, Pinky. + /// @param p_GloveId + /// @param p_Powers strength of the vibration, should be an array of 5 values + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_VibrateFingersForGlove(uint32_t p_GloveId, const float* p_Powers); + + /// @brief Vibrate the motor on the fingers of a haptic glove associated to skeleton with given id. + /// The order of the fingers is Thumb, Index, Middle, Ring, Pinky. + /// @param p_SkeletonId + /// @param p_HandType + /// @param p_Powers strength of the vibration, should be an array of 5 values + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_VibrateFingersForSkeleton(uint32_t p_SkeletonId, Side p_HandType, const float* p_Powers); + + /// @brief Get a glove ID for the given hand of the given user identified by its Id. + /// @param p_UserId + /// @param p_HandType + /// @param p_GloveId + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidArgument if the provided p_HandType was neither left nor right, + /// SDKReturnCode_InvalidID if no user with the provided p_UserId was found in the landscape. + CORESDK_API SDKReturnCode CoreSdk_GetGloveIdOfUser_UsingUserId(uint32_t p_UserId, Side p_HandType, uint32_t* p_GloveId); + + /// @brief Get the number of gloves that are available. + /// @param p_NumberOfAvailableGloves + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InternalError if the number of available gloves found is higher than the defined MAX_NUMBER_OF_GLOVES. + CORESDK_API SDKReturnCode CoreSdk_GetNumberOfAvailableGloves(uint32_t* p_NumberOfAvailableGloves); + + /// @brief Fill the given array with the IDs of all available gloves. + /// The size of the given array must match the number of available gloves. + /// Note that the number of available gloves can change at any time. + /// @param p_IdsOfAvailableGloves + /// @param p_NumberOfIdsThatFitInArray + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_NumberOfIdsThatFitInArray does not match with the number of available gloves found, + /// SDKReturnCode_InvalidArgument if p_NumberOfIdsThatFitInArray is zero or is higher than the defined MAX_NUMBER_OF_GLOVES. + CORESDK_API SDKReturnCode CoreSdk_GetIdsOfAvailableGloves(uint32_t* p_IdsOfAvailableGloves, uint32_t p_NumberOfIdsThatFitInArray); + + /// @brief Get glove id's for given dongle id. + /// @param p_DongleId + /// @param p_LeftGloveId + /// @param p_RightGloveId + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core. + /// @deprecated Get this through the Landscape instead + [[deprecated("Get this through the Landscape instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetGlovesForDongle(uint32_t p_DongleId, uint32_t* p_LeftGloveId, uint32_t* p_RightGloveId); + + /// @brief Get data for the glove with the given glove ID. + /// @param p_GloveId + /// @param p_GloveData + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_DataNotAvailable if no glove with the provided p_GloveId was found in the landscape. + /// @deprecated Get this through the Landscape instead + [[deprecated("Get this through the Landscape instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetDataForGlove_UsingGloveId(uint32_t p_GloveId, GloveLandscapeData* p_GloveData); + + /// @brief Gets the data for a dongle with the given id. + /// @param p_DongleId + /// @param p_DongleData + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_DataNotAvailable if no dongle with the provided p_DongleId was found in the landscape. + CORESDK_API SDKReturnCode CoreSdk_GetDataForDongle(uint32_t p_DongleId, DongleLandscapeData* p_DongleData); + + /// @brief Get the number of available dongles. + /// @param p_NumberOfDongles + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InternalError if the number of dongles found is higher than the defined MAX_NUMBER_OF_DONGLES. + /// @deprecated Get this through the Landscape instead + [[deprecated("Get this through the Landscape instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetNumberOfDongles(uint32_t* p_NumberOfDongles); + + /// @brief Fill the given array with the IDs of all available dongles. + /// The size of the given array must match the number of available dongles. + /// Note that the number of available dongles can change at any time. + /// @param p_DongleIds + /// @param p_NumberOfIdsThatFitInArray + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_NumberOfIdsThatFitInArray does not match with the number of dongles found, + /// SDKReturnCode_InvalidArgument if p_NumberOfIdsThatFitInArray is zero or higher than the defined MAX_NUMBER_OF_HAPTICS_DONGLES. + /// @deprecated Get this through the Landscape instead + [[deprecated("Get this through the Landscape instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetDongleIds(uint32_t* p_DongleIds, uint32_t p_NumberOfIdsThatFitInArray); + + /****************************************************************************** + * Haptics module. + *****************************************************************************/ + + /// @brief Get the number of available haptics dongles. + /// @param p_NumberOfHapticsDongles + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InternalError if the number of haptic dongles found is higher than the defined MAX_NUMBER_OF_HAPTICS_DONGLES. + /// @deprecated Get this through the Landscape instead + [[deprecated("Get this through the Landscape instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetNumberOfHapticsDongles(uint32_t* p_NumberOfHapticsDongles); + + /// @brief Fill the given array with the IDs of all available haptics dongles. + /// The size of the given array must match the number of available haptics dongles. + /// Note that the number of available haptics dongles can change at any time. + /// @param p_HapticsDongleIds + /// @param p_NumberOfIdsThatFitInArray + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_NumberOfIdsThatFitInArray does not match with the number of haptic dongles found, + /// SDKReturnCode_InvalidArgument if p_NumberOfIdsThatFitInArray is zero or higher than the defined MAX_NUMBER_OF_HAPTICS_DONGLES. + /// @deprecated Get this through the Landscape instead + [[deprecated("Get this through the Landscape instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetHapticsDongleIds(uint32_t* p_HapticsDongleIds, uint32_t p_NumberOfIdsThatFitInArray); + + /****************************************************************************** + * Users. + *****************************************************************************/ + + /// @brief Get the number of available users. + /// Note that this is reliant on the landscape, and the first second after connecting the client to the core it will not yet have landscape + /// data, so the number of users wil be 0. Since there will always be a default users, just wait until the count is above 0 and then proceed. + /// @param p_NumberOfAvailableUsers + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InternalError if the number of available users found is higher than the defined MAX_NUMBER_OF_USERS. + CORESDK_API SDKReturnCode CoreSdk_GetNumberOfAvailableUsers(uint32_t* p_NumberOfAvailableUsers); + + /// @brief Fill the given array with the IDs of all available users. + /// The size of the given array must match the number of available users. + /// Note that the number of available users can change at any time depending on the landscape. + /// @param p_IdsOfAvailableUsers, The array of ids that will get filled + /// @param p_NumberOfIdsThatFitInArray + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidArgument if p_NumberOfIdsThatFitInArray is null or higher than the defined MAX_NUMBER_OF_USERS, or + /// if p_IdsOfAvailableUsers is a null array. + /// SDKReturnCode_ArgumentSizeMismatch if p_NumberOfIdsThatFitInArray does not match with number of available users found. + CORESDK_API SDKReturnCode CoreSdk_GetIdsOfAvailableUsers(uint32_t* p_IdsOfAvailableUsers, uint32_t p_NumberOfIdsThatFitInArray); + + /****************************************************************************** + * Tracking. + *****************************************************************************/ + + /// @brief Get data for a tracker at a given index in the TrackerStream callback. + /// @param p_TrackerIndex + /// @param p_TrackerData + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_TrackerIndex is higher than the total number of trackers received from the tracker stream. + CORESDK_API SDKReturnCode CoreSdk_GetTrackerData(uint32_t p_TrackerIndex, TrackerData* p_TrackerData); + + /// @brief Get the number of available trackers. + /// @param p_NumberOfAvailableTrackers + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InternalError if the number of trackers found is higher than the defined MAX_NUMBER_OF_TRACKERS. + CORESDK_API SDKReturnCode CoreSdk_GetNumberOfAvailableTrackers(uint32_t* p_NumberOfAvailableTrackers); + + /// @brief Fill the given array with the IDs of available trackers. + /// The size of the given array must match the number of available trackers. + /// Note that the number of available trackers can change at any time. + /// @param p_IdsOfAvailableTrackers + /// @param p_NumberOfIdsThatFitInArray + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidArgument if p_NumberOfIdsThatFitInArray is zero or higher than the defined MAX_NUMBER_OF_TRACKERS, or + /// if p_IdsOfAvailableTrackers is a null array. + /// SDKReturnCode_ArgumentSizeMismatch if p_NumberOfIdsThatFitInArray does not match with the number of available trackers found. + CORESDK_API SDKReturnCode CoreSdk_GetIdsOfAvailableTrackers(TrackerId* p_IdsOfAvailableTrackers, uint32_t p_NumberOfIdsThatFitInArray); + + /// @brief Get the number of available trackers for a user with given Id. + /// @param p_NumberOfAvailableTrackers + /// @param p_UserId + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InternalError if the number of trackers found is higher than the defined MAX_NUMBER_OF_TRACKERS. + CORESDK_API SDKReturnCode CoreSdk_GetNumberOfAvailableTrackersForUserId(uint32_t* p_NumberOfAvailableTrackers, uint32_t p_UserId); + + /// @brief Fill the given array with the IDs of available trackers for a user with given Id. + /// The size of the given array must match the number of available trackers. + /// Note that the number of available trackers can change at any time. + /// @param p_IdsOfAvailableTrackers + /// @param p_UserId + /// @param p_NumberOfIdsThatFitInArray + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidArgument if p_NumberOfIdsThatFitInArray is zero or higher than the defined MAX_NUMBER_OF_TRACKERS, or + /// if p_IdsOfAvailableTrackers is a null array. + /// SDKReturnCode_ArgumentSizeMismatch if p_NumberOfIdsThatFitInArray does not match with the number of available trackers found. + CORESDK_API SDKReturnCode CoreSdk_GetIdsOfAvailableTrackersForUserId(TrackerId* p_IdsOfAvailableTrackers, uint32_t p_UserId, uint32_t p_NumberOfIdsThatFitInArray); + + /// @brief Get the number of available trackers for a user with given Id. + /// @param p_NumberOfAvailableTrackers + /// @param p_UserIndex + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InternalError if the number of trackers found is higher than the defined MAX_NUMBER_OF_TRACKERS. + CORESDK_API SDKReturnCode CoreSdk_GetNumberOfAvailableTrackersForUserIndex(uint32_t* p_NumberOfAvailableTrackers, uint32_t p_UserIndex); + + /// @brief Fill the given array with the IDs of available trackers for a user with given Id. + /// The size of the given array must match the number of available trackers. + /// Note that the number of available trackers can change at any time. + /// @param p_IdsOfAvailableTrackers + /// @param p_UserIndex + /// @param p_NumberOfIdsThatFitInArray + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidArgument if p_NumberOfIdsThatFitInArray is zero or higher than the defined MAX_NUMBER_OF_TRACKERS, or + /// if p_IdsOfAvailableTrackers is a null array. + /// SDKReturnCode_ArgumentSizeMismatch if p_NumberOfIdsThatFitInArray does not match with the number of available trackers found. + CORESDK_API SDKReturnCode CoreSdk_GetIdsOfAvailableTrackersForUserIndex(TrackerId* p_IdsOfAvailableTrackers, uint32_t p_UserIndex, uint32_t p_NumberOfIdsThatFitInArray); + + + + /// @brief Get data for the tracker with the given tracker Id. + /// @param p_TrackerId + /// @param p_TrackerData + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_DataNotAvailable if no tracker with the given p_TrackerId was found in the landscape. + CORESDK_API SDKReturnCode CoreSdk_GetDataForTracker_UsingTrackerId(TrackerId p_TrackerId, TrackerData* p_TrackerData); + + /// @brief Get data for the tracker with the given user id and type. + /// @param p_UserId + /// @param p_TrackerType + /// @param p_TrackerData + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_DataNotAvailable if no tracker with the given p_TrackerId and the given p_TrackerType was found in the landscape. + CORESDK_API SDKReturnCode CoreSdk_GetDataForTracker_UsingIdAndType(uint32_t p_UserId, uint32_t p_TrackerType, TrackerData* p_TrackerData); + + /// @brief Send data to Core for a tracker. + /// @param p_TrackerData + /// @param p_NumberOfTrackers amount of trackers for which we send the information + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_NullPointer if the provided p_TrackerData is a null pointer, + /// SDKReturnCode_InvalidArgument if p_NumberOfTrackers is null or higher than the defined MAX_NUMBER_OF_TRACKERS. + CORESDK_API SDKReturnCode CoreSdk_SendDataForTrackers(const TrackerData* p_TrackerData, uint32_t p_NumberOfTrackers); + + /// @brief Sets the offset of a tracker for a specified user + /// @param p_UserId + /// @param p_TrackerOffset + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_SetTrackerOffset(uint32_t p_UserId, const TrackerOffset* p_TrackerOffset); + + /****************************************************************************** + * Gestures. + *****************************************************************************/ + + /// @brief Get the landscape data for all the gestures in the latest landscape. + /// @param p_LandscapeDataArray + /// @param p_ArraySize + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_ArraySize is higher than the total number of gestures in the landscape stream. + CORESDK_API SDKReturnCode CoreSdk_GetGestureLandscapeData(GestureLandscapeData* p_LandscapeDataArray, uint32_t p_ArraySize); + + /// @brief The start data index allows you to get more data if there are more than MAX_GESTURE_DATA_CHUNK_SIZE gestures. + /// @param p_GestureStreamDataIndex + /// @param p_StartDataIndex + /// @param p_GestureProbabilitiesCollection + /// @return SDKReturnCode_Success if successful, or if there is no more data to get + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_ArraySize is higher than the total number of gestures in the landscape stream. + CORESDK_API SDKReturnCode CoreSdk_GetGestureStreamData(uint32_t p_GestureStreamDataIndex, uint32_t p_StartDataIndex, GestureProbabilities* p_GestureProbabilitiesCollection); + + /****************************************************************************** + * Glove Calibration. + *****************************************************************************/ + + /// @brief Start the calibration for a glove with the id that is specified in the arguments. + /// @param p_CalibrationArgs + /// @param p_Result + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core + CORESDK_API SDKReturnCode CoreSdk_GloveCalibrationStart(GloveCalibrationArgs p_CalibrationArgs, bool* p_Result); + + /// @brief Stop the calibration for a glove with the id that is specified in the arguments. + /// @param p_CalibrationArgs + /// @param p_Result + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core + CORESDK_API SDKReturnCode CoreSdk_GloveCalibrationStop(GloveCalibrationArgs p_CalibrationArgs, bool* p_Result); + + /// @brief Finish the calibration for a glove with the id that is specified in the arguments. + /// @param p_CalibrationArgs + /// @param p_Result + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core + CORESDK_API SDKReturnCode CoreSdk_GloveCalibrationFinish(GloveCalibrationArgs p_CalibrationArgs, bool* p_Result); + + + /// @brief Get the number of steps in a glove calibration sequence. + /// @param p_CalibrationArgs + /// @param p_NumberOfSteps + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core + CORESDK_API SDKReturnCode CoreSdk_GloveCalibrationGetNumberOfSteps(GloveCalibrationArgs p_CalibrationArgs, uint32_t* p_NumberOfSteps); + + /// @brief Get information data about a specific calibration step for a glove. + /// @param p_CalibrationStepArgs + /// @param p_Data + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core + CORESDK_API SDKReturnCode CoreSdk_GloveCalibrationGetStepData(GloveCalibrationStepArgs p_CalibrationStepArgs, GloveCalibrationStepData* p_Data); + + /// @brief Start a specific calibration step for a glove. + /// @param p_CalibrationStepArgs + /// @param p_Result + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core + CORESDK_API SDKReturnCode CoreSdk_GloveCalibrationStartStep(GloveCalibrationStepArgs p_CalibrationStepArgs, bool* p_Result); + + + CORESDK_API SDKReturnCode CoreSdk_GetGloveCalibrationSize(uint32_t p_GloveId, uint32_t* p_Size); + + CORESDK_API SDKReturnCode CoreSdk_GetGloveCalibration(unsigned char* p_CalibrationBytes, uint32_t p_BytesLength); + + CORESDK_API SDKReturnCode CoreSdk_SetGloveCalibration(uint32_t p_GloveId, unsigned char* p_CalibrationBytes, SetGloveCalibrationReturnCode* p_Result); + + /****************************************************************************** + * Skeletal System. + *****************************************************************************/ + + /// @brief Get information about the final animated skeleton with given index. + /// @param p_SkeletonIndex + /// @param p_Info + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_SkeletonIndex is higher than the total number of skeletons received from the skeleton stream. + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonInfo(uint32_t p_SkeletonIndex, SkeletonInfo* p_Info); + + /// @brief Get data for the final animated skeleton with given index. + /// The size of the given array must match the nodes count. + /// Note that the nodes count can change at any time. + /// @param p_SkeletonIndex + /// @param p_Nodes + /// @param p_NodeCount + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_SkeletonIndex is higher than the total number of skeletons received from the skeleton stream or + /// if the provided p_NodeCount is different from the node count of that skeleton. + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonData(uint32_t p_SkeletonIndex, SkeletonNode* p_Nodes, uint32_t p_NodeCount); + + /// @brief Determine how the raw data should be moving + /// @param p_HandMotion + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + CORESDK_API SDKReturnCode CoreSdk_SetRawSkeletonHandMotion(HandMotion p_HandMotion); + + /// @brief Get the raw skeleton hand motion type + /// @param p_HandMotion + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + CORESDK_API SDKReturnCode CoreSdk_GetRawSkeletonHandMotion(HandMotion* p_HandMotion); + + /// @brief Get information about the raw skeleton data with given index. + /// @param p_SkeletonIndex + /// @param p_Info + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_SkeletonIndex is higher than the total number of skeletons received from the skeleton stream. + CORESDK_API SDKReturnCode CoreSdk_GetRawSkeletonInfo(uint32_t p_SkeletonIndex, RawSkeletonInfo* p_Info); + + /// @brief Get data for the raw skeleton with given index. + /// The size of the given array must match the nodes count. + /// Note that the nodes count can change at any time. + /// @param p_SkeletonIndex + /// @param p_Nodes + /// @param p_NodeCount + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if p_SkeletonIndex is higher than the total number of skeletons received from the skeleton stream or + /// if the provided p_NodeCount is different from the node count of that skeleton. + CORESDK_API SDKReturnCode CoreSdk_GetRawSkeletonData(uint32_t p_SkeletonIndex, SkeletonNode* p_Nodes, uint32_t p_NodeCount); + + /// @brief Identifies if the glove associated to the skeleton with given id and side is a haptic one. + /// @param p_SkeletonId + /// @param p_HandType + /// @param p_IsHaptics + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_DataNotAvailable if the requested glove is not found or if the skeleton does not have any user associated to it, + /// SDKReturnCode_InvalidArgument if the provided p_HandType is neither Left nor Right. + CORESDK_API SDKReturnCode CoreSdk_DoesSkeletonGloveSupportHaptics(uint32_t p_SkeletonId, Side p_HandType, bool* p_IsHaptics); + /****************************************************************************** + * Skeletal System Setup. + *****************************************************************************/ + + /// @brief Create a new SkeletonSetup with the given information and returns the index on which it is saved. + /// @param p_Skeleton The SkeletonSetup information used by this skeleton. + /// @param p_SkeletonSetupIndex The index which is used by this SkeletonSetup. + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_ArgumentSizeMismatch if the maximum number of temporary skeletons per session has been reached, + /// when this happens the user can either load or clear a temporary skeleton in order to create a new skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_CreateSkeletonSetup(SkeletonSetupInfo p_Skeleton, uint32_t* p_SkeletonSetupIndex); + + /// @brief Add a node to a SkeletonSetup at a given index. + /// @param p_SkeletonSetupIndex + /// @param p_Node + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_AddNodeToSkeletonSetup(uint32_t p_SkeletonSetupIndex, NodeSetup p_Node); + + /// @brief Add a chain to a SkeletonSetup at a given index. + /// @param p_SkeletonSetupIndex + /// @param p_Chain + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_AddChainToSkeletonSetup(uint32_t p_SkeletonSetupIndex, ChainSetup p_Chain); + + /// @brief Add a collider to a SkeletonSetup at a given index. + /// @param p_SkeletonSetupIndex + /// @param p_Collider + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_AddColliderToSkeletonSetup(uint32_t p_SkeletonSetupIndex, ColliderSetup p_Collider); + + /// @brief Add a mesh setup to a SkeletonSetup at a given index. + /// @param p_SkeletonSetupIndex + /// @param p_NodeID + /// @param p_MeshSetupIndex + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_AddMeshSetupToSkeletonSetup(uint32_t p_SkeletonSetupIndex, uint32_t p_NodeID, uint32_t* p_MeshSetupIndex); + + /// @brief Add a Vertex to a mesh setup at a given index. + /// @param p_SkeletonSetupIndex + /// @param p_MeshSetupIndex + /// @param p_Vertex + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_AddVertexToMeshSetup(uint32_t p_SkeletonSetupIndex, uint32_t p_MeshSetupIndex, Vertex p_Vertex); + + + /// @brief Add a Triangle to a mesh setup at a given index. + /// @param p_SkeletonSetupIndex + /// @param p_MeshSetupIndex + /// @param p_Triangle + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_AddTriangleToMeshSetup(uint32_t p_SkeletonSetupIndex, uint32_t p_MeshSetupIndex, Triangle p_Triangle); + + /// @brief Overwrite an existing SkeletonSetup at a given index. + /// This will remove all chains and nodes from the current skeleton at this index. + /// @param p_SkeletonSetupIndex + /// @param p_SkeletonSetup + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup, + /// SDKReturnCode_NullPointer if the skeleton setup was not correctly saved, thus the new skeleton setup is a null pointer. + CORESDK_API SDKReturnCode CoreSdk_OverwriteSkeletonSetup(uint32_t p_SkeletonSetupIndex, SkeletonSetupInfo p_SkeletonSetup); + + /// @brief Overwrite a chain in a SkeletonSetup, the chain to be overwritten is idenfified by p_Chain.id. + /// @param p_SkeletonSetupIndex The SkeletonSetup's index, not to be confused by the Chain's ID. + /// @param p_Chain The chain to replace the matching (via id) chain with. + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_OverwriteChainToSkeletonSetup(uint32_t p_SkeletonSetupIndex, ChainSetup p_Chain); + + /// @brief Overwrite a node in a SkeletonSetup, the node to be overwritten is identified by p_Node.id. + /// @param p_SkeletonSetupIndex The SkeletonSetup's index, not to be confused by the Chain's ID. + /// @param p_Node The node to replace the matching (via id) node with. + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_OverwriteNodeToSkeletonSetup(uint32_t p_SkeletonSetupIndex, NodeSetup p_Node); + + /// @brief Get the skeleton info (number of nodes and chains) for a SkeletonSetup at a given index. + /// @param p_SkeletonSetupIndex + /// @param p_SkeletonInfo + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonSetupArraySizes(uint32_t p_SkeletonSetupIndex, SkeletonSetupArraySizes* p_SkeletonInfo); + + /// @brief Allocate chains for a SkeletonSetup at a given index. + /// @param p_SkeletonSetupIndex + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_AllocateChainsForSkeletonSetup(uint32_t p_SkeletonSetupIndex); + CORESDK_API SDKReturnCode CoreSdk_PrepareSkeletonSetup(uint32_t p_SkeletonSetupIndex); + + /// @brief Get setup info for a SkeletonSetup at a given index. + /// @param p_SkeletonSetupIndex + /// @param p_SDK + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonSetupInfo(uint32_t p_SkeletonSetupIndex, SkeletonSetupInfo* p_SDK); + + /// @brief Get setup chains for a SkeletonSetup at a given index. + /// The size of the given array must match the chains count. + /// Note that the chains count can change at any time. + /// @param p_SkeletonSetupIndex + /// @param p_SDK + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_NullPointer if the provided p_SDK (used to store the setup chains) is a null pointer, it should be initialized to + /// an array with size equal to the chains count, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + /// @deprecated Use GetSkeletonSetupChainsArray() instead + [[deprecated ("Use GetSkeletonSetupChainsArray() instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonSetupChains(uint32_t p_SkeletonSetupIndex, ChainSetup* p_SDK); + + /// @brief Get setup chains for a SkeletonSetup at a given index. + /// The size of the given array must match the chains count. + /// Note that the chains count can change at any time. + /// @param p_SkeletonSetupIndex + /// @param p_ChainSetupArray + /// @param p_ArraySize + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_NullPointer if the provided p_ChainSetupArray (used to store the setup chains) is a null pointer, it should be initialized to + /// an array with size equal to the chains count, + /// SDKReturnCode_ArgumentSizeMismatch if the provided p_ArraySize is not equal to the chains count, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonSetupChainsArray(uint32_t p_SkeletonSetupIndex, ChainSetup* p_ChainSetupArray, uint32_t p_ArraySize); + + /// @brief Get setup nodes for a SkeletonSetup at a given index. + /// The size of the given array must match the nodes count. + /// Note that the nodes count can change at any time. + /// @param p_SkeletonSetupIndex + /// @param p_SDK + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_NullPointer if the provided p_SDK (used to store the setup nodes) is a null pointer, it should be initialized to + /// an array with size equal to the nodes count, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + /// @deprecated Use GetSkeletonSetupNodesArray() instead + [[deprecated ("Use GetSkeletonSetupNodesArray() instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonSetupNodes(uint32_t p_SkeletonSetupIndex, NodeSetup* p_SDK); + + /// @brief Get setup nodes for a SkeletonSetup at a given index. + /// The size of the given array must match the nodes count. + /// Note that the nodes count can change at any time. + /// @param p_SkeletonSetupIndex + /// @param p_NodeSetupArray + /// @param p_ArraySize + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_NullPointer if the provided p_SDK (used to store the setup nodes) is a null pointer, it should be initialized to + /// an array with size equal to the nodes count, + /// SDKReturnCode_ArgumentSizeMismatch if the provided p_ArraySize is not equal to the nodes count, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonSetupNodesArray(uint32_t p_SkeletonSetupIndex, NodeSetup* p_NodeSetupArray, uint32_t p_ArraySize); + + /// @brief Get setup colliders for a SkeletonSetup at a given index. + /// The size of the given array must match the colliders count. + /// Note that the colliders count can change at any time. + /// @param p_SkeletonSetupIndex + /// @param p_SDK + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_NullPointer if the provided p_SDK (used to store the setup colliders) is a null pointer, it should be initialized to + /// an array with size equal to the colliders count, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + /// @deprecated + [[deprecated]] + CORESDK_API SDKReturnCode CoreSdk_GetSkeletonSetupColliders(uint32_t p_SkeletonSetupIndex, ColliderSetup* p_SDK); + + /// @brief Get the amount of nodes for the raw skeleton with given id + /// @param p_GloveId + /// @param p_NodeCount + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided glove id does not match any skeleton in core + CORESDK_API SDKReturnCode CoreSdk_GetRawSkeletonNodeCount(uint32_t p_GloveId, uint32_t& p_NodeCount); + + /// @brief Get the information for nodes of the raw skeleton with given id + /// The size of the given array p_NodeInfo must match the node count retrieved from CoreSdk_GetRawSkeletonNodeCount. + /// @param p_GloveId + /// @param p_NodeInfo + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided glove id does not match any skeleton in core + /// @deprecated Use CoreSdk_GetRawSkeletonNodeInfoArray instead + [[deprecated("Use CoreSdk_GetRawSkeletonNodeInfoArray instead")]] + CORESDK_API SDKReturnCode CoreSdk_GetRawSkeletonNodeInfo(uint32_t p_GloveId, NodeInfo* p_NodeInfo); + + + /// @brief Get the information for nodes of the raw skeleton with given id + /// The size of the given array p_NodeInfo and p_NodeCount must match the node count retrieved from CoreSdk_GetRawSkeletonNodeCount. + /// @param p_GloveId + /// @param p_NodeInfoArray + /// @param p_ArraySize + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_InvalidID if the provided glove id does not match any skeleton in core, + /// SDKReturnCode_ArgumentSizeMismatch if p_ArraySize does not match node count retrieved from CoreSdk_GetRawSkeletonNodeCount. + CORESDK_API SDKReturnCode CoreSdk_GetRawSkeletonNodeInfoArray(uint32_t p_GloveId, NodeInfo* p_NodeInfoArray, uint32_t p_ArraySize); + + /// @brief Sends a skeleton setup to core to become a skeleton upon which data is applied. + /// Returns the skeleton ID of the loaded skeleton, this ID is used to identify the skeleton in the SkeletonStreamCallback. + /// Loading a skeleton into core for retargetting removes it from the temporary skeletons array, thus causing + /// the p_SkeletonSetupIndex to no longer be valid after this call. + /// @param p_SkeletonSetupIndex The SkeletonSetup's index, will become invalid after this function. + /// @param p_SkeletonId This is the ID of the loaded skeleton. + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_LoadSkeleton(uint32_t p_SkeletonSetupIndex, uint32_t* p_SkeletonId); + + /// @brief Unload a skeleton with a certain ID from Manus Core, so data will no longer be generated for it. + /// @param p_SkeletonId The Skeleton's ID which is assigned by Manus Core. + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_UnloadSkeleton(uint32_t p_SkeletonId); + + /// @brief Save a SkeletonSetup at a given index and sessionId into Manus Core for use in the Dev Tools. + /// p_IsSkeletonModified is intended to be used mainly by the Dev Tools, it is set to true after saving any modification to the skeleton, + /// this triggers the OnSyStemCallback which is used in the SDK to be notified about a change to its temporary skeletons. + /// @param p_SkeletonSetupIndex + /// @param p_SessionId + /// @param p_IsSkeletonModified + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_SaveTemporarySkeleton(uint32_t p_SkeletonSetupIndex, uint32_t p_SessionId, bool p_IsSkeletonModified); + + /// @brief Send a temporary skeleton to Core to compress it (convert it into an array of bytes) and then get the compressed data back in the SDK, + /// the skeleton compressed data are stored internally. It returns the length of the bytes array for correct memory allocation. + /// This function must be called before CoreSdk_GetCompressedTemporarySkeletonData. + /// @param p_SkeletonSetupIndex + /// @param p_SessionId + /// @param p_TemporarySkeletonLengthInBytes + /// @return + CORESDK_API SDKReturnCode CoreSdk_CompressTemporarySkeletonAndGetSize(uint32_t p_SkeletonSetupIndex, uint32_t p_SessionId, uint32_t* p_TemporarySkeletonLengthInBytes); + + /// @brief Get the compressed temporary skeleton data which are stored internally when calling function CoreSdk_CompressTemporarySkeletonAndGetSize. + /// The size of p_TemporarySkeletonData must match with p_TemporarySkeletonLengthInBytes. + /// @param p_TemporarySkeletonData + /// @param p_TemporarySkeletonLengthInBytes + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_GetCompressedTemporarySkeletonData(unsigned char* p_TemporarySkeletonData, uint32_t p_TemporarySkeletonLengthInBytes); + + /// @brief Get a SkeletonSetup at a given index and sessionId from Manus Core. + /// This function does NOT return a loaded skeleton! + /// @param p_SkeletonSetupIndex + /// @param p_SessionId + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + CORESDK_API SDKReturnCode CoreSdk_GetTemporarySkeleton(uint32_t p_SkeletonSetupIndex, uint32_t p_SessionId); + + /// @brief Send the compressed data (an array of bytes) retrieved from a file to Core to be decompressed and converted back into a temporary skeleton. + /// The received temporary skeleton is saved internally with the given index and to the given session id. + /// The size of p_TemporarySkeletonData must match with p_TemporarySkeletonLengthInBytes. + /// @param p_SkeletonSetupIndex + /// @param p_SessionId + /// @param p_TemporarySkeletonData + /// @param p_TemporarySkeletonLengthInBytes + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + CORESDK_API SDKReturnCode CoreSdk_GetTemporarySkeletonFromCompressedData(uint32_t p_SkeletonSetupIndex, uint32_t p_SessionId, unsigned char* p_TemporarySkeletonData, uint32_t p_TemporarySkeletonLengthInBytes); + + /// @brief Clear a SkeletonSetup at a given index and sessionId in Manus Core and the SDK. + /// The given setup index will no longer be valid after this call. + /// @param p_SkeletonSetupIndex + /// @param p_SessionId + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_InvalidID if the provided p_SkeletonSetupIndex does not correspond to any skeleton setup. + CORESDK_API SDKReturnCode CoreSdk_ClearTemporarySkeleton(uint32_t p_SkeletonSetupIndex, uint32_t p_SessionId); + + /// @brief Clear all temporary skeletons associated to the current session both in the sdk and core. + /// All skeleton setups will no longer be valid after this call. + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_NotConnected if there is no connection to core, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + CORESDK_API SDKReturnCode CoreSdk_ClearAllTemporarySkeletons(); + + /// @brief Get temporary skeleton counts for all sessions connected to Core. + /// @param p_temporarySkeletonSessionsData + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_GetTemporarySkeletonCountForAllSessions(TemporarySkeletonCountForAllSessions* p_TemporarySkeletonCountForAllSessions); + + /// @brief Get information (name and index) for the SkeletonSetups of the specified session. + /// @param p_SessionId + /// @param p_temporarySkeletonSessionsData + /// @return SDKReturnCode_Success if successful, + /// SDKReturnCode_SdkNotAvailable if the Core SDK is not available, + /// SDKReturnCode_StubNullPointer if the stub has been reset but someone is trying to use it anyway. This usually happens after a shutdown of the SDK, + /// SDKReturnCode_NotConnected if there is no connection to core. + CORESDK_API SDKReturnCode CoreSdk_GetTemporarySkeletonsInfoForSession(uint32_t p_SessionId, TemporarySkeletonsInfoForSession* p_TemporarySkeletonsInfoForSession); + +#ifdef __cplusplus +} // extern "C" +#endif + +// Close the Doxygen group. +/** @} */ + +#endif // #ifndef H_MANUS_SDK diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDKTypeInitializers.h b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDKTypeInitializers.h new file mode 100644 index 0000000000000000000000000000000000000000..939bfd50325a1a917541f71b8466caabf079fe58 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDKTypeInitializers.h @@ -0,0 +1,397 @@ +#ifndef __MANUS_SDK_TYPE_INITIALIZERS_H__ +#define __MANUS_SDK_TYPE_INITIALIZERS_H__ + +// Set up a Doxygen group. +/** @addtogroup ManusSDKTypeInitializers + * @{ + */ + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ManusSDKTypes.h" + +#include + +#ifdef MANUS_SDK_STATIC + #define CORESDK_API +#else + #ifdef _WIN32 + // MANUS_SDK_EXPORTS defines if the functions are exported to or + // imported from a DLL. + #ifdef MANUS_SDK_EXPORTS + #define CORESDK_API __declspec(dllexport) + #else + #define CORESDK_API __declspec(dllimport) + #endif + #elif defined(__linux__) + #define CORESDK_API + #else + #error Unrecognized platform. + #endif +#endif + + ///@brief All these initializers take a preallocated instance of their related structure and set default values. + + /// @brief Initializer for a ManusVec3 struct + /// @param p_Val + CORESDK_API void ManusVec3_Init(ManusVec3* p_Val); + + /// @brief Initializer for a ManusVec2 struct + /// @param p_Val + CORESDK_API void ManusVec2_Init(ManusVec2* p_Val); + + /// @brief Initializer for a ManusQuaternion struct + /// @param p_Val + CORESDK_API void ManusQuaternion_Init(ManusQuaternion* p_Val); + + /// @brief Initializer for a ManusTransform struct + /// @param p_Val + CORESDK_API void ManusTransform_Init(ManusTransform* p_Val); + + /// @brief Initializer for a Color struct + /// @param p_Val + CORESDK_API void Color_Init(Color* p_Val); + + /// @brief Initializer for a ManusTimestampInfo struct + /// @param p_Val + CORESDK_API void ManusTimestampInfo_Init(ManusTimestampInfo* p_Val); + + /// @brief Initializer for a ManusTimestamp struct + /// @param p_Val + CORESDK_API void ManusTimestamp_Init(ManusTimestamp* p_Val); + + /// @brief Initializer for a IMUCalibrationInfo struct + /// @param p_Val + CORESDK_API void IMUCalibrationInfo_Init(IMUCalibrationInfo* p_Val); + + /// @brief Initializer for a Version struct + /// @param p_Val + CORESDK_API void Version_Init(Version* p_Val); + + /// @brief Initializer for a FirmwareVersion struct + /// @param p_Val + CORESDK_API void FirmwareVersion_Init(FirmwareVersion* p_Val); + + /// @brief Initializer for a ManusVersion struct + /// @param p_Val + CORESDK_API void ManusVersion_Init(ManusVersion* p_Val); + + /// @brief Initializer for a TrackerId struct + /// @param p_Val + CORESDK_API void TrackerId_Init(TrackerId* p_Val); + + /// @brief Initializer for a TrackerData struct + /// @param p_Val + CORESDK_API void TrackerData_Init(TrackerData* p_Val); + + /// @brief Initializer for a ManusHost struct + /// @param p_Val + CORESDK_API void ManusHost_Init(ManusHost* p_Val); + + /// @brief Initializer for a SkeletonNode struct + /// @param p_Val + CORESDK_API void SkeletonNode_Init(SkeletonNode* p_Val); + + /// @brief Initializer for a SkeletonInfo struct + /// @param p_Val + CORESDK_API void SkeletonInfo_Init(SkeletonInfo* p_Val); + + /// @brief Initializer for a RawSkeletonInfo struct + /// @param p_Val + CORESDK_API void RawSkeletonInfo_Init(RawSkeletonInfo* p_Val); + + /// @brief Initializer for a SkeletonStreamInfo struct + /// @param p_Val + CORESDK_API void SkeletonStreamInfo_Init(SkeletonStreamInfo* p_Val); + + /// @brief Initializer for a ErgonomicsData struct + /// @param p_Val + CORESDK_API void ErgonomicsData_Init(ErgonomicsData* p_Val); + + /// @brief Initializer for a ErgonomicsStream struct + /// @param p_Val + CORESDK_API void ErgonomicsStream_Init(ErgonomicsStream* p_Val); + + /// @brief Initializer for a DongleLandscapeData struct + /// @param p_Val + CORESDK_API void DongleLandscapeData_Init(DongleLandscapeData* p_Val); + + /// @brief Initializer for a GloveLandscapeData struct + /// @param p_Val + CORESDK_API void GloveLandscapeData_Init(GloveLandscapeData* p_Val); + + /// @brief Initializer for a Measurement struct + /// @param p_Val + CORESDK_API void Measurement_Init(Measurement* p_Val); + + /// @brief Initializer for a TrackerOffset struct + /// @param p_Val + CORESDK_API void TrackerOffset_Init(TrackerOffset* p_Val); + + /// @brief Initializer for a ExtraTrackerOffset struct + /// @param p_Val + CORESDK_API void ExtraTrackerOffset_Init(ExtraTrackerOffset* p_Val); + + /// @brief Initializer for a TrackerLandscapeData struct + /// @param p_Val + CORESDK_API void TrackerLandscapeData_Init(TrackerLandscapeData* p_Val); + + /// @brief Initializer for a UserProfileLandscapeData struct + /// @param p_Val + CORESDK_API void UserProfileLandscapeData_Init(UserProfileLandscapeData* p_Val); + + /// @brief Initializer for a UserLandscapeData struct + /// @param p_Val + CORESDK_API void UserLandscapeData_Init(UserLandscapeData* p_Val); + + /// @brief Initializer for a SkeletonLandscapeData struct + /// @param p_Val + CORESDK_API void SkeletonLandscapeData_Init(SkeletonLandscapeData* p_Val); + + /// @brief Initializer for a DeviceLandscape struct + /// @param p_Val + CORESDK_API void DeviceLandscape_Init(DeviceLandscape* p_Val); + + /// @brief Initializer for a UserLandscape struct + /// @param p_Val + CORESDK_API void UserLandscape_Init(UserLandscape* p_Val); + + /// @brief Initializer for a SkeletonLandscape struct + /// @param p_Val + CORESDK_API void SkeletonLandscape_Init(SkeletonLandscape* p_Val); + + /// @brief Initializer for a TrackerLandscape struct + /// @param p_Val + CORESDK_API void TrackerLandscape_Init(TrackerLandscape* p_Val); + + /// @brief Initializer for a LicenseInfo struct + /// @param p_Val + CORESDK_API void LicenseInfo_Init(LicenseInfo* p_Val); + + /// @brief Initializer for a SettingsLandscape struct + /// @param p_Val + CORESDK_API void SettingsLandscape_Init(SettingsLandscape* p_Val); + + /// @brief Initializer for a TimecodeInterface struct + /// @param p_Val + CORESDK_API void TimecodeInterface_Init(TimecodeInterface* p_Val); + + /// @brief Initializer for a TimeLandscape struct + /// @param p_Val + CORESDK_API void TimeLandscape_Init(TimeLandscape* p_Val); + + /// @brief Initializer for a GestureLandscapeData struct + /// @param p_Val + CORESDK_API void GestureLandscapeData_Init(GestureLandscapeData* p_Val); + + /// @brief Initializer for a NetDeviceLandscapeData struct + /// @param p_Val + CORESDK_API void NetDeviceLandscapeData_Init(NetDeviceLandscapeData* p_Val); + + /// @brief Initializer for a NetDevicesLandscape struct + /// @param p_Val + CORESDK_API void NetDevicesLandscape_Init(NetDevicesLandscape* p_Val); + + /// @brief Initializer for a Landscape struct + /// @param p_Val + CORESDK_API void Landscape_Init(Landscape* p_Val); + + /// @brief Initializer for a SkeletonSetupArraySizes struct + /// @param p_Val + CORESDK_API void SkeletonSetupArraySizes_Init(SkeletonSetupArraySizes* p_Val); + + /// @brief Initializer for a NodeSettingsIK struct + /// @param p_Val + CORESDK_API void NodeSettingsIK_Init(NodeSettingsIK* p_Val); + + /// @brief Initializer for a NodeSettingsFoot struct + /// @param p_Val + CORESDK_API void NodeSettingsFoot_Init(NodeSettingsFoot* p_Val); + + /// @brief Initializer for a NodeSettingsRotationOffset struct + /// @param p_Val + CORESDK_API void NodeSettingsRotationOffset_Init(NodeSettingsRotationOffset* p_Val); + + /// @brief Initializer for a NodeSettingsLeaf struct + /// @param p_Val + CORESDK_API void NodeSettingsLeaf_Init(NodeSettingsLeaf* p_Val); + + /// @brief Initializer for a NodeSettings struct + /// @param p_Val + CORESDK_API void NodeSettings_Init(NodeSettings* p_Val); + + /// @brief Initializer for a NodeSetup struct + /// @param p_Val + CORESDK_API void NodeSetup_Init(NodeSetup* p_Val); + + /// @brief Initializer for a ChainSettingsPelvis struct + /// @param p_Val + CORESDK_API void ChainSettingsPelvis_Init(ChainSettingsPelvis* p_Val); + + /// @brief Initializer for a ChainSettingsLeg struct + /// @param p_Val + CORESDK_API void ChainSettingsLeg_Init(ChainSettingsLeg* p_Val); + + /// @brief Initializer for a ChainSettingsSpine struct + /// @param p_Val + CORESDK_API void ChainSettingsSpine_Init(ChainSettingsSpine* p_Val); + + /// @brief Initializer for a ChainSettingsNeck struct + /// @param p_Val + CORESDK_API void ChainSettingsNeck_Init(ChainSettingsNeck* p_Val); + + /// @brief Initializer for a ChainSettingsHead struct + /// @param p_Val + CORESDK_API void ChainSettingsHead_Init(ChainSettingsHead* p_Val); + + /// @brief Initializer for a ChainSettingsArm struct + /// @param p_Val + CORESDK_API void ChainSettingsArm_Init(ChainSettingsArm* p_Val); + + /// @brief Initializer for a ChainSettingsShoulder struct + /// @param p_Val + CORESDK_API void ChainSettingsShoulder_Init(ChainSettingsShoulder* p_Val); + + /// @brief Initializer for a ChainSettingsFinger struct + /// @param p_Val + CORESDK_API void ChainSettingsFinger_Init(ChainSettingsFinger* p_Val); + + /// @brief Initializer for a ChainSettingsHand struct + /// @param p_Val + CORESDK_API void ChainSettingsHand_Init(ChainSettingsHand* p_Val); + + /// @brief Initializer for a ChainSettingsFoot struct + /// @param p_Val + CORESDK_API void ChainSettingsFoot_Init(ChainSettingsFoot* p_Val); + + /// @brief Initializer for a ChainSettingsToe struct + /// @param p_Val + CORESDK_API void ChainSettingsToe_Init(ChainSettingsToe* p_Val); + + /// @brief Initializer for a ChainSettings struct + /// @param p_Val + CORESDK_API void ChainSettings_Init(ChainSettings* p_Val); + + /// @brief Initializer for a ChainSetup struct + /// @param p_Val + CORESDK_API void ChainSetup_Init(ChainSetup* p_Val); + + /// @brief Initializer for a SphereColliderSetup struct + /// @param p_Val + CORESDK_API void SphereColliderSetup_Init(SphereColliderSetup* p_Val); + + /// @brief Initializer for a CapsuleColliderSetup struct + /// @param p_Val + CORESDK_API void CapsuleColliderSetup_Init(CapsuleColliderSetup* p_Val); + + /// @brief Initializer for a BoxColliderSetup struct + /// @param p_Val + CORESDK_API void BoxColliderSetup_Init(BoxColliderSetup* p_Val); + + /// @brief Initializer for a ColliderSetup struct + /// @param p_Val + CORESDK_API void ColliderSetup_Init(ColliderSetup* p_Val); + + /// @brief Initializer for a Vertex Weight struct + /// @param p_Val + CORESDK_API void Weight_Init(Weight* p_Val); + + /// @brief Initializer for a Vertex struct + /// @param p_Val + CORESDK_API void Vertex_Init(Vertex* p_Val); + + /// @brief Initializer for a Triangle struct + /// @param p_Val + CORESDK_API void Triangle_Init(Triangle* p_Val); + + /// @brief Initializer for a SkeletonTargetUserData struct + /// @param p_Val + CORESDK_API void SkeletonTargetUserData_Init(SkeletonTargetUserData* p_Val); + + /// @brief Initializer for a SkeletonTargetAnimationData struct + /// @param p_Val + CORESDK_API void SkeletonTargetAnimationData_Init(SkeletonTargetAnimationData* p_Val); + + /// @brief Initializer for a SkeletonTargetGloveData struct + /// @param p_Val + CORESDK_API void SkeletonTargetGloveData_Init(SkeletonTargetGloveData* p_Val); + + /// @brief Initializer for a SkeletonSettings struct + /// @param p_Val + CORESDK_API void SkeletonSettings_Init(SkeletonSettings* p_Val); + + /// @brief Initializer for a SkeletonSetupInfo struct + /// @param p_Val + CORESDK_API void SkeletonSetupInfo_Init(SkeletonSetupInfo* p_Val); + + /// @brief Initializer for a TemporarySkeletonInfo struct + /// @param p_Val + CORESDK_API void TemporarySkeletonInfo_Init(TemporarySkeletonInfo* p_Val); + + /// @brief Initializer for a TemporarySkeletonsForSession struct + /// @param p_Val + CORESDK_API void TemporarySkeletonsInfoForSession_Init(TemporarySkeletonsInfoForSession* p_Val); + + /// @brief Initializer for a TemporarySkeletonCountForSession struct + /// @param p_Val + CORESDK_API void TemporarySkeletonCountForSession_Init(TemporarySkeletonCountForSession* p_Val); + + /// @brief Initializer for a TemporarySkeletonCountForAllSessions struct + /// @param p_Val + CORESDK_API void TemporarySkeletonCountForAllSessions_Init(TemporarySkeletonCountForAllSessions* p_Val); + + /// @brief Initializer for a TemporarySkeletonSessionsData struct + /// @param p_Val + CORESDK_API void TemporarySkeletonSessionsData_Init(TemporarySkeletonSessionsData* p_Val); + + /// @brief Initializer for a SystemMessage struct + /// @param p_Val + CORESDK_API void SystemMessage_Init(SystemMessage* p_Val); + + /// @brief Initializer for a CoordinateSystemVUH struct + /// @param p_Val + CORESDK_API void CoordinateSystemVUH_Init(CoordinateSystemVUH* p_Val); + + /// @brief Initializer for a CoordinateSystemDirection struct + /// @param p_Val + CORESDK_API void CoordinateSystemDirection_Init(CoordinateSystemDirection* p_Val); + + /// @brief Initializer for a NodeInfo struct + /// @param p_Val + CORESDK_API void NodeInfo_Init(NodeInfo* p_Val); + + /// @brief Initializer for a GestureStreamInfo struct + /// @param p_Val + CORESDK_API void GestureStreamInfo_Init(GestureStreamInfo* p_Val); + + /// @brief Initializer for a GestureProbabilities struct + /// @param p_Val + CORESDK_API void GestureProbabilities_Init(GestureProbabilities* p_Val); + + /// @brief Initializer for a GestureProbability struct + /// @param p_Val + CORESDK_API void GestureProbability_Init(GestureProbability* p_Val); + + /// @brief Initializer for a GloveCalibrationArgs struct + /// @param p_Val + CORESDK_API void GloveCalibrationArgs_Init(GloveCalibrationArgs* p_Val); + + /// @brief Initializer for a GloveCalibrationStepArgs struct + /// @param p_Val + CORESDK_API void GloveCalibrationStepArgs_Init(GloveCalibrationStepArgs* p_Val); + + /// @brief Initializer for a GloveCalibrationStepData struct + /// @param p_Val + CORESDK_API void GloveCalibrationStepData_Init(GloveCalibrationStepData* p_Val); + +#ifdef __cplusplus +} // extern "C" +#endif + +// Close the Doxygen group. +/** @} */ + +#endif // #ifndef MANUS_SDK_TYPE_INITIALIZERS_H diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDKTypes.h b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDKTypes.h new file mode 100644 index 0000000000000000000000000000000000000000..7c45344c6fdd123371d088c66c66e68b460e0447 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/include/ManusSDKTypes.h @@ -0,0 +1,1717 @@ +#ifndef __MANUS_SDK_TYPES_H__ +#define __MANUS_SDK_TYPES_H__ + +// Set up a Doxygen group. +/** @addtogroup ManusSdkTypes + * @{ + */ + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +/****************************************************************************** + * Preprocessor defines. + *****************************************************************************/ + +/// @brief Used to descriptively refer to the number of fingers on a hand. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define NUM_FINGERS_ON_HAND 5 + +/// @brief Used to descriptively refer to the number of flex sensor segments. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define NUM_FLEX_SEGMENTS_PER_FINGER 2 + +/// @brief Used to descriptively refer to the maximum IMUs count on a glove. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUM_IMUS_ON_GLOVE (NUM_FINGERS_ON_HAND + 1) + +/// @brief Used to descriptively refer to the maximum number of Polygon users. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_USERS 16 // we should never reach that + +/// @brief Used to descriptively refer to the maximum user name length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_USERNAME 64 + +/// @brief Used to descriptively refer to the maximum body measurement name length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_MEASUREMENT 64 + +/// Host name length is based on a post made here: +/// https://community.cisco.com/t5/other-network-architecture/maximum-length-hostname/td-p/529327 +/// Which in turn was based on: https://www.ietf.org/rfc/rfc1035.txt +/// @brief Used to descriptively refer to the maximum host name length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_HOST_NAME 256 + +/// @brief Used to descriptively refer to the maximum IP address length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +/// It is based on the length of an IPv6 address. Example: +/// "2001:0db8:0000:0000:0000:8a2e:0370:7334". +#define MAX_NUM_CHARS_IN_IP_ADDRESS 40 + +/// @brief Used to descriptively refer to the maximum tracker name length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_TRACKER_ID 32 + +/// @brief Used to descriptively refer to the maximum tracker manufacturer length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_TRACKER_MANUFACTURER 32 + +/// @brief Used to descriptively refer to the maximum tracker manufacturer length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_TRACKER_PRODUCTNAME 32 + +/// @brief Used to descriptively refer to the maximum target name length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_TARGET_ID 32 + +/// @brief Used to descriptively refer to the maximum version string length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_VERSION 16 + +/// @brief Used to descriptively refer to the value given to glove and dongle IDs when they are uninitialized. +#define UNINITIALIZED_ID 0 + +/// @brief Used to descriptively refer to the maximum number of hosts that we support when finding manus core. +#define MAX_NUMBER_OF_HOSTS 100 + +/// @brief Used to descriptively refer to the max number of supported dongles. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUMBER_OF_DONGLES 16 // we only have 35 radio channels available. if we got 16 dongles, expect wireless issues! and no 16 usb ports is also not likely. + +/// @brief Used to descriptively refer to the maximum license type string length. +#define MAX_NUM_CHARS_IN_LICENSE_TYPE 64 + +/// @brief Used to descriptively refer to the maximum calibration step title length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_CALIBRATION_TITLE 64 + +/// @brief Used to descriptively refer to the maximum calibration step description length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_CALIBRATION_DESCRIPTION 256 + +#define MAX_NUM_CHARS_IN_CALIBRATION_FILE 65536 + +/// @brief Constants for the maximum number of devices considered plausible. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUMBER_OF_GLOVES (MAX_NUMBER_OF_DONGLES* 2) +#define MAX_NUMBER_OF_HAPTICS_DONGLES MAX_NUMBER_OF_DONGLES + +/// @brief Constants for the maximum number of skeletons. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUMBER_OF_SKELETONS 32 + +/// @brief Constants for the maximum number of users. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUMBER_OF_USERS MAX_USERS + +/// @brief Constants for the maximum number of trackers for each polygon skeleton. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define NUMBER_OF_TRACKERS_PER_POLYGON_SKELETON 8 + +/// @brief Constants for the maximum number of trackers. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUMBER_OF_TRACKERS (MAX_NUMBER_OF_USERS * NUMBER_OF_TRACKERS_PER_POLYGON_SKELETON) + +/// @brief Used to descriptively refer to the maximum node name length. +/// Used with arrays to make them more descriptive than simply using the +/// number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_NODE_NAME 256 // this is for a UTF8 string , NOT an ASCII CHAR array (same base type though) + + +/// @brief Used to descriptively refer to the max number of chain nodes. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_CHAIN_LENGTH 32 + +/// @brief Used to descriptively refer to the max number of fingers we support per hand in chains (not the same as a glove, as we can retarget alien hands with more or less fingers). +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUM_FINGER_IDS 10 + +/// @brief Used to descriptively refer to the max number of toes we support per foot in chains ( we can retarget alien feet with more or less toes). +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUM_TOE_IDS 10 + +/// @brief Used to descriptively refer to the max length of a system error message string. +/// Used with arrays to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_SYSTEM_ERROR_MESSAGE 256 + +/// @brief Used to descriptively refer to the max length of a debugging id string. +/// Used with arrays to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUM_CHAR_DEBUGGING_ID 64 + +/// @brief Used to descriptively refer to the max number of ergonomics data. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUMBER_OF_ERGONOMICS_DATA MAX_NUMBER_OF_GLOVES + +/// @brief Used to descriptively refer to the max number of sessions connected to Core. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUMBER_OF_SESSIONS 8 // this is not the real limit for Core but just for the SDKClient to handle + +/// @brief Used to descriptively refer to the max number of skeletons for each session. +/// Used with arrays and loops to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUMBER_OF_SKELETONS_PER_SESSION 32 + +/// @brief Used to descriptively refer to the max length of a skeleton name string. +/// Used with arrays to make them more descriptive than simply using +/// the number, and to make changing the number easier and safer. +#define MAX_NUM_CHARS_IN_SKELETON_NAME 256 // we already encountered 34 char names in unreal, but its utf8 so enbiggen even more! + +/// @brief Used to descriptively refer to the max length of a timecode interface string. +#define MAX_NUM_CHARS_IN_TIMECODE_INTERFACE_STRINGS 64 + +/// @brief Used to descriptively refer to the max amount of timecode interfaces. +#define MAX_NUMBER_OF_AUDIO_INTERFACES 32 + +/// @brief Used to descriptively refer to the maximum number of bone weights per vertex. +#define MAX_BONE_WEIGHTS_PER_VERTEX 4 + +/// @brief Used to descriptively refer to the maximum number of nodes per each estimation skeleton +#define MAX_NUMBER_OF_NODES_PER_ESTIMATION_SKELETON 40 + +/// @brief Used to define the max amount of gestures in one chunk +#define MAX_GESTURE_DATA_CHUNK_SIZE 64 + +#define MAX_NUM_CHARS_IN_OPENXR_FEATURE_STRING 64 + +/// @brief Used to define the max amount of net devices +#define MAX_NUMBER_OF_NETDEVICES MAX_NUMBER_OF_DONGLES + +/// @brief Matchmaker requirements. +#define BROADCAST_ADDRESS "255.255.255.255" +#define BROADCAST_PORT "62687" +#define SECONDS_TO_FIND_HOSTS 2 +#define SECONDS_TO_FIND_LOCAL_HOSTS 2 +#define DEFAULT_BUFFER_SIZE 512 + +/****************************************************************************** + * Enums. + *****************************************************************************/ + +/// @brief The return values that can be given by SDK wrapper functions. +typedef enum SDKReturnCode +{ + /// No issues occurred. + SDKReturnCode_Success, + + /// Something went wrong, but no specific reason can be given. + SDKReturnCode_Error, + + /// One of the arguments given had an invalid value. + SDKReturnCode_InvalidArgument, + + /// The size of an argument given (e.g. an array) does not match the size + /// of the data that it is intended to hold. + SDKReturnCode_ArgumentSizeMismatch, + + /// A string of an unsupported size was encountered. + SDKReturnCode_UnsupportedStringSizeEncountered, + + /// The Core SDK is not available. + SDKReturnCode_SdkNotAvailable, + + /// The network host finder is not available. + SDKReturnCode_HostFinderNotAvailable, + + /// The data requested is not available. + SDKReturnCode_DataNotAvailable, + + /// Failed to allocate memory for something. + SDKReturnCode_MemoryError, + + /// Something went wrong in the SDK internally. + SDKReturnCode_InternalError, + + /// The function was not intended to be called at this time. + SDKReturnCode_FunctionCalledAtWrongTime, + + /// No connection to Core was made. + SDKReturnCode_NotConnected, + + /// The connection with Core timed out. + SDKReturnCode_ConnectionTimeout, + + /// using an uninitialized ID is bad. + SDKReturnCode_InvalidID, + + /// memory unallocated or just a null pointer passed where it wasn't supposed to be! + SDKReturnCode_NullPointer, + + /// null sequence type for polygon calibration + SDKReturnCode_InvalidSequence, + + /// don't forget to set the coordinate system type or there will be trouble + SDKReturnCode_NoCoordinateSystemSet, + + /// if everything is being terminated. don't restart + SDKReturnCode_SdkIsTerminating, + + /// the stub has been reset but someone is tryign to use it anyway. usually after a shutdown of the SDK. + SDKReturnCode_StubNullPointer, + + /// Skeleton could not be loaded. usually when using more then the max skeletons per session (32). + SDKReturnCode_SkeletonNotLoaded, + + /// Function not available for this version of the SDK + SDKReturnCode_FunctionNotAvailable, + + SDKReturnCode_MAX_SIZE +} SDKReturnCode; + +/// @brief Used to tell what severity the log is +typedef enum LogSeverity +{ + LogSeverity_Debug, + LogSeverity_Info, + LogSeverity_Warn, + LogSeverity_Error +} LogSeverity; + + +/// @brief Used to tell what client is using the wrapper. +/// This makes the session easier to identify in the landscape. +typedef enum SessionType +{ + SessionType_Unknown, + SessionType_UnityPlugin, + SessionType_UnrealPlugin, + SessionType_CoreSDK, + SessionType_Xsens, + SessionType_Optitrack, + SessionType_MotionBuilder, + SessionType_VRED, + SessionType_OpenXR, + SessionType_Qualisys, + SessionType_Vicon, + SessionType_Nokov, + SessionType_IcIdo, + SessionType_Siemens +} SessionType; + +/// @brief Describes the different types of trackers that can be used. +typedef enum TrackerType +{ + TrackerType_Unknown, + TrackerType_Head, + TrackerType_Waist, + TrackerType_LeftHand, + TrackerType_RightHand, + TrackerType_LeftFoot, + TrackerType_RightFoot, + TrackerType_LeftUpperArm, + TrackerType_RightUpperArm, + TrackerType_LeftUpperLeg, + TrackerType_RightUpperLeg, + TrackerType_Controller, + TrackerType_Camera, + + TrackerType_MAX_SIZE +} TrackerType; + +/// @brief Describes the tracking quality. +typedef enum TrackingQuality +{ + TrackingQuality_Untrackable, + TrackingQuality_BadTracking, + TrackingQuality_Trackable, +} TrackerQuality; + +/// @brief Describes the different types of tracker systems. +typedef enum TrackerSystemType +{ + TrackerSystemType_Unknown, + TrackerSystemType_Antilatency, + TrackerSystemType_ART, + TrackerSystemType_OpenVR, + TrackerSystemType_Optitrack, + TrackerSystemType_Vicon, + TrackerSystemType_OpenXR, +} TrackerSystemType; + +/// @brief Describes the paired state of the device. +typedef enum DevicePairedState +{ + DevicePairedState_Unknown, + DevicePairedState_Paired, + DevicePairedState_Unpaired, + DevicePairedState_Pairing, +} DevicePairedState; + +/// @brief Describes the different types of device classes. +typedef enum DeviceClassType +{ + DeviceClassType_Unknown, + DeviceClassType_Dongle, + DeviceClassType_Glove, + DeviceClassType_Glongle +} DeviceClassType; + +/// @brief Describes the different types of Manus devices. +typedef enum DeviceFamilyType +{ + DeviceFamilyType_Unknown, + DeviceFamilyType_Prime1, + DeviceFamilyType_Prime2, + DeviceFamilyType_PrimeX, // TODO obsolete? + DeviceFamilyType_Metaglove, + DeviceFamilyType_Prime3, + DeviceFamilyType_Virtual, + DeviceFamilyType_MetaglovePro, +} DeviceFamilyType; + +/// @brief Describes the different types of profile used during the calibration. +typedef enum ProfileType +{ + ProfileType_Hands, + ProfileType_FullBody, + + ProfileType_MAX_SIZE +} ProfileType; + +/// @brief The different types of body measurements used for the polygon calibration. +typedef enum MeasurementType +{ + MeasurementType_Unknown, + MeasurementType_PlayerHeight, + MeasurementType_SpineLength, + MeasurementType_NeckLength, + MeasurementType_UpperArmLength, + MeasurementType_LowerArmLength, + MeasurementType_ArmLength, + MeasurementType_ArmSpan, + MeasurementType_UpperLegLength, + MeasurementType_LowerLegLength, + MeasurementType_LegLength, + MeasurementType_HandLength, + MeasurementType_FootLength, + MeasurementType_HipWidth, + MeasurementType_ShoulderWidth, + MeasurementType_ShoulderHeight, + MeasurementType_HeadLength, + MeasurementType_Thickness, + MeasurementType_ArmRatio, + MeasurementType_LegRatio, + + MeasurementType_MAX_SIZE // Warning, this value is used to define the UserProfile.Measurement[SIZE] +} MeasurementType; + +/// @brief Describes the different types of tracker offsets. +typedef enum TrackerOffsetType +{ + TrackerOffsetType_Unknown, + TrackerOffsetType_HeadTrackerToHead, + TrackerOffsetType_HeadTrackerToTopOfHead, + + TrackerOffsetType_LeftHandTrackerToWrist, + TrackerOffsetType_RightHandTrackerToWrist, + TrackerOffsetType_LeftFootTrackerToAnkle, + TrackerOffsetType_RightFootTrackerToAnkle, + + TrackerOffsetType_HipTrackerToHip, + TrackerOffsetType_HipTrackerToLeftLeg, + TrackerOffsetType_HipTrackerToRightLeg, + + TrackerOffsetType_LeftUpperArmTrackerToElbow, + TrackerOffsetType_RightUpperArmTrackerToElbow, + TrackerOffsetType_LeftUpperArmTrackerToShoulder, + TrackerOffsetType_RightUpperArmTrackerToShoulder, + + TrackerOffsetType_MAX_SIZE // Warning, this value is used to define the UserProfile.TrackerOffset[SIZE] +} TrackerOffsetType; + +/// @brief Describes the different types of extra tracker offsets. +typedef enum ExtraTrackerOffsetType +{ + ExtraTrackerOffsetType_Unknown, + ExtraTrackerOffsetType_HeadForward, + ExtraTrackerOffsetType_HipForward, + ExtraTrackerOffsetType_HipHeight, + ExtraTrackerOffsetType_MAX_SIZE // Warning, this value is used to define the UserProfile.TrackerOffset[SIZE] +} ExtraTrackerOffsetType; + +/// @brief Describes the different types of body measurement units. +typedef enum MeasurementUnit +{ + MeasurementUnit_Meters, + MeasurementUnit_Percentage, +} MeasurementUnit; + +/// @brief Describes the different types of body measurement categories used for the polygon calibration. +typedef enum MeasurementCategory +{ + MeasurementCategory_Misc, + MeasurementCategory_Generic, + MeasurementCategory_Arms, + MeasurementCategory_Legs, + MeasurementCategory_Body, +} MeasurementCategory; + +/// @brief Describes the different possibilities for the update status. +typedef enum UpdateStatusEnum +{ + UpdateStatusEnum_Unknown, + UpdateStatusEnum_NoUpdateAvailable, + UpdateStatusEnum_UpdateAvailable, + UpdateStatusEnum_MandatoryUpdateAvailable, + UpdateStatusEnum_Updating, +} UpdateStatusEnum; + +/// @brief Describes the different skeleton types. +typedef enum SkeletonType +{ + SkeletonType_Invalid, + SkeletonType_Hand, + SkeletonType_Body, + SkeletonType_Both +} SkeletonType; + +/// @brief Describes the possible data that can be used for the skeleton animation. +typedef enum SkeletonTargetType +{ + SkeletonTargetType_Invalid, + SkeletonTargetType_UserData, + SkeletonTargetType_UserIndexData, + SkeletonTargetType_AnimationData, + SkeletonTargetType_GloveData +} SkeletonTargetType; + +/// @brief Describes the possible nodes types used when setting up the skeleton. +typedef enum NodeType +{ + NodeType_Invalid, + NodeType_Joint, + NodeType_Mesh, + NodeType_Leaf, + NodeType_Collider +} NodeType; + +/// @brief Describes the settings that can be applied to a node, it is defined as a flag so that more than one setting can be set. +typedef enum NodeSettingsFlag +{ + NodeSettingsFlag_None = 0, + NodeSettingsFlag_IK = 1 << 0, + NodeSettingsFlag_Foot = 1 << 1, + NodeSettingsFlag_RotationOffset = 1 << 2, + NodeSettingsFlag_Leaf = 1 << 3, +} NodeSettingsFlag; + +/// @brief Describes the possible chain types used when setting up the skeleton. +typedef enum ChainType +{ + ChainType_Invalid, + ChainType_Arm, + ChainType_Leg, + ChainType_Neck, + ChainType_Spine, + ChainType_FingerThumb, + ChainType_FingerIndex, + ChainType_FingerMiddle, + ChainType_FingerRing, + ChainType_FingerPinky, + ChainType_Pelvis, + ChainType_Head, + ChainType_Shoulder, + ChainType_Hand, + ChainType_Foot, + ChainType_Toe +} ChainType; + +/// @brief Describes the possible collider types. +typedef enum CollisionType +{ + CollisionType_None, + CollisionType_Discrete, + CollisionType_Continuous, +} CollisionType; + +/// @brief Describes the possible collider types. +typedef enum ColliderType +{ + ColliderType_Invalid, + ColliderType_Sphere, + ColliderType_Capsule, + ColliderType_Box, +} ColliderType; + +/// @brief Describes the possible chain side. +typedef enum Side +{ + Side_Invalid, + Side_Left, + Side_Right, + Side_Center +} Side; + +/// @brief Describes which sensor data the hand motion is based on. +typedef enum HandMotion +{ + HandMotion_None, + HandMotion_IMU, + HandMotion_Tracker, + HandMotion_Tracker_RotationOnly, + HandMotion_Auto +} HandMotion; + +/// @brief Describes the direction of the coordinate system axis in 3d space. +typedef enum AxisDirection +{ + AxisDirection_Invalid, + AxisDirection_Backward, + AxisDirection_Left, + AxisDirection_Down, + AxisDirection_Up, + AxisDirection_Right, + AxisDirection_Forward +} AxisDirection; + +/// @brief Describes the view of the coordinate system axis. +/// Consider yourself sitting in front of your computer screen. +/// From Viewer means it goes into the screen, so away from you. +/// To Viewer means the axis goes from the screen towards you. +typedef enum AxisView +{ + AxisView_Invalid, + + AxisView_ZFromViewer, + AxisView_YFromViewer, + AxisView_XFromViewer, + + AxisView_XToViewer, + AxisView_YToViewer, + AxisView_ZToViewer +} AxisView; + +/// @brief Describes the polarity of the coordinate system axis. +typedef enum AxisPolarity +{ + AxisPolarity_Invalid, + + AxisPolarity_NegativeZ, + AxisPolarity_NegativeY, + AxisPolarity_NegativeX, + + AxisPolarity_PositiveX, + AxisPolarity_PositiveY, + AxisPolarity_PositiveZ +} AxisPolarity; + +/// @brief Describes the possible types for system messages received from core. +typedef enum SystemMessageType +{ + SystemMessageType_Unknown, + SystemMessageType_LibDebugReplugDongle, + SystemMessageType_LibDebugRxStall, + SystemMessageType_LibDebugTxStall, + + SystemMessageType_TrackerError, + SystemMessageType_TrackerOk, + SystemMessageType_TrackerSystemOutOfDate, + + SystemMessageType_GloveSanityErrorPSOCInit, + SystemMessageType_GloveSanityErrorQCBatV, + SystemMessageType_GloveSanityErrorQCLRACalib, + SystemMessageType_GloveSanityErrorQCFlexInit, + SystemMessageType_GloveSanityErrorQCIMUInit, + SystemMessageType_GloveSanityErrorQCIMUCalib, + SystemMessageType_GloveSanityErrorQCID, + SystemMessageType_GloveSanityErrorQCInterCPU, + + SystemMessageType_SessionConnectionVersionMismatch, + + SystemMessageType_TemporarySkeletonModified, + + SystemMessageType_SessionRefusedDueToLicenseIssue, + + SystemMessageType_LaunchDevTools +} SystemMessageType; + +/// @brief Describes the possible types for the ergonomics data. +typedef enum ErgonomicsDataType +{ +// ErgonomicsDataType_Invalid, + + ErgonomicsDataType_LeftFingerThumbMCPSpread, + ErgonomicsDataType_LeftFingerThumbMCPStretch, + ErgonomicsDataType_LeftFingerThumbPIPStretch, + ErgonomicsDataType_LeftFingerThumbDIPStretch, + + ErgonomicsDataType_LeftFingerIndexMCPSpread, + ErgonomicsDataType_LeftFingerIndexMCPStretch, + ErgonomicsDataType_LeftFingerIndexPIPStretch, + ErgonomicsDataType_LeftFingerIndexDIPStretch, + + ErgonomicsDataType_LeftFingerMiddleMCPSpread, + ErgonomicsDataType_LeftFingerMiddleMCPStretch, + ErgonomicsDataType_LeftFingerMiddlePIPStretch, + ErgonomicsDataType_LeftFingerMiddleDIPStretch, + + ErgonomicsDataType_LeftFingerRingMCPSpread, + ErgonomicsDataType_LeftFingerRingMCPStretch, + ErgonomicsDataType_LeftFingerRingPIPStretch, + ErgonomicsDataType_LeftFingerRingDIPStretch, + + ErgonomicsDataType_LeftFingerPinkyMCPSpread, + ErgonomicsDataType_LeftFingerPinkyMCPStretch, + ErgonomicsDataType_LeftFingerPinkyPIPStretch, + ErgonomicsDataType_LeftFingerPinkyDIPStretch, + + + ErgonomicsDataType_RightFingerThumbMCPSpread, + ErgonomicsDataType_RightFingerThumbMCPStretch, + ErgonomicsDataType_RightFingerThumbPIPStretch, + ErgonomicsDataType_RightFingerThumbDIPStretch, + + ErgonomicsDataType_RightFingerIndexMCPSpread, + ErgonomicsDataType_RightFingerIndexMCPStretch, + ErgonomicsDataType_RightFingerIndexPIPStretch, + ErgonomicsDataType_RightFingerIndexDIPStretch, + + ErgonomicsDataType_RightFingerMiddleMCPSpread, + ErgonomicsDataType_RightFingerMiddleMCPStretch, + ErgonomicsDataType_RightFingerMiddlePIPStretch, + ErgonomicsDataType_RightFingerMiddleDIPStretch, + + ErgonomicsDataType_RightFingerRingMCPSpread, + ErgonomicsDataType_RightFingerRingMCPStretch, + ErgonomicsDataType_RightFingerRingPIPStretch, + ErgonomicsDataType_RightFingerRingDIPStretch, + + ErgonomicsDataType_RightFingerPinkyMCPSpread, + ErgonomicsDataType_RightFingerPinkyMCPStretch, + ErgonomicsDataType_RightFingerPinkyPIPStretch, + ErgonomicsDataType_RightFingerPinkyDIPStretch, + + ErgonomicsDataType_MAX_SIZE +} ErgonomicsDataType; + +/// @brief Describes the possible Manus license types. +typedef enum LicenseType +{ + LicenseType_Undefined, + LicenseType_Polygon, + LicenseType_CoreXO, + LicenseType_CorePro, + LicenseType_CoreXOPro, + + LicenseType_CoreX, + LicenseType_CoreO, + LicenseType_CoreQ, + LicenseType_CoreXPro, + LicenseType_CoreOPro, + LicenseType_CoreQPro, + LicenseType_CoreXOQPro, + LicenseType_CoreXR, + LicenseType_CorePrimeThree, + LicenseType_Feature, + +} LicenseType; + +/// @brief The possible FPS rates +typedef enum TimecodeFPS +{ + TimecodeFPS_Undefined, + TimecodeFPS_23_976, + TimecodeFPS_24, + TimecodeFPS_25, + TimecodeFPS_29_97, + TimecodeFPS_30, + TimecodeFPS_48, + TimecodeFPS_50, + TimecodeFPS_59_94, + TimecodeFPS_60, + TimecodeFPS_29_97DF, + TimecodeFPS_59_94DF, +} TimecodeFPS; + +typedef enum FingerJointType +{ + FingerJointType_Invalid, + FingerJointType_Metacarpal, + FingerJointType_Proximal, + FingerJointType_Intermediate, + FingerJointType_Distal, //thumb doesn't have it + FingerJointType_Tip +}FingerJointType; + +typedef enum SetGloveCalibrationReturnCode +{ + SetGloveCalibrationReturnCode_Error, + SetGloveCalibrationReturnCode_Success, + SetGloveCalibrationReturnCode_VersionError, + SetGloveCalibrationReturnCode_WrongSideError, + SetGloveCalibrationReturnCode_GloveNotFoundError, + SetGloveCalibrationReturnCode_UserServiceError, + SetGloveCalibrationReturnCode_DeserializationError, + + SetGloveCalibrationReturnCode_MAX_SIZE +} SetGloveCalibrationReturnCode; + +/****************************************************************************** + * Structs. + *****************************************************************************/ + +/// @brief A 3D vector, used for translations. +typedef struct ManusVec3 +{ + float x; //default = 0.0f; + float y; //default = 0.0f; + float z; //default = 0.0f; +} ManusVec3; + +/// @brief A 2D vector, used for translations. +typedef struct ManusVec2 +{ + float x; //default = 0.0f; + float y; //default = 0.0f; +} ManusVec2; + +/// @brief A quaternion, used for rotations. +typedef struct ManusQuaternion +{ + float w; //default = 1.0f; + float x; //default = 0.0f; + float y; //default = 0.0f; + float z; //default = 0.0f; +} ManusQuaternion; + +/// @brief Transform containing position, rotation and scaling. +typedef struct ManusTransform +{ + ManusVec3 position; + ManusQuaternion rotation; + ManusVec3 scale; +} ManusTransform; + +/// @brief Color containing red, green, blue and alpha. +typedef struct Color +{ + float r; //default = 0.0f; + float g; //default = 0.0f; + float b; //default = 0.0f; + float a; //default = 0.0f; +}Color; + +/// @brief A Timestamp +typedef struct ManusTimestampInfo +{ + uint16_t fraction; //is either frame in timecode or miliseconds in non timecode + uint8_t second; + uint8_t minute; + uint8_t hour; + uint8_t day; //is 0 in timecode + uint8_t month; //is 0 in timecode + uint32_t year; //is 0 in timecode + bool timecode; +} ManusTimestampInfo; + +/// @brief A compressed timestamp +typedef struct ManusTimestamp +{ + uint64_t time; +} ManusTimestamp; + +/// @brief Information regarding IMU sensors used for calibration +typedef struct IMUCalibrationInfo +{ + uint32_t mag; // Magnometer calibration level 0-3 + uint32_t acc; // Accelerometer caibraton level 0-3 + uint32_t gyr; // Gyroscope calibration level 0-3 + uint32_t sys; // System accuracy +} IMUCalibrationInfo; + +/// @brief Used to describe hardware, firmware or ManusCore version. +typedef struct Version +{ + uint32_t major; + uint32_t minor; + uint32_t patch; + char label[MAX_NUM_CHARS_IN_VERSION]; + char sha[MAX_NUM_CHARS_IN_VERSION]; + char tag[MAX_NUM_CHARS_IN_VERSION]; +} Version; + +typedef struct FirmwareVersion +{ + int32_t version; + ManusTimestamp timestamp; +} FirmwareVersion; + +/// @brief Stores a single version string. +typedef struct ManusVersion +{ + char versionInfo[MAX_NUM_CHARS_IN_VERSION]; +} ManusVersion; + +/// @brief Contains information for connecting to a host running Manus Core. +/// Note that if one of these values is blank, the other will be used when +/// connecting. +typedef struct ManusHost +{ + char hostName[MAX_NUM_CHARS_IN_HOST_NAME]; // TODO utf8 compliant? + char ipAddress[MAX_NUM_CHARS_IN_IP_ADDRESS]; + Version manusCoreVersion; +} ManusHost; + +/****************************************************************************** + * Tracking + *****************************************************************************/ + + + +/// @brief Stores the name of a tracker. +typedef struct TrackerId +{ + char id[MAX_NUM_CHARS_IN_TRACKER_ID]; // todo. make this UTF8 compliant ? +} TrackerId; + +/// @brief Stores all the tracker data that can be sent or received. +typedef struct TrackerData +{ + ManusTimestamp lastUpdateTime; //default = 0; + + TrackerId trackerId; + + uint32_t userId; //default = 0; + + bool isHmd; //default = false; + TrackerType trackerType; //default = TrackerType::TrackerType_Unknown; + + ManusQuaternion rotation; + ManusVec3 position; + + TrackingQuality quality; //default = TrackingQuality::TrackingQuality_Untrackable; +} TrackerData; + + +/// @brief Stores the information sent by the tracker stream. +typedef struct TrackerStreamInfo +{ + ManusTimestamp publishTime; //default = 0; // DateTime.UtcNow. + uint32_t trackerCount; //default = 0; +} TrackerStreamInfo; + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Tracking +// ------------------------------------------------------------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------------------------------------------ +// Gesture Stream +// ------------------------------------------------------------------------------------------------------------------------------ + +typedef struct GestureProbability +{ + uint32_t id; + float percent; +} GestureProbability; + +typedef struct GestureProbabilities +{ + uint32_t id; //default = 0; + bool isUserID; //default = false; + uint32_t totalGestureCount; //default = 0; + GestureProbability gestureData[MAX_GESTURE_DATA_CHUNK_SIZE]; //default = { 0 }; + uint32_t gestureCount; //default = 0; +} GestureProbabilities; + +typedef struct GestureStreamInfo +{ + ManusTimestamp publishTime; //default = 0; // DateTime.UtcNow. + uint32_t gestureProbabilitiesCount; //default = 0; +} GestureStreamInfo; + + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Gesture Stream +// ------------------------------------------------------------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------------------------------------------ +// Skeleton Stream +// ------------------------------------------------------------------------------------------------------------------------------ + +/// @brief Stores the information regarding each skeleton node. +/// The transform is defined as a local or global transform depending on the coordinate system set when initializing the SDK. +/// See functions CoreSdk_InitializeCoordinateSystemWithVUH and CoreSdk_InitializeCoordinateSystemWithDirection. +typedef struct SkeletonNode +{ + uint32_t id; + ManusTransform transform; +} SkeletonNode; + +/// @brief Stores the information regarding the skeletons that have been added to Manus Core. +typedef struct SkeletonInfo +{ + uint32_t id; //default = 0; + uint32_t nodesCount; //default = 0; + ManusTimestamp publishTime; //default = 0; // DateTime.UtcNow. +} SkeletonInfo; + +/// @brief Stores the information regarding the skeletons coming from the estimation system in core +typedef struct RawSkeletonInfo +{ + uint32_t gloveId; //default = 0; + uint32_t nodesCount; //default = 0; + ManusTimestamp publishTime; //default = 0; // DateTime.UtcNow. +} RawSkeletonInfo; + +/// @brief Stores the information sent by the skeleton stream. +typedef struct SkeletonStreamInfo +{ + ManusTimestamp publishTime; //default = 0; // DateTime.UtcNow. + uint32_t skeletonsCount; //default = 0; +} SkeletonStreamInfo; + + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Skeleton Stream +// ------------------------------------------------------------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------------------------------------------ +// Ergonomics +// ------------------------------------------------------------------------------------------------------------------------------ + +/// @brief Stores the received ergonomics data. +typedef struct ErgonomicsData +{ + uint32_t id; //default = 0; + bool isUserID; //default = false; + float data[ErgonomicsDataType_MAX_SIZE]; //default = { 0 }; +} ErgonomicsData; + +/// @brief Stores the information sent by the ergonomics stream. +typedef struct ErgonomicsStream +{ + ManusTimestamp publishTime; //default = 0; + ErgonomicsData data[MAX_NUMBER_OF_ERGONOMICS_DATA]; + uint32_t dataCount; //default = 0; +} ErgonomicsStream; + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Ergonomics +// ------------------------------------------------------------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------------------------------------------ +// Landscape +// ------------------------------------------------------------------------------------------------------------------------------ + +/// @brief Stores all the received dongle data. +typedef struct DongleLandscapeData +{ + uint32_t id; + DeviceClassType classType; + DeviceFamilyType familyType; + bool isHaptics; + + Version hardwareVersion; + Version firmwareVersion; + ManusTimestamp firmwareTimestamp; + + uint32_t chargingState; + + int32_t channel; + + UpdateStatusEnum updateStatus; + + char licenseType[MAX_NUM_CHARS_IN_LICENSE_TYPE]; + + ManusTimestamp lastSeen; // this may be used in playback/recording TBD + + uint32_t leftGloveID; + uint32_t rightGloveID; + + LicenseType licenseLevel; //default = LicenseType::LicenseType_Undefined; + ManusTimestamp licenseExpiration; + + uint32_t netDeviceID; +} DongleLandscapeData; + +/// @brief Stores all the received glove data. +typedef struct GloveLandscapeData +{ + uint32_t id; + DeviceClassType classType; + DeviceFamilyType familyType; + Side side; + bool isHaptics; + + DevicePairedState pairedState; + uint32_t dongleID; + + Version hardwareVersion; + Version firmwareVersion; + ManusTimestamp firmwareTimestamp; + + UpdateStatusEnum updateStatus; + + uint32_t batteryPercentage; + int32_t transmissionStrength; + + IMUCalibrationInfo iMUCalibrationInfo[MAX_NUM_IMUS_ON_GLOVE]; + + ManusTimestamp lastSeen; // this may be used in playback/recording TBD + bool excluded; + + uint32_t netDeviceID; +} GloveLandscapeData; + +/// @brief Stores informations regarding the lengths of different parts of the body. +typedef struct Measurement +{ + MeasurementType entryType; //default = MeasurementType::MeasurementType_Unknown; + float value; //default = 0.0f; + + MeasurementUnit unit; //default = MeasurementUnit_Meters; + MeasurementCategory category; //default = MeasurementCategory_Misc; + char displayName[MAX_NUM_CHARS_IN_MEASUREMENT]; +} Measurement; + +/// @brief Stores the local offsets to the trackers. +typedef struct TrackerOffset +{ + TrackerOffsetType entryType; + ManusVec3 translation; + ManusQuaternion rotation; +} TrackerOffset; + +/// @brief Stores possible extra offsets to the trackers. +typedef struct ExtraTrackerOffset +{ + ExtraTrackerOffsetType entryType; //default = ExtraTrackerOffsetType::ExtraTrackerOffsetType_Unknown; + float value; //default = 0.0f; +} ExtraTrackerOffset; + +/// @brief Stores all the received tracker data. +typedef struct TrackerLandscapeData +{ + char id[MAX_NUM_CHARS_IN_TRACKER_ID]; + TrackerType type; //default = TrackerType::TrackerType_Unknown; + TrackerSystemType systemType; //default = TrackerSystemType::TrackerSystemType_Unknown; + uint32_t user; //default = 0; + bool isHMD; //default = false; + char manufacturer[MAX_NUM_CHARS_IN_TRACKER_MANUFACTURER]; // default = "Unknown" + char productName[MAX_NUM_CHARS_IN_TRACKER_PRODUCTNAME]; // default = "Unknown" +} TrackerLandscapeData; + +/// @brief Stores all the received user profile data. +typedef struct UserProfileLandscapeData +{ + ProfileType profileType; //default = ProfileType::ProfileType_Hands; + Measurement measurements[MeasurementType_MAX_SIZE]; + TrackerOffset trackerOffsets[TrackerOffsetType_MAX_SIZE]; + ExtraTrackerOffset extraTrackerOffsets[ExtraTrackerOffsetType_MAX_SIZE]; +} UserProfileLandscapeData; + +/// @brief Stores all the received user data. +typedef struct UserLandscapeData +{ + uint32_t id; //default = 0; + char name[MAX_NUM_CHARS_IN_USERNAME]; + Color color; + uint32_t dongleID; //default = 0; + uint32_t leftGloveID; //default = 0; + uint32_t rightGloveID; //default = 0; + UserProfileLandscapeData profile; + uint32_t userIndex; //default = 0; +} UserLandscapeData; + +/// @brief Stores all the received skeleton data. +typedef struct SkeletonLandscapeData +{ + uint32_t id; //default = 0; + char session[MAX_NUM_CHARS_IN_HOST_NAME]; + uint32_t userId; //default = 0; + SkeletonType type; //default = SkeletonType::SkeletonType_Invalid; + char rootBoneName[MAX_NUM_CHARS_IN_NODE_NAME]; + bool scaled; //default = false; +} SkeletonLandscapeData; + +/// @brief Stores all the information related to the devices present in the landscape. +typedef struct DeviceLandscape +{ + DongleLandscapeData dongles[MAX_NUMBER_OF_DONGLES]; + uint32_t dongleCount; //default = 0; + GloveLandscapeData gloves[MAX_NUMBER_OF_GLOVES]; + uint32_t gloveCount; //default = 0; +} DeviceLandscape; + +/// @brief Stores all the information related to the users present in the landscape. +typedef struct UserLandscape +{ + UserLandscapeData users[MAX_USERS]; + uint32_t userCount; //default = 0; +} UserLandscape; + +/// @brief Stores all the information related to the skeletons present in the landscape. +typedef struct SkeletonLandscape +{ + SkeletonLandscapeData skeletons[MAX_NUMBER_OF_SKELETONS]; + uint32_t skeletonCount; //default = 0; +} SkeletonLandscape; + +/// @brief Stores all the information related to the trackers present in the landscape. +typedef struct TrackerLandscape +{ + TrackerLandscapeData trackers[MAX_NUMBER_OF_TRACKERS]; + uint32_t trackerCount; //default = 0; +} TrackerLandscape; + +/// @brief Stores the license information. +typedef struct LicenseInfo +{ + bool recording; //default = false; + bool exporting; //default = false; + bool advancedExporting; //default = false; + bool unitySession; //default = false; + bool unrealSession; //default = false; + bool openXRSession; //default = false; + bool sdk; //default = false; + bool raw; //default = false; + bool mobuSession; //default = false; + bool xsensSession; //default = false; + bool optitrackSession; //default = false; + bool qualisysSession; //default = false; + bool viconSession; //default = false; + bool nokovSession; //default = false; + bool icidoSession; //default = false; + bool siemensSession; //default = false; + bool vredSession; //default = false; + +} LicenseInfo; + +/// @brief Stores the landscape settings. +typedef struct SettingsLandscape +{ + Version manusCoreVersion; + LicenseInfo license; + bool playbackMode; //default = false; + bool ignoreSessionTimeOuts; //default = false; + FirmwareVersion firmwareOne; + FirmwareVersion firmwareTwo; + bool recordingMode; //default = false; + bool isNetDevice; // default = false; + bool isConnectedAsNetDevice; // default = false; +}SettingsLandscape; + +typedef struct TimecodeInterface +{ + char name[MAX_NUM_CHARS_IN_TIMECODE_INTERFACE_STRINGS]; + char api[MAX_NUM_CHARS_IN_TIMECODE_INTERFACE_STRINGS]; + int index; //default = -1; +} TimecodeInterface; + +typedef struct TimeLandscape +{ + TimecodeInterface interfaces[MAX_NUMBER_OF_AUDIO_INTERFACES]; + uint32_t interfaceCount; //default = 0; + TimecodeInterface currentInterface; + TimecodeFPS fps; //default = Undefined; + bool fakeTimecode; //default = false; + bool useSyncPulse; //default = false; + bool deviceKeepAlive; //default = false; + bool syncStatus; //default = false; + bool timecodeStatus; //default = false; + int32_t ltcChannel; //default = -1; +} TimeLandscape; + +/// @brief Contains information about a gesture +typedef struct GestureLandscapeData +{ + uint32_t id; //default = 0; + char name[MAX_NUM_CHARS_IN_USERNAME]; +} GestureLandscapeData; + +/// @brief Contains information about a net devices +typedef struct NetDeviceLandscapeData +{ + uint32_t netDeviceID; + char hostname[MAX_NUM_CHARS_IN_HOST_NAME]; + char ip[MAX_NUM_CHARS_IN_IP_ADDRESS]; +} NetDeviceLandscapeData; + +/// @brief Contains information about a single net device +typedef struct NetDevicesLandscape +{ + uint32_t numberOfNetDevices; // default = 0; + NetDeviceLandscapeData netDevices[MAX_NUMBER_OF_NETDEVICES]; +} NetDeviceLandscape; + +/// @brief Stores the landscape data. +typedef struct Landscape +{ + DeviceLandscape gloveDevices; + UserLandscape users; + SkeletonLandscape skeletons; + TrackerLandscape trackers; + SettingsLandscape settings; + NetDevicesLandscape netDevices; + TimeLandscape time; + uint32_t gestureCount; //default = 0; +} Landscape; + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Landscape +// ------------------------------------------------------------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------------------------------------------ +// Skeleton +// ------------------------------------------------------------------------------------------------------------------------------ +/// @brief Stores the inverse kinematics settings of a node, the ikAim is used to control the IK solve, 1 is default, -1 is inversed. +typedef struct NodeSettingsIK +{ + float ikAim; +} NodeSettingsIK; + +/// @brief Stores the settings for a node of type foot, heightFromGround is used to set the height of the 3d model ankle from ground. +typedef struct NodeSettingsFoot +{ + float heightFromGround; +} NodeSettingsFoot; + +/// @brief Stores the rotation offset of a node, this is used internally for building the skeleton. +typedef struct NodeSettingsRotationOffset +{ + ManusQuaternion value; +} NodeSettingsRotationOffset; + +/// @brief Stores the settings of a node of type leaf, the direction vector is defined with respect to the previous node in the chain. +typedef struct NodeSettingsLeaf +{ + ManusVec3 direction; + float length; +} NodeSettingsLeaf; + +/// @brief Stores all the node settings. +typedef struct NodeSettings +{ + NodeSettingsFlag usedSettings; + NodeSettingsIK ik; + NodeSettingsFoot foot; + NodeSettingsRotationOffset rotationOffset; + NodeSettingsLeaf leaf; +} NodeSettings; + +/// @brief Stores the node setup information. Each node represents a segment of the skeleton that can be animated, nodes combine together to form chains. +/// the parentID is used to identify the node with respect to which the current one will move. +typedef struct NodeSetup +{ + uint32_t id; //default = 0; + char name[MAX_NUM_CHARS_IN_NODE_NAME]; // this is a UTF8 string , NOT an ASCII CHAR array (same base type though) + NodeType type; //default = NodeType::NodeType_Invalid; + ManusTransform transform; + uint32_t parentID; //default = 0; + NodeSettings settings; +} NodeSetup; + +/// @brief Stores all the settings of a chain of type pelvis. +typedef struct ChainSettingsPelvis +{ + float hipHeight; //default = 0.0f; + float hipBendOffset; //default = 0.0f; + float thicknessMultiplier; //default = 1.0f; +} ChainSettingsPelvis; + +/// @brief Stores all the settings of a chain of type leg. +typedef struct ChainSettingsLeg +{ + bool reverseKneeDirection; //default = false; + float kneeRotationOffset; //default = 0.0f; + float footForwardOffset; //default = 0.0f; + float footSideOffset; //default = 0.0f; +} ChainSettingsLeg; + +/// @brief Stores all the settings of a chain of type spine. +typedef struct ChainSettingsSpine +{ + float spineBendOffset; //default = 0.0f; +} ChainSettingsSpine; + +/// @brief Stores all the settings of a chain of type neck. +typedef struct ChainSettingsNeck +{ + float neckBendOffset; //default = 0.0f; +} ChainSettingsNeck; + +/// @brief Stores all the settings of a chain of type head. +typedef struct ChainSettingsHead +{ + float headPitchOffset; //default = 0.0f; + float headYawOffset; //default = 0.0f; + float headTiltOffset; //default = 0.0f; + bool useLeafAtEnd; //default = false; +} ChainSettingsHead; + +/// @brief Stores all the settings of a chain of type arm. +typedef struct ChainSettingsArm +{ + float armLengthMultiplier; //default = 0.0f; + float elbowRotationOffset; //default = 0.0f; + + ManusVec3 armRotationOffset; + + ManusVec3 positionMultiplier; + ManusVec3 positionOffset; +} ChainSettingsArm; + +/// @brief Stores all the settings of a chain of type shoulder. +typedef struct ChainSettingsShoulder +{ + float forwardOffset; //default = 0.0f; + float shrugOffset; //default = 0.0f; + + float forwardMultiplier; //default = 0.0f; + float shrugMultiplier; //default = 0.0f; +} ChainSettingsShoulder; + +/// @brief Stores all the settings of a chain of type finger. +typedef struct ChainSettingsFinger +{ + bool useLeafAtEnd; //default = false; + int32_t metacarpalBoneId; //default = 0; + int32_t handChainId; //default = 0; + float fingerWidth; //default = 0; +} ChainSettingsFinger; + +/// @brief Stores all the settings of a chain of type hand. +typedef struct ChainSettingsHand +{ + int32_t fingerChainIds[MAX_NUM_FINGER_IDS]; + int32_t fingerChainIdsUsed; //default = 0; + HandMotion handMotion; //default = HandMotion::HandMotion_None; +} ChainSettingsHand; + +/// @brief Stores all the settings of a chain of type foot. +typedef struct ChainSettingsFoot +{ + int32_t toeChainIds[MAX_NUM_TOE_IDS]; + int32_t toeChainIdsUsed; //default = 0; +} ChainSettingsFoot; + +/// @brief Stores all the settings of a chain of type toe. +typedef struct ChainSettingsToe +{ + int32_t footChainId; //default = 0; + bool useLeafAtEnd; //default = false; +} ChainSettingsToe; + +/// @brief Stores all chain settings. +typedef struct ChainSettings +{ + ChainType usedSettings; + ChainSettingsPelvis pelvis; + ChainSettingsLeg leg; + ChainSettingsSpine spine; + ChainSettingsNeck neck; + ChainSettingsHead head; + ChainSettingsArm arm; + ChainSettingsShoulder shoulder; + ChainSettingsFinger finger; + ChainSettingsHand hand; + ChainSettingsFoot foot; + ChainSettingsToe toe; +} ChainSettings; + +/// @brief Stores the chain setup information. +typedef struct ChainSetup +{ + uint32_t id; //default = 0; + ChainType type; //default = ChainType::ChainType_Invalid; + ChainType dataType; //default = ChainType::ChainType_Invalid; + uint32_t dataIndex; //default = 0; + uint32_t nodeIdCount; //default = 0; + uint32_t nodeIds[MAX_CHAIN_LENGTH]; + ChainSettings settings; + Side side; //default = Side::Side_Invalid; +} ChainSetup; + +/// @brief Stores all the settings of a collider of type sphere. +typedef struct SphereColliderSetup +{ + float radius; //default = 0; +} SphereColliderSetup; + +/// @brief Stores all the settings of a collider of type capsule. +typedef struct CapsuleColliderSetup +{ + float radius; //default = 0; + float length; //default = 0; +} CapsuleColliderSetup; + +/// @brief Stores all the settings of a collider of type box. +typedef struct BoxColliderSetup +{ + ManusVec3 size; //default = 0,0,0; +} BoxColliderSetup; + +/// @brief Stores the collider setup information. +typedef struct ColliderSetup +{ + uint32_t nodeID; //default = 0; + ManusVec3 localPosition; // default 0,0,0 + ManusVec3 localRotation; // default 0,0,0 + + ColliderType type;//default = ColliderType::ColliderType_Invalid + SphereColliderSetup sphere; + CapsuleColliderSetup capsule; + BoxColliderSetup box; +} ColliderSetup; + +/// @brief Stores the vertex weight information. +typedef struct Weight +{ + uint32_t nodeID; + float weightValue; +} Weight; + +/// @brief Stores the vertex information. +typedef struct Vertex +{ + ManusVec3 position; // default 0,0,0 + uint32_t weightsCount; //default = 0; + Weight weights[MAX_BONE_WEIGHTS_PER_VERTEX]; +} Vertex; + +/// @brief Stores the triangle information. +typedef struct Triangle +{ + int32_t vertexIndex1; + int32_t vertexIndex2; + int32_t vertexIndex3; +} Triangle; + +/// @brief Stores the information regarding the user data used to animate the skeleton. +typedef struct SkeletonTargetUserData +{ + uint32_t userID; //default = 0; +} SkeletonTargetUserData; + +/// @brief Stores the information regarding the user index data used to animate the skeleton. +typedef struct SkeletonTargetUserIndexData +{ + uint32_t userIndex; //default = 0; +} SkeletonTargetUserIndexData; + +/// @brief Stores the information regarding the animation data used to animate the skeleton. +typedef struct SkeletonTargetAnimationData +{ + char id[MAX_NUM_CHARS_IN_TARGET_ID]; +} SkeletonTargetAnimationData; + +/// @brief Stores the information regarding the glove data used to animate the skeleton. +typedef struct SkeletonTargetGloveData +{ + uint32_t gloveID; //default = 0; +} SkeletonTargetGloveData; + +/// @brief Stores all the possible skeleton settings. +typedef struct SkeletonSettings +{ + bool scaleToTarget; //default = false; + bool useEndPointApproximations; //default = false; + CollisionType collisionType; //default = CollisionType::CollisionType_None + + SkeletonTargetType targetType; + SkeletonTargetUserData skeletonTargetUserData; + SkeletonTargetUserIndexData skeletonTargetUserIndexData; + SkeletonTargetAnimationData skeletonTargetAnimationData; + SkeletonTargetGloveData skeletonGloveData; +} SkeletonSettings; + +/// @brief Stores the skeleton setup information. +typedef struct SkeletonSetupInfo +{ + uint32_t id; //default = 0; + SkeletonType type; //default = SkeletonType::SkeletonType_Invalid; + SkeletonSettings settings; + char name[MAX_NUM_CHARS_IN_SKELETON_NAME]; // this is a UTF8 string , NOT an ASCII CHAR array (same base type though) +} SkeletonSetupInfo; + + +/// @brief Stores the amount of nodes and chains in the skeleton setup. +typedef struct SkeletonSetupArraySizes +{ + uint32_t nodesCount; //default = 0; + uint32_t chainsCount; //default = 0; + uint32_t collidersCount; //default = 0; + uint32_t meshCount; //default = 0; +} SkeletonSetupArraySizes; + +/// @brief Stores the temporary skeleton information. +typedef struct TemporarySkeletonInfo +{ + char name[MAX_NUM_CHARS_IN_SKELETON_NAME]; // this is a UTF8 string , NOT an ASCII CHAR array (same base type though) + uint32_t index; //default = UINT32_MAX; +} TemporarySkeletonInfo; + +/// @brief Stores the temporary skeletons available for a specific session. +typedef struct TemporarySkeletonsInfoForSession +{ + uint32_t sessionId; //default = 0; + char sessionName[MAX_NUM_CHARS_IN_HOST_NAME]; + uint32_t skeletonCount; //default = 0; + TemporarySkeletonInfo skeletonInfo[MAX_NUMBER_OF_SKELETONS_PER_SESSION]; +} TemporarySkeletonsInfoForSession; + +/// @brief Stores the temporary skeletons available for a specific session. +typedef struct TemporarySkeletonCountForSession +{ + uint32_t sessionId; //default = 0; + char sessionName[MAX_NUM_CHARS_IN_HOST_NAME]; + uint32_t skeletonCount; //default = 0; +} TemporarySkeletonCountForSession; + +/// @brief Stores the temporary skeleton available for all sessions connected to Core. +typedef struct TemporarySkeletonCountForAllSessions +{ + uint32_t sessionsCount; //default = 0; + TemporarySkeletonCountForSession temporarySkeletonCountForSessions[MAX_NUMBER_OF_SESSIONS]; +} TemporarySkeletonCountForAllSessions; + +/// @brief ONLY USED INTERNALLY +/// @brief Stores the temporary skeleton available for all sessions connected to Core. +typedef struct TemporarySkeletonSessionsData +{ + uint32_t sessionsCount; //default = 0; + TemporarySkeletonsInfoForSession temporarySkeletonsSessions[MAX_NUMBER_OF_SESSIONS]; +} TemporarySkeletonSessionsData; + +/// @brief Stores the data associated to System messages received from Core. +typedef struct SystemMessage +{ + SystemMessageType type; + char infoString[MAX_NUM_CHARS_IN_SYSTEM_ERROR_MESSAGE]; + uint32_t infoUInt; +} SystemMessage; + +typedef struct NodeInfo +{ + uint32_t nodeId; //default = 0; + uint32_t parentId; //default = 0; + ChainType chainType; + Side side; + FingerJointType fingerJointType; +}NodeInfo; + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Skeleton +// ------------------------------------------------------------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------------------------------------------ +// Glove calibration +// ------------------------------------------------------------------------------------------------------------------------------ + +typedef struct GloveCalibrationArgs { + uint32_t gloveId; //default = 0; +} GloveCalibrationArgs; + +typedef struct GloveCalibrationStepArgs { + uint32_t gloveId; //default = 0; + uint32_t stepIndex; //default = 0; +} GloveCalibrationStepArgs; + +/// @brief Stores the data associated to a single calibration step for a specific glove. +/// if the time value is negative, it means that its a continuous step and the value is estimated +typedef struct GloveCalibrationStepData { + uint32_t index; //default = 0; + char title[MAX_NUM_CHARS_IN_CALIBRATION_TITLE]; + char description[MAX_NUM_CHARS_IN_CALIBRATION_DESCRIPTION]; + float time; //default = 0 +} GloveCalibrationStepData; + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Glove calibration +// ------------------------------------------------------------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------------------------------------------ +// Coordinate system settings +// ------------------------------------------------------------------------------------------------------------------------------ + +/// @brief Stores the information regarding the coordinate system used by the client, defined as VUH (view, up, handedness). +typedef struct CoordinateSystemVUH +{ + AxisView view; + AxisPolarity up; + Side handedness; + float unitScale; // in meters +} CoordinateSystemVUH; + +/// @brief Stores the information regarding the coordinate system used by the client, defined by each axis direction. +typedef struct CoordinateSystemDirection +{ + AxisDirection x; + AxisDirection y; + AxisDirection z; + float unitScale; // in meters +} CoordinateSystemDirection; + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Coordinate system settings +// ------------------------------------------------------------------------------------------------------------------------------ + +// ------------------------------------------------------------------------------------------------------------------------------ +// Callbacks +// ------------------------------------------------------------------------------------------------------------------------------ + +/// @brief Describes the ConnectedToCoreCallback function type +typedef void(*ConnectedToCoreCallback_t)(const ManusHost* const p_Host); +/// @brief Describes the DisconnectedToCoreCallback function type +typedef void(*DisconnectedFromCoreCallback_t)(const ManusHost* const p_Host); +/// @brief Describes the LoggingCallback function type +typedef void(*LoggingCallback_t)(LogSeverity p_Severity, const char* const p_Log, uint32_t p_Length); +/// @brief Describes the SkeletonStreamCallback function type +typedef void(*SkeletonStreamCallback_t)(const SkeletonStreamInfo* const p_SkeletonInfo); +/// @brief Describes the LandscapeStreamCallback function type +typedef void(*LandscapeStreamCallback_t)(const Landscape* const p_Landscape); +/// @brief Describes the TrackerStreamCallback function type +typedef void(*TrackerStreamCallback_t)(const TrackerStreamInfo* const p_TrackerStreamInfo); +/// @brief Describes the ErgonomicsStreamCallback type +typedef void(*ErgonomicsStreamCallback_t)(const ErgonomicsStream* const p_Ergonomics); +/// @brief Describes the SystemStreamCallback function type +typedef void(*SystemStreamCallback_t)(const SystemMessage* const p_SystemMessage); +/// @brief Describes the RawSkeletonStreamCallback function type +typedef void(*RawSkeletonStreamCallback_t)(const SkeletonStreamInfo* const p_SkeletonInfo); +/// @brief Describes the GestureStreamCallback function type +typedef void(*GestureStreamCallback_t)(const GestureStreamInfo* const p_GestureStream); + +// ------------------------------------------------------------------------------------------------------------------------------ +// end of Callbacks +// ------------------------------------------------------------------------------------------------------------------------------ +#ifdef __cplusplus +} // extern "C" +#endif + +// Close the Doxygen group. +/** @} */ + +#endif // #ifndef H_CORESDKWRAPPERTYPES diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Readme.md b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..4da29144412c3fe42f16e54d53405465e4b42f1b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/Readme.md @@ -0,0 +1,4 @@ +# MANUS SDK Client - Linux +The MANUS SDK Client is an example client that demonstrates the most functionality of the MANUS SDK. It handles setting up a connection to the gloves (be it directly or via a MANUS Core instance). And implements all major features available in the MANUS SDK. + +For a full guide on how to get started please refer to the guide on our knowledge center: https://docs.manus-meta.com/latest/Plugins/SDK/Windows/SDK%20Client/ \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient.cpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1cb5aad57c889882ef0ec27f5e95f19660b80006 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient.cpp @@ -0,0 +1,3118 @@ +#include "SDKClient.hpp" +#include "ManusSDKTypes.h" +#include "ClientLogging.hpp" +#include +#include +#include +#include +#include +#include + +#include "ClientPlatformSpecific.hpp" + +#define GO_TO_DISPLAY(p_Key,p_Function) if (GetKeyDown(p_Key)) { ClearConsole();\ + m_CurrentInteraction = std::bind(&SDKClient::p_Function, this); return ClientReturnCode::ClientReturnCode_Success;} + +#define GO_TO_MENU_IF_REQUESTED() if (GetKeyDown('Q')) { ClearConsole();\ + m_CurrentInteraction = nullptr; return ClientReturnCode::ClientReturnCode_Success;} + +using ManusSDK::ClientLog; + +std::map> output_map; + +SDKClient* SDKClient::s_Instance = nullptr; + +std::vector idleft={3822396207, 3998055887}; +std::vector idright={3762867141, 831307785}; + +SDKClient::SDKClient() +{ + s_Instance = this; + + // using initializers like these ensure that the data is set to its default values. + ErgonomicsData_Init(&m_LeftGloveErgoData); + ErgonomicsData_Init(&m_RightGloveErgoData); + + TestTimestamp(); +} + +SDKClient::~SDKClient() +{ + s_Instance = nullptr; +} + +/// @brief Initialize the sample console and the SDK. +/// This function attempts to resize the console window and then proceeds to initialize the SDK's interface. +ClientReturnCode SDKClient::Initialize() +{ + // if (!PlatformSpecificInitialization()) + // { + // return ClientReturnCode::ClientReturnCode_FailedPlatformSpecificInitialization; + // } + + const ClientReturnCode t_IntializeResult = InitializeSDK(); + if (t_IntializeResult != ClientReturnCode::ClientReturnCode_Success) + { + ClientLog::error("Failed to initialize the SDK. Are you sure the correct ManusSDKLibary is used?"); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief The main SDKClient loop. +/// This is a simple state machine which switches between different substates. +ClientReturnCode SDKClient::Run() +{ + ConnectingToCore(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief When you are done with the SDK, don't forget to nicely shut it down +/// this will close all connections to the host, close any threads and clean up after itself +/// after this is called it is expected to exit the client program. If not it needs to call initialize again. +ClientReturnCode SDKClient::ShutDown() +{ + const SDKReturnCode t_Result = CoreSdk_ShutDown(); + if (t_Result != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to shut down the SDK wrapper. The value returned was {}.", (int32_t)t_Result); + return ClientReturnCode::ClientReturnCode_FailedToShutDownSDK; + } + + if (!PlatformSpecificShutdown()) + { + return ClientReturnCode::ClientReturnCode_FailedPlatformSpecificShutdown; + } + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief Gets called when the client is connects to manus core +/// Using this callback is optional. +/// In this sample we use this callback to change the client's state and switch to another screen +void SDKClient::OnConnectedCallback(const ManusHost* const p_Host) +{ + ClientLog::print("Connected to manus core."); + + //No need to initialize these as they get filled in the CoreSdk_GetVersionsAndCheckCompatibility + ManusVersion t_SdkVersion; + ManusVersion t_CoreVersion; + bool t_IsCompatible; + + const SDKReturnCode t_Result = CoreSdk_GetVersionsAndCheckCompatibility(&t_SdkVersion, &t_CoreVersion, &t_IsCompatible); + + if (t_Result == SDKReturnCode::SDKReturnCode_Success) + { + const std::string t_Versions = "Sdk version : " + std::string(t_SdkVersion.versionInfo) + ", Core version : " + std::string(t_CoreVersion.versionInfo) + "."; + + if (t_IsCompatible) + { + ClientLog::print("Versions are compatible.{}", t_Versions); + } + else + { + ClientLog::warn("Versions are not compatible with each other.{}", t_Versions); + } + } + else + { + ClientLog::error("Failed to get the versions from the SDK. The value returned was {}.", (int32_t)t_Result); + } + + uint32_t t_SessionId; + const SDKReturnCode t_SessionIdResult = CoreSdk_GetSessionId(&t_SessionId); + if (t_SessionIdResult == SDKReturnCode::SDKReturnCode_Success && t_SessionId != 0) + { + ClientLog::print("Session Id: {}", t_SessionId); + s_Instance->m_SessionId = t_SessionId; + } + else + { + ClientLog::print("Failed to get the Session ID from Core. The value returned was{}.", (int32_t)t_SessionIdResult); + } + + ManusHost t_Host(*p_Host); + s_Instance->m_Host = std::make_unique(t_Host); + + // Set the hand motion mode of the RawSkeletonStream. This is optional and can be set to any of the HandMotion enum values. Default = None + const SDKReturnCode t_HandMotionResult = CoreSdk_SetRawSkeletonHandMotion(HandMotion_Auto); + if (t_HandMotionResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::print("Failed to set the hand motion mode. The value returned was {}.", (int32_t)t_HandMotionResult); + } + + // Only setting state to displaying data on automatic reconnect + if (s_Instance->m_State == ClientState::ClientState_Disconnected) + { + s_Instance->m_State = ClientState::ClientState_DisplayingData; + } +} + +/// @brief Gets called when the client disconnects from manus core. +/// This callback is optional and in the sample changes the client's state. +void SDKClient::OnDisconnectedCallback(const ManusHost* const p_Host) +{ + ClientLog::print("Disconnected from manus core."); + s_Instance->m_TimeSinceLastDisconnect = std::chrono::high_resolution_clock::now(); + ManusHost t_Host(*p_Host); + s_Instance->m_Host = std::make_unique(t_Host); + s_Instance->m_State = ClientState::ClientState_Disconnected; +} + +void SDKClient::OnLogCallback(LogSeverity p_Severity, const char* const p_Log, uint32_t p_Length) +{ + if (!s_Instance)return; + + auto t_Log = new SDKLog(); + t_Log->severity = p_Severity; + t_Log->string = std::string(p_Log); + s_Instance->m_LogMutex.lock(); + s_Instance->m_Logs.push_back(t_Log); + s_Instance->m_LogMutex.unlock(); +} + +/// @brief This gets called when the client is connected to manus core +/// @param p_SkeletonStreamInfo contains the meta data on how much data regarding the skeleton we need to get from the SDK. +void SDKClient::OnSkeletonStreamCallback(const SkeletonStreamInfo* const p_SkeletonStreamInfo) +{ + if (s_Instance) + { + ClientSkeletonCollection* t_NxtClientSkeleton = new ClientSkeletonCollection(); + t_NxtClientSkeleton->skeletons.resize(p_SkeletonStreamInfo->skeletonsCount); + + for (uint32_t i = 0; i < p_SkeletonStreamInfo->skeletonsCount; i++) + { + CoreSdk_GetSkeletonInfo(i, &t_NxtClientSkeleton->skeletons[i].info); + t_NxtClientSkeleton->skeletons[i].nodes.resize(t_NxtClientSkeleton->skeletons[i].info.nodesCount); + t_NxtClientSkeleton->skeletons[i].info.publishTime = p_SkeletonStreamInfo->publishTime; + CoreSdk_GetSkeletonData(i, t_NxtClientSkeleton->skeletons[i].nodes.data(), t_NxtClientSkeleton->skeletons[i].info.nodesCount); + } + s_Instance->m_SkeletonMutex.lock(); + if (s_Instance->m_NextSkeleton != nullptr) delete s_Instance->m_NextSkeleton; + s_Instance->m_NextSkeleton = t_NxtClientSkeleton; + s_Instance->m_SkeletonMutex.unlock(); + } +} + +/// @brief This gets called when the client is connected to manus core. It sends the skeleton data coming from the estimation system, before the retargeting to the client skeleton model. +/// @param p_RawSkeletonStreamInfo contains the meta data on how much data regarding the raw skeleton we need to get from the SDK. +void SDKClient::OnRawSkeletonStreamCallback(const SkeletonStreamInfo* const p_RawSkeletonStreamInfo) +{ + // std::cout<<"OnRawSkeletonStreamCallback"<skeletons.resize(p_RawSkeletonStreamInfo->skeletonsCount); + + for (uint32_t i = 0; i < p_RawSkeletonStreamInfo->skeletonsCount; i++) + { + CoreSdk_GetRawSkeletonInfo(i, &t_NxtClientRawSkeleton->skeletons[i].info); + t_NxtClientRawSkeleton->skeletons[i].nodes.resize(t_NxtClientRawSkeleton->skeletons[i].info.nodesCount); + t_NxtClientRawSkeleton->skeletons[i].info.publishTime = p_RawSkeletonStreamInfo->publishTime; + CoreSdk_GetRawSkeletonData(i, t_NxtClientRawSkeleton->skeletons[i].nodes.data(), t_NxtClientRawSkeleton->skeletons[i].info.nodesCount); + + std::string glove_id = std::to_string(t_NxtClientRawSkeleton->skeletons[i].info.gloveId); + std::vector positions; + std::vector orientations; + for (uint32_t j = 0; j < t_NxtClientRawSkeleton->skeletons[i].info.nodesCount; j++){ + positions.push_back(t_NxtClientRawSkeleton->skeletons[i].nodes[j].transform.position.x); + positions.push_back(t_NxtClientRawSkeleton->skeletons[i].nodes[j].transform.position.y); + positions.push_back(t_NxtClientRawSkeleton->skeletons[i].nodes[j].transform.position.z); + orientations.push_back(t_NxtClientRawSkeleton->skeletons[i].nodes[j].transform.rotation.w); + orientations.push_back(t_NxtClientRawSkeleton->skeletons[i].nodes[j].transform.rotation.x); + orientations.push_back(t_NxtClientRawSkeleton->skeletons[i].nodes[j].transform.rotation.y); + orientations.push_back(t_NxtClientRawSkeleton->skeletons[i].nodes[j].transform.rotation.z); + } + output_map[glove_id +"_position"] = positions; + output_map[glove_id +"_orientation"] = orientations; + } + s_Instance->m_RawSkeletonMutex.lock(); + if (s_Instance->m_NextRawSkeleton != nullptr) delete s_Instance->m_NextRawSkeleton; + s_Instance->m_NextRawSkeleton = t_NxtClientRawSkeleton; + s_Instance->m_RawSkeletonMutex.unlock(); + } +} + +/// @brief This gets called when receiving tracker information from core +/// @param p_TrackerStreamInfo contains the meta data on how much data regarding the trackers we need to get from the SDK. +void SDKClient::OnTrackerStreamCallback(const TrackerStreamInfo* const p_TrackerStreamInfo) +{ + if (s_Instance) + { + TrackerDataCollection* t_TrackerData = new TrackerDataCollection(); + + t_TrackerData->trackerData.resize(p_TrackerStreamInfo->trackerCount); + + for (uint32_t i = 0; i < p_TrackerStreamInfo->trackerCount; i++) + { + CoreSdk_GetTrackerData(i, &t_TrackerData->trackerData[i]); + } + s_Instance->m_TrackerMutex.lock(); + if (s_Instance->m_NextTrackerData != nullptr) delete s_Instance->m_NextTrackerData; + s_Instance->m_NextTrackerData = t_TrackerData; + s_Instance->m_TrackerMutex.unlock(); + } +} + +/// @brief This gets called when receiving gesture data from Manus Core +/// In our sample we only save the first glove's gesture data. +/// Gesture data gets generated and sent when glove data changes, this means that the stream +/// does not always contain ALL of the devices, because some may not have had new data since +/// the last time the gesture data was sent. +/// @param p_GestureStream contains the basic info to retrieve gesture data. +void SDKClient::OnGestureStreamCallback(const GestureStreamInfo* const p_GestureStream) +{ + if (s_Instance) + { + for (uint32_t i = 0; i < p_GestureStream->gestureProbabilitiesCount; i++) + { + GestureProbabilities t_Probs; + CoreSdk_GetGestureStreamData(i, 0, &t_Probs); + if (t_Probs.isUserID)continue; + if (t_Probs.id != s_Instance->m_FirstLeftGloveID && t_Probs.id != s_Instance->m_FirstRightGloveID)continue; + ClientGestures* t_Gest = new ClientGestures(); + t_Gest->info = t_Probs; + t_Gest->probabilities.reserve(t_Gest->info.totalGestureCount); + uint32_t t_BatchCount = (t_Gest->info.totalGestureCount / MAX_GESTURE_DATA_CHUNK_SIZE) + 1; + uint32_t t_ProbabilityIdx = 0; + for (uint32_t b = 0; b < t_BatchCount; b++) + { + for (uint32_t j = 0; j < t_Probs.gestureCount; j++) + { + t_Gest->probabilities.push_back(t_Probs.gestureData[j]); + } + t_ProbabilityIdx += t_Probs.gestureCount; + CoreSdk_GetGestureStreamData(i, t_ProbabilityIdx, &t_Probs); //this will get more data, if needed for the next iteration. + } + + s_Instance->m_GestureMutex.lock(); + if (t_Probs.id == s_Instance->m_FirstLeftGloveID) + { + if (s_Instance->m_NewFirstLeftGloveGestures != nullptr) delete s_Instance->m_NewFirstLeftGloveGestures; + s_Instance->m_NewFirstLeftGloveGestures = t_Gest; + } + else + { + if (s_Instance->m_NewFirstRightGloveGestures != nullptr) delete s_Instance->m_NewFirstRightGloveGestures; + s_Instance->m_NewFirstRightGloveGestures = t_Gest; + } + s_Instance->m_GestureMutex.unlock(); + } + } +} + +/// @brief This gets called when receiving landscape information from core +/// @param p_Landscape contains the new landscape from core. +void SDKClient::OnLandscapeCallback(const Landscape* const p_Landscape) +{ + if (s_Instance == nullptr)return; + + Landscape* t_Landscape = new Landscape(*p_Landscape); + s_Instance->m_LandscapeMutex.lock(); + if (s_Instance->m_NewLandscape != nullptr) delete s_Instance->m_NewLandscape; + s_Instance->m_NewLandscape = t_Landscape; + s_Instance->m_NewGestureLandscapeData.resize(t_Landscape->gestureCount); + CoreSdk_GetGestureLandscapeData(s_Instance->m_NewGestureLandscapeData.data(), (uint32_t)s_Instance->m_NewGestureLandscapeData.size()); + s_Instance->m_LandscapeMutex.unlock(); +} + + +/// @brief This gets called when receiving a system message from Core. +/// @param p_SystemMessage contains the system message received from core. +void SDKClient::OnSystemCallback(const SystemMessage* const p_SystemMessage) +{ + if (s_Instance) + { + s_Instance->m_SystemMessageMutex.lock(); + + switch (p_SystemMessage->type) + { + case SystemMessageType::SystemMessageType_TemporarySkeletonModified: + // if the message was triggered by a temporary skeleton being modified then save the skeleton index, + // this information will be used to get and load the skeleton into core + s_Instance->m_ModifiedSkeletonIndex = p_SystemMessage->infoUInt; + break; + default: + s_Instance->m_SystemMessageCode = p_SystemMessage->type; + s_Instance->m_SystemMessage = p_SystemMessage->infoString; + break; + } + s_Instance->m_SystemMessageMutex.unlock(); + } +} + +/// @brief This gets called when receiving ergonomics data from Manus Core +/// In our sample we only save the first left and first right glove's latests ergonomics data. +/// Ergonomics data gets generated and sent when glove data changes, this means that the stream +/// does not always contain ALL of the devices, because some may not have had new data since +/// the last time the ergonomics data was sent. +/// @param p_Ergo contains the ergonomics data for each glove connected to Core. +void SDKClient::OnErgonomicsCallback(const ErgonomicsStream* const p_Ergo) +{ + if (s_Instance) + { + long int left_glove_id = 0; + long int right_glove_id = 0; + for (uint32_t i = 0; i < p_Ergo->dataCount; i++) + { + if (p_Ergo->data[i].isUserID)continue; + + ErgonomicsData* t_Ergo = nullptr; + if (std::find(idleft.begin(), idleft.end(), p_Ergo->data[i].id) != idleft.end()) + { + t_Ergo = &s_Instance->m_LeftGloveErgoData; + left_glove_id = p_Ergo->data[i].id; + } + if (std::find(idright.begin(), idright.end(), p_Ergo->data[i].id) != idright.end()) + { + t_Ergo = &s_Instance->m_RightGloveErgoData; + right_glove_id = p_Ergo->data[i].id; + } + if (t_Ergo == nullptr)continue; + CoreSdk_GetTimestampInfo(p_Ergo->publishTime, &s_Instance->m_ErgoTimestampInfo); + t_Ergo->id = p_Ergo->data[i].id; + t_Ergo->isUserID = p_Ergo->data[i].isUserID; + // Create a vector to store the angles of the hand + std::vector orientations_left; + std::vector orientations_right; + for (int j = 0; j < ErgonomicsDataType::ErgonomicsDataType_MAX_SIZE; j++) + { + t_Ergo->data[j] = p_Ergo->data[i].data[j]; + double roundedValue = s_Instance->RoundFloatValue(t_Ergo->data[j], 2); + if (t_Ergo == &s_Instance->m_LeftGloveErgoData) + { + orientations_left.push_back(roundedValue); + } + else if (t_Ergo == &s_Instance->m_RightGloveErgoData) + { + orientations_right.push_back(roundedValue); + } + } + if(left_glove_id!=0){ + output_map[std::to_string(left_glove_id)+"_angle"] = orientations_left; + } + if(right_glove_id!=0){ + output_map[std::to_string(right_glove_id)+"_angle"] = orientations_right; + } + } + } +} + +/// @brief Round the given float value so that it has no more than the given number of decimals. +float SDKClient::RoundFloatValue(float p_Value, int p_NumDecimalsToKeep) +{ + // Since C++11, powf is supposed to be declared in . + // Unfortunately, gcc decided to be non-compliant on this for no apparent + // reason, so now we have to do this. + // https://stackoverflow.com/questions/5483930/powf-is-not-a-member-of-std + float t_Power = static_cast(std::pow( + 10.0, + static_cast(p_NumDecimalsToKeep))); + return std::round(p_Value * t_Power) / t_Power; +} + +/// @brief Set the position that the next log message will appear at. +/// Using this allows us to have somewhat of a static, yet flexible layout of logging. +void SDKClient::AdvanceConsolePosition(short int p_Y) +{ + if (p_Y < 0) + { + m_ConsoleCurrentOffset = 0; + } + else + { + m_ConsoleCurrentOffset += p_Y; + } + + ApplyConsolePosition(m_ConsoleCurrentOffset); +} + +/// @brief Initialize the sdk, register the callbacks and set the coordinate system. +/// This needs to be done before any of the other SDK functions can be used. +ClientReturnCode SDKClient::InitializeSDK() +{ + // ClientLog::print("Select what mode you would like to start in (and press enter to submit)"); + // ClientLog::print("[1] Core Integrated - This will run standalone without the need for a MANUS Core connection"); + // ClientLog::print("[2] Core Local - This will connect to a MANUS Core running locally on your machine"); + // ClientLog::print("[3] Core Remote - This will search for a MANUS Core running locally on your network"); + // std::string t_ConnectionTypeInput; + // std::cin >> t_ConnectionTypeInput; + + std::string t_ConnectionTypeInput = "1"; + + switch (t_ConnectionTypeInput[0]) + { + case '1': + m_ConnectionType = ConnectionType::ConnectionType_Integrated; + m_State = ClientState::ClientState_ConnectingToCore; + break; + case '2': + m_ConnectionType = ConnectionType::ConnectionType_Local; + m_State = ClientState::ClientState_LookingForHosts; + break; + case '3': + m_ConnectionType = ConnectionType::ConnectionType_Remote; + m_State = ClientState::ClientState_LookingForHosts; + break; + default: + m_ConnectionType = ConnectionType::ConnectionType_Invalid; + m_State = ClientState::ClientState_Starting; + ClientLog::print("Invalid input, try again"); + return InitializeSDK(); + } + + // Invalid connection type detected + if (m_ConnectionType == ConnectionType::ConnectionType_Invalid + || m_ConnectionType == ConnectionType::ClientState_MAX_CLIENT_STATE_SIZE) + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + + // before we can use the SDK, some internal SDK bits need to be initialized. + // however after initializing, the SDK is not yet connected to a host or doing anything network related just yet. + bool t_Remote = m_ConnectionType != ConnectionType::ConnectionType_Integrated; + const SDKReturnCode t_InitializeResult = CoreSdk_Initialize(m_ClientType, t_Remote); + if (t_InitializeResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to initialize the Manus Core SDK. The value returned was {}.", (int32_t)t_InitializeResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + const ClientReturnCode t_CallBackResults = RegisterAllCallbacks(); + if (t_CallBackResults != ::ClientReturnCode::ClientReturnCode_Success) + { + ClientLog::error("Failed to initialize callbacks."); + return t_CallBackResults; + } + + // after everything is registered and initialized as seen above + // we must also set the coordinate system being used for the data in this client. + // (each client can have their own settings. unreal and unity for instance use different coordinate systems) + // if this is not set, the SDK will not connect to any Manus core host. + // The coordinate system used for this example is z-up, x-positive, right-handed and in meter scale. + CoordinateSystemVUH t_VUH; + CoordinateSystemVUH_Init(&t_VUH); + t_VUH.handedness = Side::Side_Right; + t_VUH.up = AxisPolarity::AxisPolarity_PositiveZ; + t_VUH.view = AxisView::AxisView_XFromViewer; + t_VUH.unitScale = 1.0f; //1.0 is meters, 0.01 is cm, 0.001 is mm. + + // The above specified coordinate system is used to initialize and the coordinate space is specified (world/local). + const SDKReturnCode t_CoordinateResult = CoreSdk_InitializeCoordinateSystemWithVUH(t_VUH, true); + + /* this is an example if you want to use the other coordinate system instead of VUH (view, up, handedness) + CoordinateSystemDirection t_Direction; + t_Direction.x = AxisDirection::AD_Right; + t_Direction.y = AxisDirection::AD_Up; + t_Direction.z = AxisDirection::AD_Forward; + const SDKReturnCode t_InitializeResult = CoreSdk_InitializeCoordinateSystemWithDirection(t_Direction, true); + */ + + if (t_CoordinateResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to initialize the Manus Core SDK coordinate system. The value returned was {}.", (int32_t)t_InitializeResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief Used to restart and initialize the SDK to make sure a new connection can be set up. +/// This function is used by the client to shutdown the SDK and any connections it has. +/// After that it reinitializes the SDK so that it is ready to connect to a new Manus Core. +ClientReturnCode SDKClient::RestartSDK() +{ + const SDKReturnCode t_ShutDownResult = CoreSdk_ShutDown(); + if (t_ShutDownResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to shutdown the SDK. The value returned was {}.", (int32_t)t_ShutDownResult); + return ClientReturnCode::ClientReturnCode_FailedToShutDownSDK; + } + + const ClientReturnCode t_IntializeResult = InitializeSDK(); + if (t_IntializeResult != ClientReturnCode::ClientReturnCode_Success) + { + ClientLog::error("Failed to initialize the SDK functionality. The value returned was {}.", (int32_t)t_IntializeResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief Used to register the callbacks between sdk and core. +/// Callbacks that are registered functions that get called when a certain 'event' happens, such as data coming in from Manus Core. +/// All of these are optional, but depending on what data you require you may or may not need all of them. +ClientReturnCode SDKClient::RegisterAllCallbacks() +{ + // Register the callback for when manus core is connected to the SDK + // it is optional, but helps trigger your client nicely if needed. + // see the function OnConnectedCallback for more details + const SDKReturnCode t_RegisterConnectCallbackResult = CoreSdk_RegisterCallbackForOnConnect(*OnConnectedCallback); + if (t_RegisterConnectCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for after connecting to Manus Core. The value returned was {}.", (int32_t)t_RegisterConnectCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for when manus core is disconnected to the SDK + // it is optional, but helps trigger your client nicely if needed. + // see OnDisconnectedCallback for more details. + const SDKReturnCode t_RegisterDisconnectCallbackResult = CoreSdk_RegisterCallbackForOnDisconnect(*OnDisconnectedCallback); + if (t_RegisterDisconnectCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for after disconnecting from Manus Core. The value returned was {}.", (int32_t)t_RegisterDisconnectCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for logging from the SDK + // it is optional, but it might help display the logs at the right time/place + const SDKReturnCode t_RegisterLogCallbackResult = CoreSdk_RegisterCallbackForOnLog(*OnLogCallback); + if (t_RegisterLogCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for logging from the SDK. The value returned was {}.", (int32_t)t_RegisterLogCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for when manus core is sending Skeleton data + // it is optional, but without it you can not see any resulting skeleton data. + // see OnSkeletonStreamCallback for more details. + const SDKReturnCode t_RegisterSkeletonCallbackResult = CoreSdk_RegisterCallbackForSkeletonStream(*OnSkeletonStreamCallback); + if (t_RegisterSkeletonCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for processing skeletal data from Manus Core. The value returned was {}.", (int32_t)t_RegisterSkeletonCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for when manus core is sending landscape data + // it is optional, but this allows for a reactive adjustment of device information. + const SDKReturnCode t_RegisterLandscapeCallbackResult = CoreSdk_RegisterCallbackForLandscapeStream(*OnLandscapeCallback); + if (t_RegisterLandscapeCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback for landscape from Manus Core. The value returned was {}.", (int32_t)t_RegisterLandscapeCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for when manus core is sending System messages + // This is usually not used by client applications unless they want to show errors/events from core. + // see OnSystemCallback for more details. + const SDKReturnCode t_RegisterSystemCallbackResult = CoreSdk_RegisterCallbackForSystemStream(*OnSystemCallback); + if (t_RegisterSystemCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for system feedback from Manus Core. The value returned was {}.", (int32_t)t_RegisterSystemCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for when manus core is sending Ergonomics data + // it is optional, but helps trigger your client nicely if needed. + // see OnErgonomicsCallback for more details. + const SDKReturnCode t_RegisterErgonomicsCallbackResult = CoreSdk_RegisterCallbackForErgonomicsStream(*OnErgonomicsCallback); + if (t_RegisterErgonomicsCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for ergonomics data from Manus Core. The value returned was {}.", (int32_t)t_RegisterErgonomicsCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for when manus core is sending Raw Skeleton data + // it is optional, but without it you can not see any resulting skeleton data. + // see OnSkeletonStreamCallback for more details. + const SDKReturnCode t_RegisterRawSkeletonCallbackResult = CoreSdk_RegisterCallbackForRawSkeletonStream(*OnRawSkeletonStreamCallback); + if (t_RegisterRawSkeletonCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for processing raw skeletal data from Manus Core. The value returned was {}.", (int32_t)t_RegisterRawSkeletonCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for when manus core is sending Tracker data + // it is optional, but without it you can not see any resulting tracker data. + // see OnTrackerStreamCallback for more details. + const SDKReturnCode t_RegisterTrackerCallbackResult = CoreSdk_RegisterCallbackForTrackerStream(*OnTrackerStreamCallback); + if (t_RegisterTrackerCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for processing tracker data from Manus Core. The value returned was {}.", (int32_t)t_RegisterTrackerCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + // Register the callback for when manus core is sending Raw Skeleton data + // it is optional, but without it you can not see any resulting skeleton data. + // see OnGestureStreamCallback for more details. + const SDKReturnCode t_RegisterGestureCallbackResult = CoreSdk_RegisterCallbackForGestureStream(*OnGestureStreamCallback); + if (t_RegisterGestureCallbackResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to register callback function for processing gesture data from Manus Core. The value returned was {}.", (int32_t)t_RegisterGestureCallbackResult); + return ClientReturnCode::ClientReturnCode_FailedToInitialize; + } + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief Simple example of the SDK looking for manus core hosts on the network +/// and display them on screen. +ClientReturnCode SDKClient::LookingForHosts() +{ + ClientLog::print("Looking for hosts..."); + + // Underlying function will sleep for m_SecondsToFindHosts to allow servers to reply. + bool t_ConnectLocally = m_ConnectionType == ConnectionType::ConnectionType_Local; + const SDKReturnCode t_StartResult = CoreSdk_LookForHosts(m_SecondsToFindHosts, t_ConnectLocally); + if (t_StartResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to look for hosts. The error given was {}.", (int32_t)t_StartResult); + + return ClientReturnCode::ClientReturnCode_FailedToFindHosts; + } + + m_NumberOfHostsFound = 0; + const SDKReturnCode t_NumberResult = CoreSdk_GetNumberOfAvailableHostsFound(&m_NumberOfHostsFound); + if (t_NumberResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get the number of available hosts. The error given was {}.", (int32_t)t_NumberResult); + + return ClientReturnCode::ClientReturnCode_FailedToFindHosts; + } + + if (m_NumberOfHostsFound == 0) + { + ClientLog::warn("No hosts found."); + m_State = ClientState::ClientState_NoHostsFound; + + return ClientReturnCode::ClientReturnCode_FailedToFindHosts; + } + + m_AvailableHosts.reset(new ManusHost[m_NumberOfHostsFound]); + const SDKReturnCode t_HostsResult = CoreSdk_GetAvailableHostsFound(m_AvailableHosts.get(), m_NumberOfHostsFound); + if (t_HostsResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get the available hosts. The error given was {}.", (int32_t)t_HostsResult); + + return ClientReturnCode::ClientReturnCode_FailedToFindHosts; + } + + if (t_ConnectLocally) + { + m_State = ClientState::ClientState_ConnectingToCore; + return ClientReturnCode::ClientReturnCode_Success; + } + + m_State = ClientState::ClientState_PickingHost; + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief When no available hosts are found the user can either retry or exit. +ClientReturnCode SDKClient::NoHostsFound() +{ + if (m_ConsoleClearTickCount == 0) + { + AdvanceConsolePosition(-1); + ClientLog::print("No hosts were found. Retry?"); + ClientLog::print("[R] retry"); + ClientLog::print("[ESC] exit"); + } + + if (GetKeyDown('R')) + { + ClientLog::print("Retrying."); + + m_State = ClientState::ClientState_LookingForHosts; + } + + // Note: escape is handled by default below. + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief Print the found hosts and give the user the option to select one. +ClientReturnCode SDKClient::PickingHost() +{ + if (m_ConsoleClearTickCount == 0) + { + AdvanceConsolePosition(-1); + + ClientLog::print("[R] retry [ESC] exit"); + ClientLog::print("Pick a host to connect to."); + ClientLog::print("Found the following hosts:"); + + // Note: only 10 hosts are shown, to match the number of number keys, for easy selection. + for (unsigned int t_HostNumber = 0; t_HostNumber < 10 && t_HostNumber < m_NumberOfHostsFound; t_HostNumber++) + { + ClientLog::print( + "[{}] hostname \"{}\", IP address \"{}\" Version {}.{}.{}", + t_HostNumber, + m_AvailableHosts[t_HostNumber].hostName, + m_AvailableHosts[t_HostNumber].ipAddress, + m_AvailableHosts[t_HostNumber].manusCoreVersion.major, + m_AvailableHosts[t_HostNumber].manusCoreVersion.minor, + m_AvailableHosts[t_HostNumber].manusCoreVersion.patch); + } + } + + for (unsigned int t_HostNumber = 0; t_HostNumber < 10 && t_HostNumber < m_NumberOfHostsFound; t_HostNumber++) + { + if (GetKeyDown('0' + t_HostNumber)) + { + ClientLog::print("Selected host {}.", t_HostNumber); + + m_HostToConnectTo = t_HostNumber; + m_State = ClientState::ClientState_ConnectingToCore; + + break; + } + } + + if (GetKeyDown('R')) + { + ClientLog::print("Retrying."); + m_State = ClientState::ClientState_LookingForHosts; + } + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief After a connection option was selected, the client will now try to connect to manus core via the SDK. +ClientReturnCode SDKClient::ConnectingToCore() +{ + SDKReturnCode t_ConnectResult = SDKReturnCode::SDKReturnCode_Error; + switch (m_ConnectionType) + { + case ConnectionType::ConnectionType_Integrated: + { + ManusHost t_Empty; + ManusHost_Init(&t_Empty); + t_ConnectResult = CoreSdk_ConnectToHost(t_Empty); + break; + } + case ConnectionType::ConnectionType_Local: + { + t_ConnectResult = CoreSdk_ConnectToHost(m_AvailableHosts[0]); + break; + } + case ConnectionType::ConnectionType_Remote: + { + t_ConnectResult = CoreSdk_ConnectToHost(m_AvailableHosts[m_HostToConnectTo]); + break; + } + } + + if (t_ConnectResult == SDKReturnCode::SDKReturnCode_NotConnected) + { + m_State = ClientState::ClientState_NoHostsFound; + + return ClientReturnCode::ClientReturnCode_Success; // Differentiating between error and no connect + } + if (t_ConnectResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to connect to Core. The error given was {}.", (int32_t)t_ConnectResult); + + return ClientReturnCode::ClientReturnCode_FailedToConnect; + } + + m_State = ClientState::ClientState_DisplayingData; + + // Note: a log message from somewhere in the SDK during the connection process can cause text + // to permanently turn green after this step. Adding a sleep here of 2+ seconds "fixes" the + // issue. It seems to be caused by a threading issue somewhere, resulting in a log call being + // interrupted while it is printing the green [info] text. The log output then gets stuck in + // green mode. + + return ClientReturnCode::ClientReturnCode_Success; +} + + +/// @brief Some things happen before every display update, no matter what state. +/// They happen here, such as the updating of the landscape and the generated tracker +/// @return +ClientReturnCode SDKClient::UpdateBeforeDisplayingData() +{ + AdvanceConsolePosition(-1); + + m_SkeletonMutex.lock(); + if (m_NextSkeleton != nullptr) + { + if (m_Skeleton != nullptr)delete m_Skeleton; + m_Skeleton = m_NextSkeleton; + m_NextSkeleton = nullptr; + } + m_SkeletonMutex.unlock(); + + m_RawSkeletonMutex.lock(); + if (m_NextRawSkeleton != nullptr) + { + if (m_RawSkeleton != nullptr)delete m_RawSkeleton; + m_RawSkeleton = m_NextRawSkeleton; + m_NextRawSkeleton = nullptr; + } + m_RawSkeletonMutex.unlock(); + + m_TrackerMutex.lock(); + if (m_NextTrackerData != nullptr) + { + if (m_TrackerData != nullptr)delete m_TrackerData; + m_TrackerData = m_NextTrackerData; + m_NextTrackerData = nullptr; + } + m_TrackerMutex.unlock(); + + m_GestureMutex.lock(); + if (m_NewFirstLeftGloveGestures != nullptr) + { + if (m_FirstLeftGloveGestures != nullptr) delete m_FirstLeftGloveGestures; + m_FirstLeftGloveGestures = m_NewFirstLeftGloveGestures; + m_NewFirstLeftGloveGestures = nullptr; + } + if (m_NewFirstRightGloveGestures != nullptr) + { + if (m_FirstRightGloveGestures != nullptr) delete m_FirstRightGloveGestures; + m_FirstRightGloveGestures = m_NewFirstRightGloveGestures; + m_NewFirstRightGloveGestures = nullptr; + } + m_GestureMutex.unlock(); + + m_LandscapeMutex.lock(); + if (m_NewLandscape != nullptr) + { + if (m_Landscape != nullptr) + { + delete m_Landscape; + } + m_Landscape = m_NewLandscape; + m_NewLandscape = nullptr; + m_GestureLandscapeData.swap(m_NewGestureLandscapeData); + } + m_LandscapeMutex.unlock(); + + m_FirstLeftGloveID = 0; + m_FirstRightGloveID = 0; + if (m_Landscape == nullptr)return ClientReturnCode::ClientReturnCode_Success; + for (size_t i = 0; i < m_Landscape->gloveDevices.gloveCount; i++) + { + if (m_FirstLeftGloveID == 0 && m_Landscape->gloveDevices.gloves[i].side == Side::Side_Left) + { + m_FirstLeftGloveID = m_Landscape->gloveDevices.gloves[i].id; + continue; + } + if (m_FirstRightGloveID == 0 && m_Landscape->gloveDevices.gloves[i].side == Side::Side_Right) + { + m_FirstRightGloveID = m_Landscape->gloveDevices.gloves[i].id; + continue; + } + } + + return ClientReturnCode::ClientReturnCode_Success; +} + + +/// @brief Once the connections are made we loop this function +/// it calls all the input handlers for different aspects of the SDK +/// and then prints any relevant data of it. +ClientReturnCode SDKClient::DisplayingData() +{ + ClientLog::print("<
> [ESC] quit"); + ClientLog::print("[G] Go To Gloves & Dongle Menu"); + ClientLog::print("[S] Go To Skeleton Menu"); + ClientLog::print("[X] Go To Temporary Skeleton Menu"); + ClientLog::print("[T] Go To Tracker Menu"); + ClientLog::print("[D] Go To Landscape Time Info"); + ClientLog::print("[J] Go To Gestures Menu"); + ClientLog::print("[C] Go To Glove Calibration Menu"); + ClientLog::print("[P] Go To Pairing Menu"); + + AdvanceConsolePosition(10); + + GO_TO_DISPLAY('G', DisplayingDataGlove) + GO_TO_DISPLAY('S', DisplayingDataSkeleton) + GO_TO_DISPLAY('X', DisplayingDataTemporarySkeleton) + GO_TO_DISPLAY('T', DisplayingDataTracker) + GO_TO_DISPLAY('D', DisplayingLandscapeTimeData) + GO_TO_DISPLAY('J', DisplayingDataGestures) + GO_TO_DISPLAY('C', DisplayingGloveCalibration) + GO_TO_DISPLAY('P', DisplayingPairing) + + PrintSystemMessage(); + + // AdvanceConsolePosition(10); + // GO_TO_DISPLAY('G', DisplayingDataGlove) + // PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief display the ergonomics data of the gloves, and handles haptic commands. +/// @return +ClientReturnCode SDKClient::DisplayingDataGlove() +{ + ClientLog::print("[Q] Back <> [ESC] quit"); + ClientLog::print("Haptic keys: left:([1]-[5] = pinky-thumb.) right:([6]-[0] = thumb-pinky.)"); + + AdvanceConsolePosition(3); + + GO_TO_MENU_IF_REQUESTED() + + HandleHapticCommands(); + + PrintErgonomicsData(); + PrintDongleData(); + PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +ClientReturnCode SDKClient::DisplayingDataSkeleton() +{ + ClientLog::print("[Q] Back <> [ESC] quit"); + ClientLog::print(" [B] Load Left Hand Skeleton [N] Load Right Hand Skeleton [M] Unload Skeleton"); + ClientLog::print(" [D] Toggle Send to DevTools ({})", m_SendToDevTools); + ClientLog::print(" left:([1]-[5] = pinky-thumb) right:([6]-[0] = thumb-pinky)"); + + AdvanceConsolePosition(4); + + GO_TO_MENU_IF_REQUESTED() + + HandleSkeletonCommands(); + HandleSkeletonHapticCommands(); + + PrintSkeletonData(); + + AdvanceConsolePosition(1); + PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +ClientReturnCode SDKClient::DisplayingDataTracker() +{ + ClientLog::print("[Q] Back <> [ESC] quit"); + ClientLog::print("[O] Toggle Test Tracker [G] Toggle per user tracker display [T] Set Tracker Offset to Left Wrist"); + + AdvanceConsolePosition(3); + + GO_TO_MENU_IF_REQUESTED() + HandleTrackerCommands(); + + PrintRawSkeletonData(); + + PrintTrackerData(); + PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +ClientReturnCode SDKClient::DisplayingDataTemporarySkeleton() +{ + ClientLog::print("[Q] Back <> [ESC] quit"); + ClientLog::print("[A] Auto allocate chains and load skeleton"); + ClientLog::print("[B] Build Temporary Skeleton [C] Clear Temporary Skeleton [D] Clear All Temporary Skeletons For The Current Session"); + ClientLog::print("[E] Save Temporary Skeleton To File, [F] Get Temporary Skeleton From File"); + + AdvanceConsolePosition(5); + + GO_TO_MENU_IF_REQUESTED() + + HandleTemporarySkeletonCommands(); + + PrintTemporarySkeletonInfo(); + GetTemporarySkeletonIfModified(); + + AdvanceConsolePosition(3); + PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +ClientReturnCode SDKClient::DisplayingLandscapeTimeData() +{ + ClientLog::print("[Q] Back <> [ESC] quit"); + + AdvanceConsolePosition(2); + + GO_TO_MENU_IF_REQUESTED() + + PrintLandscapeTimeData(); + + PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +ClientReturnCode SDKClient::DisplayingDataGestures() +{ + ClientLog::print("[Q] Back <> [ESC] quit"); + ClientLog::print("[H] Show other Hand"); + + AdvanceConsolePosition(3); + + GO_TO_MENU_IF_REQUESTED() + + HandleGesturesCommands(); + + PrintGestureData(); + + AdvanceConsolePosition(1); + + PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +ClientReturnCode SDKClient::DisplayingGloveCalibration() +{ + ClientLog::print("[Q] Back <> [ESC] quit"); + ClientLog::print("[H] Toggle other Hand [P] Add 1 to the calibration step [M] Remove 1 from the calibration step"); + ClientLog::print("[S] Start glove calibration [C] Cancel glove calibration [F] Finish glove calibration"); + ClientLog::print("[E] Execute calibration step"); + + AdvanceConsolePosition(5); + + GO_TO_MENU_IF_REQUESTED() + + HandleGloveCalibrationCommands(); + + PrintGloveCalibrationData(); + + AdvanceConsolePosition(3); + PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +ClientReturnCode SDKClient::DisplayingPairing() +{ + ClientLog::print("[Q] Back <> [ESC] quit"); + ClientLog::print("<> [P] Pair first available Glove"); + ClientLog::print("<> [U] Unpair first available Glove"); + + + GO_TO_MENU_IF_REQUESTED() + + HandlePairingCommands(); + + AdvanceConsolePosition(4); + PrintSystemMessage(); + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief When the SDK loses the connection with Core the user can either +/// close the sdk or try to reconnect to a local or to a remote host. +ClientReturnCode SDKClient::DisconnectedFromCore() +{ + if (m_Host == nullptr) { return ClientReturnCode::ClientReturnCode_FailedToConnect; } + + AdvanceConsolePosition(-1); + + auto t_Duration = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - m_TimeSinceLastDisconnect).count(); + ClientLog::print("The SDK lost connection with Manus Core {} seconds ago.", t_Duration); + ClientLog::print("[P] Pick a new host. [ESC] exit"); + + AdvanceConsolePosition(3); + + bool t_ConnectLocally = m_ConnectionType == ConnectionType::ConnectionType_Local; + if (t_ConnectLocally) + { + ClientLog::print("Automatically trying to reconnect to local host."); + + ClientReturnCode t_ReconnectResult = ReconnectingToCore(); + if (t_ReconnectResult != ClientReturnCode::ClientReturnCode_FailedToConnect) + { + return t_ReconnectResult; + } + } + else + { + ClientLog::print("[R] Try to reconnect to the last host {} at {}.", m_Host->hostName, m_Host->ipAddress); + if (GetKeyDown('R')) + { + ClientLog::print("Reconnecting"); + + ClientReturnCode t_ReconnectResult = ReconnectingToCore(m_SecondsToAttemptReconnecting, m_MaxReconnectionAttempts); + if (t_ReconnectResult != ClientReturnCode::ClientReturnCode_FailedToConnect) + { + return t_ReconnectResult; + } + } + } + + AdvanceConsolePosition(10); + + + if (GetKeyDown('P')) + { + ClientLog::print("Picking new host."); + + // Restarting and initializing CoreConnection to make sure a new connection can be set up + const ClientReturnCode t_RestartResult = RestartSDK(); + if (t_RestartResult != ClientReturnCode::ClientReturnCode_Success) + { + ClientLog::error("Failed to Restart CoreConnection."); + return ClientReturnCode::ClientReturnCode_FailedToRestart; + } + + m_State = ClientState::ClientState_LookingForHosts; + } + + return ClientReturnCode::ClientReturnCode_Success; +} + +/// @brief It is called when the sdk is disconnected from Core and the user select one of the options to reconnect. +ClientReturnCode SDKClient::ReconnectingToCore(int32_t p_ReconnectionTime, int32_t p_ReconnectionAttempts) +{ + if (p_ReconnectionTime <= 0) { p_ReconnectionTime = std::numeric_limits::max(); } + if (p_ReconnectionAttempts <= 0) { p_ReconnectionAttempts = std::numeric_limits::max(); } + + // Restarting and initializing CoreConnection to make sure a new connection can be set up + const ClientReturnCode t_RestartResult = RestartSDK(); + if (t_RestartResult != ClientReturnCode::ClientReturnCode_Success) + { + ClientLog::error("Failed to Restart CoreConnection."); + return ClientReturnCode::ClientReturnCode_FailedToRestart; + } + + std::chrono::high_resolution_clock::time_point t_Start = std::chrono::high_resolution_clock::now(); + int t_Attempt = 0; + while ((p_ReconnectionAttempts > 0) && (p_ReconnectionTime > 0)) + { + ClientLog::print("Trying to reconnect to {} at {}. Attempt {}.", m_Host->hostName, m_Host->ipAddress, t_Attempt); + ClientLog::print("Attempts remaining: {}. Seconds before time out: {}.", p_ReconnectionAttempts, p_ReconnectionTime); + + bool t_ConnectLocally = m_ConnectionType == ConnectionType::ConnectionType_Local; + if (t_ConnectLocally) + { + ClientReturnCode t_ConnectionResult = LookingForHosts(); + if (t_ConnectionResult == ClientReturnCode::ClientReturnCode_Success) + { + ClientLog::print("Reconnected to ManusCore."); + return ClientReturnCode::ClientReturnCode_Success; + } + } + else + { + SDKReturnCode t_ConnectionResult = CoreSdk_ConnectToHost(*m_Host.get()); + if (t_ConnectionResult == SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::print("Reconnected to ManusCore."); + return ClientReturnCode::ClientReturnCode_Success; + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(m_SleepBetweenReconnectingAttemptsInMs)); + p_ReconnectionTime -= static_cast(std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - t_Start).count()); + --p_ReconnectionAttempts; + ++t_Attempt; + } + + ClientLog::print("Failed to reconnect to ManusCore."); + m_State = ClientState::ClientState_Disconnected; + return ClientReturnCode::ClientReturnCode_FailedToConnect; +} + + +/// @brief Prints the ergonomics data of a hand. +/// @param p_ErgoData +void SDKClient::PrintHandErgoData(ErgonomicsData& p_ErgoData, bool p_Left) +{ + const std::string t_FingerNames[NUM_FINGERS_ON_HAND] = { "[thumb] ", "[index] ", "[middle]", "[ring] ", "[pinky] " }; + const std::string t_FingerJointNames[NUM_FINGERS_ON_HAND] = { "mcp", "pip", "dip" }; + const std::string t_ThumbJointNames[NUM_FINGERS_ON_HAND] = { "cmc", "mcp", "ip " }; + + int t_DataOffset = 0; + if (!p_Left)t_DataOffset = 20; + + const std::string* t_JointNames = t_ThumbJointNames; + for (unsigned int t_FingerNumber = 0; t_FingerNumber < NUM_FINGERS_ON_HAND; t_FingerNumber++) + { + ClientLog::printWithPadding("{} {} spread: {}, {} stretch: {}, {} stretch: {}, {} stretch: {} ", 6, + t_FingerNames[t_FingerNumber], // Name of the finger. + t_JointNames[0], + RoundFloatValue(p_ErgoData.data[t_DataOffset], 2), + t_JointNames[0], + RoundFloatValue(p_ErgoData.data[t_DataOffset + 1], 2), + t_JointNames[1], + RoundFloatValue(p_ErgoData.data[t_DataOffset + 2], 2), + t_JointNames[2], + RoundFloatValue(p_ErgoData.data[t_DataOffset + 3], 2)); + t_JointNames = t_FingerJointNames; + t_DataOffset += 4; + } +} + +/// @brief Print the ergonomics data received from Core. +void SDKClient::PrintErgonomicsData() +{ + // for testing purposes we only look at the first 2 gloves available + ClientLog::print(" -- Ergo Timestamp {}:{}:{}.{} ~ {}/{}/{}(D/M/Y)", + m_ErgoTimestampInfo.hour, m_ErgoTimestampInfo.minute, m_ErgoTimestampInfo.second, m_ErgoTimestampInfo.fraction, + m_ErgoTimestampInfo.day, m_ErgoTimestampInfo.month, std::to_string(m_ErgoTimestampInfo.year)); + ClientLog::print(" -- Left Glove -- 0x{} - Angles in degrees", m_FirstLeftGloveID); + if (m_LeftGloveErgoData.id == m_FirstLeftGloveID) + { + PrintHandErgoData(m_LeftGloveErgoData, true); + } + else + { + ClientLog::print(" ...No Data..."); + } + ClientLog::print(" -- Right Glove -- 0x{} - Angles in degrees", m_FirstRightGloveID); + if (m_RightGloveErgoData.id == m_FirstRightGloveID) + { + PrintHandErgoData(m_RightGloveErgoData, false); + } + else + { + ClientLog::print(" ...No Data..."); + } + + AdvanceConsolePosition(14); +} + +std::string ConvertDeviceClassTypeToString(DeviceClassType p_Type) +{ + switch (p_Type) + { + case DeviceClassType_Dongle: + return "Dongle"; + case DeviceClassType_Glove: + return "Glove"; + case DeviceClassType_Glongle: + return "Glongle (Glove Dongle)"; + default: + return "Unknown"; + } +} + +std::string ConvertDeviceFamilyTypeToString(DeviceFamilyType p_Type) +{ + switch (p_Type) + { + case DeviceFamilyType_Prime1: + return "Prime 1"; + case DeviceFamilyType_Prime2: + return "Prime 2"; + case DeviceFamilyType_PrimeX: + return "Prime X"; + case DeviceFamilyType_Metaglove: + return "Metaglove"; + case DeviceFamilyType_Prime3: + return "Prime 3"; + case DeviceFamilyType_Virtual: + return "Virtual"; + case DeviceFamilyType_MetaglovePro: + return "Metaglove Pro"; + default: + return "Unknown"; + } +} + +/// @brief Print the ergonomics data received from Core. +void SDKClient::PrintDongleData() +{ + // get a dongle id + uint32_t t_DongleCount = m_Landscape->gloveDevices.dongleCount; + if (t_DongleCount == 0) return; // we got no gloves to work on anyway! + + DongleLandscapeData t_DongleData; + + for (uint32_t i = 0; i < t_DongleCount; i++) + { + t_DongleData = m_Landscape->gloveDevices.dongles[i]; + ClientLog::print(" -- Dongle -- 0x{}", t_DongleData.id); + + ClientLog::print(" Type: {} - {}", + ConvertDeviceClassTypeToString(t_DongleData.classType), + ConvertDeviceFamilyTypeToString(t_DongleData.familyType)); + ClientLog::print(" License: {}", t_DongleData.licenseType); + + AdvanceConsolePosition(4); + } +} + +/// @brief Prints the last received system messages received from Core. +void SDKClient::PrintSystemMessage() +{ + m_SystemMessageMutex.lock(); + ClientLog::print(""); //blank line + ClientLog::print("Received System data:{} / code:{}", m_SystemMessage, (int32_t)m_SystemMessageCode); + m_SystemMessageMutex.unlock(); +} + +/// @brief Prints the finalized skeleton data received from Core. +/// Since our console cannot render this data visually in 3d (its not in the scope of this client) +/// we only display a little bit of data of the skeletons we receive. +void SDKClient::PrintSkeletonData() +{ + if (m_Skeleton == nullptr || m_Skeleton->skeletons.size() == 0) + { + return; + } + + ClientLog::print("Received Skeleton data. skeletons:{} first skeleton id:{}", m_Skeleton->skeletons.size(), (int32_t)m_Skeleton->skeletons[0].info.id); + + AdvanceConsolePosition(2); +} + +void SDKClient::PrintRawSkeletonData() +{ + if (m_RawSkeleton == nullptr || m_RawSkeleton->skeletons.size() == 0) + { + return; + } + ClientLog::print("Received Skeleton glove data from Core. skeletons:{} first skeleton glove id:{}", m_RawSkeleton->skeletons.size(), m_RawSkeleton->skeletons[0].info.gloveId); + + if (m_FirstLeftGloveID == 0 && m_FirstRightGloveID == 0) return; // no gloves connected to core + + uint32_t t_NodeCount = 0; + uint32_t t_GloveId; + if (m_FirstLeftGloveID != 0) + { + t_GloveId = m_FirstLeftGloveID; + } + else + { + t_GloveId = m_FirstRightGloveID; + } + // we need to know the number of nodes in the hierarchy, so we can initialize an array with the correct size. + SDKReturnCode t_Result = CoreSdk_GetRawSkeletonNodeCount(t_GloveId, t_NodeCount); + if (t_Result != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get Raw Skeleton Node Count. The error given was {}.", (int32_t)t_Result); + return; + } + + // now get the hierarchy data, this can be used to reconstruct the positions of each node in case the user set up the system with a local coordinate system, and to know what each node is exactly. + // having a node position defined as local means that this will be related to its parent + NodeInfo* t_NodeInfo = new NodeInfo[t_NodeCount]; + t_Result = CoreSdk_GetRawSkeletonNodeInfoArray(t_GloveId, t_NodeInfo, t_NodeCount); + if (t_Result != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get Raw Skeleton Hierarchy. The error given was {}.", (int32_t)t_Result); + return; + } + + ClientLog::print("Fetched array with Raw Skeleton Hierarchy with {} nodes.", (int32_t)t_NodeCount); + AdvanceConsolePosition(2); +} + +/// @brief Prints the tracker data +/// Since our console cannot render this data visually in 3d (its not in the scope of this client) +/// we only display a little bit of data of the trackers we receive. +void SDKClient::PrintTrackerData() +{ + ClientLog::print("Tracker test active: {}.", m_TrackerTest); //To show that test tracker is being sent to core + ClientLog::print("Per user tracker display: {}.", m_TrackerDataDisplayPerUser); + + AdvanceConsolePosition(2); + + if (m_TrackerDataDisplayPerUser) + { + PrintTrackerDataPerUser(); + AdvanceConsolePosition(10); + } + else + { + PrintTrackerDataGlobal(); + AdvanceConsolePosition(3); + } + + // now, as a test, print the tracker data received from the stream + if (m_TrackerData == nullptr || m_TrackerData->trackerData.size() == 0) + { + return; + } + + ClientLog::print("Received Tracker data. number of received trackers:{} first tracker type:{}", m_TrackerData->trackerData.size(), (int32_t)m_TrackerData->trackerData[0].trackerType); +} + +/// @brief Prints the tracker data without taking users into account. +/// This shows how one can get the tracker data that is being streamed without caring about users. +void SDKClient::PrintTrackerDataGlobal() +{ + uint32_t t_NumberOfAvailabletrackers = 0; + SDKReturnCode t_TrackerResult = CoreSdk_GetNumberOfAvailableTrackers(&t_NumberOfAvailabletrackers); + if (t_TrackerResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get tracker data. The error given was {}.", (int32_t)t_TrackerResult); + return; + } + + ClientLog::print("received available trackers :{} ", t_NumberOfAvailabletrackers); + + if (t_NumberOfAvailabletrackers == 0) return; // nothing else to do. + TrackerId* t_TrackerId = new TrackerId[t_NumberOfAvailabletrackers]; + t_TrackerResult = CoreSdk_GetIdsOfAvailableTrackers(t_TrackerId, t_NumberOfAvailabletrackers); + if (t_TrackerResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get tracker data. The error given was {}.", (int32_t)t_TrackerResult); + return; + } +} + +/// @brief Prints the tracker data per user, this shows how to access this data for each user. +void SDKClient::PrintTrackerDataPerUser() +{ + uint32_t t_NumberOfAvailableUsers = 0; + SDKReturnCode t_UserResult = CoreSdk_GetNumberOfAvailableUsers(&t_NumberOfAvailableUsers); + if (t_UserResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get user count. The error given was {}.", (int32_t)t_UserResult); + return; + } + if (t_NumberOfAvailableUsers == 0) return; // nothing to get yet + + + for (uint32_t i = 0; i < t_NumberOfAvailableUsers; i++) + { + uint32_t t_NumberOfAvailabletrackers = 0; + SDKReturnCode t_TrackerResult = CoreSdk_GetNumberOfAvailableTrackersForUserIndex(&t_NumberOfAvailabletrackers, i); + if (t_TrackerResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get tracker data. The error given was {}.", (int32_t)t_TrackerResult); + return; + } + + if (t_NumberOfAvailabletrackers == 0) continue; + + ClientLog::print("received available trackers for user index[{}] :{} ", i, t_NumberOfAvailabletrackers); + + if (t_NumberOfAvailabletrackers == 0) return; // nothing else to do. + TrackerId* t_TrackerId = new TrackerId[t_NumberOfAvailabletrackers]; + t_TrackerResult = CoreSdk_GetIdsOfAvailableTrackersForUserIndex(t_TrackerId, i, t_NumberOfAvailabletrackers); + if (t_TrackerResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get tracker data. The error given was {}.", (int32_t)t_TrackerResult); + return; + } + } +} + +std::string GetFPSEnumName(TimecodeFPS p_FPS) +{ + switch (p_FPS) + { + case TimecodeFPS::TimecodeFPS_23_976: + return "23.976 FPS (24 dropframe)"; + case TimecodeFPS::TimecodeFPS_24: + return "24 FPS"; + case TimecodeFPS::TimecodeFPS_25: + return "25 FPS"; + case TimecodeFPS::TimecodeFPS_29_97: + return "29.97 FPS (30 dropframe)"; + case TimecodeFPS::TimecodeFPS_30: + return "30 FPS"; + case TimecodeFPS::TimecodeFPS_50: + return "50 FPS"; + case TimecodeFPS::TimecodeFPS_59_94: + return "59.94 FPS (60 dropframe)"; + case TimecodeFPS::TimecodeFPS_60: + return "60 FPS"; + default: + return "Undefined FPS"; + } +} + +void SDKClient::PrintLandscapeTimeData() +{ + ClientLog::print("Total count of Interfaces: {}", m_Landscape->time.interfaceCount); + ClientLog::print("Current Interface: {} {} at index {}", m_Landscape->time.currentInterface.name, m_Landscape->time.currentInterface.api, m_Landscape->time.currentInterface.index); + + ClientLog::print("FPS: {}", GetFPSEnumName(m_Landscape->time.fps)); + ClientLog::print("Fake signal: {} | Sync Pulse: {} | Sync Status: {}", m_Landscape->time.fakeTimecode, m_Landscape->time.useSyncPulse, m_Landscape->time.syncStatus); + ClientLog::print("Device keep alive: {} | Timecode Status: {}", m_Landscape->time.deviceKeepAlive, m_Landscape->time.timecodeStatus); + + AdvanceConsolePosition(6); +} + +void SDKClient::PrintGestureData() +{ + ClientGestures* t_Gest = m_FirstLeftGloveGestures; + std::string t_Side = "Left"; + if (!m_ShowLeftGestures) + { + t_Side = "Right"; + t_Gest = m_FirstRightGloveGestures; + } + + if (t_Gest == nullptr) + { + ClientLog::print("No Gesture information for first {} glove.", t_Side); + AdvanceConsolePosition(1); + return; + } + ClientLog::print("Total count of gestures for the {} glove: {}", t_Side, t_Gest->info.totalGestureCount); + uint32_t t_Max = t_Gest->info.totalGestureCount; + if (t_Max > 20) t_Max = 20; + ClientLog::print("Showing result of first {} gestures.", t_Max); + for (uint32_t i = 0; i < t_Max; i++) + { + char* t_Name = ""; + for (uint32_t g = 0; g < m_GestureLandscapeData.size(); g++) + { + if (m_GestureLandscapeData[g].id == t_Gest->probabilities[i].id) + { + t_Name = m_GestureLandscapeData[g].name; + } + } + ClientLog::print("Gesture {} ({}) has a probability of {}%.", t_Name, t_Gest->probabilities[i].id, t_Gest->probabilities[i].percent * 100.0f); + } + + AdvanceConsolePosition(t_Max + 2); +} + +void SDKClient::PrintGloveCalibrationData() +{ + std::string t_Side = "Left"; + if (!m_CalibrateLeftHand) + { + t_Side = "Right"; + } + ClientLog::print("Calibrating: {} - Step {} ", t_Side, m_CalibrationStep); + ClientLog::print("Glove: {}", m_CalibrationGloveId); + ClientLog::print("Number of steps: {}", m_NumberOfCalibrationSteps); + ClientLog::print("Title: {}", m_StepData.title); + ClientLog::print("Description: {}", m_StepData.description); + ClientLog::print("Time: {}", m_StepData.time); + ClientLog::print("In progress: {}", m_IsCalibrationInProgress); + ClientLog::print("Message: {}", m_CalibrationMessage); + + AdvanceConsolePosition(6); +} + +/// @brief Prints the type of the first chain generated by the AllocateChain function, this is used for testing. +void SDKClient::PrintSkeletonInfo() +{ + switch (m_ChainType) + { + case ChainType::ChainType_FingerIndex: + { + ClientLog::print("received Skeleton chain type: ChainType_FingerIndex"); + break; + } + case ChainType::ChainType_FingerMiddle: + { + ClientLog::print("received Skeleton chain type: ChainType_FingerMiddle"); + break; + } + case ChainType::ChainType_FingerPinky: + { + ClientLog::print("received Skeleton chain type: ChainType_FingerPinky"); + break; + } + case ChainType::ChainType_FingerRing: + { + ClientLog::print("received Skeleton chain type: ChainType_FingerRing"); + break; + } + case ChainType::ChainType_FingerThumb: + { + ClientLog::print("received Skeleton chain type: ChainType_FingerThumb"); + break; + } + case ChainType::ChainType_Hand: + { + ClientLog::print("received Skeleton chain type: ChainType_Hand"); + break; + } + case ChainType::ChainType_Head: + { + ClientLog::print("received Skeleton chain type: ChainType_Head"); + break; + } + case ChainType::ChainType_Leg: + { + ClientLog::print("received Skeleton chain type: ChainType_Leg"); + break; + } + case ChainType::ChainType_Neck: + { + ClientLog::print("received Skeleton chain type: ChainType_Neck"); + break; + } + case ChainType::ChainType_Pelvis: + { + ClientLog::print("received Skeleton chain type: ChainType_Pelvis"); + break; + } + case ChainType::ChainType_Shoulder: + { + ClientLog::print("received Skeleton chain type: ChainType_Shoulder"); + break; + } + case ChainType::ChainType_Spine: + { + ClientLog::print("received Skeleton chain type: ChainType_Spine"); + break; + } + case ChainType::ChainType_Arm: + { + ClientLog::print("received Skeleton chain type: ChainType_Arm"); + break; + } + case ChainType_Foot: + { + ClientLog::print("received Skeleton chain type: ChainType_Foot"); + break; + } + case ChainType_Toe: + { + ClientLog::print("received Skeleton chain type: ChainType_Toe"); + break; + } + case ChainType::ChainType_Invalid: + default: + { + ClientLog::print("received Skeleton chain type: ChainType_Invalid"); + break; + } + } + AdvanceConsolePosition(2); +} + +/// @brief This support function checks if a temporary skeleton related to the current session has been modified and gets it. +/// Whenever the Dev Tools saves the changes to the skeleton, it sets the boolean t_IsSkeletonModified to true for that skeleton. +/// With callback OnSystemCallback this application can be notified when one of its temporary skeletons has been modified, so it can get it and, potentially, load it. +void SDKClient::GetTemporarySkeletonIfModified() +{ + // if a temporary skeleton associated to the current session has been modified we can get it and, potentially, load it + if (m_ModifiedSkeletonIndex != UINT_MAX) + { + // get the temporary skeleton + uint32_t t_SessionId = m_SessionId; + SDKReturnCode t_Res = CoreSdk_GetTemporarySkeleton(m_ModifiedSkeletonIndex, t_SessionId); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get temporary skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + + // At this point if we are satisfied with the modifications to the skeleton we can load it into Core. + // Remember to always call function CoreSdk_ClearTemporarySkeleton after loading a temporary skeleton, + // this will keep the temporary skeleton list in sync between Core and the SDK. + + //uint32_t t_ID = 0; + //SDKReturnCode t_Res = CoreSdk_LoadSkeleton(m_ModifiedSkeletonIndex, &t_ID); + //if (t_Res != SDKReturnCode::SDKReturnCode_Success) + //{ + // ClientLog::error("Failed to load skeleton. The error given was {}.", t_Res); + // return; + //} + //if (t_ID == 0) + //{ + // ClientLog::error("Failed to give skeleton an ID."); + //} + //m_LoadedSkeletons.push_back(t_ID); + //t_Res = CoreSdk_ClearTemporarySkeleton(m_ModifiedSkeletonIndex, m_SessionId); + //if (t_Res != SDKReturnCode::SDKReturnCode_Success) + //{ + // ClientLog::error("Failed to clear temporary skeleton. The error given was {}.", t_Res); + // return; + //} + m_ModifiedSkeletonIndex = UINT_MAX; + } +} +/// @brief This support function gets the temporary skeletons for all sessions connected to Core and it prints the total number of temporary skeletons associated to the current session. +/// Temporary skeletons are used for auto allocation and in the Dev Tools. +void SDKClient::PrintTemporarySkeletonInfo() +{ + ClientLog::print("Number of temporary skeletons in the SDK: {} ", m_TemporarySkeletons.size()); + + static uint32_t t_TotalNumberOfTemporarySkeletonsInCore = 0; + auto t_TimeSinceLastTemporarySkeletonUpdate = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - m_LastTemporarySkeletonUpdate).count(); + if (t_TimeSinceLastTemporarySkeletonUpdate < static_cast(MILLISECONDS_BETWEEN_TEMPORARY_SKELETONS_UPDATE)) + { + ClientLog::print("Total number of temporary skeletons in core: {} ", t_TotalNumberOfTemporarySkeletonsInCore); + return; + } + TemporarySkeletonCountForAllSessions t_TemporarySkeletonCountForAllSessions; + SDKReturnCode t_Res = CoreSdk_GetTemporarySkeletonCountForAllSessions(&t_TemporarySkeletonCountForAllSessions); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get all temporary skeletons. The error given was {}.", (int32_t)t_Res); + return; + } + + t_TotalNumberOfTemporarySkeletonsInCore = 0; + for (uint32_t i = 0; i < t_TemporarySkeletonCountForAllSessions.sessionsCount; i++) + { + t_TotalNumberOfTemporarySkeletonsInCore += t_TemporarySkeletonCountForAllSessions.temporarySkeletonCountForSessions[i].skeletonCount; + } + + // print total number of temporary skeletons: + ClientLog::print("Total number of temporary skeletons in core: {} ", t_TotalNumberOfTemporarySkeletonsInCore); + m_LastTemporarySkeletonUpdate = std::chrono::high_resolution_clock::now(); +} + +void SDKClient::HandlePairingCommands() +{ + if (GetKeyDown('P')) // press P to pair + { + PairGlove(); + } + + if (GetKeyDown('U')) // press U to Unpair + { + UnpairGlove(); + } +} + +/// @brief This showcases haptics support on gloves. +/// Send haptics commands to connected gloves if specific keys were pressed. +/// We have two ways of sending the vibration commands, based on the dongle id or based on the skeleton id. +void SDKClient::HandleHapticCommands() +{ + const int t_LeftHand = 0; + const int t_RightHand = 1; + + uint32_t t_GloveIDs[2] = { 0, 0 }; + + for (size_t i = 0; i < m_Landscape->gloveDevices.gloveCount; i++) + { + GloveLandscapeData t_GloveLandscapeData = m_Landscape->gloveDevices.gloves[i]; + if (t_GloveLandscapeData.side == Side_Left && t_GloveLandscapeData.isHaptics) + { + t_GloveIDs[t_LeftHand] = t_GloveLandscapeData.id; + break; + } + } + + for (size_t i = 0; i < m_Landscape->gloveDevices.gloveCount; i++) + { + GloveLandscapeData t_GloveLandscapeData = m_Landscape->gloveDevices.gloves[i]; + if (t_GloveLandscapeData.side == Side_Right && t_GloveLandscapeData.isHaptics) + { + t_GloveIDs[t_RightHand] = t_GloveLandscapeData.id; + break; + } + } + + ClientHapticSettings t_HapticState[NUMBER_OF_HANDS_SUPPORTED]{}; + + // The strange key number sequence here results from having gloves lie in front of you, and have the keys and haptics in the same order. + t_HapticState[t_LeftHand].shouldHapticFinger[0] = GetKey('5'); // left thumb + t_HapticState[t_LeftHand].shouldHapticFinger[1] = GetKey('4'); // left index + t_HapticState[t_LeftHand].shouldHapticFinger[2] = GetKey('3'); // left middle + t_HapticState[t_LeftHand].shouldHapticFinger[3] = GetKey('2'); // left ring + t_HapticState[t_LeftHand].shouldHapticFinger[4] = GetKey('1'); // left pinky + t_HapticState[t_RightHand].shouldHapticFinger[0] = GetKey('6'); // right thumb + t_HapticState[t_RightHand].shouldHapticFinger[1] = GetKey('7'); // right index + t_HapticState[t_RightHand].shouldHapticFinger[2] = GetKey('8'); // right middle + t_HapticState[t_RightHand].shouldHapticFinger[3] = GetKey('9'); // right ring + t_HapticState[t_RightHand].shouldHapticFinger[4] = GetKey('0'); // right pinky + + const float s_FullPower = 1.0f; + + for (unsigned int t_HandNumber = 0; t_HandNumber < NUMBER_OF_HANDS_SUPPORTED; t_HandNumber++) + { + //If the Glove ID is 0, no glove was found for that side + if (t_GloveIDs[t_HandNumber] == 0) + { + continue; + } + + float t_HapticsPowers[NUM_FINGERS_ON_HAND]{}; + for (unsigned int t_FingerNumber = 0; t_FingerNumber < NUM_FINGERS_ON_HAND; t_FingerNumber++) + { + t_HapticsPowers[t_FingerNumber] = t_HapticState[t_HandNumber].shouldHapticFinger[t_FingerNumber] ? s_FullPower : 0.0f; + } + + CoreSdk_VibrateFingersForGlove(t_GloveIDs[t_HandNumber], t_HapticsPowers); + } +} + +/// @brief Handles the console commands for the skeletons. +void SDKClient::HandleSkeletonCommands() +{ + if (GetKeyDown('B')) + { + LoadTestSkeleton(Side_Left); + } + if (GetKeyDown('N')) + { + LoadTestSkeleton(Side_Right); + } + if (GetKeyDown('M')) + { + UnloadTestSkeleton(); + } + if (GetKeyDown('D')) + { + //Toggle send to DevTools + m_SendToDevTools = !m_SendToDevTools; + } +} + +/// @brief This showcases haptics support on the skeletons. +/// Send haptics commands to the gloves connected to a skeleton if specific keys were pressed. +/// We have two ways of sending the vibration commands, based on the dongle id or based on the skeleton id. +void SDKClient::HandleSkeletonHapticCommands() +{ + if (m_Skeleton == nullptr || m_Skeleton->skeletons.size() == 0) + { + return; + } + + ClientHapticSettings t_HapticState[NUMBER_OF_HANDS_SUPPORTED]{}; + const int t_LeftHand = 0; + const int t_RightHand = 1; + + // The strange key number sequence here results from having gloves lie in front of you, and have the keys and haptics in the same order. + t_HapticState[t_LeftHand].shouldHapticFinger[0] = GetKey('5'); // left thumb + t_HapticState[t_LeftHand].shouldHapticFinger[1] = GetKey('4'); // left index + t_HapticState[t_LeftHand].shouldHapticFinger[2] = GetKey('3'); // left middle + t_HapticState[t_LeftHand].shouldHapticFinger[3] = GetKey('2'); // left ring + t_HapticState[t_LeftHand].shouldHapticFinger[4] = GetKey('1'); // left pinky + t_HapticState[t_RightHand].shouldHapticFinger[0] = GetKey('6'); // right thumb + t_HapticState[t_RightHand].shouldHapticFinger[1] = GetKey('7'); // right index + t_HapticState[t_RightHand].shouldHapticFinger[2] = GetKey('8'); // right middle + t_HapticState[t_RightHand].shouldHapticFinger[3] = GetKey('9'); // right ring + t_HapticState[t_RightHand].shouldHapticFinger[4] = GetKey('0'); // right pinky + + // Note: this timer is apparently not very accurate. + // It is good enough for this test client, but should probably be replaced for other uses. + static std::chrono::high_resolution_clock::time_point s_TimeOfLastHapticsCommandSent; + const std::chrono::high_resolution_clock::time_point s_Now = std::chrono::high_resolution_clock::now(); + const long long s_MillisecondsSinceLastHapticCommand = std::chrono::duration_cast(s_Now - s_TimeOfLastHapticsCommandSent).count(); + + if (s_MillisecondsSinceLastHapticCommand < static_cast(MINIMUM_MILLISECONDS_BETWEEN_HAPTICS_COMMANDS)) + { + return; + } + + const Side s_Hands[NUMBER_OF_HANDS_SUPPORTED] = { Side::Side_Left, Side::Side_Right }; + const float s_FullPower = 1.0f; + + // The preferred way of sending the haptics commands is based on skeleton id + + for (unsigned int t_HandNumber = 0; t_HandNumber < NUMBER_OF_HANDS_SUPPORTED; t_HandNumber++) + { + float t_HapticsPowers[NUM_FINGERS_ON_HAND]{}; + for (unsigned int t_FingerNumber = 0; t_FingerNumber < NUM_FINGERS_ON_HAND; t_FingerNumber++) + { + t_HapticsPowers[t_FingerNumber] = t_HapticState[t_HandNumber].shouldHapticFinger[t_FingerNumber] ? s_FullPower : 0.0f; + } + bool t_IsHaptics = false; + if (CoreSdk_DoesSkeletonGloveSupportHaptics(m_Skeleton->skeletons[0].info.id, s_Hands[t_HandNumber], &t_IsHaptics) != SDKReturnCode::SDKReturnCode_Success) + { + continue; + } + if (!t_IsHaptics) + { + continue; + } + CoreSdk_VibrateFingersForSkeleton(m_Skeleton->skeletons[0].info.id, s_Hands[t_HandNumber], t_HapticsPowers); + } +} + +/// @brief Handles the console commands for the temporary skeletons. +void SDKClient::HandleTemporarySkeletonCommands() +{ + if (GetKeyDown('A')) + { + AllocateChains(); + } + if (GetKeyDown('B')) + { + BuildTemporarySkeleton(); + } + if (GetKeyDown('C')) + { + ClearTemporarySkeleton(); + } + if (GetKeyDown('D')) + { + ClearAllTemporarySkeletons(); + } + if (GetKeyDown('E')) + { + SaveTemporarySkeletonToFile(); + } + if (GetKeyDown('F')) + { + GetTemporarySkeletonFromFile(); + } +} + +/// @brief This support function is used to set a test tracker and add it to the landscape. +void SDKClient::HandleTrackerCommands() +{ + if (GetKeyDown('O')) + { + m_TrackerTest = !m_TrackerTest; + } + + if (GetKeyDown('G')) + { + m_TrackerDataDisplayPerUser = !m_TrackerDataDisplayPerUser; + } + + if (GetKeyDown('T')) + { + SetTrackerOffset(); + } + + if (m_TrackerTest) + { + m_TrackerOffset += 0.0005f; + if (m_TrackerOffset >= 10.0f) + { + m_TrackerOffset = 0.0f; + } + + TrackerId t_TrackerId; + CopyString(t_TrackerId.id, sizeof(t_TrackerId.id), std::string("Test Tracker")); + TrackerData t_TrackerData = {}; + t_TrackerData.isHmd = false; + t_TrackerData.trackerId = t_TrackerId; + t_TrackerData.trackerType = TrackerType::TrackerType_Unknown; + t_TrackerData.position = { 0.0f, m_TrackerOffset, 0.0f }; + t_TrackerData.rotation = { 1.0f, 0.0f, 0.0f, 0.0f }; + t_TrackerData.quality = TrackerQuality::TrackingQuality_Trackable; + TrackerData t_TrackerDatas[MAX_NUMBER_OF_TRACKERS]; + t_TrackerDatas[0] = t_TrackerData; + + const SDKReturnCode t_TrackerSend = CoreSdk_SendDataForTrackers(t_TrackerDatas, 1); + if (t_TrackerSend != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to send tracker data. The error given was {}.", (int32_t)t_TrackerSend); + return; + } + } +} + +/// @brief This support function is used to set the tracker offset. It sets the tracker offset for the left hand tracker to the wrist. +void SDKClient::SetTrackerOffset() { + + TrackerOffset t_TrackerOffset; + + //Positions the tracker 3mm right, 58mm up and 43mm forward relative to the wrist. This value is illustrative and should be adjusted to the actual tracker position. + t_TrackerOffset.translation = { 0.003f, -0.058f, -0.043f }; + t_TrackerOffset.rotation = { 1.0f, 0.0f, 0.0f, 0.0f }; + t_TrackerOffset.entryType = TrackerOffsetType::TrackerOffsetType_LeftHandTrackerToWrist; + + auto t_UserId = m_Landscape->users.users[0].id; + + SDKReturnCode t_SetTrackerReturn = CoreSdk_SetTrackerOffset(t_UserId, &t_TrackerOffset); + if (t_SetTrackerReturn != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to set tracker offset. The error given was {}.", (int32_t)t_SetTrackerReturn); + return; + } +} + +/// @brief Handles the console commands for the gestures. +void SDKClient::HandleGesturesCommands() +{ + if (GetKeyDown('H')) + { + m_ShowLeftGestures = !m_ShowLeftGestures; + } +} + +void SDKClient::ExecuteGloveCalibrationStep(GloveCalibrationStepArgs p_Args) +{ + bool t_Result; + auto t_Res = CoreSdk_GloveCalibrationStartStep(p_Args, &t_Result); + + if (t_Res == SDKReturnCode_Success && t_Result) + m_CalibrationMessage = "Step finished"; + else + m_CalibrationMessage = "Step failed"; + + m_IsCalibrationInProgress = false; +} + + +/// @brief Handles the console commands for the glove calibration. +void SDKClient::HandleGloveCalibrationCommands() +{ + // Reset data + m_NumberOfCalibrationSteps = 0; + m_CalibrationGloveId = 0; + m_ValidStepData = false; + GloveCalibrationStepData_Init(&m_StepData); + + if (GetKeyDown('H')) + { + m_CalibrateLeftHand = !m_CalibrateLeftHand; + } + + // Get glove id + if (m_Landscape == nullptr || m_Landscape->users.userCount == 0) + return; + + uint32_t t_GloveID = m_Landscape->users.users[0].leftGloveID; + if (!m_CalibrateLeftHand) + t_GloveID = m_Landscape->users.users[0].rightGloveID; + + m_CalibrationGloveId = t_GloveID; + + // Check if glove ID is valid, if not return + if (m_CalibrationGloveId == 0) + return; + + GloveCalibrationArgs t_Args; + t_Args.gloveId = m_CalibrationGloveId; + + // Get the number of calibration steps + auto t_Res = CoreSdk_GloveCalibrationGetNumberOfSteps(t_Args, &m_NumberOfCalibrationSteps); + if (t_Res != SDKReturnCode_Success || m_NumberOfCalibrationSteps == 0) + return; + + if (GetKeyDown('P') && m_CalibrationStep < 9) + { + m_CalibrationStep++; + } + + if (GetKeyDown('M') && m_CalibrationStep != 0) + { + m_CalibrationStep--; + } + + // Clamp current step to max number of steps + if (m_CalibrationStep >= m_NumberOfCalibrationSteps) + m_CalibrationStep = m_NumberOfCalibrationSteps - 1; + + // Get step data + GloveCalibrationStepArgs t_StepArgs; + t_StepArgs.gloveId = t_Args.gloveId; + t_StepArgs.stepIndex = m_CalibrationStep; + t_Res = CoreSdk_GloveCalibrationGetStepData(t_StepArgs, &m_StepData); + if (t_Res != SDKReturnCode_Success) + return; + + // Dont allow starting/stopping/etc while in progress + if (m_IsCalibrationInProgress) + return; + + if (GetKeyDown('S')) // Start + { + bool t_Result = false; + t_Res = CoreSdk_GloveCalibrationStart(t_Args, &t_Result); + + if (t_Res == SDKReturnCode::SDKReturnCode_Success && t_Result) + m_CalibrationMessage = "Glove calibration started"; + else + m_CalibrationMessage = "Failed to start glove calibration"; + } + + if (GetKeyDown('C')) // Cancel + { + bool t_Result = false; + t_Res = CoreSdk_GloveCalibrationStop(t_Args, &t_Result); + + if (t_Res == SDKReturnCode::SDKReturnCode_Success && t_Result) + m_CalibrationMessage = "Glove calibration stopped"; + else + m_CalibrationMessage = "Failed to stop glove calibration"; + } + + if (GetKeyDown('F')) // Finish + { + bool t_Result = false; + t_Res = CoreSdk_GloveCalibrationFinish(t_Args, &t_Result); + + if (t_Res == SDKReturnCode::SDKReturnCode_Success && t_Result) + m_CalibrationMessage = "Glove calibration finished"; + else + m_CalibrationMessage = "Failed to finish glove calibration"; + } + + if (GetKeyDown('E')) // Execute step + { + m_CalibrationMessage = "Step " + std::to_string(m_CalibrationStep) + " in progress"; + m_IsCalibrationInProgress = true; + std::thread t_Thread(&SDKClient::ExecuteGloveCalibrationStep, this, t_StepArgs); + t_Thread.detach(); + } +} + +/// @brief Skeletons are pretty extensive in their data setup +/// so we have several support functions so we can correctly receive and parse the data, +/// this function helps setup the data. +/// @param p_Id the id of the created node setup +/// @param p_ParentId the id of the node parent +/// @param p_PosX X position of the node, this is defined with respect to the global coordinate system or the local one depending on +/// the parameter p_UseWorldCoordinates set when initializing the sdk, +/// @param p_PosY Y position of the node this is defined with respect to the global coordinate system or the local one depending on +/// the parameter p_UseWorldCoordinates set when initializing the sdk, +/// @param p_PosZ Z position of the node this is defined with respect to the global coordinate system or the local one depending on +/// the parameter p_UseWorldCoordinates set when initializing the sdk, +/// @param p_Name the name of the node setup +/// @return the generated node setup +NodeSetup SDKClient::CreateNodeSetup(uint32_t p_Id, uint32_t p_ParentId, float p_PosX, float p_PosY, float p_PosZ, std::string p_Name) +{ + NodeSetup t_Node; + NodeSetup_Init(&t_Node); + t_Node.id = p_Id; //Every ID needs to be unique per node in a skeleton. + CopyString(t_Node.name, sizeof(t_Node.name), p_Name); + t_Node.type = NodeType::NodeType_Joint; + //Every node should have a parent unless it is the Root node. + t_Node.parentID = p_ParentId; //Setting the node ID to its own ID ensures it has no parent. + t_Node.settings.usedSettings = NodeSettingsFlag::NodeSettingsFlag_None; + + t_Node.transform.position.x = p_PosX; + t_Node.transform.position.y = p_PosY; + t_Node.transform.position.z = p_PosZ; + return t_Node; +} + +ManusVec3 SDKClient::CreateManusVec3(float p_X, float p_Y, float p_Z) +{ + ManusVec3 t_Vec; + t_Vec.x = p_X; + t_Vec.y = p_Y; + t_Vec.z = p_Z; + return t_Vec; +} + +/// @brief This support function sets up the nodes for the skeleton hand +/// In order to have any 3d positional/rotational information from the gloves or body, +/// one needs to setup the skeleton on which this data should be applied. +/// In the case of this sample we create a Hand skeleton for which we want to get the calculated result. +/// The ID's for the nodes set here are the same IDs which are used in the OnSkeletonStreamCallback, +/// this allows us to create the link between Manus Core's data and the data we enter here. +bool SDKClient::SetupHandNodes(uint32_t p_SklIndex, Side p_Side) +{ + // Define number of fingers per hand and number of joints per finger + const uint32_t t_NumFingers = 5; + const uint32_t t_NumJoints = 4; + + // Because the skeleton is build up in world space coordinates all joints have to be defined in coordate space as well + // If it is required for the skeleton to work in local space, substract all previous positions from the vectors + static ManusVec3 s_LeftHandPositions[t_NumFingers * t_NumJoints] + { + CreateManusVec3(0.025320f, -0.024950f, 0.000000f), //Thumb CMC joint + CreateManusVec3(0.025320f + 0.032742f, -0.024950f, 0.000000f), //Thumb MCP joint + CreateManusVec3(0.025320f + 0.032742f + 0.028739f, -0.024950f, 0.000000f), //Thumb IP joint + CreateManusVec3(0.025320f + 0.032742f + 0.028739f + 0.028739f, -0.024950f, 0.000000f), //Thumb Tip joint + + CreateManusVec3(0.052904f, -0.011181f, 0.000000f), //Index MCP joint + CreateManusVec3(0.052904f + 0.038257f, -0.011181f, 0.000000f), //Index PIP joint + CreateManusVec3(0.052904f + 0.038257f + 0.020884f, -0.011181f, 0.000000f), //Index DIP joint + CreateManusVec3(0.052904f + 0.038257f + 0.020884f + 0.018759f, -0.011181f, 0.000000f), //Index Tip joint + + CreateManusVec3(0.051287f, 0.000000f, 0.000000f), //Middle MCP joint + CreateManusVec3(0.051287f + 0.041861f, 0.000000f, 0.000000f), //Middle PIP joint + CreateManusVec3(0.051287f + 0.041861f + 0.024766f, 0.000000f, 0.000000f), //Middle DIP joint + CreateManusVec3(0.051287f + 0.041861f + 0.024766f + 0.019683f, 0.000000f, 0.000000f), //Middle Tip joint + + CreateManusVec3(0.049802f, 0.011274f, 0.000000f ), //Ring MCP joint + CreateManusVec3(0.049802f + 0.039736f, 0.011274f, 0.000000f), //Ring PIP joint + CreateManusVec3(0.049802f + 0.039736f + 0.023564f, 0.011274f, 0.000000f), //Ring DIP joint + CreateManusVec3(0.049802f + 0.039736f + 0.023564f + 0.019868f, 0.011274f, 0.000000f), //Ring Tip joint + + CreateManusVec3(0.047309f, 0.020145f,0.000000f), //Pinky MCP joint + CreateManusVec3(0.047309f + 0.033175f, 0.020145f, 0.000000f), //Pinky PIP joint + CreateManusVec3(0.047309f + 0.033175f + 0.018020f, 0.020145f, 0.000000f), //Pinky DIP joint + CreateManusVec3(0.047309f + 0.033175f + 0.018020f + 0.019129f, 0.020145f, 0.000000f), //Pinky Tip joint + }; + + static ManusVec3 s_RightHandPositions[t_NumFingers * t_NumJoints] + { + CreateManusVec3(0.025320f, 0.024950f, 0.000000f), //Thumb CMC joint + CreateManusVec3(0.025320f + 0.032742f, 0.024950f, 0.000000f), //Thumb MCP joint + CreateManusVec3(0.025320f + 0.032742f + 0.028739f, 0.024950f, 0.000000f), //Thumb IP joint + CreateManusVec3(0.025320f + 0.032742f + 0.028739f + 0.028739f, 0.024950f, 0.000000f), //Thumb Tip joint + + CreateManusVec3(0.052904f, 0.011181f, 0.000000f), //Index MCP joint + CreateManusVec3(0.052904f + 0.038257f, 0.011181f, 0.000000f), //Index PIP joint + CreateManusVec3(0.052904f + 0.038257f + 0.020884f, 0.011181f, 0.000000f), //Index DIP joint + CreateManusVec3(0.052904f + 0.038257f + 0.020884f + 0.018759f, 0.011181f, 0.000000f), //Index Tip joint + + CreateManusVec3(0.051287f, 0.000000f, 0.000000f), //Middle MCP joint + CreateManusVec3(0.051287f + 0.041861f, 0.000000f, 0.000000f), //Middle PIP joint + CreateManusVec3(0.051287f + 0.041861f + 0.024766f, 0.000000f, 0.000000f), //Middle DIP joint + CreateManusVec3(0.051287f + 0.041861f + 0.024766f + 0.019683f, 0.000000f, 0.000000f), //Middle Tip joint + + CreateManusVec3(0.049802f, -0.011274f, 0.000000f),//Ring MCP joint + CreateManusVec3(0.049802f + 0.039736f, -0.011274f, 0.000000f), //Ring PIP joint + CreateManusVec3(0.049802f + 0.039736f + 0.023564f, -0.011274f, 0.000000f), //Ring DIP joint + CreateManusVec3(0.049802f + 0.039736f + 0.023564f + 0.019868f, -0.011274f, 0.000000f), //Ring Tip joint + + CreateManusVec3(0.047309f, -0.020145f, 0.000000f),//Pinky MCP joint + CreateManusVec3(0.047309f + 0.033175f, -0.020145f, 0.000000f), //Pinky PIP joint + CreateManusVec3(0.047309f + 0.033175f + 0.018020f, -0.020145f, 0.000000f), //Pinky DIP joint + CreateManusVec3(0.047309f + 0.033175f + 0.018020f + 0.019129f, -0.020145f, 0.000000f), //Pinky Tip joint + }; + + // Create an array with the initial position of each hand node. + // Note, these values are just an example of node positions and refer to the hand laying on a flat surface. + ManusVec3* t_Fingers; + if (p_Side == Side::Side_Left) + { + t_Fingers = s_LeftHandPositions; + } + else + { + t_Fingers = s_RightHandPositions; + } + + // skeleton entry is already done. just the nodes now. + // setup a very simple node hierarchy for fingers + // first setup the root node + // + // root, This node has ID 0 and parent ID 0, to indicate it has no parent. + SDKReturnCode t_Res = CoreSdk_AddNodeToSkeletonSetup(p_SklIndex, CreateNodeSetup(0, 0, 0, 0, 0, "Hand")); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Node To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return false; + } + + // then loop for 5 fingers + int t_FingerId = 0; + for (uint32_t i = 0; i < t_NumFingers; i++) + { + uint32_t t_ParentID = 0; + // then the digits of the finger that are linked to the root of the finger. + for (uint32_t j = 0; j < t_NumJoints; j++) + { + t_Res = CoreSdk_AddNodeToSkeletonSetup(p_SklIndex, CreateNodeSetup(1 + t_FingerId + j, t_ParentID, t_Fingers[i * 4 + j].x, t_Fingers[i * 4 + j].y, t_Fingers[i * 4 + j].z, "fingerdigit")); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + printf("Failed to Add Node To Skeleton Setup. The error given %d.", t_Res); + return false; + } + t_ParentID = 1 + t_FingerId + j; + } + t_FingerId += t_NumJoints; + } + return true; +} + +/// @brief This function sets up some basic hand chains. +/// Chains are required for a Skeleton to be able to be animated, it basically tells Manus Core +/// which nodes belong to which body part and what data needs to be applied to which node. +/// @param p_SklIndex The index of the temporary skeleton on which the chains will be added. +/// @return Returns true if everything went fine, otherwise returns false. +bool SDKClient::SetupHandChains(uint32_t p_SklIndex, Side p_Side) +{ + // Add the Hand chain, this identifies the wrist of the hand + { + ChainSettings t_ChainSettings; + ChainSettings_Init(&t_ChainSettings); + t_ChainSettings.usedSettings = ChainType::ChainType_Hand; + t_ChainSettings.hand.handMotion = HandMotion::HandMotion_IMU; + t_ChainSettings.hand.fingerChainIdsUsed = 5; //we will have 5 fingers + t_ChainSettings.hand.fingerChainIds[0] = 1; //links to the other chains we will define further down + t_ChainSettings.hand.fingerChainIds[1] = 2; + t_ChainSettings.hand.fingerChainIds[2] = 3; + t_ChainSettings.hand.fingerChainIds[3] = 4; + t_ChainSettings.hand.fingerChainIds[4] = 5; + + ChainSetup t_Chain; + ChainSetup_Init(&t_Chain); + t_Chain.id = 0; //Every ID needs to be unique per chain in a skeleton. + t_Chain.type = ChainType::ChainType_Hand; + t_Chain.dataType = ChainType::ChainType_Hand; + t_Chain.side = p_Side; + t_Chain.dataIndex = 0; + t_Chain.nodeIdCount = 1; + t_Chain.nodeIds[0] = 0; //this links to the hand node created in the SetupHandNodes + t_Chain.settings = t_ChainSettings; + + SDKReturnCode t_Res = CoreSdk_AddChainToSkeletonSetup(p_SklIndex, t_Chain); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Chain To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return false; + } + } + + // Add the 5 finger chains + const ChainType t_FingerTypes[5] = { ChainType::ChainType_FingerThumb, + ChainType::ChainType_FingerIndex, + ChainType::ChainType_FingerMiddle, + ChainType::ChainType_FingerRing, + ChainType::ChainType_FingerPinky }; + for (int i = 0; i < 5; i++) + { + ChainSettings t_ChainSettings; + ChainSettings_Init(&t_ChainSettings); + t_ChainSettings.usedSettings = t_FingerTypes[i]; + t_ChainSettings.finger.handChainId = 0; //This links to the wrist chain above. + //This identifies the metacarpal bone, if none exists, or the chain is a thumb it should be set to -1. + //The metacarpal bone should not be part of the finger chain, unless you are defining a thumb which does need it. + t_ChainSettings.finger.metacarpalBoneId = -1; + t_ChainSettings.finger.useLeafAtEnd = false; //this is set to true if there is a leaf bone to the tip of the finger. + ChainSetup t_Chain; + ChainSetup_Init(&t_Chain); + t_Chain.id = i + 1; //Every ID needs to be unique per chain in a skeleton. + t_Chain.type = t_FingerTypes[i]; + t_Chain.dataType = t_FingerTypes[i]; + t_Chain.side = p_Side; + t_Chain.dataIndex = 0; + if (i == 0) // Thumb + { + t_Chain.nodeIdCount = 4; //The amount of node id's used in the array + t_Chain.nodeIds[0] = 1; //this links to the hand node created in the SetupHandNodes + t_Chain.nodeIds[1] = 2; //this links to the hand node created in the SetupHandNodes + t_Chain.nodeIds[2] = 3; //this links to the hand node created in the SetupHandNodes + t_Chain.nodeIds[3] = 4; //this links to the hand node created in the SetupHandNodes + } + else // All other fingers + { + t_Chain.nodeIdCount = 4; //The amount of node id's used in the array + t_Chain.nodeIds[0] = (i * 4) + 1; //this links to the hand node created in the SetupHandNodes + t_Chain.nodeIds[1] = (i * 4) + 2; //this links to the hand node created in the SetupHandNodes + t_Chain.nodeIds[2] = (i * 4) + 3; //this links to the hand node created in the SetupHandNodes + t_Chain.nodeIds[3] = (i * 4) + 4; //this links to the hand node created in the SetupHandNodes + } + t_Chain.settings = t_ChainSettings; + + SDKReturnCode t_Res = CoreSdk_AddChainToSkeletonSetup(p_SklIndex, t_Chain); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + return false; + } + } + return true; +} + +/// @brief This function sets up a very minimalistic hand skeleton. +/// In order to have any 3d positional/rotational information from the gloves or body, +/// one needs to setup a skeleton on which this data can be applied. +/// In the case of this sample we create a Hand skeleton in order to get skeleton information +/// in the OnSkeletonStreamCallback function. This sample does not contain any 3D rendering, so +/// we will not be applying the returned data on anything. +void SDKClient::LoadTestSkeleton(Side p_Side) +{ + uint32_t t_SklIndex = 0; + + SkeletonSetupInfo t_SKL; + SkeletonSetupInfo_Init(&t_SKL); + t_SKL.type = SkeletonType::SkeletonType_Hand; + t_SKL.settings.scaleToTarget = true; + t_SKL.settings.useEndPointApproximations = true; + t_SKL.settings.targetType = SkeletonTargetType::SkeletonTargetType_UserIndexData; + //If the user does not exist then the added skeleton will not be animated. + //Same goes for any other skeleton made for invalid users/gloves. + t_SKL.settings.skeletonTargetUserIndexData.userIndex = 0; + + CopyString(t_SKL.name, sizeof(t_SKL.name), p_Side == Side::Side_Left ? std::string("LeftHand") : std::string("RightHand")); + + SDKReturnCode t_Res = CoreSdk_CreateSkeletonSetup(t_SKL, &t_SklIndex); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Create Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + m_TemporarySkeletons.push_back(t_SklIndex); + + // setup nodes and chains for the skeleton hand + if (!SetupHandNodes(t_SklIndex, p_Side)) return; + if (!SetupHandChains(t_SklIndex, p_Side)) return; + + if (m_SendToDevTools) + { + SendLoadedSkeleton(t_SklIndex); + } + + // load skeleton + uint32_t t_ID = 0; + t_Res = CoreSdk_LoadSkeleton(t_SklIndex, &t_ID); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to load skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + RemoveIndexFromTemporarySkeletonList(t_SklIndex); + + if (t_ID == 0) + { + ClientLog::error("Failed to give skeleton an ID."); + } + m_LoadedSkeletons.push_back(t_ID); +} + +/// @brief This support function is used to unload a skeleton from Core. +void SDKClient::UnloadTestSkeleton() +{ + if (m_LoadedSkeletons.size() == 0) + { + ClientLog::error("There was no skeleton for us to unload."); + return; + } + SDKReturnCode t_Res = CoreSdk_UnloadSkeleton(m_LoadedSkeletons[0]); + m_LoadedSkeletons.erase(m_LoadedSkeletons.begin()); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to unload skeleton. The error given was {}.", (int32_t)t_Res); + + return; + } +} + +/// @brief +/// Sends the loaded skeleton to the Core SDK. +/// This function saves the temporary skeleton with the given session ID and returns an error if the operation fails. +void SDKClient::SendLoadedSkeleton(uint32_t p_SklIndex) +{ + // save the temporary skeleton + SDKReturnCode t_Res = CoreSdk_SaveTemporarySkeleton(p_SklIndex, m_SessionId, true); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to save temporary skeleton. The error given was {}.", (int32_t)t_Res); + } +} + + +/// @brief This support function sets up an incomplete hand skeleton and then uses manus core to allocate chains for it. +void SDKClient::AllocateChains() +{ + m_ChainType = ChainType::ChainType_Invalid; + + uint32_t t_SklIndex = 0; + + SkeletonSettings t_Settings; + SkeletonSettings_Init(&t_Settings); + t_Settings.scaleToTarget = true; + t_Settings.targetType = SkeletonTargetType::SkeletonTargetType_UserData; + t_Settings.skeletonTargetUserData.userID = 0; + + SkeletonSetupInfo t_SKL; + SkeletonSetupInfo_Init(&t_SKL); + t_SKL.id = 0; + t_SKL.type = SkeletonType::SkeletonType_Hand; + t_SKL.settings = t_Settings; + CopyString(t_SKL.name, sizeof(t_SKL.name), std::string("hand")); + + SDKReturnCode t_Res = CoreSdk_CreateSkeletonSetup(t_SKL, &t_SklIndex); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Create Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + m_TemporarySkeletons.push_back(t_SklIndex); + + // setup nodes for the skeleton hand + SetupHandNodes(t_SklIndex, Side::Side_Left); + + // allocate chains for skeleton + t_Res = CoreSdk_AllocateChainsForSkeletonSetup(t_SklIndex); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to allocate chains for skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + + // get the skeleton info + SkeletonSetupArraySizes t_SkeletonInfo; + t_Res = CoreSdk_GetSkeletonSetupArraySizes(t_SklIndex, &t_SkeletonInfo); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get info about skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + + ChainSetup* t_Chains = new ChainSetup[t_SkeletonInfo.chainsCount]; + // now get the chain data + t_Res = CoreSdk_GetSkeletonSetupChainsArray(t_SklIndex, t_Chains, t_SkeletonInfo.chainsCount); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get skeleton setup chains. The error given was {}.", (int32_t)t_Res); + delete[] t_Chains; + return; + } + // as proof store the first chain type + m_ChainType = t_Chains[0].dataType; + + // but since we want to cleanly load the skeleton without holding everything up + // we need to set its side first + for (size_t i = 0; i < t_SkeletonInfo.chainsCount; i++) + { + if (t_Chains[i].dataType == ChainType::ChainType_Hand) + { + t_Chains[i].side = Side::Side_Left; // we're just picking a side here. + + t_Res = CoreSdk_OverwriteChainToSkeletonSetup(t_SklIndex, t_Chains[i]); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to overwrite Chain To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + delete[] t_Chains; + return; + } + break; // no need to continue checking the others. + } + } + // cleanup + delete[] t_Chains; + + // load skeleton so it is done. + uint32_t t_ID = 0; + t_Res = CoreSdk_LoadSkeleton(t_SklIndex, &t_ID); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to load skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + RemoveIndexFromTemporarySkeletonList(t_SklIndex); + + if (t_ID == 0) + { + ClientLog::error("Failed to give skeleton an ID."); + } + m_LoadedSkeletons.push_back(t_ID); +} + +/// @brief This support function is used for the manual allocation of the skeleton chains with means of a temporary skeleton. +/// Temporary Skeletons can be helpful when the user wants to modify the skeletons chains or nodes more than once before retargeting, +/// as they can be saved in core and retrieved later by the user to apply further modifications. This can be done easily with means of the Dev Tools. +/// The current function contains an example that shows how to create a temporary skeleton, modify its chains, nodes and +/// skeleton info, and save it into Core. This process should be used during development. +/// After that, the final skeleton should be loaded into core for retargeting and for getting the actual data,as displayed in the LoadTestSkeleton +/// function. +void SDKClient::BuildTemporarySkeleton() +{ + // define the session Id for which we want to save + // in this example we want to save a skeleton for the current session so we use our own Session Id + uint32_t t_SessionId = m_SessionId; + + bool t_IsSkeletonModified = false; // this bool is set to true by the Dev Tools after saving any modification to the skeleton, + // this triggers the OnSyStemCallback which is used in the SDK to be notified about a change to its temporary skeletons. + // for the purpose of this example setting this bool to true is not really necessary. + + // first create a skeleton setup of type Body + uint32_t t_SklIndex = 0; + + SkeletonSettings t_Settings; + SkeletonSettings_Init(&t_Settings); + t_Settings.scaleToTarget = true; + t_Settings.targetType = SkeletonTargetType::SkeletonTargetType_UserData; + t_Settings.skeletonTargetUserData.userID = 0; // this needs to be a real user Id when retargeting, when editing the temporary skeleton this may (hopefully) not cause issues + + SkeletonSetupInfo t_SKL; + SkeletonSetupInfo_Init(&t_SKL); + t_SKL.id = 0; + t_SKL.type = SkeletonType::SkeletonType_Body; + t_SKL.settings = t_Settings; + CopyString(t_SKL.name, sizeof(t_SKL.name), std::string("body")); + + SDKReturnCode t_Res = CoreSdk_CreateSkeletonSetup(t_SKL, &t_SklIndex); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Create Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + m_TemporarySkeletons.push_back(t_SklIndex); + //Add 3 nodes to the skeleton setup + t_Res = CoreSdk_AddNodeToSkeletonSetup(t_SklIndex, CreateNodeSetup(0, 0, 0, 0, 0, "root")); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Node To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + + t_Res = CoreSdk_AddNodeToSkeletonSetup(t_SklIndex, CreateNodeSetup(1, 0, 0, 1, 0, "branch")); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Node To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + + t_Res = CoreSdk_AddNodeToSkeletonSetup(t_SklIndex, CreateNodeSetup(2, 1, 0, 2, 0, "leaf")); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Node To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + + //Add one chain of type Leg to the skeleton setup + ChainSettings t_ChainSettings; + ChainSettings_Init(&t_ChainSettings); + t_ChainSettings.usedSettings = ChainType::ChainType_Leg; + t_ChainSettings.leg.footForwardOffset = 0; + t_ChainSettings.leg.footSideOffset = 0; + t_ChainSettings.leg.reverseKneeDirection = false; + t_ChainSettings.leg.kneeRotationOffset = 0; + + ChainSetup t_Chain; + ChainSetup_Init(&t_Chain); + t_Chain.id = 0; + t_Chain.type = ChainType::ChainType_Leg; + t_Chain.dataType = ChainType::ChainType_Leg; + t_Chain.dataIndex = 0; + t_Chain.nodeIdCount = 3; + t_Chain.nodeIds[0] = 0; + t_Chain.nodeIds[1] = 1; + t_Chain.nodeIds[2] = 2; + t_Chain.settings = t_ChainSettings; + t_Chain.side = Side::Side_Left; + + t_Res = CoreSdk_AddChainToSkeletonSetup(t_SklIndex, t_Chain); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Chain To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + + // save the temporary skeleton + t_Res = CoreSdk_SaveTemporarySkeleton(t_SklIndex, t_SessionId, t_IsSkeletonModified); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to save temporary skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + + // if we want to go on with the modifications to the same temporary skeleton + // get the skeleton + t_Res = CoreSdk_GetTemporarySkeleton(t_SklIndex, t_SessionId); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get temporary skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + + // now add second chain to the same temporary skeleton + t_ChainSettings.usedSettings = ChainType::ChainType_Head; + + t_Chain.id = 1; + t_Chain.type = ChainType::ChainType_Head; + t_Chain.dataType = ChainType::ChainType_Head; + t_Chain.dataIndex = 0; + t_Chain.nodeIdCount = 1; + t_Chain.nodeIds[0] = 0; + t_Chain.settings = t_ChainSettings; + t_Chain.side = Side::Side_Center; + + t_Res = CoreSdk_AddChainToSkeletonSetup(t_SklIndex, t_Chain); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Chain To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + + // save the temporary skeleton + t_Res = CoreSdk_SaveTemporarySkeleton(t_SklIndex, t_SessionId, t_IsSkeletonModified); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to save temporary skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + + // get the skeleton info (number of nodes and chains for that skeleton) + SkeletonSetupArraySizes t_SkeletonInfo; + t_Res = CoreSdk_GetSkeletonSetupArraySizes(t_SklIndex, &t_SkeletonInfo); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get info about skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + + // now get the chain data + ChainSetup* t_Chains = new ChainSetup[t_SkeletonInfo.chainsCount]; + t_Res = CoreSdk_GetSkeletonSetupChainsArray(t_SklIndex, t_Chains, t_SkeletonInfo.chainsCount); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get skeleton setup chains. The error given was {}.", (int32_t)t_Res); + return; + } + + // get the node data + NodeSetup* t_Nodes = new NodeSetup[t_SkeletonInfo.nodesCount]; + t_Res = CoreSdk_GetSkeletonSetupNodesArray(t_SklIndex, t_Nodes, t_SkeletonInfo.nodesCount); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get skeleton setup nodes. The error given was {}.", (int32_t)t_Res); + return; + } + + // just as an example try to get the skeleton setup info + SkeletonSetupInfo t_SKeletonSetupInfo; + SkeletonSetupInfo_Init(&t_SKeletonSetupInfo); + t_Res = CoreSdk_GetSkeletonSetupInfo(t_SklIndex, &t_SKeletonSetupInfo); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to overwrite Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + + // if we want to modify the skeleton setup or if we want to apply some changes to the chains or nodes: + // first overwrite the existing skeleton setup and then re-add all the chains and nodes to it + SkeletonSettings_Init(&t_Settings); + t_Settings.targetType = SkeletonTargetType::SkeletonTargetType_GloveData; + + t_SKL.settings = t_Settings; + CopyString(t_SKL.name, sizeof(t_SKL.name), std::string("body2")); + + // this way we overwrite the temporary skeleton with index t_SklIndex with the modified skeleton setup + t_Res = CoreSdk_OverwriteSkeletonSetup(t_SklIndex, t_SKL); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to overwrite Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + + // modify chains and nodes + t_Chains[0].side = Side::Side_Right; + t_Nodes[0].type = NodeType::NodeType_Mesh; + + // add all the existing nodes to the new skeleton setup + for (size_t i = 0; i < t_SkeletonInfo.nodesCount; i++) + { + t_Res = CoreSdk_AddNodeToSkeletonSetup(t_SklIndex, t_Nodes[i]); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Node To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + } + + // then add all the existing chains to the new skeleton setup + for (size_t i = 0; i < t_SkeletonInfo.chainsCount; i++) + { + t_Res = CoreSdk_AddChainToSkeletonSetup(t_SklIndex, t_Chains[i]); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Add Chains To Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + } + + // cleanup + delete[] t_Chains; + delete[] t_Nodes; + + // save temporary skeleton + // in the Dev Tools this bool is set to true when saving the temporary skeleton, this triggers OnSystemCallback which + // notifies the SDK sessions about a modifications to one of their temporary skeletons. + // setting the bool to true in this example is not really necessary, it's just for testing purposes. + t_IsSkeletonModified = true; + t_Res = CoreSdk_SaveTemporarySkeleton(t_SklIndex, t_SessionId, t_IsSkeletonModified); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to save temporary skeleton. The error given was {}.", (int32_t)t_Res); + return; + } +} + +/// @brief This support function is used to clear a temporary skeleton from the temporary skeleton list, for example it can be used when the +/// max number of temporary skeletons has been reached for a specific session. +void SDKClient::ClearTemporarySkeleton() +{ + // clear the first element of the temporary skeleton list + if (m_TemporarySkeletons.size() == 0) + { + ClientLog::error("There are no Temporary Skeletons to clear!"); + return; + } + uint32_t t_SklIndex = m_TemporarySkeletons[0]; + SDKReturnCode t_Res = CoreSdk_ClearTemporarySkeleton(t_SklIndex, m_SessionId); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Clear Temporary Skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + m_TemporarySkeletons.erase(m_TemporarySkeletons.begin()); +} + +/// @brief This support function is used to clear all temporary skeletons associated to the current SDK session, it can be used when the +/// max number of temporary skeletons has been reached for the current session and we want to make room for more. +void SDKClient::ClearAllTemporarySkeletons() +{ + if (m_TemporarySkeletons.size() == 0) + { + ClientLog::error("There are no Temporary Skeletons to clear!"); + return; + } + SDKReturnCode t_Res = CoreSdk_ClearAllTemporarySkeletons(); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Clear All Temporary Skeletons. The error given was {}.", (int32_t)t_Res); + return; + } + m_TemporarySkeletons.clear(); +} + +void SDKClient::SaveTemporarySkeletonToFile() +{ + // this example shows how to save a temporary skeleton to a file + // first create a temporary skeleton: + + // define the session Id for which we want to save + uint32_t t_SessionId = m_SessionId; + + bool t_IsSkeletonModified = false; // setting this bool to true is not necessary here, it is mostly used by the Dev Tools + // to notify the SDK sessions about their skeleton being modified. + + // first create a skeleton setup + uint32_t t_SklIndex = 0; + + SkeletonSetupInfo t_SKL; + SkeletonSetupInfo_Init(&t_SKL); + t_SKL.type = SkeletonType::SkeletonType_Hand; + t_SKL.settings.scaleToTarget = true; + t_SKL.settings.targetType = SkeletonTargetType::SkeletonTargetType_GloveData; + t_SKL.settings.skeletonTargetUserIndexData.userIndex = 0; + + CopyString(t_SKL.name, sizeof(t_SKL.name), std::string("LeftHand")); + + SDKReturnCode t_Res = CoreSdk_CreateSkeletonSetup(t_SKL, &t_SklIndex); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Create Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + m_TemporarySkeletons.push_back(t_SklIndex); + + // setup nodes and chains for the skeleton hand + if (!SetupHandNodes(t_SklIndex, Side_Left)) return; + if (!SetupHandChains(t_SklIndex, Side_Left)) return; + + // save the temporary skeleton + t_Res = CoreSdk_SaveTemporarySkeleton(t_SklIndex, t_SessionId, t_IsSkeletonModified); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to save temporary skeleton. The error given was {}.", (int32_t)t_Res); + return; + } + + // now compress the temporary skeleton data and get the size of the compressed data: + uint32_t t_TemporarySkeletonLengthInBytes; + + t_Res = CoreSdk_CompressTemporarySkeletonAndGetSize(t_SklIndex, t_SessionId, &t_TemporarySkeletonLengthInBytes); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to compress temporary skeleton and get size. The error given was {}.", (int32_t)t_Res); + return; + } + unsigned char* t_TemporarySkeletonData = new unsigned char[t_TemporarySkeletonLengthInBytes]; + + // get the array of bytes with the compressed temporary skeleton data, remember to always call function CoreSdk_CompressTemporarySkeletonAndGetSize + // before trying to get the compressed temporary skeleton data + t_Res = CoreSdk_GetCompressedTemporarySkeletonData(t_TemporarySkeletonData, t_TemporarySkeletonLengthInBytes); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to get compressed temporary skeleton data. The error given was {}.", (int32_t)t_Res); + return; + } + + // now save the data into a .mskl file + // as an example we save the temporary skeleton in a folder called ManusTemporarySkeleton inside the documents directory + // get the path for the documents directory + std::string t_DirectoryPathString = GetDocumentsDirectoryPath_UTF8(); + + // create directory name and file name for storing the temporary skeleton + std::string t_DirectoryPath = + t_DirectoryPathString + + s_SlashForFilesystemPath + + "ManusTemporarySkeleton"; + + CreateFolderIfItDoesNotExist(t_DirectoryPath); + + std::string t_DirectoryPathAndFileName = + t_DirectoryPath + + s_SlashForFilesystemPath + + "TemporarySkeleton.mskl"; + + // write the temporary skeleton data to .mskl file + std::ofstream t_File = GetOutputFileStream(t_DirectoryPathAndFileName); + t_File.write((char*)t_TemporarySkeletonData, t_TemporarySkeletonLengthInBytes); + t_File.close(); + + t_Res = CoreSdk_ClearTemporarySkeleton(t_SklIndex, t_SessionId); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Clear Temporary Skeleton after saving. The error given was {}.", (int32_t)t_Res); + return; + } + RemoveIndexFromTemporarySkeletonList(t_SklIndex); +} + + +void SDKClient::GetTemporarySkeletonFromFile() +{ + // this example shows how to load a temporary skeleton data from a file + + // as an example we try to get the temporary skeleton data previously saved as .mskl file in directory Documents/ManusTemporarySkeleton + // get the path for the documents directory + std::string t_DirectoryPathString = GetDocumentsDirectoryPath_UTF8(); + + // check if directory exists + std::string t_DirectoryPath = + t_DirectoryPathString + + s_SlashForFilesystemPath + + "ManusTemporarySkeleton"; + + if (!DoesFolderOrFileExist(t_DirectoryPath)) + { + ClientLog::warn("Failed to read from client file, the mentioned directory does not exist"); + return; + } + + // create string with file name + std::string t_DirectoryPathAndFileName = + t_DirectoryPath + + s_SlashForFilesystemPath + + "TemporarySkeleton.mskl"; + + // read from file + std::ifstream t_File = GetInputFileStream(t_DirectoryPathAndFileName); + + if (!t_File) + { + ClientLog::warn("Failed to read from client file, the file does not exist in the mentioned directory"); + return; + } + + // get file dimension + t_File.seekg(0, t_File.end); + int t_FileLength = (int)t_File.tellg(); + t_File.seekg(0, t_File.beg); + + // get temporary skeleton data from file + unsigned char* t_TemporarySkeletonData = new unsigned char[t_FileLength]; + t_File.read((char*)t_TemporarySkeletonData, t_FileLength); + t_File.close(); + + + // save the zipped temporary skeleton information, they will be used internally for sending the data to Core + uint32_t t_TemporarySkeletonLengthInBytes = t_FileLength; + + if (t_TemporarySkeletonData == nullptr) + { + ClientLog::warn("Failed to read the compressed temporary skeleton data from file"); + delete[] t_TemporarySkeletonData; + return; + } + + // create a skeleton setup where we will store the temporary skeleton retrieved from file + SkeletonSetupInfo t_SKL; + SkeletonSetupInfo_Init(&t_SKL); + uint32_t t_SklIndex = 0; + SDKReturnCode t_Res = CoreSdk_CreateSkeletonSetup(t_SKL, &t_SklIndex); + if (t_Res != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to Create Skeleton Setup. The error given was {}.", (int32_t)t_Res); + return; + } + m_TemporarySkeletons.push_back(t_SklIndex); + + // associate the retrieved temporary skeleton to the current session id + uint32_t t_SessionId = m_SessionId; + + // load the temporary skeleton data retrieved from the zipped file and save it with index t_SklIndex and session id of the current session + SDKReturnCode t_Result = CoreSdk_GetTemporarySkeletonFromCompressedData(t_SklIndex, t_SessionId, t_TemporarySkeletonData, t_TemporarySkeletonLengthInBytes); + if (t_Result != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::warn("Failed to load temporary skeleton data from client file in Core, the error code was: {}.", (int32_t)t_Result); + return; + } + + delete[] t_TemporarySkeletonData; +} + +void SDKClient::TestTimestamp() +{ + ManusTimestamp t_TS; + ManusTimestamp_Init(&t_TS); + ManusTimestampInfo t_TSInfo; + ManusTimestampInfo_Init(&t_TSInfo); + t_TSInfo.fraction = 30; + t_TSInfo.second = 15; + t_TSInfo.minute = 30; + t_TSInfo.hour = 12; + t_TSInfo.day = 1; + t_TSInfo.month = 8; + t_TSInfo.year = 2012; + t_TSInfo.timecode = true; + + CoreSdk_SetTimestampInfo(&t_TS, t_TSInfo); + + ManusTimestampInfo t_TSInfo2; + CoreSdk_GetTimestampInfo(t_TS, &t_TSInfo2); +} + +void SDKClient::RemoveIndexFromTemporarySkeletonList(uint32_t p_Idx) +{ + for (int i = 0; i < m_TemporarySkeletons.size(); i++) + { + if (m_TemporarySkeletons[i] == p_Idx) + { + m_TemporarySkeletons.erase(m_TemporarySkeletons.begin() + i); + } + } +} + +void SDKClient::PairGlove() +{ + bool t_GloveFound = false; + uint32_t t_GloveToPairId = -1; + + for (size_t i = 0; i < m_Landscape->gloveDevices.gloveCount; i++) + { + if (m_Landscape->gloveDevices.gloves[i].pairedState == DevicePairedState_Unpaired) + { + t_GloveToPairId = m_Landscape->gloveDevices.gloves[i].id; + t_GloveFound = true; + break; + } + } + + if (!t_GloveFound) + { + ClientLog::warn("No glove available for pairing found."); + return; + } + + bool t_Paired; + SDKReturnCode t_PairGloveResult = CoreSdk_PairGlove(t_GloveToPairId, &t_Paired); + if (t_PairGloveResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to pair glove with ID: {}. The error given was {}", t_GloveToPairId, (int32_t)t_PairGloveResult); + return; + } + + if (!t_Paired) + { + ClientLog::error("Failed to pair glove with ID: {}", t_GloveToPairId); + return; + } + + ClientLog::print("Succesfully paired glove with ID: {}", t_GloveToPairId); + + return; +} + +void SDKClient::UnpairGlove() +{ + bool t_GloveFound = false; + uint32_t t_GloveToUnPairId = -1; + + for (size_t i = 0; i < m_Landscape->gloveDevices.gloveCount; i++) + { + if (m_Landscape->gloveDevices.gloves[i].id == m_Landscape->gloveDevices.gloves[i].dongleID) + continue; + + if (m_Landscape->gloveDevices.gloves[i].pairedState == DevicePairedState_Paired) + { + t_GloveToUnPairId = m_Landscape->gloveDevices.gloves[i].id; + t_GloveFound = true; + break; + } + } + + if (!t_GloveFound) + { + ClientLog::error("No glove to unpair found"); + return; + } + + bool t_Unpaired; + SDKReturnCode t_UnpairGloveResult = CoreSdk_UnpairGlove(t_GloveToUnPairId, &t_Unpaired); + if (t_UnpairGloveResult != SDKReturnCode::SDKReturnCode_Success) + { + ClientLog::error("Failed to unpair glove with ID: {}. The error given was ", t_GloveToUnPairId, (int32_t)t_UnpairGloveResult); + return; + } + + ClientLog::print("Succesfully unpaired glove with ID: {}", t_GloveToUnPairId); + return; +} +/// @brief Prints the type of the first chain generated by the AllocateChain function, this is used for testing. +void SDKClient::PrintLogs() +{ + std::vector t_SDKLogs; + s_Instance->m_LogMutex.lock(); + t_SDKLogs.swap(s_Instance->m_Logs); + s_Instance->m_LogMutex.unlock(); + + for (size_t i = 0; i < t_SDKLogs.size(); i++) + { + ClientLog::print(t_SDKLogs[i]->string.c_str()); + delete t_SDKLogs[i]; + } +} diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient.hpp b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient.hpp new file mode 100644 index 0000000000000000000000000000000000000000..edbdc1b71fabf69b44b39e022409a5d675227ac7 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient.hpp @@ -0,0 +1,349 @@ +#ifndef _SDK_CLIENT_HPP_ +#define _SDK_CLIENT_HPP_ + +// Set up a Doxygen group. +/** @addtogroup SDKClient + * @{ + */ + +#include // Used for haptic commands. +#include // Used for rounding float values. +#include // Used for printing glove data, and converting glove IDs to strings. +#include // Used for smart pointers. +#include +#include +#include +#include +#include + +#include "ClientPlatformSpecific.hpp" +#include "ManusSDK.h" + +extern std::map> output_map; + + +/// @brief Constant expression: number of hands supported by demo. +constexpr unsigned int NUMBER_OF_HANDS_SUPPORTED = 2; + +/// @brief Constant expression used to define the time between two possible haptics commands sent +constexpr unsigned long long int MINIMUM_MILLISECONDS_BETWEEN_HAPTICS_COMMANDS = 20; + +/// @brief Constant expression used to define the time between two updates of the temporary skeleton count printing +constexpr unsigned long long int MILLISECONDS_BETWEEN_TEMPORARY_SKELETONS_UPDATE = 1000; + +/// @brief The type of connection to core. +enum class ConnectionType : int +{ + ConnectionType_Invalid = 0, + ConnectionType_Integrated, + ConnectionType_Local, + ConnectionType_Remote, + ClientState_MAX_CLIENT_STATE_SIZE +}; + +/// @brief The current state of the client. +enum class ClientState : int +{ + ClientState_Starting = 0, + ClientState_LookingForHosts, + ClientState_NoHostsFound, + ClientState_PickingHost, + ClientState_ConnectingToCore, + ClientState_DisplayingData, + ClientState_Disconnected, + + ClientState_MAX_CLIENT_STATE_SIZE +}; + +/// @brief Values that can be returned by this application. +enum class ClientReturnCode : int +{ + ClientReturnCode_Success = 0, + ClientReturnCode_FailedPlatformSpecificInitialization, + ClientReturnCode_FailedToResizeWindow, + ClientReturnCode_FailedToInitialize, + ClientReturnCode_FailedToFindHosts, + ClientReturnCode_FailedToConnect, + ClientReturnCode_UnrecognizedStateEncountered, + ClientReturnCode_FailedToShutDownSDK, + ClientReturnCode_FailedPlatformSpecificShutdown, + ClientReturnCode_FailedToRestart, + ClientReturnCode_FailedWrongTimeToGetData, + + ClientReturnCode_MAX_CLIENT_RETURN_CODE_SIZE +}; + +struct SDKLog +{ + LogSeverity severity; + std::string string; +}; + +/// @brief Haptic settings for a single glove. +/// +/// This is used to store if a specific motor on the glove should be enabled or not. +struct ClientHapticSettings +{ + bool shouldHapticFinger[NUM_FINGERS_ON_HAND]; +}; + +/// @brief Used to store the information about the final animated skeletons. +class ClientSkeleton +{ +public: + SkeletonInfo info; + std::vector nodes; +}; + +/// @brief Used to store all the final animated skeletons received from Core. +class ClientSkeletonCollection +{ +public: + std::vector skeletons; +}; + +/// @brief Used to store the information about the skeleton data coming from the estimation system in Core. +class ClientRawSkeleton +{ +public: + RawSkeletonInfo info; + std::vector nodes; +}; + +/// @brief Used to store all the skeleton data coming from the estimation system in Core. +class ClientRawSkeletonCollection +{ +public: + std::vector skeletons; +}; + +/// @brief Used to store all the tracker data coming from Core. +class TrackerDataCollection +{ +public: + std::vector trackerData; +}; + +/// @brief Used to store the information about the final animated skeletons. +class ClientGestures +{ +public: + GestureProbabilities info; + std::vector probabilities; +}; + +class SDKClient : public SDKClientPlatformSpecific +{ +public: + SDKClient(); + ~SDKClient(); + + ClientReturnCode Initialize(); + ClientReturnCode Run(); + ClientReturnCode ShutDown(); + + //Callbacks + static void OnConnectedCallback(const ManusHost* const p_Host); + static void OnDisconnectedCallback(const ManusHost* const p_Host); + static void OnLogCallback(LogSeverity p_Severity, const char* const p_Log, uint32_t p_Length); + static void OnSkeletonStreamCallback(const SkeletonStreamInfo* const p_Skeleton); + static void OnLandscapeCallback(const Landscape* const p_Landscape); + static void OnSystemCallback(const SystemMessage* const p_SystemMessage); + static void OnErgonomicsCallback(const ErgonomicsStream* const p_Ergo); + static void OnRawSkeletonStreamCallback(const SkeletonStreamInfo* const p_RawSkeletonStreamInfo); + static void OnTrackerStreamCallback(const TrackerStreamInfo* const p_TrackerStreamInfo); + static void OnGestureStreamCallback(const GestureStreamInfo* const p_GestureStream); + + float RoundFloatValue(float p_Value, int p_NumDecimalsToKeep); + void AdvanceConsolePosition(short int p_Y); + +protected: + virtual ClientReturnCode InitializeSDK(); + virtual ClientReturnCode RestartSDK(); + virtual ClientReturnCode RegisterAllCallbacks(); + + virtual ClientReturnCode LookingForHosts(); + virtual ClientReturnCode NoHostsFound(); + virtual ClientReturnCode PickingHost(); + virtual ClientReturnCode ConnectingToCore(); + + virtual ClientReturnCode UpdateBeforeDisplayingData(); + + virtual ClientReturnCode DisplayingData(); + virtual ClientReturnCode DisplayingDataGlove(); + virtual ClientReturnCode DisplayingDataSkeleton(); + virtual ClientReturnCode DisplayingDataTracker(); + virtual ClientReturnCode DisplayingDataTemporarySkeleton(); + virtual ClientReturnCode DisplayingLandscapeTimeData(); + virtual ClientReturnCode DisplayingDataGestures(); + virtual ClientReturnCode DisplayingGloveCalibration(); + virtual ClientReturnCode DisplayingPairing(); + + virtual ClientReturnCode DisconnectedFromCore(); + virtual ClientReturnCode ReconnectingToCore(int32_t p_ReconnectionTime = 0, int32_t p_ReconnectionAttempts = 0); + + void PrintHandErgoData(ErgonomicsData& p_ErgoData, bool p_Left); + void PrintErgonomicsData(); + void PrintDongleData(); + void PrintSystemMessage(); + void PrintSkeletonData(); + void PrintRawSkeletonData(); + + + void PrintTrackerData(); + void PrintTrackerDataGlobal(); + void PrintTrackerDataPerUser(); + + void PrintLandscapeTimeData(); + + void PrintGestureData(); + void PrintGloveCalibrationData(); + + void PrintSkeletonInfo(); + void PrintTemporarySkeletonInfo(); + void HandlePairingCommands(); + void GetTemporarySkeletonIfModified(); + + void HandleHapticCommands(); + + void HandleSkeletonCommands(); + void HandleSkeletonHapticCommands(); + void HandleTemporarySkeletonCommands(); + void HandleTrackerCommands(); + void SetTrackerOffset(); + void HandleGesturesCommands(); + void HandleGloveCalibrationCommands(); + + static NodeSetup CreateNodeSetup(uint32_t p_Id, uint32_t p_ParentId, float p_PosX, float p_PosY, float p_PosZ, std::string p_Name); + bool SetupHandNodes(uint32_t p_SklIndex, Side p_Side); + bool SetupHandChains(uint32_t p_SklIndex, Side p_Side); + + void LoadTestSkeleton(Side p_Side); + void UnloadTestSkeleton(); + void SendLoadedSkeleton(uint32_t p_SklIndex); + + void AllocateChains(); + + void BuildTemporarySkeleton(); + void ClearTemporarySkeleton(); + void ClearAllTemporarySkeletons(); + void SaveTemporarySkeletonToFile(); + void GetTemporarySkeletonFromFile(); + + void TestTimestamp(); + + void RemoveIndexFromTemporarySkeletonList(uint32_t p_Idx); + void PairGlove(); + void UnpairGlove(); + static ManusVec3 CreateManusVec3(float p_X, float p_Y, float p_Z); + + void ExecuteGloveCalibrationStep(GloveCalibrationStepArgs p_Args); + + void PrintLogs(); + +protected: + static SDKClient* s_Instance; + + bool m_RequestedExit = false; + ConnectionType m_ConnectionType = ConnectionType::ConnectionType_Invalid; + + //Console + uint32_t m_ConsoleClearTickCount = 0; + const short int m_ConsoleWidth = 220; + const short int m_ConsoleHeight = 55; + const short int m_ConsoleScrollback = 500; + int m_ConsoleCurrentOffset = 0; + + SessionType m_ClientType = SessionType::SessionType_CoreSDK; + + ClientState m_State = ClientState::ClientState_Starting; + ClientState m_PreviousState = m_State; + + std::function m_CurrentInteraction = nullptr; + + uint32_t m_HostToConnectTo = 0; + uint32_t m_NumberOfHostsFound = 0; + uint32_t m_SecondsToFindHosts = 2; + + int32_t m_SecondsToAttemptReconnecting = 60; + int32_t m_MaxReconnectionAttempts = 10; + uint32_t m_SleepBetweenReconnectingAttemptsInMs = 100; + + std::unique_ptr m_AvailableHosts = nullptr; + std::unique_ptr m_Host; + + //Data + uint32_t m_SessionId = 0; + + bool m_RumblingWrist[NUMBER_OF_HANDS_SUPPORTED] = { false, false }; + + std::vector m_LoadedSkeletons; + std::vector m_TemporarySkeletons; + + std::mutex m_SkeletonMutex; + std::mutex m_RawSkeletonMutex; + + ClientSkeletonCollection* m_NextSkeleton = nullptr; + ClientSkeletonCollection* m_Skeleton = nullptr; + + ClientRawSkeletonCollection* m_NextRawSkeleton = nullptr; + ClientRawSkeletonCollection* m_RawSkeleton = nullptr; + + std::mutex m_TrackerMutex; + + TrackerDataCollection* m_NextTrackerData = nullptr; + TrackerDataCollection* m_TrackerData = nullptr; + + std::chrono::time_point m_TimeSinceLastDisconnect; + std::chrono::time_point m_LastTemporarySkeletonUpdate = std::chrono::high_resolution_clock::now(); + + std::mutex m_SystemMessageMutex; + std::string m_SystemMessage = ""; + SystemMessageType m_SystemMessageCode = SystemMessageType::SystemMessageType_Unknown; + uint32_t m_ModifiedSkeletonIndex = UINT_MAX; + + ManusTimestampInfo m_ErgoTimestampInfo; + ErgonomicsData m_LeftGloveErgoData; + ErgonomicsData m_RightGloveErgoData; + + ChainType m_ChainType = ChainType::ChainType_Invalid; + + bool m_TrackerTest = false; + bool m_TrackerDataDisplayPerUser = false; + float m_TrackerOffset = 0.0f; + + std::mutex m_LandscapeMutex; + Landscape* m_NewLandscape = nullptr; + Landscape* m_Landscape = nullptr; + std::vector m_NewGestureLandscapeData; + std::vector m_GestureLandscapeData; + + uint32_t m_FirstLeftGloveID = 0; + uint32_t m_FirstRightGloveID = 0; + + std::mutex m_GestureMutex; + ClientGestures* m_NewFirstLeftGloveGestures = nullptr; + ClientGestures* m_FirstLeftGloveGestures = nullptr; + + ClientGestures* m_NewFirstRightGloveGestures = nullptr; + ClientGestures* m_FirstRightGloveGestures = nullptr; + + bool m_ShowLeftGestures = true; + + bool m_CalibrateLeftHand = true; + uint32_t m_CalibrationStep = 0; + uint32_t m_CalibrationGloveId = 0; + uint32_t m_NumberOfCalibrationSteps = 0; + bool m_ValidStepData = false; + GloveCalibrationStepData m_StepData; + bool m_IsCalibrationInProgress = false; + std::string m_CalibrationMessage = ""; + bool m_SendToDevTools = false; + + std::mutex m_LogMutex; + std::vector m_Logs; +}; + +// Close the Doxygen group. +/** @} */ +#endif diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient_Linux.vcxproj b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient_Linux.vcxproj new file mode 100644 index 0000000000000000000000000000000000000000..205c4d60398f615463a580ccdf979c0ac4ef3907 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient_Linux.vcxproj @@ -0,0 +1,249 @@ + + + + + Debug + ARM + + + Release + ARM + + + Debug + ARM64 + + + Release + ARM64 + + + Debug + x64 + + + Release + x64 + + + + + + + + + + + + + + + {DADD0545-4F93-41DE-B0B7-C28B8497D16B} + Linux + SDKClient_Linux + 15.0 + Linux + 1.0 + Generic + {D51BCBC9-82E9-4017-911E-C93873C4EA2B} + + + + true + Remote_Clang_1_0 + + + false + Remote_Clang_1_0 + + + true + Remote_GCC_1_0 + + + false + Remote_GCC_1_0 + + + false + Remote_Clang_1_0 + + + true + Remote_Clang_1_0 + + + + + + + + $(RemoteRootDir)/$(RemoteOutRelDir)/$(TargetName)$(TargetExt) + + + $(SolutionDir)Output\$(Platform)\$(Configuration)\ + $(SolutionDir)Temp\$(ProjectGuid)\$(Platform)\$(Configuration)\ + 8 + + + $(SolutionDir)Output\$(Platform)\$(Configuration)\ + $(SolutionDir)Temp\$(ProjectGuid)\$(Platform)\$(Configuration)\ + 8 + + + $(SolutionDir)Output\$(Platform)\$(Configuration)\ + $(SolutionDir)Temp\$(ProjectGuid)\$(Platform)\$(Configuration)\ + 8 + + + $(SolutionDir)Output\$(Platform)\$(Configuration)\ + $(SolutionDir)Temp\$(ProjectGuid)\$(Platform)\$(Configuration)\ + 8 + + + $(SolutionDir)Output\$(Platform)\$(Configuration)\ + $(SolutionDir)Temp\$(ProjectGuid)\$(Platform)\$(Configuration)\ + 8 + + + $(SolutionDir)Output\$(Platform)\$(Configuration)\ + $(SolutionDir)Temp\$(ProjectGuid)\$(Platform)\$(Configuration)\ + 8 + + + + ~/ManusSDK/include;%(AdditionalIncludeDirectories) + c++17 + + + ~/ManusSDK/lib/libManusSDK.so;%(AdditionalDependencies) + ncurses + -pthread + + + rem Copy SDK client base files + copy /Y "$(SolutionDir)SDKClient_Windows\Main.cpp" "$(ProjectDir)\Main.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.hpp" "$(ProjectDir)\SDKClient.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.cpp" "$(ProjectDir)\SDKClient.cpp" + + rem Copy platform specific files + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\ClientPlatformSpecific.hpp" "$(ProjectDir)\ClientPlatformSpecific.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecific.cpp" "$(ProjectDir)\ClientPlatformSpecific.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecificTypes.hpp" "$(ProjectDir)\ClientPlatformSpecificTypes.hpp" + + + + + ~/ManusSDK/include;%(AdditionalIncludeDirectories) + c++17 + + + ~/ManusSDK/lib/libManusSDK.so;%(AdditionalDependencies) + ncurses + -pthread + + + rem Copy SDK client base files + copy /Y "$(SolutionDir)SDKClient_Windows\Main.cpp" "$(ProjectDir)\Main.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.hpp" "$(ProjectDir)\SDKClient.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.cpp" "$(ProjectDir)\SDKClient.cpp" + + rem Copy platform specific files + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\ClientPlatformSpecific.hpp" "$(ProjectDir)\ClientPlatformSpecific.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecific.cpp" "$(ProjectDir)\ClientPlatformSpecific.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecificTypes.hpp" "$(ProjectDir)\ClientPlatformSpecificTypes.hpp" + + + + + ~/ManusSDK/include;%(AdditionalIncludeDirectories) + c++17 + + + ~/ManusSDK/lib/libManusSDK.so;%(AdditionalDependencies) + ncurses + -pthread + + + rem Copy SDK client base files + copy /Y "$(SolutionDir)SDKClient_Windows\Main.cpp" "$(ProjectDir)\Main.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.hpp" "$(ProjectDir)\SDKClient.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.cpp" "$(ProjectDir)\SDKClient.cpp" + + rem Copy platform specific files + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\ClientPlatformSpecific.hpp" "$(ProjectDir)\ClientPlatformSpecific.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecific.cpp" "$(ProjectDir)\ClientPlatformSpecific.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecificTypes.hpp" "$(ProjectDir)\ClientPlatformSpecificTypes.hpp" + + + + + ~/ManusSDK/include;%(AdditionalIncludeDirectories) + c++17 + + + ~/ManusSDK/lib/libManusSDK.so;%(AdditionalDependencies) + ncurses + -pthread + + + rem Copy SDK client base files + copy /Y "$(SolutionDir)SDKClient_Windows\Main.cpp" "$(ProjectDir)\Main.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.hpp" "$(ProjectDir)\SDKClient.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.cpp" "$(ProjectDir)\SDKClient.cpp" + + rem Copy platform specific files + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\ClientPlatformSpecific.hpp" "$(ProjectDir)\ClientPlatformSpecific.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecific.cpp" "$(ProjectDir)\ClientPlatformSpecific.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecificTypes.hpp" "$(ProjectDir)\ClientPlatformSpecificTypes.hpp" + + + + + ~/ManusSDK/include;%(AdditionalIncludeDirectories) + c++17 + FMT_HEADER_ONLY;DEBUG;_DEBUG;%(PreprocessorDefinitions) + + + ~/ManusSDK/lib/libManusSDK.so;%(AdditionalDependencies) + ncurses + -pthread + + + rem Copy SDK client base files + copy /Y "$(SolutionDir)SDKClient_Windows\Main.cpp" "$(ProjectDir)\Main.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.hpp" "$(ProjectDir)\SDKClient.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.cpp" "$(ProjectDir)\SDKClient.cpp" + + rem Copy platform specific files + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\ClientPlatformSpecific.hpp" "$(ProjectDir)\ClientPlatformSpecific.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecific.cpp" "$(ProjectDir)\ClientPlatformSpecific.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecificTypes.hpp" "$(ProjectDir)\ClientPlatformSpecificTypes.hpp" + + + + + ~/ManusSDK/include;%(AdditionalIncludeDirectories) + c++17 + FMT_HEADER_ONLY;NDEBUG;%(PreprocessorDefinitions) + + + ~/ManusSDK/lib/libManusSDK.so;%(AdditionalDependencies) + ncurses + -pthread + + + rem Copy SDK client base files + copy /Y "$(SolutionDir)SDKClient_Windows\Main.cpp" "$(ProjectDir)\Main.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.hpp" "$(ProjectDir)\SDKClient.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\SDKClient.cpp" "$(ProjectDir)\SDKClient.cpp" + + rem Copy platform specific files + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\ClientPlatformSpecific.hpp" "$(ProjectDir)\ClientPlatformSpecific.hpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecific.cpp" "$(ProjectDir)\ClientPlatformSpecific.cpp" + copy /Y "$(SolutionDir)SDKClient_Windows\PlatformSpecific\Linux\ClientPlatformSpecificTypes.hpp" "$(ProjectDir)\ClientPlatformSpecificTypes.hpp" + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient_Linux.vcxproj.filters b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient_Linux.vcxproj.filters new file mode 100644 index 0000000000000000000000000000000000000000..85be7913d58ad6b7490784ca97f974665a438157 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/SDKClient_Linux.vcxproj.filters @@ -0,0 +1,25 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + + + + + + Platform Specific + + + + + + + Platform Specific + + + Platform Specific + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/ClientPlatformSpecific.d b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/ClientPlatformSpecific.d new file mode 100644 index 0000000000000000000000000000000000000000..95cf4b37bc667849b88abf2b14efc11add5a8112 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/ClientPlatformSpecific.d @@ -0,0 +1,4 @@ +objects/ClientPlatformSpecific.o: ClientPlatformSpecific.cpp \ + ClientPlatformSpecific.hpp ClientPlatformSpecificTypes.hpp \ + ManusSDK/include/ManusSDK.h ManusSDK/include/ManusSDKTypes.h \ + ManusSDK/include/ManusSDKTypeInitializers.h ClientLogging.hpp diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/ClientPlatformSpecific.o b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/ClientPlatformSpecific.o new file mode 100644 index 0000000000000000000000000000000000000000..f15e6b3642bf7584c5800ea1c0a529cb0752a0e6 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/ClientPlatformSpecific.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e770aa6327cd78246c0fd084025e7824f3ffa13a76b1a183f927905179b7db02 +size 562984 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/Main.d b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/Main.d new file mode 100644 index 0000000000000000000000000000000000000000..4a8fe373044dc1795bdf739b59938eb9337e989b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/Main.d @@ -0,0 +1,124 @@ +objects/Main.o: Main.cpp ClientLogging.hpp SDKClient.hpp \ + ClientPlatformSpecific.hpp ClientPlatformSpecificTypes.hpp \ + ManusSDK/include/ManusSDK.h ManusSDK/include/ManusSDKTypes.h \ + ManusSDK/include/ManusSDKTypeInitializers.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/pybind11.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/class.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/common.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/Python.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/patchlevel.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pyconfig.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pymacconfig.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pyport.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/exports.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pymacro.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pymath.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pymem.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pymem.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/object.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/object.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/objimpl.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/objimpl.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/typeslots.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pyhash.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pydebug.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/bytearrayobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/bytearrayobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/bytesobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/bytesobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/unicodeobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/unicodeobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/longobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/longintrepr.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/boolobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/floatobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/complexobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/rangeobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/memoryobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/tupleobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/tupleobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/listobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/listobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/dictobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/dictobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/odictobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/enumobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/setobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/methodobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/methodobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/moduleobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/funcobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/classobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/fileobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/fileobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pycapsule.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/code.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/code.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pyframe.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/traceback.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/traceback.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/sliceobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cellobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/iterobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/initconfig.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/genobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pystate.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pystate.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/abstract.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/abstract.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/descrobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/genericaliasobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/warnings.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/weakrefobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/structseq.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/namespaceobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/picklebufobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pytime.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/codecs.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pyerrors.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pyerrors.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pythread.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/context.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/modsupport.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/compile.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/compile.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pythonrun.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pythonrun.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pylifecycle.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pylifecycle.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/ceval.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/ceval.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/sysmodule.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/sysmodule.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/osmodule.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/intrcheck.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/import.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/import.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/bltinmodule.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/eval.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pyctype.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pystrtod.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pystrcmp.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/fileutils.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/fileutils.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/pyfpe.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/tracemalloc.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/frameobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/cpython/frameobject.h \ + /home/gear/miniconda3/envs/decoupled_wbc/include/python3.10/pythread.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/descr.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/type_caster_base.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/pytypes.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/cpp_conduit.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/internals.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/typeid.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/value_and_holder.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/options.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/exception_translation.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/detail/init.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/gil.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/gil_safe_call_once.h \ + /home/gear/miniconda3/envs/decoupled_wbc/lib/python3.10/site-packages/pybind11/include/pybind11/typing.h diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/Main.o b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/Main.o new file mode 100644 index 0000000000000000000000000000000000000000..46a0add3bd2826b10d4b0d1256df204ee1aaca66 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/Main.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8f44a3df601dbb2e65d517c903677d028f6c8e17778703f38dcc17b4696e3f6 +size 3823648 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/SDKClient.d b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/SDKClient.d new file mode 100644 index 0000000000000000000000000000000000000000..281f1309c4eccaa24178df434cbdc1c31285fce6 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/SDKClient.d @@ -0,0 +1,5 @@ +objects/SDKClient.o: SDKClient.cpp SDKClient.hpp \ + ClientPlatformSpecific.hpp ClientPlatformSpecificTypes.hpp \ + ManusSDK/include/ManusSDK.h ManusSDK/include/ManusSDKTypes.h \ + ManusSDK/include/ManusSDKTypeInitializers.h \ + ManusSDK/include/ManusSDKTypes.h ClientLogging.hpp diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/SDKClient.o b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/SDKClient.o new file mode 100644 index 0000000000000000000000000000000000000000..6e05d937d0cade217991ec2890b327f47b22c1b9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/objects/SDKClient.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0cbc7585f9762dfe77ff4ef4a78ad2cf8df9f5b5103b197f4bb2cab2152c59a8 +size 1904960 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/test.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/test.py new file mode 100644 index 0000000000000000000000000000000000000000..6483c1dcaa715d8b49f3ece87b9f36240dd0fda5 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/SDKClient_Linux/test.py @@ -0,0 +1,14 @@ +import time + +import ManusServer + +ManusServer.init() + +for i in range(10): + time.sleep(1) + output = ManusServer.get_latest_state() + # print(output.keys()) + # if(output['3762867141_angle']!=[] and output['3822396207_angle']!=[]): + # print(output['3762867141_angle']) + +ManusServer.shutdown() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/iphone/iphone.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/iphone/iphone.py new file mode 100644 index 0000000000000000000000000000000000000000..1606e2d5307db4dd96636b8f08a6d9353ba9e16e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/iphone/iphone.py @@ -0,0 +1,102 @@ +import json +import threading + +from flask import Flask +import socketio + + +class IPhoneDevice: + """ + Returns the absolute pose of the iPhone device relative to the world frame. + The coordinate system is defined when ARKit is initialized. + + Absolute pose coordinate system (at ARKit start): + + y (out of screen) + ⊙---> x + | + | + ↓ z + + + If you compute the relative pose (T_0_inv @ T_now), the coordinate system becomes: + + z (out of screen) + ⊙---> y + | + | + ↓ x + + """ + + def __init__(self, port: int = 5557, silent: bool = True): + self._silent = silent + self._port = port + self._latest_transform: dict = {} + self._latest_speed: dict = {} + self._commands: list[str] = [] + + # Use threading mode for socketio + self._sio = socketio.Server(async_mode="threading", cors_allowed_origins="*") + self._app = Flask(__name__) + self._app.wsgi_app = socketio.WSGIApp(self._sio, self._app.wsgi_app) + + # Set up the event handler for updates + @self._sio.event + def connect(sid, environ): + if not self._silent: + print(f"===============>Client connected: {sid}") + + @self._sio.event + def disconnect(sid): + if not self._silent: + print(f"===============>Client disconnected: {sid}") + + @self._sio.event + def update(sid, data): + try: + data = json.loads(data) + self._latest_transform = data + self._sio.emit("commands", json.dumps(self._commands), to=sid) + except Exception as e: + if not self._silent: + print(f"Update failed: {e}") + + def _run_server(self): + """Run the Flask server with threading.""" + self._app.run(host="0.0.0.0", port=self._port, threaded=True) + + def start(self): + """Start the server in a background thread.""" + server_thread = threading.Thread(target=self._run_server, daemon=True) + server_thread.start() + if not self._silent: + print(f"IPhone Device running at http://0.0.0.0:{self._port}") + + def stop(self): + if not self._silent: + print("IPhone Device stopped.") + + def get_cmd(self) -> dict: + return self._latest_transform + + def send_cmd(self, enable: bool) -> None: + self._commands = ["start_haptics" if enable else "stop_haptics"] + + +if __name__ == "__main__": + import time + + device = IPhoneDevice() + device.start() + + # or _ in range(100): + try: + while True: + data = device.get_cmd() + print("Latest data:", data) + time.sleep(1.0) + except KeyboardInterrupt: + print("Stopping device...") + finally: + device.stop() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/manus.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/manus.py new file mode 100644 index 0000000000000000000000000000000000000000..aa7634164626f9458702293cbb2f126baaf871ae --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/manus.py @@ -0,0 +1,138 @@ +from contextlib import contextmanager +import pickle +import time + +import click +import numpy as np +from scipy.spatial.transform import Rotation as R +import zmq + +from decoupled_wbc.control.teleop.device.SDKClient_Linux import ManusServer + +manus_idx = { + "left": ["3822396207", "3998055887", "432908014"], + "right": ["3762867141", "831307785", "3585023564"], +} + + +class Manus: + def __init__(self, port=5556): + # Storage for the latest finger data + self.latest_finger_data = { + "left_fingers": {"angle": np.zeros([40]), "position": np.zeros([25, 4, 4])}, + "right_fingers": {"angle": np.zeros([40]), "position": np.zeros([25, 4, 4])}, + } + self.manus_server = None + self.port = port + + def process_finger_pose(self, raw_position, raw_orientation, dir): + raw_position = np.asarray(raw_position).reshape([-1, 3]) + raw_orientation = np.asarray(raw_orientation).reshape([-1, 4]) + + def reorder(data): + return np.concatenate( + [ + data[0:1], # root + data[21:25], # thumb + data[1:6], # index + data[6:11], # middle + data[16:21], # ring + data[11:16], # pinky + ] + ) + + raw_position = reorder(raw_position) + raw_orientation = reorder(raw_orientation) + + transformation_matrix = np.zeros([25, 4, 4]) + rot_matrix = R.from_quat(raw_orientation[0][[1, 2, 3, 0]]).as_matrix() + transformation_matrix[:, :3, :3] = rot_matrix + transformation_matrix[:, :3, 3] = raw_position + transformation_matrix[:, 3, 3] = 1.0 + + T_root = transformation_matrix[0] + T_root_inv = np.linalg.inv(T_root) + transformation_matrix = np.matmul(T_root_inv[None], transformation_matrix) + + T_manus2avp = np.identity(4) + if dir == "right": + T_manus2avp[:3, :3] = R.from_euler("zx", [180, -90], degrees=True).as_matrix() + else: + T_manus2avp[:3, :3] = R.from_euler("x", [90], degrees=True).as_matrix() + transformation_matrix = np.matmul(T_manus2avp[None], transformation_matrix) + + return transformation_matrix + + def process_finger_angle(self, raw_finger_data, dir): + if dir == "right": + non_zero_data = [value for value in raw_finger_data if value != 0.0] + trailing_zeros_count = len(raw_finger_data) - len(non_zero_data) + raw_finger_data = non_zero_data + [0.0] * trailing_zeros_count + + return raw_finger_data + + def request_finger_data(self): + output = ManusServer.get_latest_state() + for dir, val in manus_idx.items(): + for id in val: + angle_name = f"{id}_angle" + if angle_name in output and len(output[angle_name]) > 0: + self.latest_finger_data[f"{dir}_fingers"]["angle"] = self.process_finger_angle( + np.asarray(output[angle_name]), dir + ) + + position_name = f"{id}_position" + orientation_name = f"{id}_orientation" + if ( + position_name in output + and orientation_name in output + and len(output[position_name]) > 0 + and len(output[orientation_name]) > 0 + ): + self.latest_finger_data[f"{dir}_fingers"]["position"] = ( + self.process_finger_pose( + output[position_name], output[orientation_name], dir + ) + ) + + return self.latest_finger_data + + @contextmanager + def activate(self): + try: + ManusServer.init() + self.context = zmq.Context() + self.socket = self.context.socket(zmq.REP) + self.socket.bind(f"tcp://*:{self.port}") + yield self + finally: + ManusServer.shutdown() + + def run(self): + while True: + # Wait for a request from the client + _ = self.socket.recv() + # Process finger data + data = self.request_finger_data() + data["timestamp"] = time.time() + + # Serialize the data to send back + serialized_data = pickle.dumps(data) + + # Send the serialized data back to the client + self.socket.send(serialized_data) + + +@click.command() +@click.option("--port", type=int, default=5556) +def main(port): + print("... starting manus server ... at port", port, flush=True) + manus = Manus(port=port) + print("... manus server activating ...") + with manus.activate(): + print("==> Manus server is running at port", port, flush=True) + manus.run() + + +if __name__ == "__main__": + main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/pico/xr_client.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/pico/xr_client.py new file mode 100644 index 0000000000000000000000000000000000000000..378ffc643407860bbb7d7884290fc1fe1b77fb9e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/device/pico/xr_client.py @@ -0,0 +1,155 @@ +import numpy as np +import xrobotoolkit_sdk as xrt + +# xrt interface is defined in +# https://github.com/XR-Robotics/XRoboToolkit-PC-Service-Pybind/blob/main/bindings/py_bindings.cpp + + +class XrClient: + """Client for the XrClient SDK to interact with XR devices.""" + + def __init__(self): + """Initializes the XrClient and the SDK.""" + xrt.init() + print("XRoboToolkit SDK initialized.") + + def get_pose_by_name(self, name: str) -> np.ndarray: + """Returns the pose of the specified device by name. + Valid names: "left_controller", "right_controller", "headset". + Pose is [x, y, z, qx, qy, qz, qw].""" + if name == "left_controller": + return xrt.get_left_controller_pose() + elif name == "right_controller": + return xrt.get_right_controller_pose() + elif name == "headset": + return xrt.get_headset_pose() + else: + raise ValueError( + f"Invalid name: {name}. Valid names are: 'left_controller', 'right_controller', 'headset'." + ) + + def get_key_value_by_name(self, name: str) -> float: + """Returns the trigger/grip value by name (float). + Valid names: "left_trigger", "right_trigger", "left_grip", "right_grip". + """ + if name == "left_trigger": + return xrt.get_left_trigger() + elif name == "right_trigger": + return xrt.get_right_trigger() + elif name == "left_grip": + return xrt.get_left_grip() + elif name == "right_grip": + return xrt.get_right_grip() + else: + raise ValueError( + f"Invalid name: {name}. Valid names are: \ + 'left_trigger', 'right_trigger', 'left_grip', 'right_grip'." + ) + + def get_button_state_by_name(self, name: str) -> bool: + """Returns the button state by name (bool). + Valid names: "A", "B", "X", "Y", + "left_menu_button", "right_menu_button", + "left_axis_click", "right_axis_click" + """ + if name == "A": + return xrt.get_A_button() + elif name == "B": + return xrt.get_B_button() + elif name == "X": + return xrt.get_X_button() + elif name == "Y": + return xrt.get_Y_button() + elif name == "left_menu_button": + return xrt.get_left_menu_button() + elif name == "right_menu_button": + return xrt.get_right_menu_button() + elif name == "left_axis_click": + return xrt.get_left_axis_click() + elif name == "right_axis_click": + return xrt.get_right_axis_click() + else: + raise ValueError( + f"Invalid name: {name}. Valid names are: 'A', 'B', 'X', 'Y', " + "'left_menu_button', 'right_menu_button', 'left_axis_click', 'right_axis_click'." + ) + + def get_timestamp_ns(self) -> int: + """Returns the current timestamp in nanoseconds (int).""" + return xrt.get_time_stamp_ns() + + def get_hand_tracking_state(self, hand: str) -> np.ndarray | None: + """Returns the hand tracking state for the specified hand. + Valid hands: "left", "right". + State is a 27 x 7 numpy array, where each row is [x, y, z, qx, qy, qz, qw] for each joint. + Returns None if hand tracking is inactive (low quality). + """ + if hand.lower() == "left": + if not xrt.get_left_hand_is_active(): + return None + return xrt.get_left_hand_tracking_state() + elif hand.lower() == "right": + if not xrt.get_right_hand_is_active(): + return None + return xrt.get_right_hand_tracking_state() + else: + raise ValueError(f"Invalid hand: {hand}. Valid hands are: 'left', 'right'.") + + def get_joystick_state(self, controller: str) -> list[float]: + """Returns the joystick state for the specified controller. + Valid controllers: "left", "right". + State is a list with shape (2) representing [x, y] for each joystick. + """ + if controller.lower() == "left": + return xrt.get_left_axis() + elif controller.lower() == "right": + return xrt.get_right_axis() + else: + raise ValueError( + f"Invalid controller: {controller}. Valid controllers are: 'left', 'right'." + ) + + def get_motion_tracker_data(self) -> dict: + """Returns a dictionary of motion tracker data, where the keys are the tracker serial numbers. + Each value is a dictionary containing the pose, velocity, and acceleration of the tracker. + """ + num_motion_data = xrt.num_motion_data_available() + if num_motion_data == 0: + return {} + + poses = xrt.get_motion_tracker_pose() + velocities = xrt.get_motion_tracker_velocity() + accelerations = xrt.get_motion_tracker_acceleration() + serial_numbers = xrt.get_motion_tracker_serial_numbers() + + tracker_data = {} + for i in range(num_motion_data): + serial = serial_numbers[i] + tracker_data[serial] = { + "pose": poses[i], + "velocity": velocities[i], + "acceleration": accelerations[i], + } + + return tracker_data + + def get_body_tracking_data(self) -> dict | None: + """Returns complete body tracking data or None if unavailable. + + Returns: + Dict with keys: 'poses', 'velocities', 'accelerations', 'imu_timestamps', 'body_timestamp' + - poses: (24, 7) array [x,y,z,qx,qy,qz,qw] for each joint + - velocities: (24, 6) array [vx,vy,vz,wx,wy,wz] for each joint + - accelerations: (24, 6) array [ax,ay,az,wax,way,waz] for each joint + """ + if not xrt.is_body_data_available(): + return None + + return { + "poses": xrt.get_body_joints_pose(), + "velocities": xrt.get_body_joints_velocity(), + "accelerations": xrt.get_body_joints_acceleration(), + } + + def close(self): + xrt.close() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/cli.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..b37996c5046e73b8c3d0e2d5303c171bcd997c25 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/cli.py @@ -0,0 +1,20 @@ +import subprocess + +import click + + +@click.command() +def teleop(): + """CLI for interacting with the osmo.""" + subprocess.run(["python", "decoupled_wbc/control/teleop/gui/main.py"]) + + +@click.group() +def cli(): + """CLI for interacting with the osmo.""" + + +cli.add_command(teleop) + +if __name__ == "__main__": + cli() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/events3d.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/events3d.py new file mode 100644 index 0000000000000000000000000000000000000000..13f96964347a0808ea8206d294555f87ee43deaa --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/events3d.py @@ -0,0 +1,253 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Marc Flerackers + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +This module contains classes to allow an object to handle events. +""" +import library.log as log +import library.profiler as profiler +from library.universal import G + + +class Event: + """ + Base class for all events, does not contain information. + """ + + def __init__(self): + pass + + def __repr__(self) -> str: + return "event:" + + +class MouseEvent(Event): + """ + Contains information about a mouse event. + + :param button: the button that is pressed in case of a mousedown or mouseup event, + or button flags in case of a mousemove event. + :type button: int + :param x: the x position of the mouse in window coordinates. + :type x: int + :param y: the y position of the mouse in window coordinates. + :type y: int + :param dx: the difference in x position in case of a mousemove event. + :type dx: int + :param dy: the difference in y position in case of a mousemove event. + :type dy: int + """ + + def __init__(self, button, x, y, dx=0, dy=0): + self.button = button + self.x = x + self.y = y + self.dx = dx + self.dy = dy + + def __repr__(self): + return "MouseEvent(%d, %d, %d, %d, %d)" % (self.button, self.x, self.y, self.dx, self.dy) + + +class MouseWheelEvent(Event): + """ + Contains information about a mouse wheel event. + + :param wheelDelta: the amount and direction that the wheel was scrolled. + :type wheelDelta: int + """ + + def __init__(self, wheelDelta, x, y): + self.wheelDelta = wheelDelta + self.x = x + self.y = y + + def __repr__(self): + return "MouseWheelEvent(%d)" % self.wheelDelta + + +class KeyEvent(Event): + """ + Contains information about a keyboard event. + + :param key: the key code of the key that was pressed or released. + :type key: int + :param character: the unicode character if the key represents a character. + :type character: unicode + :param modifiers: the modifier keys that were down at the time of pressing the key. + :type modifiers: int + """ + + def __init__(self, key, character, modifiers): + self.key = key + self.character = character + self.modifiers = modifiers + + def __repr__(self): + return "KeyEvent(%d, %04x %s, %d)" % ( + self.key, + ord(self.character), + self.character, + self.modifiers, + ) + + +class FocusEvent(Event): + """ + Contains information about a view focus/blur event + + :param blurred: the view that lost the focus. + :type blurred: guid3d.View + :param focused: the view that gained the focus. + :type focused: guid3d.View + """ + + def __init__(self, blurred, focused): + self.blurred = blurred + self.focused = focused + + def __repr__(self): + return "FocusEvent(%s, %s)" % (self.blurred, self.focused) + + +class ResizeEvent(Event): + """ + Contains information about a resize event + + :param width: the new width of the window in pixels. + :type width: int + :param height: the new height of the window in pixels. + :type height: int + :param fullscreen: the new fullscreen state of the window. + :type fullscreen: Boolean + :param dx: the change in width of the window in pixels. + :type dx: int + :param dy: the change in height of the window in pixels. + :type dy: int + """ + + def __init__(self, width, height, fullscreen): + self.width = width + self.height = height + self.fullscreen = fullscreen + + def __repr__(self): + return "ResizeEvent(%d, %d, %s)" % (self.width, self.height, self.fullscreen) + + +class HumanEvent(Event): + def __init__(self, human, change): + self.human = human + self.change = change + + def __repr__(self): + return "event: %s, %s" % (self.human, self.change) + + +class EventHandler(object): + """ + Base event handler class. Derive from this class if an object needs to be able to have events attached to it. + Currently only one event per event name can be attached. This is because we either allow a class method or + a custom method to be attached as event handling method. Since the custom method replaces the class method, + it is needed in some case to call the base class's method from the event handling method. + + There are 2 ways to attach handlers: + + 1. Override the method. This is the most appropriate way when you want to add distinctive behaviour to many + EventHandlers. + + :: + + class Widget(View): + + def onMouseDown(self, event): + #Handle event + + 2. Use the event decorator. This is the most appropriate way when you want + to attach distinctive behaviour to one EventHandler. + + :: + + widget = Widget() + + @widget.mhEvent: + def onMouseDown(event): + #Handle event + + Note that self is not passed to the handler in this case, which should not be a problem + as you can just use the variable since you are creating a closure. + """ + + def __init__(self): + self.sortOrder = None + + _logger = log.getLogger("mh.callEvent") + _depth = 0 + + def callEvent(self, eventType, event): + if not hasattr(self, eventType): + return False + topLevel = EventHandler._depth == 0 + EventHandler._depth += 1 + try: + self._logger.debug("callEvent[%d]: %s.%s(%s)", self._depth, self, eventType, event) + method = getattr(self, eventType) + if topLevel and profiler.active(): + profiler.accum("method(event)", globals(), locals()) + else: + method(event) + except Exception as _: + log.warning("Exception during event %s", eventType, exc_info=True) + self.eventFailed(EventHandler._depth) + EventHandler._depth -= 1 + if topLevel: + self._logger.debug("callEvent: done") + if G.app: + G.app.redraw() + return True + return False + + def eventFailed(self, level): + # Reset progress + if G.app: + G.app.progress(1) + + def attachEvent(self, eventName, eventMethod): + setattr(self, eventName, eventMethod) + + def detachEvent(self, eventName): + delattr(self, eventName) + + def mhEvent(self, eventMethod): + self.attachEvent(eventMethod.__name__, eventMethod) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/gui3d.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/gui3d.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c83c44f6acd6ffcadc9bb7470be31d835f950a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/gui3d.py @@ -0,0 +1,670 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Joel Palmius, Marc Flerackers + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +This module contains classes defined to implement widgets that provide utility functions +to the graphical user interface. + +Importing this module loads OpenGL dependencies. +""" + +import weakref + +import events3d +import library.log as log +import mh +import module3d + + +class View(events3d.EventHandler): + """ + The base view from which all widgets are derived. + """ + + def __init__(self): + + self.children = [] + self.objects = [] + self._visible = False + self._totalVisibility = False + self._parent = None + self._attached = False + self.widgets = [] + + @property + def parent(self): + if self._parent: + return self._parent() + else: + return None + + def _attach(self): + + self._attached = True + + for object in self.objects: + object._attach() + + for child in self.children: + child._attach() + + def _detach(self): + self._attached = False + + for object in self.objects: + object._detach() + + for child in self.children: + child._detach() + + def addView(self, view): + """ + Adds the view to this view. If this view is attached to the app, the view will also be attached. + + :param view: The view to be added. + :type view: gui3d.View + :return: The view, for convenience. + :rvalue: gui3d.View + """ + if view.parent: + raise RuntimeError("The view is already added to a view") + + view._parent = weakref.ref(self) + view._updateVisibility() + if self._attached: + view._attach() + + self.children.append(view) + + return view + + def removeView(self, view): + """ + Removes the view from this view. If this view is attached to the app, the view will be detached. + + :param view: The view to be removed. + :type view: gui3d.View + """ + if view not in self.children: + raise RuntimeError("The view is not a child of this view") + + view._parent = None + if self._attached: + view._detach() + + self.children.remove(view) + + def addObject(self, object): + """ + Adds the object to the view. If the view is attached to the app, + the object will also be attached and will get an OpenGL counterpart. + + :param object: The object to be added. + :type object: gui3d.Object + :return: The object, for convenience. + :rvalue: gui3d.Object + """ + if object._view: + raise RuntimeError("The object is already added to a view") + + object._view = weakref.ref(self) + if self._attached: + object._attach() + + self.objects.append(object) + + return object + + def removeObject(self, object): + """ + Removes the object from the view. If the object was attached to the app, + its OpenGL counterpart will be removed as well. + + :param object: The object to be removed. + :type object: gui3d.Object + """ + if object not in self.objects: + raise RuntimeError("The object is not a child of this view") + + object._view = None + if self._attached: + object._detach() + + self.objects.remove(object) + + def show(self): + self._visible = True + self._updateVisibility() + + def hide(self): + self._visible = False + self._updateVisibility() + + def isShown(self): + return self._visible + + def isVisible(self): + return self._totalVisibility + + def _updateVisibility(self): + previousVisibility = self._totalVisibility + + self._totalVisibility = self._visible and (not self.parent or self.parent.isVisible()) + + for o in self.objects: + o.setVisibility(self._totalVisibility) + + for v in self.children: + v._updateVisibility() + + if self._totalVisibility != previousVisibility: + if self._totalVisibility: + self.callEvent("onShow", None) + else: + self.callEvent("onHide", None) + + def onShow(self, event): + self.show() + + def onHide(self, event): + self.hide() + + def onMouseDown(self, event): + self.parent.callEvent("onMouseDown", event) + + def onMouseMoved(self, event): + self.parent.callEvent("onMouseMoved", event) + + def onMouseDragged(self, event): + self.parent.callEvent("onMouseDragged", event) + + def onMouseUp(self, event): + self.parent.callEvent("onMouseUp", event) + + def onMouseEntered(self, event): + self.parent.callEvent("onMouseEntered", event) + + def onMouseExited(self, event): + self.parent.callEvent("onMouseExited", event) + + def onClicked(self, event): + self.parent.callEvent("onClicked", event) + + def onMouseWheel(self, event): + self.parent.callEvent("onMouseWheel", event) + + def addTopWidget(self, widget): + mh.addTopWidget(widget) + self.widgets.append(widget) + widget._parent = self + if self.isVisible(): + widget.show() + else: + widget.hide() + return widget + + def removeTopWidget(self, widget): + self.widgets.remove(widget) + mh.removeTopWidget(widget) + + def showWidgets(self): + for w in self.widgets: + w.show() + + def hideWidgets(self): + for w in self.widgets: + w.hide() + + +class TaskView(View): + + def __init__(self, category, name, label=None): + super(TaskView, self).__init__() + self.name = name + self.category = category + self.label = label + self.focusWidget = None + self.tab = None + self.left, self.right = mh.addPanels() + self.sortOrder = None + + def getModifiers(self): + return {} + + def showWidgets(self): + super(TaskView, self).showWidgets() + mh.showPanels(self.left, self.right) + + def addLeftWidget(self, widget): + return self.left.addWidget(widget) + + def addRightWidget(self, widget): + return self.right.addWidget(widget) + + def removeLeftWidget(self, widget): + self.left.removeWidget(widget) + + def removeRightWidget(self, widget): + self.right.removeWidget(widget) + + +class Category(View): + + def __init__(self, name, label=None): + super(Category, self).__init__() + self.name = name + self.label = label + self.tasks = [] + self.tasksByName = {} + self.tab = None + self.tabs = None + self.panel = None + self.task = None + self.sortOrder = None + + def _taskTab(self, task): + if task.tab is None: + task.tab = self.tabs.addTab(task.name, task.label or task.name, self.tasks.index(task)) + + def realize(self, app): + self.tasks.sort(key=lambda t: t.sortOrder) + for task in self.tasks: + self._taskTab(task) + + @self.tabs.mhEvent + def onTabSelected(tab): + self.task = tab.name + app.switchTask(tab.name) + + def addTask(self, task): + if task.name in self.tasksByName: + raise KeyError("A task with this name already exists", task.name) + if task.sortOrder is None: + orders = [t.sortOrder for t in self.tasks] + o = 0 + while o in orders: + o = o + 1 + task.sortOrder = o + + self.tasks.append(task) + self.tasks.sort(key=lambda t: t.sortOrder) + + self.tasksByName[task.name] = task + self.addView(task) + if self.tabs is not None: + self._taskTab(task) + self.task = self.tasks[0].name + + categories = sorted(list(self.parent.categories.values()), key=lambda c: c.sortOrder) + categoryOrder = categories.index(self) + # Ensure that event order is per category, per task + eventOrder = 1000 * categoryOrder + task.sortOrder + self.parent.addEventHandler(task, eventOrder) + + return task + + def getTaskByName(self, name): + return self.tasksByName.get(name) + + +# The application +app = None + + +class Application(events3d.EventHandler): + """ + The Application. + """ + + singleton = None + + def __init__(self): + global app + app = self + self.parent = self + self.children = [] + self.objects = [] + self.categories = {} + self.currentCategory = None + self.currentTask = None + self.mouseDownObject = None + self.enteredObject = None + self.fullscreen = False + + self.tabs = None # Assigned in mhmain.py + + def addObject(self, object): + """ + Adds the object to the application. The object will also be attached and will get an OpenGL counterpart. + + :param object: The object to be added. + :type object: gui3d.Object + :return: The object, for convenience. + :rvalue: gui3d.Object + """ + if object._view: + raise RuntimeError("The object is already attached to a view") + + object._view = weakref.ref(self) + object._attach() + + self.objects.append(object) + + return object + + def removeObject(self, object): + """ + Removes the object from the application. Its OpenGL counterpart will be removed as well. + + :param object: The object to be removed. + :type object: gui3d.Object + """ + if object not in self.objects: + raise RuntimeError("The object is not a child of this view") + + object._view = None + object._detach() + + self.objects.remove(object) + + def addView(self, view): + """ + Adds the view to the application.The view will also be attached. + + :param view: The view to be added. + :type view: gui3d.View + :return: The view, for convenience. + :rvalue: gui3d.View + """ + if view.parent: + raise RuntimeError("The view is already attached") + + view._parent = weakref.ref(self) + view._updateVisibility() + view._attach() + + self.children.append(view) + + return view + + def removeView(self, view): + """ + Removes the view from the application. The view will be detached. + + :param view: The view to be removed. + :type view: gui3d.View + """ + if view not in self.children: + raise RuntimeError("The view is not a child of this view") + + view._parent = None + view._detach() + + self.children.remove(view) + + def isVisible(self): + return True + + def addCategory(self, category, sortOrder=None): + if category.name in self.categories: + raise KeyError("A category with this name already exists", category.name) + + if category.parent: + raise RuntimeError("The category is already attached") + + if sortOrder is None: + orders = [c.sortOrder for c in list(self.categories.values())] + o = 0 + while o in orders: + o = o + 1 + sortOrder = o + + category.sortOrder = sortOrder + self.categories[category.name] = category + + categories = list(self.categories.values()) + categories.sort(key=lambda c: c.sortOrder) + + category.tab = self.tabs.addTab( + category.name, category.label or category.name, categories.index(category) + ) + category.tabs = category.tab.child + self.addView(category) + category.realize(self) + + return category + + def switchTask(self, name): + if not self.currentCategory: + return + newTask = self.currentCategory.tasksByName[name] + + if self.currentTask and self.currentTask is newTask: + return + + if self.currentTask: + log.debug("hiding task %s", self.currentTask.name) + self.currentTask.hide() + self.currentTask.hideWidgets() + + self.currentTask = self.currentCategory.tasksByName[name] + + if self.currentTask: + log.debug("showing task %s", self.currentTask.name) + self.currentTask.show() + self.currentTask.showWidgets() + + def switchCategory(self, name): + + # Do we need to switch at all + + if self.currentCategory and self.currentCategory.name == name: + return + + # Does the category exist + + if name not in self.categories: + return + + category = self.categories[name] + + # Does the category have at least one view + + if len(category.tasks) == 0: + return + + if self.currentCategory: + log.debug("hiding category %s", self.currentCategory.name) + self.currentCategory.hide() + self.currentCategory.hideWidgets() + + self.currentCategory = category + + log.debug("showing category %s", self.currentCategory.name) + self.currentCategory.show() + self.currentCategory.showWidgets() + + self.switchTask(category.task) + + def getCategory(self, name, sortOrder=None): + category = self.categories.get(name) + if category: + return category + return self.addCategory(Category(name), sortOrder=sortOrder) + + def getTask(self, category, task): + """ + Retrieve a task by category and name. + Will not create a task or category if it does not exist. + + Set category to None or False to search for a task by name. Will raise + an exception when the result is ambiguous (there are multiple tasks with + the same name in different categories). + This quickhand is mostly useful for shell usage, but dangerous to use in + a plugin. + """ + if category: + if category not in list(self.categories.keys()): + raise RuntimeWarning('Category with name "%s" does not exist.' % category) + c = self.getCategory(category) + if task not in list(c.tasksByName.keys()): + raise RuntimeWarning( + 'Category "%s" does not contain a task with name "%s".' % (category, task) + ) + return c.getTaskByName(task) + else: + tasks = [] + for c in list(self.categories.keys()): + if task in list(self.getCategory(c).tasksByName.keys()): + tasks.append(self.getCategory(c).tasksByName[task]) + if len(tasks) == 0: + raise RuntimeWarning('No task with name "%s" found.' % task) + if len(tasks) > 1: + raise RuntimeWarning( + 'Ambiguous result for task "%s", there are multiple tasks with that name.' + % task + ) + return tasks[0] + + # called from native + + def onMouseDownCallback(self, event): + # Get picked object + pickedObject = self.getSelectedFaceGroupAndObject() + + # Do not allow picking detached objects (in case of stale picking buffer) + if pickedObject and hasattr(pickedObject, "view") and not pickedObject.view: + pickedObject = None + + if pickedObject: + object = pickedObject[1].object + else: + object = self + + # It is the object which will receive the following mouse messages + self.mouseDownObject = object + + # Send event to the object + if object: + object.callEvent("onMouseDown", event) + + def onMouseUpCallback(self, event): + if event.button == 4 or event.button == 5: + return + + # Get picked object + pickedObject = self.getSelectedFaceGroupAndObject() + + # Do not allow picking detached objects (in case of stale picking buffer) + if pickedObject and hasattr(pickedObject, "view") and not pickedObject.view: + pickedObject = None + + if pickedObject: + object = pickedObject[1].object + else: + object = self + + # Clean up handles to detached (guicommon.Object) objects + if ( + self.mouseDownObject + and hasattr(self.mouseDownObject, "view") + and not self.mouseDownObject.view + ): + self.mouseDownObject = None + + if self.mouseDownObject: + self.mouseDownObject.callEvent("onMouseUp", event) + if self.mouseDownObject is object: + self.mouseDownObject.callEvent("onClicked", event) + + def onMouseMovedCallback(self, event): + # Get picked object + picked = self.getSelectedFaceGroupAndObject() + + # Do not allow picking detached objects (in case of stale picking buffer) + if picked and hasattr(picked, "view") and not picked.view: + picked = None + + if picked and picked[1]: + group = picked[0] + object = picked[1].object or self + else: + group = None + object = self + + event.object = object + event.group = group + + # Clean up handles to detached (guicommon.Object) objects + if ( + self.mouseDownObject + and hasattr(self.mouseDownObject, "view") + and not self.mouseDownObject.view + ): + self.mouseDownObject = None + if ( + self.enteredObject + and hasattr(self.enteredObject, "view") + and not self.enteredObject.view + ): + self.enteredObject = None + + if event.button: + if self.mouseDownObject: + self.mouseDownObject.callEvent("onMouseDragged", event) + else: + if self.enteredObject != object: + if self.enteredObject: + self.enteredObject.callEvent("onMouseExited", event) + self.enteredObject = object + self.enteredObject.callEvent("onMouseEntered", event) + if object != self: + object.callEvent("onMouseMoved", event) + elif self.currentTask: + self.currentTask.callEvent("onMouseMoved", event) + + def onMouseWheelCallback(self, event): + if self.currentTask: + self.currentTask.callEvent("onMouseWheel", event) + + def onResizedCallback(self, event): + if self.fullscreen != event.fullscreen: + module3d.reloadTextures() + + self.fullscreen = event.fullscreen + + for category in list(self.categories.values()): + category.callEvent("onResized", event) + for task in category.tasks: + task.callEvent("onResized", event) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/guicommon.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/guicommon.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f69d1c5c7e162b679cc9887815205db7389a82 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/guicommon.py @@ -0,0 +1,860 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Joel Palmius, Marc Flerackers + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +Common GUI elements extracted from gui3d to minimize coupling with gui backend. +""" + +import collections + +import events3d +import library.log as log +import library.matrix as matrix +import numpy as np +import shared.material as material + + +class Action(object): + def __init__(self, name): + self.name = name + + def do(self): + return True + + def undo(self): + return True + + +# Wrapper around Object3D +class Object(events3d.EventHandler): + """ + An object on the screen. + + :param position: The position in 3d space. + :type position: list or tuple + :param mesh: The mesh object. + :param visible: Wether the object should be initially visible. + :type visible: Boolean + """ + + def __init__(self, mesh, position=[0.0, 0.0, 0.0], visible=True): + + if mesh.object: + raise RuntimeError("This mesh is already attached to an object") + + self.mesh = mesh + self.mesh.object = self + self.mesh.setVisibility(visible) + + self._material = material.Material(self.name + "_Material") # Render material + + self._loc = np.zeros(3, dtype=np.float32) + self._rot = np.zeros(3, dtype=np.float32) + self._scale = np.ones(3, dtype=np.float32) + + self.setLoc(*position) + # Set to true to make the rotation of this object independent of the camera rotation + self.lockRotation = False + # Set to true to automatically set Y loc (position) to height of ground helper joint of the human + self.placeAtFeet = False + + self._view = None + + self.visible = visible + self.excludeFromProduction = False # Set to true to exclude from production renders + + self.proxy = None + + self.__seedMesh = self.mesh + self.__proxyMesh = None + self.__subdivisionMesh = None + self.__proxySubdivisionMesh = None + + self.setUVMap(mesh.material.uvMap) + + def __str__(self): + return "" % self.name + + # TODO + def clone(self): + raise NotImplementedError("You probably want to do object.mesh.clone()") + + def _attach(self): + if self.view.isVisible() and self.visible: + self.mesh.setVisibility(1) + else: + self.mesh.setVisibility(0) + + for mesh in self._meshes(): + self.attachMesh(mesh) + + def _detach(self): + for mesh in self._meshes(): + self.detachMesh(mesh) + + @staticmethod + def attachMesh(mesh): + import object3d + import selection + + selection.selectionColorMap.assignSelectionID(mesh) + object3d.Object3D.attach(mesh) + + @staticmethod + def detachMesh(mesh): + import object3d + + object3d.Object3D.detach(mesh) + + def _meshes(self): + for mesh in ( + self.__seedMesh, + self.__proxyMesh, + self.__subdivisionMesh, + self.__proxySubdivisionMesh, + ): + if mesh is not None: + yield mesh + + @property + def view(self): + if not self._view or not isinstance(self._view, collections.abc.Callable): + return None + return self._view() + + def show(self): + self.visible = True + self.setVisibility(True) + + def hide(self): + self.visible = False + self.setVisibility(False) + + def isVisible(self): + return self.visible + + @property + def name(self): + return self.mesh.name + + def setVisibility(self, visibility): + if not self.view: + self.mesh.setVisibility(0) + if self.view.isVisible() and self.visible and visibility: + self.mesh.setVisibility(1) + else: + self.mesh.setVisibility(0) + + def getPriority(self): + return self.mesh.priority + + def setPriority(self, priority): + self.mesh.priority = priority + + priority = property(getPriority, setPriority) + + ## + # Orientation properties + ## + + def getLoc(self): + result = np.zeros(3, dtype=np.float32) + result[:] = self._loc[:] + if self.placeAtFeet: + from core import G + + human = G.app.selectedHuman + result[1] = human.getJointPosition("ground")[1] + return result + + def setLoc(self, locx, locy, locz): + """ + This method is used to set the location of the object in the 3D coordinate space of the scene. + + :param locx: The x coordinate of the object. + :type locx: float + :param locy: The y coordinate of the object. + :type locy: float + :param locz: The z coordinate of the object. + :type locz: float + """ + self._loc[...] = (locx, locy, locz) + + loc = property(getLoc, setLoc) + + def get_x(self): + return self.loc[0] + + def set_x(self, x): + self._loc[0] = x + + x = property(get_x, set_x) + + def get_y(self): + return self.loc[1] + + def set_y(self, y): + self._loc[1] = y + + y = property(get_y, set_y) + + def get_z(self): + return self.loc[2] + + def set_z(self, z): + self._loc[2] = z + + z = property(get_z, set_z) + + def get_rx(self): + return self._rot[0] + + def set_rx(self, rx): + self._rot[0] = rx + + rx = property(get_rx, set_rx) + + def get_ry(self): + return self._rot[1] + + def set_ry(self, ry): + self._rot[1] = ry + + ry = property(get_ry, set_ry) + + def get_rz(self): + return self._rot[2] + + def set_rz(self, rz): + self._rot[2] = rz + + rz = property(get_rz, set_rz) + + def get_sx(self): + return self._scale[0] + + def set_sx(self, sx): + self._scale[0] = sx + + sx = property(get_sx, set_sx) + + def get_sy(self): + return self._scale[1] + + def set_sy(self, sy): + self._scale[1] = sy + + sy = property(get_sy, set_sy) + + def get_sz(self): + return self._scale[2] + + def set_sz(self, sz): + self._scale[2] = sz + + sz = property(get_sz, set_sz) + + def getPosition(self): + return [self.x, self.y, self.z] + + def setPosition(self, position): + self.setLoc(position[0], position[1], position[2]) + + def getRotation(self): + return [self.rx, self.ry, self.rz] + + def setRotation(self, rotation): + rotation[0] = rotation[0] % 360 + rotation[1] = rotation[1] % 360 + + if rotation[2] != 0.0: + log.warning("Setting a non-zero rotation around Z axis is not supported!") + rotation[2] = 0.0 + + self.setRot(rotation[0], rotation[1], rotation[2]) + + def setRot(self, rx, ry, rz): + """ + This method sets the orientation of the object in the 3D coordinate space of the scene. + + :param rx: Rotation around the x-axis. + :type rx: float + :param ry: Rotation around the y-axis. + :type ry: float + :param rz: Rotation around the z-axis. + :type rz: float + """ + self._rot[...] = (rx, ry, rz) + + rot = property(getRotation, setRotation) + + def setScale(self, scale, scaleY=None, scaleZ=1): + """ + This method sets the scale of the object in the 3D coordinate space of + the scene, relative to the initially defined size of the object. + + :param scale: Scale along the x-axis, uniform scale if other params not + specified. + :type scale: float + :param scaleY: Scale along the x-axis. + :type scaleY: float + :param scaleZ: Scale along the x-axis. + :type scaleZ: float + """ + if scaleY is None: + scaleY = scale + scaleZ = scale + self._scale[...] = (scale, scaleY, scaleZ) + + def getScale(self): + return list(self._scale) + + scale = property(getScale, setScale) + + @property + def transform(self): + m = matrix.translate(self.loc) + if any(x != 0 for x in self.rot): + m = m * matrix.rotx(self.rx) + m = m * matrix.roty(self.ry) + m = m * matrix.rotz(self.rz) + if any(x != 1 for x in self.scale): + m = m * matrix.scale(self.scale) + return m + + def getSeedMesh(self): + return self.__seedMesh + + def getProxyMesh(self): + return self.__proxyMesh + + def updateProxyMesh(self, fit_to_posed=False): + if self.proxy and self.__proxyMesh: + self.proxy.update(self.__proxyMesh, fit_to_posed) + self.__proxyMesh.update() + + def isProxied(self): + return self.mesh == self.__proxyMesh or self.mesh == self.__proxySubdivisionMesh + + def setProxy(self, proxy): + isSubdivided = self.isSubdivided() + + if self.proxy: + self.proxy = None + self.detachMesh(self.__proxyMesh) + self.__proxyMesh.clear() + self.__proxyMesh = None + if self.__proxySubdivisionMesh: + self.detachMesh(self.__proxySubdivisionMesh) + self.__proxySubdivisionMesh.clear() + self.__proxySubdivisionMesh = None + self.mesh = self.__seedMesh + self.mesh.setVisibility(1) + + if proxy: + + self.proxy = proxy + + self.__proxyMesh = proxy.object.mesh.clone() + self.__proxyMesh.object = self + + # Copy attributes from human mesh to proxy mesh + for attr in ("visibility", "pickable", "cameraMode"): + setattr(self.__proxyMesh, attr, getattr(self.mesh, attr)) + + self.updateProxyMesh() + + # Attach to GL object if this object is attached to viewport + if self.__seedMesh.object3d: + self.attachMesh(self.__proxyMesh) + + self.mesh.setVisibility(0) + self.mesh = self.__proxyMesh + self.mesh.setVisibility(1) + + self.setSubdivided(isSubdivided) + + def getProxy(self): + return self.proxy + + def getSubdivisionMesh(self, update=True): + """ + Create or update the Catmull-Clark subdivided (or smoothed) mesh for + this mesh. + This does not change the status of isSubdivided(), use setSubdivided() + for that. + + If this mesh is doubled by a proxy, when isProxied() is true, a + subdivision mesh for the proxy is used. + + Returns the subdivided mesh data. + + """ + import catmull_clark_subdivision as cks + + if self.isProxied(): + if not self.__proxySubdivisionMesh: + self.__proxySubdivisionMesh = cks.createSubdivisionObject(self.__proxyMesh, None) + if self.__seedMesh.object3d: + self.attachMesh(self.__proxySubdivisionMesh) + elif update: + cks.updateSubdivisionObject(self.__proxySubdivisionMesh) + + return self.__proxySubdivisionMesh + else: + if not self.__subdivisionMesh: + self.__subdivisionMesh = cks.createSubdivisionObject( + self.__seedMesh, self.staticFaceMask + ) + if self.__seedMesh.object3d: + self.attachMesh(self.__subdivisionMesh) + elif update: + cks.updateSubdivisionObject(self.__subdivisionMesh) + + return self.__subdivisionMesh + + def isSubdivided(self): + """ + Returns whether this mesh is currently set to be subdivided + (or smoothed). + + """ + return self.mesh == self.__subdivisionMesh or self.mesh == self.__proxySubdivisionMesh + + def setSubdivided(self, flag, update=True): + """ + Set whether this mesh is to be subdivided (or smoothed). + When set to true, the subdivision mesh is automatically created or + updated. + + """ + if flag == self.isSubdivided(): + return False + + if flag: + self.mesh.setVisibility(0) + originalMesh = self.mesh + self.mesh = self.getSubdivisionMesh(update) + self.mesh.setVisibility(1) + else: + originalMesh = ( + self.__seedMesh if self.mesh == self.__subdivisionMesh else self.__proxyMesh + ) + + self.mesh.setVisibility(0) + self.mesh = originalMesh + if update: + self.mesh.calcNormals() + self.mesh.update() + self.mesh.setVisibility(1) + + return True + + def updateSubdivisionMesh(self, rebuildIndexBuffer=False): + if rebuildIndexBuffer: + # Purge old subdivision mesh and recalculate entirely + self.setSubdivided(False) + self.__subdivisionMesh = self.__proxySubdivisionMesh = None + self.setSubdivided(True) + else: + self.getSubdivisionMesh(True) + + def _setMeshUVMap(self, filename, mesh): + if filename == self.material.uvMap: + # No change, do nothing + return + + if not hasattr(mesh, "_originalUVMap") or not mesh._originalUVMap: + # Backup original mesh UVs + mesh._originalUVMap = dict() + mesh._originalUVMap["texco"] = mesh.texco + mesh._originalUVMap["fuvs"] = mesh.fuvs + # self._originalUVMap['fvert'] = mesh.fvert + # self._originalUVMap['group'] = mesh.group + + faceMask = mesh.getFaceMask() + faceGroups = mesh.group + + self.material.uvMap = filename + + if not filename: + # Restore original UVs + mesh.setUVs(mesh._originalUVMap["texco"]) + mesh.setFaces(mesh.fvert, mesh._originalUVMap["fuvs"], faceGroups) + mesh._originalUVMap = None + else: + uvset = material.UVMap(filename) + uvset.read(mesh, filename) + + if len(uvset.fuvs) != len(mesh.fuvs): + raise NameError( + "The UV file %s is not valid for mesh %s. \ + Number of faces %d != %d" + % (filename, mesh.name, len(uvset.fuvs), len(mesh.fuvs)) + ) + + mesh.setUVs(uvset.uvs) + mesh.setFaces(mesh.fvert, uvset.fuvs, faceGroups) + + mesh.changeFaceMask(faceMask) + mesh.updateIndexBuffer() + + @property + def staticFaceMask(self): + if not hasattr(self, "_staticFaceMask") or self._staticFaceMask is None: + # If not already set, consider the current face mask state of the + # mesh to be the static face mask + self._staticFaceMask = self.__seedMesh.face_mask.copy() + return self._staticFaceMask + + def changeVertexMask(self, vertsMask): + """ + Apply a face mask to the meshes (original seed mesh, subdivided mesh + and proxied meshes) specified by a vertex mask. + The vertex mask is a list of booleans, one for each vertex, where True + means not masked (visible), and False means masked (hidden). + A face is masked if all of the vertices that define it are masked. + """ + if vertsMask is None: + # Undo face mask set by vertex mask + self.__seedMesh.changeFaceMask(self.staticFaceMask) + self.__seedMesh.updateIndexBufferFaces() + if self.__subdivisionMesh: + self.__subdivisionMesh.changeFaceMask(self.staticFaceMask) + self.__subdivisionMesh.updateIndexBufferFaces() + if self.__proxyMesh: + self.__proxyMesh.changeFaceMask( + np.ones(self.__proxyMesh.getFaceCount(), dtype=bool) + ) + self.__proxyMesh.updateIndexBufferFaces() + if self.__proxySubdivisionMesh: + self.__proxySubdivisionMesh.changeFaceMask( + np.ones(self.__proxySubdivisionMesh.getFaceCount(), dtype=bool) + ) + self.__proxySubdivisionMesh.updateIndexBufferFaces() + return + + # Mask seed mesh + faceMask = self.__seedMesh.getFaceMaskForVertices(np.argwhere(vertsMask)[..., 0]) + self.__seedMesh.changeFaceMask(np.logical_and(faceMask, self.staticFaceMask)) + self.__seedMesh.updateIndexBufferFaces() + + import log + + log.debug("%s faces masked for %s", np.count_nonzero(~faceMask), self.__seedMesh.name) + + # Mask smoothed seed mesh + if self.__subdivisionMesh: + # Remap faceMask to subdivision mesh base faces, accounting for the + # excluded faces of the static facemask (staticFaceMask). + + # Statically masked faces (staticFaceMask) are excluded from + # subdivision mesh geometry, for performance. + # Dynamically masked faces (eg. using this method) are not excluded + # from the subdivision mesh and simply masked, allowing faster + # changes to the face mask without requiring a rebuild of the + # subdivision mesh. + self.__subdivisionMesh.changeFaceMask(faceMask) + self.__subdivisionMesh.updateIndexBufferFaces() + + # Mask proxy and subdivided proxy mesh + if self.__proxyMesh: + import proxy + + # Transfer face mask to proxy + proxyVertMask = proxy.transferVertexMaskToProxy(vertsMask, self.proxy) + proxyFaceMask = self.__proxyMesh.getFaceMaskForVertices( + np.argwhere(proxyVertMask)[..., 0] + ) + + self.__proxyMesh.changeFaceMask(proxyFaceMask) + self.__proxyMesh.updateIndexBufferFaces() + + if self.__proxySubdivisionMesh: + self.__proxySubdivisionMesh.changeFaceMask(proxyFaceMask) + self.__proxySubdivisionMesh.updateIndexBufferFaces() + + ## + # Material properties + ## + + def setTexture(self, path): + """ + This method is used to specify the path of a file on disk containing the object texture. + + :param path: The path of a texture file. + :type path: str + :param cache: The texture cache to use. + :type cache: dict + """ + self.material.diffuseTexture = path + + def getTexture(self): + return self.material.diffuseTexture + + texture = property(getTexture, setTexture) + + def clearTexture(self): + """ + This method is used to clear an object's texture. + """ + self.material.diffuseTexture = None + + def hasTexture(self): + return self.texture is not None + + def setShader(self, shader): + """ + This method is used to specify the shader. + + :param shader: The path to a pair of shader files. + :type shader: string + """ + self.material.setShader(shader) + + def getShader(self): + return self.material.shader + + shader = property(getShader, setShader) + + @property + def shaderObj(self): + return self.material.shaderObj + + def configureShading( + self, diffuse=None, bump=None, normal=None, displacement=None, spec=None, vertexColors=None + ): + """ + Configure shader options and set the necessary properties based on + the material configuration of this object. + This can be done without an actual shader being set for this object. + Call this method when changes are made to the material property. + """ + self.material.configureShading(diffuse, bump, normal, displacement, spec, vertexColors) + + def getMaterial(self): + return self._material + + def setMaterial(self, material): + if self.material.uvMap != material.uvMap: + # UV map has changed + self.setUVMap(material.uvMap) + self._material.copyFrom(material) + + material = property(getMaterial, setMaterial) + + def setShaderParameter(self, name, value): + """ + Updates the shader parameters. + """ + self.material.setShaderParameter(name, value) + + @property + def shaderParameters(self): + return self.material.shaderParameters + + @property + def shaderConfig(self): + return self.material.shaderConfig + + @property + def shaderDefines(self): + return self.material.shaderDefines + + def addShaderDefine(self, defineStr): + self.material.addShaderDefine(defineStr) + + def removeShaderDefine(self, defineStr): + self.material.removeShaderDefine(defineStr) + + def clearShaderDefines(self): + self.material.clearShaderDefines() + + def setShadeless(self, shadeless): + """ + This method is used to specify whether or not the object is affected by lights. + This is used for certain GUI controls to give them a more 2D type + appearance (predominantly the top bar of GUI controls). + + NOTE enabling this option disables the use of the shader configured in the material. + + :param shadeless: Whether or not the object is unaffected by lights. + :type shadeless: Boolean + """ + self.material.shadeless = shadeless + + def getShadeless(self): + return self.material.shadeless + + shadeless = property(getShadeless, setShadeless) + + def setDepthless(self, depthless): + """ + This method is used to specify whether or not the object occludes or is occluded + by other objects + + :param depthless: Whether or not the object is occluded or occludes. + :type depthless: Boolean + """ + self.material.depthless = depthless + + def getDepthless(self): + return self.material.depthless + + depthless = property(getDepthless, setDepthless) + + def setSolid(self, solid): + """ + This method is used to specify whether or not the object is drawn solid or wireframe. + + :param solid: Whether or not the object is drawn solid or wireframe. + :type solid: Boolean + """ + self.material.wireframe = not solid + + def isSolid(self): + return self.solid + + def getSolid(self): + return not self.material.wireframe + + solid = property(getSolid, setSolid) + + def setCull(self, cull): + """ + This method is used to specify whether or not the object is back-face culled. + + :param cull: Whether and how to cull + :type cull: 0 => no culling, >0 => draw front faces, <0 => draw back faces + """ + + # Because we don't really need frontface culling, we simplify to only backface culling + if (isinstance(cull, bool) and cull) or cull > 0: + self.material.backfaceCull = True + else: + self.material.backfaceCull = False + + def getCull(self): + # Because we don't really need frontface culling, we simplify to only backface culling + if self.material.backfaceCull: + return 1 + else: + return 0 + + cull = property(getCull, setCull) + + def getAlphaToCoverage(self): + return self.material.alphaToCoverage + + def setAlphaToCoverage(self, a2cEnabled): + self.material.alphaToCoverage = a2cEnabled + + alphaToCoverage = property(getAlphaToCoverage, setAlphaToCoverage) + + def setUVMap(self, filename): + subdivided = self.isSubdivided() + + if subdivided: + # Re-generate the subdivided mesh + self.setSubdivided(False) + + # Remove stale subdivision cache if present + self.__subdivisionMesh = None + + # Set uv map on original, unsubdivided, unproxied mesh + self._setMeshUVMap(filename, self.__seedMesh) + + if self.isProxied(): + # TODO transfer UV coordinates to proxy mesh + pass + + if subdivided: + # Re-generate the subdivided mesh with new UV coordinates + self.setSubdivided(True) + + def onMouseDown(self, event): + if self.view: + self.view.callEvent("onMouseDown", event) + else: + import log + + log.debug("FAILED: mouseDown") + + def onMouseMoved(self, event): + if self.view: + self.view.callEvent("onMouseMoved", event) + else: + import log + + log.debug("FAILED: mouseMoved") + + def onMouseDragged(self, event): + if self.view: + self.view.callEvent("onMouseDragged", event) + else: + import log + + log.debug("FAILED: mouseDragged") + + def onMouseUp(self, event): + if self.view: + self.view.callEvent("onMouseUp", event) + + def onMouseEntered(self, event): + if self.view: + self.view.callEvent("onMouseEntered", event) + else: + import log + + log.debug("FAILED: mouseEntered") + + def onMouseExited(self, event): + if self.view: + self.view.callEvent("onMouseExited", event) + else: + import log + + log.debug("FAILED: mouseExited") + + def onClicked(self, event): + if self.view: + self.view.callEvent("onClicked", event) + else: + import log + + log.debug("FAILED: clicked") + + def onMouseWheel(self, event): + if self.view: + self.view.callEvent("onMouseWheel", event) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/module3d.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/module3d.py new file mode 100644 index 0000000000000000000000000000000000000000..e2dc87a20ef1eb882b0c94a59c31881033431edf --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/module3d.py @@ -0,0 +1,1307 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Marc Flerackers, Glynn Clements, Jonas Hauquier + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +TODO +""" + +import weakref + +# import material +import library.log as log +import numpy as np + +# import unique # Bugfix for numpy.unique on older numpy versions + + +class FaceGroup(object): + """ + A FaceGroup (a group of faces with a unique name). + + Each Face object can be part of one FaceGroup. Each face object has an + attribute, *group*, storing the FaceGroup it is a member of. + + The FaceGroup object contains a list of the faces in the group and must be + kept in sync with the FaceGroup references stored by the individual faces. + + .. py:attribute:: name + + The name. str + + .. py:attribute:: parent + + The parent. :py:class:`module3d.Object3D` + + :param name: The name of the group. + :type name: str + """ + + black = np.zeros(3, dtype=np.uint8) + + def __init__(self, object, name, idx): + self.object = object + self.name = name + self.idx = idx + self.color = None + self.colorID = self.black.copy() + + def __str__(self): + """ + This method returns a string containing the name of the FaceGroup. This + method is called when the object is passed to the 'print' function. + + **Parameters:** This method has no parameters. + + """ + return "facegroup %s" % self.name + + def setColor(self, rgba): + self.color = np.asarray(rgba, dtype=np.uint8) + + def getObject(self): + if self.__object: + return self.__object() + else: + return None + + def setObject(self, value): + if value is None: + self.__object = None + else: + # Ensure link to gui3d.object is weak to avoid circular references (which break garbage collection) + self.__object = weakref.ref(value) + + object = property(getObject, setObject) + + @property + def parent(self): + return self.object + + +class Object3D(object): + def __init__(self, objName, vertsPerPrimitive=4): + self.clear() + + self.name = objName + self.vertsPerPrimitive = vertsPerPrimitive + self._faceGroups = [] + self._groups_rev = {} + self.cameraMode = 0 + self._visibility = True + self.pickable = False + self.calculateTangents = True # TODO disable when not needed by shader + self.object3d = None + self._priority = 0 + self.MAX_FACES = 8 + + # Cache used for retrieving vertex colors multiplied with material diffuse color + self._old_diff = None + self._r_color_diff = None + + self.__object = None + + def clone( + self, scale=1.0, filterMaskedVerts=False + ): # TODO it's also possible to add offset to the parameters + """ + Create a clone of this mesh, with adapted scale. + If filterVerts is True, all vertices that are not required (do not + belong to any visible face) are removed and vertex mapping is added to + cloned object (see filterMaskedVerts()). For a face mapping, the + facemask of the original mesh can be used. + + By default cloning a mesh links it to the object of its parent, remove + the link by setting other.object to None before attaching it to a new + object. + """ + if self.getFaceCount(excludeMaskedFaces=filterMaskedVerts) == 0: + raise RuntimeError( + "Error cloning mesh %s. Cannot clone a mesh with 0 (unmasked) faces!", self.name + ) + + other = type(self)(self.name, self.vertsPerPrimitive) + + for prop in [ + "cameraMode", + "visibility", + "pickable", + "calculateTangents", + "priority", + "MAX_FACES", + "object", + ]: + setattr(other, prop, getattr(self, prop)) + + for fg in self.faceGroups: + ofg = other.createFaceGroup(fg.name) + if fg.color is not None: + ofg.color = fg.color.copy() + else: + ofg.color = fg.color + + if filterMaskedVerts: + self.filterMaskedVerts(other, update=False) + if scale != 1: + other.coord = scale * other.coord + else: + other.setCoords(scale * self.coord) + other.setColor(self.color.copy()) + other.setUVs(self.texco.copy()) + other.setFaces(self.fvert.copy(), self.fuvs.copy(), self.group.copy()) + other.changeFaceMask(self.face_mask.copy()) + + other.calcNormals() + other.updateIndexBuffer() + + return other + + def transformed(self, transform_mat, filterMaskedVerts=False): + """Create a clone of this mesh with its coordinates transformed + with the specified transformation matrix. filterMaskedVerts works the + same is for clone() + """ + if transform_mat.shape == (4, 4): + translation = transform_mat[:3, 3] + transform_mat = transform_mat[:3, :3] + else: + translation = np.zeros(3, dtype=np.float32) + + result = self.clone(filterMaskedVerts=filterMaskedVerts) + + coords = np.dot(transform_mat, result.getCoords().T).T + coords += translation + result.changeCoords(coords) + result.calcNormals() + result.update() + return result + + @property + def parent_map(self): + """ + Maps vertex indices from this mesh to its original parent mesh + (self.parent). This happens recursively to the topmost parent. + + Forward vertex mapping (self -> self.parent): + parent_map[idx] = mIdx: self.coord[idx] -> self.parent.coord[mIdx] + + Will return a (n, self.MAX_FACES) array if this chain of meshes + contains a subdivided mesh. + + Note that vertex maps only support one subdivision in a chain of mesh + to parent meshes. + """ + if not hasattr(self, "parent") or not self.parent: + return None + + if not hasattr(self, "_parent_map"): + mapping = np.arange(self.getVertexCount(), dtype=np.uint32) + else: + mapping = self._parent_map + + # Traverse to parent + pmap = self.parent.parent_map + if pmap is None: + return mapping + else: + # Combine mappings to topmost parent + return pmap[mapping] + + @property + def parent_map_weights(self): + return np.ones(self.getVertexCount(), dtype=np.float32) + + @property + def inverse_parent_map(self): + """ + Maps vertex indices from original parent mesh (self.parent) to + this mesh (-1 if vertex is removed in this mesh). + This happens recursively to the topmost parent. + + Reverse vertex mapping: + inverse_parent_map[idx] = mIdx: self.parent.coord[idx] -> self.coord[mIdx] + + Will return a (n, 1+self.MAX_FACES*2) array if this chain of meshes + contains a subdivided mesh. + + Note that vertex maps only support one subdivision in a chain of mesh + to parent meshes. + """ + # TODO will require nxn matrix if subdivided (catmull-clark module) + + if not hasattr(self, "parent") or not self.parent: + return None + + if not hasattr(self, "_inverse_parent_map"): + mapping = np.arange(self.parent.getVertexCount(), dtype=np.int32) + else: + mapping = self._inverse_parent_map + + # Traverse to parent + pmap = self.parent.inverse_parent_map + if pmap is None: + return mapping + else: + # Combine mappings to topmost parent + if len(mapping.shape) > 1: + shape = (len(pmap), mapping.shape[1]) + else: + shape = len(pmap) + result = -np.ones(shape, dtype=np.int32) + idx = np.where(pmap > -1) + result[idx] = mapping[pmap[idx]] + return result + + def filterMaskedVerts(self, other, update=True): + """ + Set the vertices, faces and vertex attributes of other object to the + vertices and faces of this mesh object, with the hidden faces and + vertices filtered out. + + The other mesh contains a parent_map which maps vertex indices from + the other to its original mesh and inverse_parent_map which maps vertex + indexes from original to other (-1 if removed). + + other.parent is set to the original mesh. + """ + # TODO or build a chain of parents? + if hasattr(self, "parent") and self.parent: + other.parent = self.parent + else: + other.parent = self + + # Forward vertex mapping: + # _parent_map[idx] = mIdx: other.coord[idx] -> self.coord[mIdx] + other._parent_map = np.unique(self.getVerticesForFaceMask(self.face_mask)) + + # Reverse vertex mapping: + # _inverse_parent_map[idx] = mIdx: self.coord[idx] -> other.coord[mIdx] + other._inverse_parent_map = -np.ones(self.getVertexCount(), dtype=np.int32) + other._inverse_parent_map[other.parent_map] = np.arange( + len(other._parent_map), dtype=np.int32 + ) + # other._inverse_parent_map = np.ma.masked_less(other._inverse_parent_map, 0) # TODO might be useful + + other.setCoords(self.coord[other.parent_map]) + other.setColor(self.color[other.parent_map]) + + # Filter out and remap masked faces + fvert = self.fvert[self.face_mask] + for i in range(self.vertsPerPrimitive): + fvert[:, i] = other._inverse_parent_map[fvert[:, i]] + + # Filter out and remap unused UVs + fuvs = self.fuvs[self.face_mask] + uv_idx = np.unique(fuvs.reshape(-1)) + inverse_uv_idx = -np.ones(self.texco.shape[0], dtype=np.int32) + inverse_uv_idx[uv_idx] = np.arange(uv_idx.shape[0], dtype=np.int32) + for i in range(self.vertsPerPrimitive): + fuvs[:, i] = inverse_uv_idx[fuvs[:, i]] + + other.setUVs(self.texco[uv_idx]) + + other.setFaces(fvert, fuvs, self.group[self.face_mask]) + + if update: + other.calcNormals() + other.updateIndexBuffer() + + def getCenter(self): + """ + Get center position of mesh using center of its bounding box. + """ + bBox = self.calcBBox() + bmin = np.asarray(bBox[0], dtype=np.float32) + bmax = np.asarray(bBox[1], dtype=np.float32) + return -(bmin + ((bmax - bmin) / 2)) + + def calcFaceNormals(self, ix=None): + """ + Calculate the face normals. A right-handed coordinate system is assumed, + which requires mesh faces to be defined with counter clock-wise vertex order. + Face normals are not normalized. + + Faces are treated as if they were triangles (using only the 3 first verts), + so for quads with non co-planar points, inaccuracies may occur (even though + those have a high change of being corrected by neighbouring faces). + """ + # We assume counter clock-wise winding order + # (if your normals are inversed, you're using clock-wise winding order) + if ix is None: + ix = np.s_[:] + fvert = self.coord[self.fvert[ix]] + v1 = fvert[:, 0, :] + v2 = fvert[:, 1, :] + v3 = fvert[:, 2, :] + va = v1 - v2 + vb = v2 - v3 + self.fnorm[ix] = np.cross(va, vb) + + def calcVertexNormals(self, ix=None): + """ + Calculate per-vertex normals from the face normals for smooth shading + the model. Requires face normals to be calculated first. + """ + self.markCoords(ix, norm=True) + if ix is None: + ix = np.s_[:] + + vface = self.vface[ix] + norms = self.fnorm[vface] + norms *= np.arange(self.MAX_FACES)[None, :, None] < self.nfaces[ix][:, None, None] + norms = np.sum(norms, axis=1) + norms /= np.sqrt(np.sum(norms**2, axis=-1))[:, None] + self.vnorm[ix] = norms + + def calcVertexTangents(self, ix=None): + """ + Calculate vertex tangents using Lengyel’s Method. + """ + if not self.has_uv: + return + self.markCoords(ix, norm=True) + if ix is None: + ix = np.s_[:] + xLen = self.getVertexCount() + f_ix = np.s_[:] + else: + xLen = len(ix) + f_ix = np.unique(self.vface[ix]) + + # This implementation is based on + # http://www.terathon.com/code/tangent.html + + tan = np.zeros((xLen, 2, 3), dtype=np.float32) + + fvert = self.coord[self.fvert[f_ix]] + v1 = fvert[:, 0, :] + v2 = fvert[:, 1, :] + v3 = fvert[:, 2, :] + + x1 = v2[:, 0] - v1[:, 0] + x2 = v3[:, 0] - v1[:, 0] + y1 = v2[:, 1] - v1[:, 1] + y2 = v3[:, 1] - v1[:, 1] + z1 = v2[:, 2] - v1[:, 2] + z2 = v3[:, 2] - v1[:, 2] + + fuv = self.texco[self.fuvs[f_ix]] + w1 = fuv[:, 0, :] + w2 = fuv[:, 1, :] + w3 = fuv[:, 2, :] + + s1 = w2[:, 0] - w1[:, 0] + s2 = w3[:, 0] - w1[:, 0] + t1 = w2[:, 1] - w1[:, 1] + t2 = w3[:, 1] = w1[:, 1] + + # Prevent NANs because of borked up UV coordinates # TODO perhaps remove this + s1[np.argwhere(np.equal(s1, 0.0))] = 0.0000001 + s2[np.argwhere(np.equal(s2, 0.0))] = 0.0000001 + t1[np.argwhere(np.equal(t1, 0.0))] = 0.0000001 + t2[np.argwhere(np.equal(t2, 0.0))] = 0.0000001 + + r = np.repeat(1.0, len(s1)) / ((s1 * t2) - (s2 * t1)) + sdir = np.zeros((self.getFaceCount(), 3), dtype=np.float32) + tdir = np.zeros((self.getFaceCount(), 3), dtype=np.float32) + sdir[f_ix] = np.column_stack( + [((t2 * x1) - (t1 * x2)) * r, ((t2 * y1) - (t1 * y2)) * r, ((t2 * z1) - (t1 * z2)) * r] + ) + tdir[f_ix] = np.column_stack( + [((s1 * x2) - (s2 * x1)) * r, ((s1 * y2) - (s2 * y1)) * r, ((s1 * z2) - (s2 * z1)) * r] + ) + + tan[:, 0] = np.sum(sdir[self.vface[ix]]) + tan[:, 1] = np.sum(tdir[self.vface[ix]]) + + # Gramm-Schmidt orthogonalize + dotP = dot_v3(self.vnorm[ix], tan[:, 0]) + # Duplicate dot product value in 3 columns because scalar * (n x 3) + # does not work + dotP = np.tile(dotP, (3, 1)).transpose().reshape(len(tan), 3) + self.vtang[ix, :3] = tan[:, 0] - dotP * self.vnorm[ix] + # Normalize + self.vtang[ix, :3] /= np.sqrt(np.sum(self.vtang[ix, :3] ** 2, axis=-1))[:, None] + + # Determine Handedness as w parameter + self.vtang[ix, 3] = 1.0 + indx = np.argwhere(np.less(dot_v3(np.cross(self.vnorm[ix], tan[:, 0]), tan[:, 1]), 0.0)) + self.vtang[ix, 3][indx] = -1.0 + + def getObject(self): + if self.__object: + return self.__object() + else: + return None + + def setObject(self, value): + if value is None: + self.__object = None + else: + # Ensure link to gui3d.object is weak to avoid circular references (which break garbage collection) + self.__object = weakref.ref(value) + + object = property(getObject, setObject) + + @property + def faceGroups(self): + return iter(self._faceGroups) + + @property + def faceGroupCount(self): + return len(self._faceGroups) + + def clear(self): + """ + Clears both local and remote data to repurpose this object + """ + + # Clear remote data + self._faceGroups = [] + + self._transparentPrimitives = 0 + + # Reference to vertex attributes (coordinate, normal, color, tang) that form the faces (idx = face idx) + self.fvert = [] + # Stores the face normal of the faces (idx = face idx) + self.fnorm = [] + # References to UVs at the verts of the faces (idx = face idx) + # (NOTE: UVs are not tied to vertex IDs, and are not necessarily + # uniform per vertex, like the other attributes!) + self.fuvs = [] + self.group = [] # Determines facegroup per face (idx = face idx) + self.face_mask = [] # Determines visibility per face (idx = face idx) + + self.texco = [] # UV coordinates (idx = uv idx) + + self.coord = [] # Vertex coordinates (positions) (idx = vertex idx) + self.vnorm = [] # Vertex normals (idx = vertex idx) + self.vtang = [] # Vertex tangents (idx = vertex idx) + self.color = [] # Vertex colors (idx = vertex idx) + self.vface = ( + [] + ) # References the faces that a vertex belongs to (limited to MAX_FACES) (idx = vertex idx) + self.nfaces = 0 # Polycount + + self.ucoor = False # Update flags for updating to OpenGL renderbuffers + self.unorm = False + self.utang = False + self.ucolr = False + self.utexc = False + + self.has_uv = False + + if hasattr(self, "index"): + del self.index + if hasattr(self, "grpix"): + del self.grpix + + # Maps unwelded vertices back to original welded ones (idx = unwelded vertex idx) + self.vmap = None + # Maps unwelded vertex texture (UV) coordinates back to original ones (idx = unwelded vertex idx) + self.tmap = None + + # Cached inverse of vmap: maps original welded vert idx (coord) to one or multiple unwelded + # vert idxs (r_coord) + self._inverse_vmap = None + + # Unwelded vertex buffers used by OpenGL + if hasattr(self, "r_coord"): + del self.r_coord + if hasattr(self, "r_texco"): + del self.r_texco + if hasattr(self, "r_vnorm"): + del self.r_vnorm + if hasattr(self, "r_vtang"): + del self.r_vtang + if hasattr(self, "r_color"): + del self.r_color + if hasattr(self, "r_faces"): + del self.r_faces + + def setCoords(self, coords): + nverts = len(coords) + self.coord = np.asarray(coords, dtype=np.float32) + self.vnorm = np.zeros((nverts, 3), dtype=np.float32) + self.vtang = np.zeros((nverts, 4), dtype=np.float32) + self.color = np.zeros((nverts, 4), dtype=np.uint8) + 255 + self.vface = np.zeros((nverts, self.MAX_FACES), dtype=np.uint32) + self.nfaces = np.zeros(nverts, dtype=np.uint8) + + self.orig_coord = self.coord.copy() # Keep a copy of the original coordinates + + self.ucoor = True + self.unorm = True + self.utang = True + self.ucolr = True + + self.markCoords(None, True, True, True) + + def getVertexCount(self, excludeMaskedVerts=False): + # return len(self.vface) + if excludeMaskedVerts: + return np.count_nonzero(self.getVertexMaskForFaceMask(self.getFaceMask())) + return len(self.coord) + + def getCoords(self, indices=None): + if indices is None: + indices = np.s_[...] + return self.coord[indices] + + def getNormals(self, indices=None): + if indices is None: + indices = np.s_[...] + return self.vnorm[indices] + + def markCoords(self, indices=None, coor=False, norm=False, colr=False): + if isinstance(indices, tuple): + indices = indices[0] + + nverts = len(self.coord) + + if coor: + if indices is None: + self.ucoor = True + else: + if self.ucoor is False: + self.ucoor = np.zeros(nverts, dtype=bool) + if self.ucoor is not True: + self.ucoor[indices] = True + + if norm: + if indices is None: + self.unorm = self.utang = True + else: + if self.unorm is False: + self.unorm = self.utang = np.zeros(nverts, dtype=bool) + if self.unorm is not True: + self.unorm[indices] = True + self.utang[indices] = True + + if colr: + if indices is None: + self.ucolr = True + else: + if self.ucolr is False: + self.ucolr = np.zeros(nverts, dtype=bool) + if self.ucolr is not True: + self.ucolr[indices] = True + + def changeCoords(self, coords, indices=None): + self.markCoords(indices, coor=True) + + if indices is None: + indices = np.s_[...] + self.coord[indices] = coords + + def setUVs(self, uvs): + self.texco = np.asarray(uvs, dtype=np.float32) + self.utexc = True + + def getUVCount(self): + return len(self.texco) + + def getUVs(self, indices=None): + if indices is None: + indices = np.s_[...] + return self.texco[indices] + + def markUVs(self, indices=None): + if isinstance(indices, tuple): + indices = indices[0] + + ntexco = len(self.texco) + + if indices is None: + self.utexc = True + else: + if self.utexc is False: + self.utexc = np.zeros(ntexco, dtype=bool) + if self.utexc is not True: + self.utexc[indices] = True + + def setFaces(self, verts, uvs=None, groups=None, skipUpdate=False): + nfaces = len(verts) + + self.fvert = np.empty((nfaces, self.vertsPerPrimitive), dtype=np.uint32) + self.fnorm = np.zeros((nfaces, 3), dtype=np.float32) + self.fuvs = np.zeros(self.fvert.shape, dtype=np.uint32) + self.group = np.zeros(nfaces, dtype=np.uint16) + self.face_mask = np.ones(nfaces, dtype=bool) + + # preset number of vertices for all export formats to 4 + self.vertsPerFaceForExport = 4 + if nfaces != 0: + + # evaluate if we have 3 or 4 vertices per face, do it here so it works for npz or obj file + if len(verts[0]) == 4 and verts[0][0] == verts[0][3]: + self.vertsPerFaceForExport = 3 + + self.fvert[...] = verts + if uvs is not None: + self.fuvs[...] = uvs + if groups is not None: + self.group[...] = groups + + self.has_uv = uvs is not None + + if not skipUpdate: + self._update_faces(resize=True) + + def changeFaceMask(self, mask, indices=None): + if indices is None: + indices = np.s_[...] + self.face_mask[indices] = mask + + def getFaceMask(self, indices=None): + if indices is None: + indices = np.s_[...] + return self.face_mask[indices] + + def hasUVs(self): + return self.has_uv + + def getFaceCount(self, excludeMaskedFaces=False): + if excludeMaskedFaces: + return np.count_nonzero(self.getFaceMask()) + return len(self.fvert) + + def getFaceVerts(self, indices=None): + if indices is None: + indices = np.s_[...] + return self.fvert[indices] + + def getFaceUVs(self, indices=None): + if indices is None: + indices = np.s_[...] + return self.fuvs[indices] + + @property + def inverse_vmap(self): + """ + The inverse of vmap: a mapping of original welded (relating to UVs) + vertex (coord indices) to a set of unwelded vertices that represent the + same coordinate (r_coord indices). + """ + if self._inverse_vmap is None: + # TODO this loop is quite slow and could benefit from numpy optimization + originalToUnweldedMap = {} + for unweldedIdx, originalIdx in enumerate(self.vmap): + if originalIdx not in originalToUnweldedMap: + originalToUnweldedMap[originalIdx] = [] + originalToUnweldedMap[originalIdx].append(unweldedIdx) + self._inverse_vmap = originalToUnweldedMap + return self._inverse_vmap + + def _update_faces(self, resize=False): + # + # this procedure is only called, when geometry is not taken from npz-file + # + # create an 2dim array self.vface for each vertex + # which contains an array of faces, where the vertex belongs to, maximum of + # the array inside is self.MAX_FACES + # + # use self.nfaces as counter for the inner array, it is needed afterwards + + nverts = len(self.coord) + self.nfaces = np.zeros(nverts, dtype=np.uint8) # reset the counters to zero + + for idx, vert in enumerate(self.fvert): # contains faces with vertex number + for i in range( + 0, min(len(vert), self.vertsPerFaceForExport) + ): # use minimum of attached vertices, works for less than 3 also + vn = vert[i] # vertex.number + if self.nfaces[vn] >= self.MAX_FACES: + log.error( + "Failed to index faces of mesh %s, you are probably loading a mesh " + "with mixed nb of verts per face (do not mix tris and quads). " + "Or your mesh has too many faces attached to one vertex " + "(the maximum is %s-poles). In the second case, either increase " + "MAX_FACES for this mesh, or improve the mesh topology.", + self.name, + self.MAX_FACES, + ) + raise RuntimeError("Incompatible mesh topology.") + return + self.vface[vn, self.nfaces[vn]] = ( + idx # add the index of the face to the array, row given by vn, column by counter nfaces[vn] + ) + self.nfaces[vn] += 1 # now increment the counter + + imax = i + 1 # just needed later not to be recalculated. + + # in case this function is not called from catmull-clark function resize the self.vface to a minimum + if resize is True: + # now lets recalculate the maximum number of faces belonging to a plane + newmax = np.max(self.nfaces) + if ( + newmax > 2 + ): # Avoid the information when function calculates internal objects not to confuse users + log.debug("Calculated maximum number of faces for one vertex: %d", newmax) + + # unfortunately catmull-clark expects maxpoles and not maxfaces, so we need + # also to calculate max-poles + # + # for each vertex we have to check all attached faces, these faces are already collected in self.vface + # when we check all the faces we will collect the neighbors using a modulo function, the vertices are + # entered clockwise ... modulo allows us to use neighbor of 1 and 3 when index is 0 + # if not already existent, the neighbors are added to an array and the maximum size of this array will + # be maxpole + + maxpole = 0 + for vn, row in enumerate(self.vface): + noticed = np.zeros(self.MAX_FACES * 4, dtype=int) + m = 0 + for j in range(0, self.nfaces[vn]): + # collect neighbors + face = row[j] + for ix, v2 in enumerate(self.fvert[face]): + if v2 == vn: + ln = self.fvert[face][(ix - 1) % imax] + rn = self.fvert[face][(ix + 1) % imax] + if ln not in noticed: + noticed[m] = ln + m += 1 + if rn not in noticed: + noticed[m] = rn + m += 1 + break + if m > maxpole: + maxpole = m + + if ( + maxpole > 2 + ): # Avoid the information when function calculates internal objects not to confuse users + log.debug("Calculated maximum number of poles for one vertex: %d", maxpole) + + if newmax < maxpole: + newmax = maxpole + + # keep in mind that a maximum number of neighboring faces lower than 4 will crash subdiv + # (try to load a cube) + if newmax < 4: + newmax = 4 + + if newmax != self.MAX_FACES: + # it is different so resize vface + self.vface = np.delete(self.vface, np.s_[newmax::], 1) + self.MAX_FACES = newmax + + def getVertexWeights(self, parentWeights): + """ + Map armature weights mapped to the root parent (original mesh) to this + child mesh. Returns parentWeights unaltered if this mesh has no parent. + If this is a proxy mesh, parentWeights should be the weights mapped + through the proxy.getVertexWeights() method first. + + This particular vertex weights mapping is only used for exporting rigged + meshes, as in MakeHuman only unsubdivided meshes are posed, and then + smoothed in their posed state if required. Vertices are not removed + within MH when faces are hidden, either. + """ + if not hasattr(self, "parent") or not self.parent: + return parentWeights + + vmap = self.inverse_parent_map + vwmap = self.parent_map_weights + + from collections import OrderedDict + + weights = OrderedDict() + for bname, (verts, wghts) in list(parentWeights.data.items()): + vgroup = [] + empty = True + for v, wt in zip(verts, wghts): + mvs = vmap[v] + if isinstance(mvs, (int, np.int32)): + mvs = [mvs] + for mv in mvs: + w = vwmap[mv] + if mv > -1: + vgroup.append((mv, w * wt)) + empty = False + if not empty: + weights[bname] = vgroup + + return parentWeights.create(weights, self.getVertexCount()) + + def updateIndexBuffer(self): + self.updateIndexBufferVerts() + self.updateIndexBufferFaces() + + def updateIndexBufferVerts(self): + packed = self.fvert.astype(np.uint64) << 32 + packed |= self.fuvs + packed = packed.reshape(-1) + + u, rev = np.unique(packed, return_inverse=True) + del packed + + unwelded = u[:, None] >> np.array([[32, 0]], dtype=np.uint64) + unwelded = unwelded.astype(np.uint32) + nverts = len(unwelded) + iverts = rev.reshape(self.fvert.shape) + del rev, u + + self.vmap = unwelded[:, 0] + self.tmap = unwelded[:, 1] + self._inverse_vmap = None + del unwelded + + self.r_coord = np.empty((nverts, 3), dtype=np.float32) + self.r_texco = np.empty((nverts, 2), dtype=np.float32) + self.r_vnorm = np.zeros((nverts, 3), dtype=np.float32) + self.r_vtang = np.zeros((nverts, 4), dtype=np.float32) + self.r_color = np.zeros((nverts, 4), dtype=np.uint8) + 255 + + self.r_faces = np.array(iverts, dtype=np.uint32) + + def updateIndexBufferFaces(self): + index = self.r_faces[self.face_mask] + group = self.group[self.face_mask] + + if len(group) > 0: + order = np.argsort(group) + group = group[order] + index = index[order] + + group, start = np.unique(group, return_index=True) + count = np.empty(len(start), dtype=np.uint32) + count[:-1] = start[1:] - start[:-1] + count[-1] = len(index) - start[-1] + + grpix = np.zeros((max(self.group) + 1, 2), dtype=np.uint32) + grpix[group, 0] = start + grpix[group, 1] = count + else: + grpix = np.zeros((0, 2), dtype=np.uint32) + + self.index = index + self.grpix = grpix + + self.ucoor = True + self.unorm = True + self.utang = True + self.ucolr = True + self.utexc = True + self.sync_all() + + def sync_coord(self): + if self.ucoor is False: + return + if self.vmap is None or len(self.vmap) == 0: + return + if self.ucoor is True: + self.r_coord[...] = self.coord[self.vmap] + else: + self.r_coord[self.ucoor[self.vmap]] = self.coord[self.vmap][self.ucoor[self.vmap]] + self.ucoor = False + + def sync_norms(self): + if self.unorm is False: + return + if self.vmap is None or len(self.vmap) == 0: + return + if self.unorm is True: + self.r_vnorm[...] = self.vnorm[self.vmap] + else: + self.r_vnorm[self.unorm[self.vmap]] = self.vnorm[self.vmap][self.unorm[self.vmap]] + self.unorm = False + + def sync_tangents(self): + if not self.has_uv: + return + if self.utang is False: + return + if self.vmap is None or len(self.vmap) == 0: + return + if self.utang is True: + self.r_vtang[...] = self.vtang[self.vmap] + else: + self.r_vtang[self.utang[self.vmap]] = self.vtang[self.vmap][self.utang[self.vmap]] + self.utang = False + + def sync_color(self): + if self.ucolr is False: + return + if self.vmap is None or len(self.vmap) == 0: + return + if self.ucolr is True: + self.r_color[...] = self.color[self.vmap] + else: + self.r_color[self.ucolr[self.vmap]] = self.color[self.vmap][self.ucolr[self.vmap]] + self.ucolr = False + self._r_color_diff = None + + def sync_texco(self): + if not self.has_uv: + return + if self.utexc is False: + return + if self.tmap is None or len(self.tmap) == 0: + return + if self.utexc is True: + self.r_texco[...] = self.texco[self.tmap] + else: + self.r_texco[self.utexc[self.tmap]] = self.texco[self.tmap][self.utexc[self.tmap]] + self.utexc = False + + def sync_all(self): + self.sync_coord() + self.sync_norms() + if self.calculateTangents: + self.sync_tangents() + self.sync_color() + self.sync_texco() + + def createFaceGroup(self, name): + """ + Creates a new module3d.FaceGroup with the given name. + + :param name: The name for the face group. + :type name: [float, float, float] + :return: The new face group. + :rtype: :py:class:`module3d.FaceGroup` + """ + idx = len(self._faceGroups) + fg = FaceGroup(self, name, idx) + self._groups_rev[name] = fg + self._faceGroups.append(fg) + return fg + + def setColor(self, color): + """ + Sets the vertex colors for the entire object. + + :param color: The color in rgba. + :type color: [byte, byte, byte, byte] + """ + color = np.asarray(color, dtype=np.uint8) + if len(color.shape) == 1: # One color for all vertices + if len(color) == 3: + # Add alpha component to simple RGB color + color = list(color) + [255] + self.color[:] = color + else: + self.color[...] = color[None, :] + self.markCoords(colr=True) + self.sync_color() + + @property + def r_color_diff(self): + """ + Vertex colors multiplied with the diffuse material color. + """ + if self._r_color_diff is None: + self._r_color_diff = np.zeros(self.r_color.shape, dtype=np.uint8) + self._old_diff = None + + diff = self.material.diffuseColor.values + [self.material.opacity] + if diff != self._old_diff: + # Update diffuse * vertex colors + self._r_color_diff[:] = diff * self.r_color + self._old_diff = diff + return self._r_color_diff + + @property + def visibility(self): + return self._visibility + + def setVisibility(self, visible): + self.visibility = visible + + @visibility.setter + def visibility(self, visible): + """ + This method sets the visibility of the object. + + :param visible: Whether or not the object is visible. + :type visible: Boolean + """ + self._visibility = visible + + def setPickable(self, pickable): + """ + This method sets the pickable flag of the object. + + :param pickable: Whether or not the object is pickable. + :type pickable: Boolean + """ + + self.pickable = pickable + + def getPriority(self): + """ + The rendering priority of this object. + Objects with higher priorities will be drawn later. + + Common priorities used: + file description 2D/3D priority + + core/mhmain.py background-gradient 2D -200 + 0_modeling_background.py background 2D -90 + core/mhmain.py human 3D 0 + 3_libraries_clothes_chooser.py clothing 3D 10 + 3_libraries_polygon_hair_chooser.py hair 3D 20 + 2_posing_armature.py armature 3D 30 + 0_modeling_a_measurement.py measureMesh 2D 50 + 5_settings_censor.py censor rectangles 2D 80 + apps/gui/guifiles.py black frame 2D 90 + """ + return self._priority + + def setPriority(self, priority): + """ + Set the rendering priority of this object. + Objects with higher priorities will be drawn later. + + Common priorities used: + file description 2D/3D priority + + 0_modeling_background.py background 2D -90 + core/mhmain.py human 3D 0 + 3_libraries_clothes_chooser.py clothing 3D 10 + 3_libraries_polygon_hair_chooser.py hair 3D 20 + 2_posing_armature.py armature 3D 30 + 0_modeling_a_measurement.py measureMesh 2D 50 + 5_settings_censor.py censor rectangles 2D 80 + apps/gui/guifiles.py black frame 2D 90 + """ + self._priority = priority + + priority = property(getPriority, setPriority) + + @property + def material(self): + if not self.object and hasattr(self, "parent"): + return self.parent.material + return self.object.material + + def setTransparentPrimitives(self, transparentPrimitives): + """ + This method is used to specify the amount of transparent faces. + This property is overridden if self.material.transparent is set to True. + + :param transparentPrimitives: The amount of transparent faces. + :type transparentPrimitives: int + """ + self._transparentPrimitives = transparentPrimitives + + def getTransparentPrimitives(self): + # Object allows transparency rendering of only a subset (starting from + # the first face) of faces of the mesh, but material property transparent + # set to True overrides this and makes all faces render with transparency technique + if self.material.transparent: + return len(self.fvert) + else: + return self._transparentPrimitives + + transparentPrimitives = property(getTransparentPrimitives, setTransparentPrimitives) + + def getFaceGroup(self, name): + """ + This method searches the list of FaceGroups held for this object, and + returns the FaceGroup with the specified name. If no FaceGroup is found + for that name, this method returns None. + + :param name: The name of the FaceGroup to retrieve. + :type name: str + :return: The FaceGroup if found, None otherwise. + :rtype: :py:class:`module3d.FaceGroup` + """ + return self._groups_rev.get(name, None) + + def getFaceGroups(self): + """ + The names of the facegroups available on this mesh. + """ + return list(self._groups_rev.keys()) + + def getGroupMaskForGroups(self, groupNames): + groups = np.zeros(len(self._faceGroups), dtype=bool) + for name in groupNames: + groups[self._groups_rev[name].idx] = True + return groups + + def getFaceMaskForGroups(self, groupNames): + groups = self.getGroupMaskForGroups(groupNames) + face_mask = groups[self.group] + return face_mask + + def getFacesForGroups(self, groupNames): + face_mask = self.getFaceMaskForGroups(groupNames) + faces = np.argwhere(face_mask)[..., 0] + return faces + + def getVertexMaskForGroups(self, groupNames): + face_mask = self.getFaceMaskForGroups(groupNames) + verts = self.fvert[face_mask] + vert_mask = np.zeros(len(self.coord), dtype=bool) + vert_mask[verts] = True + return vert_mask + + def getVerticesForGroups(self, groupNames): + vert_mask = self.getVertexMaskForGroups(groupNames) + verts = np.argwhere(vert_mask)[..., 0] + return verts + + def getVerticesForFaceMask(self, face_mask): + verts = self.fvert[face_mask] + verts = verts.reshape(-1) + return verts + + def getVertexMaskForFaceMask(self, face_mask): + verts = self.getVerticesForFaceMask(face_mask) + vert_mask = np.zeros(len(self.coord), dtype=bool) + vert_mask[verts] = True + return vert_mask + + def getVertexAndFaceMasksForGroups(self, groupNames): + face_mask = self.getFaceMaskForGroups(groupNames) + verts = self.fvert[face_mask] + vert_mask = np.zeros(len(self.coord), dtype=bool) + vert_mask[verts] = True + return vert_mask, face_mask + + def getFaceMaskForVertices(self, verts): + """ + Get mask that selects all faces that are connected to the specified + vertices. + """ + mask = np.zeros(len(self.fvert), dtype=bool) + valid = ( + np.arange(self.MAX_FACES)[None, :] < self.nfaces[verts][:, None] + ) # Mask that filters out unused slots for faces connected to a vert + vface = self.vface[verts] + faces = vface[valid] + mask[faces] = True + return mask + + def getFacesForVertices(self, verts): + return np.argwhere(self.getFaceMaskForVertices(verts))[..., 0] + + def setCameraProjection(self, cameraMode): + """ + This method sets the camera mode used to visualize this object (fixed or movable). + The 3D engine has two camera modes (both perspective modes). + The first is moved by the mouse, while the second is fixed. + The first is generally used to model 3D objects (a human, clothes, + etc.), while the second is used for 3D GUI controls. + + :param cameraMode: The camera mode. 0 = movable camera (modelCamera); + 1 = static camera (guiCamera). + :type cameraMode: int + """ + + self.cameraMode = cameraMode + + def getCamera(self): + """ + The camera with which this mesh is rendered. + """ + from core import G + + return G.cameras[self.cameraMode] + + def update(self): + """ + This method is used to call the update methods on each of a list of vertices + or all vertices that form part of this object. Passes the current mesh state + to the OpenGL buffers. + """ + self.sync_all() + + def calcNormals( + self, recalcVertexNormals=1, recalcFaceNormals=1, verticesToUpdate=None, facesToUpdate=None + ): + """ + Updates the given vertex and/or face normals. + + :param recalcVertexNormals: A flag to indicate whether or not the vertex normals should be recalculated. + :type recalcVertexNormals: Boolean + :param recalcFaceNormals: A flag to indicate whether or not the face normals should be recalculated. + :type recalcFaceNormals: Boolean + :param verticesToUpdate: The list of vertices to be updated, if None all vertices are updated. + :type verticesToUpdate: list of :py:class:`module3d.Vert` + :param facesToUpdate: The list of faces to be updated, if None all faces are updated. + :type facesToUpdate: list of :py:class:`module3d.Face` + """ + + if recalcFaceNormals: + self.calcFaceNormals(facesToUpdate) + + if recalcVertexNormals: + self.calcVertexNormals(verticesToUpdate) + + if recalcFaceNormals or recalcVertexNormals and self.calculateTangents: + self.calcVertexTangents(verticesToUpdate) + + def calcBBox(self, ix=None, onlyVisible=True, fixedFaceMask=None): + """ + Calculates the axis aligned bounding box of this object in the object's coordinate system. + """ + # TODO maybe cache bounding box + if ix is None: + ix = np.s_[:] + if fixedFaceMask is not None: + verts = self.getVerticesForFaceMask(fixedFaceMask) + coord = self.coord[verts] + elif onlyVisible: + verts = self.getVerticesForFaceMask(self.getFaceMask()) + coord = self.coord[verts] + else: + coord = self.coord[ix] + if len(coord) == 0: + return np.zeros((2, 3), dtype=np.float32) + v0 = np.amin(coord, axis=0) + v1 = np.amax(coord, axis=0) + return np.vstack((v0, v1)) + + def __str__(self): + return "object3D Mesh named: %s, nverts: %s, nfaces: %s" % ( + self.name, + self.getVertexCount(), + self.getFaceCount(), + ) + + +def dot_v3(v3_arr1, v3_arr2): + """ + Numpy Ufunc'ed implementation of a series of dot products of two vector3 + objects. + """ + return ( + (v3_arr1[:, 0] * v3_arr2[:, 0]) + + (v3_arr1[:, 1] * v3_arr2[:, 1]) + + (v3_arr2[:, 2] * v3_arr1[:, 2]) + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/selection.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/selection.py new file mode 100644 index 0000000000000000000000000000000000000000..3400aabc5623a07eaa845f23d56858acdfaa402e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/core/selection.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Glynn Clements + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +TODO +""" + + +class SelectionColorMap: + """ + The objects support the use of a technique called *Selection Using Unique + Color IDs*, that internally uses color-coding of components within the + scene to support the selection of objects by the user using the mouse. + + This technique generates a sequence of colors (color IDs), assigning a + unique color to each uniquely selectable object or component in the scene. + These colors are not displayed, but are used by MakeHuman to generates an + unseen image of the various selectable elements. This image uses the same + camera settings currently being used for the actual, on-screen image. + When the mouse is clicked, the position of the mouse is used with the + unseen image to retrieve a color. MakeHuman uses this color as an ID to + identify which object or component the user clicked with the mouse. + + This technique uses glReadPixels() to read the single pixel at the + current mouse location, using the unseen, color-coded image. + + For further information on this technique, see: + + - http://www.opengl.org/resources/faq/technical/selection.htm and + - http://wiki.gamedev.net/index.php/OpenGL_Selection_Using_Unique_Color_IDs + + **Note.** Because the 3D engine uses glDrawElements in a highly opimized + way and each vertex can have only one color ID, there there is a known + problem with selecting individual faces with very small FaceGroups using + this technique. However, this is not a major problem for MakeHuman, which + doesn't use such low polygon groupings. + + - **self.colorIDToFaceGroup**: *Dictionary of colors IDs* A dictionary of the color IDs used for + selection (see MakeHuman Selectors, above). + - **self.colorID**: *float list* A progressive color ID. + + The attributes *self.colorID* and *self.colorIDToFaceGroup* + support a technique called *Selection Using Unique Color IDs* to make each + FaceGroup independently clickable. + + The attribute *self.colorID* stores a progressive color that is incremented for each successive + FaceGroup added to the scene. + The *self.colorIDToFaceGroup* attribute contains a list that serves as a directory to map + each color back to the corresponding FaceGroup by using its color ID. + """ + + def __init__(self): + + self.colorIDToFaceGroup = {} + self.colorID = 0 + + def assignSelectionID(self, obj): + """ + This method generates a new, unique color ID for each FaceGroup, + within a particular Object3D object, that forms a part of this scene3D + object. This color ID can subsequently be used in a non-displayed + image map to determine the FaceGroup that a mouse click was made in. + + This method loops through the FaceGroups, assigning the next color + in the sequence to each subsequent FaceGroup. The color value is + written into a 'dictionary' to serve as a color ID that can be + translated back into the corresponding FaceGroup name when a mouse + click is detected. + This is part of a technique called *Selection Using Unique Color IDs* + to make each FaceGroup independently clickable. + + :param obj: The object3D object for which color dictionary entries need to be generated. + :type obj: module3d.Object 3D + """ + for g in obj.faceGroups: + self.colorID += 1 + + # 555 to 24-bit rgb + + idR = (self.colorID % 32) * 8 + idG = ((self.colorID >> 5) % 32) * 8 + idB = ((self.colorID >> 10) % 32) * 8 + + g.colorID = (idR, idG, idB) + + self.colorIDToFaceGroup[self.colorID] = g + + def getSelectedFaceGroup(self, picked): + """ + This method uses a non-displayed image containing color-coded faces + to return the index of the FaceGroup selected by the user with the mouse. + This is part of a technique called *Selection Using Unique Color IDs* to make each + FaceGroup independently clickable. + + :return: The selected face group. + :rtype: :py:class:`module3d.FaceGroup` + """ + # Force integer divide + IDkey = picked[0] // 8 | picked[1] // 8 << 5 | picked[2] // 8 << 10 # 555 + + # print "DEBUG COLOR PICKED: %s,%s,%s %s"%(picked[0], picked[1], picked[2], IDkey) + + try: + groupSelected = self.colorIDToFaceGroup[IDkey] + except Exception: + print("Color %s (%s) not found" % (IDkey, picked)) + # print (groupSelected.name) + # this print should only come on while debugging color picking + # print ('Color %s (%s) not found' % (IDkey, picked)) + groupSelected = None + return groupSelected + + def getSelectedFaceGroupAndObject(self, picked): + """ + This method determines whether a FaceGroup or a non-selectable zone has been + clicked with the mouse. It returns a tuple, showing the FaceGroup and the parent + Object3D object, or None. + If no object is picked, this method will simply print \"no clickable zone.\" + + :return: The selected face group and object. + :rtype: (:py:class:`module3d.FaceGroup`, :py:class:`module3d.Object3d`) + """ + + facegroupPicked = self.getSelectedFaceGroup(picked) + if facegroupPicked: + objPicked = facegroupPicked.parent + return (facegroupPicked, objPicked) + else: + # this print should only be made while debugging picking + # print ('not a clickable zone') + return None + + +selectionColorMap = SelectionColorMap() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/getpath.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/getpath.py new file mode 100644 index 0000000000000000000000000000000000000000..d116e18a087023b72e93137e15414ed617b2a43f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/getpath.py @@ -0,0 +1,446 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Jonas Hauquier, Glynn Clements, Joel Palmius, Marc Flerackers + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +Utility module for finding the user home path. +""" + +import os +import sys + +from library.xdg_parser import XDG_PATHS + +__home_path = None + +# Search for an optional configuration file, providing another location for the home folder. +# The encoding of the file must be utf-8 and an absolute path is expected. + +if sys.platform.startswith("linux"): + + configFile = os.path.expanduser("~/.config/makehuman.conf") + +elif sys.platform.startswith("darwin"): + + configFile = os.path.expanduser("~/Library/Application Support/MakeHuman/makehuman.conf") + +elif sys.platform.startswith("win32"): + + configFile = os.path.join(os.getenv("LOCALAPPDATA", ""), "makehuman.conf") + +else: + + configFile = "" + +configPath = "" + +if os.path.isfile(configFile): + with open(configFile, "r", encoding="utf-8") as f: + configPath = f.readline().strip() + + if os.path.isdir(configPath): + __home_path = os.path.normpath(configPath).replace("\\", "/") + + +def pathToUnicode(path): + """ + Unicode representation of the filename. + Bytes is decoded with the codeset used by the filesystem of the operating + system. + Unicode representations of paths are fit for use in GUI. + """ + + if isinstance(path, bytes): + # Approach for bytes string type + try: + return str(path, "utf-8") + except UnicodeDecodeError: + pass + try: + return str(path, sys.getfilesystemencoding()) + except UnicodeDecodeError: + pass + try: + return str(path, sys.getdefaultencoding()) + except UnicodeDecodeError: + pass + try: + import locale + + return str(path, locale.getpreferredencoding()) + except UnicodeDecodeError: + return path + else: + return path + + +def formatPath(path): + if path is None: + return None + return pathToUnicode(os.path.normpath(path).replace("\\", "/")) + + +def canonicalPath(path): + """ + Return canonical name for location specified by path. + Useful for comparing paths. + """ + return formatPath(os.path.realpath(path)) + + +def localPath(path): + """ + Returns the path relative to the MH program directory, + i.e. the inverse of canonicalPath. + """ + path = os.path.realpath(path) + root = os.path.realpath(getSysPath()) + return formatPath(os.path.relpath(path, root)) + + +def getHomePath(): + """ + Find the user home path. + Note: If you are looking for MakeHuman data, you probably want getPath()! + """ + # Cache the home path + global __home_path + + # The environment variable MH_HOME_LOCATION will supersede any other settings for the home folder. + alt_home_path = os.environ.get("MH_HOME_LOCATION", "") + if os.path.isdir(alt_home_path): + __home_path = formatPath(alt_home_path) + + if __home_path is not None: + return __home_path + + # Windows + if sys.platform.startswith("win"): + import winreg + + keyname = r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" + # name = 'Personal' + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, keyname) as k: + try: + value, type_ = winreg.QueryValueEx(k, "Personal") + except FileNotFoundError: + value, type_ = r"%USERPROFILE%\Documents", winreg.REG_EXPAND_SZ + if type_ == winreg.REG_EXPAND_SZ: + __home_path = formatPath(winreg.ExpandEnvironmentStrings(value)) + return __home_path + elif type_ == winreg.REG_SZ: + __home_path = formatPath(value) + return __home_path + else: + raise RuntimeError("Couldn't determine user folder") + + # Linux + elif sys.platform.startswith("linux"): + doc_folder = XDG_PATHS.get("DOCUMENTS", "") + if os.path.isdir(doc_folder): + __home_path = doc_folder + else: + __home_path = pathToUnicode(os.path.expanduser("~")) + + # Darwin + else: + __home_path = os.path.expanduser("~") + + return __home_path + + +def getPath(subPath=""): + """ + Get MakeHuman folder that contains per-user files, located in the user home + path. + """ + path = getHomePath() + + # Windows + if sys.platform.startswith("win"): + path = os.path.join(path, "makehuman") + + # MAC OSX + elif sys.platform.startswith("darwin"): + path = os.path.join(path, "Documents") + path = os.path.join(path, "MakeHuman") + + # Unix/Linux + else: + path = os.path.join(path, "makehuman") + + path = os.path.join(path, "v1py3") + + if subPath: + path = os.path.join(path, subPath) + + return formatPath(path) + + +def getDataPath(subPath=""): + """ + Path to per-user data folder, should always be the same as getPath('data'). + """ + if subPath: + path = getPath(os.path.join("data", subPath)) + else: + path = getPath("data") + return formatPath(path) + + +def getSysDataPath(subPath=""): + """ + Path to the data folder that is installed with MakeHuman system-wide. + NOTE: do NOT assume that getSysPath("data") == getSysDataPath()! + """ + if subPath: + path = getSysPath(os.path.join("data", subPath)) + else: + path = getSysPath("data") + return formatPath(path) + + +def getSysPath(subPath=""): + """ + Path to the system folder where MakeHuman is installed (it is possible that + data is stored in another path). + Writing to this folder or modifying this data usually requires admin rights, + contains system-wide data (for all users). + """ + if subPath: + path = os.path.join(".", subPath) + else: + path = "." + return formatPath(path) + + +def _allnamesequal(name): + return all(n == name[0] for n in name[1:]) + + +def commonprefix(paths, sep="/"): + """ + Implementation of os.path.commonprefix that works as you would expect. + + Source: http://rosettacode.org/wiki/Find_Common_Directory_Path#Python + """ + from itertools import takewhile + + bydirectorylevels = list(zip(*[p.split(sep) for p in paths])) + return sep.join(x[0] for x in takewhile(_allnamesequal, bydirectorylevels)) + + +def isSubPath(subpath, path): + """ + Verifies whether subpath is within path. + """ + subpath = canonicalPath(subpath) + path = canonicalPath(path) + return commonprefix([subpath, path]) == path + + +def isSamePath(path1, path2): + """ + Determines whether two paths point to the same location. + """ + return canonicalPath(path1) == canonicalPath(path2) + + +def getRelativePath(path, relativeTo=[getDataPath(), getSysDataPath()], strict=False): + """ + Return a relative file path, relative to one of the specified search paths. + First valid path is returned, so order in which search paths are given matters. + """ + if not isinstance(relativeTo, list): + relativeTo = [relativeTo] + + relto = None + for p in relativeTo: + if isSubPath(path, p): + relto = p + if relto is None: + if strict: + return None + else: + return path + + relto = os.path.abspath(os.path.realpath(relto)) + path = os.path.abspath(os.path.realpath(path)) + rpath = os.path.relpath(path, relto) + return formatPath(rpath) + + +def findFile(relPath, searchPaths=[getDataPath(), getSysDataPath()], strict=False): + """ + Inverse of getRelativePath: find an absolute path from specified relative + path in one of the search paths. + First occurence is returned, so order in which search paths are given matters. + Note: does NOT treat the path as relative to the current working dir, unless + you explicitly specify '.' as one of the searchpaths. + """ + if not isinstance(searchPaths, list): + searchPaths = [searchPaths] + + for dataPath in searchPaths: + path = os.path.join(dataPath, relPath) + if os.path.isfile(path): + return formatPath(path) + + if strict: + return None + else: + return relPath + + +def thoroughFindFile(filename, searchPaths=[], searchDefaultPaths=True): + """ + Extensively search the data paths to find a file with matching filename in + as much cases as possible. If file is found, returns absolute filename. + If nothing is found return the most probable filename. + """ + # Ensure unix style path + filename.replace("\\", "/") + + if not isinstance(searchPaths, list): + searchPaths = [searchPaths] + + if searchDefaultPaths: + # Search in user / sys data, and user / sys root folders + searchPaths = list(searchPaths) + searchPaths.extend([getDataPath(), getSysDataPath(), getPath(), getSysPath()]) + + path = findFile(filename, searchPaths, strict=True) + if path: + return canonicalPath(path) + + # Treat as absolute path or search relative to application path + if os.path.isfile(filename): + return canonicalPath(filename) + + # Strip leading data/ folder if present (for the scenario where sysDataPath is not in sysPath) + if filename.startswith("data/"): + result = thoroughFindFile(filename[5:], searchPaths, False) + if os.path.isfile(result): + return result + + # Nothing found + return formatPath(filename) + + +def search(paths, extensions, recursive=True, mutexExtensions=False): + """ + Search for files with specified extensions in specified paths. + If mutexExtensions is True, no duplicate files with only differing extension + will be returned. Instead, only the file with highest extension precedence + (extensions occurs earlier in the extensions list) is kept. + """ + if isinstance(paths, str): + paths = [paths] + if isinstance(extensions, str): + extensions = [extensions] + extensions = [e[1:].lower() if e.startswith(".") else e.lower() for e in extensions] + + if mutexExtensions: + discovered = dict() + + def _aggregate_files_mutexExt(filepath): + basep, ext = os.path.splitext(filepath) + ext = ext[1:] + if basep in discovered: + if extensions.index(ext) < extensions.index(discovered[basep]): + discovered[basep] = ext + else: + discovered[basep] = ext + + if recursive: + for path in paths: + for root, dirs, files in os.walk(path): + for f in files: + ext = os.path.splitext(f)[1][1:].lower() + if ext in extensions: + if mutexExtensions: + _aggregate_files_mutexExt(os.path.join(root, f)) + else: + yield pathToUnicode(os.path.join(root, f)) + else: + for path in paths: + if not os.path.isdir(path): + continue + for f in os.listdir(path): + f = os.path.join(path, f) + if os.path.isfile(f): + ext = os.path.splitext(f)[1][1:].lower() + if ext in extensions: + if mutexExtensions: + _aggregate_files_mutexExt(f) + else: + yield pathToUnicode(f) + + if mutexExtensions: + for f in ["%s.%s" % (p, e) for p, e in list(discovered.items())]: + yield pathToUnicode(f) + + +def getJailedPath(filepath, relativeTo, jailLimits=[getDataPath(), getSysDataPath()]): + """ + Get a path to filepath, relative to relativeTo path, confined within the + jailLimits folders. Returns None if the path would fall outside of the jail. + This is a portable path which can be used for distributing eg. materials + (texture paths are portable). + Returns None if the filepath falls outside of the jail folders. Returns + a path to filename relative to relativeTo path if it is a subpath of it, + else returns a path relative to the jailLimits. + """ + + def _withinJail(path): + for j in jailLimits: + if isSubPath(path, j): + return True + return False + + # These paths may become messed up when using symlinks for user home. + # Make sure we use the same paths when calculating relative paths. + filepath = os.path.realpath(filepath) + + if relativeTo is str: + relativeTo = os.path.realpath(relativeTo) + + output = None + + if _withinJail(filepath): + relPath = getRelativePath(filepath, relativeTo, strict=True) + if relPath: + output = relPath + else: + output = getRelativePath(filepath, jailLimits) + return output diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/image.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/image.py new file mode 100644 index 0000000000000000000000000000000000000000..31a4bdbffd2ebdcb2898f19ac582cf8c05d318a9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/image.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Image class definition +====================== + +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Glynn Clements + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +The image module contains the definition of the Image class, the container +that MakeHuman uses to handle images. + +Image only depends on the numpy library, except when image have to be loaded +or saved to disk, in which case one of the back-ends (Qt or PIL) will have to +be imported (import happens only when needed). +""" + +import time + +import numpy as np + +FILTER_NEAREST = 0 # Nearest neighbour resize filter (no real filtering) +FILTER_BILINEAR = 1 # Bi-linear filter +FILTER_BICUBIC = 2 # Bi-cubic filter (not supported with Qt, only PIL) + + +class Image(object): + """Container for handling images. + + It is equipped with the necessary methods that one needs for loading + and saving images and fetching their data, as well as many properties + providing information about the loaded image. + """ + + def __init__(self, path=None, width=0, height=0, bitsPerPixel=32, components=None, data=None): + """Image constructor. + + The Image can be constructed by an existing Image, a QPixmap, a + QImage, loaded from a file path, or created empty. + + To construct the Image by copying the data from the source, + pass the source as the first argument of the constructor. + ``dest = Image(source)`` + + To create the Image by sharing the data of another Image, pass + the source Image as the data argument. + ``dest = Image(data=sharedsource)`` + + The data argument can be a numpy array of 3 dimensions (w, h, c) which + will be used directly as the image's data, where w is the width, h is + the height, and c is the number of channels. + The data argument can also be a path to load. + + To create an empty Image, leave path=None, and specify the width and + height. You can then optionally adjust the new Image's channels by + setting bitsPerPixel = 8, 16, 24, 32, or components = 1, 2, 3, 4, + which are equivalent to W (Grayscale), WA (Grayscale with Alpha), + RGB, and RGBA respectively. + """ + import image_qt as image_lib + + if path is not None: + self._is_empty = False + if isinstance(path, Image): + # Create a copy of the image. + self._data = path.data.copy() + elif _isQPixmap(path): + qimg = path.toImage() + self._data = image_lib.load(qimg) + else: # Path string / QImage. + self._data = image_lib.load(path) + self.sourcePath = path + elif data is not None: + self._is_empty = False + if isinstance(data, Image): + # Share data between images. + self._data = data.data + elif isinstance(data, str): + self._data = image_lib.load(data) + else: # Data array. + self._data = data + else: + self._is_empty = True + if components is None: + if bitsPerPixel == 32: + components = 4 + elif bitsPerPixel == 24: + components = 3 + else: + raise NotImplementedError("bitsPerPixel must be 24 or 32") + self._data = np.empty((height, width, components), dtype=np.uint8) + self._data = np.ascontiguousarray(self._data) + + self.modified = time.time() + + @property + def size(self): + """Return the size of the Image as a (width, height) tuple.""" + h, w, c = self._data.shape + return (w, h) + + @property + def width(self): + """Return the width of the Image in pixels.""" + h, w, c = self._data.shape + return w + + @property + def height(self): + """Return the height of the Image in pixels.""" + h, w, c = self._data.shape + return h + + @property + def components(self): + """Return the number of the Image channels.""" + h, w, c = self._data.shape + return c + + @property + def bitsPerPixel(self): + """Return the number of bits per pixel used for the Image.""" + h, w, c = self._data.shape + return c * 8 + + @property + def data(self): + """Return the numpy ndarray that contains the Image data.""" + return self._data + + def save(self, path): + """Save the Image to a file.""" + import image_qt as image_lib + + image_lib.save(path, self._data) + + def toQImage(self): + """ + Get a QImage copy of this Image. + Useful when the image should be shown in a Qt GUI + """ + import image_qt + + # return image_qt.toQImage(self.data) + # ^ For some reason caused problems + if self.components == 1: + fmt = image_qt.QtGui.QImage.Format_RGB888 + h, w, c = self.data.shape + data = np.repeat(self.data[:, :, 0], 3).reshape((h, w, 3)) + elif self.components == 2: + fmt = image_qt.QtGui.QImage.Format_ARGB32 + h, w, c = self.data.shape + data = np.repeat(self.data[:, :, 0], 3).reshape((h, w, 3)) + data = np.insert(data, 3, values=self.data[:, :, 1], axis=2) + elif self.components == 3: + """ + fmt = image_qt.QtGui.QImage.Format_RGB888 + data = self.data + """ + # The above causes a crash or misaligned image raster. + # Quickhack solution: + fmt = image_qt.QtGui.QImage.Format_ARGB32 + _data = self.convert(components=4).data + # There appear to be channel mis-alignments, another hack: + data = np.zeros(_data.shape, dtype=_data.dtype) + data[:, :, :] = _data[:, :, [2, 1, 0, 3]] + else: + # components == 4 + fmt = image_qt.QtGui.QImage.Format_ARGB32 + data = self.data + return image_qt.QtGui.QImage(data.tostring(), data.shape[1], data.shape[0], fmt) + + def resized_(self, width, height, filter=FILTER_NEAREST): + if filter == FILTER_NEAREST: + dw, dh = width, height + sw, sh = self.size + xmap = np.floor((np.arange(dw) + 0.5) * sw / dw).astype(int) + ymap = np.floor((np.arange(dh) + 0.5) * sh / dh).astype(int) + return self._data[ymap, :][:, xmap] + else: + # NOTE: bi-cubic filtering is not supported by Qt, use bi-linear + import image_qt + + return image_qt.resized(self, width, height, filter=filter) + + def resized(self, width, height, filter=FILTER_NEAREST): + """Get a resized copy of the Image.""" + return Image(data=self.resized_(width, height, filter)) + + def resize(self, width, height, filter=FILTER_NEAREST): + """Resize the Image to a specified size.""" + self._data = self.resized_(width, height, filter) + self.modified = time.time() + + def blit(self, other, x, y): + """Copy the contents of an Image to another. + The target image may have a different size.""" + dh, dw, dc = self._data.shape + sh, sw, sc = other._data.shape + if sc != dc: + raise ValueError("source image has incorrect format") + sw = min(sw, dw - x) + sh = min(sh, dh - y) + self._data[y : y + sh, x : x + sw, :] = other._data + + self.modified = time.time() + + def flip_vertical(self): + """Turn the Image upside down.""" + return Image(data=self._data[::-1, :, :]) + + def flip_horizontal(self): + """Flip the Image in the left-right direction.""" + return Image(data=self._data[:, ::-1, :]) + + def __getitem__(self, xy): + """Get the color of a specified pixel by using the + square brackets operator. + + Example: my_color = my_image[(17, 42)]""" + if not isinstance(xy, tuple) or len(xy) != 2: + raise TypeError("tuple of length 2 expected") + + x, y = xy + + if not isinstance(x, int) or not isinstance(y, int): + raise TypeError("tuple of 2 ints expected") + + if x < 0 or x >= self.width or y < 0 or y >= self.height: + raise IndexError("element index out of range") + + pix = self._data[y, x, :] + if self.components == 4: + return (pix[0], pix[1], pix[2], pix[3]) + elif self.components == 3: + return (pix[0], pix[1], pix[2], 255) + elif self.components == 2: + return (pix[0], pix[0], pix[0], pix[1]) + elif self.components == 1: + return (pix[0], pix[0], pix[0], 255) + else: + return None + + def __setitem__(self, xy, color): + """Set the color of a pixel using the square brackets + operator. + + Example: my_image[(17, 42)] = (0, 255, 64, 255)""" + if not isinstance(xy, tuple) or len(xy) != 2: + raise TypeError("tuple of length 2 expected") + + x, y = xy + + if not isinstance(x, int) or not isinstance(y, int): + raise TypeError("tuple of 2 ints expected") + + if x < 0 or x >= self.width or y < 0 or y >= self.height: + raise IndexError("element index out of range") + + if not isinstance(color, tuple): + raise TypeError("tuple expected") + + self._data[y, x, :] = color + self.modified = time.time() + + def convert(self, components): + """Convert the Image to a different color format. + + 'components': The number of color channels the Image + will have after the conversion.""" + if self.components == components: + return self + + hasAlpha = self.components in (2, 4) + needAlpha = components in (2, 4) + + if hasAlpha: + alpha = self._data[..., -1] + color = self._data[..., :-1] + else: + alpha = None + color = self._data + + isMono = self.components in (1, 2) + toMono = components in (1, 2) + + if isMono and not toMono: + color = np.dstack((color, color, color)) + elif toMono and not isMono: + color = np.sum(color.astype(np.uint16), axis=-1) / 3 + color = color.astype(np.uint8)[..., None] + + if needAlpha and alpha is None: + alpha = np.zeros_like(color[..., :1]) + 255 + + if needAlpha: + data = np.dstack((color, alpha)) + else: + data = color + + return type(self)(data=data) + + def markModified(self): + """Mark the Image as modified.""" + self.modified = time.time() + self._is_empty = False + + @property + def isEmpty(self): + """ + Returns True if the Image is empty or new. + Returns False if the Image contains data or has been modified. + """ + return self._is_empty + + +def _isQPixmap(img): + """ + Test an image object for being a QPixmap instance if Qt libraries were + loaded in the application. + """ + import sys + + if "PyQt5" in list(sys.modules.keys()): + import image_qt + + return isinstance(img, image_qt.QtGui.QPixmap) + else: + return False diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/language.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/language.py new file mode 100644 index 0000000000000000000000000000000000000000..9935843363738ca1c0036a88211b6a451bd4e21c --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/language.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Translation and localization module. + +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Code Home Page:** http://code.google.com/p/makehuman/ + +**Authors:** Joel Palmius, Marc Flerackers, Glynn Clements + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +Language file loading and translation. +""" + +from collections import OrderedDict +import json +import os + +from getpath import getDataPath, getSysDataPath +import log + + +class Language(object): + def __init__(self): + self.language = None + self.languageStrings = None + self.missingStrings = OrderedDict() + self.rtl = False + + def setLanguage(self, lang): + self.languageStrings = None + path = os.path.join(getSysDataPath("languages/"), lang + ".json") + if not os.path.isfile(path): + return + with open(path, "r", encoding="utf-8") as f: + try: + self.languageStrings = json.loads(f.read()) + except Exception: + print("Error in language file %s" % lang) + log.error("Error in language file %s", lang, exc_info=True) + self.languageStrings = None + self.language = lang + self.rtl = False + if self.languageStrings and "__options__" in self.languageStrings: + self.rtl = self.languageStrings["__options__"].get("rtl", False) + + def getLanguageString(self, string, appendData=None, appendFormat=None): + if not string: + return string + if string == "%%s": + return string + if isinstance(string, list): + if len(string) == 2: + appendData = string[1] + string = string[0] + else: + if len(string) == 3: + appendFormat = string[2] + appendData = string[1] + string = string[0] + + if self.languageStrings is None: + result = string + else: + result = self.languageStrings.get(string) + + if result is not None: + if appendData is not None: + if appendFormat is not None: + result = result + (appendFormat % appendData) + else: + result = result + appendData + return result + self.missingStrings[string] = None + return string + + def dumpMissingStrings(self): + if not self.language: + return + path = os.path.join(getSysDataPath("languages/"), self.language + ".missing") + pathdir = os.path.dirname(path) + if not os.path.isdir(pathdir): + os.makedirs(pathdir) + with open(path, "w", encoding="utf-8") as f: + for string in self.missingStrings.keys(): + if self.language == "master": + f.write( + '"%s": "%s",\n' + % ( + string.replace("\n", "\\n").encode("utf8"), + string.replace("\n", "\\n").encode("utf8"), + ) + ) + else: + f.write('"%s": "",\n' % string.replace("\n", "\\n").encode("utf8")) + + +def getLanguages(): + """ + The languages available on this MH installation, by listing all .json + files in the languages folder in user and system data path. + """ + langDirFiles = os.listdir(getSysDataPath("languages")) + try: + langDirFiles = langDirFiles + os.listdir(getDataPath("languages")) + except Exception: + print("No user data path") + return ["english"] + [ + os.path.basename(filename).replace(".json", "") + for filename in sorted(langDirFiles) + if filename.split(os.extsep)[-1] == "json" + ] + + +language = Language() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/log.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/log.py new file mode 100644 index 0000000000000000000000000000000000000000..0a9ffd5db9a755066dc06d6770746b36b8cb88f4 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/log.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Logging. + +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Glynn Clements + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +Logging component. To be used instead of print statements. +""" + +import code +import logging +from logging import CRITICAL, DEBUG, ERROR, INFO, WARNING +import logging.config +import os + +from library.getpath import getPath, getSysDataPath +from library.universal import G + +NOTICE = 25 +MESSAGE = logging.INFO + +LEVEL_TO_STR = { + DEBUG: "debug", + INFO: "info", + WARNING: "warning", + ERROR: "error", + CRITICAL: "critical", + NOTICE: "notice", +} + + +def logLevelToStr(levelCode): + if levelCode in LEVEL_TO_STR: + return LEVEL_TO_STR[levelCode] + else: + levels = sorted(LEVEL_TO_STR.keys()) + i = 0 + while i < len(levels) and levelCode < levels[i]: + i += 1 + i = min(i, len(levels) - 1) + return levels[i].upper() + + +def _toUnicode(msg, *args): + """ + Unicode representation of the formatted message. + String is decoded with the codeset used by the filesystem of the operating + system. + """ + try: + msg_ = msg % args + except TypeError: + # Also allow dict with keywords in format string, passed as first arg + if len(args) == 1 and isinstance(args[0], dict): + msg_ = msg % args[0] + else: + raise + + if isinstance(msg_, bytes): + return str(msg_, encoding="utf-8") + else: + return msg_ + + +def debug(msg, *args, **kwargs): + try: + logging.debug(msg, *args, **kwargs) + except UnicodeError: + msg_ = _toUnicode(msg, args) + logging.debug(msg_, kwargs) + + +def warning(msg, *args, **kwargs): + try: + logging.warning(msg, *args, **kwargs) + except UnicodeError: + msg_ = _toUnicode(msg, args) + logging.warning(msg_, kwargs) + + +def error(msg, *args, **kwargs): + try: + logging.error(msg, *args, **kwargs) + except UnicodeError: + msg_ = _toUnicode(msg, args) + logging.error(msg_, kwargs) + + +def message(msg, *args, **kwargs): + try: + logging.info(msg, *args, **kwargs) + except UnicodeError: + msg_ = _toUnicode(msg, args) + logging.info(msg_, kwargs) + + +# We have to make notice() appear to have been defined in the logging module +# so that logging.findCaller() finds its caller, not notice() itself +# This is required for the pathname, filename, module, funcName and lineno +# members of the LogRecord refer to the caller rather than to notice() itself. + +_notice_src = r""" +def notice(format, *args, **kwargs): + logging.log(NOTICE, format, *args, **kwargs) +""" +try: + exec(code.compile_command(_notice_src, logging.info.__code__.co_filename)) +except Exception: + print("Error defining notice() function in log.py") + + def notice(format, *args, **kwargs): + logging.log(NOTICE, format, *args, **kwargs) + + +logging.addLevelName(NOTICE, "NOTICE") +logging.addLevelName(MESSAGE, "MESSAGE") + + +def _splitpath(path): + + head, tail = os.path.split(path) + if tail == "": + return [head] + return _splitpath(head) + [tail] + + +class NoiseFilter(logging.Filter): + def filter(self, record): + try: + if record.msg.endswith(":\n%s"): + record.msg = record.msg[:-4] + record.args = record.args[:-1] + except Exception as e: + print("Error in NoiseFilter", e) + import traceback + + traceback.print_exc() + return True + + +class DowngradeFilter(logging.Filter): + def __init__(self, level): + super(DowngradeFilter, self).__init__() + self.level = level + + def filter(self, record): + try: + if record.levelno > self.level: + record.levelno = self.level + record.levelname = logging.getLevelName(record.levelno) + except Exception as e: + print("Error in DowngradeFilter", e) + import traceback + + traceback.print_exc() + return True + + +_logLevelColors = { + DEBUG: "grey", + NOTICE: "blue", + INFO: "blue", + WARNING: "darkorange", + ERROR: "red", + CRITICAL: "red", +} + + +def getLevelColor(logLevel): + global _logLevelColors + if logLevel not in _logLevelColors: + warning("Unknown log level color %s (%s)" % (logLevel, logLevelToStr(logLevel))) + return _logLevelColors.get(logLevel, "red") + + +class SplashLogHandler(logging.Handler): + def emit(self, record): + if G.app is not None and G.app.splash is not None: + G.app.splash.logMessage(self.format(record).split("\n", 1)[0] + "\n") + + +class StatusLogHandler(logging.Handler): + def emit(self, record): + if G.app is not None and G.app.statusBar is not None and record.levelno >= ERROR: + msg = "An ERROR Occurred. Check Utilities/Logs For More Information! Error Message: {:s}".format( + record.getMessage() + ) + G.app.statusBar.temporaryMessage("%s", msg, msec=10000) + + +class ApplicationLogHandler(logging.Handler): + def emit(self, record): + if G.app is not None and G.app.log_window is not None: + G.app.addLogMessage(self.format(record), record.levelno) + + +_logger_notice_src = r""" +def _logger_notice(self, msg, *args, **kwargs): + self.log(NOTICE, msg, *args, **kwargs) +""" +try: + exec(code.compile_command(_logger_notice_src, logging.info.__code__.co_filename)) +except Exception as e: + print("Error defining _logger_notice() function in log.py", e) + + def _logger_notice(self, format, *args, **kwargs): + self.log(NOTICE, format, *args, **kwargs) + + +class Logger(logging.Logger): + message = logging.Logger.info + notice = _logger_notice + + +def init(): + def config(): + userDir = getPath("") + defaults = dict(mhUserDir=userDir.replace("\\", "/")) + + try: + filename = os.path.join(userDir, "logging.ini") + if os.path.isfile(filename): + logging.config.fileConfig(filename, defaults) + return + except Exception: + pass + + try: + logging.config.fileConfig(getSysDataPath("logging.ini"), defaults) + return + except Exception: + pass + + try: + logging.basicConfig(level=logging.DEBUG) + return + except Exception: + pass + + logging.setLoggerClass(Logger) + + config() + + logging.captureWarnings(True) + + try: + logging.getLogger("OpenGL.formathandler").addFilter(NoiseFilter()) + logging.getLogger("OpenGL.extensions").addFilter(DowngradeFilter(logging.DEBUG)) + except Exception: + import traceback + + traceback.print_exc() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/matrix.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..82c334043e61be91491248bb05d2aaf99d31d257 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/matrix.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Glynn Clements + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +Numpy powered matrix transformations. +""" + +import math + +import numpy as np + + +def transform(m, v): + return np.asarray(m * np.asmatrix(v).T)[:, 0] + + +def transform3(m, v): + x, y, z = v + v = np.asmatrix((x, y, z, 1)).T + v = np.asarray(m * v)[:, 0] + return v[:3] / v[3] + + +def magnitude(v): + return math.sqrt(np.sum(v**2)) + + +def normalize(v): + m = magnitude(v) + if m == 0: + return v + return v / m + + +def ortho(l1, r1, b1, t1, n1, f1): + dx = r1 - l1 + dy = t1 - b1 + dz = f1 - n1 + rx = -(r1 + l1) / (r1 - l1) + ry = -(t1 + b1) / (t1 - b1) + rz = -(f1 + n1) / (f1 - n1) + return np.matrix( + [[2.0 / dx, 0, 0, rx], [0, 2.0 / dy, 0, ry], [0, 0, -2.0 / dz, rz], [0, 0, 0, 1]] + ) + + +def perspective(fovy, aspect, n, f): + s = 1.0 / math.tan(math.radians(fovy) / 2.0) + sx, sy = s / aspect, s + zz = (f + n) / (n - f) + zw = 2 * f * n / (n - f) + return np.matrix([[sx, 0, 0, 0], [0, sy, 0, 0], [0, 0, zz, zw], [0, 0, -1, 0]]) + + +def frustum(x0, x1, y0, y1, z0, z1): + a = (x1 + x0) / (x1 - x0) + b = (y1 + y0) / (y1 - y0) + c = -(z1 + z0) / (z1 - z0) + d = -2 * z1 * z0 / (z1 - z0) + sx = 2 * z0 / (x1 - x0) + sy = 2 * z0 / (y1 - y0) + return np.matrix([[sx, 0, a, 0], [0, sy, b, 0], [0, 0, c, d], [0, 0, -1, 0]]) + + +def translate(xyz): + x, y, z = xyz + return np.matrix([[1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, z], [0, 0, 0, 1]]) + + +def scale(xyz): + x, y, z = xyz + return np.matrix([[x, 0, 0, 0], [0, y, 0, 0], [0, 0, z, 0], [0, 0, 0, 1]]) + + +def _sincos(a): + a = math.radians(a) + return math.sin(a), math.cos(a) + + +def rotate(a, xyz): + x, y, z = normalize(xyz) + s, c = _sincos(a) + nc = 1 - c + return np.matrix( + [ + [x * x * nc + c, x * y * nc - z * s, x * z * nc + y * s, 0], + [y * x * nc + z * s, y * y * nc + c, y * z * nc - x * s, 0], + [x * z * nc - y * s, y * z * nc + x * s, z * z * nc + c, 0], + [0, 0, 0, 1], + ] + ) + + +def rotx(a): + s, c = _sincos(a) + return np.matrix([[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]]) + + +def roty(a): + s, c = _sincos(a) + return np.matrix([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]]) + + +def rotz(a): + s, c = _sincos(a) + return np.matrix([[c, -s, 0, 0], [s, c, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) + + +def lookat(eye, target, up): + F = target[:3] - eye[:3] + f = normalize(F) + U = normalize(up[:3]) + s = np.cross(f, U) + u = np.cross(s, f) + M = np.matrix(np.identity(4)) + M[:3, :3] = np.vstack([s, u, -f]) + T = translate(-eye) + return M * T + + +def viewport(x, y, w, h): + x, y, w, h = list(map(float, (x, y, w, h))) + return np.matrix( + [[w / 2, 0, 0, x + w / 2], [0, h / 2, 0, y + h / 2], [0, 0, 0.5, 0.5], [0, 0, 0, 1]] + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/mh.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/mh.py new file mode 100644 index 0000000000000000000000000000000000000000..b56185763c24eef5fd2116e9babfc074fdf9c5bb --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/mh.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Glynn Clements + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +Python compatibility layer replacing the old C functions of MakeHuman. +""" + +from library.universal import G + +cameras = G.cameras + + +def setClearColor(r, g, b, a): + G.clearColor = (r, g, b, a) + + +def setCaption(caption): + G.app.mainwin.setWindowTitle(caption) + + +def changeCategory(category): + G.app.mainwin.tabs.changeTab(category) + + +def changeTask(category, task): + if not G.app.mainwin.tabs.findTab(category): + return + changeCategory(category) + G.app.mainwin.tabs.findTab(category).child.changeTab(task) + + +def refreshLayout(): + G.app.mainwin.refreshLayout() + + +def addPanels(): + return G.app.mainwin.addPanels() + + +def showPanels(left, right): + return G.app.mainwin.showPanels(left, right) + + +def addTopWidget(widget, *args, **kwargs): + return G.app.mainwin.addTopWidget(widget, *args, **kwargs) + + +def removeTopWidget(widget): + return G.app.mainwin.removeTopWidget(widget) + + +def addToolBar(name): + return G.app.mainwin.addToolBar(name) + + +def redraw(): + G.app.redraw() + + +def getKeyModifiers(): + return int(G.app.keyboardModifiers()) + + +def addTimer(milliseconds, callback): + return G.app.addTimer(milliseconds, callback) + + +def removeTimer(id): + G.app.removeTimer(id) + + +def callAsync(func, *args, **kwargs): + G.app.callAsync(func, *args, **kwargs) + + +def getSetting(setting_name): + return G.app.getSetting(setting_name) + + +def setSetting(setting_name, value): + G.app.setSetting(setting_name, value) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/profiler.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e35e7ab6bcfc33f2a675e6d94f80889a66d2e846 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/profiler.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Glynn Clements + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +TODO +""" + +import atexit +from cProfile import Profile + +_sort = "cumulative" +_profiler = None +_show = None + + +def run(cmd, globals, locals): + prof = Profile() + try: + prof.runctx(cmd, globals, locals) + finally: + show(prof) + + +def active(): + return _profiler is not None + + +def start(): + global _profiler + if active(): + return + _profiler = Profile() + + +def stop(): + global _profiler + if not active(): + return + show(_profiler) + _profiler = None + + +def accum(cmd, globals, locals): + if not active(): + return + _profiler.runctx(cmd, globals, locals) + + +def show(prof): + try: + if _show is not None: + _show(prof) + else: + prof.print_stats(_sort) + except TypeError: + pass + + +def set_sort(sort): + global _sort + _sort = sort + + +def set_show(show): + global _show + _show = show + + +atexit.register(stop) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/qtgui.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/qtgui.py new file mode 100644 index 0000000000000000000000000000000000000000..26a42e292ebcb066f96f7bd4a15ff39353f012bd --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/qtgui.py @@ -0,0 +1,190 @@ +from PyQt6 import QtCore, QtGui, QtWidgets +from PyQt6.QtCore import Qt + + +class ListItem(QtWidgets.QListWidgetItem): + def __init__(self, label): + super(ListItem, self).__init__(label) + self.__hasCheckbox = False + + @property + def hasCheckbox(self): + return self.__hasCheckbox + + def setUserData(self, data): + self.setData(Qt.ItemDataRole.UserRole, data) + + def getUserData(self): + return self.data(Qt.ItemDataRole.UserRole) + + def text(self): + return str(super(ListItem, self).text()) + + def enableCheckbox(self): + self.__hasCheckbox = True + self.setFlags(self.flags() | Qt.ItemFlag.ItemIsUserCheckable) + self.setCheckState(QtCore.Qt.CheckState.Unchecked) + self.checkedState = False + + def setChecked(self, checked): + if not self.hasCheckbox: + self.setSelected(checked) + return + + if checked: + self.setCheckState(QtCore.Qt.CheckState.Checked) + else: + self.setCheckState(QtCore.Qt.CheckState.Unchecked) + self.checkedState = self.checkState() + + def isChecked(self): + return self.hasCheckbox and self.checkState() != QtCore.Qt.CheckState.Unchecked + + def _clicked(self): + # owner = self.listWidget() + if self.hasCheckbox: + if self.checkState() != self.checkedState: + self.checkedState = self.checkState() + if self.checkState(): + print("Item checked") + else: + print("Item unchecked") + return True + return False + + +class ListView(QtWidgets.QListWidget): + def __init__(self): + super(ListView, self).__init__() + # Widget.__init__(self) + self._vertical_scrolling = True + self.itemActivated[QtWidgets.QListWidgetItem].connect(self._activate) + self.itemClicked[QtWidgets.QListWidgetItem].connect(self._clicked) + + def _activate(self, item): + print("Item activated") + + def _clicked(self, item): + if item._clicked(): + return + if self.allowsMultipleSelection(): + if item.isSelected(): + print("Item selected") + else: + print("Item deselected") + else: + pass + + def onActivate(self, event): + pass + + def onClicked(self, event): + pass + + def setData(self, items): + self.clear() + for item in items: + self.addItem(item) + + def setVerticalScrollingEnabled(self, enabled): + self._vertical_scrolling = enabled + if enabled: + self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAsNeeded) + else: + self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.updateGeometry() + + def rowCount(self): + return len([item for item in self.getItems() if item is not None and not item.isHidden()]) + + def sizeHint(self): + if self._vertical_scrolling: + return super(ListView, self).sizeHint() + else: + rows = self.rowCount() + if rows > 0: + rowHeight = self.sizeHintForRow(0) + rowHeight = max(rowHeight, self.iconSize().height()) + else: + rowHeight = 0 + height = rowHeight * rows + + size = super(ListView, self).sizeHint() + size.setHeight(height) + return size + + _brushes = {} + + @classmethod + def getBrush(cls, color): + if color not in cls._brushes: + cls._brushes[color] = QtGui.QBrush(QtGui.QColor(color)) + return cls._brushes[color] + + def addLogItem(self, text, color=None, data=None, checkbox=False, pos=None): + item = ListItem(text) + item.setText(text) + if color is not None: + item.setForeground(self.getBrush(color)) + if data is not None: + item.setUserData(data) + if checkbox: + item.enableCheckbox() + return self.addItemObject(item, pos) + + def addItemObject(self, item, pos=None): + if pos is not None: + super(ListView, self).insertItem(pos, item) + else: + super(ListView, self).addItem(item) + if not self._vertical_scrolling: + self.updateGeometry() + return item + + def getSelectedItem(self): + items = self.selectedItems() + if len(items) > 0: + return items[0].text + return None + + def getSelectedItems(self): + return [item.text for item in self.selectedItems()] + + def getItemData(self, row): + item = self.item(row) + if item is not None: + return item.getUserData() + + def setItemColor(self, row, color): + item = self.item(row) + if item is not None: + item.setForeground(self.getBrush(color)) + + def showItem(self, row, state): + item = self.item(row) + if item is not None: + item.setHidden(not state) + + def allowMultipleSelection(self, allow): + self.setSelectionMode( + QtWidgets.QAbstractItemView.SelectionMode.MultiSelection + if allow + else QtWidgets.QAbstractItemView.SelectionMode.SingleSelection + ) + + def allowsMultipleSelection(self): + return self.selectionMode() == QtWidgets.QAbstractItemView.SelectionMode.MultiSelection + + def getItems(self): + return [self.item(row) for row in range(self.count())] + + def clearSelection(self): + super(ListView, self).clearSelection() + + for item in self.getItems(): + if item is None: + continue + if item.isSelected(): + item.setSelected(False) + + self.callEvent("onClearSelection", None) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/universal.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/universal.py new file mode 100644 index 0000000000000000000000000000000000000000..6b97ad7dbf6bb46d390253b1de64109e6c2a9b54 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/universal.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Github Code Home Page:** https://github.com/makehumancommunity/ + +**Authors:** Glynn Clements + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman Community (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- + +TODO +""" + +import json +import os +from typing import Any + +from library.getpath import getPath + +_PRE_STARTUP_KEYS = ["useHDPI", "noShaders", "noSampleBuffers"] + + +class Globals(object): + def __init__(self): + self.app: Any = None + self.args = {} + self.world = [] + self.cameras = [] + self.canvas = None + self.windowHeight = 600 + self.windowWidth = 800 + self.clearColor = (0.0, 0.0, 0.0, 0.0) + self.preStartupSettings = dict() + self._preStartupConfigScan() + + def _preStartupConfigScan(self): + """Run a very primitive scan in order to pick up settings which has + to be known before we launch the QtApplication object.""" + iniPath = getPath("settings.ini") + data = None + if os.path.exists(iniPath): + with open(iniPath, encoding="utf-8") as f: + data = json.load(f) + if data is None: + for key in _PRE_STARTUP_KEYS: + self.preStartupSettings[key] = None + else: + for key in _PRE_STARTUP_KEYS: + if key in data: + self.preStartupSettings[key] = data[key] + # Would be nice to log this, but log has not been initialized yet + print("PRE STARTUP SETTING: " + key + " = " + str(data[key])) + else: + self.preStartupSettings[key] = None + + +G = Globals() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/xdg_parser.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/xdg_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..0445b7c0702479865daec8da69ab23f4af80ce9e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/library/xdg_parser.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +**Project Name:** MakeHuman + +**Product Home Page:** http://www.makehumancommunity.org/ + +**Code Home Page:** https://github.com/makehumancommunity/makehuman + +**Authors:** Aranuvir + +**Copyright(c):** MakeHuman Team 2001-2020 + +**Licensing:** AGPL3 + + This file is part of MakeHuman (www.makehumancommunity.org). + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + +Abstract +-------- +This module provides the "well known" user directories from a Linux Desktop. Common +directories are 'DESKTOP', 'DOCUMENTS', 'DOWNLOAD', 'MUSIC', 'PICTURES', ' +PUBLICSHARE', 'TEMPLATES' and 'VIDEOS'. The predefined directories and their +paths are stored in the dictionary XDG_PATHS, which will be None on platforms other +than Linux.""" + + +import os +import sys + +isLinux = sys.platform.startswith("linux") + +if isLinux: + + # Default path to xdg configuration file + CONFIG_PATH = os.path.expanduser("~/.config/user-dirs.dirs") + + def get_userdirs(path=CONFIG_PATH): + """This function parses a configuration file to retrieve user directories and their configured paths. + Environment variables are replaced by their values""" + + dirs = dict() + + if os.path.isfile(path): + with open(path, "r", encoding="utf-8") as file: + for line in file: + if line and line.startswith("XDG_"): + line = line.strip() + key, value = line.split("=") + key = key.split("_")[1] + value = os.path.expandvars(value.strip('"')) + if os.path.isdir(value): + dirs[key] = value + + return dirs + +else: + + def get_userdirs(path=""): + """Dummy function for use on other Platform than Linux""" + return {} + + +XDG_PATHS = get_userdirs() + +if XDG_PATHS: + XDG_DIRS = sorted(XDG_PATHS.keys()) +else: + XDG_DIRS = [] + + +# Main Function ############################################################# +if __name__ == "__main__": + + if isLinux and XDG_DIRS: + + print("Found XDG_DIRS:", ", ".join(XDG_DIRS), "\n") + + max_len = max([len(d) for d in XDG_DIRS]) + f_str = "{0:" + str(max_len) + "s} ---> {1}" + + for d in XDG_DIRS: + print(f_str.format(d, XDG_PATHS.get(d))) + + else: + + print("This module should be used on Linux platforms only!") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/main.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/main.py new file mode 100644 index 0000000000000000000000000000000000000000..ad6cbd3158dfd12ef61772b3f2e1f8f53eed248f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/gui/main.py @@ -0,0 +1,547 @@ +import json +import os +import signal +import subprocess +import sys +from typing import Dict + +import library.log as log +import library.qtgui as qtgui +from library.universal import G +from PyQt6.QtCore import QProcess, QSettings, Qt +from PyQt6.QtWidgets import ( + QApplication, + QCheckBox, + QComboBox, + QFormLayout, + QGridLayout, + QHBoxLayout, + QLabel, + QLineEdit, + QMainWindow, + QPushButton, + QVBoxLayout, + QWidget, +) + +import decoupled_wbc + +signal.signal(signal.SIGINT, signal.SIG_DFL) + + +GR00T_TELEOP_DATA_ROOT = os.path.join(os.path.dirname(decoupled_wbc.__file__), "./external/teleop/data") + + +class MainWindow(QMainWindow): + def __init__( + self, + fix_pick_up=True, + fix_pointing=False, + object_A_options=[ + "small cup", + "dragon fruit", + "orange", + "apple", + "mango", + "star fruit", + "rubiks cube", + "lemon", + "lime", + "red can", + "blue can", + "green can", + "cucumber", + "bottled water", + "big cup", + "mayo", + "mustard", + "bok choy", + "grapes", + "soup can", + "mouse", + "water apple", + "corn", + "mug", + "orange cup", + "bitter gourd", + "banana", + "mangosteen", + "marker", + "coffee pod", + "plastic cup", + "grapes", + "small mug", + "condiment bottles", + "corn", + "tools", + "pear", + "eggplant", + "canned beans", + "potato", + ], + object_from_options=[ + "cutting board", + "pan", + "plate", + "bowl", + "tray", + "desk", + "placemat", + "table", + "mesh cup", + "shelf", + ], + object_to_options=[ + "cutting board", + "pan", + "plate", + "bowl", + "tray", + "microwave", + "basket", + "drawer", + "placemat", + "clear bin", + "mesh cup", + "yellow bin", + "shelf", + ], + ): + super().__init__() + # Fix the pick up and place object type + self.fix_pick_up = fix_pick_up + self.fix_pointing = fix_pointing + + # window settings + self.setWindowTitle("Gr00t Capture Test") + self.setFixedWidth(800) + self.setMinimumHeight(1000) + + self.main_layout = QVBoxLayout() + self.main_layout.setAlignment(Qt.AlignmentFlag.AlignTop) + + # stop button + self.stop_button = QPushButton("Emergency Stop", self) + self.stop_button.setStyleSheet( + "background-color: red; color: white; font-size: 20px; font-weight: bold; height: 60px;" + ) + # self.stop_button.setEnabled(False) + self.stop_button.clicked.connect(self.stop_process) + self.main_layout.addWidget(self.stop_button) + + # property label + self.property_label = QLabel("Settings") + self.property_label.setStyleSheet( + "font-size: 20px; font-weight: bold; color: #333; max-hedescription.jight: 30px;" + ) + self.main_layout.addWidget(self.property_label) + + # operator form + settings_form_layout = QFormLayout() + self.operator_input = QLineEdit("Zu") + # self.operator_input.textChanged.connect(self.property_label.setText) + settings_form_layout.addRow(QLabel("Operator Name:"), self.operator_input) + + # collector form + self.collector_input = QLineEdit("Zu") + settings_form_layout.addRow(QLabel("Collector Name:"), self.collector_input) + + # description form + self.description_input = QLineEdit("3D pick up") + + # object A menu + self.object_A_input = QComboBox() + self.object_A_input.addItems(object_A_options) + + # object A menu + self.object_from_input = QComboBox() + self.object_from_input.addItems(object_from_options) + + # object B menu + self.object_to_input = QComboBox() + self.object_to_input.addItems(object_to_options) + + box_layout = QHBoxLayout() + box_layout.setAlignment(Qt.AlignmentFlag.AlignLeft) + if self.fix_pick_up: + # box_layout.addWidget(QLabel("Pour Object:")) + box_layout.addWidget(QLabel("Pick up Object:")) + box_layout.addWidget(self.object_A_input) + box_layout.addWidget(QLabel("from:")) + box_layout.addWidget(self.object_from_input) + box_layout.addWidget(QLabel("To:")) + box_layout.addWidget(self.object_to_input) + elif self.fix_pointing: + box_layout.addWidget(QLabel("Pointing Object:")) + box_layout.addWidget(self.object_A_input) + else: + box_layout.addWidget(self.description_input) + + # add a button to fix the pick up and place object + self.save_description_button = QPushButton("Save Description") + self.save_description_button.setMinimumWidth(100) + self.save_description_button.clicked.connect(self.save_settings) + box_layout.addWidget(self.save_description_button) + + settings_form_layout.addRow(QLabel("Task description:"), box_layout) + + # robot form + self.robot_input = QLineEdit("gr00t002") + settings_form_layout.addRow(QLabel("Robot Name:"), self.robot_input) + + # vive keyword form + self.vive_keyword_input = QComboBox() + self.vive_keyword_input.addItems(["elbow", "knee", "wrist", "shoulder", "foot"]) + settings_form_layout.addRow(QLabel("Vive keyword:"), self.vive_keyword_input) + + settings_form_layout.addRow(QLabel("-" * 300)) + self.vive_ip_input = QLineEdit("192.168.0.182") + settings_form_layout.addRow(QLabel("Vive ip:"), self.vive_ip_input) + + self.vive_port_input = QLineEdit("5555") + settings_form_layout.addRow(QLabel("Vive port:"), self.vive_port_input) + self.manus_port_input = QLineEdit("5556") + settings_form_layout.addRow(QLabel("Manus port:"), self.manus_port_input) + + # manus form + # self.manus_input = QLineEdit("foot") + # settings_form_layout.addRow(QLabel("Manus name:"), self.manus_input) + + self.main_layout.addLayout(settings_form_layout) + + # testing buttons + self.testing_button_layout = QGridLayout() + + # vive button + self.test_vive_button = QPushButton("Test Vive") + self.test_vive_button.setCheckable(True) + self.test_vive_button.toggled.connect(self.test_vive) + self.test_vive_button.setMaximumHeight(30) + self.testing_button_layout.addWidget(self.test_vive_button, 0, 1) + self.vive_checkbox = QCheckBox("Vive Ready") + self.testing_button_layout.addWidget(self.vive_checkbox, 0, 2) + + # start manus button + self.server_manus_button = QPushButton("Start Manus") + self.server_manus_button.setCheckable(True) + self.server_manus_button.toggled.connect(self.test_manus_server) + self.server_manus_button.setMaximumHeight(30) + self.testing_button_layout.addWidget(self.server_manus_button, 1, 0) + + # manus button + self.client_manus_button = QPushButton("Test Manus") + self.client_manus_button.setCheckable(True) + self.client_manus_button.toggled.connect(self.test_manus_client) + self.client_manus_button.setMaximumHeight(30) + self.testing_button_layout.addWidget(self.client_manus_button, 1, 1) + + self.manus_checkbox = QCheckBox("Manus Ready") + self.manus_checkbox.setEnabled(False) + self.testing_button_layout.addWidget(self.manus_checkbox, 1, 2) + + # self.testing_button_layout.addWidget() + self.main_layout.addLayout(self.testing_button_layout) + + container = QWidget() + container.setLayout(self.main_layout) + + # Set the central widget of the Window. + self.setCentralWidget(container) + + # Process + # QProcess for running scripts + self.process = QProcess(self) + # self.process.readyRead.connect(self.handle_stdout) + self.process.readyReadStandardOutput.connect(self.handle_stdout) + self.process.readyReadStandardError.connect(self.handle_stderr) + self.process.errorOccurred.connect(self.process_error) + self.process.finished.connect(self.process_finished) + self.current_process_name = "" + + # QProcess for running scripts + self.manus_process = QProcess(self) + # self.process.readyRead.connect(self.handle_stdout) + self.manus_process.readyReadStandardOutput.connect(self.handle_stdout) + self.manus_process.readyReadStandardError.connect(self.handle_stderr) + self.manus_process.finished.connect(self.process_finished) + + # load history + self.load_settings() + + # record all buttons + self.test_buttons: Dict[str, QPushButton] = { + "test_vive": self.test_vive_button, + "test_manus": self.client_manus_button, + } + + def load_settings(self): + settings = QSettings("Gear", "Teleop") + self.vive_ip_input.setText(settings.value("vive_ip", "192.168.0.182")) + self.vive_keyword_input.setCurrentIndex(int(settings.value("vive_keyword", 0))) + self.robot_input.setText(settings.value("robot_input", "")) + self.operator_input.setText(settings.value("operator", "")) + self.collector_input.setText(settings.value("data_collector", "")) + self.description_input.setText(settings.value("description", "")) + self.object_A_input.setCurrentIndex(int(settings.value("object", 0))) + self.object_from_input.setCurrentIndex(int(settings.value("object_from", 0))) + self.object_to_input.setCurrentIndex(int(settings.value("object_to", 0))) + + def save_settings(self): + # Create QSettings object (You can provide your app name and organization for persistent storage) + settings = QSettings("Gear", "Teleop") + + # Save the text from the QLineEdit + settings.setValue("vive_ip", self.vive_ip_input.text()) + settings.setValue("vive_keyword", self.vive_keyword_input.currentIndex()) + settings.setValue("robot_input", self.robot_input.text()) + settings.setValue("operator", self.operator_input.text()) + settings.setValue("data_collector", self.collector_input.text()) + + if self.fix_pick_up: + description = ( + f"pick {self.object_A_input.currentText()} " + f"{self.object_from_input.currentText()}->" + f"{self.object_to_input.currentText()}" + ) + elif self.fix_pointing: + description = f"point at {self.object_A_input.currentText()}" + else: + description = self.description_input.text() + + settings.setValue("description", description) + settings.setValue("object", self.object_A_input.currentIndex()) + settings.setValue("object_from", self.object_from_input.currentIndex()) + settings.setValue("object_to", self.object_to_input.currentIndex()) + + # Save the settings + descrition_file = os.path.join(GR00T_TELEOP_DATA_ROOT, "description.json") + with open(descrition_file, "w") as f: + json.dump( + { + "operator": self.operator_input.text(), + "data_collector": self.collector_input.text(), + "description": description, + }, + f, + ) + print("Settings saved to {}".format(descrition_file)) + + ################################# Process ################################# + def handle_stdout(self): + data = self.process.readAllStandardOutput().data() + stdout = data.decode("utf-8") + G.app.log_window.addLogMessage(stdout, log.DEBUG) + + data = self.manus_process.readAllStandardOutput().data() + stdout = data.decode("utf-8") + G.app.log_window.addLogMessage(stdout, log.DEBUG) + + def handle_stderr(self): + data = self.process.readAllStandardError().data() + stderr = data.decode("utf-8") + G.app.log_window.addLogMessage(stderr, log.ERROR) + + data = self.manus_process.readAllStandardError().data() + stderr = data.decode("utf-8") + G.app.log_window.addLogMessage(stderr, log.ERROR) + + def process_finished(self, exit_code, exit_status): + if exit_status == QProcess.ExitStatus.NormalExit: + G.app.log_window.addLogMessage( + f"Process finished successfully with exit code {exit_code}.", log.INFO + ) + else: + G.app.log_window.addLogMessage( + f"Process finished with error code {exit_code}.", log.ERROR + ) + + G.app.log_window.addLogMessage("---------------------------------------------", log.INFO) + + # toggle the button for the current task + print("current_process_name", self.current_process_name, self.test_buttons.keys()) + if self.current_process_name in self.test_buttons.keys(): + if self.test_buttons[self.current_process_name].isChecked(): + self.test_buttons[self.current_process_name].click() + + def process_error(self, error): + G.app.log_window.addLogMessage(f"Process Error (or stopped manually): {error}", log.ERROR) + G.app.log_window.addLogMessage("---------------------------------------------", log.INFO) + + ################################# Timer ################################# + + def update_log(self): + print("update log") + # G.app.log_window.addLogMessage("Update log", log.DEBUG) + returnBool = self.process.waitForFinished(1000) + print("returnBool", returnBool) + if not returnBool: + data = self.process.readAllStandardOutput().data() + stdout = data.decode("utf8") + if stdout: + G.app.log_window.addLogMessage(stdout, log.DEBUG) + G.app.log_window.updateView() + + def test_vive(self, checked): + print("checked", checked) + if not checked: + self.test_vive_button.setText("Test Vive") + self.stop_process() + self.current_process_name = "" + else: + self.current_process_name = "test_vive" + self.test_vive_button.setText("Stop Test") + self.stop_button.setEnabled(True) + G.app.log_window.addLogMessage("Testing Vive", log.DEBUG) + script = "python" + args = [ + "decoupled_wbc/control/teleop/main/test_vive.py", + "--keyword", + self.vive_keyword_input.currentText(), + "--ip", + self.vive_ip_input.text(), + "--port", + self.vive_port_input.text(), + ] + self.process.start(script, args) + + def test_manus_server(self, checked): + if not checked: # 2 + self.server_manus_button.setText("Start Manus") + self.stop_manus_server() + self.manus_checkbox.setEnabled(False) + else: # 1 + self.server_manus_button.setText("Stop Manus") + self.manus_checkbox.setEnabled(True) + self.start_manus_server() + + def start_manus_server(self): + G.app.log_window.addLogMessage("Starting manus server", log.WARNING) + script = "python" + args = ["decoupled_wbc/control/teleop/device/manus.py", "--port", self.manus_port_input.text()] + self.manus_process.start(script, args) + + def stop_manus_server(self): + G.app.log_window.addLogMessage("Stopping manus server", log.WARNING) + self.manus_process.terminate() + self.manus_process.waitForFinished(2000) + if self.manus_process.state() != QProcess.ProcessState.NotRunning: + self.manus_process.kill() + self.stop_button.setEnabled(False) + G.app.log_window.addLogMessage("Manus stopped", log.DEBUG) + + def test_manus_client(self, checked): + if not checked: + self.client_manus_button.setText("Test Manus") + self.stop_process() + self.current_process_name = "" + else: + self.current_process_name = "test_manus" + self.client_manus_button.setText("Stop Test") + self.stop_button.setEnabled(True) + G.app.log_window.addLogMessage("Testing", log.DEBUG) + print("Testing manus") + script = "python" + args = [ + "decoupled_wbc/control/teleop/main/test_manus.py", + "--port", + self.manus_port_input.text(), + ] + self.process.start(script, args) + + ############################### Stop Process ################################# + + def stop_process(self): + G.app.log_window.addLogMessage("Stopping process", log.WARNING) + # disable all buttons + for button in self.test_buttons.values(): + button.setCheckable(False) + button.setChecked(False) + button.setEnabled(False) + + # kill the process + if self.process.state() == QProcess.ProcessState.Running: + # os.kill(self.process.processId(), signal.SIGINT) + self.process.waitForFinished(2000) # Wait for up to 2 seconds for termination + if self.process.state() != QProcess.ProcessState.NotRunning: + self.process.kill() + # self.stop_button.setEnabled(False) + G.app.log_window.addLogMessage("Script stopped", log.DEBUG) + + if self.current_process_name in ["test_oak", "record_demonstration", "test_robot"]: + command = ( + f"ps aux | grep {self.current_process_name}" + + " | grep -v grep | awk '{print $2}' | xargs kill" + ) + + # Execute the command with subprocess.Popen, capturing both stdout and stderr + sub_process = subprocess.Popen( + command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + # Get the output and errors (if any) + stdout, stderr = sub_process.communicate() + # Ensure the process is successfully terminated + sub_process.wait() + + # enable all buttons + for button in self.test_buttons.values(): + button.setCheckable(True) + button.setEnabled(True) + + # check the button if the button was checked + if self.current_process_name in self.test_buttons.keys(): + if self.test_buttons[self.current_process_name].isChecked(): + self.test_buttons[self.current_process_name].setChecked(False) + + +class LogWindow(qtgui.ListView): + def __init__(self): + super(LogWindow, self).__init__() + self.level = log.DEBUG + self.allowMultipleSelection(True) + + def setLevel(self, level): + self.level = level + self.updateView() + + def keyPressEvent(self, e): + e.ignore() + + def updateView(self): + for i in range(self.count()): + ilevel = self.getItemData(i) + self.showItem(i, ilevel >= self.level) + self.setItemColor(i, log.getLevelColor(ilevel)) + + def addLogMessage(self, text, level=log.INFO): + index = self.count() + color = log.getLevelColor(level) + self.addLogItem(text, color, level) + self.showItem(index, level >= self.level) + + +class GCApplication(QApplication): + def __init__(self, argv): + super(GCApplication, self).__init__(argv) + + # application + if G.app is not None: + raise RuntimeError("MHApplication is a singleton") + G.app = self + + self.mainwin = MainWindow() + self.log_window = LogWindow() + self.mainwin.main_layout.addWidget(self.log_window) + self.mainwin.show() + # self.log_window.show() + + +# Function to terminate the subprocess gracefully +def terminate_subprocess(proc): + if proc.poll() is None: # Check if the process is still running + proc.terminate() # Terminate the process + print("Subprocess terminated.") + + +if __name__ == "__main__": + app = GCApplication(sys.argv) + sys.exit(app.exec()) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_iphone.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_iphone.py new file mode 100644 index 0000000000000000000000000000000000000000..f46bca6ed1884f3e2c1b0128baaac863daf7884b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_iphone.py @@ -0,0 +1,306 @@ +import argparse +import time + +import matplotlib.pyplot as plt +import numpy as np + +from decoupled_wbc.control.teleop.device.iphone.iphone import IPhoneDevice + + +class IphonePublisher: + def __init__(self, port: int = 5555, silent: bool = True): + self._device = IPhoneDevice(port=port, silent=silent) + + # record the initial transform + self._init_transform = None + self._init_transform_inverse = None + + # record the latest transform and timestamp + self._latest_transform = None + self._latest_timestamp = None + + # publishing variables + self._velocity = [0, 0, 0] + self._position = [0, 0, 0] + + # visualization + self._fig = None + self._ax = None + self._setup_visualization() + + def _draw_axes(self, ax): + """Draw coordinate axes, labels, and legend on the given axes object.""" + origin = [0, 0, 0] + axis_length = 0.3 + # X axis (right) + ax.quiver( + origin[0], + origin[1], + origin[2], + axis_length, + 0, + 0, + color="r", + arrow_length_ratio=0.1, + linewidth=2, + ) + # Y axis (out/forward) + ax.quiver( + origin[0], + origin[1], + origin[2], + 0, + axis_length, + 0, + color="b", + arrow_length_ratio=0.1, + linewidth=2, + ) + # Z axis (up) + ax.quiver( + origin[0], + origin[1], + origin[2], + 0, + 0, + axis_length, + color="g", + arrow_length_ratio=0.1, + linewidth=2, + ) + ax.text(axis_length, 0, 0, "X", color="red") + ax.text(0, axis_length, 0, "Y", color="blue") + ax.text(0, 0, axis_length, "Z", color="green") + from matplotlib.lines import Line2D + + legend_elements = [ + Line2D([0], [0], color="r", lw=2, label="X axis (right)"), + Line2D([0], [0], color="g", lw=2, label="Y axis (out)"), + Line2D([0], [0], color="b", lw=2, label="Z axis (up)"), + ] + ax.legend(handles=legend_elements, loc="upper right") + + def _draw_cube(self, ax): + """Draw a 1x1x1 meter cube centered at the origin on the given axes object.""" + r = [-0.5, 0.5] + corners = [ + [r[0], r[0], r[0]], + [r[0], r[0], r[1]], + [r[0], r[1], r[0]], + [r[0], r[1], r[1]], + [r[1], r[0], r[0]], + [r[1], r[0], r[1]], + [r[1], r[1], r[0]], + [r[1], r[1], r[1]], + ] + edges = [ + (0, 1), + (0, 2), + (0, 4), + (1, 3), + (1, 5), + (2, 3), + (2, 6), + (3, 7), + (4, 5), + (4, 6), + (5, 7), + (6, 7), + ] + for i, j in edges: + x = [corners[i][0], corners[j][0]] + y = [corners[i][1], corners[j][1]] + z = [corners[i][2], corners[j][2]] + ax.plot3D(x, y, z, "gray") + + def _setup_visualization(self): + """Setup matplotlib figure for 6D pose visualization""" + plt.ion() # Enable interactive mode + self._fig = plt.figure(figsize=(8, 8)) + self._ax = self._fig.add_subplot(111, projection="3d") + self._ax.set_xlim([-0.5, 0.5]) + self._ax.set_ylim([-0.5, 0.5]) + self._ax.set_zlim([-0.5, 0.5]) + self._ax.set_xlabel("X (right)") + self._ax.set_ylabel("Y (out)") + self._ax.set_zlabel("Z (up)") + self._ax.set_title("iPhone 6D Pose") + self._ax.view_init(elev=30, azim=-45) + self._draw_cube(self._ax) + self._draw_axes(self._ax) + plt.tight_layout() + self._fig.canvas.draw() + plt.pause(0.001) + + def start(self): + self._device.start() + + def stop(self): + self._device.stop() + if self._fig is not None: + plt.close(self._fig) + + def reset_transform(self, *args, timeout=5.0, poll_interval=0.1): + """ + Wait until device returns data, then set the initial transform. + + Args: + timeout (float): Maximum time to wait in seconds. + poll_interval (float): Time between checks in seconds. + """ + start_time = time.time() + while True: + data = self._device.get_cmd() + if data: + self._init_transform = np.array(data.get("transformMatrix")) + self._init_transform_inverse = np.linalg.inv(self._init_transform) + print( + "initial position", [round(v, 4) for v in self._init_transform[:3, 3].tolist()] + ) + self._latest_transform = self._init_transform.copy() + self._latest_timestamp = data.get("timestamp") + print("Initial transform set.") + break + elif time.time() - start_time > timeout: + print("Timeout: Failed to get initial transform data after waiting.") + break + else: + time.sleep(poll_interval) + + return {"success": True, "message": "Triggered!"} + + def update_transfrom(self) -> dict: + data = self._device.get_cmd() + + if data: + transform_matrix = np.array(data.get("transformMatrix")) + position = transform_matrix[:3, 3] + rotation = transform_matrix[:3, :3] + + # Create a single multiline string with position and rotation data + output = f"\r\033[KPosition: {[round(v, 4) for v in position.tolist()]}\n" + output += "\033[KRotation matrix:\n" + for i in range(3): + row = [round(v, 4) for v in rotation[i].tolist()] + output += f"\033[K {row}\n" + + # Move cursor up 5 lines (position + "rotation matrix:" + 3 rows) + # and print the entire output at once + print(f"\033[5A{output}", end="", flush=True) + + # draw 6d pose + self._visualize_pose(position, rotation) + + if data: + current_transform = np.array(data.get("transformMatrix")) @ self._init_transform_inverse + # print("current_transform", [round(v, 4) for v in current_transform.flatten().tolist()]) + current_timestamp = data.get("timestamp") + + # Check if the current timestamp is the same as the latest timestamp (No update or disconnect) + if current_timestamp == self._latest_timestamp: + return { + "transform_matrix": self._latest_transform, + "velocity": [0, 0, 0], + "position": self._latest_transform[:3, 3].tolist(), + "timestamp": self._latest_timestamp, + } + + if self._latest_transform is not None: + current_position = current_transform[:3, 3] + current_velocity = (current_position - self._latest_transform[:3, 3]) / ( + current_timestamp - self._latest_timestamp + ) + self._velocity = current_velocity.tolist() + self._position = current_position.tolist() + + self._latest_transform = current_transform.copy() + self._latest_timestamp = current_timestamp + + return { + "transform_matrix": self._latest_transform, + "velocity": self._velocity, + "position": self._position, + "timestamp": self._latest_timestamp, + } + + def _visualize_pose(self, position, rotation): + """Visualize the 6D pose using matplotlib""" + if self._fig is None or not plt.fignum_exists(self._fig.number): + self._setup_visualization() + self._ax.clear() + self._ax.set_xlim([-0.5, 0.5]) + self._ax.set_ylim([-0.5, 0.5]) + self._ax.set_zlim([-0.5, 0.5]) + self._ax.set_xlabel("X (right)") + self._ax.set_ylabel("Y (out)") + self._ax.set_zlabel("Z (up)") + self._ax.set_title("iPhone 6D Pose") + self._ax.view_init(elev=30, azim=-45) + self._draw_cube(self._ax) + self._draw_axes(self._ax) + # Draw position as a marker + pos = np.clip(position, -0.5, 0.5) + self._ax.scatter(pos[0], pos[1], pos[2], color="red", s=100, marker="o") + # Draw orientation axes + length = 0.2 + colors = ["r", "b", "g"] # X=red, Y=blue, Z=green + for i in range(3): + direction = rotation[:, i] * length + self._ax.quiver( + pos[0], + pos[1], + pos[2], + direction[0], + direction[1], + direction[2], + color=colors[i], + arrow_length_ratio=0.2, + linewidth=2, + ) + self._fig.canvas.draw() + plt.pause(0.001) + + +def main(): + # Parse command line arguments + parser = argparse.ArgumentParser() + parser.add_argument("--fps", type=int, default=20, help="Frames per second (default: 20)") + parser.add_argument( + "--timeout", + type=int, + default=30, + help="Timeout for waiting for the device to connect (default: 30 seconds)", + ) + parser.add_argument("--debug", action="store_true", help="Enable debug mode") + args = parser.parse_args() + fps = args.fps + timeout = args.timeout + + # Initialize the iPhone publisher + iphone_publisher = IphonePublisher(port=5555, silent=False) + iphone_publisher.start() + print("Waiting for device to connect...press the reset button on the device to start") + iphone_publisher.reset_transform( + timeout=timeout + ) # wait x seconds for the device to return data + + def update_and_visualize(): + # Update the transform and get the latest data + data = iphone_publisher.update_transfrom() + + # print the data for debugging + if args.debug and np.random.rand() < 1 / fps: + print("data", data) + + try: + while True: + update_and_visualize() + time.sleep(1.0 / fps) + except KeyboardInterrupt: + print("Stopping device...") + finally: + iphone_publisher.stop() + + +if __name__ == "__main__": + main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_manus.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_manus.py new file mode 100644 index 0000000000000000000000000000000000000000..81f6967c0c0fd4c0bb262d2f3091e22c449beff2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_manus.py @@ -0,0 +1,102 @@ +import pickle +import time + +import click +import matplotlib.pyplot as plt +import numpy as np +import zmq + + +def plot_fingertips(data, ax): + """Plot specific fingertip positions of left and right fingers in 3D space.""" + + left_fingertips = data["left_fingers"]["position"] + right_fingertips = data["right_fingers"]["position"] + + # Extract X, Y, Z positions of fingertips from the transformation matrices + left_positions = np.array([finger[:3, 3] for finger in left_fingertips]) + right_positions = np.array([finger[:3, 3] for finger in right_fingertips]) + + # Ensure the positions are 2D arrays (N, 3) + left_positions = np.reshape(left_positions, (-1, 3)) # Ensure 2D array with shape (N, 3) + right_positions = np.reshape(right_positions, (-1, 3)) # Ensure 2D array with shape (N, 3) + + # Create a 3D plot + ax.cla() # Clear the previous plot + + # Plot selected left fingertips (use red color) + ax.scatter( + left_positions[:, 0], + left_positions[:, 1], + left_positions[:, 2], + c="r", + label="Left Fingers", + ) + ax.scatter( + right_positions[:, 0], + right_positions[:, 1], + right_positions[:, 2], + c="b", + label="Right Fingers", + ) + # ax.scatter(avp_left_fingers[:, 0], avp_left_fingers[:, 1], avp_left_fingers[:, 2], c='b', label='AVP') + + # Set plot labels + ax.set_xlabel("X") + ax.set_ylabel("Y") + ax.set_zlabel("Z") + + ax.set_xlim([-0.3, 0.3]) # Set X-axis limits, adjust to your range + ax.set_ylim([-0.3, 0.3]) # Set Y-axis limits, adjust to your range + ax.set_zlim([-0.3, 0.3]) # Set Z-axis limits, adjust to your range + + # Add a legend + ax.legend() + + # Display the plot (update it) + plt.draw() + plt.pause(0.00001) + + +class ManusVisClient: + def __init__(self, port=5556): + self.context = zmq.Context() + self.socket = self.context.socket(zmq.REQ) # Use REQ instead of SUB + self.socket.connect(f"tcp://localhost:{port}") + + def request_data(self): + """Request the latest data from the server.""" + # Send request to the server + self.socket.send(b"request_data") # Send a request message + + # Wait for the server's response + message = self.socket.recv() # Receive response + data = pickle.loads(message) # Deserialize the data + + return data + + +@click.command() +@click.option("--port", type=int, default=5556) +def main(port): + print("==>start test manus") + plt.ion() + fig = plt.figure() + ax = fig.add_subplot(111, projection="3d") + + client = ManusVisClient(port=port) + + iter_idx = 0 + while True: + data = client.request_data() + plot_fingertips(data, ax) + + time.sleep(0.1) + iter_idx += 1 + if iter_idx > 100: + break + + +# Run the client +if __name__ == "__main__": + main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_vive.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_vive.py new file mode 100644 index 0000000000000000000000000000000000000000..7c957c7b083d36c49932edd618e375a229f297bc --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/main/test_vive.py @@ -0,0 +1,82 @@ +import click +import matplotlib.animation as animation +import matplotlib.pyplot as plt +import numpy as np + +from decoupled_wbc.control.teleop.streamers.vive_streamer import ViveStreamer + + +@click.command() +@click.option("--ip", default="192.168.0.182", help="IP address of the Vive Tracker") +@click.option("--port", default=5555, help="Port number of the Vive Tracker") +@click.option("--keyword", default="elbow", help="Keyword to filter the tracker data") +def main(ip, port, keyword): + print("==>start test vive") + streamer = ViveStreamer(ip=ip, port=port, fps=20, keyword=keyword) + streamer.start_streaming() + + # Create figure and 3D axis + fig = plt.figure() + ax = fig.add_subplot(111, projection="3d") + + pos_data = {} + pose_data_init = {} + ax_line = {} + for dir in ["left", "right"]: + pose_data_init[dir] = None + pos_data[dir] = list() + # Initialize a line object that will be updated in the animation + color = "r" if dir == "left" else "b" + ax_line[dir] = ax.plot([], [], [], f"{color}-", marker="o")[0] + + # Set plot limits (adjust as needed) + ax.set_xlim(-1, 1) + ax.set_ylim(-1, 1) + ax.set_zlim(-1, 1) + + # Set axis labels + ax.set_xlabel("X") + ax.set_ylabel("Y") + ax.set_zlabel("Z") + + # Define the initialization function for the animation + def init(): + for dir in ["left", "right"]: + ax_line[dir].set_data([], []) + ax_line[dir].set_3d_properties([]) + + return ax_line["left"], ax_line["right"] + + # Define the update function that will update the trajectory in real-time + def update(num): + streamer_output = streamer.get() + + # Handle case where no data is available yet + if not streamer_output or not streamer_output.ik_data: + return ax_line["left"], ax_line["right"] + + for dir in ["left", "right"]: + wrist_key = f"{dir}_wrist" + if wrist_key not in streamer_output.ik_data: + continue + + raw_pose = streamer_output.ik_data[wrist_key] + if pose_data_init[dir] is None: + pose_data_init[dir] = raw_pose + relative_pose = np.linalg.inv(pose_data_init[dir]) @ raw_pose + pos_data[dir].append(relative_pose[:3, 3]) + pos_data_np = np.array(pos_data[dir]) + ax_line[dir].set_data(pos_data_np[:, 0], pos_data_np[:, 1]) + ax_line[dir].set_3d_properties(pos_data_np[:, 2]) + return ax_line["left"], ax_line["right"] + + # Create the animation + _ = animation.FuncAnimation(fig, update, init_func=init, frames=20, interval=50, blit=True) + + # Show the plot + plt.show(block=False) + plt.pause(5) + + +if __name__ == "__main__": + main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/fingers/fingers.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/fingers/fingers.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ec7a4bb935309bf1f5442d76fb17dead56eeb9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/fingers/fingers.py @@ -0,0 +1,16 @@ +from decoupled_wbc.control.teleop.pre_processor.pre_processor import PreProcessor + + +class FingersPreProcessor(PreProcessor): + """Dummy class just takes out the fingers from the data.""" + + def __init__(self, side: str): + super().__init__() + self.side = side + + def __call__(self, data): + return data[f"{self.side}_fingers"] + + # TODO: calibrate max and min + def calibrate(self, data, control_device): + pass diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/pre_processor.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/pre_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..76c5d6f0acc3990470e4457c2733e1b3f46ceec7 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/pre_processor.py @@ -0,0 +1,13 @@ +import abc + + +class PreProcessor(abc.ABC): + def __init__(self, **kwargs): + pass + + def register(self, robot): + self.robot = robot + + @abc.abstractmethod + def __call__(self, data) -> dict: + pass diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/wrists/wrists.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/wrists/wrists.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f8fd9b0d37a173fa56a14dee984c3c8f54b1b4 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/pre_processor/wrists/wrists.py @@ -0,0 +1,110 @@ +from copy import deepcopy + +import numpy as np + +from decoupled_wbc.control.teleop.pre_processor.pre_processor import PreProcessor + +RIGHT_HAND_ROTATION = np.array([[-1, 0, 0], [0, -1, 0], [0, 0, 1]]) + + +class WristsPreProcessor(PreProcessor): + def __init__(self, motion_scale: float, **kwargs): + super().__init__(**kwargs) + self.motion_scale = motion_scale # scale factor for robot motion + self.calibration_ee_pose = {} # poses to calibrate the robot + self.ee_name_list = ( + [] + ) # name of the end-effector "link_head_pitch", "link_LArm7", "link_RArm7" + self.robot_world_T_init_ee = {} # initial end-effector pose of the robot + self.init_teleop_T_teleop_world = {} # initial transformation matrix + self.init_teleop_T_init_ee = {} # alignment of end effector and local teleop frames + + self.latest_data = None + + def calibrate(self, data, control_device): + left_elbow_joint_name = self.robot.supplemental_info.joint_name_mapping["elbow_pitch"][ + "left" + ] + right_elbow_joint_name = self.robot.supplemental_info.joint_name_mapping["elbow_pitch"][ + "right" + ] + if "left_wrist" in data: + self.ee_name_list.append(self.robot.supplemental_info.hand_frame_names["left"]) + self.calibration_ee_pose[left_elbow_joint_name] = ( + self.robot.supplemental_info.elbow_calibration_joint_angles["left"] + ) + if "right_wrist" in data: + self.ee_name_list.append(self.robot.supplemental_info.hand_frame_names["right"]) + self.calibration_ee_pose[right_elbow_joint_name] = ( + self.robot.supplemental_info.elbow_calibration_joint_angles["right"] + ) + + if self.calibration_ee_pose: + q = deepcopy(self.robot.q_zero) + # set pose + for joint, degree in self.calibration_ee_pose.items(): + joint_idx = self.robot.joint_to_dof_index[joint] + q[joint_idx] = np.deg2rad(degree) + self.robot.cache_forward_kinematics(q, auto_clip=False) + calibration_ee_poses = [ + self.robot.frame_placement(ee_name).np for ee_name in self.ee_name_list + ] + self.robot.reset_forward_kinematics() + else: + calibration_ee_poses = [ + self.robot.frame_placement(ee_name).np for ee_name in self.ee_name_list + ] + + for ee_name in self.ee_name_list: + self.robot_world_T_init_ee[ee_name] = deepcopy( + calibration_ee_poses[self.ee_name_list.index(ee_name)] + ) + self.init_teleop_T_teleop_world[ee_name] = ( + np.linalg.inv(deepcopy(data["left_wrist"])) + if ee_name == self.robot.supplemental_info.hand_frame_names["left"] + else np.linalg.inv(deepcopy(data["right_wrist"])) + ) + + # Initial teleop local frame is aligned with the initial end effector + # local frame with hardcoded rotations since we don't have a common + # reference frame for teleop and robot. + self.init_teleop_T_init_ee[ee_name] = np.eye(4) + if control_device == "pico": + # TODO: add pico wrist calibration respect to the headset frame + pass + else: + if ee_name == self.robot.supplemental_info.hand_frame_names["left"]: + self.init_teleop_T_init_ee[ee_name][ + :3, :3 + ] = self.robot.supplemental_info.hand_rotation_correction + else: + self.init_teleop_T_init_ee[ee_name][:3, :3] = ( + RIGHT_HAND_ROTATION @ self.robot.supplemental_info.hand_rotation_correction + ) + + def __call__(self, data) -> dict: + processed_data = {} + for ee_name in self.ee_name_list: + # Select wrist data based on ee_name + teleop_world_T_final_teleop = ( + data["left_wrist"] + if ee_name == self.robot.supplemental_info.hand_frame_names["left"] + else data["right_wrist"] + ) + init_teleop_T_final_teleop = ( + self.init_teleop_T_teleop_world[ee_name] @ teleop_world_T_final_teleop + ) + # End effector differential transform is teleop differential transform expressed + # in the end effector frame. + init_ee_T_final_ee = ( + np.linalg.inv(self.init_teleop_T_init_ee[ee_name]) + @ init_teleop_T_final_teleop + @ self.init_teleop_T_init_ee[ee_name] + ) + # Translation scaling + init_ee_T_final_ee[:3, 3] = self.motion_scale * init_ee_T_final_ee[:3, 3] + robot_world_T_final_ee = self.robot_world_T_init_ee[ee_name] @ init_ee_T_final_ee + processed_data[ee_name] = robot_world_T_final_ee + + self.latest_data = processed_data + return processed_data diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/body/body_ik_solver.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/body/body_ik_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..c208b617f5a1654d91ebcd5086c3eb6d2cbe6e3f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/body/body_ik_solver.py @@ -0,0 +1,179 @@ +from typing import Dict + +import numpy as np +import pink +from pink import solve_ik +from pink.tasks import FrameTask, PostureTask +import pinocchio as pin +import qpsolvers + +from decoupled_wbc.control.teleop.solver.body.body_ik_solver_settings import BodyIKSolverSettings +from decoupled_wbc.control.teleop.solver.solver import Solver + + +class WeightedPostureTask(PostureTask): + def __init__( + self, cost: float, weights: np.ndarray, lm_damping: float = 0.0, gain: float = 1.0 + ) -> None: + r"""Create weighted posture task. + + Args: + cost: value used to cast joint angle differences to a homogeneous + cost, in :math:`[\mathrm{cost}] / [\mathrm{rad}]`. + weights: vector of weights for each joint. + lm_damping: Unitless scale of the Levenberg-Marquardt (only when + the error is large) regularization term, which helps when + targets are unfeasible. Increase this value if the task is too + jerky under unfeasible targets, but beware that too large a + damping can slow down the task. + gain: Task gain :math:`\alpha \in [0, 1]` for additional low-pass + filtering. Defaults to 1.0 (no filtering) for dead-beat + control. + """ + super().__init__(cost=cost, lm_damping=lm_damping, gain=gain) + self.weights = weights + + def compute_error(self, configuration): + error = super().compute_error(configuration) + return self.weights * error + + def compute_jacobian(self, configuration): + J = super().compute_jacobian(configuration) + # breakpoint() + return self.weights[:, np.newaxis] * J + + def __repr__(self): + """Human-readable representation of the weighted posture task.""" + return ( + "WeightedPostureTask(" + f"cost={self.cost}, " + f"weights={self.weights}, " + f"gain={self.gain}, " + f"lm_damping={self.lm_damping})" + ) + + +class BodyIKSolver(Solver): + def __init__(self, ik_solver_settings: BodyIKSolverSettings): + self.dt = ik_solver_settings.dt + self.num_step_per_frame = ik_solver_settings.num_step_per_frame + self.amplify_factor = ik_solver_settings.amplify_factor + self.link_costs = ik_solver_settings.link_costs + self.posture_weight = ik_solver_settings.posture_weight + self.posture_cost = ik_solver_settings.posture_cost + self.posture_lm_damping = ik_solver_settings.posture_lm_damping + self.robot = None + + def register_robot(self, robot): + self.robot = robot + self.initialize() + + def initialize(self): + self.solver = qpsolvers.available_solvers[0] + if "quadprog" in qpsolvers.available_solvers: + self.solver = "quadprog" + else: + self.solver = qpsolvers.available_solvers[0] + + q_default = self.robot.q_zero.copy() + q_default[self.robot.joint_to_dof_index["left_shoulder_roll_joint"]] = 0.2 + q_default[self.robot.joint_to_dof_index["right_shoulder_roll_joint"]] = -0.2 + + self.configuration = pink.Configuration( + self.robot.pinocchio_wrapper.model, + self.robot.pinocchio_wrapper.data, + q_default, + ) + self.configuration.model.lowerPositionLimit = self.robot.lower_joint_limits + self.configuration.model.upperPositionLimit = self.robot.upper_joint_limits + + # initialize tasks + self.tasks = {} + for link_name, weight in self.link_costs.items(): + assert link_name != "posture", "posture is a reserved task name" + + # Map robot-agnostic link names to robot-specific names + if link_name == "hand": + # Use hand_frame_names from supplemental info + for side in ["left", "right"]: + frame_name = self.robot.supplemental_info.hand_frame_names[side] + task = FrameTask( + frame_name, + **weight, + ) + self.tasks[frame_name] = task + else: + # For other links, use the name directly + task = FrameTask( + link_name, + **weight, + ) + self.tasks[link_name] = task + + # add posture task + if self.posture_weight is not None: + weight = np.ones(self.robot.num_dofs) + + # Map robot-agnostic joint types to specific robot joint names using supplemental info + for joint_type, posture_weight in self.posture_weight.items(): + if joint_type not in self.robot.supplemental_info.joint_name_mapping: + print(f"Warning: Unknown joint type {joint_type}") + continue + + # Get the joint name mapping for this type + joint_mapping = self.robot.supplemental_info.joint_name_mapping[joint_type] + + # Handle both single joint names and left/right mappings + if isinstance(joint_mapping, str): + # Single joint (e.g., waist joints) + if joint_mapping in self.robot.joint_to_dof_index: + joint_idx = self.robot.joint_to_dof_index[joint_mapping] + weight[joint_idx] = posture_weight + else: + # Left/right mapping (e.g., arm joints) + for side in ["left", "right"]: + joint_name = joint_mapping[side] + if joint_name in self.robot.joint_to_dof_index: + joint_idx = self.robot.joint_to_dof_index[joint_name] + weight[joint_idx] = posture_weight + + self.tasks["posture"] = WeightedPostureTask( + cost=self.posture_cost, + weights=weight, + lm_damping=self.posture_lm_damping, + ) + else: + self.tasks["posture"] = PostureTask( + cost=self.posture_cost, lm_damping=self.posture_lm_damping + ) + for task in self.tasks.values(): + task.set_target_from_configuration(self.configuration) + + def __call__(self, target_pose: Dict): + for link_name, pose in target_pose.items(): + if link_name not in self.tasks: + continue + pose = pin.SE3(pose[:3, :3], pose[:3, 3]) + self.tasks[link_name].set_target(pose) + + for _ in range(self.num_step_per_frame): + velocity = solve_ik( + self.configuration, + self.tasks.values(), + dt=self.dt, + solver=self.solver, + ) + self.configuration.q = self.robot.clip_configuration( + self.configuration.q + velocity * self.dt * self.amplify_factor + ) + self.configuration.update() + self.robot.cache_forward_kinematics(self.configuration.q) + + return self.configuration.q.copy() + + def update_weights(self, weights): + for link_name, weight in weights.items(): + if "position_cost" in weight: + self.tasks[link_name].set_position_cost(weight["position_cost"]) + if "orientation_cost" in weight: + self.tasks[link_name].set_orientation_cost(weight["orientation_cost"]) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/body/body_ik_solver_settings.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/body/body_ik_solver_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..b8453f5e13456c35e3ae335e40298aac0bcf08da --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/body/body_ik_solver_settings.py @@ -0,0 +1,35 @@ +from dataclasses import dataclass + + +@dataclass +class BodyIKSolverSettings: + def __init__(self): + self.dt = 0.05 + self.num_step_per_frame = 3 + self.amplify_factor = 1.0 + self.posture_cost = 0.01 + self.posture_lm_damping = 1.0 + self.link_costs = { + "hand": { + "orientation_cost": 2.0, + "position_cost": 8.0, + "lm_damping": 3.0, + } + } + self.posture_weight = { + "waist_pitch": 10.0, + "waist_yaw": 2.0, + "waist_roll": 10.0, + "shoulder_pitch": 4.0, + "shoulder_roll": 3.0, + "shoulder_yaw": 0.1, + "elbow_pitch": 3.0, + "wrist_pitch": 1.0, + "wrist_yaw": 0.1, + } + # These joint limits override the joint limits in the robot model for the IK solver + self.ik_joint_limits = { + # Increase waist pitch limit since lower body policy can use hip joints to pitch + "waist_pitch": [-0.52, 0.9], + "elbow_pitch": [-1.0472, 1.4], + } diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/hand/g1_gripper_ik_solver.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/hand/g1_gripper_ik_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..0b736bf5c35e88c3c67b1479d0c4301075011665 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/hand/g1_gripper_ik_solver.py @@ -0,0 +1,137 @@ +import numpy as np + +from decoupled_wbc.control.teleop.solver.solver import Solver + + +###################################### +### Define your solver here +###################################### +class G1GripperInverseKinematicsSolver(Solver): + def __init__(self, side) -> None: + self.side = "L" if side.lower() == "left" else "R" + + def register_robot(self, robot): + pass + + def __call__(self, finger_data): + q_desired = np.zeros(7) + + # manus data + fingertips = finger_data["position"] + + # Extract X, Y, Z positions of fingertips from the transformation matrices + positions = np.array([finger[:3, 3] for finger in fingertips]) + + # Ensure the positions are 2D arrays (N, 3) + positions = np.reshape(positions, (-1, 3)) # Ensure 2D array with shape (N, 3) + + thumb_pos = positions[4, :] + index_pos = positions[4 + 5, :] + middle_pos = positions[4 + 10, :] + ring_pos = positions[4 + 15, :] + pinky_pos = positions[4 + 20, :] + + index_dist = np.linalg.norm(thumb_pos - index_pos) + middle_dist = np.linalg.norm(thumb_pos - middle_pos) + ring_dist = np.linalg.norm(thumb_pos - ring_pos) + pinky_dist = np.linalg.norm(thumb_pos - pinky_pos) + dist_threshold = 0.05 + + index_close = index_dist < dist_threshold + middle_close = middle_dist < dist_threshold + ring_close = ring_dist < dist_threshold + pinky_close = pinky_dist < dist_threshold + + if index_close: + q_desired = self._get_index_close_q_desired() + elif middle_close: + q_desired = self._get_middle_close_q_desired() + elif ring_close: + q_desired = self._get_ring_close_q_desired() + elif pinky_close: + q_desired = self._get_pinky_close_q_desired() + + return q_desired + + def _get_index_close_q_desired(self): + q_desired = np.zeros(7) + + amp0 = 0.5 + if self.side == "L": + q_desired[0] -= amp0 + else: + q_desired[0] += amp0 + + amp = 0.7 + + q_desired[1] += amp + q_desired[2] += amp + + ampA1 = 1.5 + ampB1 = 1.5 + ampA2 = 0.6 + ampB2 = 1.5 + + q_desired[3] -= ampA1 + q_desired[4] -= ampB1 + q_desired[5] -= ampA2 + q_desired[6] -= ampB2 + + return q_desired if self.side == "L" else -q_desired + + def _get_middle_close_q_desired(self): + q_desired = np.zeros(7) + + amp0 = 0.0 + if self.side == "L": + q_desired[0] -= amp0 + else: + q_desired[0] += amp0 + + amp = 0.7 + + q_desired[1] += amp + q_desired[2] += amp + + ampA1 = 1.0 + ampB1 = 1.5 + ampA2 = 1.0 + ampB2 = 1.5 + + q_desired[3] -= ampA1 + q_desired[4] -= ampB1 + q_desired[5] -= ampA2 + q_desired[6] -= ampB2 + + return q_desired if self.side == "L" else -q_desired + + def _get_ring_close_q_desired(self): + q_desired = np.zeros(7) + + amp0 = -0.5 + if self.side == "L": + q_desired[0] -= amp0 + else: + q_desired[0] += amp0 + + amp = 0.7 + + q_desired[1] += amp + q_desired[2] += amp + + ampA1 = 0.6 + ampB1 = 1.5 + ampA2 = 1.5 + ampB2 = 1.5 + + q_desired[3] -= ampA1 + q_desired[4] -= ampB1 + q_desired[5] -= ampA2 + q_desired[6] -= ampB2 + + return q_desired if self.side == "L" else -q_desired + + def _get_pinky_close_q_desired(self): + q_desired = np.zeros(7) + + return q_desired if self.side == "L" else -q_desired diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/hand/instantiation/g1_hand_ik_instantiation.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/hand/instantiation/g1_hand_ik_instantiation.py new file mode 100644 index 0000000000000000000000000000000000000000..c06561f5598aea12c062274d84e7ef9625c95ab2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/hand/instantiation/g1_hand_ik_instantiation.py @@ -0,0 +1,10 @@ +from decoupled_wbc.control.teleop.solver.hand.g1_gripper_ik_solver import ( + G1GripperInverseKinematicsSolver, +) + + +# initialize hand ik solvers for g1 robot +def instantiate_g1_hand_ik_solver(): + left_hand_ik_solver = G1GripperInverseKinematicsSolver(side="left") + right_hand_ik_solver = G1GripperInverseKinematicsSolver(side="right") + return left_hand_ik_solver, right_hand_ik_solver diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/solver.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/solver.py new file mode 100644 index 0000000000000000000000000000000000000000..58fa508726fad2ce7c26d8726a5654f70f8d9311 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/solver/solver.py @@ -0,0 +1,17 @@ +from abc import ABC, abstractmethod +from typing import Any + + +class Solver(ABC): + def __init__(self): + pass + + def register_robot(self, robot): + pass + + def calibrate(self, data): + pass + + @abstractmethod + def __call__(self, target) -> Any: + pass diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/base_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/base_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..3da36d86303a63c1ae8dc2c03a73379a006b578e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/base_streamer.py @@ -0,0 +1,46 @@ +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +import time +from typing import Any, Dict + + +@dataclass +class StreamerOutput: + """Clean separation of different data types""" + + # Data that needs IK processing (ik_keys) + ik_data: Dict[str, Any] = field(default_factory=dict) + + # Commands that pass directly to robot control loop (control_keys) + control_data: Dict[str, Any] = field(default_factory=dict) + + # Commands used internally by teleop policy (teleop_keys) + teleop_data: Dict[str, Any] = field(default_factory=dict) + + # Commands used for data collection (data_collection_keys) + data_collection_data: Dict[str, Any] = field(default_factory=dict) + + # Metadata + timestamp: float = field(default_factory=time.time) + source: str = "" + + +class BaseStreamer(ABC): + def __init__(self, *args, **kwargs): + pass + + def reset_status(self): + pass + + @abstractmethod + def start_streaming(self): + pass + + @abstractmethod + def get(self) -> StreamerOutput: + """Return StreamerOutput with structured data""" + pass + + @abstractmethod + def stop_streaming(self): + pass diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/dummy_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/dummy_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..a7e372d23b2a61edb3d320889c5ac80ac1b54aab --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/dummy_streamer.py @@ -0,0 +1,81 @@ +import numpy as np + +from decoupled_wbc.control.teleop.streamers.base_streamer import BaseStreamer, StreamerOutput +from decoupled_wbc.control.utils.keyboard_dispatcher import KeyboardListenerSubscriber + + +class DummyStreamer(BaseStreamer): + """A dummy streamer that returns hardcoded structured data for testing.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.is_streaming = False + self.keyboard_listener = KeyboardListenerSubscriber() + self.left_fingertips = np.zeros((25, 4, 4)) + self.right_fingertips = np.zeros((25, 4, 4)) + self.left_fingertips[4, 0, 3] = 1.0 # open + self.right_fingertips[4, 0, 3] = 1.0 # open + + def start_streaming(self): + self.is_streaming = True + print("Dummy streamer started with hardcoded IK data") + + def get(self) -> StreamerOutput: + """Return hardcoded dummy data with proper IK format.""" + if not self.is_streaming: + return StreamerOutput() + + # Hardcoded dummy data - identity matrices and zeros + left_wrist_pose = np.eye(4) + right_wrist_pose = np.eye(4) + left_fingers, right_fingers = self._generate_finger_data() + + return StreamerOutput( + ik_data={ + "left_wrist": left_wrist_pose, + "right_wrist": right_wrist_pose, + "left_fingers": {"position": left_fingers}, + "right_fingers": {"position": right_fingers}, + }, + control_data={ + "navigate_cmd": [0.0, 0.0, 0.0], # No movement + "toggle_stand_command": False, + "base_height_command": 0.78, # Default standing height + }, + teleop_data={ + "toggle_activation": False, + "freeze_upper_body": False, + }, + source="dummy", + ) + + def stop_streaming(self): + self.is_streaming = False + print("Dummy streamer stopped") + + def _generate_finger_data(self): + """Generate finger position data similar to iPhone streamer.""" + + # Control thumb based on shoulder button state (index 4 is thumb tip) + key = self.keyboard_listener.read_msg() + index = 5 + middle = 10 + ring = 15 + if key is not None: + if key == "b": + if self.left_fingertips[4 + index, 0, 3] == 1.0: + self.left_fingertips[4 + index, 0, 3] = 0.0 # open + else: + self.left_fingertips[4 + index, 0, 3] = 1.0 # closed + if key == "n": + if self.left_fingertips[4 + middle, 0, 3] == 1.0: + self.left_fingertips[4 + middle, 0, 3] = 0.0 # open + else: + self.left_fingertips[4 + middle, 0, 3] = 1.0 # closed + if key == "m": + if self.left_fingertips[4 + ring, 0, 3] == 1.0: + self.left_fingertips[4 + ring, 0, 3] = 0.0 # open + else: + self.left_fingertips[4 + ring, 0, 3] = 1.0 # closed + + return self.left_fingertips, self.right_fingertips diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/iphone_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/iphone_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..68544503cc2040b341a4d1eaf112037181bb9794 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/iphone_streamer.py @@ -0,0 +1,150 @@ +import concurrent.futures +import time + +import numpy as np +from scipy.spatial.transform import Rotation as R + +from decoupled_wbc.control.teleop.device.iphone.iphone import IPhoneDevice +from decoupled_wbc.control.teleop.streamers.base_streamer import BaseStreamer, StreamerOutput + + +def get_data_with_timeout(obj, timeout=0.02): + with concurrent.futures.ThreadPoolExecutor() as executor: + future = executor.submit(obj.data_collect.request_vive_data) + try: + combined_data = future.result(timeout=timeout) + return combined_data + except concurrent.futures.TimeoutError: + print("Data request timed out.") + return None + + +def get_transformation(vive_raw_data): + """ + Turn the raw data from the Vive tracker into a transformation matrix. + """ + position = np.array( + [ + vive_raw_data["position"]["x"], + vive_raw_data["position"]["y"], + vive_raw_data["position"]["z"], + ] + ) + quat = np.array( + [ + vive_raw_data["orientation"]["x"], + vive_raw_data["orientation"]["y"], + vive_raw_data["orientation"]["z"], + vive_raw_data["orientation"]["w"], + ] + ) + T = np.identity(4) + T[:3, :3] = R.from_quat(quat).as_matrix() + T[:3, 3] = position + return T + + +class IphoneStreamer(BaseStreamer): + def __init__(self): + self.left_device = IPhoneDevice(port=5557) + self.right_device = IPhoneDevice(port=5558) + self.left_prev_button_states = {"Reset": False, "Close": False} + self.right_prev_button_states = {"Reset": False, "Close": False} + + def start_streaming(self): + self.left_device.start() + self.right_device.start() + + def __del__(self): + self.stop_streaming() + + def get(self): + """Request combined data and return transformations as StreamerOutput.""" + # Initialize data groups + ik_data = {} # For pose and joint data (ik_keys) + control_data = {} # For robot control commands (control_keys) + teleop_data = {} # For internal policy commands (teleop_keys) + + try: + # Request combined data from the server and wait until we get data + left_combined_data = None + right_combined_data = None + while not left_combined_data: + left_combined_data = self.left_device.get_cmd() + if not left_combined_data: + print("Waiting for left iPhone data...") + while not right_combined_data: + right_combined_data = self.right_device.get_cmd() + if not right_combined_data: + print("Waiting for right iPhone data...") + + # IK data - wrist poses and finger positions (ik_keys) + ik_data["left_wrist"] = np.array(left_combined_data.get("transformMatrix")) + ik_data["right_wrist"] = np.array(right_combined_data.get("transformMatrix")) + + # left button states + current_left_reset = left_combined_data.get("buttonStates").get("Reset") + current_left_close = left_combined_data.get("buttonStates").get("Close") + + # Trigger logic: only True when button transitions from False to True + left_reset = current_left_reset and not self.left_prev_button_states["Reset"] + + # Store current button states for next iteration + self.left_prev_button_states["Reset"] = current_left_reset + self.left_prev_button_states["Close"] = current_left_close + + # left fingers - IK data (ik_keys) + fingertips = np.zeros([25, 4, 4]) + positions = fingertips[:, :3, 3] + if current_left_close: + positions[4, 0] = 0 # closed + else: + positions[4, 0] = 1 # open + ik_data["left_fingers"] = {"position": fingertips} + + # right button states + current_right_reset = right_combined_data.get("buttonStates").get("Reset") + current_right_close = right_combined_data.get("buttonStates").get("Close") + + # Trigger logic: only True when button transitions from False to True + right_reset = current_right_reset and not self.right_prev_button_states["Reset"] + + # Store current button states for next iteration + self.right_prev_button_states["Reset"] = current_right_reset + self.right_prev_button_states["Close"] = current_right_close + + # right fingers - IK data (ik_keys) + fingertips = np.zeros([25, 4, 4]) + positions = fingertips[:, :3, 3] + if current_right_close: + positions[4, 0] = 0 # closed + else: + positions[4, 0] = 1 # open + ik_data["right_fingers"] = {"position": fingertips} + + # Teleop commands (teleop_keys) - used by TeleopPolicy for activation + teleop_data["toggle_activation"] = left_reset + + # Control commands (control_keys) - sent to robot + control_data["toggle_stand_command"] = right_reset + + except Exception as e: + print(f"Error while requesting iPhone data: {e}") + + # Return structured output + return StreamerOutput( + ik_data=ik_data, control_data=control_data, teleop_data=teleop_data, source="iphone" + ) + + def stop_streaming(self): + self.left_device.stop() + self.right_device.stop() + + +if __name__ == "__main__": + streamer = IphoneStreamer() + streamer.start_streaming() + while True: + data = streamer.get() + print(data) + time.sleep(0.1) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/joycon_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/joycon_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2ae31c9a4c36159bda89b06a0bf40ca4db23d4 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/joycon_streamer.py @@ -0,0 +1,695 @@ +import time +from typing import Any, Dict + +from evdev import InputDevice, ecodes, list_devices +import numpy as np + +from decoupled_wbc.control.teleop.streamers.base_streamer import BaseStreamer, StreamerOutput + + +class JoyConDevice: + """ + A class to handle a single Joy-Con controller using evdev. + Supports both individual Joy-Cons and their IMU sensors. + """ + + def __init__( + self, device_path: str = None, controller_type: str = "auto", silent: bool = False + ): + """ + Initialize the Joy-Con device. + + Args: + device_path: Path to the Joy-Con event device (e.g., /dev/input/event25) + controller_type: "left", "right", or "auto" + silent: Whether to suppress output messages + """ + self._silent = silent + self._device_path = device_path + self._controller_type = controller_type + self._device = None + self._prev_button_states = {} + + # Joy-Con button mappings (evdev key codes) + self._setup_mappings() + + # Current analog stick values + self._stick_x = 0.0 + self._stick_y = 0.0 + + # Axis codes (will be set in start() based on controller type) + self._x_axis_code = 0 # Default for left Joy-Con + self._y_axis_code = 1 # Default for left Joy-Con + + def _setup_mappings(self): + """Set up button and axis mappings for Joy-Con event codes.""" + # Left Joy-Con button mappings + self._left_button_mappings = { + # Left Joy-Con specific buttons + 544: "dpad_up", + 545: "dpad_down", + 546: "dpad_left", + 547: "dpad_right", + 309: "capture", + 314: "minus", + # Left Joy-Con shoulder/trigger buttons + 310: "L", # L button + 312: "ZL", # ZL trigger + 311: "SL", # SL side button + 313: "SR", # SR side button + } + + # Right Joy-Con button mappings + self._right_button_mappings = { + # Right Joy-Con specific buttons + 304: "a", + 305: "b", + 307: "x", + 308: "y", + 315: "plus", + 316: "home", + # Right Joy-Con shoulder/trigger buttons + 311: "R", # SL side button + 313: "ZR", # SR side button + 310: "SL", # R button + 312: "SR", # ZR trigger + } + + # Will be set in start() based on controller type + self._button_mappings = {} + self._prev_button_states = {} + + # Axis codes (set dynamically in start()) + self._x_axis_code = 0 + self._y_axis_code = 1 + + def _find_joycon_device(self): + """Find and return a Joy-Con device, waiting until one is found.""" + while True: + devices = [InputDevice(path) for path in list_devices()] + joycon_devices = [] + for device in devices: + if "Joy-Con" in device.name and "IMU" not in device.name: + joycon_devices.append(device) + + if not joycon_devices: + if not self._silent: + print("Warning: No Joy-Con devices found. Waiting for Joy-Con connection...") + time.sleep(1.0) # Wait 1 second before checking again + continue + + # Joy-Con devices found, proceed with selection + # If specific type requested, find matching device + if self._controller_type == "left": + for device in joycon_devices: + if "Joy-Con (L)" in device.name: + if not self._silent: + print(f"Found requested left Joy-Con: {device.name}") + return device + # If left Joy-Con not found but other Joy-Cons exist + if not self._silent: + print("Warning: Left Joy-Con requested but not found. Waiting...") + time.sleep(1.0) + continue + + elif self._controller_type == "right": + for device in joycon_devices: + if "Joy-Con (R)" in device.name: + if not self._silent: + print(f"Found requested right Joy-Con: {device.name}") + return device + # If right Joy-Con not found but other Joy-Cons exist + if not self._silent: + print("Warning: Right Joy-Con requested but not found. Waiting...") + time.sleep(1.0) + continue + + # Auto mode or fallback - return first available + if not self._silent: + print(f"Found Joy-Con in auto mode: {joycon_devices[0].name}") + return joycon_devices[0] + + def start(self): + """Start the Joy-Con device.""" + try: + if self._device_path: + # Use specific device path + self._device = InputDevice(self._device_path) + else: + # Auto-find Joy-Con device + self._device = self._find_joycon_device() + + # Determine actual controller type and axis codes from device name + if "Joy-Con (L)" in self._device.name: + self._controller_type = "left" + self._x_axis_code = 0 + self._y_axis_code = 1 + # Set up left Joy-Con specific button mappings + self._button_mappings = self._left_button_mappings.copy() + elif "Joy-Con (R)" in self._device.name: + self._controller_type = "right" + self._x_axis_code = 3 # Right Joy-Con uses ABS_RX (3) + self._y_axis_code = 4 # Right Joy-Con uses ABS_RY (4) + # Set up right Joy-Con specific button mappings + self._button_mappings = self._right_button_mappings.copy() + else: + # Unknown device, keep defaults + if not self._silent: + print(f"Warning: Unknown Joy-Con type: {self._device.name}") + self._button_mappings = self._left_button_mappings.copy() + + # Initialize button states + self._prev_button_states = {name: False for name in self._button_mappings.values()} + + if not self._silent: + print(f"Joy-Con connected: {self._device.name}") + print(f"Device path: {self._device.path}") + print(f"Controller type: {self._controller_type}") + print(f"Axis codes: X={self._x_axis_code}, Y={self._y_axis_code}") + print(f"Button mappings: {list(self._button_mappings.values())}") + print(f"Capabilities: {list(self._device.capabilities(verbose=True).keys())}") + + except Exception as e: + if not self._silent: + print(f"Failed to initialize Joy-Con: {e}") + raise e + + def stop(self): + """Stop the Joy-Con device.""" + if self._device: + try: + self._device.close() + except (OSError, AttributeError): + pass # Ignore errors during cleanup + if not self._silent: + print("Joy-Con disconnected.") + + def get_state(self) -> Dict[str, Any]: + """Get the current state of the Joy-Con by reading all available events.""" + if not self._device: + return {} + + try: + # Read all available events (non-blocking) + import select + + r, w, x = select.select([self._device], [], [], 0) # Non-blocking + + if r: + # Read ALL events available right now + events = self._device.read() + for event in events: + self._process_event(event) + + # Return current state + return self._build_state() + + except Exception as e: + if not self._silent: + print(f"Error reading Joy-Con state: {e}") + return {} + + def _process_event(self, event): + """Process a single input event from the Joy-Con.""" + if event.type == ecodes.EV_KEY: + # Button event + button_pressed = event.value == 1 + button_name = self._button_mappings.get(event.code) + if button_name: + self._prev_button_states[button_name] = button_pressed + + elif event.type == ecodes.EV_ABS: + # Analog stick event - use dynamic axis codes + if event.code == self._x_axis_code: + self._stick_x = event.value / 32767.0 + elif event.code == self._y_axis_code: + self._stick_y = -event.value / 32767.0 + + def _build_state(self): + """Build the current state dictionary.""" + if not self._device: + return {} + + # Get current button states and detect press events + buttons = {} + button_events = {} + + for button_name in self._button_mappings.values(): + current_state = self._prev_button_states.get(button_name, False) + buttons[button_name] = current_state + + # Detect button press events (transition from False to True) + prev_state = getattr(self, f"_prev_press_{button_name}", False) + button_events[f"{button_name}_pressed"] = current_state and not prev_state + setattr(self, f"_prev_press_{button_name}", current_state) + + # Package state + return { + "buttons": buttons, + "button_events": button_events, + "axes": {"stick_x": self._stick_x, "stick_y": self._stick_y}, + "timestamp": time.time(), + } + + +class JoyconStreamer(BaseStreamer): + """ + A streamer for Nintendo Joy-Con controllers following iPhone streamer pattern. + Supports two modes: locomotion and manipulation. + """ + + def __init__( + self, left_device_path: str = None, right_device_path: str = None, silent: bool = False + ): + """Initialize the Joy-Con streamer.""" + super().__init__() + + self._silent = silent + self.latest_data = {} + + # Mode management + self.reset_status() + + # Initialize devices + self.left_device = JoyConDevice(left_device_path, "left", silent) + self.right_device = JoyConDevice(right_device_path, "right", silent) + + def reset_status(self): + """Reset the cache of the streamer.""" + self.current_base_height = 0.74 # Initial base height, 0.74m (standing height) + self.stand_toggle_cooldown = 0.5 # prevent rapid stand toggling + self.last_stand_toggle_time = 0 + + def start_streaming(self): + """Start streaming from Joy-Con devices.""" + try: + if not self._silent: + print("Starting Joy-Con devices...") + + # Start devices and wait until both are connected + self.left_device.start() + self.right_device.start() + + # Wait until both devices are ready + max_wait_time = 10 # seconds + start_time = time.time() + while (time.time() - start_time) < max_wait_time: + left_state = self.left_device.get_state() + right_state = self.right_device.get_state() + + if left_state and right_state: + if not self._silent: + print("Both Joy-Con devices connected successfully!") + break + + if not self._silent: + print("Waiting for both Joy-Con devices to connect...") + time.sleep(0.5) + else: + print("Warning: Timeout waiting for both Joy-Con devices") + + if not self._silent: + print("Joy-Con streamer started in unified mode") + print("Controls:") + print(" ZL+ZR: Toggle stand command") + print(" D-pad Up/Down: Increase/Decrease base height") + print(" Capture (Left): Toggle locomotion policy (e-stop for lower body)") + print(" L/R shoulders: Left/Right finger open/close") + print(" Home button: Toggle activation") + print(" Left stick: Forward/backward and strafe movement") + print(" Right stick: Yaw rotation") + print(" A button: Toggle data collection") + print(" B button: Abort current episode") + + except Exception as e: + if not self._silent: + print(f"Failed to start Joy-Con streaming: {e}") + raise e + + def stop_streaming(self): + """Stop streaming from Joy-Con devices.""" + if self.left_device: + self.left_device.stop() + if self.right_device: + self.right_device.stop() + + if not self._silent: + print("Joy-Con streaming stopped") + + def _get_joycon_state(self): + """ + Get combined Joy-Con state with error handling. + DDA: Warning and wait until we got all left and right device data. + """ + left_state = self.left_device.get_state() if self.left_device else {} + right_state = self.right_device.get_state() if self.right_device else {} + + # Check if we have valid data from both devices + if not left_state or not right_state: + if not self._silent: + missing = [] + if not left_state: + missing.append("left") + if not right_state: + missing.append("right") + print(f"Warning: Missing Joy-Con data from {', '.join(missing)} device(s)") + + # Return empty data structure if either device is missing + return { + "left_button_states": {}, + "right_button_states": {}, + "left_stick_inputs": {}, + "right_stick_inputs": {}, + } + + # Combine states + combined_data = { + "left_button_states": left_state.get("buttons", {}), + "right_button_states": right_state.get("buttons", {}), + "left_stick_inputs": left_state.get("axes", {}), + "right_stick_inputs": right_state.get("axes", {}), + "left_button_events": left_state.get("button_events", {}), + "right_button_events": right_state.get("button_events", {}), + } + return combined_data + + def _handle_stand_toggle(self, joycon_data): + """Handle stand toggle command via ZL+ZR buttons.""" + current_time = time.time() + if (current_time - self.last_stand_toggle_time) > self.stand_toggle_cooldown: + # Use button states to check if both triggers are currently pressed + left_buttons = joycon_data.get("left_button_states", {}) + right_buttons = joycon_data.get("right_button_states", {}) + + # Use button events to detect if at least one trigger was just pressed + left_button_events = joycon_data.get("left_button_events", {}) + right_button_events = joycon_data.get("right_button_events", {}) + + # Check if both triggers are held AND at least one was just pressed + both_triggers_held = left_buttons.get("ZL", False) and right_buttons.get("ZR", False) + at_least_one_just_pressed = left_button_events.get( + "ZL_pressed", False + ) or right_button_events.get("ZR_pressed", False) + + if both_triggers_held and at_least_one_just_pressed: + self.last_stand_toggle_time = current_time + if not self._silent: + print("Stand toggle activated") + return True + return False + + def _apply_dead_zone(self, value, dead_zone): + """Apply dead zone and normalize.""" + if abs(value) < dead_zone: + return 0.0 + sign = 1 if value > 0 else -1 + # Normalize the output to be between -1 and 1 after dead zone + return sign * (abs(value) - dead_zone) / (1.0 - dead_zone) + + def _handle_height_adjustment(self, joycon_data): + """Handle base height adjustment via d-pad up/down.""" + left_button_states = joycon_data.get("left_button_states", {}) + + # Check d-pad button states + dpad_up = left_button_states.get("dpad_up", False) + dpad_down = left_button_states.get("dpad_down", False) + + # Incremental height adjustment + height_increment = 0.005 # Small step per call when button is pressed + + if dpad_up: + self.current_base_height += height_increment + elif dpad_down: + self.current_base_height -= height_increment + + # Clamp to bounds + self.current_base_height = np.clip(self.current_base_height, 0.2, 0.74) + + def _detect_stand_toggle(self, joycon_data): + """Detect stand/walk toggle command - triggered by ZL+ZR.""" + return self._handle_stand_toggle(joycon_data) + + def _detect_locomotion_policy_toggle(self, joycon_data): + """Detect locomotion policy toggle command using left Joy-Con capture button.""" + left_button_events = joycon_data.get("left_button_events", {}) + return left_button_events.get("capture_pressed", False) + + def _detect_emergency_stop(self, joycon_data): + """Detect emergency stop command (Placeholder - not implemented yet).""" + return False # Not implemented yet + + def _detect_data_collection_toggle(self, joycon_data): + """Detect data collection toggle command using right Joy-Con A button.""" + right_button_events = joycon_data.get("right_button_events", {}) + return right_button_events.get("a_pressed", False) + + def _detect_abort_toggle(self, joycon_data): + """Detect abort toggle command using right Joy-Con B button.""" + right_button_events = joycon_data.get("right_button_events", {}) + return right_button_events.get("b_pressed", False) + + def _generate_finger_data(self, shoulder_button_pressed): + """Generate finger position data similar to iPhone streamer.""" + fingertips = np.zeros([25, 4, 4]) + + # Set identity matrices for all finger joints + for i in range(25): + fingertips[i] = np.eye(4) + + # Control thumb based on shoulder button state (index 4 is thumb tip) + if shoulder_button_pressed: + fingertips[4, 0, 3] = 0.0 # closed + else: + fingertips[4, 0, 3] = 1.0 # open + + return fingertips + + def _generate_unified_raw_data(self, joycon_data): + """Generate unified raw_data combining navigation, finger control, and height adjustment.""" + + # Extract stick inputs + left_stick = joycon_data.get("left_stick_inputs", {}) + right_stick = joycon_data.get("right_stick_inputs", {}) + + # Extract button/trigger states for finger control + left_buttons = joycon_data.get("left_button_states", {}) + right_buttons = joycon_data.get("right_button_states", {}) + + # Handle d-pad height adjustment + self._handle_height_adjustment(joycon_data) + + # Map to velocity commands with dead zones and scaling + DEAD_ZONE = 0.1 + MAX_LINEAR_VEL = 0.2 # m/s + MAX_ANGULAR_VEL = 0.5 # rad/s + + # Left stick Y for forward/backward (lin_vel_x), X for strafe (lin_vel_y). + # Right stick X for yaw (ang_vel_z). Verify command signs. + fwd_bwd_input = left_stick.get("stick_y", 0.0) + strafe_input = -left_stick.get("stick_x", 0.0) # Flip sign for intuitive left/right + yaw_input = -right_stick.get("stick_x", 0.0) + + lin_vel_x = self._apply_dead_zone(fwd_bwd_input, DEAD_ZONE) * MAX_LINEAR_VEL + lin_vel_y = self._apply_dead_zone(strafe_input, DEAD_ZONE) * MAX_LINEAR_VEL # Strafe + ang_vel_z = self._apply_dead_zone(yaw_input, DEAD_ZONE) * MAX_ANGULAR_VEL + + # Extract home button press event for toggle activation + right_button_events = joycon_data.get("right_button_events", {}) + home_button_pressed = right_button_events.get("home_pressed", False) + + # Map L/R (shoulder buttons) to finger control + left_shoulder_pressed = left_buttons.get("L", False) + right_shoulder_pressed = right_buttons.get("R", False) + + # Generate finger data based on shoulder button states + left_fingers = self._generate_finger_data(left_shoulder_pressed) + right_fingers = self._generate_finger_data(right_shoulder_pressed) + + return StreamerOutput( + ik_data={ + "left_fingers": {"position": left_fingers}, + "right_fingers": {"position": right_fingers}, + }, + control_data={ + "base_height_command": self.current_base_height, + "navigate_cmd": [lin_vel_x, lin_vel_y, ang_vel_z], + "toggle_stand_command": self._detect_stand_toggle(joycon_data), + "toggle_policy_action": self._detect_locomotion_policy_toggle(joycon_data), + }, + teleop_data={ + "toggle_activation": home_button_pressed, + }, + data_collection_data={ + "toggle_data_collection": self._detect_data_collection_toggle(joycon_data), + "toggle_data_abort": self._detect_abort_toggle(joycon_data), + }, + source="joycon", + ) + + def get(self) -> StreamerOutput: + """ + Return StreamerOutput with unified control data. + """ + # Get current Joy-Con state + joycon_data = self._get_joycon_state() + + # Generate unified structured output + raw_data = self._generate_unified_raw_data(joycon_data) + return raw_data + + def __del__(self): + """Cleanup when the streamer is destroyed.""" + self.stop_streaming() + + +def debug_joycons(controller_type="both", duration=30): + """Debug function to show Joy-Con devices and capture real-time events.""" + print(f"\n=== JOY-CON DEBUG ({controller_type.upper()}) ===") + + # Show available devices + devices = [InputDevice(path) for path in list_devices()] + joycon_devices = [d for d in devices if "Joy-Con" in d.name and "IMU" not in d.name] + print(f"Found {len(joycon_devices)} Joy-Con devices:") + for device in joycon_devices: + print(f" {device.name} at {device.path}") + + if not joycon_devices: + print("No Joy-Con devices found!") + return + + # Select devices to monitor + devices_to_monitor = [] + if controller_type in ["left", "both"]: + devices_to_monitor.extend([d for d in joycon_devices if "Joy-Con (L)" in d.name]) + if controller_type in ["right", "both"]: + devices_to_monitor.extend([d for d in joycon_devices if "Joy-Con (R)" in d.name]) + + if not devices_to_monitor: + print(f"No {controller_type} Joy-Con found!") + return + + print(f"\nMonitoring events for {duration}s (Press Ctrl+C to stop)...") + + import select + + start_time = time.time() + try: + while (time.time() - start_time) < duration: + r, w, x = select.select(devices_to_monitor, [], [], 0.1) + for device in r: + events = device.read() + for event in events: + if event.type in [ecodes.EV_KEY, ecodes.EV_ABS]: + event_type = "KEY" if event.type == ecodes.EV_KEY else "ABS" + device_name = "L" if "Joy-Con (L)" in device.name else "R" + print(f"[{device_name}] {event_type}:{event.code}:{event.value}") + except KeyboardInterrupt: + print("\nStopped.") + finally: + for device in devices_to_monitor: + device.close() + + print("=== END DEBUG ===\n") + + +def test_unified_controls(): + """Test unified control system with all functionality available.""" + print("=== Testing Unified Controls ===") + print("Controls:") + print(" ZL+ZR: Toggle stand command") + print(" D-pad Up/Down: Increase/Decrease base height") + print(" Capture (Left): Toggle locomotion policy (e-stop for lower body)") + print(" Left stick: Forward/backward and strafe movement") + print(" Right stick: Yaw rotation") + print(" L/R shoulders: Left/Right finger open/close") + print(" Home button: Toggle activation") + print(" A button: Toggle data collection") + print(" B button: Abort current episode") + print("Press Ctrl+C to stop\n") + + streamer = JoyconStreamer(silent=False) + + try: + streamer.start_streaming() + + while True: + data = streamer.get() + + # Extract all control data + nav_cmd = data.control_data.get("navigate_cmd", [0, 0, 0]) + height_cmd = data.control_data.get("base_height_command", 0.78) + stand_toggle = data.control_data.get("toggle_stand_command", False) + policy_action = data.control_data.get("toggle_policy_action", False) + toggle_activation = data.teleop_data.get("toggle_activation", False) + toggle_data_collection = data.data_collection_data.get("toggle_data_collection", False) + toggle_data_abort = data.data_collection_data.get("toggle_data_abort", False) + + # Get finger states + left_fingers = data.ik_data.get("left_fingers", {}).get( + "position", np.zeros([25, 4, 4]) + ) + right_fingers = data.ik_data.get("right_fingers", {}).get( + "position", np.zeros([25, 4, 4]) + ) + left_closed = ( + left_fingers[4, 0, 3] == 0.0 if left_fingers.shape == (25, 4, 4) else False + ) + right_closed = ( + right_fingers[4, 0, 3] == 0.0 if right_fingers.shape == (25, 4, 4) else False + ) + + print( + f"UNIFIED - Nav:[{nav_cmd[0]:.2f},{nav_cmd[1]:.2f},{nav_cmd[2]:.2f}] " + f"Height:{height_cmd:.2f} L:{left_closed} R:{right_closed} " + f"StandToggle:{stand_toggle} PolicyAction:{policy_action} " + f"ToggleActivation:{toggle_activation} " + f"ToggleDataCollection:{toggle_data_collection} ToggleDataAbort:{toggle_data_abort}" + ) + + time.sleep(0.1) + + except KeyboardInterrupt: + print("\nStopping unified controls test...") + finally: + streamer.stop_streaming() + + +if __name__ == "__main__": + import sys + + # Check for debug mode + if len(sys.argv) > 1 and sys.argv[1] == "debug_both": + debug_joycons(controller_type="both", duration=60) + sys.exit(0) + + # Check for test mode + if len(sys.argv) > 1 and sys.argv[1] == "test_unified": + test_unified_controls() + sys.exit(0) + + # Default: show usage and run unified controls test + print("Joy-Con Teleop Streamer - Unified Mode") + print("Usage:") + print(" python joycon_streamer.py debug_both - Debug both Joy-Con devices") + print(" python joycon_streamer.py test_unified - Test unified controls") + print() + print("Unified Button Mapping:") + print("| Input | Function |") + print("|-------|----------|") + print("| Left Stick Y | Forward/Backward movement |") + print("| Left Stick X | Strafe Left/Right |") + print("| Right Stick X | Yaw rotation |") + print("| D-pad Up | Increase base height |") + print("| D-pad Down | Decrease base height |") + print("| L (Left Shoulder) | Left finger open/close |") + print("| R (Right Shoulder) | Right finger open/close |") + print("| Home (Right Joy-Con) | Toggle activation |") + print("| Capture (Left Joy-Con) | Toggle locomotion policy (e-stop) |") + print("| ZL+ZR (Triggers) | Toggle stand command |") + print("| A (Right Joy-Con) | Start/Stop Data Collection |") + print("| B (Right Joy-Con) | Abort Current Episode |") + print() + print("Running unified controls test by default...") + print() + + test_unified_controls() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/leapmotion_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/leapmotion_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..5025759728f4d37737ac4ad5095ab8fc48ced467 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/leapmotion_streamer.py @@ -0,0 +1,289 @@ +from copy import deepcopy +import pickle +import queue +import threading +import time +from typing import Dict, List, Tuple + +import leap +import leap.events +import numpy as np +from scipy.spatial.transform import Rotation as R + +from decoupled_wbc.control.teleop.streamers.base_streamer import BaseStreamer, StreamerOutput + + +def xyz2np_array(position: leap.datatypes.Vector) -> np.ndarray: + return np.array([position.x, position.y, position.z]) + + +def quat2np_array(quaternion: leap.datatypes.Quaternion) -> np.ndarray: + return np.array([quaternion.x, quaternion.y, quaternion.z, quaternion.w]) + + +def get_raw_finger_points(hand: leap.datatypes.Hand) -> np.ndarray: + target_points = np.array([np.eye(4) for _ in range(25)]) + target_points[0, :3, :3] = R.from_quat(quat2np_array(hand.palm.orientation)).as_matrix() + target_points[0, :3, 3] = xyz2np_array(hand.arm.next_joint) + target_points[1, :3, 3] = xyz2np_array(hand.thumb.bones[0].next_joint) + target_points[2, :3, 3] = xyz2np_array(hand.thumb.bones[1].next_joint) + target_points[3, :3, 3] = xyz2np_array(hand.thumb.bones[2].next_joint) + target_points[4, :3, 3] = xyz2np_array(hand.thumb.bones[3].next_joint) + target_points[5, :3, 3] = xyz2np_array(hand.index.bones[0].prev_joint) + target_points[6, :3, 3] = xyz2np_array(hand.index.bones[0].next_joint) + target_points[7, :3, 3] = xyz2np_array(hand.index.bones[1].next_joint) + target_points[8, :3, 3] = xyz2np_array(hand.index.bones[2].next_joint) + target_points[9, :3, 3] = xyz2np_array(hand.index.bones[3].next_joint) + target_points[10, :3, 3] = xyz2np_array(hand.middle.bones[0].prev_joint) + target_points[11, :3, 3] = xyz2np_array(hand.middle.bones[0].next_joint) + target_points[12, :3, 3] = xyz2np_array(hand.middle.bones[1].next_joint) + target_points[13, :3, 3] = xyz2np_array(hand.middle.bones[2].next_joint) + target_points[14, :3, 3] = xyz2np_array(hand.middle.bones[3].next_joint) + target_points[15, :3, 3] = xyz2np_array(hand.ring.bones[0].prev_joint) + target_points[16, :3, 3] = xyz2np_array(hand.ring.bones[0].next_joint) + target_points[17, :3, 3] = xyz2np_array(hand.ring.bones[1].next_joint) + target_points[18, :3, 3] = xyz2np_array(hand.ring.bones[2].next_joint) + target_points[19, :3, 3] = xyz2np_array(hand.ring.bones[3].next_joint) + target_points[20, :3, 3] = xyz2np_array(hand.pinky.bones[0].prev_joint) + target_points[21, :3, 3] = xyz2np_array(hand.pinky.bones[0].next_joint) + target_points[22, :3, 3] = xyz2np_array(hand.pinky.bones[1].next_joint) + target_points[23, :3, 3] = xyz2np_array(hand.pinky.bones[2].next_joint) + target_points[24, :3, 3] = xyz2np_array(hand.pinky.bones[3].next_joint) + + return target_points + + +def get_fake_finger_points_from_pinch(hand: leap.datatypes.Hand) -> np.ndarray: + # print(hand.pinch_strength) + target_points = np.array([np.eye(4) for _ in range(25)]) + for i in range(25): + target_points[i] = np.eye(4) + + # Control thumb based on shoulder button state (index 4 is thumb tip) + if hand.pinch_strength > 0.3: + target_points[4, 0, 3] = 0.0 # closed + else: + target_points[4, 0, 3] = 1000.0 # open, in mm + + return target_points + + +def get_raw_wrist_pose(hand: leap.datatypes.Hand) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + hand_palm_position = xyz2np_array(hand.palm.position) + hand_palm_normal = np.array([-hand.palm.normal.z, -hand.palm.normal.x, hand.palm.normal.y]) + hand_palm_direction = np.array( + [-hand.palm.direction.z, -hand.palm.direction.x, hand.palm.direction.y] + ) + + return hand_palm_position, hand_palm_normal, hand_palm_direction + + +def get_finger_transform(target_points: np.ndarray, hand_type: str) -> np.ndarray: + pose_palm_root = target_points[0, :3, 3].copy() + rot_palm = target_points[0, :3, :3].copy() + + if hand_type == "right": + rot_leap2base = R.from_euler("z", [180], degrees=True).as_matrix() + rot_reverse = np.array( + [[[0, 0, 1], [0, -1, 0], [1, 0, 0]]] + ) # due to the target_base_rotation in hand IK solver + else: + rot_leap2base = np.eye(3) + rot_reverse = np.array([[[0, 0, -1], [0, -1, 0], [-1, 0, 0]]]) + offset = (target_points[:, :3, 3] - pose_palm_root).copy() / 1000.0 # mm to m + offset = offset @ rot_palm @ rot_leap2base @ rot_reverse + + target_points[:, :3, 3] = offset + + return target_points + + +def get_wrist_transformation( + hand_palm_position: np.ndarray, + hand_palm_normal: np.ndarray, + hand_palm_direction: np.ndarray, + hand_type: str, + pos_sensitivity: float = 1.0 / 800.0, +) -> np.ndarray: + T = np.eye(4) + T[:3, 3] = hand_palm_position[[2, 0, 1]] * pos_sensitivity * np.array([-1, -1, 1]) + direction_np = hand_palm_direction + palm_normal_np = hand_palm_normal + if hand_type == "left": + transform = R.from_euler("y", -90, degrees=True).as_matrix() + lh_thumb_np = -np.cross(direction_np, palm_normal_np) + rotation_matrix = np.array([direction_np, -palm_normal_np, lh_thumb_np]).T + else: + transform = R.from_euler("xy", [-180, 90], degrees=True).as_matrix() + rh_thumb_np = np.cross(direction_np, palm_normal_np) + rotation_matrix = np.array([direction_np, palm_normal_np, rh_thumb_np]).T + T[:3, :3] = np.dot(rotation_matrix, transform) + return T + + +def get_raw_data( + hands: List[leap.datatypes.Hand], data: Dict[str, np.ndarray] = None +) -> Dict[str, np.ndarray]: + if data is None: + data = {} + for hand in hands: + hand_type = "left" if str(hand.type) == "HandType.Left" else "right" + data[hand_type + "_wrist"] = get_raw_wrist_pose(hand) + # @runyud: this is a hack to get the finger points from the pinch strength + data[hand_type + "_fingers"] = get_fake_finger_points_from_pinch(hand) + assert len(data) == 4, f"Leapmotiondata length should be 4, but got {len(data)}" + return data + + +def process_data(raw_data: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]: + data = {} + for hand_type in ["left", "right"]: + data[hand_type + "_wrist"] = get_wrist_transformation( + *raw_data[hand_type + "_wrist"], hand_type + ) + data[hand_type + "_fingers"] = { + "position": get_finger_transform(raw_data[hand_type + "_fingers"], hand_type) + } + return data + + +class LeapMotionListener(leap.Listener): + def __init__(self, verbose=False): + self.data = None + self.data_lock = threading.Lock() + self.verbose = verbose + + def on_connection_event(self, event): + print("Connected") + + def on_device_event(self, event: leap.events.DeviceEvent): + try: + with event.device.open(): + info = event.device.get_info() + except AttributeError: + # Handle the case where LeapCannotOpenDeviceError is not available + try: + info = event.device.get_info() + except Exception as e: + print(f"Error opening device: {e}") + info = None + + print(f"Found Leap Motion device {info.serial}") + + def on_tracking_event(self, event: leap.events.TrackingEvent): + if ( + len(event.hands) == 2 or self.data is not None + ): # only when two hands are detected, we update the data + with self.data_lock: + self.data: Dict[str, np.ndarray] = get_raw_data(event.hands, self.data) + if self.verbose: + for hand in event.hands: + hand_type = "left" if str(hand.type) == "HandType.Left" else "right" + print( + f"Hand id {hand.id} is a {hand_type} hand with position" + f"({hand.palm.position.x}, {hand.palm.position.y}, {hand.palm.position.z})." + ) + + def get_data(self): + with self.data_lock: + return deepcopy(self.data) + + def reset_status(self): + """Reset the cache of the streamer.""" + with self.data_lock: + self.data = None + + +class FakeLeapMotionListener: + def __init__(self, data_path=None): + self.data_lock = threading.Lock() + with open(data_path, "rb") as f: + self.data_list = pickle.load(f) + self.data_index = 0 + + def get_data(self) -> Dict[str, np.ndarray]: + with self.data_lock: + data = deepcopy(self.data_list[self.data_index % len(self.data_list)]) + self.data_index += 1 + return data + + +# Note currently it is a auto-polling based streamer. +# The connection will start another thread to continue polling data +# and the listener will continue to receive data from the connection. +class LeapMotionStreamer(BaseStreamer): + """LeapMotion streamer that provides hand tracking data.""" + + def __init__(self, verbose=False, record_data=False, **kwargs): + self.connection = leap.Connection() + self.listener = LeapMotionListener(verbose=verbose) + self.connection.add_listener(self.listener) + # self.listener = FakeLeapMotionListener(data_path="leapmotion_data_rot.pkl") + + self.connection.set_tracking_mode(leap.TrackingMode.Desktop) + + self.record_data = record_data + self.data_queue = queue.Queue() + + def reset_status(self): + """Reset the cache of the streamer.""" + self.listener.reset_status() + while not self.listener.get_data(): + time.sleep(0.1) + + def start_streaming(self): + self.connection.connect() + print("Waiting for the first data...") + time.sleep(0.5) + while not self.listener.get_data(): + time.sleep(0.1) + print("First data received!") + + def stop_streaming(self): + self.connection.disconnect() + + def get(self) -> StreamerOutput: + """Return hand tracking data as StreamerOutput.""" + # Get raw data and save if recording + raw_data = self.listener.get_data() + if self.record_data: + self.data_queue.put(raw_data) + + # Process raw data into transformations + processed_data = process_data(raw_data) + + # Initialize IK data (ik_keys) - LeapMotion provides hand/finger tracking + ik_data = {} + for hand_type in ["left", "right"]: + # Add wrist poses and finger positions to IK data + ik_data[f"{hand_type}_wrist"] = processed_data[f"{hand_type}_wrist"] + ik_data[f"{hand_type}_fingers"] = processed_data[f"{hand_type}_fingers"] + + # Return structured output - LeapMotion only provides IK data + return StreamerOutput( + ik_data=ik_data, + control_data={}, # No control commands from LeapMotion + teleop_data={}, # No teleop commands from LeapMotion + source="leapmotion", + ) + + def dump_data_to_file(self): + """Save recorded data to file if recording was enabled.""" + if not self.record_data: + return + + data_list = [] + while not self.data_queue.empty(): + data_list.append(self.data_queue.get()) + with open("leapmotion_data_trans.pkl", "wb") as f: + pickle.dump(data_list, f) + + +if __name__ == "__main__": + streamer = LeapMotionStreamer(verbose=True) + streamer.start_streaming() + for _ in range(100): + streamer.get() + time.sleep(0.1) + streamer.stop_streaming() + streamer.dump_data_to_file() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/manus_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/manus_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..17567796c644085eb355c7433174a0d0d22b4414 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/manus_streamer.py @@ -0,0 +1,90 @@ +import pickle +import threading + +import zmq + +from decoupled_wbc.control.teleop.device.manus import Manus +from decoupled_wbc.control.teleop.streamers.base_streamer import BaseStreamer, StreamerOutput + + +class ManusStreamer(BaseStreamer): + def __init__(self, port=5556): + self.port = port + self.context = None + self.socket = None + self.manus_server = None + self.server_thread = None + + def request_data(self): + """Request the latest data from the server.""" + if self.socket is None: + raise RuntimeError("ManusStreamer not started. Call start_streaming() first.") + + # Send request to the server + self.socket.send(b"request_data") # Send a request message + + # Wait for the server's response + message = self.socket.recv() # Receive response + data = pickle.loads(message) # Deserialize the data + + return data + + def _run_server(self): + """Run the manus server in a separate thread.""" + with self.manus_server.activate(): + print("Manus server activated") + self.manus_server.run() + + def start_streaming(self): + """Start the manus server and establish connection.""" + if self.manus_server is not None: + return + + print(f"Starting manus server on port {self.port}...") + + # Create manus server instance + self.manus_server = Manus(port=self.port) + + # Start server in separate thread + self.server_thread = threading.Thread(target=self._run_server, daemon=True) + self.server_thread.start() + + # Establish ZMQ connection + self.context = zmq.Context() + self.socket = self.context.socket(zmq.REQ) + self.socket.connect(f"tcp://localhost:{self.port}") + + def get(self): + """Return hand tracking data as StreamerOutput.""" + raw_data = self.request_data() + + # Initialize IK data (ik_keys) - Manus provides hand/finger tracking + ik_data = {} + if isinstance(raw_data, dict): + # Extract finger and hand pose data + for key, value in raw_data.items(): + if "finger" in key.lower() or "hand" in key.lower(): + ik_data[key] = value + + # Return structured output - Manus only provides IK data + return StreamerOutput( + ik_data=ik_data, + control_data={}, # No control commands from Manus + teleop_data={}, # No teleop commands from Manus + source="manus", + ) + + def stop_streaming(self): + """Stop the manus server and close connections.""" + # Close ZMQ connection + if self.socket: + self.socket.close() + self.socket = None + + if self.context: + self.context.term() + self.context = None + + # Reset server references + self.manus_server = None + self.server_thread = None diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/pico_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/pico_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..315e762a1c30f1c34ed1b3f9f42572b08425000a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/pico_streamer.py @@ -0,0 +1,280 @@ +import subprocess +import time + +import numpy as np +from scipy.spatial.transform import Rotation as R + +from decoupled_wbc.control.teleop.device.pico.xr_client import XrClient +from decoupled_wbc.control.teleop.streamers.base_streamer import BaseStreamer, StreamerOutput + +R_HEADSET_TO_WORLD = np.array( + [ + [0, 0, -1], + [-1, 0, 0], + [0, 1, 0], + ] +) + + +class PicoStreamer(BaseStreamer): + def __init__(self): + self.xr_client = XrClient() + self.run_pico_service() + + self.reset_status() + + def run_pico_service(self): + # Run the pico service + self.pico_service_pid = subprocess.Popen( + ["bash", "/opt/apps/roboticsservice/runService.sh"] + ) + print(f"Pico service running with pid {self.pico_service_pid.pid}") + + def stop_pico_service(self): + # find pid and kill it + if self.pico_service_pid: + subprocess.Popen(["kill", "-9", str(self.pico_service_pid.pid)]) + print(f"Pico service killed with pid {self.pico_service_pid.pid}") + else: + print("Pico service not running") + + def reset_status(self): + self.current_base_height = 0.74 # Initial base height, 0.74m (standing height) + self.toggle_policy_action_last = False + self.toggle_activation_last = False + self.toggle_data_collection_last = False + self.toggle_data_abort_last = False + + def start_streaming(self): + pass + + def stop_streaming(self): + self.xr_client.close() + + def get(self) -> StreamerOutput: + pico_data = self._get_pico_data() + + raw_data = self._generate_unified_raw_data(pico_data) + return raw_data + + def __del__(self): + pass + + def _get_pico_data(self): + pico_data = {} + + # Get the pose of the left and right controllers and the headset + pico_data["left_pose"] = self.xr_client.get_pose_by_name("left_controller") + pico_data["right_pose"] = self.xr_client.get_pose_by_name("right_controller") + pico_data["head_pose"] = self.xr_client.get_pose_by_name("headset") + + # Get key value of the left and right controllers + pico_data["left_trigger"] = self.xr_client.get_key_value_by_name("left_trigger") + pico_data["right_trigger"] = self.xr_client.get_key_value_by_name("right_trigger") + pico_data["left_grip"] = self.xr_client.get_key_value_by_name("left_grip") + pico_data["right_grip"] = self.xr_client.get_key_value_by_name("right_grip") + + # Get button state of the left and right controllers + pico_data["A"] = self.xr_client.get_button_state_by_name("A") + pico_data["B"] = self.xr_client.get_button_state_by_name("B") + pico_data["X"] = self.xr_client.get_button_state_by_name("X") + pico_data["Y"] = self.xr_client.get_button_state_by_name("Y") + pico_data["left_menu_button"] = self.xr_client.get_button_state_by_name("left_menu_button") + pico_data["right_menu_button"] = self.xr_client.get_button_state_by_name( + "right_menu_button" + ) + pico_data["left_axis_click"] = self.xr_client.get_button_state_by_name("left_axis_click") + pico_data["right_axis_click"] = self.xr_client.get_button_state_by_name("right_axis_click") + + # Get the timestamp of the left and right controllers + pico_data["timestamp"] = self.xr_client.get_timestamp_ns() + + # Get the hand tracking state of the left and right controllers + pico_data["left_hand_tracking_state"] = self.xr_client.get_hand_tracking_state("left") + pico_data["right_hand_tracking_state"] = self.xr_client.get_hand_tracking_state("right") + + # Get the joystick state of the left and right controllers + pico_data["left_joystick"] = self.xr_client.get_joystick_state("left") + pico_data["right_joystick"] = self.xr_client.get_joystick_state("right") + + # Get the motion tracker data + pico_data["motion_tracker_data"] = self.xr_client.get_motion_tracker_data() + + # Get the body tracking data + pico_data["body_tracking_data"] = self.xr_client.get_body_tracking_data() + + return pico_data + + def _generate_unified_raw_data(self, pico_data): + # Get controller position and orientation in z up world frame + left_controller_T = self._process_xr_pose(pico_data["left_pose"], pico_data["head_pose"]) + right_controller_T = self._process_xr_pose(pico_data["right_pose"], pico_data["head_pose"]) + + # Get navigation commands + DEAD_ZONE = 0.1 + MAX_LINEAR_VEL = 0.5 # m/s + MAX_ANGULAR_VEL = 1.0 # rad/s + + fwd_bwd_input = pico_data["left_joystick"][1] + strafe_input = -pico_data["left_joystick"][0] + yaw_input = -pico_data["right_joystick"][0] + + lin_vel_x = self._apply_dead_zone(fwd_bwd_input, DEAD_ZONE) * MAX_LINEAR_VEL + lin_vel_y = self._apply_dead_zone(strafe_input, DEAD_ZONE) * MAX_LINEAR_VEL + ang_vel_z = self._apply_dead_zone(yaw_input, DEAD_ZONE) * MAX_ANGULAR_VEL + + # Get base height command + height_increment = 0.01 # Small step per call when button is pressed + if pico_data["Y"]: + self.current_base_height += height_increment + elif pico_data["X"]: + self.current_base_height -= height_increment + self.current_base_height = np.clip(self.current_base_height, 0.2, 0.74) + + # Get gripper commands + left_fingers = self._generate_finger_data(pico_data, "left") + right_fingers = self._generate_finger_data(pico_data, "right") + + # Get activation commands + toggle_policy_action_tmp = pico_data["left_menu_button"] and ( + pico_data["left_trigger"] > 0.5 + ) + toggle_activation_tmp = pico_data["left_menu_button"] and (pico_data["right_trigger"] > 0.5) + + if self.toggle_policy_action_last != toggle_policy_action_tmp: + toggle_policy_action = toggle_policy_action_tmp + else: + toggle_policy_action = False + self.toggle_policy_action_last = toggle_policy_action_tmp + + if self.toggle_activation_last != toggle_activation_tmp: + toggle_activation = toggle_activation_tmp + else: + toggle_activation = False + self.toggle_activation_last = toggle_activation_tmp + + # Get data collection commands + toggle_data_collection_tmp = pico_data["A"] + toggle_data_abort_tmp = pico_data["B"] + + if self.toggle_data_collection_last != toggle_data_collection_tmp: + toggle_data_collection = toggle_data_collection_tmp + else: + toggle_data_collection = False + self.toggle_data_collection_last = toggle_data_collection_tmp + + if self.toggle_data_abort_last != toggle_data_abort_tmp: + toggle_data_abort = toggle_data_abort_tmp + else: + toggle_data_abort = False + self.toggle_data_abort_last = toggle_data_abort_tmp + + # print(f"toggle_data_collection: {toggle_data_collection}, toggle_data_abort: {toggle_data_abort}") + + return StreamerOutput( + ik_data={ + "left_wrist": left_controller_T, + "right_wrist": right_controller_T, + "left_fingers": {"position": left_fingers}, + "right_fingers": {"position": right_fingers}, + }, + control_data={ + "base_height_command": self.current_base_height, + "navigate_cmd": [lin_vel_x, lin_vel_y, ang_vel_z], + "toggle_policy_action": toggle_policy_action, + }, + teleop_data={ + "toggle_activation": toggle_activation, + }, + data_collection_data={ + "toggle_data_collection": toggle_data_collection, + "toggle_data_abort": toggle_data_abort, + }, + source="pico", + ) + + def _process_xr_pose(self, controller_pose, headset_pose): + # Convert controller pose to x, y, z, w quaternion + xr_pose_xyz = np.array(controller_pose)[:3] # x, y, z + xr_pose_quat = np.array(controller_pose)[3:] # x, y, z, w + + # Handle all-zero quaternion case by using identity quaternion + if np.allclose(xr_pose_quat, 0): + xr_pose_quat = np.array([0, 0, 0, 1]) # identity quaternion: x, y, z, w + + # Convert from y up to z up + xr_pose_xyz = R_HEADSET_TO_WORLD @ xr_pose_xyz + xr_pose_rotation = R.from_quat(xr_pose_quat).as_matrix() + xr_pose_rotation = R_HEADSET_TO_WORLD @ xr_pose_rotation @ R_HEADSET_TO_WORLD.T + + # Convert headset pose to x, y, z, w quaternion + headset_pose_xyz = np.array(headset_pose)[:3] + headset_pose_quat = np.array(headset_pose)[3:] + + if np.allclose(headset_pose_quat, 0): + headset_pose_quat = np.array([0, 0, 0, 1]) # identity quaternion: x, y, z, w + + # Convert from y up to z up + headset_pose_xyz = R_HEADSET_TO_WORLD @ headset_pose_xyz + headset_pose_rotation = R.from_quat(headset_pose_quat).as_matrix() + headset_pose_rotation = R_HEADSET_TO_WORLD @ headset_pose_rotation @ R_HEADSET_TO_WORLD.T + + # Calculate the delta between the controller and headset positions + xr_pose_xyz_delta = xr_pose_xyz - headset_pose_xyz + + # Calculate the yaw of the headset + R_headset_to_world = R.from_matrix(headset_pose_rotation) + headset_pose_yaw = R_headset_to_world.as_euler("xyz")[2] # Extract yaw (Z-axis rotation) + inverse_yaw_rotation = R.from_euler("z", -headset_pose_yaw).as_matrix() + + # Align with headset yaw to controller position delta and rotation + xr_pose_xyz_delta_compensated = inverse_yaw_rotation @ xr_pose_xyz_delta + xr_pose_rotation_compensated = inverse_yaw_rotation @ xr_pose_rotation + + xr_pose_T = np.eye(4) + xr_pose_T[:3, :3] = xr_pose_rotation_compensated + xr_pose_T[:3, 3] = xr_pose_xyz_delta_compensated + return xr_pose_T + + def _apply_dead_zone(self, value, dead_zone): + """Apply dead zone and normalize.""" + if abs(value) < dead_zone: + return 0.0 + sign = 1 if value > 0 else -1 + # Normalize the output to be between -1 and 1 after dead zone + return sign * (abs(value) - dead_zone) / (1.0 - dead_zone) + + def _generate_finger_data(self, pico_data, hand): + """Generate finger position data.""" + fingertips = np.zeros([25, 4, 4]) + + thumb = 0 + index = 5 + middle = 10 + ring = 15 + + # Control thumb based on shoulder button state (index 4 is thumb tip) + fingertips[4 + thumb, 0, 3] = 1.0 # open thumb + if not pico_data["left_menu_button"]: + if pico_data[f"{hand}_trigger"] > 0.5 and not pico_data[f"{hand}_grip"] > 0.5: + fingertips[4 + index, 0, 3] = 1.0 # close index + elif pico_data[f"{hand}_trigger"] > 0.5 and pico_data[f"{hand}_grip"] > 0.5: + fingertips[4 + middle, 0, 3] = 1.0 # close middle + elif not pico_data[f"{hand}_trigger"] > 0.5 and pico_data[f"{hand}_grip"] > 0.5: + fingertips[4 + ring, 0, 3] = 1.0 # close ring + + return fingertips + + +if __name__ == "__main__": + # from decoupled_wbc.control.utils.debugger import wait_for_debugger + # wait_for_debugger() + + streamer = PicoStreamer() + streamer.start_streaming() + while True: + raw_data = streamer.get() + print( + f"left_wrist: {raw_data.ik_data['left_wrist']}, right_wrist: {raw_data.ik_data['right_wrist']}" + ) + time.sleep(0.1) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/vive_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/vive_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d0077a5862ee96b4d4276ca3e0123d6612d0ee --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/streamers/vive_streamer.py @@ -0,0 +1,131 @@ +import concurrent.futures +import json + +import numpy as np +from scipy.spatial.transform import Rotation as R +import zmq + +from .base_streamer import BaseStreamer, StreamerOutput + + +def get_data_with_timeout(obj, timeout=0.02): + with concurrent.futures.ThreadPoolExecutor() as executor: + future = executor.submit(obj.data_collect.request_vive_data) + try: + combined_data = future.result(timeout=timeout) + return combined_data + except concurrent.futures.TimeoutError: + print("Data request timed out.") + return None + + +def get_transformation(vive_raw_data): + """ + Turn the raw data from the Vive tracker into a transformation matrix. + """ + position = np.array( + [ + vive_raw_data["position"]["x"], + vive_raw_data["position"]["y"], + vive_raw_data["position"]["z"], + ] + ) + quat = np.array( + [ + vive_raw_data["orientation"]["x"], + vive_raw_data["orientation"]["y"], + vive_raw_data["orientation"]["z"], + vive_raw_data["orientation"]["w"], + ] + ) + T = np.identity(4) + T[:3, :3] = R.from_quat(quat).as_matrix() + T[:3, 3] = position + return T + + +class DataCollectorClient: + def __init__(self, vive_tracker_address): + # Create a ZeroMQ context + self.context = zmq.Context() + + # Create a REQ socket to request data from the server + self.vive_socket = self.context.socket(zmq.REQ) + self.vive_socket.connect(vive_tracker_address) # Connect to the server address + self.latest_data = None + + def request_vive_data(self): + """Request combined data for both left and right wrists.""" + try: + # Send a request to the server asking for both left and right Vive tracker data + self.vive_socket.send_string("get_vive_data") + + # Receive the response from the server + message = self.vive_socket.recv_string() + + # Parse the received JSON string into a Python dictionary + data = json.loads(message) + + # print(f"Received combined tracker data:", data) + return data + + except zmq.ZMQError as e: + print(f"ZMQ Error while requesting Vive data: {e}") + + def stop(self): + """Stop the client and clean up resources.""" + try: + # Close the socket and terminate the context + self.vive_socket.close() # Close the socket + self.context.term() # Terminate the context + print("Client stopped successfully.") + except zmq.ZMQError as e: + print(f"Error while stopping client: {e}") + + +class ViveStreamer(BaseStreamer): + def __init__(self, ip, port=5555, fps=20, keyword=None, **kwargs): + self.ip = f"tcp://{ip}:{port}" + self.fps = fps + self.latest_data = None + self.stop_thread = False + self.update_thread = None + self.keyword = keyword + + def reset_status(self): + """Reset the cache of the streamer.""" + self.latest_data = None + + def start_streaming(self): + self.data_collect = DataCollectorClient(self.ip) + + def __del__(self): + self.stop_streaming() + + def get(self): + """Request combined data and return transformations as StreamerOutput.""" + # Initialize IK data (ik_keys) - Vive only provides pose data + ik_data = {} + + try: + # Request combined data from the server + combined_data = self.data_collect.request_vive_data() + if combined_data: + for dir in ["left", "right"]: + actual_name = f"{dir}_{self.keyword}" + if actual_name in combined_data and combined_data[actual_name] is not None: + ik_data[f"{dir}_wrist"] = get_transformation(combined_data[actual_name]) + + except zmq.ZMQError as e: + print(f"ZMQ Error while requesting Vive data: {e}") + + # Return structured output - Vive only provides IK data + return StreamerOutput( + ik_data=ik_data, + control_data={}, # No control commands from Vive + teleop_data={}, # No teleop commands from Vive + source="vive", + ) + + def stop_streaming(self): + self.data_collect.stop() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/teleop_retargeting_ik.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/teleop_retargeting_ik.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbf7d070487cc704473de262e3fabe2aa63d536 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/teleop_retargeting_ik.py @@ -0,0 +1,148 @@ +import time +from typing import List, Optional + +import numpy as np + +from decoupled_wbc.control.base.policy import Policy +from decoupled_wbc.control.robot_model.robot_model import ReducedRobotModel, RobotModel +from decoupled_wbc.control.teleop.solver.body.body_ik_solver import BodyIKSolver +from decoupled_wbc.control.teleop.solver.body.body_ik_solver_settings import BodyIKSolverSettings +from decoupled_wbc.control.teleop.solver.solver import Solver +from decoupled_wbc.control.visualization.humanoid_visualizer import RobotVisualizer + + +class TeleopRetargetingIK(Policy): + """ + Robot-agnostic teleop retargeting inverse kinematics code. + Focus only on IK processing, ignore commands. + """ + + def __init__( + self, + robot_model: RobotModel, + left_hand_ik_solver: Solver, + right_hand_ik_solver: Solver, + enable_visualization=False, + body_active_joint_groups: Optional[List[str]] = None, + body_ik_solver_settings_type: str = "default", + ): + # initialize the body + if body_active_joint_groups is not None: + self.body = ReducedRobotModel.from_active_groups(robot_model, body_active_joint_groups) + self.full_robot = self.body.full_robot + self.using_reduced_robot_model = True + else: + self.body = robot_model + self.full_robot = self.body + self.using_reduced_robot_model = False + if body_ik_solver_settings_type == "default": + body_ik_solver_settings = BodyIKSolverSettings() + else: + raise ValueError( + f"Unknown body_ik_solver_settings_type: {body_ik_solver_settings_type}" + ) + self.body_ik_solver = BodyIKSolver(body_ik_solver_settings) + + # We register the specific robot model to the robot-agnostic body IK solver class + self.body_ik_solver.register_robot(self.body) + + # Hand IK solvers are hand specific, so we pass them in the constructor + self.left_hand_ik_solver = left_hand_ik_solver + self.right_hand_ik_solver = right_hand_ik_solver + + # enable visualizer + self.enable_visualization = enable_visualization + if self.enable_visualization: + self.visualizer = RobotVisualizer(self.full_robot) + self.visualizer.visualize(self.full_robot.q_zero) + time.sleep(1) # wait for the visualizer to start + + self.in_warmup = True + self._most_recent_ik_data = None + self._most_recent_q = self.full_robot.default_body_pose.copy() + + def compute_joint_positions( + self, body_data: dict, left_hand_data: dict, right_hand_data: dict + ) -> np.ndarray: + """Process only IK-related data, return joint positions""" + if self.in_warmup: + # TODO: Warmup is not necessary if we start IK from the current robot qpos, rather than the zero qpos + for _ in range(50): + target_robot_joints = self._inverse_kinematics( + body_data, left_hand_data, right_hand_data + ) + self.in_warmup = False + else: + target_robot_joints = self._inverse_kinematics( + body_data, left_hand_data, right_hand_data + ) + + return target_robot_joints + + def _inverse_kinematics( + self, + body_target_pose, + left_hand_target_pose, + right_hand_target_pose, + ): + """ + Solve the inverse kinematics problem for the given target poses. + Args: + body_target_pose: Dictionary of link names and their corresponding target pose. + left_hand_target_pose: Dictionary with key "position" mapping to a (25, 4, 4) np.ndarray from AVP data + right_hand_target_pose: Dictionary with key "position" mapping to a (25, 4, 4) np.ndarray from AVP data + q: Initial configuration vector. + Returns: + Configuration vector that achieves the target poses. + """ + if body_target_pose: + if self.using_reduced_robot_model: + body_q = self.body.reduced_to_full_configuration( + self.body_ik_solver(body_target_pose) + ) + else: + body_q = self.body_ik_solver(body_target_pose) + else: + # If no body target pose is provided, set the body to the default pose + body_q = self.full_robot.default_body_pose.copy() + + if left_hand_target_pose is not None: + left_hand_actuated_q = self.left_hand_ik_solver(left_hand_target_pose) + body_q[self.full_robot.get_hand_actuated_joint_indices(side="left")] = ( + left_hand_actuated_q + ) + + if right_hand_target_pose is not None: + right_hand_actuated_q = self.right_hand_ik_solver(right_hand_target_pose) + body_q[self.full_robot.get_hand_actuated_joint_indices(side="right")] = ( + right_hand_actuated_q + ) + + if self.enable_visualization: + self.visualizer.visualize(np.array(body_q)) + + return body_q + + def reset(self): + """Reset the robot model and IK solvers to the initial state, and re-activate the warmup procedure.""" + self.body.reset_forward_kinematics() # self.body is the same one as self.body_ik_solver.robot + self.full_robot.reset_forward_kinematics() + self.body_ik_solver.initialize() + # If in the future, the hand IK solver has initialize method, call it + self._most_recent_ik_data = None + self._most_recent_q = self.full_robot.default_body_pose.copy() + self.in_warmup = True + + def set_goal(self, ik_data: dict): + self._most_recent_ik_data = ik_data + + def get_action(self) -> dict[str, any]: + # Process IK if active + if self._most_recent_ik_data is not None: + body_data = self._most_recent_ik_data["body_data"] + left_hand_data = self._most_recent_ik_data["left_hand_data"] + right_hand_data = self._most_recent_ik_data["right_hand_data"] + target_joints = self.compute_joint_positions(body_data, left_hand_data, right_hand_data) + self._most_recent_q = target_joints + + return self._most_recent_q[self.full_robot.get_joint_group_indices("upper_body")] diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/teleop_streamer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/teleop_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..df761a74f021e26438d6dad70b9fbae031278da6 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/teleop/teleop_streamer.py @@ -0,0 +1,240 @@ +from math import floor +import pickle +from typing import Optional + +from decoupled_wbc.control.robot_model.robot_model import RobotModel +from decoupled_wbc.control.teleop.pre_processor.fingers.fingers import FingersPreProcessor +from decoupled_wbc.control.teleop.pre_processor.wrists.wrists import WristsPreProcessor +from decoupled_wbc.control.teleop.streamers.base_streamer import StreamerOutput + + +class TeleopStreamer: + def __init__( + self, + robot_model: RobotModel, + body_control_device: Optional[str] = None, + hand_control_device: Optional[str] = None, + enable_real_device=True, + body_streamer_ip="", + body_streamer_keyword="", + replay_data_path: Optional[str] = None, + replay_speed: float = 1.0, + ): + # initialize the body + self.body = robot_model + + self.body_control_device = body_control_device + self.hand_control_device = hand_control_device + self.body_streamer_ip = body_streamer_ip + self.body_streamer_keyword = body_streamer_keyword + self.replay_speed = replay_speed + + # enable real robot and devices + self.enable_real_device = enable_real_device + if self.enable_real_device: + if body_control_device == "vive": + from decoupled_wbc.control.teleop.streamers.vive_streamer import ViveStreamer + + self.body_streamer = ViveStreamer( + ip=self.body_streamer_ip, keyword=self.body_streamer_keyword + ) + self.body_streamer.start_streaming() + elif body_control_device == "iphone": + from decoupled_wbc.control.teleop.streamers.iphone_streamer import IphoneStreamer + + self.body_streamer = IphoneStreamer() + self.body_streamer.start_streaming() + elif body_control_device == "leapmotion": + from decoupled_wbc.control.teleop.streamers.leapmotion_streamer import ( + LeapMotionStreamer, + ) + + self.body_streamer = LeapMotionStreamer() + self.body_streamer.start_streaming() + elif body_control_device == "joycon": + from decoupled_wbc.control.teleop.streamers.joycon_streamer import JoyconStreamer + + self.body_streamer = JoyconStreamer() + self.body_streamer.start_streaming() + + elif body_control_device == "pico": + from decoupled_wbc.control.teleop.streamers.pico_streamer import PicoStreamer + + self.body_streamer = PicoStreamer() + self.body_streamer.start_streaming() + elif body_control_device == "dummy": + from decoupled_wbc.control.teleop.streamers.dummy_streamer import DummyStreamer + + self.body_streamer = DummyStreamer() + self.body_streamer.start_streaming() + else: + self.body_streamer = None + + if hand_control_device and hand_control_device != body_control_device: + if hand_control_device == "manus": + from decoupled_wbc.control.teleop.streamers.manus_streamer import ManusStreamer + + self.hand_streamer = ManusStreamer() + self.hand_streamer.start_streaming() + elif hand_control_device == "joycon": + from decoupled_wbc.control.teleop.streamers.joycon_streamer import JoyconStreamer + + self.hand_streamer = JoyconStreamer() + self.hand_streamer.start_streaming() + elif hand_control_device == "iphone": + from decoupled_wbc.control.teleop.streamers.iphone_streamer import IphoneStreamer + + self.hand_streamer = IphoneStreamer() + self.hand_streamer.start_streaming() + elif hand_control_device == "pico": + from decoupled_wbc.control.teleop.streamers.pico_streamer import PicoStreamer + + self.hand_streamer = PicoStreamer() + self.hand_streamer.start_streaming() + else: + self.hand_streamer = None + else: + self.hand_streamer = None + else: + self.body_streamer = None + self.hand_streamer = None + + self.raw_replay_data = None + self.replay_calibration_data = None + self.replay_mode = False + if replay_data_path and not self.enable_real_device: + with open(replay_data_path, "rb") as f: + data_ = pickle.load(f) + self.raw_replay_data = data_["replay_data"] + self.replay_calibration_data = data_["calibration_data"] + print("Found teleop replay data in file: ", replay_data_path) + self.replay_idx = 0 + self.replay_mode = True + + # initialize pre_processors + self.body_control_device = body_control_device + if body_control_device or self.replay_mode: + self.body_pre_processor = WristsPreProcessor( + motion_scale=robot_model.supplemental_info.teleop_upper_body_motion_scale + ) + self.body_pre_processor.register(self.body) + else: + self.body_pre_processor = None + + # initialize hand pre-processors and post-processors + self.hand_control_device = hand_control_device + if hand_control_device or self.replay_mode: + self.left_hand_pre_processor = FingersPreProcessor(side="left") + self.right_hand_pre_processor = FingersPreProcessor(side="right") + + else: + self.left_hand_pre_processor = None + self.right_hand_pre_processor = None + + self.is_calibrated = False + + def _get_replay_data(self) -> StreamerOutput: + streamer_data = StreamerOutput() + + if self.replay_idx < len(self.raw_replay_data): + streamer_data.ik_data.update( + self.raw_replay_data[floor(self.replay_idx / self.replay_speed)] + ) + self.replay_idx += 1 + + return streamer_data + + def _get_live_data(self) -> StreamerOutput: + """Get structured data instead of raw dict""" + if self.body_streamer: + streamer_data = self.body_streamer.get() + else: + streamer_data = StreamerOutput() + + if self.hand_streamer and self.hand_streamer != self.body_streamer: + hand_data = self.hand_streamer.get() + + # Merge hand data into body data (hand data takes precedence) + streamer_data.ik_data.update(hand_data.ik_data) + streamer_data.control_data.update(hand_data.control_data) + streamer_data.teleop_data.update(hand_data.teleop_data) + streamer_data.data_collection_data.update(hand_data.data_collection_data) + + return streamer_data + + def get_streamer_data(self) -> StreamerOutput: + if self.enable_real_device: + streamer_data = self._get_live_data() + elif self.replay_mode: + streamer_data = self._get_replay_data() + else: + streamer_data = StreamerOutput() + + if self.is_calibrated and streamer_data.ik_data: + body_data, left_hand_data, right_hand_data = self.pre_process(streamer_data.ik_data) + streamer_data.ik_data = { + "body_data": body_data, + "left_hand_data": left_hand_data, + "right_hand_data": right_hand_data, + } + elif not self.is_calibrated: + streamer_data.ik_data = {} + + return streamer_data + + def calibrate(self): + """Calibrate the pre-processors using only IK data.""" + if self.replay_mode: + ik_data = self.replay_calibration_data + else: + streamer_data = self._get_live_data() + ik_data = streamer_data.ik_data + + if self.body_pre_processor: + self.body_pre_processor.calibrate(ik_data, self.body_control_device) + if self.left_hand_pre_processor: + self.left_hand_pre_processor.calibrate(ik_data, self.hand_control_device) + if self.right_hand_pre_processor: + self.right_hand_pre_processor.calibrate(ik_data, self.hand_control_device) + + self.is_calibrated = True + + def pre_process(self, raw_data): + """Pre-process the raw data.""" + assert ( + self.body_pre_processor or self.left_hand_pre_processor or self.right_hand_pre_processor + ), "Pre-processors are not initialized." + + # Check if finger data is present in raw_data + has_finger_data = "left_fingers" in raw_data and "right_fingers" in raw_data + + if self.body_pre_processor: + body_data = self.body_pre_processor(raw_data) + # Only process hand data if finger keys are present and preprocessors are available + if has_finger_data and self.left_hand_pre_processor and self.right_hand_pre_processor: + left_hand_data = self.left_hand_pre_processor(raw_data) + right_hand_data = self.right_hand_pre_processor(raw_data) + return body_data, left_hand_data, right_hand_data + else: + return body_data, None, None + else: # only hands + if has_finger_data and self.left_hand_pre_processor and self.right_hand_pre_processor: + left_hand_data = self.left_hand_pre_processor(raw_data) + right_hand_data = self.right_hand_pre_processor(raw_data) + return None, left_hand_data, right_hand_data + else: + # No finger data available, return None for hand data + return None, None, None + + def reset(self): + if self.body_streamer is not None: + self.body_streamer.reset_status() + if self.hand_streamer is not None: + self.hand_streamer.reset_status() + + def stop_streaming(self): + if self.body_streamer: + self.body_streamer.stop_streaming() + # Only stop hand_streamer if it's a different instance than body_streamer + if self.hand_streamer and self.hand_streamer is not self.body_streamer: + self.hand_streamer.stop_streaming() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/cv_bridge.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/cv_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e7ade227fd86d2a3af917e04d6c9cc2c3f0ec3 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/cv_bridge.py @@ -0,0 +1,396 @@ +# Software License Agreement (BSD License) +# +# Copyright (c) 2011, Willow Garage, Inc. +# Copyright (c) 2016, Tal Regev. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of Willow Garage, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import sys + +import cv2 +import sensor_msgs.msg + + +def CV_MAT_CNWrap(flags): + return (((flags) & ((63) << 3)) >> 3) + 1 + + +def CV_MAT_DEPTHWrap(flags): + return (flags) & 7 + + +_CV_CONVERSIONS = { + ("mono8", "rgb8"): cv2.COLOR_GRAY2RGB, + ("mono8", "bgr8"): cv2.COLOR_GRAY2BGR, + ("mono8", "rgba8"): cv2.COLOR_GRAY2RGBA, + ("mono8", "bgra8"): cv2.COLOR_GRAY2BGRA, + ("rgb8", "mono8"): cv2.COLOR_RGB2GRAY, + ("rgb8", "bgr8"): cv2.COLOR_RGB2BGR, + ("rgb8", "rgba8"): cv2.COLOR_RGB2RGBA, + ("rgb8", "bgra8"): cv2.COLOR_RGB2BGRA, + ("bgr8", "mono8"): cv2.COLOR_BGR2GRAY, + ("bgr8", "rgb8"): cv2.COLOR_BGR2RGB, + ("bgr8", "rgba8"): cv2.COLOR_BGR2RGBA, + ("bgr8", "bgra8"): cv2.COLOR_BGR2BGRA, + ("rgba8", "mono8"): cv2.COLOR_RGBA2GRAY, + ("rgba8", "rgb8"): cv2.COLOR_RGBA2RGB, + ("rgba8", "bgr8"): cv2.COLOR_RGBA2BGR, + ("rgba8", "bgra8"): cv2.COLOR_RGBA2BGRA, + ("bgra8", "mono8"): cv2.COLOR_BGRA2GRAY, + ("bgra8", "rgb8"): cv2.COLOR_BGRA2RGB, + ("bgra8", "bgr8"): cv2.COLOR_BGRA2BGR, + ("bgra8", "rgba8"): cv2.COLOR_BGRA2RGBA, + ("yuv422", "mono8"): cv2.COLOR_YUV2GRAY_UYVY, + ("yuv422", "rgb8"): cv2.COLOR_YUV2RGB_UYVY, + ("yuv422", "bgr8"): cv2.COLOR_YUV2BGR_UYVY, + ("yuv422", "rgba8"): cv2.COLOR_YUV2RGBA_UYVY, + ("yuv422", "bgra8"): cv2.COLOR_YUV2BGRA_UYVY, + ("bayer_rggb8", "mono8"): cv2.COLOR_BayerBG2GRAY, + ("bayer_rggb8", "rgb8"): cv2.COLOR_BayerBG2RGB, + ("bayer_rggb8", "bgr8"): cv2.COLOR_BayerBG2BGR, + ("bayer_bggr8", "mono8"): cv2.COLOR_BayerRG2GRAY, + ("bayer_bggr8", "rgb8"): cv2.COLOR_BayerRG2RGB, + ("bayer_bggr8", "bgr8"): cv2.COLOR_BayerRG2BGR, + ("bayer_gbrg8", "mono8"): cv2.COLOR_BayerGR2GRAY, + ("bayer_gbrg8", "rgb8"): cv2.COLOR_BayerGR2RGB, + ("bayer_gbrg8", "bgr8"): cv2.COLOR_BayerGR2BGR, + ("bayer_grbg", "mono8"): cv2.COLOR_BayerGB2GRAY, + ("bayer_grbg", "rgb8"): cv2.COLOR_BayerGB2RGB, + ("bayer_grbg", "bgr8"): cv2.COLOR_BayerGB2BGR, +} + +_CV_TYPES = { + "rgb8": cv2.CV_8UC3, + "rgba8": cv2.CV_8UC4, + "rgb16": cv2.CV_16UC3, + "rgba16": cv2.CV_16UC4, + "bgr8": cv2.CV_8UC3, + "bgra8": cv2.CV_8UC4, + "bgr16": cv2.CV_16UC3, + "bgra16": cv2.CV_16UC4, + "mono8": cv2.CV_8UC1, + "mono16": cv2.CV_16UC1, + "8UC1": cv2.CV_8UC1, + "8UC2": cv2.CV_8UC2, + "8UC3": cv2.CV_8UC3, + "8UC4": cv2.CV_8UC4, + "8SC1": cv2.CV_8SC1, + "8SC2": cv2.CV_8SC2, + "8SC3": cv2.CV_8SC3, + "8SC4": cv2.CV_8SC4, + "16UC1": cv2.CV_8UC1, + "16UC2": cv2.CV_8UC2, + "16UC3": cv2.CV_8UC3, + "16UC4": cv2.CV_8UC4, + "16SC1": cv2.CV_16SC1, + "16SC2": cv2.CV_16SC2, + "16SC3": cv2.CV_16SC3, + "16SC4": cv2.CV_16SC4, + "32SC1": cv2.CV_32SC1, + "32SC2": cv2.CV_32SC2, + "32SC3": cv2.CV_32SC3, + "32SC4": cv2.CV_32SC4, + "32FC1": cv2.CV_32FC1, + "32FC2": cv2.CV_32FC2, + "32FC3": cv2.CV_32FC3, + "32FC4": cv2.CV_32FC4, + "64FC1": cv2.CV_64FC1, + "64FC2": cv2.CV_64FC2, + "64FC3": cv2.CV_64FC3, + "64FC4": cv2.CV_64FC4, + "bayer_rggb8": cv2.CV_8UC1, + "bayer_bggr8": cv2.CV_8UC1, + "bayer_gbrg8": cv2.CV_8UC1, + "bayer_grbg8": cv2.CV_8UC1, + "bayer_rggb16": cv2.CV_16UC1, + "bayer_bggr16": cv2.CV_16UC1, + "bayer_gbrg16": cv2.CV_16UC1, + "bayer_grbg16": cv2.CV_16UC1, +} + + +def cvtColor2(img, encoding_in, encoding_out): + if encoding_in == encoding_out: + return img + + conversion = _CV_CONVERSIONS[(encoding_in, encoding_out)] + # depth conversion is not yet implemented + return cv2.cvtColor(img, conversion) + + +def getCvType(encoding): + return _CV_TYPES[encoding] + + +class CvBridgeError(TypeError): + """ + This is the error raised by :class:`cv_bridge.CvBridge` methods when they fail. + """ + + pass + + +class CvBridge(object): + """ + The CvBridge is an object that converts between OpenCV Images and ROS Image messages. + + .. doctest:: + :options: -ELLIPSIS, +NORMALIZE_WHITESPACE + + >>> import cv2 + >>> import numpy as np + >>> from cv_bridge import CvBridge + >>> br = CvBridge() + >>> dtype, n_channels = br.encoding_as_cvtype2('8UC3') + >>> im = np.ndarray(shape=(480, 640, n_channels), dtype=dtype) + >>> msg = br.cv2_to_imgmsg(im) # Convert the image to a message + >>> im2 = br.imgmsg_to_cv2(msg) # Convert the message to a new image + >>> cmprsmsg = br.cv2_to_compressed_imgmsg(im) # Convert the image to a compress message + >>> im22 = br.compressed_imgmsg_to_cv2(msg) # Convert the compress message to a new image + >>> cv2.imwrite("this_was_a_message_briefly.png", im2) + + """ + + def __init__(self): + import cv2 + + self.cvtype_to_name = {} + self.cvdepth_to_numpy_depth = { + cv2.CV_8U: "uint8", + cv2.CV_8S: "int8", + cv2.CV_16U: "uint16", + cv2.CV_16S: "int16", + cv2.CV_32S: "int32", + cv2.CV_32F: "float32", + cv2.CV_64F: "float64", + } + + for t in ["8U", "8S", "16U", "16S", "32S", "32F", "64F"]: + for c in [1, 2, 3, 4]: + nm = "%sC%d" % (t, c) + self.cvtype_to_name[getattr(cv2, "CV_%s" % nm)] = nm + + self.numpy_type_to_cvtype = { + "uint8": "8U", + "int8": "8S", + "uint16": "16U", + "int16": "16S", + "int32": "32S", + "float32": "32F", + "float64": "64F", + } + self.numpy_type_to_cvtype.update( + dict((v, k) for (k, v) in self.numpy_type_to_cvtype.items()) + ) + + def dtype_with_channels_to_cvtype2(self, dtype, n_channels): + return "%sC%d" % (self.numpy_type_to_cvtype[dtype.name], n_channels) + + def cvtype2_to_dtype_with_channels(self, cvtype): + return self.cvdepth_to_numpy_depth[CV_MAT_DEPTHWrap(cvtype)], CV_MAT_CNWrap(cvtype) + + def encoding_to_cvtype2(self, encoding): + try: + return getCvType(encoding) + except RuntimeError as e: + raise CvBridgeError(e) + + def encoding_to_dtype_with_channels(self, encoding): + return self.cvtype2_to_dtype_with_channels(self.encoding_to_cvtype2(encoding)) + + def compressed_imgmsg_to_cv2(self, cmprs_img_msg, desired_encoding="passthrough"): + """ + Convert a sensor_msgs::CompressedImage message to an OpenCV :cpp:type:`cv::Mat`. + + :param cmprs_img_msg: A :cpp:type:`sensor_msgs::CompressedImage` message + :param desired_encoding: The encoding of the image data, one of the following strings: + + * ``"passthrough"`` + * one of the standard strings in sensor_msgs/image_encodings.h + + :rtype: :cpp:type:`cv::Mat` + :raises CvBridgeError: when conversion is not possible. + + If desired_encoding is ``"passthrough"``, then the returned image has the same format as img_msg. + Otherwise desired_encoding must be one of the standard image encodings + + This function returns an OpenCV :cpp:type:`cv::Mat` message on success, or raises + :exc:`cv_bridge.CvBridgeError` on failure. + + If the image only has one channel, the shape has size 2 (width and height) + """ + import cv2 + import numpy as np + + str_msg = cmprs_img_msg.data + buf = np.ndarray(shape=(1, len(str_msg)), dtype=np.uint8, buffer=cmprs_img_msg.data) + im = cv2.imdecode(buf, cv2.IMREAD_ANYCOLOR) + + if desired_encoding == "passthrough": + return im + + try: + res = cvtColor2(im, "bgr8", desired_encoding) + except RuntimeError as e: + raise CvBridgeError(e) + + return res + + def imgmsg_to_cv2(self, img_msg, desired_encoding="passthrough"): + """ + Convert a sensor_msgs::Image message to an OpenCV :cpp:type:`cv::Mat`. + + :param img_msg: A :cpp:type:`sensor_msgs::Image` message + :param desired_encoding: The encoding of the image data, one of the following strings: + + * ``"passthrough"`` + * one of the standard strings in sensor_msgs/image_encodings.h + + :rtype: :cpp:type:`cv::Mat` + :raises CvBridgeError: when conversion is not possible. + + If desired_encoding is ``"passthrough"``, then the returned image has the same format as img_msg. + Otherwise desired_encoding must be one of the standard image encodings + + This function returns an OpenCV :cpp:type:`cv::Mat` message on success, or raises + :exc:`cv_bridge.CvBridgeError` on failure. + + If the image only has one channel, the shape has size 2 (width and height) + """ + import numpy as np + + dtype, n_channels = self.encoding_to_dtype_with_channels(img_msg.encoding) + dtype = np.dtype(dtype) + dtype = dtype.newbyteorder(">" if img_msg.is_bigendian else "<") + if n_channels == 1: + im = np.ndarray(shape=(img_msg.height, img_msg.width), dtype=dtype, buffer=img_msg.data) + else: + im = np.ndarray( + shape=(img_msg.height, img_msg.width, n_channels), dtype=dtype, buffer=img_msg.data + ) + # If the byt order is different between the message and the system. + if img_msg.is_bigendian == (sys.byteorder == "little"): + im = im.byteswap().newbyteorder() + + if desired_encoding == "passthrough": + return im + + try: + res = cvtColor2(im, img_msg.encoding, desired_encoding) + except RuntimeError as e: + raise CvBridgeError(e) + + return res + + def cv2_to_compressed_imgmsg(self, cvim, dst_format="jpg"): + """ + Convert an OpenCV :cpp:type:`cv::Mat` type to a ROS sensor_msgs::CompressedImage message. + + :param cvim: An OpenCV :cpp:type:`cv::Mat` + :param dst_format: The format of the image data, one of the following strings: + + * from http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html + * from http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#Mat + imread(const string& filename, int flags) + * bmp, dib + * jpeg, jpg, jpe + * jp2 + * png + * pbm, pgm, ppm + * sr, ras + * tiff, tif + + :rtype: A sensor_msgs.msg.CompressedImage message + :raises CvBridgeError: when the ``cvim`` has a type that is incompatible with ``format`` + + + This function returns a sensor_msgs::Image message on success, or raises + :exc:`cv_bridge.CvBridgeError` on failure. + """ + import cv2 + import numpy as np + + if not isinstance(cvim, (np.ndarray, np.generic)): + raise TypeError("Your input type is not a numpy array") + cmprs_img_msg = sensor_msgs.msg.CompressedImage() + cmprs_img_msg.format = dst_format + ext_format = "." + dst_format + try: + cmprs_img_msg.data = np.array(cv2.imencode(ext_format, cvim)[1]).tostring() + except RuntimeError as e: + raise CvBridgeError(e) + + return cmprs_img_msg + + def cv2_to_imgmsg(self, cvim, encoding="passthrough"): + """ + Convert an OpenCV :cpp:type:`cv::Mat` type to a ROS sensor_msgs::Image message. + + :param cvim: An OpenCV :cpp:type:`cv::Mat` + :param encoding: The encoding of the image data, one of the following strings: + + * ``"passthrough"`` + * one of the standard strings in sensor_msgs/image_encodings.h + + :rtype: A sensor_msgs.msg.Image message + :raises CvBridgeError: when the ``cvim`` has a type that is incompatible with ``encoding`` + + If encoding is ``"passthrough"``, then the message has the same encoding as the image's OpenCV type. + Otherwise desired_encoding must be one of the standard image encodings + + This function returns a sensor_msgs::Image message on success, or raises + :exc:`cv_bridge.CvBridgeError`on failure. + """ + import numpy as np + + if not isinstance(cvim, (np.ndarray, np.generic)): + raise TypeError("Your input type is not a numpy array") + img_msg = sensor_msgs.msg.Image() + img_msg.height = cvim.shape[0] + img_msg.width = cvim.shape[1] + if len(cvim.shape) < 3: + cv_type = self.dtype_with_channels_to_cvtype2(cvim.dtype, 1) + else: + cv_type = self.dtype_with_channels_to_cvtype2(cvim.dtype, cvim.shape[2]) + if encoding == "passthrough": + img_msg.encoding = cv_type + else: + img_msg.encoding = encoding + # # Verify that the supplied encoding is compatible with the type of the OpenCV image + # if self.cvtype_to_name[self.encoding_to_cvtype2(encoding)] != cv_type: + # raise CvBridgeError( + # "encoding specified as %s, but image has incompatible type %s" + # % (encoding, cv_type) + # ) + if cvim.dtype.byteorder == ">": + img_msg.is_bigendian = True + img_msg.data = cvim.tostring() + img_msg.step = len(img_msg.data) // img_msg.height + + return img_msg diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/episode_state.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/episode_state.py new file mode 100644 index 0000000000000000000000000000000000000000..a808a9c5a1d750b1536f819515913e9632dbdb94 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/episode_state.py @@ -0,0 +1,32 @@ +class EpisodeState: + """Episode state controller for data collection. + + Manages the state transitions for episode recording: + - IDLE: Not recording + - RECORDING: Currently recording data + - NEED_TO_SAVE: Recording stopped, waiting to save + """ + + def __init__(self): + self.RECORDING = "recording" + self.IDLE = "idle" + self.NEED_TO_SAVE = "need_to_save" + + self.state = self.IDLE + + def change_state(self): + """Cycle through states: IDLE -> RECORDING -> NEED_TO_SAVE -> IDLE.""" + if self.state == self.IDLE: + self.state = self.RECORDING + elif self.state == self.RECORDING: + self.state = self.NEED_TO_SAVE + elif self.state == self.NEED_TO_SAVE: + self.state = self.IDLE + + def reset_state(self): + """Reset to IDLE state.""" + self.state = self.IDLE + + def get_state(self): + """Get current state.""" + return self.state diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/gear_wbc_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/gear_wbc_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bf036ceb006b77ee88369631d8f56edcc075fd19 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/gear_wbc_utils.py @@ -0,0 +1,100 @@ +import os + +import numpy as np +import yaml + + +def load_config(config_path): + """Load and process the YAML configuration file""" + with open(config_path, "r") as f: + config = yaml.safe_load(f) + + # Set the path to the LEGGED_GYM_ROOT_DIR using relative path + current_file_dir = os.path.dirname(os.path.abspath(config_path)) + LEGGED_GYM_ROOT_DIR = os.path.join(current_file_dir, "..", "GearWbcRL", "legged_gym") + LEGGED_GYM_ROOT_DIR = os.path.abspath(LEGGED_GYM_ROOT_DIR) + + # Process paths with LEGGED_GYM_ROOT_DIR + for path_key in ["policy_path", "xml_path", "onnx_policy_path"]: + if path_key in config: + config[path_key] = config[path_key].format(LEGGED_GYM_ROOT_DIR=LEGGED_GYM_ROOT_DIR) + + # Convert lists to numpy arrays where needed + array_keys = ["kps", "kds", "default_angles", "cmd_scale", "cmd_init"] + for key in array_keys: + if key in config: + config[key] = np.array(config[key], dtype=np.float32) + + return config, LEGGED_GYM_ROOT_DIR + + +def pd_control(target_q, q, kp, target_dq, dq, kd): + """Calculates torques from position commands""" + return (target_q - q) * kp + (target_dq - dq) * kd + + +def quat_rotate_inverse(q, v): + """Rotate vector v by the inverse of quaternion q""" + w = q[..., 0] + x = q[..., 1] + y = q[..., 2] + z = q[..., 3] + + q_conj = np.array([w, -x, -y, -z]) + + return np.array( + [ + v[0] * (q_conj[0] ** 2 + q_conj[1] ** 2 - q_conj[2] ** 2 - q_conj[3] ** 2) + + v[1] * 2 * (q_conj[1] * q_conj[2] - q_conj[0] * q_conj[3]) + + v[2] * 2 * (q_conj[1] * q_conj[3] + q_conj[0] * q_conj[2]), + v[0] * 2 * (q_conj[1] * q_conj[2] + q_conj[0] * q_conj[3]) + + v[1] * (q_conj[0] ** 2 - q_conj[1] ** 2 + q_conj[2] ** 2 - q_conj[3] ** 2) + + v[2] * 2 * (q_conj[2] * q_conj[3] - q_conj[0] * q_conj[1]), + v[0] * 2 * (q_conj[1] * q_conj[3] - q_conj[0] * q_conj[2]) + + v[1] * 2 * (q_conj[2] * q_conj[3] + q_conj[0] * q_conj[1]) + + v[2] * (q_conj[0] ** 2 - q_conj[1] ** 2 - q_conj[2] ** 2 + q_conj[3] ** 2), + ] + ) + + +def get_gravity_orientation(quat): + """Get gravity vector in body frame""" + gravity_vec = np.array([0.0, 0.0, -1.0]) + return quat_rotate_inverse(quat, gravity_vec) + + +def compute_observation(d, config, action, cmd, height_cmd, n_joints): + """Compute the observation vector from current state""" + # Get state from MuJoCo + qj = d.qpos[7 : 7 + n_joints].copy() + dqj = d.qvel[6 : 6 + n_joints].copy() + quat = d.qpos[3:7].copy() + omega = d.qvel[3:6].copy() + + # Handle default angles padding + if len(config["default_angles"]) < n_joints: + padded_defaults = np.zeros(n_joints, dtype=np.float32) + padded_defaults[: len(config["default_angles"])] = config["default_angles"] + else: + padded_defaults = config["default_angles"][:n_joints] + + # Scale the values + qj_scaled = (qj - padded_defaults) * config["dof_pos_scale"] + dqj_scaled = dqj * config["dof_vel_scale"] + gravity_orientation = get_gravity_orientation(quat) + omega_scaled = omega * config["ang_vel_scale"] + + # Calculate single observation dimension + single_obs_dim = 3 + 1 + 3 + 3 + n_joints + n_joints + 12 + + # Create single observation + single_obs = np.zeros(single_obs_dim, dtype=np.float32) + single_obs[0:3] = cmd[:3] * config["cmd_scale"] + single_obs[3:4] = np.array([height_cmd]) + single_obs[4:7] = omega_scaled + single_obs[7:10] = gravity_orientation + single_obs[10 : 10 + n_joints] = qj_scaled + single_obs[10 + n_joints : 10 + 2 * n_joints] = dqj_scaled + single_obs[10 + 2 * n_joints : 10 + 2 * n_joints + 12] = action + + return single_obs, single_obs_dim diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/img_viewer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/img_viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..9416eff66a22cef0f1bf627f0dee6a80cd319e03 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/img_viewer.py @@ -0,0 +1,91 @@ +import matplotlib.pyplot as plt +import numpy as np + + +class ImageViewer: + def __init__(self, title="Image Viewer", figsize=(8, 6), num_images=1, image_titles=None): + self.title = title + self.figsize = figsize + self.num_images = num_images + self.image_titles = image_titles or [f"Camera {i+1}" for i in range(num_images)] + + # Enable interactive mode before creating subplots + plt.ion() + + if num_images == 1: + self._fig, self._ax = plt.subplots(figsize=self.figsize) + self._ax.set_title(self.title) + self._im = self._ax.imshow(np.zeros((100, 100))) + self._ax.axis("off") + self._axes = [self._ax] + self._images = [self._im] + else: + # Calculate grid dimensions + cols = min(num_images, 3) # Max 3 columns + rows = (num_images + cols - 1) // cols + + # Adjust figure size based on number of images + fig_width = self.figsize[0] * min(cols, 2) + fig_height = self.figsize[1] * rows / 2 + + self._fig, axes = plt.subplots(rows, cols, figsize=(fig_width, fig_height)) + self._fig.suptitle(self.title) + + # Flatten axes array for easier access + if num_images == 2: + axes = [axes[0], axes[1]] + elif rows == 1: + axes = axes if cols > 1 else [axes] + else: + axes = axes.flatten() + + self._axes = [] + self._images = [] + + for i in range(num_images): + ax = axes[i] + ax.set_title(self.image_titles[i]) + im = ax.imshow(np.zeros((100, 100))) + ax.axis("off") + self._axes.append(ax) + self._images.append(im) + + # Hide unused subplots + for i in range(num_images, len(axes)): + axes[i].set_visible(False) + + # Show the figure initially to make window appear + self._fig.show() + + def show(self, image_array): + """Show a single image (backward compatibility)""" + if self.num_images == 1: + self._images[0].set_data(image_array) + else: + # If multiple viewers but single image provided, show in first viewer + self._images[0].set_data(image_array) + + # non-blocking update + self._fig.canvas.draw_idle() + self._fig.canvas.flush_events() + + def show_multiple(self, images): + """Show multiple images""" + for i, img in enumerate(images): + if i < len(self._images) and img is not None: + self._images[i].set_data(img) + # Auto-adjust aspect ratio + self._axes[i].set_aspect("auto") + + # non-blocking update + self._fig.canvas.draw_idle() + self._fig.canvas.flush_events() + + def close(self): + plt.close(self._fig) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/keyboard_dispatcher.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/keyboard_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b91627917cb5fa04137a30553d41b02a259ac3 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/keyboard_dispatcher.py @@ -0,0 +1,255 @@ +import os +import subprocess +import sys +import threading + +import rclpy +from sshkeyboard import listen_keyboard, stop_listening +from std_msgs.msg import String as RosStringMsg + +from decoupled_wbc.control.main.constants import KEYBOARD_INPUT_TOPIC + +# Global variable to store original terminal attributes +_original_terminal_attrs = None + + +def save_terminal_state(): + """Save the current terminal state.""" + global _original_terminal_attrs + try: + import termios + + fd = sys.stdin.fileno() + _original_terminal_attrs = termios.tcgetattr(fd) + except (ImportError, OSError, termios.error): + _original_terminal_attrs = None + + +def restore_terminal(): + """Restore terminal to original state.""" + global _original_terminal_attrs + try: + import termios + + if _original_terminal_attrs is not None: + fd = sys.stdin.fileno() + termios.tcsetattr(fd, termios.TCSANOW, _original_terminal_attrs) + return + except (ImportError, OSError, termios.error): + pass + + # Fallback for non-Unix systems or if termios fails + try: + if os.name == "posix": + os.system("stty sane") + except OSError: + pass + + +class ROSKeyboardDispatcher: + """ROS-based keyboard dispatcher that receives keyboard events via ROS topics.""" + + def __init__(self): + self.listeners = [] + self._active = False + assert rclpy.ok(), "Expected ROS2 to be initialized in this process..." + executor = rclpy.get_global_executor() + self.node = executor.get_nodes()[0] + print("creating keyboard input subscriber...") + self.subscription = self.node.create_subscription( + RosStringMsg, KEYBOARD_INPUT_TOPIC, self._callback, 10 + ) + + def register(self, listener): + if not hasattr(listener, "handle_keyboard_button"): + raise NotImplementedError("handle_keyboard_button is not implemented") + self.listeners.append(listener) + + def start(self): + """Start the ROS keyboard dispatcher.""" + self._active = True + print("ROS keyboard dispatcher started") + + def stop(self): + """Stop the ROS keyboard dispatcher and cleanup.""" + if self._active: + self._active = False + # Clean up subscription + if hasattr(self, "subscription"): + self.node.destroy_subscription(self.subscription) + print("ROS keyboard dispatcher stopped") + + def _callback(self, msg: RosStringMsg): + if self._active: + for listener in self.listeners: + listener.handle_keyboard_button(msg.data) + + def __del__(self): + """Cleanup when object is destroyed.""" + self.stop() + + +class KeyboardDispatcher: + def __init__(self): + self.listeners = [] + self._listening_thread = None + self._stop_event = threading.Event() + self._key = None + + def register(self, listener): + # raise if handle_keyboard_button is not implemented + # TODO(YL): let listener be a Callable instead of a class + if not hasattr(listener, "handle_keyboard_button"): + raise NotImplementedError("handle_keyboard_button is not implemented") + self.listeners.append(listener) + + def handle_key(self, key): + # Check if we should stop + if self._stop_event.is_set(): + stop_listening() + return + + for listener in self.listeners: + listener.handle_keyboard_button(key) + + def start_listening(self): + try: + save_terminal_state() # Save original terminal state before listening + listen_keyboard( + on_press=self.handle_key, + delay_second_char=0.1, + delay_other_chars=0.05, + sleep=0.01, + ) + except Exception as e: + print(f"Keyboard listener stopped: {e}") + finally: + # Ensure terminal is restored even if an exception occurs + self._restore_terminal() + + def start(self): + self._listening_thread = threading.Thread(target=self.start_listening, daemon=True) + self._listening_thread.start() + + def stop(self): + """Stop the keyboard listener and restore terminal settings.""" + if self._listening_thread and self._listening_thread.is_alive(): + self._stop_event.set() + # Force stop_listening to be called + try: + stop_listening() + except Exception: + pass + # Wait a bit for the thread to finish + self._listening_thread.join(timeout=0.5) + # Restore terminal settings + self._restore_terminal() + + def _restore_terminal(self): + """Restore terminal to a sane state.""" + restore_terminal() + + def __del__(self): + """Cleanup when object is destroyed.""" + self.stop() + + +KEYBOARD_LISTENER_TOPIC_NAME = "/Gr00tKeyboardListener" + + +class KeyboardListener: + def __init__(self): + self.key = None + + def handle_keyboard_button(self, key): + self.key = key + + def pop_key(self): + key = self.key + self.key = None + return key + + +class KeyboardListenerPublisher: + def __init__(self, topic_name: str = KEYBOARD_LISTENER_TOPIC_NAME): + """ + Initialize keyboard listener for remote teleop with simplified interface. + + Args: + remote_system: RemoteSystem instance + control_channel_name: Name of the control channel + """ + assert rclpy.ok(), "Expected ROS2 to be initialized in this process..." + executor = rclpy.get_global_executor() + self.node = executor.get_nodes()[0] + self.publisher = self.node.create_publisher(RosStringMsg, topic_name, 1) + + def handle_keyboard_button(self, key): + self.publisher.publish(RosStringMsg(data=key)) + + +class KeyboardListenerSubscriber: + def __init__( + self, + topic_name: str = KEYBOARD_LISTENER_TOPIC_NAME, + node_name: str = "keyboard_listener_subscriber", + ): + assert rclpy.ok(), "Expected ROS2 to be initialized in this process..." + executor = rclpy.get_global_executor() + nodes = executor.get_nodes() + if nodes: + self.node = nodes[0] + self._create_node = False + else: + self.node = rclpy.create_node("KeyboardListenerSubscriber") + executor.add_node(self.node) + self._create_node = True + self.subscriber = self.node.create_subscription(RosStringMsg, topic_name, self._callback, 1) + self._data = None + + def _callback(self, msg: RosStringMsg): + self._data = msg.data + + def read_msg(self): + data = self._data + self._data = None + return data + + +class KeyboardEStop: + def __init__(self): + """Initialize KeyboardEStop with automatic tmux cleanup detection.""" + # Automatically create tmux cleanup if in deployment mode + self.cleanup_callback = self._create_tmux_cleanup_callback() + + def _create_tmux_cleanup_callback(self): + """Create a cleanup callback that kills the tmux session if running in deployment mode.""" + tmux_session = os.environ.get("DECOUPLED_WBC_TMUX_SESSION") + + def cleanup_callback(): + if tmux_session: + print(f"Emergency stop: Killing tmux session '{tmux_session}'...") + try: + subprocess.run(["tmux", "kill-session", "-t", tmux_session], timeout=5) + print("Tmux session terminated successfully.") + except subprocess.TimeoutExpired: + print("Warning: Tmux session termination timed out, forcing kill...") + try: + subprocess.run(["tmux", "kill-session", "-t", tmux_session, "-9"]) + except Exception: + pass + except Exception as e: + print(f"Warning: Error during tmux cleanup: {e}") + # If tmux cleanup fails, fallback to immediate exit + restore_terminal() + os._exit(1) + else: + print("Emergency stop: No tmux session, exiting normally...") + sys.exit(1) + + return cleanup_callback + + def handle_keyboard_button(self, key): + if key == "`": + print("Emergency stop triggered - running cleanup...") + self.cleanup_callback() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/logging_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa5f06d0bfc9496573ef72610635b939331db0e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/logging_utils.py @@ -0,0 +1,83 @@ +""" +Simple logging utilities for teleop evaluation. +""" + +from datetime import datetime +import os +from pathlib import Path +from typing import Any, Dict + +import numpy as np + +import decoupled_wbc + + +class EvaluationLogger: + """Simple logger that writes evaluation metrics to a timestamped file.""" + + def __init__(self, log_subdir: str = "logs_teleop"): + """ + Initialize the evaluation logger. + + Args: + log_subdir: Subdirectory name under project root for logs + """ + self.log_subdir = log_subdir + self._setup_logging() + + def _setup_logging(self): + """Setup simple file logging with timestamp-based filename""" + # Get project root directory + project_root = Path(os.path.dirname(decoupled_wbc.__file__)).parent + + # Create logs directory if it doesn't exist + self.logs_dir = project_root / self.log_subdir + self.logs_dir.mkdir(exist_ok=True) + + # Create timestamp-based filename + timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + log_filename = f"eval_{timestamp}.log" + self.log_file_path = self.logs_dir / log_filename + + # Open file for writing + self.log_file = open(self.log_file_path, "w") + + def write(self, message: str): + """Write a message to the log file.""" + self.log_file.write(message + "\n") + self.log_file.flush() # Ensure immediate write + + def log_metrics(self, metrics: Dict[str, Any]): + """ + Log evaluation metrics to file - just like the original print statements. + + Args: + metrics: Dictionary of metric names and values + """ + for metric_name, value in metrics.items(): + if isinstance(value, np.ndarray): + # Convert numpy arrays to readable format + if value.size == 1: + self.write(f"{metric_name}: {value.item()}") + else: + self.write(f"{metric_name}: {value}") + else: + self.write(f"{metric_name}: {value}") + + def get_log_file_path(self) -> Path: + """Get the path to the current log file.""" + return self.log_file_path + + def print(self): + """Print out the contents of the log file.""" + if self.log_file_path.exists(): + with open(self.log_file_path, "r") as f: + content = f.read() + print(content) + else: + print(f"Log file not found: {self.log_file_path}") + + def close(self): + """Close the log file.""" + if hasattr(self, "log_file") and self.log_file: + self.log_file.close() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/n1_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/n1_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..042f328758a60707656610ed1d581c081bb56cb3 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/n1_utils.py @@ -0,0 +1,226 @@ +from typing import Any, Dict, SupportsFloat, Tuple + +import gymnasium as gym +from gymnasium import spaces +import numpy as np + +from decoupled_wbc.control.main.constants import DEFAULT_BASE_HEIGHT, DEFAULT_NAV_CMD +from decoupled_wbc.control.main.teleop.configs.configs import SyncSimDataCollectionConfig +from decoupled_wbc.control.policy.wbc_policy_factory import get_wbc_policy +from decoupled_wbc.control.robot_model import RobotModel +from decoupled_wbc.control.robot_model.instantiation import get_robot_type_and_model + + +class WholeBodyControlWrapper(gym.Wrapper): + """Gymnasium wrapper to integrate whole-body control for locomotion/manipulation sims.""" + + def __init__(self, env, script_config): + super().__init__(env) + self.script_config = script_config + self.script_config["robot"] = env.unwrapped.robot_name + self.wbc_policy = self.setup_wbc_policy() + self._action_space = self._wbc_action_space() + + @property + def robot_model(self) -> RobotModel: + """Return the robot model from the wrapped environment.""" + return self.env.unwrapped.robot_model # type: ignore + + def reset(self, **kwargs): + obs, info = self.env.reset(**kwargs) + self.wbc_policy = self.setup_wbc_policy() + self.wbc_policy.set_observation(obs) + return obs, info + + def step(self, action: Dict[str, Any]) -> Tuple[Any, SupportsFloat, bool, bool, Dict[str, Any]]: + action_dict = concat_action(self.robot_model, action) + + wbc_goal = {} + for key in ["navigate_cmd", "base_height_command", "target_upper_body_pose"]: + if key in action_dict: + wbc_goal[key] = action_dict[key] + + self.wbc_policy.set_goal(wbc_goal) + wbc_action = self.wbc_policy.get_action() + + result = super().step(wbc_action) + self.wbc_policy.set_observation(result[0]) + return result + + def setup_wbc_policy(self): + robot_type, robot_model = get_robot_type_and_model( + self.script_config["robot"], + enable_waist_ik=self.script_config.get("enable_waist", False), + ) + config = SyncSimDataCollectionConfig.from_dict(self.script_config) + config.update( + { + "save_img_obs": False, + "ik_indicator": False, + "enable_real_device": False, + "replay_data_path": None, + } + ) + wbc_config = config.load_wbc_yaml() + wbc_config["upper_body_policy_type"] = "identity" + wbc_policy = get_wbc_policy(robot_type, robot_model, wbc_config, init_time=0.0) + self.total_dofs = len(robot_model.get_joint_group_indices("upper_body")) + wbc_policy.activate_policy() + return wbc_policy + + def _get_joint_group_size(self, group_name: str) -> int: + """Return the number of joints in a group, cached since lookup is static.""" + if not hasattr(self, "_joint_group_size_cache"): + self._joint_group_size_cache = {} + if group_name not in self._joint_group_size_cache: + self._joint_group_size_cache[group_name] = len( + self.robot_model.get_joint_group_indices(group_name) + ) + return self._joint_group_size_cache[group_name] + + def _wbc_action_space(self) -> spaces.Dict: + action_space: Dict[str, spaces.Space] = { + "action.navigate_command": spaces.Box( + low=-np.inf, high=np.inf, shape=(3,), dtype=np.float32 + ), + "action.base_height_command": spaces.Box( + low=-np.inf, high=np.inf, shape=(1,), dtype=np.float32 + ), + "action.left_hand": spaces.Box( + low=-np.inf, + high=np.inf, + shape=(self._get_joint_group_size("left_hand"),), + dtype=np.float32, + ), + "action.right_hand": spaces.Box( + low=-np.inf, + high=np.inf, + shape=(self._get_joint_group_size("right_hand"),), + dtype=np.float32, + ), + "action.left_arm": spaces.Box( + low=-np.inf, + high=np.inf, + shape=(self._get_joint_group_size("left_arm"),), + dtype=np.float32, + ), + "action.right_arm": spaces.Box( + low=-np.inf, + high=np.inf, + shape=(self._get_joint_group_size("right_arm"),), + dtype=np.float32, + ), + } + if ( + "waist" + in self.robot_model.supplemental_info.joint_groups["upper_body_no_hands"]["groups"] # type: ignore[attr-defined] + ): + action_space["action.waist"] = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(self._get_joint_group_size("waist"),), + dtype=np.float32, + ) + return spaces.Dict(action_space) + + +def concat_action(robot_model: RobotModel, goal: Dict[str, Any]) -> Dict[str, Any]: + """Combine individual joint-group targets into the upper-body action vector.""" + processed_goal = {} + for key, value in goal.items(): + processed_goal[key.replace("action.", "")] = value + + first_value = next(iter(processed_goal.values())) + action = np.zeros(first_value.shape[:-1] + (robot_model.num_dofs,)) + + action_dict = {} + action_dict["navigate_cmd"] = processed_goal.pop("navigate_command", DEFAULT_NAV_CMD) + action_dict["base_height_command"] = np.array( + processed_goal.pop("base_height_command", DEFAULT_BASE_HEIGHT) + ) + + for joint_group, value in processed_goal.items(): + indices = robot_model.get_joint_group_indices(joint_group) + action[..., indices] = value + + upper_body_indices = robot_model.get_joint_group_indices("upper_body") + action = action[..., upper_body_indices] + action_dict["target_upper_body_pose"] = action + return action_dict + + +def prepare_observation_for_eval(robot_model: RobotModel, obs: dict) -> dict: + """Add joint-group slices to an observation dict (real + sim evaluation helper).""" + assert "q" in obs, "q is not in the observation" + + whole_q = obs["q"] + assert whole_q.shape[-1] == robot_model.num_joints, "q has wrong shape" + + left_arm_q = whole_q[..., robot_model.get_joint_group_indices("left_arm")] + right_arm_q = whole_q[..., robot_model.get_joint_group_indices("right_arm")] + waist_q = whole_q[..., robot_model.get_joint_group_indices("waist")] + left_leg_q = whole_q[..., robot_model.get_joint_group_indices("left_leg")] + right_leg_q = whole_q[..., robot_model.get_joint_group_indices("right_leg")] + left_hand_q = whole_q[..., robot_model.get_joint_group_indices("left_hand")] + right_hand_q = whole_q[..., robot_model.get_joint_group_indices("right_hand")] + + obs["state.left_arm"] = left_arm_q + obs["state.right_arm"] = right_arm_q + obs["state.waist"] = waist_q + obs["state.left_leg"] = left_leg_q + obs["state.right_leg"] = right_leg_q + obs["state.left_hand"] = left_hand_q + obs["state.right_hand"] = right_hand_q + + return obs + + +def prepare_gym_space_for_eval( + robot_model: RobotModel, gym_space: gym.spaces.Dict +) -> gym.spaces.Dict: + """Extend a gym Dict space with the joint-group keys used during evaluation.""" + left_arm_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(len(robot_model.get_joint_group_indices("left_arm")),), + ) + right_arm_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(len(robot_model.get_joint_group_indices("right_arm")),), + ) + waist_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(len(robot_model.get_joint_group_indices("waist")),), + ) + left_leg_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(len(robot_model.get_joint_group_indices("left_leg")),), + ) + right_leg_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(len(robot_model.get_joint_group_indices("right_leg")),), + ) + left_hand_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(len(robot_model.get_joint_group_indices("left_hand")),), + ) + right_hand_space = spaces.Box( + low=-np.inf, + high=np.inf, + shape=(len(robot_model.get_joint_group_indices("right_hand")),), + ) + + gym_space["state.left_arm"] = left_arm_space + gym_space["state.right_arm"] = right_arm_space + gym_space["state.waist"] = waist_space + gym_space["state.left_leg"] = left_leg_space + gym_space["state.right_leg"] = right_leg_space + gym_space["state.left_hand"] = left_hand_space + gym_space["state.right_hand"] = right_hand_space + + return gym_space diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/network_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/network_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..105a5cd2e7958e3732cf3ed135576b5d90b81e30 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/network_utils.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +""" +Simple network interface utilities +""" + +import platform +import re +import subprocess + + +def get_network_interfaces(): + """Get network interfaces with their IP addresses""" + try: + result = subprocess.run( + ["/sbin/ip", "addr", "show"], capture_output=True, text=True, check=True + ) + return _parse_ip_output(result.stdout) + except (subprocess.CalledProcessError, FileNotFoundError): + try: + result = subprocess.run(["ifconfig"], capture_output=True, text=True, check=True) + return _parse_ifconfig_output(result.stdout) + except (subprocess.CalledProcessError, FileNotFoundError): + return {} + + +def _parse_ip_output(output): + """Parse 'ip addr' command output""" + interfaces = {} + current_interface = None + + for line in output.split("\n"): + interface_match = re.match(r"^\d+:\s+(\w+):", line) + if interface_match: + current_interface = interface_match.group(1) + interfaces[current_interface] = [] + + ip_match = re.search(r"inet\s+(\d+\.\d+\.\d+\.\d+)", line) + if ip_match and current_interface: + interfaces[current_interface].append(ip_match.group(1)) + + return interfaces + + +def _parse_ifconfig_output(output): + """Parse 'ifconfig' command output""" + interfaces = {} + current_interface = None + + for line in output.split("\n"): + interface_match = re.match(r"^(\w+):", line) + if interface_match: + current_interface = interface_match.group(1) + interfaces[current_interface] = [] + + ip_match = re.search(r"inet\s+(\d+\.\d+\.\d+\.\d+)", line) + if ip_match and current_interface: + interfaces[current_interface].append(ip_match.group(1)) + + return interfaces + + +def find_interface_by_ip(target_ip): + """Find interface name for given IP address""" + interfaces = get_network_interfaces() + for interface, ip_list in interfaces.items(): + if target_ip in ip_list: + return interface + return None + + +def resolve_interface(interface: str) -> tuple[str, str]: + """ + Resolve interface parameter to actual network interface name and environment type + + Args: + interface: "sim", "real", or direct interface name or IP address + + Returns: + tuple: (interface_name, env_type) where env_type is "sim" or "real" + """ + # Check if interface is an IP address + if re.match(r"^\d+\.\d+\.\d+\.\d+$", interface): + if interface == "127.0.0.1": + return interface, "sim" + else: + return interface, "real" + + if interface == "sim": + lo_interface = find_interface_by_ip("127.0.0.1") + if lo_interface: + # macOS uses lo0 instead of lo + if platform.system() == "Darwin" and lo_interface == "lo": + return "lo0", "sim" + return lo_interface, "sim" + return ("lo0" if platform.system() == "Darwin" else "lo"), "sim" + + elif interface == "real": + interfaces = get_network_interfaces() + for iface, ip_list in interfaces.items(): + for ip in ip_list: + if ip.startswith("192.168.123."): + return iface, "real" + return interface, "real" # fallback + + else: + # Direct interface name - check if it has 127.0.0.1 to determine env_type + interfaces = get_network_interfaces() + if interface in interfaces: + for ip in interfaces[interface]: + if ip == "127.0.0.1": + return interface, "sim" + + # macOS lo interface handling + if platform.system() == "Darwin" and interface == "lo": + return "lo0", "sim" + + # Default to real for unknown interfaces + return interface, "real" + + +if __name__ == "__main__": + interfaces = get_network_interfaces() + + if not interfaces: + print("No network interfaces found") + exit(1) + + # Show all interfaces + print("Network interfaces:") + for interface, ip_list in interfaces.items(): + print(f" {interface}: {', '.join(ip_list)}") + + # Test resolve_interface function + print("\nTesting resolve_interface:") + for test_interface in ["sim", "real", "lo", "127.0.0.1"]: + interface_name, env_type = resolve_interface(test_interface) + print(f" {test_interface} -> {interface_name} ({env_type})") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/ros_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/ros_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f24890fb72dcd00401602eccb772e861f30c72d0 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/ros_utils.py @@ -0,0 +1,201 @@ +import base64 +import signal +import threading +from typing import Optional + +import msgpack +import msgpack_numpy as mnp +import rclpy +from rclpy.executors import SingleThreadedExecutor +from rclpy.node import Node +from sensor_msgs.msg import Image +from std_msgs.msg import ByteMultiArray +from std_srvs.srv import Trigger + +_signal_registered = False + + +def register_keyboard_interrupt_handler(): + """ + Register a signal handler for SIGINT (Ctrl+C) and SIGTERM that raises KeyboardInterrupt. + This ensures consistent exception handling across different termination signals. + """ + global _signal_registered + if not _signal_registered: + + def signal_handler(signum, frame): + raise KeyboardInterrupt + + signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) + _signal_registered = True + + +class ROSManager: + """ + Manages the ROS2 node and executor. + + Usage example: + ```python + def main(): + ros_manager = ROSManager() + node = ros_manager.node + + try: + while ros_manager.ok(): + time.sleep(0.1) + except ros_manager.exceptions() as e: + print(f"ROSManager interrupted by user: {e}") + finally: + ros_manager.shutdown() + ``` + """ + + def __init__(self, node_name: str = "ros_manager"): + if not rclpy.ok(): + rclpy.init() + self.node = rclpy.create_node(node_name) + self.thread = threading.Thread(target=rclpy.spin, args=(self.node,), daemon=True) + self.thread.start() + else: + executor = rclpy.get_global_executor() + if len(executor.get_nodes()) > 0: + self.node = executor.get_nodes()[0] + else: + self.node = rclpy.create_node(node_name) + + register_keyboard_interrupt_handler() + + @staticmethod + def ok(): + return rclpy.ok() + + @staticmethod + def shutdown(): + if rclpy.ok(): + rclpy.shutdown() + + @staticmethod + def exceptions(): + return (rclpy.exceptions.ROSInterruptException, KeyboardInterrupt) + + +class ROSMsgPublisher: + """ + Publishes any serializable dict to a topic. + """ + + def __init__(self, topic_name: str): + ros_manager = ROSManager() + self.node = ros_manager.node + self.publisher = self.node.create_publisher(ByteMultiArray, topic_name, 1) + + def publish(self, msg: dict): + payload = msgpack.packb(msg, default=mnp.encode) + payload = tuple(bytes([a]) for a in payload) + msg = ByteMultiArray() + msg.data = payload + self.publisher.publish(msg) + + +class ROSMsgSubscriber: + """ + Subscribes to any topics published by a ROSMsgPublisher. + """ + + def __init__(self, topic_name: str): + ros_manager = ROSManager() + self.node = ros_manager.node + self._msg = None + self.subscription = self.node.create_subscription( + ByteMultiArray, topic_name, self._callback, 1 + ) + + def _callback(self, msg: ByteMultiArray): + self._msg = msg + + def get_msg(self) -> Optional[dict]: + msg = self._msg + if msg is None: + return None + self._msg = None + return msgpack.unpackb(bytes([ab for a in msg.data for ab in a]), object_hook=mnp.decode) + + +class ROSImgMsgSubscriber: + """ + Subscribes to an `Image` topic and returns the image as a numpy array and timestamp. + """ + + def __init__(self, topic_name: str): + ros_manager = ROSManager() + self.node = ros_manager.node + self._msg = None + self.subscription = self.node.create_subscription(Image, topic_name, self._callback, 1) + + from decoupled_wbc.control.utils.cv_bridge import CvBridge + + self.bridge = CvBridge() + + def _callback(self, msg: Image): + self._msg = msg + + def get_image(self) -> Optional[dict]: + """ + Returns the image as a numpy array and the timestamp. + """ + + msg = self._msg + if msg is None: + return None + return { + "image": self.bridge.imgmsg_to_cv2(msg), + "timestamp": msg.header.stamp.sec + msg.header.stamp.nanosec * 1e-9, + } + + +class ROSServiceServer: + """ + Generic ROS2 Service server that stores and serves a config dict. + """ + + def __init__(self, service_name: str, config: dict): + ros_manager = ROSManager() + self.node = ros_manager.node + packed = msgpack.packb(config, default=mnp.encode) + self.message = base64.b64encode(packed).decode("ascii") + self.server = self.node.create_service(Trigger, service_name, self._callback) + + def _callback(self, request, response): + try: + response.success = True + response.message = self.message + print("Sending encoded message of length:", len(response.message)) + except Exception as e: + response.success = False + response.message = str(e) + return response + + +class ROSServiceClient(Node): + + def __init__(self, service_name: str, node_name: str = "service_client"): + super().__init__(node_name) + self.cli = self.create_client(Trigger, service_name) + while not self.cli.wait_for_service(timeout_sec=1.0): + self.get_logger().info("service not available, waiting again...") + self.req = Trigger.Request() + + def get_config(self): + future = self.cli.call_async(self.req) + executor = SingleThreadedExecutor() + executor.add_node(self) + executor.spin_until_future_complete(future, timeout_sec=1.0) + executor.remove_node(self) + executor.shutdown() + result = future.result() + if result.success: + decoded = base64.b64decode(result.message.encode("ascii")) + return msgpack.unpackb(decoded, object_hook=mnp.decode) + else: + raise RuntimeError(f"Service call failed: {result.message}") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/run_real_checklist.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/run_real_checklist.py new file mode 100644 index 0000000000000000000000000000000000000000..9ececbc6005f7f72deee7ef201c46113bc46c6de --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/run_real_checklist.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 + +import sys + + +def check_real_deployment(extra_args): + """Check if this is a real robot deployment.""" + is_real_deployment = False + + # Check if interface argument is provided and not 'lo' or 'lo0' + for i, arg in enumerate(extra_args): + if arg == "--interface": + # Get the next argument (interface value) + if i + 1 < len(extra_args): + interface_value = extra_args[i + 1] + if interface_value not in ["lo", "lo0"]: + is_real_deployment = True + print(f"Real deployment detected: interface = {interface_value}") + break + else: + print(f"Simulation deployment detected: interface = {interface_value}") + + # If no interface specified, assume simulation (default is 'lo' in deploy_g1.py) + if not is_real_deployment: + print("No interface specified - assuming simulation (default interface = lo)") + + return is_real_deployment + + +def show_deployment_checklist(): + """Show deployment checklist and get confirmation.""" + checklist_content = """═══════════════════════════════════════════════════════════════════════════════ + G1 ROBOT DEPLOYMENT CHECKLIST +═══════════════════════════════════════════════════════════════════════════════ + +⚠️ SAFETY VERIFICATION - Complete ALL checks before deployment + +PRE-DEPLOYMENT CHECKLIST: + +□ Sim2Sim Verification + Test in simulation first with interface set to 'sim' before real deployment + +□ Camera System Check + Test real camera with simulation environment before full deployment + +□ State Reading Validation + • Disable action queue + • Verify sensor readings (IMU, joints, fingers) + • Use rerun for visualization + • Contact: Dennis Da (xda@nvidia.com) for assistance + +□ Low Gain Test + • Start with low kp values (2-5x lower than normal) + • Keep kd values unchanged + +□ Clear Workspace + • Remove obstacles and avoid tables + • Ensure adequate clearance in all directions + +□ Emergency Stop Ready + Ensure access to at least one: + • Keyboard e-stop + • Joycon controller + • External power cutoff + +═══════════════════════════════════════════════════════════════════════════════ +🚨 EMERGENCY: Press ` at any time to stop all processes +📹 RECORDING: Connect a webcam to your computer to record the experiment +═══════════════════════════════════════════════════════════════════════════════ + +Usages: + +- hit ` to stop all processes +- hit Ctrl+C to stop single process +- hit Ctrl+\ to quit the tmux +""" + + print("") + print("🚨 REAL ROBOT DEPLOYMENT DETECTED 🚨") + print("") + print(checklist_content) + print("") + + # Get user confirmation + while True: + user_input = input("Continue with deployment? [Y/n]: ").strip() + + # Default to Y if empty input + if not user_input: + user_input = "Y" + + user_input_upper = user_input.upper() + + if user_input_upper in ["Y", "YES"]: + print("") + print("✅ Deployment confirmed. Proceeding with robot deployment...") + print("") + return True + elif user_input_upper in ["N", "NO"]: + print("") + print("❌ Deployment aborted by user.") + print("") + return False + else: + print( + "❌ Invalid input. Please enter 'Y' for yes, 'N' for no, or press Enter for default (Y)." + ) + + +def main(): + """Main function.""" + # Always show the checklist + if not show_deployment_checklist(): + print("Deployment cancelled.") + sys.exit(1) + + return 0 + + +if __name__ == "__main__": + main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/service.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/service.py new file mode 100644 index 0000000000000000000000000000000000000000..1d510ab600ae2afbf0728d4589e38205f2122219 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/service.py @@ -0,0 +1,182 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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 dataclasses import dataclass +from io import BytesIO +from typing import Any, Callable, Dict + +import torch +import zmq + + +class TorchSerializer: + @staticmethod + def to_bytes(data: dict) -> bytes: + buffer = BytesIO() + torch.save(data, buffer) + return buffer.getvalue() + + @staticmethod + def from_bytes(data: bytes) -> dict: + buffer = BytesIO(data) + obj = torch.load(buffer, weights_only=False) + return obj + + +@dataclass +class EndpointHandler: + handler: Callable + requires_input: bool = True + + +class BaseInferenceServer: + """ + An inference server that spin up a ZeroMQ socket and listen for incoming requests. + Can add custom endpoints by calling `register_endpoint`. + """ + + def __init__(self, host: str = "*", port: int = 5555): + self.running = True + self.context = zmq.Context() + self.socket = self.context.socket(zmq.REP) + self.socket.bind(f"tcp://{host}:{port}") + self._endpoints: dict[str, EndpointHandler] = {} + + # Register the ping endpoint by default + self.register_endpoint("ping", self._handle_ping, requires_input=False) + self.register_endpoint("kill", self._kill_server, requires_input=False) + + def _kill_server(self): + """ + Kill the server. + """ + self.running = False + + def _handle_ping(self) -> dict: + """ + Simple ping handler that returns a success message. + """ + return {"status": "ok", "message": "Server is running"} + + def register_endpoint(self, name: str, handler: Callable, requires_input: bool = True): + """ + Register a new endpoint to the server. + + Args: + name: The name of the endpoint. + handler: The handler function that will be called when the endpoint is hit. + requires_input: Whether the handler requires input data. + """ + self._endpoints[name] = EndpointHandler(handler, requires_input) + + def run(self): + addr = self.socket.getsockopt_string(zmq.LAST_ENDPOINT) + print(f"Server is ready and listening on {addr}") + while self.running: + try: + message = self.socket.recv() + request = TorchSerializer.from_bytes(message) + endpoint = request.get("endpoint", "get_action") + + if endpoint not in self._endpoints: + raise ValueError(f"Unknown endpoint: {endpoint}") + + handler = self._endpoints[endpoint] + result = ( + handler.handler(request.get("data", {})) + if handler.requires_input + else handler.handler() + ) + self.socket.send(TorchSerializer.to_bytes(result)) + except Exception as e: + print(f"Error in server: {e}") + import traceback + + print(traceback.format_exc()) + self.socket.send(b"ERROR") + + +class BaseInferenceClient: + def __init__(self, host: str = "localhost", port: int = 5555, timeout_ms: int = 15000): + self.context = zmq.Context() + self.host = host + self.port = port + self.timeout_ms = timeout_ms + self._init_socket() + + def _init_socket(self): + """Initialize or reinitialize the socket with current settings""" + self.socket = self.context.socket(zmq.REQ) + self.socket.connect(f"tcp://{self.host}:{self.port}") + + def ping(self) -> bool: + try: + self.call_endpoint("ping", requires_input=False) + return True + except zmq.error.ZMQError: + self._init_socket() # Recreate socket for next attempt + return False + + def kill_server(self): + """ + Kill the server. + """ + self.call_endpoint("kill", requires_input=False) + + def call_endpoint( + self, endpoint: str, data: dict | None = None, requires_input: bool = True + ) -> dict: + """ + Call an endpoint on the server. + + Args: + endpoint: The name of the endpoint. + data: The input data for the endpoint. + requires_input: Whether the endpoint requires input data. + """ + request: dict = {"endpoint": endpoint} + if requires_input: + request["data"] = data + + self.socket.send(TorchSerializer.to_bytes(request)) + message = self.socket.recv() + if message == b"ERROR": + raise RuntimeError("Server error") + return TorchSerializer.from_bytes(message) + + def __del__(self): + """Cleanup resources on destruction""" + self.socket.close() + self.context.term() + + +class ExternalRobotInferenceClient(BaseInferenceClient): + """ + Client for communicating with the RealRobotServer + """ + + def set_observation(self, observation: dict[str, Any]): + self.call_endpoint("set_observation", data=observation) + + def get_action(self, time: float | None = None) -> Dict[str, Any]: + """ + Get the action from the server. + The exact definition of the observations is defined + by the policy, which contains the modalities configuration. + """ + return self.call_endpoint("get_action", data={"time": time}) + + def get_modality_config(self) -> dict[str, Any]: + return self.call_endpoint("get_modality_config") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/sync_sim_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/sync_sim_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ab02db50bd32b66f3530e68446782693ec21221a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/sync_sim_utils.py @@ -0,0 +1,590 @@ +from datetime import datetime +import pathlib +import shutil +from typing import Any, Dict, Optional + +import numpy as np + +from decoupled_wbc.control.envs.robocasa.sync_env import G1SyncEnv, SyncEnv +from decoupled_wbc.control.envs.robocasa.utils.controller_utils import ( + get_body_ik_solver_settings_type, + update_robosuite_controller_configs, +) +from decoupled_wbc.control.main.constants import DEFAULT_BASE_HEIGHT, DEFAULT_NAV_CMD +from decoupled_wbc.control.main.teleop.configs.configs import SyncSimDataCollectionConfig +from decoupled_wbc.control.policy.teleop_policy import TeleopPolicy +from decoupled_wbc.control.policy.wbc_policy_factory import get_wbc_policy +from decoupled_wbc.control.robot_model.instantiation import get_robot_type_and_model +from decoupled_wbc.control.robot_model.robot_model import RobotModel +from decoupled_wbc.control.teleop.solver.hand.instantiation.g1_hand_ik_instantiation import ( + instantiate_g1_hand_ik_solver, +) +from decoupled_wbc.control.teleop.teleop_retargeting_ik import TeleopRetargetingIK +from decoupled_wbc.control.utils.episode_state import EpisodeState +from decoupled_wbc.control.utils.text_to_speech import TextToSpeech +from decoupled_wbc.data.exporter import Gr00tDataExporter +from decoupled_wbc.data.utils import get_dataset_features, get_modality_config + +MAX_MUJOCO_STATE_LEN = 800 +COLLECTION_KEY = "c" +SKIP_KEY = "x" + + +class EpisodeManager: + """Manages episode state transitions, done flags, and task completion hold counts. + + This class encapsulates the logic for: + - Episode state management (IDLE -> RECORDING -> NEED_TO_SAVE) + - Done flag handling + - Task completion hold count tracking + - Data collection triggering based on manual/auto mode + - Step counting within episodes + """ + + def __init__(self, config: SyncSimDataCollectionConfig): + self.config = config + self.task_completion_hold_count = -1 + self.done = False + self.step_count = 0 + + # Initialize episode state and text-to-speech for both manual and automatic modes + self.episode_state = EpisodeState() + self.text_to_speech = TextToSpeech() + + def should_collect_data(self) -> bool: + """Determine if data should be collected at this timestep.""" + if not self.config.data_collection: + return False + + if self.config.manual_control: + # Manual mode: only collect when RECORDING or NEED_TO_SAVE + return self.episode_state.get_state() in [ + self.episode_state.RECORDING, + self.episode_state.NEED_TO_SAVE, + ] + else: + # Auto mode: collect when RECORDING or NEED_TO_SAVE + return self.episode_state.get_state() in [ + self.episode_state.RECORDING, + self.episode_state.NEED_TO_SAVE, + ] + + def increment_step(self): + """Increment the step counter.""" + self.step_count += 1 + + def reset_step_count(self): + """Reset the step counter to 0.""" + self.step_count = 0 + + def get_step_count(self) -> int: + """Get the current step count.""" + return self.step_count + + def handle_collection_trigger( + self, wbc_goal: dict, keyboard_input: str | None, step_info: dict + ): + """Handle data collection start/stop triggers. + + Args: + wbc_goal: WBC goal dictionary + keyboard_input: Keyboard input from user (can be None) + step_info: Step information from environment containing success flag + """ + self.done = False + state_changed = False + + if self.config.manual_control: + if wbc_goal.get("toggle_data_collection", False) or ( + keyboard_input and keyboard_input == COLLECTION_KEY + ): + self.episode_state.change_state() + # IDLE -> RECORDING or RECORDING -> NEED_TO_SAVE + state_changed = True + else: + # Auto mode: automatically start collecting data for new env + if self.episode_state.get_state() == self.episode_state.IDLE: + self.episode_state.change_state() # IDLE -> RECORDING + state_changed = True + self.done = step_info.get("success", False) + if ( + self.episode_state.get_state() == self.episode_state.RECORDING + and self.done + and self.task_completion_hold_count == 0 + ): + self.episode_state.change_state() # RECORDING -> NEED_TO_SAVE + state_changed = True + + # Check for CI test completion + if self.config.ci_test and self.step_count >= self._get_ci_test_steps(): + self.episode_state.change_state() # RECORDING -> NEED_TO_SAVE + state_changed = True + + if state_changed: + if self.episode_state.get_state() == self.episode_state.RECORDING: + self.text_to_speech.print_and_say("Started recording episode") + elif self.episode_state.get_state() == self.episode_state.NEED_TO_SAVE: + self.done = True + self.task_completion_hold_count = 0 + self.text_to_speech.print_and_say("Stopping recording, preparing to save") + + def check_export_and_completion(self, exporter: Gr00tDataExporter) -> bool: + """Check if episode should be exported and update completion state. + + Args: + exporter: Data exporter instance + + Returns: + bool: True if environment needs to be reset + """ + need_reset = False + + # Check if we should save the episode + if self.task_completion_hold_count == 0: + exporter.save_episode() + need_reset = True + self.task_completion_hold_count = -1 + + if self.episode_state.get_state() == self.episode_state.NEED_TO_SAVE: + self.episode_state.change_state() # NEED_TO_SAVE -> IDLE + self.text_to_speech.print_and_say("Episode saved.") + + # State machine to check for having a success for N consecutive timesteps + elif self.done: + print( + f"Task success detected! Will collect {self.config.success_hold_steps} additional steps..." + ) + print(f"currently {self.task_completion_hold_count}") + if self.task_completion_hold_count > 0: + self.task_completion_hold_count -= 1 # latched state, decrement count + print(f"Task completed! Collecting {self.task_completion_hold_count} more steps...") + else: + self.task_completion_hold_count = ( + self.config.success_hold_steps + ) # reset count on first success timestep + print( + f"Task success detected! Will collect {self.config.success_hold_steps} additional steps..." + ) + else: + self.task_completion_hold_count = -1 # null the counter if there's no success + + return need_reset + + def handle_skip( + self, wbc_goal: dict, keyboard_input: str | None, exporter: Gr00tDataExporter + ) -> bool: + """Handle episode skip/abort. + + Args: + wbc_goal: WBC goal dictionary + keyboard_input: Keyboard input from user (can be None) + exporter: Data exporter instance + + Returns: + bool: True if episode was skipped and needs reset + """ + if wbc_goal.get("toggle_data_abort", False) or ( + keyboard_input and keyboard_input == SKIP_KEY + ): + exporter.skip_and_start_new_episode() + self.episode_state.reset_state() + self.text_to_speech.print_and_say("Episode discarded, starting new episode") + return True + return False + + def _get_ci_test_steps(self) -> int: + """Get CI test steps based on CI test mode.""" + if self.config.get("ci_test_mode", "unit") == "unit": + return 50 + else: # pre_merge + return 500 + + +class CITestManager: + def __init__(self, config: SyncSimDataCollectionConfig): + self.config = config + self.ci_test_steps = 50 if config.ci_test_mode == "unit" else 500 + self.enable_tracking_check = True if config.ci_test_mode == "pre_merge" else False + self.upper_body_speed_hist = [] + self.last_q_upper_body = None + self.end_effector_tracking_errors = [] + + def check_upper_body_motion( + self, robot_model: RobotModel, wbc_action: dict, config: SyncSimDataCollectionConfig + ): + upper_body_joint_indices = robot_model.get_joint_group_indices("upper_body") + q_upper_body = wbc_action["q"][upper_body_joint_indices] + if self.last_q_upper_body is None: + self.last_q_upper_body = q_upper_body.copy() + self.upper_body_speed_hist.append( + np.abs(q_upper_body - self.last_q_upper_body).mean() * config.control_frequency + ) + self.last_q_upper_body = q_upper_body.copy() + assert q_upper_body.mean() != 0, "Upper body joints should not be zero" + + def check_end_effector_tracking( + self, teleop_cmd: dict, obs: dict, config: SyncSimDataCollectionConfig, i: int + ): + """ + Check end effector tracking error and validate thresholds. + + Args: + teleop_cmd: Teleoperation command containing target poses + obs: Environment observation containing current poses + end_effector_tracking_errors: List to store tracking errors + config: Configuration object containing robot type + i: Current step index + ci_test_steps: Number of steps for CI test + upper_body_speed_hist: History of upper body joint speeds + """ + from scipy.spatial.transform import Rotation as R + + # Get target poses from teleop command (replay data format) + target_left_wrist = teleop_cmd.get("left_wrist") + target_right_wrist = teleop_cmd.get("right_wrist") + + wrist_pose = obs.get("wrist_pose") + + # Extract left and right wrist poses from environment observation (7 for left + 7 for right) + left_pos = wrist_pose[:3] + left_quat = wrist_pose[3:7] + right_pos = wrist_pose[7:10] + right_quat = wrist_pose[10:14] + + # Convert quaternions to rotation matrices for error calculation + left_rot_matrix = R.from_quat(left_quat, scalar_first=True).as_matrix() + right_rot_matrix = R.from_quat(right_quat, scalar_first=True).as_matrix() + + # Construct 4x4 transformation matrices + actual_left_wrist = np.eye(4) + actual_left_wrist[:3, 3] = left_pos + actual_left_wrist[:3, :3] = left_rot_matrix + + actual_right_wrist = np.eye(4) + actual_right_wrist[:3, 3] = right_pos + actual_right_wrist[:3, :3] = right_rot_matrix + + # Calculate position error + left_pos_error = np.linalg.norm(target_left_wrist[:3, 3] - actual_left_wrist[:3, 3]) + right_pos_error = np.linalg.norm(target_right_wrist[:3, 3] - actual_right_wrist[:3, 3]) + + # Calculate rotation error (similar to test_teleop_retargeting_ik) + left_rot_diff = actual_left_wrist[:3, :3] @ target_left_wrist[:3, :3].T + left_rot_error = np.arccos(np.clip((np.trace(left_rot_diff) - 1) / 2, -1, 1)) + right_rot_diff = actual_right_wrist[:3, :3] @ target_right_wrist[:3, :3].T + right_rot_error = np.arccos(np.clip((np.trace(right_rot_diff) - 1) / 2, -1, 1)) + + # Store max error for this timestep + max_pos_error = max(left_pos_error, right_pos_error) + max_rot_error = max(left_rot_error, right_rot_error) + self.end_effector_tracking_errors.append((max_pos_error, max_rot_error)) + + if i >= self.ci_test_steps: + max_pos_errors = [error[0] for error in self.end_effector_tracking_errors] + max_rot_errors = [error[1] for error in self.end_effector_tracking_errors] + + max_pos_error = np.max(max_pos_errors) + max_rot_error = np.max(max_rot_errors) + + average_pos_error = np.mean(max_pos_errors) + average_rot_error = np.mean(max_rot_errors) + + # More realistic thresholds based on observed data + max_pos_threshold = 0.07 # 7cm threshold + max_rot_threshold = np.deg2rad(17) # 17 degree threshold + average_pos_threshold = 0.05 # 5cm threshold + average_rot_threshold = np.deg2rad(12) # 12 degree threshold + + print(f" Position errors - Max: {max_pos_error:.4f}") + print(f" Rotation errors - Max: {np.rad2deg(max_rot_error):.2f}°") + print(f" Average position error: {average_pos_error:.4f}") + print(f" Average rotation error: {np.rad2deg(average_rot_error):.2f}°") + + assert ( + max_pos_error < max_pos_threshold + ), "Maximum end effector position tracking error exceeds threshold" + assert ( + max_rot_error < max_rot_threshold + ), "Maximum end effector rotation tracking error exceeds threshold" + assert ( + average_pos_error < average_pos_threshold + ), "Average end effector position tracking error exceeds threshold" + assert ( + average_rot_error < average_rot_threshold + ), "Average end effector rotation tracking error exceeds threshold" + + assert ( + np.array(self.upper_body_speed_hist).mean() > 0.03 + ), "Mean upper body joint velocities should be larger. Robot might not be moving." + + print("End effector tracking validation passed.") + + # Ensure end effector tracking validation has run + if not self.end_effector_tracking_errors: + assert False, "No end effector tracking data collected during CI test" + elif len(self.end_effector_tracking_errors) < self.ci_test_steps: + assert ( + False + ), f"Only {len(self.end_effector_tracking_errors)} end effector tracking samples collected" + + +def get_features( + robot_model: RobotModel, save_img_obs: bool = False, image_obs_configs: dict[str, dict] = {} +) -> dict[str, dict]: + """Fixture providing test features dict.""" + features = get_dataset_features(robot_model) + features.update( + { + "observation.sim.seed": { + "dtype": "int32", + "shape": (1,), + }, + "observation.sim.max_mujoco_state_len": { + "dtype": "int32", + "shape": (1,), + }, + "observation.sim.mujoco_state_len": { + "dtype": "int32", + "shape": (1,), + }, + "observation.sim.mujoco_state": { + "dtype": "float64", + "shape": (MAX_MUJOCO_STATE_LEN,), + }, + "observation.sim.left_wrist": { + "dtype": "float64", + "shape": (16,), + }, + "observation.sim.right_wrist": { + "dtype": "float64", + "shape": (16,), + }, + "observation.sim.left_fingers": { + "dtype": "float64", + "shape": (400,), + }, + "observation.sim.right_fingers": { + "dtype": "float64", + "shape": (400,), + }, + "observation.sim.target_upper_body_pose": { + "dtype": "float64", + "shape": (len(robot_model.get_joint_group_indices("upper_body")),), + }, + # TODO: support different reduced robot models + } + ) + + features.pop("observation.img_state_delta") + features.pop("observation.images.ego_view") + + if save_img_obs: + for key, value in image_obs_configs.items(): + features.update( + { + f"observation.images.{key.replace('_image', '')}": { + "dtype": "video", + "shape": value["shape"], + "names": ["height", "width", "channel"], + } + } + ) + + return features + + +def generate_frame( + obs: Dict[str, Any], + wbc_action: Dict[str, Any], + seed: int, + mujoco_state: np.ndarray, + mujoco_state_len: int, + max_mujoco_state_len: int, + teleop_cmd: Dict[str, Any], + wbc_goal: Dict[str, Any], + save_img_obs: bool = False, +): + frame = { + "observation.state": np.array(obs["q"], dtype=np.float64), + "observation.eef_state": np.array(obs["wrist_pose"], dtype=np.float64), + "action": np.array(wbc_action["q"], dtype=np.float64), + "action.eef": np.array(wbc_goal["wrist_pose"], dtype=np.float64), + "teleop.navigate_command": np.array( + wbc_goal.get("navigate_cmd", DEFAULT_NAV_CMD), dtype=np.float64 + ), + "teleop.base_height_command": np.array( + teleop_cmd.get("base_height_command", [DEFAULT_BASE_HEIGHT]), dtype=np.float64 + ).reshape( + 1, + ), + "observation.sim.seed": np.array([seed], dtype=np.int32), + "observation.sim.mujoco_state_len": np.array([mujoco_state_len], dtype=np.int32), + "observation.sim.max_mujoco_state_len": np.array([max_mujoco_state_len], dtype=np.int32), + "observation.sim.mujoco_state": mujoco_state.astype(np.float64), + "observation.sim.left_wrist": teleop_cmd["left_wrist"].flatten().astype(np.float64), + "observation.sim.right_wrist": teleop_cmd["right_wrist"].flatten().astype(np.float64), + "observation.sim.left_fingers": teleop_cmd["left_fingers"]["position"] + .flatten() + .astype(np.float64), + "observation.sim.right_fingers": teleop_cmd["right_fingers"]["position"] + .flatten() + .astype(np.float64), + "observation.sim.target_upper_body_pose": wbc_goal["target_upper_body_pose"].astype( + np.float64 + ), + # "observation.sim.target_time": np.array([wbc_goal["target_time"]], dtype=np.float64), + # "observation.sim.interpolation_garbage_collection_time": np.array( + # [wbc_goal["interpolation_garbage_collection_time"]], dtype=np.float64 + # ), + } + + if save_img_obs: + for key, value in obs.items(): + if key.endswith("image"): + frame[f"observation.images.{key.replace('_image', '')}"] = value + return frame + + +def get_data_exporter( + config: SyncSimDataCollectionConfig, + obs: Dict[str, Any], + robot_model: RobotModel, + save_path: Optional[pathlib.Path] = None, +) -> Gr00tDataExporter: + if save_path is None: + save_path = pathlib.Path( + f"./outputs/{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}-{config.robot}-sim-{config.task_name}/" + ) + + if config.remove_existing_dir: + if save_path.exists(): + shutil.rmtree(save_path) + + image_obs_configs = {} + for key, value in obs.items(): + if key.endswith("image"): + image_obs_configs[key] = { + "dtype": "uint8", + "shape": value.shape, + } + + # TODO: use standardized keys for training dataset + modality_config = get_modality_config(robot_model) + exporter = Gr00tDataExporter.create( + save_root=save_path, + fps=config.control_frequency, + features=get_features( + robot_model, save_img_obs=config.save_img_obs, image_obs_configs=image_obs_configs + ), + modality_config=modality_config, + task=config.task_name, + script_config=config, + robot_type=config.robot, + vcodec="libx264", # Use a common codec that should be available + ) + return exporter + + +def get_env(config: SyncSimDataCollectionConfig, **kwargs) -> SyncEnv: + robot_type, _ = get_robot_type_and_model(config.robot, enable_waist_ik=config.enable_waist) + print("Instantiating environment:", config.env_name, config.robot) + controller_configs = update_robosuite_controller_configs( + robot=config.robot, + wbc_version=config.wbc_version, + enable_gravity_compensation=config.enable_gravity_compensation, + ) + + kwargs.update( + { + "ik_indicator": config.ik_indicator, + "control_freq": config.control_frequency, + "renderer": config.renderer, + "controller_configs": controller_configs, + "enable_waist": config.enable_waist, + "enable_gravity_compensation": config.enable_gravity_compensation, + "gravity_compensation_joints": config.gravity_compensation_joints, + } + ) + if robot_type == "g1": + env_type = G1SyncEnv + else: + raise ValueError(f"Unsupported robot type: {robot_type}") + + env = env_type( + env_name=config.task_name, # TODO: should merge with config.env_name + robot_name=config.robot, + **kwargs, + ) + return env + + +def get_env_name(robot: str, task_name: str, enable_waist_ik: bool = False) -> str: + robot_type, _ = get_robot_type_and_model(robot, enable_waist_ik=enable_waist_ik) + env_name = f"gr00tlocomanip_{robot_type}_sim/{task_name}_{robot}_Env" + return env_name + + +def get_body_teleoped_joint_groups(robot: str) -> list[str]: + robot2body_teleoped_joint_groups = { + "G1FixedLowerBody": ["arms"], + "G1FixedBase": ["arms"], + "G1ArmsOnly": ["arms"], + "G1": ["upper_body"], + } + return robot2body_teleoped_joint_groups[robot] + + +def get_teleop_policy( + robot_type: str, + robot_model: RobotModel, + config: SyncSimDataCollectionConfig, + activate_keyboard_listener: bool = True, +) -> TeleopPolicy: + if robot_type == "g1": + left_hand_ik_solver, right_hand_ik_solver = instantiate_g1_hand_ik_solver() + else: + raise ValueError(f"Invalid robot type: {robot_type}") + + # Initializing the teleop policy will block the main process until the Leap Motion is ready. + retargeting_ik = TeleopRetargetingIK( + robot_model=robot_model, + left_hand_ik_solver=left_hand_ik_solver, + right_hand_ik_solver=right_hand_ik_solver, + enable_visualization=config.enable_visualization, + body_active_joint_groups=get_body_teleoped_joint_groups(config.robot), + body_ik_solver_settings_type=get_body_ik_solver_settings_type(config.robot), + ) + teleop_policy = TeleopPolicy( + robot_model=robot_model, + retargeting_ik=retargeting_ik, + body_control_device=config.body_control_device, + hand_control_device=config.hand_control_device, + body_streamer_ip=config.body_streamer_ip, + body_streamer_keyword=config.body_streamer_keyword, + enable_real_device=config.enable_real_device, + replay_data_path=config.replay_data_path, + replay_speed=config.replay_speed, + activate_keyboard_listener=activate_keyboard_listener, + ) + return teleop_policy + + +def get_wbc_config(config: SyncSimDataCollectionConfig): + wbc_config = config.load_wbc_yaml() + wbc_config["upper_body_policy_type"] = "identity" + return wbc_config + + +def get_policies( + config: SyncSimDataCollectionConfig, + robot_type: str, + robot_model: RobotModel, + activate_keyboard_listener: bool = True, +): + wbc_config = get_wbc_config(config) + wbc_policy = get_wbc_policy(robot_type, robot_model, wbc_config, init_time=0.0) + wbc_policy.activate_policy() + teleop_policy = get_teleop_policy(robot_type, robot_model, config, activate_keyboard_listener) + if not config.manual_control: + teleop_policy.activate_policy() + return wbc_policy, teleop_policy diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/telemetry.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..6043184d1dcf3ae3f3f8503a87765586810d5da9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/telemetry.py @@ -0,0 +1,129 @@ +from collections import deque +import time + + +class Telemetry: + """Handles timing and performance monitoring for different code sections.""" + + def __init__(self, window_size: int = 100): + self.window_size = window_size + self._current_timers = {} + self._last_results = {} + self._history = {} # Stores deques for history + + def start_timer(self, name: str): + """Starts a timer for a given operation.""" + self._current_timers[name] = time.perf_counter() + + def stop_timer(self, name: str) -> float: + """Stops a timer and records the duration.""" + if name not in self._current_timers: + print(f"Warning: Telemetry Timer '{name}' stopped without being started.") + return 0.0 + + start_time = self._current_timers.pop(name) + duration = time.perf_counter() - start_time + self.record_value(name, duration) + return duration + + class Timer: + """Context manager for timing operations.""" + + def __init__(self, telemetry, name: str): + self.telemetry = telemetry + self.name = name + + def __enter__(self): + self.telemetry.start_timer(self.name) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.telemetry.stop_timer(self.name) + return False # Don't suppress exceptions + + def timer(self, name: str): + """Returns a context manager for timing an operation. + + Example usage: + with telemetry.timer("operation_name"): + # Code to time goes here + """ + return self.Timer(self, name) + + def record_value(self, name: str, value: float): + """Records a pre-calculated value (e.g., duration, count).""" + self._last_results[name] = value + if name not in self._history: + self._history[name] = deque(maxlen=self.window_size) + self._history[name].append(value) + + def get_last_timing(self) -> dict[str, float]: + """Returns the timing results from the most recent cycle and clears internal state.""" + results = self._last_results.copy() + # Don't clear _last_results here, let the logger decide when it's done + return results + + def clear_last_timing(self): + """Clears the timing results for the next iteration.""" + self._last_results.clear() + + def get_average(self, name: str) -> float | None: + """Calculates the moving average for a recorded metric.""" + if name not in self._history or not self._history[name]: + return None + return sum(self._history[name]) / len(self._history[name]) + + def get_history(self, name: str) -> deque[float] | None: + """Returns the historical data for a metric.""" + return self._history.get(name) + + def log_timing_info( + self, + context: str = "", + threshold: float = 0.001, + log_averages: bool = True, + ): + """Logs timing information based on thresholds and averages.""" + current_iteration_data = self.get_last_timing() # Get the latest data + significant_timings = {k: v for k, v in current_iteration_data.items() if v > threshold} + + should_log = bool(significant_timings) # Log if any timing exceeds threshold + + # Check averages condition + avg_data = {} + if log_averages: + for name in self._history: + avg = self.get_average(name) + if avg is not None: + avg_data[f"{name}_avg"] = avg + if avg_data: # Log if average data exists + should_log = True + + # If nothing to log, return early + if not should_log: + self.clear_last_timing() # Clear data since it wasn't logged + return + + log_lines = [f"\n{context} Timing breakdown:" if context else "\nTiming breakdown:"] + + # Log current iteration significant timings + if significant_timings: + log_lines.append(f" Current Iteration (> {threshold*1000:.1f}ms):") + for name, duration in sorted(significant_timings.items()): + log_lines.append(f" {name}: {duration * 1000:.2f}ms") + elif current_iteration_data: # Log total time even if below threshold + total_key = next((k for k in current_iteration_data if "total" in k), None) + if total_key: + log_lines.append( + f" Current Iteration Total: {current_iteration_data[total_key] * 1000:.2f}ms" + ) + + # Log averages if requested and available + if log_averages and avg_data: + log_lines.append(f" Moving Averages (last {self.window_size} iters):") + for name, avg in sorted(avg_data.items()): + log_lines.append(f" {name}: {avg * 1000:.2f}ms") + + # Print the collected log lines + print("\n".join(log_lines)) + self.clear_last_timing() # Clear data now that it has been logged/processed diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/term_color_constants.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/term_color_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..4e13ac1f3a27380881eb98fa4b857acd348c0fe6 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/term_color_constants.py @@ -0,0 +1,19 @@ +GREEN_BOLD = "\033[1;32m" +RED_BOLD = "\033[1;31m" +YELLOW_BOLD = "\033[1;33m" +BLUE_BOLD = "\033[1;34m" +MAGENTA_BOLD = "\033[1;35m" +CYAN_BOLD = "\033[1;36m" +WHITE_BOLD = "\033[1;37m" +GREY_BOLD = "\033[1;90m" + +GREEN = "\033[32m" +RED = "\033[31m" +YELLOW = "\033[33m" +BLUE = "\033[34m" +MAGENTA = "\033[35m" +CYAN = "\033[36m" +WHITE = "\033[37m" +GREY = "\033[90m" + +RESET = "\033[0m" diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/text_to_speech.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/text_to_speech.py new file mode 100644 index 0000000000000000000000000000000000000000..4e076c814eaa79452ef123e59ed60a4b77e6d367 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/utils/text_to_speech.py @@ -0,0 +1,28 @@ +# text to speech +import pyttsx3 + + +class TextToSpeech: + def __init__(self, rate: int = 150, volume: float = 1.0): + try: + self.engine = pyttsx3.init(driverName="espeak") + self.engine.setProperty("rate", rate) + self.engine.setProperty("volume", volume) + except Exception as e: + print(f"[Text To Speech] Initialization failed: {e}") + self.engine = None + + def say(self, message: str): + """Speak the message if engine is available.""" + if self.engine: + try: + self.engine.say(message) + self.engine.runAndWait() + except Exception as e: + print(f"[Text To Speech] Failed to say message: {e}") + + def print_and_say(self, message: str, say: bool = True): + """Print message and optionally speak it using Text To Speech.""" + print(message) + if say and self.engine is not None: + self.say(message) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/visualization/humanoid_visualizer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/visualization/humanoid_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..815af250c5a944236301683102c438fa73bcc826 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/visualization/humanoid_visualizer.py @@ -0,0 +1,52 @@ +import time + +import meshcat_shapes +import numpy as np +from pinocchio.visualize import MeshcatVisualizer + +from decoupled_wbc.control.robot_model import RobotModel +from decoupled_wbc.control.robot_model.instantiation.g1 import instantiate_g1_robot_model + + +class RobotVisualizer: + def __init__(self, robot: RobotModel): + self.robot = robot + self.viz = MeshcatVisualizer( + self.robot.pinocchio_wrapper.model, + self.robot.pinocchio_wrapper.collision_model, + self.robot.pinocchio_wrapper.visual_model, + ) + try: + self.viz.initViewer(open=True) + + except ImportError as err: + print("Error while initializing the viewer. It seems you should install Python meshcat") + print(err) + exit(0) + + self.viz.loadViewerModel() + self.viz.display(self.robot.q_zero) + + # Visualize frames + self.viz_frames = [self.robot.supplemental_info.root_frame_name] + for side in ["left", "right"]: + self.viz_frames.append(self.robot.supplemental_info.hand_frame_names[side]) + for frame in self.viz_frames: + meshcat_shapes.frame(self.viz.viewer[frame], opacity=1.0) + + def visualize(self, robot_state: np.ndarray): + # visualize robot state + if robot_state is not None: + self.robot.cache_forward_kinematics(robot_state, auto_clip=False) + self.viz.display(robot_state) + for frame_name in self.viz_frames: + self.viz.viewer[frame_name].set_transform(self.robot.frame_placement(frame_name).np) + + +if __name__ == "__main__": + # robot_model = instantiate_gr1_robot_model() + robot_model = instantiate_g1_robot_model() + visualizer = RobotVisualizer(robot_model) + while True: + visualizer.visualize(robot_model.q_zero) + time.sleep(0.01) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/visualization/meshcat_visualizer_env.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/visualization/meshcat_visualizer_env.py new file mode 100644 index 0000000000000000000000000000000000000000..c3981d7f83f41bc5ee22f4a0d3c709b74bda6374 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/control/visualization/meshcat_visualizer_env.py @@ -0,0 +1,77 @@ +from contextlib import contextmanager +import time + +import gymnasium as gym +import numpy as np +from pinocchio.visualize import MeshcatVisualizer + +from decoupled_wbc.control.base.env import Env +from decoupled_wbc.control.robot_model import RobotModel + + +class MeshcatVisualizerEnv(Env): + def __init__(self, robot_model: RobotModel): + self.robot_model = robot_model + self.viz = MeshcatVisualizer( + self.robot_model.pinocchio_wrapper.model, + self.robot_model.pinocchio_wrapper.collision_model, + self.robot_model.pinocchio_wrapper.visual_model, + ) + try: + self.viz.initViewer(open=True) + + except ImportError as err: + print("Error while initializing the viewer. It seems you should install Python meshcat") + print(err) + exit(0) + + self.viz.loadViewerModel() + self.visualize(self.robot_model.pinocchio_wrapper.q0) + time.sleep(1.0) + + self._observation_space = gym.spaces.Dict( + { + "q": gym.spaces.Box( + low=-2 * np.pi, high=2 * np.pi, shape=(self.robot_model.num_dofs,) + ) + } + ) + self._action_space = gym.spaces.Dict( + { + "q": gym.spaces.Box( + low=-2 * np.pi, high=2 * np.pi, shape=(self.robot_model.num_dofs,) + ) + } + ) + + def visualize(self, robot_state: np.ndarray): + # visualize robot state + if robot_state is not None: + self.viz.display(robot_state) + + def observe(self): + # Dummy observation + return {"q": self.robot_model.pinocchio_wrapper.q0} + + def queue_action(self, action: dict[str, np.ndarray]): + self.visualize(action["q"]) + + def reset(self, **kwargs): + self.visualize(self.robot_model.pinocchio_wrapper.q0) + return {"q": self.robot_model.pinocchio_wrapper.q0} + + def sensors(self) -> dict[str, any]: + return {} + + def observation_space(self) -> gym.Space: + return self._observation_space + + def action_space(self) -> gym.Space: + return self._action_space + + def close(self): + return + + @contextmanager + def activate(self): + yield diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/constants.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..024865f60b8efee1ab529ff58322addb59508787 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/constants.py @@ -0,0 +1,5 @@ +# This will be used for both sim and real data collection +RS_VIEW_CAMERA_HEIGHT = 480 +RS_VIEW_CAMERA_WIDTH = 640 + +BUCKET_BASE_PATH = "GearRawDataLeRobotV0" diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/exporter.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb4d2eda5d894d079f4b50b351f0c06cd935d90 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/exporter.py @@ -0,0 +1,514 @@ +import copy +from dataclasses import dataclass +from functools import partial +import json +import os +from pathlib import Path +import shutil +from typing import Optional + +import datasets +from datasets import load_dataset +from datasets.utils import disable_progress_bars +from huggingface_hub.errors import RepositoryNotFoundError +from lerobot.common.datasets.lerobot_dataset import ( + LeRobotDataset, + LeRobotDatasetMetadata, + compute_episode_stats, +) +from lerobot.common.datasets.utils import ( + check_timestamps_sync, + get_episode_data_index, + validate_episode_buffer, + validate_frame, +) +import numpy as np +from PIL import Image as PILImage +import torch +from torchvision import transforms + +from decoupled_wbc.control.main.config_template import ArgsConfig +from decoupled_wbc.data.video_writer import VideoWriter + +disable_progress_bars() # Disable HuggingFace progress bars + + +@dataclass +class DataCollectionInfo: + """ + This dataclass stores additional information that is relevant to the data collection process. + """ + + lower_body_policy: Optional[str] = None + wbc_model_path: Optional[str] = None + teleoperator_username: Optional[str] = None + support_operator_username: Optional[str] = None + robot_type: Optional[str] = None + robot_id: Optional[str] = None + + def to_dict(self) -> dict: + """Convert the dataclass to a dictionary for JSON serialization.""" + return { + "lower_body_policy": self.lower_body_policy, + "wbc_model_path": self.wbc_model_path, + "teleoperator_username": self.teleoperator_username, + "support_operator_username": self.support_operator_username, + "robot_type": self.robot_type, + "robot_id": self.robot_id, + } + + @classmethod + def from_dict(cls, data: dict) -> "DataCollectionInfo": + """Create a DataCollectionInfo instance from a dictionary.""" + return cls(**data) + + +class Gr00tDatasetMetadata(LeRobotDatasetMetadata): + """ + Additional metadata on top of LeRobotDatasetMetadata: + - modality_config: Written to `meta/modality.json` + - discarded_episode_indices: List of episode indices that were discarded. Written to `meta/info.json` + """ + + MODALITY_CONFIG_REL_PATH = Path("meta/modality.json") + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + with open(self.root / self.MODALITY_CONFIG_REL_PATH, "rb") as f: + self.modality_config = json.load(f) + + @classmethod + def create( + cls, + modality_config: dict, + script_config: dict, + data_collection_info: DataCollectionInfo, + *args, + **kwargs, + ): + cls.validate_modality_config(modality_config) + + # Create base metadata object using parent class + obj = super().create(*args, **kwargs) + + # we also need to initialize the discarded_episode_indices + obj.info["script_config"] = script_config + obj.info["discarded_episode_indices"] = [] + obj.info["data_collection_info"] = data_collection_info.to_dict() + with open(obj.root / "meta" / "info.json", "w") as f: + json.dump(obj.info, f, indent=4) + + obj.__class__ = cls + with open(obj.root / cls.MODALITY_CONFIG_REL_PATH, "w") as f: + json.dump(modality_config, f, indent=4) + obj.modality_config = modality_config + return obj + + @staticmethod + def validate_modality_config(modality_config: dict) -> None: + # verify if it contains all state, action, video, annotation keys + valid_keys = ["state", "action", "video", "annotation"] + if not all(key in modality_config for key in valid_keys): + raise ValueError( + f"Modality config must contain all of the following keys: {valid_keys}" + ) + + # verify that each key has a modality_config dict + for key in valid_keys: + if key not in modality_config: + raise ValueError(f"Modality config must contain a '{key}' key") + + +class Gr00tDataExporter(LeRobotDataset): + """ + A class for exporting data collected for a single session to LeRobot Dataset. + + Intended life cycle: + 1. Create a Gr00tDataExporter object + 2. Add frames using add_frame() + 3. Save the episode using save_episode() + - This will flush the episode buffer to disk + - This will also close the video writers + - Create a new video writer and ep buffer to start new episode + + If interrupted, here's the indented behavior: + - Interruption before save_episode() is called: loses the current episode + - Interruption after save_episode() is called: keeps completed episodes + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.video_writers = self.create_video_writer() + + @property + def repo_id(self): + return self.meta.repo_id + + @property + def root(self): + return self.meta.root + + @property + def local_files_only(self): + return self.meta.local_files_only + + @property + def video_keys(self): + return self.meta.video_keys + + @classmethod + def create( + cls, + save_root: str | Path, + fps: int, + features: dict, + modality_config: dict, + task: str, + script_config: ArgsConfig = ArgsConfig(), + data_collection_info: DataCollectionInfo = DataCollectionInfo(), + robot_type: str | None = None, + tolerance_s: float = 1e-4, + vcodec: str = "h264", + overwrite_existing: bool = False, + upload_bucket_path: str | None = None, + ) -> "Gr00tDataExporter": + """ + Create a Gr00tDataExporter object. + + Args: + save_root: The root directory to save the dataset. + fps: The frame rate of the dataset. + features: The features of the dataset. + modality_config: The modality config of the dataset. + task: The task performed during the data collection session. + data_collection_info: The data collection info. + If the dataset already exists, this argument will be ignored. + If data_collection_info is not provided, it will be set to an empty DataCollectionInfo object. + robot_type: The type of robot. + tolerance_s: The tolerance for the dataset. + image_writer_processes: The number of processes to use for the image writer. + image_writer_threads: The number of threads to use for the image writer. + vcodec: The codec to use for the video writer. + """ + + obj = cls.__new__(cls) + repo_id = ( + "tmp/tmp_dataset" # NOTE(fengyuanh): Not relevant since we are not pushing to the hub + ) + if overwrite_existing and (Path(save_root)).exists(): + print( + f"Found existing dataset at {save_root}", + "Cleaning up this directory since overwrite_existing is True.", + ) + shutil.rmtree(save_root) + + if (Path(save_root)).exists(): + # Try to resume from existing dataset + try: + # Load the metadata + obj.meta = Gr00tDatasetMetadata( + repo_id=repo_id, + root=save_root, + ) + + except RepositoryNotFoundError as e: + raise ValueError( + f"Failed to resume from corrupted dataset. Please manually check the dataset at {save_root}" + ) from e + else: + if not isinstance(script_config, dict): + script_config = script_config.to_dict() + obj.meta = Gr00tDatasetMetadata.create( + repo_id=repo_id, + fps=fps, + root=save_root, + # NOTE(fengyuanh): We use "robot_type" instead of this field which requires a Robot object + robot=None, + robot_type=robot_type, + features=features, + modality_config=modality_config, + script_config=script_config, + # NOTE(fengyuanh): Always use videos for exporting + use_videos=True, + data_collection_info=data_collection_info, + ) + obj.tolerance_s = tolerance_s + obj.video_backend = ( + "pyav" # NOTE(fengyuanh): Only used in training, not relevant for exporting + ) + obj.vcodec = vcodec + obj.task = task + obj.image_writer = None + + obj.episode_buffer = obj.create_episode_buffer() + + obj.episodes = None + obj.hf_dataset = obj.create_hf_dataset() + obj.image_transforms = None + obj.delta_timestamps = None + obj.delta_indices = None + obj.episode_data_index = None + obj.upload_bucket_path = upload_bucket_path + obj.video_writers = obj.create_video_writer() + return obj + + def create_video_writer(self) -> dict[str, VideoWriter]: + video_writers = {} + for key in self.meta.video_keys: + video_writers[key] = VideoWriter( + self.root + / self.meta.get_video_file_path(self.episode_buffer["episode_index"], key), + self.meta.shapes[key][1], + self.meta.shapes[key][0], + self.fps, + self.vcodec, + ) + return video_writers + + # @note (k2): This function is copied from LeRobotDataset.add_frame. + # This is done because we want to bypass lerobot's + # image_writer and use our own VideoWriter class. + def add_frame(self, frame: dict) -> None: + """ + This function only adds the frame to the episode_buffer. Videos are handled by the video_writer, + which uses a stream writer to write to disk. + """ + frame = copy.deepcopy(frame) + frame["task"] = frame.get("task", self.task) + + # Convert torch to numpy if needed + for name in frame: + if isinstance(frame[name], torch.Tensor): + frame[name] = frame[name].numpy() + + validate_frame(frame, self.features) + + if self.episode_buffer is None: + self.episode_buffer = self.create_episode_buffer() + + # Automatically add frame_index and timestamp to episode buffer + frame_index = self.episode_buffer["size"] + timestamp = frame.pop("timestamp") if "timestamp" in frame else frame_index / self.fps + self.episode_buffer["frame_index"].append(frame_index) + self.episode_buffer["timestamp"].append(timestamp) + + # Add frame features to episode_buffer + for key in frame: + if key == "task": + # Note: we associate the task in natural language to its task index during `save_episode` + self.episode_buffer["task"].append(frame["task"]) + continue + + if key not in self.features: + raise ValueError( + f"An element of the frame is not in the features. '{key}' not in '{self.features.keys()}'." + ) + + if self.features[key]["dtype"] in ["image", "video"]: + img_path = self._get_image_file_path( + episode_index=self.episode_buffer["episode_index"], + image_key=key, + frame_index=frame_index, + ) + if frame_index == 0: + img_path.parent.mkdir(parents=True, exist_ok=True) + + # @note (k2): using our own VideoWriter class, bypassing the image_writer + self.video_writers[key].add_frame(frame[key]) + self.episode_buffer[key].append(str(img_path)) + else: + self.episode_buffer[key].append(frame[key]) + + self.episode_buffer["size"] += 1 + + def stop_video_writers(self): + if not hasattr(self, "video_writers"): + raise RuntimeError( + "Can't stop video writers because they haven't been initialized. Call create() first." + ) + for key in self.video_writers: + self.video_writers[key].stop() + + def skip_and_start_new_episode( + self, + ) -> None: + """ + Skip the current episode and start a new one. + """ + self.stop_video_writers() + self.episode_buffer = self.create_episode_buffer() + self.video_writers = self.create_video_writer() + + # @note (k2): Code copied from LeRobotDataset.save_episode + # We override this function because we want to bypass lerobot's `compute_episode_stats` on video features + # since `compute_episode_stats` only works when images are written to disk. + def save_episode(self, episode_data: dict | None = None) -> None: + if not episode_data: + episode_buffer = self.episode_buffer + + validate_episode_buffer(episode_buffer, self.meta.total_episodes, self.features) + + # size and task are special cases that won't be added to hf_dataset + episode_length = episode_buffer.pop("size") + tasks = episode_buffer.pop("task") + episode_tasks = list(set(tasks)) + episode_index = episode_buffer["episode_index"] + + episode_buffer["index"] = np.arange( + self.meta.total_frames, self.meta.total_frames + episode_length + ) + episode_buffer["episode_index"] = np.full((episode_length,), episode_index) + + # Add new tasks to the tasks dictionary + for task in episode_tasks: + task_index = self.meta.get_task_index(task) + if task_index is None: + self.meta.add_task(task) + + # Given tasks in natural language, find their corresponding task indices + episode_buffer["task_index"] = np.array([self.meta.get_task_index(task) for task in tasks]) + + for key, ft in self.features.items(): + # index, episode_index, task_index are already processed above, and image and video + # are processed separately by storing image path and frame info as meta data + if key in ["index", "episode_index", "task_index"] or ft["dtype"] in ["image", "video"]: + continue + episode_buffer[key] = np.stack(episode_buffer[key]) + + self._wait_image_writer() + self._save_episode_table(episode_buffer, episode_index) + + # @note (k2): computing only non-video features stats + non_video_features = {k: v for k, v in self.features.items() if v["dtype"] not in ["video"]} + non_vid_ep_buffer = { + k: v for k, v in episode_buffer.items() if k in non_video_features.keys() + } + ep_stats = compute_episode_stats(non_vid_ep_buffer, non_video_features) + + if len(self.meta.video_keys) > 0: + video_paths = self.encode_episode_videos(episode_index) + for key in self.meta.video_keys: + episode_buffer[key] = video_paths[key] + + # `meta.save_episode` be executed after encoding the videos + self.meta.save_episode(episode_index, episode_length, episode_tasks, ep_stats) + + ep_data_index = get_episode_data_index(self.meta.episodes, [episode_index]) + ep_data_index_np = {k: t.numpy() for k, t in ep_data_index.items()} + check_timestamps_sync( + episode_buffer["timestamp"], + episode_buffer["episode_index"], + ep_data_index_np, + self.fps, + self.tolerance_s, + ) + + video_files = list(self.root.rglob("*.mp4")) + assert len(video_files) == self.num_episodes * len(self.meta.video_keys) + + parquet_files = list(self.root.rglob("*.parquet")) + assert len(parquet_files) == self.num_episodes + + # delete images + img_dir = self.root / "images" + if img_dir.is_dir(): + shutil.rmtree(self.root / "images") + + if not episode_data: # Reset the buffer and create new video writers + self.episode_buffer = self.create_episode_buffer() + self.video_writers = self.create_video_writer() + + # check if all video and parquet files exist + for key in self.meta.video_keys: + video_path = os.path.join(self.root, self.meta.get_video_file_path(episode_index, key)) + if not os.path.exists(video_path): + raise FileNotFoundError( + f"Video path: {video_path} does not exist for episode {episode_index}" + ) + + parquet_path = os.path.join(self.root, self.meta.get_data_file_path(episode_index)) + if not os.path.exists(parquet_path): + raise FileNotFoundError( + f"Parquet path: {parquet_path} does not exist for episode {episode_index}" + ) + + # @note (k2): Overriding LeRobotDataset.encode_episode_videos to use our own VideoWriter class + def encode_episode_videos(self, episode_index: int) -> dict: + video_paths = {} + for key in self.meta.video_keys: + video_paths[key] = self.video_writers[key].stop() + return video_paths + + def save_episode_as_discarded(self) -> None: + """ + Flag ongoing episode as discarded and save it to disk. Failed manipulations (grasp, manipulation) are + flagged as discarded. It will add the episode index to the discarded episode indices list in info.json. + """ + self.meta.info["discarded_episode_indices"] = self.meta.info.get( + "discarded_episode_indices", [] + ) + [self.episode_buffer["episode_index"]] + self.save_episode() + + +def hf_transform_to_torch_by_features( + features: datasets.Sequence, items_dict: dict[torch.Tensor | None] +): + """Get a transform function that convert items from Hugging Face dataset (pyarrow) + to torch tensors. Importantly, images are converted from PIL, which corresponds to + a channel last representation (h w c) of uint8 type, to a torch image representation + with channel first (c h w) of float32 type in range [0,1]. + """ + for key in items_dict: + first_item = items_dict[key][0] + if isinstance(first_item, PILImage.Image): + to_tensor = transforms.ToTensor() + items_dict[key] = [to_tensor(img) for img in items_dict[key]] + elif first_item is None: + pass + else: + if isinstance(features[key], datasets.Value): + dtype_str = features[key].dtype + elif isinstance(features[key], datasets.Sequence): + assert isinstance(features[key].feature, datasets.Value) + dtype_str = features[key].feature.dtype + else: + raise ValueError(f"Unsupported feature type for key '{key}': {features[key]}") + dtype_mapping = { + "float32": torch.float32, + "float64": torch.float64, + "int32": torch.int32, + "int64": torch.int64, + } + items_dict[key] = [ + torch.tensor(x, dtype=dtype_mapping[dtype_str]) for x in items_dict[key] + ] + return items_dict + + +# This is a subclass of LeRobotDataset that only fixes the data type when loading +# By default, LeRobotDataset will automatically convert float64 to float32 +class TypedLeRobotDataset(LeRobotDataset): + def __init__(self, load_video=True, *args, **kwargs): + super().__init__(*args, **kwargs) + if not load_video: + video_keys = [] + for key in self.meta.features.keys(): + if self.meta.features[key]["dtype"] == "video": + video_keys.append(key) + for key in video_keys: + self.meta.features.pop(key) + + def load_hf_dataset(self) -> datasets.Dataset: + """hf_dataset contains all the observations, states, actions, rewards, etc.""" + if self.episodes is None: + path = str(self.root / "data") + hf_dataset = load_dataset("parquet", data_dir=path, split="train") + else: + files = [ + str(self.root / self.meta.get_data_file_path(ep_idx)) for ep_idx in self.episodes + ] + hf_dataset = load_dataset("parquet", data_files=files, split="train") + + # TODO(aliberts): hf_dataset.set_format("torch") + hf_dataset.set_transform(partial(hf_transform_to_torch_by_features, hf_dataset.features)) + return hf_dataset diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..04874bd2759566f61645c0e7799e576ad64c5ca7 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/utils.py @@ -0,0 +1,156 @@ +from decoupled_wbc.control.robot_model.robot_model import RobotModel +from decoupled_wbc.data.constants import RS_VIEW_CAMERA_HEIGHT, RS_VIEW_CAMERA_WIDTH + + +def get_modality_config(robot_model: RobotModel, add_stereo_camera: bool = False) -> dict: + """ + Get the modality config for the robot model. + """ + left_hand_indices = sorted(robot_model.get_joint_group_indices("left_hand")) + right_hand_indices = sorted(robot_model.get_joint_group_indices("right_hand")) + left_arm_indices = sorted(robot_model.get_joint_group_indices("left_arm")) + right_arm_indices = sorted(robot_model.get_joint_group_indices("right_arm")) + waist_indices = sorted(robot_model.get_joint_group_indices("waist")) + left_leg_indices = sorted(robot_model.get_joint_group_indices("left_leg")) + right_leg_indices = sorted(robot_model.get_joint_group_indices("right_leg")) + + modality_config = { + "state": { + "left_leg": {"start": left_leg_indices[0], "end": left_leg_indices[-1] + 1}, + "right_leg": {"start": right_leg_indices[0], "end": right_leg_indices[-1] + 1}, + "waist": {"start": waist_indices[0], "end": waist_indices[-1] + 1}, + "left_arm": {"start": left_arm_indices[0], "end": left_arm_indices[-1] + 1}, + "left_hand": {"start": left_hand_indices[0], "end": left_hand_indices[-1] + 1}, + "right_arm": {"start": right_arm_indices[0], "end": right_arm_indices[-1] + 1}, + "right_hand": {"start": right_hand_indices[0], "end": right_hand_indices[-1] + 1}, + "left_wrist_pos": {"start": 0, "end": 3, "original_key": "observation.eef_state"}, + "left_wrist_abs_quat": { + "start": 3, + "end": 7, + "original_key": "observation.eef_state", + "rotation_type": "quaternion", + }, + "right_wrist_pos": {"start": 7, "end": 10, "original_key": "observation.eef_state"}, + "right_wrist_abs_quat": { + "start": 10, + "end": 14, + "original_key": "observation.eef_state", + "rotation_type": "quaternion", + }, + }, + "action": { + "left_leg": {"start": left_leg_indices[0], "end": left_leg_indices[-1] + 1}, + "right_leg": {"start": right_leg_indices[0], "end": right_leg_indices[-1] + 1}, + "waist": {"start": waist_indices[0], "end": waist_indices[-1] + 1}, + "left_arm": {"start": left_arm_indices[0], "end": left_arm_indices[-1] + 1}, + "left_hand": {"start": left_hand_indices[0], "end": left_hand_indices[-1] + 1}, + "right_arm": {"start": right_arm_indices[0], "end": right_arm_indices[-1] + 1}, + "right_hand": {"start": right_hand_indices[0], "end": right_hand_indices[-1] + 1}, + "left_wrist_pos": {"start": 0, "end": 3, "original_key": "action.eef"}, + "left_wrist_abs_quat": { + "start": 3, + "end": 7, + "original_key": "action.eef", + "rotation_type": "quaternion", + }, + "right_wrist_pos": {"start": 7, "end": 10, "original_key": "action.eef"}, + "right_wrist_abs_quat": { + "start": 10, + "end": 14, + "original_key": "action.eef", + "rotation_type": "quaternion", + }, + "base_height_command": { + "start": 0, + "end": 1, + "original_key": "teleop.base_height_command", + }, + "navigate_command": {"start": 0, "end": 3, "original_key": "teleop.navigate_command"}, + }, + "video": {"ego_view": {"original_key": "observation.images.ego_view"}}, + "annotation": {"human.task_description": {"original_key": "task_index"}}, + } + if add_stereo_camera: + modality_config["video"].update( + { + "ego_view_left_mono": {"original_key": "observation.images.ego_view_left_mono"}, + "ego_view_right_mono": {"original_key": "observation.images.ego_view_right_mono"}, + } + ) + + return modality_config + + +def get_dataset_features(robot_model: RobotModel, add_stereo_camera: bool = False) -> dict: + """ + Get the dataset features for the robot model. + """ + dataset_features = { + "observation.images.ego_view": { + "dtype": "video", + "shape": [RS_VIEW_CAMERA_HEIGHT, RS_VIEW_CAMERA_WIDTH, 3], + "names": ["height", "width", "channel"], + }, + "observation.state": { + "dtype": "float64", + "shape": (robot_model.num_joints,), + "names": robot_model.joint_names, + }, + "observation.eef_state": { + "dtype": "float64", + "shape": (14,), + "names": [ + "left_wrist_pos", + "left_wrist_abs_quat", + "right_wrist_pos", + "right_wrist_abs_quat", + ], + }, + "action": { + "dtype": "float64", + "shape": (robot_model.num_joints,), + "names": robot_model.joint_names, + }, + "action.eef": { + "dtype": "float64", + "shape": (14,), + "names": [ + "left_wrist_pos", + "left_wrist_abs_quat", + "right_wrist_pos", + "right_wrist_abs_quat", + ], + }, + "observation.img_state_delta": { + "dtype": "float32", + "shape": (1,), + "names": "img_state_delta", + }, + "teleop.navigate_command": { + "dtype": "float64", + "shape": (3,), + "names": ["lin_vel_x", "lin_vel_y", "ang_vel_z"], + }, + "teleop.base_height_command": { + "dtype": "float64", + "shape": (1,), + "names": "base_height_command", + }, + } + if add_stereo_camera: + dataset_features.update( + { + "observation.images.ego_view_left_mono": { + "dtype": "video", + "shape": [RS_VIEW_CAMERA_HEIGHT, RS_VIEW_CAMERA_WIDTH, 3], + "names": ["height", "width", "channel"], + }, + "observation.images.ego_view_right_mono": { + "dtype": "video", + "shape": [RS_VIEW_CAMERA_HEIGHT, RS_VIEW_CAMERA_WIDTH, 3], + "names": ["height", "width", "channel"], + }, + } + ) + + return dataset_features diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/video_writer.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/video_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..a171c4e2191d8ff81aeb8258615edc4ec86fae9a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/video_writer.py @@ -0,0 +1,102 @@ +import os +import queue +import sys +import threading +import time + +import av +import numpy as np + + +class VideoWriter: + def __init__( + self, + output_path: str, + width: int, + height: int, + fps: float, + codec: str = "h264", + buffer_size: int = 50, + ): + self.output_path = output_path + self._first_frame = True # Track first frame to suppress x264 info output + + # Create output directory if it doesn't exist + output_dir = os.path.dirname(output_path) + if output_dir and not os.path.exists(output_dir): + os.makedirs(output_dir, exist_ok=True) + + self.queue = queue.Queue(maxsize=buffer_size) + self.container = av.open(output_path, mode="w") + self.stream = self.container.add_stream(codec, rate=fps) + self.stream.width = width + self.stream.height = height + thread = threading.Thread(target=self._writer_worker, daemon=True) + thread.start() + + def _assert_dimensions(self, frame: np.ndarray) -> None: + assert ( + frame.shape[1] == self.stream.width and frame.shape[0] == self.stream.height + ), f"""Incorrect frame dimensions. Input dimensions: {frame.shape[1]}x{frame.shape[0]}. + Expected dimensions: {self.stream.width}x{self.stream.height}""" + + def add_frame(self, frame: np.ndarray) -> None: + self._assert_dimensions(frame) + self.queue.put(frame) + + def _writer_worker(self) -> None: + while True: + frame = self.queue.get() + if frame is None: + continue + self._assert_dimensions(frame) + frame = av.VideoFrame.from_ndarray(frame, format="rgb24") + + # Suppress stderr for first frame encoding (x264 prints info then) + if self._first_frame: + stderr_fd = sys.stderr.fileno() + old_stderr = os.dup(stderr_fd) + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, stderr_fd) + try: + packets = self.stream.encode(frame) + for packet in packets: + self.container.mux(packet) + finally: + os.dup2(old_stderr, stderr_fd) + os.close(old_stderr) + os.close(devnull) + self._first_frame = False + else: + packets = self.stream.encode(frame) + for packet in packets: + self.container.mux(packet) + + def _flush_stream(self) -> None: + packets = self.stream.encode() + for packet in packets: + self.container.mux(packet) + + def stop(self) -> str: + """ + Blocking call. Waits until all the frames in the queue have been written to the file + and the video writer has been closed. + """ + if not self.queue.empty(): + print("Waiting for video writer queue to empty...") + while not self.queue.empty(): + time.sleep(0.1) + + print("Video writer queue is empty, flushing stream...") + self._flush_stream() + self.container.close() + return self.output_path + + def cancel(self) -> None: + """Immediately stops writing and deletes the output file""" + if os.path.exists(self.output_path): + os.remove(self.output_path) + self.container.close() + + def __del__(self) -> None: + self.container.close() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/viz/rerun_viz.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/viz/rerun_viz.py new file mode 100644 index 0000000000000000000000000000000000000000..c649640db30e7d428e44d5c76aec0cb60627a161 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/data/viz/rerun_viz.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Rerun visualization utilities for plotting data and images.""" + +from __future__ import annotations + +import argparse +import time +from typing import Dict, List, Optional + +import cv2 +import numpy as np +import rerun as rr # pip install rerun-sdk +import rerun.blueprint as rrb + + +class RerunViz: + """Class for visualizing data using Rerun.""" + + def __init__( + self, + image_keys: List[str], + tensor_keys: List[str], + app_name: str = "rerun_visualization", + memory_limit: str = "1GB", + window_size: float = 5.0, + port: int = 9876, + in_docker: bool = False, + ): + """Initialize the RerunViz class. + Args: + app_name: Name of the Rerun application + memory_limit: Memory limit for Rerun + window_size: Size of the time window in seconds + image_keys: List of image keys to plot + tensor_keys: List of tensor keys to plot + in_docker: Whether running inside Docker container. If in docker, + forward data to outside of the container to be rendered. + Use `rerun --port 9876` to visualize. Expecting rerun-cli 0.22.1 outside of docker. + Tested with rerun-sdk 0.21.0 inside docker. + """ + self.app_name = app_name + self.memory_limit = memory_limit + self.window_size = window_size + self.tensor_keys = tensor_keys + self.image_keys = image_keys + self.port = port + self.in_docker = in_docker + # Initialize Rerun + self._initialize_rerun() + + def _initialize_rerun(self): + """Initialize Rerun and set up the blueprint.""" + rr.init(self.app_name) + if not self.in_docker: + # support for web visualization + rr.spawn(memory_limit=self.memory_limit, port=self.port, connect=True) + else: + # forward data to outside of the docker container + rr.connect(f"127.0.0.1:{self.port}") + self._create_blueprint() + + def _create_blueprint(self): + # Create a grid of plots + contents = [] + + # Add time series plots + for tensor_key in self.tensor_keys: + contents.append( + rrb.TimeSeriesView( + origin=tensor_key, + time_ranges=[ + rrb.VisibleTimeRange( + "time", + start=rrb.TimeRangeBoundary.cursor_relative(seconds=-self.window_size), + end=rrb.TimeRangeBoundary.cursor_relative(), + ) + ], + ) + ) + + # Add image views + for image_key in self.image_keys: + contents.append(rrb.Spatial2DView(origin=image_key, name=image_key)) + + # Send the blueprint with collapsed panels to hide side/bottom bars + rr.send_blueprint(rrb.Blueprint(rrb.Grid(contents=contents), collapse_panels=True)) + + def set_rerun_keys(self, image_keys: List[str], tensor_keys: List[str]): + """Set the Rerun keys.""" + self.image_keys = image_keys + self.tensor_keys = tensor_keys + self._create_blueprint() + + def plot_images(self, images: Dict[str, np.ndarray], timestamp: Optional[float] = None): + """Plot image data. + + Args: + images: Dictionary mapping image names to image data + timestamp: Timestamp for the data (if None, uses current time) + """ + if timestamp is None: + timestamp = time.time() + + rr.set_time_seconds("time", timestamp) + + for key, image in images.items(): + if image is None: + continue + + if "depth" in key: + # Color jet + depth_colormap = cv2.applyColorMap( + cv2.convertScaleAbs(image, alpha=0.03), cv2.COLORMAP_JET + ) + rr.log(f"{key}", rr.Image(depth_colormap)) + else: + # Convert to RGB + # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + rr.log(f"{key}", rr.Image(image)) + + def plot_tensors( + self, data: Optional[Dict[str, np.ndarray]] = None, timestamp: Optional[float] = None + ): + """Plot tensor data. + + Args: + data: Dictionary mapping keys to tensor values + timestamp: Timestamp for the data (if None, uses current time) + """ + if timestamp is None: + timestamp = time.time() + + rr.set_time_seconds("time", timestamp) + + # If no data provided, use random walk generators + for tensor_key in self.tensor_keys: + for i in range(data[tensor_key].shape[0]): + rr.log(f"{tensor_key}/{i}", rr.Scalar(data[tensor_key][i])) + + def close(self): + """Close the RerunViz instance.""" + rr.rerun_shutdown() + + +if __name__ == "__main__": + """Main function to demonstrate the RerunViz class.""" + parser = argparse.ArgumentParser(description="Plot dashboard stress test") + parser.add_argument( + "--freq", type=float, default=20, help="Frequency of logging (applies to all series)" + ) + parser.add_argument( + "--window-size", type=float, default=5.0, help="Size of the window in seconds" + ) + parser.add_argument("--duration", type=float, default=60, help="How long to log for in seconds") + parser.add_argument("--use-rs", action="store_true", help="Use RealSense sensor") + parser.add_argument("--use-zed", action="store_true", help="Use ZED sensor") + parser.add_argument("--in-docker", action="store_true", help="Running inside Docker container") + args = parser.parse_args() + + if args.use_rs: + image_keys = ["color_image", "depth_image"] + from decoupled_wbc.control.sensor.realsense import RealSenseClientSensor + + sensor = RealSenseClientSensor() + elif args.use_zed: + image_keys = ["left_image", "right_image"] + from decoupled_wbc.control.sensor.zed import ZEDClientSensor + + sensor = ZEDClientSensor() + else: + from decoupled_wbc.control.sensor.dummy import DummySensor + + sensor = DummySensor() + image_keys = ["color_image"] + + tensor_keys = ["left_arm_qpos", "left_hand_qpos", "right_arm_qpos", "right_hand_qpos"] + + # Initialize the RerunViz class + viz = RerunViz( + image_keys=image_keys, + tensor_keys=tensor_keys, + window_size=args.window_size, + in_docker=args.in_docker, + ) + + # Run the visualization loop + cur_time = time.time() + end_time = cur_time + args.duration + time_per_tick = 1.0 / args.freq + + while cur_time < end_time: + # Advance time and sleep if necessary + cur_time += time_per_tick + sleep_for = cur_time - time.time() + if sleep_for > 0: + time.sleep(sleep_for) + + if sleep_for < -0.1: + print(f"Warning: missed logging window by {-sleep_for:.2f} seconds") + + # Plot dummy tensor + dummy_tensor = np.random.randn(5) + dummy_tensor_dict = {key: dummy_tensor for key in tensor_keys} + + viz.plot_tensors(dummy_tensor_dict, cur_time) + + # Plot images if available + images = sensor.read() + if images is not None: + img_to_show = {key: images[key] for key in image_keys} + viz.plot_images(img_to_show, cur_time) + + rr.script_teardown(args) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/requirements.txt b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d6e1198b1ab1f5a7f19c6f1fc2ba7338438cf718 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/requirements.txt @@ -0,0 +1 @@ +-e . diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eab921c1988c976d1e8b65096001d0bab61a5fb7 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/__init__.py @@ -0,0 +1,79 @@ +from robocasa.environments.locomanipulation.base import ( + PnPBottle, + PickBottleShelf, + PnPBottleHigh, + NavPickBottle, + PnPBottleRandRobotPose, + VisualReach, + PnPBottleFixtureToFixture, + PnPBottleFixtureToFixtureSourceDemo, + PnPBottleShelfToTable, + PnPBottleTableToTable, + PickBottleGround, + PickBottles, + NavPickBottles, + PnPBottlesTableToTable, +) +from robocasa.environments.locomanipulation.locomanip_basic import ( + LMPickBottle, + LMPickBottleHigh, + LMNavPickBottle, + LMPickBottleGround, + LMPnPBottle, + LMPickMultipleBottles, + LMPnPMultipleBottles, + LMPickBottleShelf, + LMNavPickBottleShelf, + LMPickBottleShelfLow, + LMNavPickBottleShelfLow, + LMPnPBottleToPlate, + LMPnPAppleToPlate, +) +from robocasa.environments.locomanipulation.locomanip_pnp import ( + LMBottlePnP, + LMBoxPnP, +) + +from robocasa.environments.locomanipulation.locomanip_dc import ( + LMNavPickBottleDC, + LMPnPAppleToPlateDC, +) + +# from robosuite.controllers import ALL_CONTROLLERS, load_controller_config +from robosuite.controllers import ALL_PART_CONTROLLERS, load_composite_controller_config +from robosuite.environments import ALL_ENVIRONMENTS +from robosuite.models.grippers import ALL_GRIPPERS +from robosuite.robots import ALL_ROBOTS + + +import mujoco + +assert ( + mujoco.__version__ == "3.2.6" or mujoco.__version__ == "3.3.2" +), "MuJoCo version must be 3.2.6 or 3.3.2. Please install the correct version." + +import numpy + +assert numpy.__version__ in [ + "1.23.2", + "1.23.3", + "1.23.5", + "1.26.4", + "2.2.5", + "2.2.6", +], "numpy version must be either 1.23.{2,3,5}, 1.26.4 or 2.2.{5,6}. Please install one of these versions." + +import robosuite + +assert robosuite.__version__ in [ + "1.5.0", + "1.5.1", +], "robosuite version must be 1.5.{0,1}. Please install the correct version" + +__version__ = "0.2.0" +__logo__ = """ + ; / ,--. + ["] ["] ,< |__**| + /[_]\ [~]\/ |// | + ] [ OOO /o|__| +""" diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf2e332bd8a434b7e77e8fa5d3f2699ff57d2719 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/__init__.py @@ -0,0 +1,13 @@ +""" +Full list of loco-manipulation tasks. + +GroundOnly - ground only environments + +locomanip_pnp - factory environments, pick and place tasks: +LMBottlePnP +LMBoxPnP +""" + +from .base import REGISTERED_LOCOMANIPULATION_ENVS + +ALL_LOCOMANIPULATION_ENVIRONMENTS = REGISTERED_LOCOMANIPULATION_ENVS.keys() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/base.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/base.py new file mode 100644 index 0000000000000000000000000000000000000000..fde74e9d7324dfb625d9848957a4eb7e27f29226 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/base.py @@ -0,0 +1,1658 @@ +from copy import deepcopy +import os +from typing import Optional, Type +import warnings +import xml.etree.ElementTree as ET + +import mujoco +import numpy as np +import robosuite +from robosuite.environments.base import EnvMeta +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.models.arenas import Arena +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.mjcf_utils import array_to_string, find_elements, xml_path_completion +from robosuite.utils.observables import Observable, sensor + +import robocasa +from robocasa.models.objects.objects import MJCFObject +from robocasa.models.scenes import GroundArena +import robocasa.utils.camera_utils as CamUtils +from robocasa.utils.dexmg_utils import DexMGConfigHelper +from robocasa.utils.object_utils import check_obj_upright +from robocasa.utils.visuals_utls import Gradient, randomize_materials_rgba + +REGISTERED_LOCOMANIPULATION_ENVS = {} + + +def register_locomanipulation_env(target_class): + REGISTERED_LOCOMANIPULATION_ENVS[target_class.__name__] = target_class + + +class LocoManipulationEnvMeta(EnvMeta): + """Metaclass for registering robocasa environments""" + + def __new__(meta, name, bases, class_dict): + cls = super().__new__(meta, name, bases, class_dict) + register_locomanipulation_env(cls) + return cls + + +class CameraPoseRandomizer: + @staticmethod + def randomize_cameras( + env: "LocoManipulationEnv", + cam_names: list[str], + pos_range: tuple[np.ndarray, np.ndarray], + euler_range: tuple[np.ndarray, np.ndarray], + ): + """ + Randomize camera poses while maintaining their relative transforms. + + Args: + env: The environment instance + cam_names: List of camera names to randomize together + pos_range: Tuple of (min_pos, max_pos) as 3D arrays for position randomization + euler_range: Tuple of (min_euler, max_euler) as 3D arrays for euler angle randomization (in radians) + """ + if len(cam_names) == 0: + return + + # Sample random transform offset + random_pos_offset = env.rng.uniform(pos_range[0], pos_range[1]) + random_euler_offset = env.rng.uniform(euler_range[0], euler_range[1]) + + # Convert euler offset to quaternion + quat_offset = np.zeros(4, dtype=float) + mujoco.mju_euler2Quat(quat_offset, random_euler_offset, "xyz") + + # Apply the same transform to all specified cameras + for cam_name in cam_names: + if cam_name not in env._cam_configs: + warnings.warn(f"Camera {cam_name} not found in camera configs. Skipping.") + continue + + cam_config = env._cam_configs[cam_name] + + # Get original position and quaternion + original_pos = np.array(cam_config["pos"], dtype=float) + original_quat = np.array(cam_config["quat"], dtype=float) + + # Apply rotation offset to position (rotate position offset by the random rotation) + rotated_offset = np.zeros(3, dtype=float) + mujoco.mju_rotVecQuat(rotated_offset, random_pos_offset, original_quat) + new_pos = original_pos + rotated_offset + + # Compose quaternions: new_quat = quat_offset * original_quat + new_quat = np.zeros(4, dtype=float) + mujoco.mju_mulQuat(new_quat, quat_offset, original_quat) + + # Update camera config + cam_config["pos"] = new_pos.tolist() + cam_config["quat"] = new_quat.tolist() + + # Update in simulation if already created + if hasattr(env, "sim") and env.sim is not None: + try: + cam_id = env.sim.model.camera_name2id(cam_name) + env.sim.model.cam_pos[cam_id] = new_pos + env.sim.model.cam_quat[cam_id] = new_quat + except: + # Camera might not be in the model yet + pass + + +class RobotPoseRandomizer: + @staticmethod + def set_pose( + env: "LocoManipulationEnv", + x_range: [tuple[float, float]], + y_range: [tuple[float, float]], + yaw_range: [tuple[float, float]], + ): + new_x = env.rng.uniform(*x_range) + new_y = env.rng.uniform(*y_range) + new_yaw = env.rng.uniform(*yaw_range) + + if env.robots[0].name == "G1": + base_offset = env.ROBOT_POS_OFFSETS[env.robots[0].robot_model.__class__.__name__] + target_pos = np.array([new_x, new_y, base_offset[2]], dtype=float) + quat = np.zeros(4, dtype=float) + mujoco.mju_euler2Quat(quat, np.array([0.0, 0.0, new_yaw]), "xyz") + base_freejoint = f"{env.robots[0].robot_model.naming_prefix}base" + if base_freejoint in env.sim.model.joint_names: + env.sim.data.set_joint_qpos(base_freejoint, np.concatenate([target_pos, quat])) + else: + warnings.warn(f"Base joint {base_freejoint} not found in the model.") + else: + base_joint_pos = np.array([new_x, new_y, new_yaw]) + base_joint_names = [ + "mobilebase0_joint_mobile_forward", + "mobilebase0_joint_mobile_side", + "mobilebase0_joint_mobile_yaw", + ] + for i, base_joint_name in enumerate(base_joint_names): + if base_joint_name not in env.sim.model.joint_names: + warnings.warn( + f"Base joint {base_joint_name} not found in the model. " + f"Skipping randomization of {base_joint_name}." + ) + else: + env.sim.data.set_joint_qpos(base_joint_name, base_joint_pos[i]) + + @staticmethod + def set_arm(env: ManipulationEnv, elbow_qpos: float, shoulder_pitch_qpos: float): + """Helper function to reinitialize G1 robot arm configuration.""" + robot = env.robots[0] + if "G1" not in robot.name: + # avoid reinitializing arm configuration for non-G1 robots + return + + joint_names = robot.robot_joints + joint_pos_indices = robot._ref_joint_pos_indexes + for joint_name, pos_idx in zip(joint_names, joint_pos_indices): + if "elbow" in joint_name: + print(f"reinitializing G1 {joint_name} with idx {pos_idx} to {elbow_qpos}") + env.sim.data.qpos[pos_idx] = elbow_qpos + elif "shoulder_pitch" in joint_name: + print(f"reinitializing G1 {joint_name} with idx {pos_idx} to {shoulder_pitch_qpos}") + env.sim.data.qpos[pos_idx] = shoulder_pitch_qpos + + +class LocoManipulationEnv(ManipulationEnv, metaclass=LocoManipulationEnvMeta): + """ + Initialized a Base Ground Standing environment. + """ + + MUJOCO_ARENA_CLS: Type[Arena] = GroundArena + + ROBOT_POS_OFFSETS: dict[str, list[float]] = { + "PandaOmron": [0, 0, 0], + "GR1FloatingBody": [0, 0, 0.97], + "GR1": [0, 0, 0.97], + "GR1FixedLowerBody": [0, 0, 0.97], + "GR1FixedLowerBodyInspireHands": [0, 0, 0.97], + "GR1FixedLowerBodyFourierHands": [0, 0, 0.97], + "GR1ArmsOnly": [0, 0, 0.97], + "GR1ArmsOnlyInspireHands": [0, 0, 0.97], + "GR1ArmsOnlyFourierHands": [0, 0, 0.97], + "GR1ArmsAndWaistFourierHands": [0, 0, 0.97], + "G1": [0, 0, 0.793], + "G1FixedBase": [0, 0, 0.793], + "G1FixedLowerBody": [0, 0, 0.793], + "G1ArmsOnly": [0, 0, 0.793], + "G1ArmsOnlyFloating": [0, 0, 0.793], + "G1FloatingBody": [0, 0, 0.793], + "G1FloatingBodyWithVertical": [0, 0, 0.793], + } + + def __init__( + self, + translucent_robot: bool = False, + use_object_obs: bool = False, + randomize_cameras: bool = False, + *args, + **kwargs, + ): + self.mujoco_objects = [] + self.randomize_cameras = randomize_cameras + + super().__init__( + *args, + **kwargs, + ) + + self.translucent_robot = translucent_robot + + def _load_model(self): + super()._load_model() + + self.mujoco_arena = self.MUJOCO_ARENA_CLS() + self.mujoco_arena.set_origin([0, 0, 0]) + self.set_cameras() + + self.model = ManipulationTask( + mujoco_arena=self.mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=self.mujoco_objects, + ) + + robot_base_pos = self.ROBOT_POS_OFFSETS[self.robots[0].robot_model.__class__.__name__] + robot_model = self.robots[0].robot_model + robot_model.set_base_xpos(robot_base_pos) + # robot_model.set_base_ori(robot_base_ori) + + def set_cameras(self): + """ + Adds new tabletop-relevant cameras to the environment. Will randomize cameras if specified. + """ + + self._cam_configs = deepcopy(CamUtils.CAM_CONFIGS) + + for robot in self.robots: + if hasattr(robot.robot_model, "get_camera_configs"): + self._cam_configs.update(robot.robot_model.get_camera_configs()) + + 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"], + camera_attribs=cam_cfg.get("camera_attribs", None), + ) + + self.mujoco_arena.set_camera( + camera_name="egoview", + pos=[0.078, 0, 1.308], + quat=[0.66491268, 0.24112495, -0.24112507, -0.66453637], + camera_attribs=dict(fovy="90"), + ) + + def visualize(self, vis_settings): + """ + In addition to super call, make the robot semi-transparent + + 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) + + visual_geom_names = [] + + for robot in self.robots: + robot_model = robot.robot_model + visual_geom_names += robot_model.visual_geoms + + for name in visual_geom_names: + rgba = self.sim.model.geom_rgba[self.sim.model.geom_name2id(name)] + if self.translucent_robot: + rgba[-1] = 0.10 + else: + rgba[-1] = 1.0 + + def reward(self, action=None): + """ + Reward function for the task. The reward function is based on the task + and to be implemented in the subclasses. Returns 0 by default. + + Returns: + float: Reward for the task + """ + reward = 0 + if self._check_success(): + reward = 1.0 + return reward + + def _check_success(self): + """ + Checks if the task has been successfully completed. + Success condition is based on the task and to be implemented in the + subclasses. Returns False by default. + + Returns: + bool: True if the task is successfully completed, False otherwise + """ + return False + + def edit_model_xml(self, xml_str): + """ + This function postprocesses the model.xml collected from a MuJoCo demonstration + for retrospective model changes. + + Args: + xml_str (str): Mujoco sim demonstration XML file as string + + Returns: + str: Post-processed xml file as string + """ + xml_str = super().edit_model_xml(xml_str) + + tree = ET.fromstring(xml_str) + root = tree + worldbody = root.find("worldbody") + actuator = root.find("actuator") + asset = root.find("asset") + meshes = asset.findall("mesh") + textures = asset.findall("texture") + all_elements = meshes + textures + + robosuite_path_split = os.path.split(robosuite.__file__)[0].split("/") + robocasa_path_split = os.path.split(robocasa.__file__)[0].split("/") + + # replace robocasa-specific asset paths + 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 + if "models/assets" in old_path: + if "/robosuite/" in old_path: + check_lst = [ + loc for loc, val in enumerate(old_path_split) if val == "robosuite" + ] + ind = max(check_lst) # last occurrence index + new_path_split = robosuite_path_split + old_path_split[ind + 1 :] + elif "/robocasa/" in old_path: + check_lst = [loc for loc, val in enumerate(old_path_split) if val == "robocasa"] + ind = max(check_lst) # last occurrence index + new_path_split = robocasa_path_split + old_path_split[ind + 1 :] + else: + raise ValueError + + new_path = "/".join(new_path_split) + elem.set("file", new_path) + + # set cameras + for cam_name, cam_config in self._cam_configs.items(): + parent_body = cam_config.get("parent_body", None) + + cam_root = worldbody + if parent_body is not None: + cam_root = find_elements(root=worldbody, tags="body", attribs={"name": parent_body}) + if cam_root is None: + # camera config refers to body that doesnt exist on the robot + continue + + cam = find_elements(root=cam_root, tags="camera", attribs={"name": cam_name}) + + if cam is None: + old_cam = find_elements(root=worldbody, tags="camera", attribs={"name": cam_name}) + if old_cam is not None: + # old camera associated with different body + continue + + cam = ET.Element("camera") + cam.set("mode", "fixed") + cam.set("name", cam_name) + cam_root.append(cam) + + cam.set("pos", array_to_string(cam_config["pos"])) + cam.set("quat", array_to_string(cam_config["quat"])) + for k, v in cam_config.get("camera_attribs", {}).items(): + cam.set(k, v) + + # replace base -> mobilebase (this is needed for old PandaOmron demos) + for elem in find_elements( + root=worldbody, tags=["geom", "site", "body", "joint"], return_first=False + ): + if elem.get("name") is None: + continue + if elem.get("name").startswith("base0_"): + old_name = elem.get("name") + new_name = "mobilebase0_" + old_name[6:] + elem.set("name", new_name) + for elem in find_elements( + root=actuator, + tags=["velocity", "position", "motor", "general"], + return_first=False, + ): + if elem.get("name") is None: + continue + if elem.get("name").startswith("base0_"): + old_name = elem.get("name") + new_name = "mobilebase0_" + old_name[6:] + elem.set("name", new_name) + for elem in find_elements( + root=actuator, + tags=["velocity", "position", "motor", "general"], + return_first=False, + ): + if elem.get("joint") is None: + continue + if elem.get("joint").startswith("base0_"): + old_joint = elem.get("joint") + new_joint = "mobilebase0_" + old_joint[6:] + elem.set("joint", new_joint) + + # result = ET.tostring(root, encoding="utf8").decode("utf8") + result = ET.tostring(root).decode("utf8") + + # # replace with generative textures + # if (self.generative_textures is not None) and ( + # self.generative_textures is not False + # ): + # # sample textures + # assert self.generative_textures == "100p" + # self._curr_gen_fixtures = get_random_textures(self.rng) + + # cab_tex = self._curr_gen_fixtures["cab_tex"] + # counter_tex = self._curr_gen_fixtures["counter_tex"] + # wall_tex = self._curr_gen_fixtures["wall_tex"] + # floor_tex = self._curr_gen_fixtures["floor_tex"] + + # result = replace_cab_textures( + # self.rng, result, new_cab_texture_file=cab_tex + # ) + # result = replace_counter_top_texture( + # self.rng, result, new_counter_top_texture_file=counter_tex + # ) + # result = replace_wall_texture( + # self.rng, result, new_wall_texture_file=wall_tex + # ) + # result = replace_floor_texture( + # self.rng, result, new_floor_texture_file=floor_tex + # ) + + return result + + def _setup_references(self): + super()._setup_references() + + self.obj_body_id = {} + + def _randomize_robot_cameras(self): + """Randomize the poses of robot-mounted cameras while preserving their relative transforms.""" + cam_names = ["robot0_oak_egoview", "robot0_oak_left_monoview", "robot0_oak_right_monoview"] + + # Define randomization ranges + pos_range = ( + np.array([-0.02, -0.02, -0.02]), # min position offset [x, y, z] in meters + np.array([0.02, 0.02, 0.02]), # max position offset [x, y, z] in meters + ) + euler_range = ( + np.array([-0.1, -0.1, -0.1]), # min euler angles [roll, pitch, yaw] in radians + np.array([0.1, 0.1, 0.1]), # max euler angles [roll, pitch, yaw] in radians + ) + + CameraPoseRandomizer.randomize_cameras( + env=self, cam_names=cam_names, pos_range=pos_range, euler_range=euler_range + ) + + def _reset_internal(self): + super()._reset_internal() + + if self.randomize_cameras: + self._randomize_robot_cameras() + + def _reset_observables(self): + if self.hard_reset: + self._observables = self._setup_observables() + + # these sensors need a lot of computation, so we disable them by default for speed up simulation + disabled_sensors = [ + "base_to_left_eef_pos", + "base_to_left_eef_quat", + "base_to_left_eef_quat_site", + "base_to_right_eef_pos", + "base_to_right_eef_quat", + "base_to_right_eef_quat_site", + ] + for name in disabled_sensors: + for robot in self.robots: + robot_name_prefix = robot.robot_model.naming_prefix + if f"{robot_name_prefix}{name}" in self._observables: + self._observables[f"{robot_name_prefix}{name}"].set_enabled(False) + self._observables[f"{robot_name_prefix}{name}"].set_active(False) + + def get_state(self): + return {"states": self.sim.get_state().flatten()} + + +class GroundOnly(LocoManipulationEnv): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +class PrimitiveBottle: + DEFAULT_RGB = [0.3, 0.7, 0.8] + + def __init__( + self, + name="bottle", + radius: float = 0.03, + half_height: float = 0.075, + rgb: Optional[list[float]] = None, + ): + self.name = name + self.assets = [ + ET.Element( + "texture", + type="2d", + name=f"{name}_tex", + builtin="flat", + rgb1=" ".join(map(str, self.DEFAULT_RGB if rgb is None else rgb)), + width="512", + height="512", + ), + ET.Element( + "material", + name=f"{name}_mat", + texture=f"{name}_tex", + texuniform="true", + reflectance="0.1", + ), + ] + + self.body = ET.Element("body", name=f"{self.name}_body", pos="0.35 0 0.8") + bottle_vis_geom = ET.Element( + "geom", + name=f"{name}_vis", + pos="0 0 0", + size=f"{radius} {half_height}", + type="cylinder", + material=f"{name}_mat", + group="1", + conaffinity="0", + contype="0", + ) + self.body.append(bottle_vis_geom) + + # Cylinder collider approximation for stable contacts + self.contact_geoms = [] + n_sides = 3 + half_width = radius * np.tan(np.pi / n_sides / 2) + for i in range(n_sides): + coll_name = f"{self.name}_collider_{i}" + angle = np.pi / n_sides * i + quat = np.zeros(4) + euler = np.array([0, 0, angle]) + mujoco.mju_euler2Quat(quat, euler, "xyz") + box_geom = ET.Element( + "geom", + name=coll_name, + type="box", + pos="0 0 0", + size=f"{radius} {half_width} {half_height}", + quat=" ".join(map(str, quat)), + solimp="0.998 0.998 0.001", + solref="0.001 2", + density="100", + friction="0.95 0.3 0.1", + ) + self.body.append(box_geom) + self.contact_geoms.append(coll_name) + + bottle_joint = ET.Element( + "joint", + name=f"{self.name}_joint", + type="free", + damping="0.0005", + ) + self.body.append(bottle_joint) + + +class PrimitiveFixture: + DEFAULT_RGB = [0.8, 0.8, 0.8] + + def __init__( + self, + name: str, + pos: np.ndarray = np.array([0.0, 0.0, 0.8]), + half_size: np.ndarray = np.array([0.1, 0.1, 0.001]), + rgb: Optional[str] = None, + ): + """ + A simple primitive fixture as a flat box. + + Args: + half_size: Half-sizes in [x, y, z] directions. Default creates a 20cm x 20cm x 2mm box. + """ + self.half_size = half_size + + self.assets = [ + ET.Element( + "texture", + type="2d", + name=f"{name}", + builtin="flat", + rgb1=" ".join(map(str, self.DEFAULT_RGB if rgb is None else rgb)), + width="512", + height="512", + ), + ET.Element( + "material", + name=f"{name}", + texture=f"{name}", + texuniform="true", + reflectance="0.05", # Less reflective than bottle + ), + ] + + self.body = ET.Element("body", name=f"{name}_body", pos=array_to_string(pos)) + + # Visual geometry + fixture_vis_geom = ET.Element( + "geom", + name=f"{name}_vis", + pos="0 0 0", + size=f"{half_size[0]} {half_size[1]} {half_size[2]}", + type="box", + material=f"{name}", + group="1", + conaffinity="0", + contype="0", + ) + self.body.append(fixture_vis_geom) + + # Collision geometry - just a single box since it's already a simple shape + self.contact_geoms = [] + fixture_collider = ET.Element( + "geom", + name=f"{name}_collider", + type="box", + pos="0 0 0", + size=f"{half_size[0]} {half_size[1]} {half_size[2]}", + solimp="0.998 0.998 0.001", + solref="0.001 2", + density="100", + friction="0.6 0.01 0.001", # Similar to add_fixture_body friction + ) + self.body.append(fixture_collider) + self.contact_geoms.append("fixture_collider") + + +class PnPBottle(LocoManipulationEnv, DexMGConfigHelper): + TABLE_GRADIENT: Gradient = Gradient( + np.array([0.68, 0.34, 0.07, 1.0]), np.array([1.0, 1.0, 1.0, 1.0]) + ) + DEFAULT_BOTTLE_POS: np.ndarray = np.array([0.4, 0, 0.77]) + BOTTLE_POS_RANGE_X = (-0.08, 0.04) + BOTTLE_POS_RANGE_Y = (-0.08, 0.08) + + def __init__(self, *args, **kwargs): + self.objects = {} + super().__init__(*args, **kwargs) + + def _load_model(self): + self.mujoco_objects = [self._create_table("table_body", [0.5, 0, 0], [0, 0, np.pi / 2])] + + super()._load_model() + + self.bottle = self._create_bottle() + + @staticmethod + def _create_table(name: str, position: list[float], euler: list[float]) -> MJCFObject: + table = MJCFObject( + name=name, + mjcf_path=xml_path_completion( + "objects/omniverse/locomanip/lab_table/model.xml", root=robocasa.models.assets_root + ), + scale=1.0, + solimp=(0.998, 0.998, 0.001), + solref=(0.001, 1), + density=10, + friction=(1, 1, 1), + static=True, + ) + table.set_pos(position) + table.set_euler(euler) + return table + + def _create_bottle( + self, name: str = "bottle", rgb: Optional[list[float]] = None + ) -> PrimitiveBottle: + bottle = PrimitiveBottle(name=name, radius=0.03, half_height=0.075, rgb=rgb) + self.model.asset.extend(bottle.assets) + self.model.worldbody.append(bottle.body) + self.objects[name] = {"name": f"{name}_body"} + return bottle + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + if not self.deterministic_reset: + self._randomize_bottle_placement() + self._randomize_table_texture() + + def _randomize_bottle_placement( + self, name: str = "bottle", base_pos: Optional[np.ndarray] = None + ): + if not self.deterministic_reset: + bottle_joint = f"{name}_joint" + base_pos = self.DEFAULT_BOTTLE_POS if base_pos is None else base_pos + + random_x = self.rng.uniform(*self.BOTTLE_POS_RANGE_X) + random_y = self.rng.uniform(*self.BOTTLE_POS_RANGE_Y) + new_pos = base_pos + np.array([random_x, random_y, 0]) + + current_qpos = self.sim.data.get_joint_qpos(bottle_joint) + new_qpos = current_qpos.copy() + new_qpos[:3] = new_pos + + self.sim.data.set_joint_qpos(bottle_joint, new_qpos) + + def _randomize_table_texture(self): + table = self.mujoco_objects[0] + randomize_materials_rgba( + rng=self.rng, mjcf_obj=table, gradient=self.TABLE_GRADIENT, linear=True + ) + + def _setup_references(self): + super()._setup_references() + + self.obj_body_id = {} + for name, model in self.objects.items(): + self.obj_body_id[name] = self.sim.model.body_name2id(model["name"]) + + def _check_success(self): + check_grasp = self._check_grasp(self.robots[0].gripper["right"], self.bottle.contact_geoms) + + bottle_z = self.sim.data.body_xpos[self.obj_body_id["bottle"]][2] + table_z = self.mujoco_objects[0].top_offset[2] + check_bottle_in_air = bottle_z > table_z + 0.2 + # check bottle and table collision + # check_bottle_in_air = not self.check_contact("bottle", "table") + return check_grasp and check_bottle_in_air + + def get_object(self): + return dict( + bottle=dict(obj_name=self.objects["bottle"]["name"], obj_type="body"), + ) + + def get_subtask_term_signals(self): + signals = dict() + signals["grasp_bottle"] = int( + self._check_grasp(self.robots[0].gripper["right"], self.bottle.contact_geoms) + ) + return signals + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + task.task_spec_0.subtask_1 = dict( + object_ref="bottle", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() + + +def create_shelf(pos: list[float], euler: list[float]) -> MJCFObject: + shelf = MJCFObject( + name="shelf_body", + mjcf_path=xml_path_completion( + "objects/aigc/shelf/model.xml", root=robocasa.models.assets_root + ), + scale=[1.0, 1.0, 1.0], + solimp=(0.998, 0.998, 0.001), + solref=(0.001, 1), + density=10, + friction=(1, 1, 1), + static=True, + ) + shelf.set_pos(pos) + shelf.set_euler(euler) + return shelf + + +class PickBottleShelf(PnPBottle): + def _load_model(self): + # Create both the original table and the target table + self.mujoco_objects = [create_shelf(pos=[0.8, 0.4, 0], euler=[0, 0, np.pi / 2])] + + LocoManipulationEnv._load_model(self) + + self.bottle = self._create_bottle() + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + LocoManipulationEnv._reset_internal(self) + + if not self.deterministic_reset: + # Base position on ground (z=0.075 is bottle radius) + # Level 2 of shelf + self._randomize_bottle_placement(base_pos=np.array([0.7, 0.4, 0.376660 + 0.075 + 0.02])) + self._randomize_table_texture() + RobotPoseRandomizer.set_arm(self, elbow_qpos=-0.5, shoulder_pitch_qpos=0.5) + + +class PnPBottleHigh(PnPBottle): + def _load_model(self): + self.mujoco_objects = [self._create_table("table_body", [0.5, 0, 0.1], [0, 0, np.pi / 2])] + + LocoManipulationEnv._load_model(self) + + self.bottle = self._create_bottle() + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + LocoManipulationEnv._reset_internal(self) + + # Randomize bottle position within +/- 0.1 range on x and y axes + if not self.deterministic_reset: + # Base position of the bottle + base_pos = np.array([0.4, 0, 0.875]) + + # Add random offset within +/- 0.1 range for x and y + random_x = np.random.uniform(-0.1, 0.1) + random_y = np.random.uniform(-0.1, 0.1) + # New randomized position (keep z constant) + new_pos = base_pos + np.array([random_x, random_y, 0]) + + # Set the bottle position using the free joint + # For free joints, qpos includes [x, y, z, qw, qx, qy, qz] + current_qpos = self.sim.data.get_joint_qpos("bottle_joint") + new_qpos = current_qpos.copy() + new_qpos[:3] = new_pos # Update position (x, y, z) + + self.sim.data.set_joint_qpos("bottle_joint", new_qpos) + + def _setup_observables(self): + observables = super()._setup_observables() + + @sensor(modality="object") + def obj_pos(obs_cache): + return self.sim.data.body_xpos[self.obj_body_id["bottle"]] + + @sensor(modality="object") + def obj_quat(obs_cache): + return self.sim.data.body_xquat[self.obj_body_id["bottle"]] + + @sensor(modality="object") + def obj_linear_vel(obs_cache): + return self.sim.data.get_body_xvelp("bottle_body") + + @sensor(modality="object") + def obj_angular_vel(obs_cache): + return self.sim.data.get_body_xvelr("bottle_body") + + sensors = [obj_pos, obj_quat, obj_linear_vel, obj_angular_vel] + names = [s.__name__ for s in sensors] + + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def get_privileged_obs_keys(self): + return { + "obj_pos": (3,), + "obj_quat": (4,), + "obj_linear_vel": (3,), + "obj_angular_vel": (3,), + } + + +class NavPickBottle(PnPBottle): + """ + Pick-and-Place Bottle environment with robot position randomized at reset. + """ + + def _reset_internal(self): + super()._reset_internal() + + if not self.deterministic_reset: + RobotPoseRandomizer.set_pose(self, (-0.3, -0.16), (-0.2, 0.2), (-np.pi / 6, np.pi / 6)) + + +class PnPBottleRandRobotPose(NavPickBottle): + pass + + +class VisualReach(LocoManipulationEnv): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def _load_model(self): + super()._load_model() + + self.create_visual_only_goal_cube() + + def create_visual_only_goal_cube(self): + cube_tex = ET.Element( + "texture", + type="2d", + name="cube", + builtin="flat", + rgb1="1.0 0.0 0.0", + width="512", + height="512", + ) + cube_mat = ET.Element( + "material", + name="cube", + texture="cube", + texuniform="true", + reflectance="0.1", + ) + self.model.asset.append(cube_tex) + self.model.asset.append(cube_mat) + + self.objects = {} + cube_body = ET.Element("body", name="cube_body", pos="0.4 0 0.875") + + cube_vis_geom = ET.Element( + "geom", + name="cube_vis", + pos="0 0 0", + size="0.0375 0.0375 0.0375", + type="box", + material="cube", + group="1", + conaffinity="0", + contype="0", + ) + + cube_body.append(cube_vis_geom) + self.model.worldbody.append(cube_body) + self.objects["cube"] = {"name": "cube_body"} + + def _setup_references(self): + super()._setup_references() + + self.obj_body_id = {} + for name, model in self.objects.items(): + self.obj_body_id[name] = self.sim.model.body_name2id(model["name"]) + + def _check_success(self): + # check_grasp = self._check_grasp(self.robots[0].gripper["right"], self.objects["bottle"]) + # check_reach = self._check_reach(self.objects["bottle"]) + return True + + def _check_reach(self, obj_name): + raise NotImplementedError + # To be implemented by the subclass + + def get_object(self): + return dict( + cube=dict(obj_name=self.objects["cube"].root_body, obj_type="body"), + ) + + def reset_obj_pos(self): + # reset object pos randomly around bottle_body pos="0.4 0 0.875" + init_pos = np.array([0.4, 0, 0.875]) + random_x = np.random.uniform(-0.3, 0.15) + random_y = np.random.uniform(-0.15, 0.15) + random_z = np.random.uniform(-0.15, 0.30) + self.sim.model.body_pos[self.obj_body_id["cube"]] = init_pos + np.array( + [random_x, random_y, random_z] + ) + + def set_cameras(self): + super().set_cameras() + self.mujoco_arena.set_camera( + camera_name="egoview", + pos=[0.078, 0, 1.308], + quat=[0.66491268, 0.24112495, -0.24112507, -0.66453637], + camera_attribs=dict(fovy="90"), + ) + + def _setup_observables(self): + observables = super()._setup_observables() + + @sensor(modality="object") + def obj_pos(obs_cache): + return self.sim.data.body_xpos[self.obj_body_id["cube"]] + + @sensor(modality="object") + def obj_quat(obs_cache): + return self.sim.data.body_xquat[self.obj_body_id["cube"]] + + @sensor(modality="object") + def obj_linear_vel(obs_cache): + return self.sim.data.get_body_xvelp("cube_body") + + @sensor(modality="object") + def obj_angular_vel(obs_cache): + return self.sim.data.get_body_xvelr("cube_body") + + sensors = [obj_pos, obj_quat, obj_linear_vel, obj_angular_vel] + names = [s.__name__ for s in sensors] + + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def get_privileged_obs_keys(self): + return { + "obj_pos": (3,), + "obj_quat": (4,), + "obj_linear_vel": (3,), + "obj_angular_vel": (3,), + } + + +class PnPBottleFixtureToFixture(PnPBottle): + """ + Task: Robot picks up bottle and places it on a fixture. + + Initialization: bottle rests on a source fixture. + + Idea: by changing the location of the target fixture, we can change the data generation task layout for + these placement related tasks. + """ + + SEPARATION_THRESH_M: float = 0.0005 # 0.05 cm + DISTMAX_SCAN_M: float = 0.05 # 5 cm window for distance queries + _SRC_NAME = "start_fixture" + _TGT_NAME = "target_fixture" + _FIXTURE_HALF_SIZE = np.array([0.05, 0.05, 0.001]) + _BOTTLE_HALF_HEIGHT = 0.075 + _X_SRC_RANGE = (0.30, 0.55) + _X_TGT_RANGE = (0.30, 0.55) + _Y_SRC_RANGE = (-0.20, -0.05) + _Y_TGT_RANGE = (0.05, 0.20) + _SRC_FIXTURE_VISIBLE = False + _TGT_FIXTURE_VISIBLE = True + + def _load_model(self): + self.mujoco_objects = [self._create_table("table_body", [0.5, 0, 0], [0, 0, np.pi / 2])] + LocoManipulationEnv._load_model(self) + self.bottle = self._create_bottle() + self._create_fixture(self._SRC_NAME, visible=self._SRC_FIXTURE_VISIBLE, rgb="1 0 0") + self._create_fixture(self._TGT_NAME, visible=self._TGT_FIXTURE_VISIBLE, rgb="0 1 0") + self._src_body = f"{self._SRC_NAME}_body" + self._tgt_body = f"{self._TGT_NAME}_body" + self._src_coll = f"{self._SRC_NAME}_collider" + self._tgt_coll = f"{self._TGT_NAME}_collider" + + def _create_fixture(self, name: str, visible: bool, rgb: Optional[str] = None) -> None: + """Create a flat box fixture; add assets + body to the compiled model.""" + fx = PrimitiveFixture( + name=name, pos=np.array([0.0, 0.0, 0.0]), half_size=self._FIXTURE_HALF_SIZE, rgb=rgb + ) + + # Make source fixture invisible (keep collision only) + if not visible: + # Find the visual geom and hide it + for child in list(fx.body): + if child.tag == "geom" and child.get("name") == f"{name}_vis": + child.set("rgba", "0 0 0 0") # invisible visual + break + + # Register assets + body into the scene graph + self.model.asset.extend(fx.assets) + self.model.worldbody.append(fx.body) + + def _setup_references(self): + super()._setup_references() + # Table root body is "_main" (same convention as target_table above) + self.table_body_id = self.sim.model.body_name2id("table_body_main") + self.src_fixture_id = self.sim.model.body_name2id(self._src_body) + self.tgt_fixture_id = self.sim.model.body_name2id(self._tgt_body) + + def _check_success(self) -> bool: + """Bottle touches target fixture collider and is upright.""" + bottle_on_target = self.check_contact(self.bottle.contact_geoms, [self._tgt_coll]) + bottle_upright = check_obj_upright(self, "bottle", threshold=0.8, symmetric=True) + return bottle_on_target and bottle_upright + + # --- runtime table height --- + def _table_top_z(self) -> float: + base_z = float(self.sim.data.body_xpos[self.table_body_id][2]) + top_offset_z = float(self.mujoco_objects[0].top_offset[2]) + return base_z + top_offset_z + + def _reset_internal(self): + LocoManipulationEnv._reset_internal(self) + + if not self.deterministic_reset: + # Sample fixture XY, compute Z from current table pose + x_src = self.rng.uniform(*self._X_SRC_RANGE) + y_src = self.rng.uniform(*self._Y_SRC_RANGE) + + x_tgt = self.rng.uniform(*self._X_TGT_RANGE) + y_tgt = self.rng.uniform(*self._Y_TGT_RANGE) + # y_tgt = self.rng.uniform(*self._Y_TGT_RANGE) + + z_top = self._table_top_z() # dynamic table top + src_pos = np.array([x_src, y_src, z_top]) + tgt_pos = np.array([x_tgt, y_tgt, z_top]) + + # Reset fixture body poses (static bodies): write to model; MuJoCo will use it after forward() + self.sim.model.body_pos[self.src_fixture_id] = src_pos + self.sim.model.body_pos[self.tgt_fixture_id] = tgt_pos + + # Place bottle on source fixture: top of fixture + bottle half-height + tiny clearance + bottle_z = z_top + self._FIXTURE_HALF_SIZE[2] + self._BOTTLE_HALF_HEIGHT + 0.002 + qpos = self.sim.data.get_joint_qpos("bottle_joint").copy() + qpos[:3] = np.array([x_src, y_src, bottle_z]) + qpos[3:7] = np.array([1.0, 0.0, 0.0, 0.0]) # upright + self.sim.data.set_joint_qpos("bottle_joint", qpos) + + self._randomize_table_texture() + RobotPoseRandomizer.set_pose(self, (-0.3, -0.16), (-0.2, 0.2), (-np.pi / 6, np.pi / 6)) + + # --- distance via MuJoCo --- + def _min_signed_distance_mj(self, geoms_a: list[str], geoms_b: list[str]) -> float: + model, data = self.sim.model, self.sim.data + dmin = np.inf + fromto = np.empty(6, dtype=np.float64) + a_ids = [model.geom_name2id(n) for n in geoms_a] + b_ids = [model.geom_name2id(n) for n in geoms_b] + for ga in a_ids: + for gb in b_ids: + dist = mujoco.mj_geomDistance( + model._model, data._data, ga, gb, self.DISTMAX_SCAN_M + 0.01, fromto + ) + dmin = min(dmin, float(dist)) + return dmin + + def get_subtask_term_signals(self) -> dict[str, int]: + """ + 1 iff (no contact between bottle and source fixture) AND + (min signed distance > DISTMAX_SCAN_M). + """ + in_contact = self.check_contact(self.bottle.contact_geoms, [self._src_coll]) + min_dist = self._min_signed_distance_mj(self.bottle.contact_geoms, [self._src_coll]) + return { + "obj_off_source_fixture": int((not in_contact) and (min_dist > self.DISTMAX_SCAN_M)) + } + + def get_object(self) -> dict: + return dict( + bottle=dict(obj_name=self.objects["bottle"]["name"], obj_type="body"), + source_fixture=dict(obj_name=self._src_body, obj_type="body"), + target_fixture=dict(obj_name=self._tgt_body, obj_type="body"), + ) + + @staticmethod + def task_config() -> dict: + task = DexMGConfigHelper.AttrDict() + # Subtask 1: pick (leave source fixture) + task.task_spec_0.subtask_1 = dict( + object_ref="bottle", + subtask_term_signal="obj_off_source_fixture", + subtask_term_offset_range=(5, 10), + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + # Subtask 2: place on target fixture + task.task_spec_0.subtask_2 = dict( + object_ref="target_fixture", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + # Default filler for task_spec_1, mirroring other tasks + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() + + +class PnPBottleFixtureToFixtureSourceDemo(PnPBottleFixtureToFixture): + """ + Environment for collecting source demo for PnPBottleFixtureToFixture tasks. + """ + + _X_SRC_RANGE = (0.375, 0.375) + _X_TGT_RANGE = (0.375, 0.375) + _Y_SRC_RANGE = (-0.15, -0.15) + _Y_TGT_RANGE = (0.1, 0.1) + _SRC_FIXTURE_VISIBLE = False + _TGT_FIXTURE_VISIBLE = True + + +class PnPBottleShelfToTable(PnPBottleFixtureToFixture): + """ + Task: Robot picks up bottle from a fixture on a shelf and places it on a fixture on a table. + + Initialization: bottle rests on a source fixture on the shelf. + Target: place bottle on target fixture on the table. + """ + + # Adjust ranges for shelf-to-table layout + _X_SRC_RANGE = (-0.05, 0.05) # Shelf position range + _X_TGT_RANGE = (-0.05 - 0.2, 0.05 - 0.2) # Table position range + # TODO: could be better to have some 'center' specified here + _Y_SRC_RANGE = (-0.05, 0.05) # Shelf position range + _Y_TGT_RANGE = (-0.05, 0.05) # Table position range + _SRC_FIXTURE_VISIBLE = True + _TGT_FIXTURE_VISIBLE = True + _FIXTURE_HALF_SIZE = np.array([0.05, 0.05, 0.001]) + + # Shelf height constants (from PnPBottleShelf) + # _SHELF_HEIGHT = 0.386660 # Level 2 of shelf from the original shelf environment + _SHELF_HEIGHT = 0.753321 + 0.015 # Level 3 of shelf from the original shelf environment + + def _load_model(self): + # Create both shelf and table + self.mujoco_objects = [ + self._create_table("table_body", [0.5, 0.6, 0], [0, 0, np.pi / 2]), + create_shelf(pos=[0.8, -0.4, 0], euler=[0, 0, np.pi / 2]), + ] + + LocoManipulationEnv._load_model(self) + + self.bottle = self._create_bottle() + self._create_fixture(self._SRC_NAME, visible=self._SRC_FIXTURE_VISIBLE, rgb="1 0 0") + self._create_fixture(self._TGT_NAME, visible=self._TGT_FIXTURE_VISIBLE, rgb="0 1 0") + self._src_body = f"{self._SRC_NAME}_body" + self._tgt_body = f"{self._TGT_NAME}_body" + self._src_coll = f"{self._SRC_NAME}_collider" + self._tgt_coll = f"{self._TGT_NAME}_collider" + + def _setup_references(self): + super()._setup_references() + # Add reference to shelf + self.shelf_body_id = self.sim.model.body_name2id("shelf_body_main") + + def _shelf_top_z(self) -> float: + """Get the Z coordinate of the shelf top surface""" + # Use the same shelf height as in PnPBottleShelf + return self._SHELF_HEIGHT + + def _shelf_xy(self) -> tuple[float, float]: + """Get the XY coordinates of the shelf""" + return self.sim.data.body_xpos[self.shelf_body_id][:2] + + def _table_xy(self) -> tuple[float, float]: + """Get the XY coordinates of the table""" + return self.sim.data.body_xpos[self.table_body_id][:2] + + def _reset_internal(self): + LocoManipulationEnv._reset_internal(self) + + if not self.deterministic_reset: + # Sample fixture XY positions + x_src = self.rng.uniform(*self._X_SRC_RANGE) + y_src = self.rng.uniform(*self._Y_SRC_RANGE) + + x_tgt = self.rng.uniform(*self._X_TGT_RANGE) + y_tgt = self.rng.uniform(*self._Y_TGT_RANGE) + + # Source fixture on shelf + z_shelf = self._shelf_top_z() + x_shelf, y_shelf = self._shelf_xy() + src_pos = np.array([x_src, y_src, z_shelf]) + src_pos += np.array([x_shelf, y_shelf, 0]) + + # table pos + # Target fixture on table + z_table = self._table_top_z() + x_table, y_table = self._table_xy() + tgt_pos = np.array([x_tgt, y_tgt, z_table]) + tgt_pos += np.array([x_table, y_table, 0]) + + # Reset fixture body poses + self.sim.model.body_pos[self.src_fixture_id] = src_pos + self.sim.model.body_pos[self.tgt_fixture_id] = tgt_pos + + # Place bottle on source fixture (shelf): top of fixture + bottle half-height + clearance + bottle_z = z_shelf + self._FIXTURE_HALF_SIZE[2] + self._BOTTLE_HALF_HEIGHT + 0.002 + qpos = self.sim.data.get_joint_qpos("bottle_joint").copy() + qpos[:3] = np.array([src_pos[0], src_pos[1], bottle_z]) + qpos[3:7] = np.array([1.0, 0.0, 0.0, 0.0]) # upright + self.sim.data.set_joint_qpos("bottle_joint", qpos) + + self._randomize_table_texture() + RobotPoseRandomizer.set_pose(self, (-0.3, -0.16), (-0.2, 0.2), (-np.pi / 6, np.pi / 6)) + + def _randomize_table_texture(self): + """Randomize textures for the table (shelf texture is static)""" + # Only randomize the table texture (index 1), not the shelf + table = self.mujoco_objects[1] + randomize_materials_rgba( + rng=self.rng, mjcf_obj=table, gradient=self.TABLE_GRADIENT, linear=True + ) + + +class PnPBottleTableToTable(PnPBottle): + def _load_model(self): + # Create both the original table and the target table + self.mujoco_objects = [ + self._create_table("table_body", [0.5, 0, 0], [0, 0, np.pi / 2]), + self._create_table("target_table_body", [0.5, 1.2, 0], [0, 0, np.pi / 2]), + ] + + LocoManipulationEnv._load_model(self) + + self.bottle = self._create_bottle() + + def _setup_references(self): + super()._setup_references() + + # Add reference to target table - note the _main suffix + self.target_table_body_id = self.sim.model.body_name2id("target_table_body_main") + + def _check_success(self): + """Check if bottle is successfully placed on the target table""" + bottle_on_table = self.check_contact(self.bottle.contact_geoms, self.mujoco_objects[1]) + bottle_is_upright = check_obj_upright(self, "bottle", threshold=0.8, symmetric=True) + return bottle_on_table and bottle_is_upright + + def _randomize_table_texture(self): + """Randomize textures for both tables""" + # Randomize original table + original_table = self.mujoco_objects[0] + randomize_materials_rgba( + rng=self.rng, mjcf_obj=original_table, gradient=self.TABLE_GRADIENT, linear=True + ) + + # Randomize target table + target_table = self.mujoco_objects[1] + randomize_materials_rgba( + rng=self.rng, mjcf_obj=target_table, gradient=self.TABLE_GRADIENT, linear=True + ) + + def get_object(self): + return dict( + bottle=dict(obj_name=self.objects["bottle"]["name"], obj_type="body"), + target_table=dict(obj_name="target_table_body_main", obj_type="body"), + ) + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + task.task_spec_0.subtask_1 = dict( + object_ref="bottle", + subtask_term_signal="obj_off_table", + subtask_term_offset_range=(5, 10), + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + # Second subtask for placing on target table + task.task_spec_0.subtask_2 = dict( + object_ref="target_table", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() + + def get_subtask_term_signals(self): + """ + Retrieve signals used to define subtask termination conditions. + + Returns: + dict: Dictionary mapping signal names to their current values + """ + signals = dict() + + obj_z = self.sim.data.body_xpos[self.obj_body_id["bottle"]][2] + target_table_pos = self.sim.data.body_xpos[self.target_table_body_id] + target_table_z = target_table_pos[2] + self.mujoco_objects[1].top_offset[2] + + th = 0.15 + signals["obj_off_table"] = int(obj_z - target_table_z > th) + + return signals + + +class PickBottleGround(PnPBottle): + """ + Pick-and-Place Bottle environment with bottle initialized on the ground. + """ + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + LocoManipulationEnv._reset_internal(self) + + if not self.deterministic_reset: + # Base position on ground (z=0.075 is bottle radius) + self._randomize_bottle_placement(base_pos=np.ndarray([0.4, 0, 0.075])) + self._randomize_table_texture() + + def _randomize_table_texture(self): + pass + + def _check_success(self): + check_grasp = self._check_grasp(self.robots[0].gripper["right"], "bottle") + + bottle_z = self.sim.data.body_xpos[self.obj_body_id["bottle"]][2] + ground_z = 0 + check_bottle_in_air = bottle_z > ground_z + 0.2 + # check bottle and table collision + # check_bottle_in_air = not self.check_contact("bottle", "table") + return check_grasp and check_bottle_in_air + + def _load_model(self): + self.mujoco_objects = [] + + super(PnPBottle, self)._load_model() + self._create_bottle() + + +class PickBottles(PnPBottle): + BOTTLE_POS_RANGE_X = (-0.08, 0.04) + BOTTLE_POS_RANGE_Y = (-0.04, 0.04) + + COLOURS: list[list[float]] = [[0.3, 0.7, 0.8], [0.8, 0.4, 0.3]] + BOTTLES_COUNT = 2 + Y_OFFSET_STEP = 0.1 + + @staticmethod + def _get_bottle_names() -> list[str]: + return [f"bottle_{i}" for i in range(PickBottles.BOTTLES_COUNT)] + + def _load_model(self): + self.mujoco_objects = [self._create_table("table_body", [0.5, 0, 0], [0, 0, np.pi / 2])] + + LocoManipulationEnv._load_model(self) + + self.bottles = self._create_bottles() + + def _create_bottles(self) -> list[PrimitiveBottle]: + bottles = [] + for i, name in enumerate(self._get_bottle_names()): + rgb = self.COLOURS[i % len(self.COLOURS)] + bottles.append(self._create_bottle(name=name, rgb=rgb)) + return bottles + + def _reset_internal(self): + LocoManipulationEnv._reset_internal(self) + + n = len(self.bottles) + offsets = np.arange(n) - (n - 1) / 2.0 + for i, bottle in enumerate(self.bottles): + self._randomize_bottle_placement( + name=bottle.name, + base_pos=self.DEFAULT_BOTTLE_POS + + np.array([0, self.Y_OFFSET_STEP * offsets[i], 0]), + ) + self._randomize_table_texture() + + def _check_success(self): + for bottle in self.bottles: + check_grasp = self._check_grasp( + self.robots[0].gripper["right"], bottle.contact_geoms + ) or self._check_grasp(self.robots[0].gripper["left"], bottle.contact_geoms) + bottle_z = self.sim.data.body_xpos[self.obj_body_id[bottle.name]][2] + table_z = self.mujoco_objects[0].top_offset[2] + check_bottle_in_air = bottle_z > table_z + 0.2 + if check_grasp and check_bottle_in_air: + continue + return False + return True + + def get_object(self): + result = {} + for bottle in self.bottles: + result[bottle.name] = dict(obj_name=self.objects[bottle.name]["name"], obj_type="body") + return result + + def get_subtask_term_signals(self): + signals = dict() + for bottle in self.bottles: + signals[f"grasp_{bottle.name}"] = int( + self._check_grasp(self.robots[0].gripper["right"], bottle.contact_geoms) + or self._check_grasp(self.robots[0].gripper["left"], bottle.contact_geoms) + ) + return signals + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + bottle_names = PickBottles._get_bottle_names() + assert len(bottle_names) == 2 + for i, name in enumerate(bottle_names): + subtask = dict( + object_ref=name, + subtask_term_signal=f"grasp_{name}", + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + spec_attr = f"task_spec_{i}" + setattr(getattr(task, spec_attr), "subtask_1", subtask) + return task.to_dict() + + +class NavPickBottles(PickBottles): + """ + PickBottles environment with robot position randomized further from table at reset. + """ + + def _reset_internal(self): + super()._reset_internal() + + if not self.deterministic_reset: + RobotPoseRandomizer.set_pose(self, (-0.3, -0.16), (-0.2, 0.2), (-np.pi / 6, np.pi / 6)) + + +class PnPBottlesTableToTable(PickBottles): + def _load_model(self): + self.mujoco_objects = [ + self._create_table("table_body", [0.5, 0, 0], [0, 0, np.pi / 2]), + self._create_table("target_table_body", [0.5, 1.2, 0], [0, 0, np.pi / 2]), + ] + + LocoManipulationEnv._load_model(self) + + self.bottles = self._create_bottles() + + def _check_success(self): + """Check if bottles are successfully placed on the target table""" + for bottle in self.bottles: + bottle_on_table = self.check_contact(bottle.contact_geoms, self.mujoco_objects[1]) + bottle_is_upright = check_obj_upright(self, bottle.name, threshold=0.8, symmetric=True) + if bottle_on_table and bottle_is_upright: + continue + return False + return True + + def _setup_references(self): + super()._setup_references() + + # Add reference to target table - note the _main suffix + self.target_table_body_id = self.sim.model.body_name2id("target_table_body_main") + + def get_object(self): + result = super().get_object() + result["target_table"] = dict(obj_name="target_table_body_main", obj_type="body") + return result + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + + bottle_names = PickBottles._get_bottle_names() + assert len(bottle_names) == 2 + for i, name in enumerate(bottle_names): + + # pick subtask per arm + subtask = dict( + object_ref=name, + subtask_term_signal=f"{name}_off_table", + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + spec_attr = f"task_spec_{i}" + setattr(getattr(task, spec_attr), "subtask_1", subtask) + + # place subtask per arm + subtask = dict( + object_ref="target_table", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + spec_attr = f"task_spec_{i}" + setattr(getattr(task, spec_attr), "subtask_2", subtask) + + return task.to_dict() + + def get_subtask_term_signals(self): + signals = dict() + for bottle in self.bottles: + obj_z = self.sim.data.body_xpos[self.obj_body_id[bottle.name]][2] + target_table_pos = self.sim.data.body_xpos[self.target_table_body_id] + target_table_z = target_table_pos[2] + self.mujoco_objects[1].top_offset[2] + th = 0.15 + signals[f"{bottle.name}_off_table"] = int(obj_z - target_table_z > th) + return signals diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip.py new file mode 100644 index 0000000000000000000000000000000000000000..56661a306485ccaed6394e02cbcb6ac44d18a0a2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip.py @@ -0,0 +1,83 @@ +from abc import abstractmethod +from typing import Optional + +from robocasa.environments.locomanipulation.base import LocoManipulationEnv +from robocasa.models.scenes import GroundArena +from robocasa.models.scenes.factory_arena import FactoryArena +from robocasa.utils.scene.configs import SceneConfig, SceneScaleConfig +from robocasa.utils.scene.scene import Scene, SceneObject +from robocasa.utils.scene.success_criteria import SuccessCriteria + + +class LMEnvBase(LocoManipulationEnv): + SCENE_SCALE = SceneScaleConfig() + + def __init__( + self, + translucent_robot: bool = False, + use_object_obs: bool = False, + scene_scale: Optional[SceneScaleConfig] = None, + *args, + **kwargs, + ): + self.scene_scale = scene_scale or self.SCENE_SCALE + super().__init__(translucent_robot, use_object_obs, *args, **kwargs) + + def _load_model(self): + self.scene = Scene(self, self._get_env_config(), self.scene_scale) + self.mujoco_objects = self.scene.mujoco_objects + + super()._load_model() + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + if not self.deterministic_reset: + self.scene.reset() + + def _setup_references(self): + super()._setup_references() + + self.obj_body_id = {} + for obj in self.mujoco_objects: + self.obj_body_id[obj.name] = self.sim.model.body_name2id(obj.root_body) + + def _get_env_config(self) -> SceneConfig: + return SceneConfig( + objects=self._get_objects(), + success=self._get_success_criteria(), + instruction=self._get_instruction(), + ) + + @abstractmethod + def _get_objects(self) -> list[SceneObject]: + raise NotImplementedError + + @abstractmethod + def _get_success_criteria(self) -> SuccessCriteria: + raise NotImplementedError + + @abstractmethod + def _get_instruction(self) -> str: + raise NotImplementedError + + def _check_success(self): + return self.scene.success() + + def get_ep_meta(self): + ep_meta = super().get_ep_meta() + ep_meta["lang"] = self.scene.instruction + return ep_meta + + +# noinspection PyAbstractClass +class LMSimpleEnv(LMEnvBase): + MUJOCO_ARENA_CLS = GroundArena + + +# noinspection PyAbstractClass +class LMFactoryEnv(LMEnvBase): + MUJOCO_ARENA_CLS = FactoryArena diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_basic.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..1c6b5ab776abaa4555e39cc782f363dd46ab5727 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_basic.py @@ -0,0 +1,732 @@ +import numpy as np +from robocasa.environments.locomanipulation.base import RobotPoseRandomizer +from robocasa.environments.locomanipulation.locomanip import LMSimpleEnv +from robocasa.utils.dexmg_utils import DexMGConfigHelper +from robocasa.utils.scene.configs import ( + ObjectConfig, + ReferenceConfig, + SamplingConfig, + SceneScaleConfig, +) +from robocasa.utils.scene.scene import SceneObject +from robocasa.utils.scene.success_criteria import ( + AllCriteria, + AnyCriteria, + IsGrasped, + IsInContact, + IsPositionInRange, + IsRobotInRange, + IsUpright, + NotCriteria, + SuccessCriteria, +) +from robocasa.utils.visuals_utls import Gradient, randomize_materials_rgba + + +class LMPickBottle(LMSimpleEnv, DexMGConfigHelper): + SCENE_SCALE = SceneScaleConfig(planar_scale=1.0) + + TABLE_GRADIENT: Gradient = Gradient( + np.array([0.68, 0.34, 0.07, 1.0]), np.array([1.0, 1.0, 1.0, 1.0]) + ) + LIFT_OFFSET = 0.1 + + def _get_objects(self) -> list[SceneObject]: + self.table = SceneObject( + ObjectConfig( + name="table", + mjcf_path="objects/omniverse/locomanip/lab_table/model.xml", + scale=1.0, + static=True, + sampler_config=SamplingConfig( + x_range=np.array([-0.02, 0.02]), + y_range=np.array([-0.02, 0.02]), + reference_pos=np.array([0.5, 0, 0]), + rotation=np.array([np.pi * 0.5, np.pi * 0.5]), + ), + ) + ) + self.bottle = SceneObject( + ObjectConfig( + name="bottle", + mjcf_path="objects/omniverse/locomanip/jug_a01/model.xml", + static=False, + scale=0.6, + sampler_config=SamplingConfig( + x_range=np.array([-0.08, 0.04]), + y_range=np.array([-0.08, 0.08]), + rotation=np.array([-np.pi, np.pi]), + reference_pos=np.array([0.4, 0, self.table.mj_obj.top_offset[2]]), + ), + ) + ) + return [self.table, self.bottle] + + def _get_success_criteria(self) -> SuccessCriteria: + return AllCriteria( + IsGrasped(self.bottle, "right"), + IsPositionInRange(self.bottle, 2, self.table.mj_obj.top_offset[2] + self.LIFT_OFFSET), + ) + + def _get_instruction(self) -> str: + return "Pick up the bottle." + + def get_object(self): + return dict( + bottle=dict(obj_name=self.bottle.mj_obj.root_body, obj_type="body"), + ) + + def get_subtask_term_signals(self): + signals = dict() + signals["grasp_bottle"] = int( + self._check_grasp(self.robots[0].gripper["right"], self.bottle.mj_obj.contact_geoms) + ) + return signals + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + task.task_spec_0.subtask_1 = dict( + object_ref="bottle", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() + + def _reset_internal(self): + super()._reset_internal() + + if not self.deterministic_reset: + self._randomize_table_rgba() + + def _randomize_table_rgba(self): + randomize_materials_rgba( + rng=self.rng, mjcf_obj=self.table.mj_obj, gradient=self.TABLE_GRADIENT, linear=True + ) + + +class LMPickBottleHigh(LMPickBottle): + TABLE_OFFSET = 0.1 + + def _get_objects(self) -> list[SceneObject]: + self.table = SceneObject( + ObjectConfig( + name="table", + mjcf_path="objects/omniverse/locomanip/lab_table/model.xml", + scale=1.0, + static=True, + sampler_config=SamplingConfig( + x_range=np.array([-0.02, 0.02]), + y_range=np.array([-0.02, 0.02]), + reference_pos=np.array([0.5, 0, self.TABLE_OFFSET]), + rotation=np.array([np.pi * 0.5, np.pi * 0.5]), + ), + ) + ) + self.bottle = SceneObject( + ObjectConfig( + name="bottle", + mjcf_path="objects/omniverse/locomanip/jug_a01/model.xml", + static=False, + scale=0.6, + sampler_config=SamplingConfig( + x_range=np.array([-0.08, 0.04]), + y_range=np.array([-0.08, 0.08]), + rotation=np.array([-np.pi, np.pi]), + reference_pos=np.array( + [0.4, 0, self.TABLE_OFFSET + self.table.mj_obj.top_offset[2]] + ), + reference=ReferenceConfig(obj=self.table), + ), + ) + ) + return [self.table, self.bottle] + + +class LMNavPickBottle(LMPickBottle): + def _reset_internal(self): + super()._reset_internal() + + if not self.deterministic_reset: + RobotPoseRandomizer.set_pose(self, (-0.3, -0.16), (-0.2, 0.2), (-np.pi / 6, np.pi / 6)) + + def _get_instruction(self) -> str: + return "Walk forward and pick up the bottle from the table." + + +class LMPickBottleGround(LMPickBottle): + def _get_objects(self) -> list[SceneObject]: + self.bottle = SceneObject( + ObjectConfig( + name="bottle", + mjcf_path="objects/omniverse/locomanip/jug_a01/model.xml", + static=False, + scale=0.6, + sampler_config=SamplingConfig( + x_range=np.array([-0.08, 0.04]), + y_range=np.array([-0.08, 0.08]), + rotation=np.array([-np.pi, np.pi]), + reference_pos=np.array( + [0.4, 0, 0.075] + ), # Base position on ground (z=0.075 is bottle radius) + ), + ) + ) + return [self.bottle] + + def _get_success_criteria(self) -> SuccessCriteria: + return AllCriteria( + IsGrasped(self.bottle, "right"), + IsPositionInRange(self.bottle, 2, self.LIFT_OFFSET, 10), + ) + + def _randomize_table_rgba(self): + pass + + +class LMPnPBottle(LMPickBottle): + LIFT_OFFSET = 0.15 + + def _get_objects(self) -> list[SceneObject]: + super()._get_objects() + self.table_target = SceneObject( + ObjectConfig( + name="table_target", + mjcf_path="objects/omniverse/locomanip/lab_table/model.xml", + scale=1.0, + static=True, + sampler_config=SamplingConfig( + x_range=np.array([-0.02, 0.02]), + y_range=np.array([-0.02, 0.02]), + reference_pos=np.array([0.5, 1.2, 0]), + rotation=np.array([np.pi * 0.5, np.pi * 0.5]), + ), + ) + ) + return [self.table, self.table_target, self.bottle] + + def _get_success_criteria(self) -> SuccessCriteria: + return AllCriteria( + IsUpright(self.bottle, symmetric=True), IsInContact(self.bottle, self.table_target) + ) + + def _get_instruction(self) -> str: + return "Pick up the bottle and place it on the other table." + + def get_object(self): + return dict( + bottle=dict(obj_name=self.bottle.mj_obj.root_body, obj_type="body"), + target_table=dict(obj_name=self.table_target.mj_obj.root_body, obj_type="body"), + ) + + def get_subtask_term_signals(self): + obj_z = self.sim.data.body_xpos[self.obj_body_id(self.bottle.mj_obj.name)][2] + target_table_pos = self.sim.data.body_xpos[self.obj_body_id(self.table_target.mj_obj.name)] + target_table_z = target_table_pos[2] + self.table_target.mj_obj.top_offset[2] + return dict(obj_off_table=int(obj_z - target_table_z > self.LIFT_OFFSET)) + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + task.task_spec_0.subtask_1 = dict( + object_ref="bottle", + subtask_term_signal="obj_off_table", + subtask_term_offset_range=(5, 10), + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + # Second subtask for placing on target table + task.task_spec_0.subtask_2 = dict( + object_ref="target_table", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() + + def _randomize_table_rgba(self): + for table in [self.table_target, self.table]: + randomize_materials_rgba( + rng=self.rng, mjcf_obj=table.mj_obj, gradient=self.TABLE_GRADIENT, linear=True + ) + + +class LMPickMultipleBottles(LMPickBottle): + BOTTLE_COLOURS = [(0.3, 0.7, 0.8, 1.0), (0.8, 0.4, 0.3, 1.0)] + BOTTLES_COUNT = 2 + Y_OFFSET_STEP = 0.1 + + def _get_objects(self) -> list[SceneObject]: + self.table = SceneObject( + ObjectConfig( + name="table", + mjcf_path="objects/omniverse/locomanip/lab_table/model.xml", + scale=1.0, + static=True, + sampler_config=SamplingConfig( + x_range=np.array([-0.02, 0.02]), + y_range=np.array([-0.02, 0.02]), + reference_pos=np.array([0.5, 0, 0]), + rotation=np.array([np.pi * 0.5, np.pi * 0.5]), + ), + ) + ) + + self.bottles = [] + offsets = np.arange(self.BOTTLES_COUNT) - (self.BOTTLES_COUNT - 1) / 2.0 + for i in range(self.BOTTLES_COUNT): + reference_pos = np.array([0.4, 0, self.table.mj_obj.top_offset[2]]) + reference_pos += np.array([0, self.Y_OFFSET_STEP * offsets[i], 0]) + bottle = SceneObject( + ObjectConfig( + name=f"bottle_{i}", + mjcf_path="objects/omniverse/locomanip/jug_a01/model.xml", + static=False, + scale=0.6, + sampler_config=SamplingConfig( + x_range=np.array([-0.08, 0.04]), + y_range=np.array([-0.04, 0.04]), + rotation=np.array([-np.pi, np.pi]), + reference_pos=reference_pos, + ), + rgba=self.BOTTLE_COLOURS[i % len(self.BOTTLE_COLOURS)], + ) + ) + self.bottles.append(bottle) + return [self.table, *self.bottles] + + def _get_success_criteria(self) -> SuccessCriteria: + criteria = [] + for bottle in self.bottles: + criteria.append(AnyCriteria(IsGrasped(bottle, "right"), IsGrasped(bottle, "left"))) + criteria.append( + IsPositionInRange(bottle, 2, self.table.mj_obj.top_offset[2] + self.LIFT_OFFSET, 10) + ) + return AllCriteria(*criteria) + + def _get_instruction(self) -> str: + return "Pick up bottles." + + def get_object(self): + return { + bottle.mj_obj.name: dict(obj_name=bottle.mj_obj.root_body, obj_type="body") + for bottle in self.bottles + } + + def get_subtask_term_signals(self): + return { + f"grasp_{bottle.mj_obj.name}": int( + self._check_grasp(self.robots[0].gripper["right"], bottle.mj_obj) + or self._check_grasp(self.robots[0].gripper["left"], bottle.mj_obj) + ) + for bottle in self.bottles + } + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + for i in range(LMPickMultipleBottles.BOTTLES_COUNT): + subtask = dict( + object_ref=f"bottle_{i}", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + setattr(task.task_spec_0, f"subtask_{i+1}", subtask) + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() + + +class LMPnPMultipleBottles(LMPickMultipleBottles): + def _get_objects(self) -> list[SceneObject]: + super()._get_objects() + self.table_target = SceneObject( + ObjectConfig( + name="table_target", + mjcf_path="objects/omniverse/locomanip/lab_table/model.xml", + scale=1.0, + static=True, + sampler_config=SamplingConfig( + x_range=np.array([-0.02, 0.02]), + y_range=np.array([-0.02, 0.02]), + reference_pos=np.array([0.5, 1.2, 0]), + rotation=np.array([np.pi * 0.5, np.pi * 0.5]), + ), + ) + ) + return [self.table, self.table_target, *self.bottles] + + def _get_success_criteria(self) -> SuccessCriteria: + criteria = [ + AllCriteria(IsInContact(bottle, self.table_target), IsUpright(bottle, symmetric=True)) + for bottle in self.bottles + ] + return AllCriteria(*criteria) + + def _get_instruction(self) -> str: + return "Pick up bottles from one table and place it on the other." + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + for i in range(LMPnPMultipleBottles.BOTTLES_COUNT): + bottle_name = f"bottle_{i}" + subtask = dict( + object_ref=bottle_name, + subtask_term_signal=f"{bottle_name}_off_table", + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + setattr(task.task_spec_0, f"subtask_{i+1}", subtask) + # Next subtask for placing on target table + task.task_spec_0.subtask_3 = dict( + object_ref="target_table", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() + + def get_subtask_term_signals(self): + signals = dict() + for bottle in self.bottles: + obj_z = self.sim.data.body_xpos[self.obj_body_id(self.bottle.mj_obj.name)][2] + target_table_pos = self.sim.data.body_xpos[ + self.obj_body_id(self.table_target.mj_obj.name) + ] + target_table_z = target_table_pos[2] + self.table_target.mj_obj.top_offset[2] + signals[f"{bottle.mj_obj.name}_off_table"] = int( + obj_z - target_table_z > self.LIFT_OFFSET + ) + return signals + + def _randomize_table_rgba(self): + for table in [self.table_target, self.table]: + randomize_materials_rgba( + rng=self.rng, mjcf_obj=table.mj_obj, gradient=self.TABLE_GRADIENT, linear=True + ) + + +class LMPickBottleShelf(LMPickBottle): + def _get_objects(self) -> list[SceneObject]: + super()._get_objects() + self.shelf = SceneObject( + ObjectConfig( + name="shelf", + mjcf_path="objects/omniverse/locomanip/lab_shelf/model.xml", + static=True, + sampler_config=SamplingConfig( + rotation=np.array([np.pi / 2, np.pi / 2]), + reference_pos=np.array([0.9, 0, 0]), + ), + ) + ) + self.bottle = SceneObject( + ObjectConfig( + name="bottle", + mjcf_path="objects/omniverse/locomanip/jug_a01/model.xml", + static=False, + scale=0.6, + sampler_config=SamplingConfig( + x_range=np.array([-0.14, -0.06]), + y_range=np.array([-0.08, 0.08]), + rotation=np.array([-np.pi, np.pi]), + reference=ReferenceConfig(self.shelf, spawn_id=2), + ), + ) + ) + return [self.shelf, self.bottle] + + def _get_success_criteria(self) -> SuccessCriteria: + return AllCriteria( + IsGrasped(self.bottle, "right"), + NotCriteria(IsInContact(self.bottle, self.shelf)), + ) + + +class LMNavPickBottleShelf(LMPickBottleShelf): + ROBOT_DISTANCE_THRESHOLD = 1.0 + + def _reset_internal(self): + super()._reset_internal() + if not self.deterministic_reset: + RobotPoseRandomizer.set_pose(self, (-0.1, 0.1), (-0.1, 0.1), (-np.pi / 6, np.pi / 6)) + + def _get_success_criteria(self) -> SuccessCriteria: + return AllCriteria( + NotCriteria(IsRobotInRange(self.shelf, self.ROBOT_DISTANCE_THRESHOLD, True)), + IsGrasped(self.bottle, "right"), + NotCriteria(IsInContact(self.bottle, self.shelf)), + ) + + def _get_instruction(self) -> str: + return "Pick up the bottle from the shelf and move backward away from it." + + +class LMPickBottleShelfLow(LMPickBottleShelf): + def _get_objects(self) -> list[SceneObject]: + super()._get_objects() + self.bottle = SceneObject( + ObjectConfig( + name="bottle", + mjcf_path="objects/omniverse/locomanip/jug_a01/model.xml", + static=False, + scale=0.6, + sampler_config=SamplingConfig( + x_range=np.array([-0.14, -0.06]), + y_range=np.array([-0.08, 0.08]), + rotation=np.array([-np.pi, np.pi]), + reference=ReferenceConfig(self.shelf, spawn_id=1), + ), + ) + ) + return [self.shelf, self.bottle] + + +class LMNavPickBottleShelfLow(LMNavPickBottleShelf): + def _get_objects(self) -> list[SceneObject]: + super()._get_objects() + self.bottle = SceneObject( + ObjectConfig( + name="bottle", + mjcf_path="objects/omniverse/locomanip/jug_a01/model.xml", + static=False, + scale=0.6, + sampler_config=SamplingConfig( + x_range=np.array([-0.14, -0.06]), + y_range=np.array([-0.08, 0.08]), + rotation=np.array([-np.pi, np.pi]), + reference=ReferenceConfig(self.shelf, spawn_id=1), + ), + ) + ) + return [self.shelf, self.bottle] + + +class LMPnPBottleToPlate(LMPnPBottle): + def _get_objects(self) -> list[SceneObject]: + super()._get_objects() + self.plate = SceneObject( + ObjectConfig( + name="plate", + mjcf_path="objects/omniverse/locomanip/plate_1/model.xml", + scale=1.0, + static=True, + sampler_config=SamplingConfig( + x_range=np.array([-0.2 - 0.08, -0.2 + 0.04]), + y_range=np.array([-0.08, 0.08]), + rotation=np.array([-np.pi, np.pi]), + reference=ReferenceConfig(self.table_target), + ), + ) + ) + return [self.table, self.table_target, self.bottle, self.plate] + + def _get_success_criteria(self) -> SuccessCriteria: + return AllCriteria( + IsUpright(self.bottle, symmetric=True), IsInContact(self.bottle, self.plate) + ) + + def _get_instruction(self) -> str: + return "Pick up the bottle and place it on the plate." + + def get_object(self): + return dict( + bottle=dict(obj_name=self.bottle.mj_obj.root_body, obj_type="body"), + plate=dict(obj_name=self.plate.mj_obj.root_body, obj_type="body"), + ) + + def get_subtask_term_signals(self): + obj_z = self.sim.data.body_xpos[self.obj_body_id(self.bottle.mj_obj.name)][2] + target_table_pos = self.sim.data.body_xpos[self.obj_body_id(self.table_target.mj_obj.name)] + target_table_z = target_table_pos[2] + self.table_target.mj_obj.top_offset[2] + return dict(obj_off_table=int(obj_z - target_table_z > self.LIFT_OFFSET)) + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + task.task_spec_0.subtask_1 = dict( + object_ref="bottle", + subtask_term_signal="obj_off_table", + subtask_term_offset_range=(5, 10), + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + # Second subtask for placing on plate + task.task_spec_0.subtask_2 = dict( + object_ref="plate", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() + + +class LMPnPAppleToPlate(LMPnPBottleToPlate): + def _get_objects(self) -> list[SceneObject]: + super()._get_objects() + self.apple = SceneObject( + ObjectConfig( + name="apple", + mjcf_path="objects/omniverse/locomanip/apple_0/model.xml", + static=False, + scale=1.0, + sampler_config=SamplingConfig( + x_range=np.array([-0.08, 0.04]), + y_range=np.array([-0.08, 0.08]), + rotation=np.array([-np.pi, np.pi]), + reference_pos=np.array([0.4, 0, self.table.mj_obj.top_offset[2]]), + ), + ) + ) + return [self.table, self.table_target, self.apple, self.plate] + + def _get_success_criteria(self) -> SuccessCriteria: + return IsInContact(self.apple, self.plate) + + def _get_instruction(self) -> str: + return "pick up the apple, walk left and place the apple on the plate." + + def get_object(self): + return dict( + apple=dict(obj_name=self.apple.mj_obj.root_body, obj_type="body"), + plate=dict(obj_name=self.plate.mj_obj.root_body, obj_type="body"), + ) + + def get_subtask_term_signals(self): + obj_z = self.sim.data.body_xpos[self.obj_body_id(self.apple.mj_obj.name)][2] + target_table_pos = self.sim.data.body_xpos[self.obj_body_id(self.table_target.mj_obj.name)] + target_table_z = target_table_pos[2] + self.table_target.mj_obj.top_offset[2] + return dict(obj_off_table=int(obj_z - target_table_z > self.LIFT_OFFSET)) + + @staticmethod + def task_config(): + task = DexMGConfigHelper.AttrDict() + task.task_spec_0.subtask_1 = dict( + object_ref="apple", + subtask_term_signal="obj_off_table", + subtask_term_offset_range=(5, 10), + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + # Second subtask for placing on plate + task.task_spec_0.subtask_2 = dict( + object_ref="plate", + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + task.task_spec_1.subtask_1 = dict( + object_ref=None, + subtask_term_signal=None, + subtask_term_offset_range=None, + selection_strategy="random", + selection_strategy_kwargs=None, + action_noise=0.05, + num_interpolation_steps=5, + num_fixed_steps=0, + apply_noise_during_interpolation=False, + ) + return task.to_dict() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_dc.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_dc.py new file mode 100644 index 0000000000000000000000000000000000000000..465df91a6b6a7c4e7791d263e61bff0959ee2103 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_dc.py @@ -0,0 +1,15 @@ +from robocasa import ( + LMNavPickBottle, + LMPnPAppleToPlate, +) +from robocasa.models.scenes.lab_arena import LabArena + + +class LabEnvMixin: + MUJOCO_ARENA_CLS = LabArena + + +class LMNavPickBottleDC(LabEnvMixin, LMNavPickBottle): ... + + +class LMPnPAppleToPlateDC(LabEnvMixin, LMPnPAppleToPlate): ... diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_pnp.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_pnp.py new file mode 100644 index 0000000000000000000000000000000000000000..e526417c773b8ed3367bf3a065367582aa86517c --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/environments/locomanipulation/locomanip_pnp.py @@ -0,0 +1,99 @@ +import numpy as np +from robocasa.environments.locomanipulation.locomanip import LMFactoryEnv +from robocasa.utils.scene.configs import ( + ObjectConfig, + ReferenceConfig, + SamplingConfig, + SceneHandedness, + SceneScaleConfig, +) +from robocasa.utils.scene.scene import SceneObject +from robocasa.utils.scene.success_criteria import ( + AllCriteria, + IsInContact, + IsUpright, + SuccessCriteria, +) + + +class LMBottlePnP(LMFactoryEnv): + SCENE_SCALE = SceneScaleConfig(planar_scale=(1, 1), handedness=SceneHandedness.RIGHT) + + def _get_objects(self) -> list[SceneObject]: + self.table_target = SceneObject( + ObjectConfig( + name="table_target", + mjcf_path="objects/omniverse/locomanip/factory_ergo_table/model.xml", + static=True, + sampler_config=SamplingConfig( + x_range=np.array([-0.02, 0.02]), + y_range=np.array([-0.02, 0.02]), + reference_pos=np.array([1.2, 0.8, 0]), + rotation=np.array([np.pi, np.pi]), + ), + ) + ) + self.table_origin = SceneObject( + ObjectConfig( + name="table_origin", + mjcf_path="objects/omniverse/locomanip/factory_ergo_table/model.xml", + static=True, + sampler_config=SamplingConfig( + x_range=np.array([-0.02, 0.02]), + y_range=np.array([-0.02, 0.02]), + reference_pos=np.array([1.2, -0.8, 0]), + rotation=np.array([np.pi, np.pi]), + ), + ) + ) + self.bottle = SceneObject( + ObjectConfig( + name="obj", + mjcf_path="objects/omniverse/locomanip/jug_a01/model.xml", + static=False, + scale=0.6, + sampler_config=SamplingConfig( + x_range=np.array([-0.4, -0.35]), + y_range=np.array([-0.1, 0.1]), + rotation=np.array([-np.pi, np.pi]), + reference=ReferenceConfig(self.table_origin), + ), + ) + ) + return [self.table_origin, self.table_target, self.bottle] + + def _get_success_criteria(self) -> SuccessCriteria: + return AllCriteria(IsInContact(self.bottle, self.table_target), IsUpright(self.bottle)) + + def _get_instruction(self) -> str: + return "Pick up the bottle from one table and place it on the other." + + +class LMBoxPnP(LMBottlePnP): + SCENE_SCALE = SceneScaleConfig(planar_scale=(1, 1), handedness=SceneHandedness.RIGHT) + + def _get_objects(self) -> list[SceneObject]: + super()._get_objects() + self.box = SceneObject( + ObjectConfig( + name="obj", + mjcf_path="objects/omniverse/locomanip/cardbox_a1/model.xml", + static=False, + scale=0.7, + density=1, + friction=(2, 1, 1), + sampler_config=SamplingConfig( + x_range=np.array([-0.35, -0.3]), + y_range=np.array([-0.1, 0.1]), + rotation=np.array([np.pi * 0.9, np.pi * 1.1]), + reference=ReferenceConfig(self.table_origin), + ), + ) + ) + return [self.table_origin, self.table_target, self.box] + + def _get_success_criteria(self) -> SuccessCriteria: + return AllCriteria(IsInContact(self.box, self.table_target), IsUpright(self.box)) + + def _get_instruction(self) -> str: + return "Pick up the box from one table and place it on the other." diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/examples/third_party_controller/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/examples/third_party_controller/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/examples/third_party_controller/default_mink_ik_g1_gear_wbc.json b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/examples/third_party_controller/default_mink_ik_g1_gear_wbc.json new file mode 100644 index 0000000000000000000000000000000000000000..bb76a83d4d54257bbb05d9542872da569deefacf --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/examples/third_party_controller/default_mink_ik_g1_gear_wbc.json @@ -0,0 +1,113 @@ +{ + "type": "HYBRID_WHOLE_BODY_MINK_IK", + "composite_controller_specific_configs": { + "ref_name": ["gripper0_right_grip_site", "gripper0_left_grip_site"], + "interpolation": null, + "actuation_part_names": ["torso", "left", "right"], + "external_part_names": ["legs"], + "max_dq": 4, + "ik_pseudo_inverse_damping": 5e-2, + "ik_integration_dt": 1e-1, + "ik_input_type": "absolute", + "ik_input_ref_frame": "base", + "ik_input_rotation_repr": "axis_angle", + "verbose": false, + "ik_posture_weights": { + "robot0_waist_yaw_joint": 100.0, + "robot0_waist_roll_joint": 200.0, + "robot0_waist_pitch_joint": 400.0, + "robot0_left_shoulder_pitch_joint": 4.0, + "robot0_left_shoulder_roll_joint": 3.0, + "robot0_left_shoulder_yaw_joint": 2.0, + "robot0_left_elbow_joint": 1.0, + "robot0_right_shoulder_pitch_joint": 4.0, + "robot0_right_shoulder_roll_joint": 3.0, + "robot0_right_shoulder_yaw_joint": 2.0, + "robot0_right_elbow_joint": 1.0 + }, + "ik_hand_pos_cost": 10.0, + "ik_hand_ori_cost": 5, + "use_joint_angle_action_input": false + }, + "body_parts": { + "legs": { + "type" : "JOINT_POSITION", + "input_max": 100, + "input_min": -100, + "input_type": "absolute", + "output_max": 100, + "output_min": -100, + "kd": [2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2], + "kv": 0, + "kp": [150, 150, 150, 300, 40, 40, 150, 150, 150, 200, 40, 40], + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "use_torque_compensation": false, + "desired_torque_as_acceleration": false + }, + "arms": { + "left": { + "type" : "JOINT_POSITION", + "input_max": 100, + "input_min": -100, + "input_type": "absolute", + "output_max": 100, + "output_min": -100, + "kd": [5.0, 5.0, 2.0, 2.0, 2.0, 2.0, 2.0], + "kp": [100, 100, 40, 40, 20, 20, 20], + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + }, + "use_torque_compensation": false, + "desired_torque_as_acceleration": false + }, + "right": { + "type" : "JOINT_POSITION", + "input_max": 100, + "input_min": -100, + "input_type": "absolute", + "output_max": 100, + "output_min": -100, + "kd": [5.0, 5.0, 2.0, 2.0, 2.0, 2.0, 2.0], + "kp": [100, 100, 40, 40, 20, 20, 20], + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + }, + "use_torque_compensation": false, + "desired_torque_as_acceleration": false + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 100, + "input_min": -100, + "input_type": "absolute", + "output_max": 100, + "output_min": -100, + "kd": 5.0, + "kp": 250.0, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "use_torque_compensation": false, + "desired_torque_as_acceleration": false + }, + "base": { + "type": "JOINT_VELOCITY_AND_POSITION", + "interpolation": "null" + } + } +} diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/examples/third_party_controller/default_mink_ik_g1_gear_wbc_gc.json b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/examples/third_party_controller/default_mink_ik_g1_gear_wbc_gc.json new file mode 100644 index 0000000000000000000000000000000000000000..7362f22594d89787177c096bce8cb947f21fa60a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/examples/third_party_controller/default_mink_ik_g1_gear_wbc_gc.json @@ -0,0 +1,117 @@ +{ + "type": "HYBRID_WHOLE_BODY_MINK_IK", + "composite_controller_specific_configs": { + "ref_name": ["gripper0_right_grip_site", "gripper0_left_grip_site"], + "interpolation": null, + "actuation_part_names": ["torso", "left", "right"], + "external_part_names": ["legs"], + "max_dq": 4, + "ik_pseudo_inverse_damping": 5e-2, + "ik_integration_dt": 1e-1, + "ik_input_type": "absolute", + "ik_input_ref_frame": "base", + "ik_input_rotation_repr": "axis_angle", + "verbose": false, + "ik_posture_weights": { + "robot0_waist_yaw_joint": 100.0, + "robot0_waist_roll_joint": 200.0, + "robot0_waist_pitch_joint": 400.0, + "robot0_left_shoulder_pitch_joint": 4.0, + "robot0_left_shoulder_roll_joint": 3.0, + "robot0_left_shoulder_yaw_joint": 2.0, + "robot0_left_elbow_joint": 1.0, + "robot0_right_shoulder_pitch_joint": 4.0, + "robot0_right_shoulder_roll_joint": 3.0, + "robot0_right_shoulder_yaw_joint": 2.0, + "robot0_right_elbow_joint": 1.0 + }, + "ik_hand_pos_cost": 10.0, + "ik_hand_ori_cost": 5, + "use_joint_angle_action_input": false + }, + "body_parts": { + "legs": { + "type" : "JOINT_POSITION", + "input_max": 100, + "input_min": -100, + "input_type": "absolute", + "output_max": 100, + "output_min": -100, + "kd": [2, 2, 2, 4, 2, 2, 2, 2, 2, 4, 2, 2], + "kv": 0, + "kp": [150, 150, 150, 300, 40, 40, 150, 150, 150, 200, 40, 40], + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "use_torque_compensation": false, + "use_external_torque_compensation": true, + "desired_torque_as_acceleration": false + }, + "arms": { + "left": { + "type" : "JOINT_POSITION", + "input_max": 100, + "input_min": -100, + "input_type": "absolute", + "output_max": 100, + "output_min": -100, + "kd": [5.0, 5.0, 2.0, 2.0, 2.0, 2.0, 2.0], + "kp": [100, 100, 40, 40, 20, 20, 20], + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + }, + "use_torque_compensation": false, + "use_external_torque_compensation": true, + "desired_torque_as_acceleration": false + }, + "right": { + "type" : "JOINT_POSITION", + "input_max": 100, + "input_min": -100, + "input_type": "absolute", + "output_max": 100, + "output_min": -100, + "kd": [5.0, 5.0, 2.0, 2.0, 2.0, 2.0, 2.0], + "kp": [100, 100, 40, 40, 20, 20, 20], + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + }, + "use_torque_compensation": false, + "use_external_torque_compensation": true, + "desired_torque_as_acceleration": false + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 100, + "input_min": -100, + "input_type": "absolute", + "output_max": 100, + "output_min": -100, + "kd": 5.0, + "kp": 250.0, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "use_torque_compensation": false, + "use_external_torque_compensation": true, + "desired_torque_as_acceleration": false + }, + "base": { + "type": "JOINT_VELOCITY_AND_POSITION", + "interpolation": "null" + } + } +} diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/macros.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/macros.py new file mode 100644 index 0000000000000000000000000000000000000000..048a800fa003f38f8267561a2fcb69fdf6922cb9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/macros.py @@ -0,0 +1,32 @@ +""" +Macro settings that can be imported and toggled. Internally, specific parts of the codebase rely on these settings +for determining core functionality. + +To make sure global reference is maintained, should import these settings as: + +`import robocasa.macros as macros` +""" + +SHOW_SITES = False + +# whether to print debugging information +VERBOSE = False + +# Spacemouse settings. Used by SpaceMouse class in robosuite/devices/spacemouse.py +SPACEMOUSE_VENDOR_ID = 9583 +SPACEMOUSE_PRODUCT_ID = 50741 + +DATASET_BASE_PATH = None + +try: + from robocasa.macros_private import * +except ImportError: + from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + + import robocasa + + ROBOSUITE_DEFAULT_LOGGER.warning("No private macro file found!") + ROBOSUITE_DEFAULT_LOGGER.warning("It is recommended to use a private macro file") + ROBOSUITE_DEFAULT_LOGGER.warning( + "To setup, run: python {}/scripts/setup_macros.py".format(robocasa.__path__[0]) + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb69cbf75946578508a38c3d3e60381e68c4091 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/__init__.py @@ -0,0 +1,3 @@ +import os + +assets_root = os.path.join(os.path.dirname(__file__), "assets") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/gear_factory/gear_factory.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/gear_factory/gear_factory.xml new file mode 100644 index 0000000000000000000000000000000000000000..92f2cd4f40f5c8e69dfe34f5ee17086bdd4618b8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/gear_factory/gear_factory.xml @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/gear_lab/gear_lab.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/gear_lab/gear_lab.xml new file mode 100644 index 0000000000000000000000000000000000000000..0e52097c44c7930ade36fcd0111b0cd986975d3e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/gear_lab/gear_lab.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/ground_arena.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/ground_arena.xml new file mode 100644 index 0000000000000000000000000000000000000000..f5460ee1bca1e304270e974d29f6dd5d4ef266ae --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/arenas/ground_arena.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/apple_0/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/apple_0/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..78f4bb81b80bed087d906a94d26acdab0d25c92f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/apple_0/model.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_a1/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_a1/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..afd903b7ddea55e28be83e8b8001a1fcba9add26 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_a1/model.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_b1/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_b1/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..894de6922acacd8a27972e5174f6eb362d3ba1c6 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_b1/model.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_c1/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_c1/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..0b1e0377c5188fbd5ae48e8e34ac8f639687f664 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_c1/model.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_d1/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_d1/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..528fd9ec71f37444335c94604d8cac886a934c6e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/cardbox_d1/model.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/clock_0/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/clock_0/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..535a3afc327a14831b1197e6879967f8ca98e511 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/clock_0/model.xml @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/control_box/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/control_box/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..3ea361579c90e42ff1bdfe892593de105585b0c6 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/control_box/model.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/control_conveyorbelt_a08/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/control_conveyorbelt_a08/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..28678bd2d3fa0f3473882e1da3fdb0db3bee8aab --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/control_conveyorbelt_a08/model.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/dock_board_a12/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/dock_board_a12/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..fac18f8bd78bc0661f53b4c4bb73ea610075f185 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/dock_board_a12/model.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/factory_ergo_table/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/factory_ergo_table/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..c1a038e04c2676b375cda7d90e4eb67c65caccf7 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/factory_ergo_table/model.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/jug_a01/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/jug_a01/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..6b5d4c05aeb86a28bf2c458118c93d6a01d396f9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/jug_a01/model.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..f0e25213108c69e467a652ce4357f8dbdf06754b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf/model.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf_board/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf_board/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..e08ea1083aca6a336426d90f54ace052a3e03210 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf_board/model.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf_cabinet/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf_cabinet/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..9e48631e3a7afacb93ad54f1af5945f672038441 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_shelf_cabinet/model.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_table/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_table/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..864c3beba8762291b807991af449c56b46d300d8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/lab_table/model.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/longbox_a08/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/longbox_a08/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..981b2af4f6aa8c607c66cb415559162fd1151b7a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/longbox_a08/model.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/longbox_a09/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/longbox_a09/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..b3e4d5d2ee06e27698a5ecafa5dd06cc66bbf220 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/longbox_a09/model.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/mobile_shelving_cart/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/mobile_shelving_cart/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..67382df3f8a8ea3fe7067555cc536035141995fd --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/mobile_shelving_cart/model.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/pallet_b1/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/pallet_b1/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..baa6b1da8ae8c1398a7f110add5028533fa4d997 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/pallet_b1/model.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/pallet_c1/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/pallet_c1/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..a69ffea21b94414492597ff8cc9f52e559fbea0e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/pallet_c1/model.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/plate_1/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/plate_1/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..45048c4b36e0fb267124a0394ae469f49d5aa469 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/plate_1/model.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/rubix_cube_1/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/rubix_cube_1/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..47722c9a0a395b66b1ee027864f7dac90f0664e5 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/rubix_cube_1/model.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/shelf_a12/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/shelf_a12/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..21f81ccfdbb6095119e7d82c54aa83771c9297a1 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/shelf_a12/model.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/target_zone/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/target_zone/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..acee67cb74a300eb306c0fe69ca778c3f615599b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/target_zone/model.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/tote_f01/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/tote_f01/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..91cde7155f20d858bc8a5a9de97cddaac781cb15 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/tote_f01/model.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/tote_f02/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/tote_f02/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..f291a4875eef5c36345ebb9e068ce90977a2f049 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/tote_f02/model.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/workshop_trolley_a01/model.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/workshop_trolley_a01/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..5b8a39f789c98b4a4e0e805cb3bf5f075a8e5778 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/objects/omniverse/locomanip/workshop_trolley_a01/model.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_29dof_rev_1_0.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_29dof_rev_1_0.xml new file mode 100644 index 0000000000000000000000000000000000000000..da74e298f951a2e5eff64938c8a5c66d07313902 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_29dof_rev_1_0.xml @@ -0,0 +1,431 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_threefinger_left_hand.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_threefinger_left_hand.xml new file mode 100644 index 0000000000000000000000000000000000000000..4048fc201b39f3b1b637da54748e936a633a1e1f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_threefinger_left_hand.xml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_threefinger_right_hand.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_threefinger_right_hand.xml new file mode 100644 index 0000000000000000000000000000000000000000..88ba6386752ee2a442c6fa72fbee1c7bb632e012 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/assets/robots/unitree_g1/g1_threefinger_right_hand.xml @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/grippers/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/grippers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e7f360f388df0530c8bda2a20806f78d56d8b17 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/grippers/__init__.py @@ -0,0 +1 @@ +from .g1_threefinger_hands import G1ThreeFingerLeftHand, G1ThreeFingerRightHand diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/grippers/g1_threefinger_hands.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/grippers/g1_threefinger_hands.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9aaa347912bc6d779d6ee9acd6a0d8c636c7cc --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/grippers/g1_threefinger_hands.py @@ -0,0 +1,170 @@ +""" +Dexterous hands for GR1 robot. +""" + +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion +from robosuite.utils.mjcf_utils import find_parent, xml_path_completion +from robosuite.models.grippers import register_gripper + +import robocasa.models + + +@register_gripper +class G1ThreeFingerLeftHand(GripperModel): + """ + Dexterous left hand of G1 robot + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__( + xml_path_completion( + "robots/unitree_g1/g1_threefinger_left_hand.xml", + root=robocasa.models.assets_root, + ), + idn=idn, + ) + + def format_action(self, action): + # grasp = action[0] + # action = [0] * 7 + # if grasp > 0: + # # note that the sign of the action is opposite of the right hand + # action[1] = action[2] = grasp + # action[3] = action[4] = action[5] = action[6] = -grasp + + return action + + @property + def init_qpos(self): + return np.array([0.0] * 7) + + @property + def grasp_qpos(self): + return { + -1: np.array([0.0] * 7), + 1: np.array([0, 1, 1.25, -1.2, -1.2, -1.2, -1.2]), + } + + @property + def speed(self): + return 0.15 + + @property + def dof(self): + return 7 # 12 + + @property + def _important_geoms(self): + return { + "left_finger": [ + "left_hand_thumb_0_link_col", + "left_hand_thumb_1_link_col", + "left_hand_thumb_2_link_col", + "left_hand_middle_0_link_col", + "left_hand_middle_1_link_col", + "left_hand_index_0_link_col", + "left_hand_index_1_link_col", + ], + "right_finger": [ + "left_hand_thumb_0_link_col", + "left_hand_thumb_1_link_col", + "left_hand_thumb_2_link_col", + "left_hand_middle_0_link_col", + "left_hand_middle_1_link_col", + "left_hand_index_0_link_col", + "left_hand_index_1_link_col", + ], + "left_fingerpad": [ + "left_hand_thumb_2_link_col", + "left_hand_middle_1_link_col", + "left_hand_index_1_link_col", + ], + "right_fingerpad": [ + "left_hand_thumb_2_link_col", + "left_hand_middle_1_link_col", + "left_hand_index_1_link_col", + ], + } + + +@register_gripper +class G1ThreeFingerRightHand(GripperModel): + """ + Dexterous right hand of G1 robot + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__( + xml_path_completion( + "robots/unitree_g1/g1_threefinger_right_hand.xml", + root=robocasa.models.assets_root, + ), + idn=idn, + ) + + def format_action(self, action): + # grasp = action[0] + # action = [0] * 7 + # if grasp > 0: + # action[1] = action[2] = -grasp + # action[3] = action[4] = action[5] = action[6] = grasp + return action + + @property + def init_qpos(self): + return np.array([0.0] * 7) + + @property + def grasp_qpos(self): + return { + -1: np.array([0.0] * 7), + 1: np.array([0, -1, -1.25, 1.2, 1.2, 1.2, 1.2]), + } + + @property + def speed(self): + return 0.15 + + @property + def dof(self): + return 7 + + @property + def _important_geoms(self): + return { + "left_finger": [ + "right_hand_thumb_0_link_col", + "right_hand_thumb_1_link_col", + "right_hand_thumb_2_link_col", + "right_hand_middle_0_link_col", + "right_hand_middle_1_link_col", + "right_hand_index_0_link_col", + "right_hand_index_1_link_col", + ], + "right_finger": [ + "right_hand_thumb_0_link_col", + "right_hand_thumb_1_link_col", + "right_hand_thumb_2_link_col", + "right_hand_middle_0_link_col", + "right_hand_middle_1_link_col", + "right_hand_index_0_link_col", + "right_hand_index_1_link_col", + ], + "left_fingerpad": [ + "right_hand_thumb_2_link_col", + "right_hand_middle_1_link_col", + "right_hand_index_1_link_col", + ], + "right_fingerpad": [ + "right_hand_thumb_2_link_col", + "right_hand_middle_1_link_col", + "right_hand_index_1_link_col", + ], + } diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e58d64f52731abfe20fb3bd9fdfce135861dd58 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/__init__.py @@ -0,0 +1,13 @@ +from robosuite.models.objects import * +from robosuite.utils import * + +from .xml_objects import ( + CoffeeMachinePodObject, + CoffeeMachineBodyObject, + CoffeeMachineLidObject, + CoffeeMachineBaseObject, + DrawerObject, + LongDrawerObject, +) +from .composite import * +from .composite_body import * diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ac011def690701e1ba67ab06200f8a40600d8cc --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/__init__.py @@ -0,0 +1,6 @@ +from .box_pattern_object import BoxPatternObject +from .needle import NeedleObject +from .ring_tripod import RingTripodObject +from .bin import Bin +from .lid import Lid +from .pot_with_handles import PotWithHandlesObject diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/bin.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/bin.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e95a6e1d0ec0a2f5beb146ab132b65e650644e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/bin.py @@ -0,0 +1,205 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import CustomMaterial, add_to_dict + + +class Bin(CompositeObject): + """ + Generates a four-walled bin container with an open top. + Args: + name (str): Name of this Bin object + bin_size (3-array): (x,y,z) full size of bin + wall_thickness (float): How thick to make walls of bin + transparent_walls (bool): If True, walls will be semi-translucent + friction (3-array or None): If specified, sets friction values for this bin. None results in default values + density (float): Density value to use for all geoms. Defaults to 1000 + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values + material: If specified, use this material + upside_down (bool): if True, construct and initialize the Bin so the bottom geom is at the top + """ + + def __init__( + self, + name, + bin_size=(0.3, 0.3, 0.15), + wall_thickness=0.01, + transparent_walls=True, + friction=None, + density=1000.0, + use_texture=True, + rgba=(0.2, 0.1, 0.0, 1.0), + material=None, + upside_down=False, + add_second_base=False, + transparent_base=False, + ): + # Set name + self._name = name + + # Set object attributes + self.bin_size = np.array(bin_size) + self.wall_thickness = wall_thickness + self.transparent_walls = transparent_walls + self.friction = friction if friction is None else np.array(friction) + self.density = density + self.use_texture = use_texture + self.rgba = rgba + self.bin_mat_name = "dark_wood_mat" + + # if box should be constructed and initialized upside down + self.upside_down = upside_down + + # if box should have a second base (so it will be a closed box) + self.add_second_base = add_second_base + if self.add_second_base: + assert not self.upside_down + + # if base(s) should be transparent + self.transparent_base = transparent_base + + self.has_material = material is not None + if self.has_material: + assert isinstance(material, CustomMaterial) + self.material = material + self.bin_mat_name = self.material.mat_attrib["name"] + else: + # default material + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + bin_mat = CustomMaterial( + texture="WoodDark", + tex_name="dark_wood", + mat_name=self.bin_mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.material = bin_mat + + # Element references + self._base_geom = "base" + if self.add_second_base: + self._second_base_geom = "base2" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + self.append_material(self.material) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": self.bin_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + "density": self.density, + } + obj_args = {} + + # Base(s) + base_geom_loc = (0, 0, -(self.bin_size[2] - self.wall_thickness) / 2) + if self.upside_down: + base_geom_loc = ( + base_geom_loc[0], + base_geom_loc[1], + -1.0 * base_geom_loc[2], + ) + if self.transparent_base: + base_rgba = (1.0, 1.0, 1.0, 0.3) + base_mat = None + else: + base_rgba = None if self.use_texture else self.rgba + base_mat = self.bin_mat_name if self.use_texture else None + + base_geom_names = [self._base_geom] + base_geom_locs = [base_geom_loc] + if self.add_second_base: + base_geom_names.append(self._second_base_geom) + base_geom_locs.append((base_geom_loc[0], base_geom_loc[1], -1.0 * base_geom_loc[2])) + + for base_g_name, base_g_loc in zip(base_geom_names, base_geom_locs): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=base_g_loc, + geom_quats=(1, 0, 0, 0), + geom_sizes=( + np.array((self.bin_size[0], self.bin_size[1], self.wall_thickness)) + - np.array((self.wall_thickness, self.wall_thickness, 0)) + ) + / 2, + geom_names=base_g_name, + geom_rgbas=base_rgba, + geom_materials=base_mat, + geom_frictions=self.friction, + ) + + # Walls + x_vals = np.array( + [ + 0, + -(self.bin_size[0] - self.wall_thickness) / 2, + 0, + (self.bin_size[0] - self.wall_thickness) / 2, + ] + ) + y_vals = np.array( + [ + -(self.bin_size[1] - self.wall_thickness) / 2, + 0, + (self.bin_size[1] - self.wall_thickness) / 2, + 0, + ] + ) + w_vals = np.array([self.bin_size[0], self.bin_size[1], self.bin_size[0], self.bin_size[1]]) + r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi]) + if self.transparent_walls: + wall_rgba = (1.0, 1.0, 1.0, 0.3) + wall_mat = None + else: + wall_rgba = None if self.use_texture else self.rgba + wall_mat = self.bin_mat_name if self.use_texture else None + for i, (x, y, w, r) in enumerate(zip(x_vals, y_vals, w_vals, r_vals)): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(x, y, 0), + geom_quats=T.convert_quat(T.axisangle2quat(np.array([0, 0, r])), to="wxyz"), + geom_sizes=(self.wall_thickness / 2, w / 2, self.bin_size[2] / 2), + geom_names=f"wall{i}", + geom_rgbas=wall_rgba, + geom_materials=wall_mat, + geom_frictions=self.friction, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def base_geoms(self): + """ + Returns: + list of str: geom names corresponding to bin base + """ + return [self.correct_naming(self._base_geom)] diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/box_pattern_object.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/box_pattern_object.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a3a2129a7ff3c7adf32b00557bacad423f633e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/box_pattern_object.py @@ -0,0 +1,124 @@ +import numpy as np + +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import add_to_dict +import robosuite.utils.transform_utils as T + + +class BoxPatternObject(CompositeObject): + """ + Generates shapes by using a pattern of unit-size boxes. + + Args: + name (str): Name of this Needle object + """ + + def __init__( + self, + name, + unit_size, + pattern, + rgba=None, + material=None, + density=100.0, + # solref=[0.02, 1.], + # solimp=[0.9, 0.95, 0.001], + friction=None, + ): + """ + Args: + unit_size (3d array / list): size of each unit block in each dimension + + pattern (3d array / list): array of normalized sizes specifying the + geometry of the shape. A "0" indicates the absence of a cube and + a "1" indicates the presence of a full unit block. The dimensions + correspond to z, x, and y respectively. + """ + self._name = name + self.rgba = rgba + self.material = material + self.density = density + self.friction = friction + + # number of blocks in z, x, and y + self.pattern = np.array(pattern) + self.nz, self.nx, self.ny = self.pattern.shape + self.unit_size = unit_size + self.total_size = [ + self.nx * unit_size[0], + self.ny * unit_size[1], + self.nz * unit_size[2], + ] + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + if self.material is not None: + self.append_material(self.material) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": self.total_size, + "name": self.name, + "locations_relative_to_center": False, + "obj_types": "all", + "density": self.density, + } + obj_args = {} + + geom_locations = [] + geom_sizes = [] + geom_names = [] + nz, nx, ny = self.pattern.shape + for k in range(nz): + for i in range(nx): + for j in range(ny): + if self.pattern[k, i, j] > 0: + geom_sizes.append( + [ + self.unit_size[0], + self.unit_size[1], + self.unit_size[2], + ] + ) + geom_locations.append( + [ + i * 2.0 * self.unit_size[0], + j * 2.0 * self.unit_size[1], + k * 2.0 * self.unit_size[2], + ] + ) + geom_names.append("{}_{}_{}".format(k, i, j)) + + # geom_rgbas = [rgba for _ in geom_locations] + # geom_frictions = [friction for _ in geom_locations] + for i in range(len(geom_locations)): + add_to_dict( + dic=obj_args, + geom_types="box", + # needle geom needs to be offset from boundary in (x, z) + geom_locations=tuple(geom_locations[i]), + geom_quats=(1, 0, 0, 0), + geom_sizes=tuple(geom_sizes[i]), + geom_names=geom_names[i], + geom_rgbas=self.rgba, + geom_materials=self.material.name if self.material is not None else None, + geom_frictions=None, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/lid.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/lid.py new file mode 100644 index 0000000000000000000000000000000000000000..3eb602bd9308bbe387e4648939d61c00c32f5520 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/lid.py @@ -0,0 +1,136 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import CustomMaterial, add_to_dict + + +class Lid(CompositeObject): + """ + Generates a square lid with a simple handle. + Args: + name (str): Name of this Lid object + lid_size (3-array): (length, width, thickness) of lid + handle_size (3-array): (thickness, length, height) of handle + transparent (bool): If True, lid will be semi-translucent + friction (3-array or None): If specified, sets friction values for this lid. None results in default values + density (float): Density value to use for all geoms. Defaults to 1000 + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values + """ + + def __init__( + self, + name, + lid_size=(0.3, 0.3, 0.01), + handle_size=(0.02, 0.08, 0.03), + transparent=True, + friction=None, + density=250.0, + use_texture=True, + rgba=(0.2, 0.1, 0.0, 1.0), + ): + # Set name + self._name = name + + # Set object attributes + self.lid_size = np.array(lid_size) + self.handle_size = np.array(handle_size) + self.transparent = transparent + self.friction = friction if friction is None else np.array(friction) + self.density = density + self.use_texture = use_texture + self.rgba = rgba + self.lid_mat_name = "dark_wood_mat" + + # Element references + self._handle_geom = "handle" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + lid_mat = CustomMaterial( + texture="WoodDark", + tex_name="dark_wood", + mat_name=self.lid_mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(lid_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + full_height = self.lid_size[2] + self.handle_size[2] + full_size = np.array([self.lid_size[0], self.lid_size[1], full_height]) + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": full_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + } + obj_args = {} + + # Top + if self.transparent: + top_rgba = (1.0, 1.0, 1.0, 0.3) + top_mat = None + else: + top_rgba = None if self.use_texture else self.rgba + top_mat = self.lid_mat_name if self.use_texture else None + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, (-full_size[2] + self.lid_size[2]) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array((full_size[0], full_size[1], self.lid_size[2])) / 2, + geom_names="top", + geom_rgbas=top_rgba, + geom_materials=top_mat, + geom_frictions=self.friction, + density=self.density, + ) + + # Handle + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, (full_size[2] - self.handle_size[2]) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=self.handle_size / 2, + geom_names=self._handle_geom, + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.lid_mat_name if self.use_texture else None, + geom_frictions=self.friction, + density=self.density * 2, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def handle_geoms(self): + """ + Returns: + list of str: geom names corresponding to lid handle + """ + return [self.correct_naming(self._handle_geom)] diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/needle.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/needle.py new file mode 100644 index 0000000000000000000000000000000000000000..9dc6bb1fea50a76ba8c681643354596a7676e797 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/needle.py @@ -0,0 +1,109 @@ +import numpy as np + +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import add_to_dict, CustomMaterial +import robosuite.utils.transform_utils as T + + +class NeedleObject(CompositeObject): + """ + Generates a needle with a handle (used in Threading task) + + Args: + name (str): Name of this Needle object + """ + + def __init__( + self, + name, + ): + + ### TODO: make this object more general (with more args and configuration options) later ### + + # Set object attributes + self._name = name + self.needle_mat_name = "darkwood_mat" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + needle_mat = CustomMaterial( + texture="WoodDark", + tex_name="darkwood", + mat_name="darkwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(needle_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": [0.02, 0.08, 0.02], + "name": self.name, + "locations_relative_to_center": False, + "obj_types": "all", + "density": 100.0, + } + obj_args = {} + + # make a skinny needle object with a large handle + needle_size = [0.005, 0.06, 0.005] + handle_size = [0.02, 0.02, 0.02] + + # Needle + add_to_dict( + dic=obj_args, + geom_types="box", + # needle geom needs to be offset from boundary in (x, z) + geom_locations=( + (handle_size[0] - needle_size[0]), + 0.0, + (handle_size[2] - needle_size[2]), + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=tuple(needle_size), + geom_names="needle", + geom_rgbas=None, + geom_materials=self.needle_mat_name, + # make the needle low friction to ensure easy insertion + geom_frictions=(0.3, 5e-3, 1e-4), + ) + + # Handle + add_to_dict( + dic=obj_args, + geom_types="box", + # handle geom needs to be offset in y + geom_locations=(0.0, 2.0 * needle_size[1], 0.0), + geom_quats=(1, 0, 0, 0), + geom_sizes=tuple(handle_size), + geom_names="handle", + geom_rgbas=None, + geom_materials=self.needle_mat_name, + geom_frictions=None, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/pot_with_handles.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/pot_with_handles.py new file mode 100644 index 0000000000000000000000000000000000000000..0aebf356375f01a1847043fff262b9eecd32204e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/pot_with_handles.py @@ -0,0 +1,396 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import ( + BLUE, + GREEN, + RED, + CustomMaterial, + add_to_dict, + array_to_string, +) + + +class PotWithHandlesObject(CompositeObject): + """ + Generates the Pot object with side handles (used in TwoArmLift) + + Args: + name (str): Name of this Pot object + + body_half_size (3-array of float): If specified, defines the (x,y,z) half-dimensions of the main pot + body. Otherwise, defaults to [0.07, 0.07, 0.07] + + handle_radius (float): Determines the pot handle radius + + handle_length (float): Determines the pot handle length + + handle_width (float): Determines the pot handle width + + handle_friction (float): Friction value to use for pot handles. Defauls to 1.0 + + density (float): Density value to use for all geoms. Defaults to 1000 + + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + + rgba_body (4-array or None): If specified, sets pot body rgba values + + rgba_handle_0 (4-array or None): If specified, sets handle 0 rgba values + + rgba_handle_1 (4-array or None): If specified, sets handle 1 rgba values + + solid_handle (bool): If true, uses a single geom to represent the handle + + thickness (float): How thick to make the pot body walls + """ + + def __init__( + self, + name, + body_half_size=(0.07, 0.07, 0.07), + handle_radius=0.01, + handle_length=0.09, + handle_width=0.09, + handle_friction=1.0, + density=1000, + use_texture=True, + rgba_body=None, + rgba_handle_0=None, + rgba_handle_1=None, + solid_handle=False, + thickness=0.01, # For body + ): + # Set name + self._name = name + + # Set object attributes + self.body_half_size = np.array(body_half_size) + self.thickness = thickness + self.handle_radius = handle_radius + self.handle_length = handle_length + self.handle_width = handle_width + self.handle_friction = handle_friction + self.density = density + self.use_texture = use_texture + self.rgba_body = np.array(rgba_body) if rgba_body else RED + self.rgba_handle_0 = np.array(rgba_handle_0) if rgba_handle_0 else GREEN + self.rgba_handle_1 = np.array(rgba_handle_1) if rgba_handle_1 else BLUE + self.solid_handle = solid_handle + + # Element references to be filled when generated + self._handle0_geoms = None + self._handle1_geoms = None + self.pot_base = None + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + redwood = CustomMaterial( + texture="WoodRed", + tex_name="redwood", + mat_name="pot_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + greenwood = CustomMaterial( + texture="WoodGreen", + tex_name="greenwood", + mat_name="handle0_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + bluewood = CustomMaterial( + texture="WoodBlue", + tex_name="bluewood", + mat_name="handle1_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(redwood) + self.append_material(greenwood) + self.append_material(bluewood) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + full_size = np.array( + ( + self.body_half_size, + self.body_half_size + self.handle_length * 2, + self.body_half_size, + ) + ) + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": full_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + } + site_attrs = [] + obj_args = {} + + # Initialize geom lists + self._handle0_geoms = [] + self._handle1_geoms = [] + + # Add main pot body + # Base geom + name = f"base" + self.pot_base = [name] + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, -self.body_half_size[2] + self.thickness / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array( + [self.body_half_size[0], self.body_half_size[1], self.thickness / 2] + ), + geom_names=name, + geom_rgbas=None if self.use_texture else self.rgba_body, + geom_materials="pot_mat" if self.use_texture else None, + geom_frictions=None, + density=self.density, + ) + + # Walls + x_off = np.array( + [ + 0, + -(self.body_half_size[0] - self.thickness / 2), + 0, + self.body_half_size[0] - self.thickness / 2, + ] + ) + y_off = np.array( + [ + -(self.body_half_size[1] - self.thickness / 2), + 0, + self.body_half_size[1] - self.thickness / 2, + 0, + ] + ) + w_vals = np.array( + [ + self.body_half_size[0], + self.body_half_size[1], + self.body_half_size[0], + self.body_half_size[1], + ] + ) + r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi]) + for i, (x, y, w, r) in enumerate(zip(x_off, y_off, w_vals, r_vals)): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(x, y, 0), + geom_quats=T.convert_quat(T.axisangle2quat(np.array([0, 0, r])), to="wxyz"), + geom_sizes=np.array([self.thickness / 2, w, self.body_half_size[2]]), + geom_names=f"body{i}", + geom_rgbas=None if self.use_texture else self.rgba_body, + geom_materials="pot_mat" if self.use_texture else None, + geom_frictions=None, + density=self.density, + ) + + # Add handles + main_bar_size = np.array( + [ + self.handle_width / 2 + self.handle_radius, + self.handle_radius, + self.handle_radius, + ] + ) + side_bar_size = np.array([self.handle_radius, self.handle_length / 2, self.handle_radius]) + handle_z = self.body_half_size[2] - self.handle_radius + for i, (g_list, handle_side, rgba) in enumerate( + zip( + [self._handle0_geoms, self._handle1_geoms], + [1.0, -1.0], + [self.rgba_handle_0, self.rgba_handle_1], + ) + ): + handle_center = np.array( + ( + 0, + handle_side * (self.body_half_size[1] + self.handle_length), + handle_z, + ) + ) + # Solid handle case + if self.solid_handle: + handle_center = np.array( + ( + 0, + handle_side * (self.body_half_size[1] + self.handle_length / 2), + handle_z, + ) + ) + name = f"handle{i}" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=handle_center, + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array( + [ + self.handle_width / 2, + self.handle_length / 2, + self.handle_radius, + ] + ), + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Hollow handle case + else: + # Center bar + name = f"handle{i}_c" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=handle_center, + geom_quats=(1, 0, 0, 0), + geom_sizes=main_bar_size, + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Side bars + for bar_side, suffix in zip([-1.0, 1.0], ["-", "+"]): + name = f"handle{i}_{suffix}" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=( + bar_side * self.handle_width / 2, + handle_side * (self.body_half_size[1] + self.handle_length / 2), + handle_z, + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=side_bar_size, + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Add relevant site + handle_site = self.get_site_attrib_template() + handle_name = f"handle{i}" + handle_site.update( + { + "name": handle_name, + "pos": array_to_string(handle_center - handle_side * np.array([0, 0.005, 0])), + "size": "0.005", + "rgba": rgba, + } + ) + site_attrs.append(handle_site) + # Add to important sites + self._important_sites[f"handle{i}"] = self.naming_prefix + handle_name + + # Add pot body site + pot_site = self.get_site_attrib_template() + center_name = "center" + pot_site.update( + { + "name": center_name, + "size": "0.005", + } + ) + site_attrs.append(pot_site) + # Add to important sites + self._important_sites["center"] = self.naming_prefix + center_name + + # Add back in base args and site args + obj_args.update(base_args) + obj_args["sites"] = site_attrs # All sites are part of main (top) body + + # Return this dict + return obj_args + + @property + def handle_distance(self): + """ + Calculates how far apart the handles are + + Returns: + float: handle distance + """ + return self.body_half_size[1] * 2 + self.handle_length * 2 + + @property + def handle0_geoms(self): + """ + Returns: + list of str: geom names corresponding to handle0 (green handle) + """ + return self.correct_naming(self._handle0_geoms) + + @property + def handle1_geoms(self): + """ + Returns: + list of str: geom names corresponding to handle1 (blue handle) + """ + return self.correct_naming(self._handle1_geoms) + + @property + def handle_geoms(self): + """ + Returns: + list of str: geom names corresponding to both handles + """ + return self.handle0_geoms + self.handle1_geoms + + @property + def important_sites(self): + """ + Returns: + dict: In addition to any default sites for this object, also provides the following entries + + :`'handle0'`: Name of handle0 location site + :`'handle1'`: Name of handle1 location site + """ + # Get dict from super call and add to it + dic = super().important_sites + dic.update(self._important_sites) + return dic + + @property + def bottom_offset(self): + return np.array([0, 0, -1 * self.body_half_size[2]]) + + @property + def top_offset(self): + return np.array([0, 0, self.body_half_size[2]]) + + @property + def horizontal_radius(self): + return np.sqrt(2) * (max(self.body_half_size) + self.handle_length) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/ring_tripod.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/ring_tripod.py new file mode 100644 index 0000000000000000000000000000000000000000..339c56e4926a87e9ffe2937ed4412a00989b4c11 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite/ring_tripod.py @@ -0,0 +1,194 @@ +import numpy as np + +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import add_to_dict +from robosuite.utils.mjcf_utils import CustomMaterial +import robosuite.utils.transform_utils as T + + +class RingTripodObject(CompositeObject): + """ + Generates a tripod base with a small ring for threading a needle through it (used in Threading task) + + Args: + name (str): Name of this RingTripod object + """ + + def __init__( + self, + name, + ): + + ### TODO: make this object more general (with more args and configuration options) later ### + + # Set object attributes + self._name = name + self.tripod_mat_name = "lightwood_mat" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + tripod_mat = CustomMaterial( + texture="WoodLight", + tex_name="lightwood", + mat_name="lightwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(tripod_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + total_size = (0.05, 0.05, 0.1) + base_args = { + "total_size": total_size, + "name": self.name, + "locations_relative_to_center": False, + "obj_types": "all", + "density": 100.0, + # NOTE: this lower value of solref allows the thin hole wall to avoid penetration through it + "solref": (0.02, 1.0), + "solimp": (0.9, 0.95, 0.001), + } + obj_args = {} + + # pattern for threading ring + unit_size = [0.005, 0.002, 0.002] + pattern = np.ones((6, 1, 6)) + for i in range(1, 5): + pattern[i][0][1:5] = np.zeros(4) + ring_size = [ + unit_size[0] * pattern.shape[1], + unit_size[1] * pattern.shape[2], + unit_size[2] * pattern.shape[0], + ] + self.ring_size = np.array(ring_size) + + # ring offset for where the ring is located relative to the (0, 0, 0) corner + ring_offset = [ + total_size[0] - ring_size[0], + total_size[1] - ring_size[1], + 2.0 * (total_size[2] - ring_size[2]), + ] + + # RING-GEOMS: use the pattern to instantiate geoms corresponding to the threading ring + nz, nx, ny = pattern.shape + self.num_ring_geoms = 0 + for k in range(nz): + for i in range(nx): + for j in range(ny): + if pattern[k, i, j] > 0: + add_to_dict( + dic=obj_args, + geom_types="box", + # needle geom needs to be offset from boundary in (x, z) + geom_locations=( + (i * 2.0 * unit_size[0]) + ring_offset[0], + (j * 2.0 * unit_size[1]) + ring_offset[1], + (k * 2.0 * unit_size[2]) + ring_offset[2], + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=tuple(unit_size), + geom_names="ring_{}".format(self.num_ring_geoms), + geom_rgbas=None, + geom_materials=self.tripod_mat_name, + # make the ring low friction to ensure easy insertion + geom_frictions=(0.3, 5e-3, 1e-4), + ) + self.num_ring_geoms += 1 + + # TRIPOD-GEOMS: legs of the tripod + tripod_capsule_r = 0.01 + tripod_capsule_h = 0.03 + tripod_geom_locations = [ + (0.0, 0.0, 0.0), + (0.0, 2.0 * total_size[1] - 2.0 * tripod_capsule_r, 0.0), + ( + 2.0 * total_size[0] - 2.0 * tripod_capsule_r, + total_size[1] - tripod_capsule_r, + 0.0, + ), + ] + # rotate the legs to resemble a tripod + tripod_center = np.array([total_size[0], total_size[1], 0.0]) + xy_offset = np.array([tripod_capsule_r, tripod_capsule_r, 0.0]) + rotation_angle = -np.pi / 6.0 # 30 degrees + tripod_geom_quats = [] + for i in range(3): + capsule_loc = np.array(tripod_geom_locations[i]) + xy_offset + capsule_loc[2] = 0.0 # only care about location in x-y plane + vec_to_center = tripod_center - capsule_loc + vec_to_center = vec_to_center / np.linalg.norm(vec_to_center) + # cross-product with z unit vector to get vector to rotate about + rot_vec = np.cross(vec_to_center, np.array([0.0, 0.0, 1.0])) + rot_quat = T.mat2quat(T.rotation_matrix(angle=rotation_angle, direction=rot_vec)) + tripod_geom_quats.append(T.convert_quat(rot_quat, to="wxyz")) + + for i in range(3): + add_to_dict( + dic=obj_args, + geom_types="capsule", + geom_locations=tripod_geom_locations[i], + geom_quats=tripod_geom_quats[i], + geom_sizes=(tripod_capsule_r, tripod_capsule_h), + geom_names="tripod_{}".format(i), + geom_rgbas=None, + geom_materials=self.tripod_mat_name, + geom_frictions=None, + ) + + # POST-GEOMS: mounted base + post + base_thickness = 0.005 + post_size = 0.005 + post_geom_sizes = [ + (total_size[0], total_size[1], base_thickness), + ( + post_size, + post_size, + total_size[2] - ring_size[2] - base_thickness - tripod_capsule_r - tripod_capsule_h, + ), + ] + post_geom_locations = [ + (0.0, 0.0, 2.0 * (tripod_capsule_r + tripod_capsule_h)), + ( + total_size[0] - post_size, + total_size[1] - post_size, + 2.0 * (tripod_capsule_r + tripod_capsule_h + base_thickness), + ), + ] + for i in range(2): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=post_geom_locations[i], + geom_quats=(1, 0, 0, 0), + geom_sizes=post_geom_sizes[i], + geom_names="post_{}".format(i), + geom_rgbas=None, + geom_materials=self.tripod_mat_name, + geom_frictions=None, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dcea55930782409ac0c9dc2ba09a1b4432fd5e58 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/__init__.py @@ -0,0 +1,8 @@ +from .cup import CupObject +from .coffee_machine import CoffeeMachineObject +from .stacked_cylinder import StackedCylinderObject +from .inverse_stacked_cylinder import InverseStackedCylinderObject +from .stacked_box import StackedBoxObject +from .sliding_box import SlidingBoxObject +from .bin_with_handles import BinWithHandles +from .spray_bottle import SprayBottleObject diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/bin_with_handles.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/bin_with_handles.py new file mode 100644 index 0000000000000000000000000000000000000000..ef35b5e9f2f0a3e1615572596b399f9c1d6c6cdd --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/bin_with_handles.py @@ -0,0 +1,162 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, Bin +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class BinWithHandles(CompositeBodyObject): + """ + Bin with simple square handles on each side. + """ + + def __init__( + self, + name, + bin_size, + bin_wall_thickness, + bin_transparent_walls, + bin_upside_down, + center_handle_size, + adjacent_handle_size, + joints="default", + rgba=(0.2, 0.1, 0.0, 1.0), + material=None, + density=1000.0, + friction=None, + ): + + # Object properties + + # FULL size of bin + self.bin_size = list(bin_size) + self.bin_wall_thickness = bin_wall_thickness + self.bin_transparent_walls = bin_transparent_walls + self.bin_upside_down = bin_upside_down + + # half-sizes of box geom used for center part of handle (which you grab) + self.center_handle_size = list(center_handle_size) + + # half-sizes of box geoms used for adjacent parts of handle (not grabbed) + self.adjacent_handle_size = list(adjacent_handle_size) + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # bin + self.bin = Bin( + name="bin", + bin_size=self.bin_size, + wall_thickness=self.bin_wall_thickness, + transparent_walls=self.bin_transparent_walls, + rgba=rgba, + material=material, + density=density, + friction=friction, + upside_down=bin_upside_down, + ) + objects.append(self.bin) + object_locations.append([0.0, 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # handles on each side + + left_handle_1_loc = [ + 0.0, + -( + self.bin_size[1] / 2.0 + + 2.0 * self.adjacent_handle_size[1] + + self.center_handle_size[1] + ), + 0.0, + ] + left_handle_1_size = self.center_handle_size + + left_handle_2_loc = [ + (self.center_handle_size[0] - self.adjacent_handle_size[0]), + -(self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]), + 0.0, + ] + left_handle_2_size = self.adjacent_handle_size + + left_handle_3_loc = [ + -(self.center_handle_size[0] - self.adjacent_handle_size[0]), + -(self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]), + 0.0, + ] + left_handle_3_size = self.adjacent_handle_size + + right_handle_1_loc = [ + 0.0, + ( + self.bin_size[1] / 2.0 + + 2.0 * self.adjacent_handle_size[1] + + self.center_handle_size[1] + ), + 0.0, + ] + right_handle_1_size = self.center_handle_size + + right_handle_2_loc = [ + (self.center_handle_size[0] - self.adjacent_handle_size[0]), + (self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]), + 0.0, + ] + right_handle_2_size = self.adjacent_handle_size + + right_handle_3_loc = [ + -(self.center_handle_size[0] - self.adjacent_handle_size[0]), + (self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]), + 0.0, + ] + right_handle_3_size = self.adjacent_handle_size + + handle_locs = [ + left_handle_1_loc, + left_handle_2_loc, + left_handle_3_loc, + right_handle_1_loc, + right_handle_2_loc, + right_handle_3_loc, + ] + handle_sizes = [ + left_handle_1_size, + left_handle_2_size, + left_handle_3_size, + right_handle_1_size, + right_handle_2_size, + right_handle_3_size, + ] + handle_ind = 1 + for b_loc, b_size in zip(handle_locs, handle_sizes): + this_handle = BoxObject( + name="handle_{}".format(handle_ind), + size=b_size, + rgba=rgba, + material=material, + density=density, + friction=friction, + joints=None, + ) + objects.append(this_handle) + object_locations.append(b_loc) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + handle_ind += 1 + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + # total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/coffee_machine.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/coffee_machine.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a457086f3b346446a9b7e5860c42d8bf2099d1 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/coffee_machine.py @@ -0,0 +1,244 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject +from robocasa.models.objects.composite_body.cup import ( + CupObject, +) +from robocasa.models.objects.xml_objects import ( + CoffeeMachineBodyObject, + CoffeeMachineLidObject, + CoffeeMachineBaseObject, +) +import numpy as np + +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class CoffeeMachineObject(CompositeBodyObject): + """ + Coffee machine object with a lid fixed on a hinge joint. + """ + + def __init__( + self, + name, + add_cup=True, + pod_holder_friction=None, + joints="default", + density=1000.0, + ): + + # pieces of the coffee machine + body = CoffeeMachineBodyObject(name="body") + body_size = body.get_bounding_box_half_size() + body_location = [0.0, 0.0, 0.0] + + lid = CoffeeMachineLidObject(name="lid") + lid_size = self.lid_size = lid.get_bounding_box_half_size() + # add tolerance to allow lid to open fully + lid_location = [ + body_size[0] - lid_size[0], + 2.0 * body_size[1] + 0.01, + 2.0 * (body_size[2] - lid_size[2]) + 0.005, + ] + + # add in hinge joint to lid + hinge_pos = [0.0, -lid_size[1], 0.0] + hinge_joint = dict( + type="hinge", + axis="1 0 0", + pos=array_to_string(hinge_pos), + limited="true", + range="{} {}".format(0, 2.0 * np.pi / 3.0), + damping="0.005", + ) + body_joints = dict(lid_main=[hinge_joint]) # note: "main" gets appended to body name + lid = CoffeeMachineLidObject(name="lid") + + base = CoffeeMachineBaseObject(name="base") + base_size = base.get_bounding_box_half_size() + base_location = [body_size[0] - base_size[0], 2.0 * body_size[1], 0.0] + + pod_holder_holder = BoxObject( + name="pod_holder_holder", + size=[ + 0.01, + # tolerance for having the lid stick out a little from the holder + 0.9 * (lid_size[1] - lid_size[0]), + 0.005, + ], + rgba=[0.839, 0.839, 0.839, 1], # silver + joints=None, + ) + pod_holder_holder_size = pod_holder_holder.get_bounding_box_half_size() + pod_holder_holder_location = [ + body_size[0] - pod_holder_holder_size[0], + 2.0 * body_size[1], + # put right underneath lid + 2.0 * (body_size[2] - lid_size[2] - pod_holder_holder_size[2]), + ] + + pod_holder = CupObject( + name="pod_holder", + outer_cup_radius=lid_size[0], + inner_cup_radius=0.028, + cup_height=0.028, + cup_ngeoms=64, # 8, + cup_base_height=0.005, + cup_base_offset=0.002, + add_handle=False, + rgba=[1, 0, 0, 1], + density=density, + joints=None, + friction=pod_holder_friction, + ) + pod_holder_size = self.pod_holder_size = pod_holder.get_bounding_box_half_size() + # pod_holder_size = self.pod_holder_size = np.array([0.0295, 0.0295, 0.028 ]) + pod_holder_location = [ + body_size[0] - pod_holder_size[0], + 2.0 * (body_size[1] + pod_holder_holder_size[1]), + # put right underneath lid + 2.0 * (body_size[2] - lid_size[2] - pod_holder_size[2]), + ] + + total_size = [ + body_size[0], + body_size[1] + base_size[1], + body_size[2], + ] + + objects = [ + body, + lid, + base, + pod_holder_holder, + pod_holder, + ] + + object_locations = [ + body_location, + lid_location, + base_location, + pod_holder_holder_location, + pod_holder_location, + ] + + object_quats = [ + [0.0, 0.0, 0.0, 1.0], # z-rotate body and base by 180 + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + [1.0, 0.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 0.0], + ] + + # add a rigidly mounted cup to the base + self.add_cup = add_cup + if self.add_cup: + cup = CupObject( + name="cupppp", + outer_cup_radius=0.03, + inner_cup_radius=0.025, + cup_height=0.025, + cup_ngeoms=64, # 8, + cup_base_height=0.005, + cup_base_offset=0.005, + add_handle=True, + handle_outer_radius=0.015, + handle_inner_radius=0.010, + handle_thickness=0.003, + handle_ngeoms=64, + rgba=[0.839, 0.839, 0.839, 1], + density=1000.0, + joints=None, + ) + cup_total_size = cup.get_bounding_box_half_size() + # cup_total_size = np.array([0.03 , 0.045, 0.025]) + objects.append(cup) + object_locations.append( + [ + body_size[0] - cup_total_size[0], + 2.0 * (body_size[1] + pod_holder_holder_size[1]) + + pod_holder_size[1] + - cup_total_size[1], + 2.0 * base_size[2], + ] + ) + rot_angle = -np.pi / 2.0 + object_quats.append([np.cos(rot_angle / 2), 0, 0, np.sin(rot_angle / 2)]) + + object_parents = [None] * len(objects) + + """ + Variables to compare: + + objects + [, + , + , + , + , + ] + + object_locations + [[0.0, 0.0, 0.0], + [0.056999999999999995, 0.21100000000000002, 0.20700000000000002], + [0.04449999999999999, 0.201, 0.0], + [0.0765, 0.201, 0.192], + [0.056999999999999995, 0.22710000000000002, 0.14600000000000002], + [0.056499999999999995, 0.21160000000000007, 0.01]] + + object_quats + [[0.0, 0.0, 0.0, 1.0], + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + [1.0, 0.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 0.0], + [0.7071067811865476, 0, 0, -0.7071067811865475]] + + body_size + array([0.0865, 0.1005, 0.1105]) + + lid_size + array([0.0295, 0.044 , 0.0095]) + + lid_location + [0.056999999999999995, 0.21100000000000002, 0.20700000000000002] + + base_size + array([0.042, 0.05 , 0.005]) + + base_location + [0.04449999999999999, 0.201, 0.0] + + pod_holder_holder_size + array([0.01 , 0.01305, 0.005 ]) + + pod_holder_holder_location + [0.0765, 0.201, 0.192] + + pod_holder_size + array([0.0295, 0.0295, 0.028 ]) + + pod_holder_location + [0.056999999999999995, 0.22710000000000002, 0.14600000000000002] + + total_size + [0.0865, 0.15050000000000002, 0.1105] + + cup.total_size + array([0.03 , 0.045, 0.025]) + """ + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + body_joints=body_joints, # make sure hinge joint is added + joints=joints, + # joints="default", # coffee machine can move + # joints=None, # coffee machine does not move + total_size=total_size, + locations_relative_to_corner=True, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/cup.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/cup.py new file mode 100644 index 0000000000000000000000000000000000000000..e5afb17aaabb85e05f28723bf48fe47d801dfa36 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/cup.py @@ -0,0 +1,183 @@ +from robosuite.models.objects import ( + CompositeBodyObject, + BoxObject, + CylinderObject, + HollowCylinderObject, +) +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class CupObject(CompositeBodyObject): + """ + Cup object with optional handle. + """ + + def __init__( + self, + name, + outer_cup_radius=0.0425, + inner_cup_radius=0.03, + cup_height=0.05, + cup_ngeoms=8, + cup_base_height=0.01, + cup_base_offset=0.005, + add_handle=False, + handle_outer_radius=0.03, + handle_inner_radius=0.015, + handle_thickness=0.005, + handle_ngeoms=8, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + ): + + # Object properties + + # radius of the inner cup hole and entire cup + self.r1 = inner_cup_radius + self.r2 = outer_cup_radius + + # number of geoms used to approximate the cylindrical shell + self.n = cup_ngeoms + + # cup half-height + self.cup_height = cup_height + + # cup base args + self.cup_base_height = cup_base_height + self.cup_base_offset = cup_base_offset + + # handle args + self.add_handle = add_handle + self.handle_outer_radius = handle_outer_radius + self.handle_inner_radius = handle_inner_radius + self.handle_thickness = handle_thickness + self.handle_ngeoms = handle_ngeoms + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # cup body + self.cup_body = HollowCylinderObject( + name="cup_body", + outer_radius=self.r2, + inner_radius=self.r1, + height=self.cup_height, + ngeoms=self.n, + rgba=rgba, + material=material, + density=density, + friction=friction, + ) + objects.append(self.cup_body) + object_locations.append([0.0, 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # cup base + self.cup_base = CylinderObject( + name="cup_base", + size=[self.cup_body.int_r, self.cup_base_height], + rgba=rgba, + material=material, + density=density, + solref=[0.02, 1.0], + solimp=[0.998, 0.998, 0.001], + joints=None, + ) + objects.append(self.cup_base) + object_locations.append( + [0.0, 0.0, -self.cup_height + self.cup_base_height + self.cup_base_offset] + ) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + if self.add_handle: + # cup handle is a hollow half-cylinder + self.cup_handle = HollowCylinderObject( + name="cup_handle", + outer_radius=self.handle_outer_radius, + inner_radius=self.handle_inner_radius, + height=self.handle_thickness, + ngeoms=self.handle_ngeoms, + rgba=rgba, + material=material, + density=density, + make_half=True, + friction=friction, + ) + # translate handle to right side of cup body, and rotate by +90 degrees about y-axis + # to orient the handle geoms on the cup body + objects.append(self.cup_handle) + object_locations.append([0.0, (self.cup_body.r2 + self.cup_handle.unit_box_width), 0.0]) + object_quats.append( + T.convert_quat( + T.mat2quat( + T.rotation_matrix(angle=np.pi / 2.0, direction=[0.0, 1.0, 0.0])[:3, :3] + ), + to="wxyz", + ) + ) + object_parents.append(None) + + # total size of cup + body_total_size = [self.r2, self.r2, self.cup_height] + if self.add_handle: + body_total_size[1] += self.handle_outer_radius + + """ + To match on cup 1: + + objects + [, + ] + + body_total_size + [0.0295, 0.0295, 0.028] + + object_locations + [[0.0, 0.0, 0.0], [0.0, 0.0, -0.020999999999999998]] + + object_quats + [[1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]] + + + To match on cup 2: + + objects + [, + , + ] + + body_total_size + [0.03, 0.045, 0.025] + + object_locations + [[0.0, 0.0, 0.0], [0.0, 0.0, -0.015], [0.0, 0.03073601511491127, 0.0]] + + object_quats + [[1.0, 0.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 0.0], + array([ 0.70710677, -0. , 0.70710677, -0. ], dtype=float32)] + """ + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/inverse_stacked_cylinder.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/inverse_stacked_cylinder.py new file mode 100644 index 0000000000000000000000000000000000000000..13ce6f1bee0e466452e168128beea1446128e738 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/inverse_stacked_cylinder.py @@ -0,0 +1,139 @@ +from robosuite.models.objects import ( + CompositeBodyObject, + BoxObject, + CylinderObject, + HollowCylinderObject, +) +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class InverseStackedCylinderObject(CompositeBodyObject): + """ + Inverse of stacked cylinder object, where the top piece is a hollow cylinder object + and the bottom piece is a cylinder object. Optionally add a square base for stability. + """ + + def __init__( + self, + name, + radius_1, + radius_2, + height_1, + height_2, + ngeoms=64, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + square_base_width=None, + square_base_height=None, + ): + + # Object properties + + # radius of first (bottom) cylinder and inner radius of second (top) hollow cylinder + self.r1 = radius_1 + self.r2 = radius_2 + + # half-height of first (bottom) cylinder and second (top) hollow cylinder + self.h1 = height_1 + self.h2 = height_2 + + # num geoms to approximate the hollow cylinder + self.ngeoms = ngeoms + + # whether to add square base + self.add_square_base = (square_base_width is not None) and (square_base_height is not None) + + # half-width and half-height for square base + self.square_base_width = square_base_width + self.square_base_height = square_base_height + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # NOTE: we will place the object frame at the vertical center of the two stacked cylinders + z_center = (self.h1 + self.h2) / 2.0 + c1_offset = self.h1 - z_center + c2_offset = 2.0 * self.h1 + self.h2 - z_center + + # first (bottom) cylinder + self.cylinder_1 = CylinderObject( + name="cylinder_1", + size=[self.r1, self.h1], + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + # solimp=[0.998, 0.998, 0.001], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(self.cylinder_1) + object_locations.append([0.0, 0.0, c1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # second (top) hollow cylinder + self.cylinder_2 = HollowCylinderObject( + name="cylinder_2", + outer_radius=self.r1, # match radius of first cylinder + inner_radius=self.r2, + height=self.h2, + ngeoms=self.ngeoms, + rgba=rgba, + material=material, + density=density, + friction=friction, + # TODO: maybe tune solimp and try (0.998, 0.998, 0.001) + solref=[0.02, 1.0], + solimp=[0.9, 0.95, 0.001], + # solimp=(0.998, 0.998, 0.001), + ) + objects.append(self.cylinder_2) + object_locations.append([0.0, 0.0, c2_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # # total size of object + # max_r = max(self.r1, self.r2) + # body_total_size = [max_r, max_r, self.h1 + self.h2] + + if self.add_square_base: + # add square base underneath bottom cylinder + s1_offset = c1_offset - (self.square_base_height + self.h1) + self.square_base = BoxObject( + name="square_base", + size=[ + self.square_base_width, + self.square_base_width, + self.square_base_height, + ], + rgba=rgba, + material=material, + ) + objects.append(self.square_base) + object_locations.append([0.0, 0.0, s1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + # total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/lightbulb.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/lightbulb.py new file mode 100644 index 0000000000000000000000000000000000000000..7d8d58461ee54baeb5e13cd477f2a7d50994da4b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/lightbulb.py @@ -0,0 +1,153 @@ +from robosuite.models.objects import ( + CompositeBodyObject, + BoxObject, + CylinderObject, + BallObject, +) +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string, new_site +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class BallObjectWithSite(BallObject): + """ + A ball object with a inner site (used for the bulb). + """ + + def _get_object_subtree(self): + # tree = super()._get_object_subtree() + tree = self._get_object_subtree_(ob_type="sphere") + site_element_attr = self.get_site_attrib_template() + + site_element_attr["pos"] = "0 0 0.1" + site_element_attr["name"] = "center_site" + site_element_attr["size"] = "{} {} {}".format( + 2.0 * self.size[0], 2.0 * self.size[0], 2.0 * self.size[0] + ) + site_element_attr["rgba"] = "1.0 0.0 0.0 1.0" + site_element_attr["group"] = "1" + # site_element_attr["rgba"] = "1.0 0.976 0.839 0.9" + # site_element_attr["rgba"] = "1.0 0.976 0.839 0.0" + tree.append(new_site(**site_element_attr)) + return tree + + +class LightbulbObject(CompositeBodyObject): + """ + A simple lightbulb constructed out of a base of alternating radius cylinders + and a sphere on top. + """ + + def __init__( + self, + name, + radius_low, + radius_high, + cylinder_height, + num_cylinders, + sphere_radius, + joints="default", + density=100.0, + friction=None, + ): + + # Object properties + + # radii of alternating cylinders for base + self.radius_low = radius_low + self.radius_high = radius_high + + # half-height of each cylinder + self.cylinder_height = cylinder_height + + # number of cylinders for base + self.num_cylinders = num_cylinders + + # radius of sphere at top + self.sphere_radius = sphere_radius + + # toggle between translucent and yellow + self.translucent_rgba = (1.0, 1.0, 1.0, 0.3) + self.yellow_rgba = (1.0, 0.976, 0.839, 0.7) + # self.yellow_rgba = (0.0, 0.0, 0.0, 0.0) + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # NOTE: we will place the object frame at the vertical center of all the stacked objects + self.z_center = ( + (2.0 * self.cylinder_height) * self.num_cylinders + 2.0 * self.sphere_radius + ) / 2.0 + + metal = CustomMaterial( + texture="Metal", + tex_name="metal", + mat_name="MatMetal", + tex_attrib={"type": "cube"}, + mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"}, + ) + + # we will define all objects relative to the bottom of the object, and then subtract the z_center value + for cylinder_ind in range(self.num_cylinders): + r = self.radius_low if ((cylinder_ind % 2) == 0) else self.radius_high + cyl_obj = CylinderObject( + name="cylinder_{}".format(cylinder_ind), + size=[r, self.cylinder_height], + rgba=None, + material=metal, + density=density, + friction=friction, + solref=[0.02, 1.0], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(cyl_obj) + z_cyl = (2.0 * cylinder_ind + 1) * self.cylinder_height + object_locations.append([0.0, 0.0, z_cyl]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # then add translucent sphere at top + self.bulb = BallObject( + name="bulb", + size=[self.sphere_radius], + density=density, + friction=friction, + rgba=self.translucent_rgba, + material=None, + joints=None, + ) + objects.append(self.bulb) + z_bulb = object_locations[-1][2] + self.cylinder_height + self.sphere_radius + object_locations.append([0.0, 0.0, z_bulb]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # do frame conversion from bottom of object to z_center + object_locations = [[loc[0], loc[1], loc[2] - self.z_center] for loc in object_locations] + + # add site that can be toggled to turn lightbulb on + sites = [ + dict( + name="bulb_on", + pos=array_to_string(object_locations[-1]), + size="{}".format(0.95 * self.sphere_radius), + rgba=array_to_string(self.yellow_rgba), + ) + ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + sites=sites, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/sliding_box.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/sliding_box.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6542b615457918a9ab869b62f54eb1923db5d5 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/sliding_box.py @@ -0,0 +1,132 @@ +import numpy as np + +from robosuite.models.objects import BoxObject, CompositeBodyObject, CylinderObject +from robosuite.utils.mjcf_utils import BLUE, RED, CustomMaterial, array_to_string + + +class SlidingBoxObject(CompositeBodyObject): + """ + An example object that demonstrates the CompositeBodyObject functionality. This object consists of two cube bodies + joined together by a slide joint allowing one box to slide on top of the other. + + Args: + name (str): Name of this object + + box1_size (3-array): (L, W, H) half-sizes for the first box + + box2_size (3-array): (L, W, H) half-sizes for the second box + + use_texture (bool): set True if using wood textures for the blocks + """ + + def __init__( + self, + name, + box1_size=(0.1, 0.1, 0.02), + box2_size=(0.02, 0.02, 0.02), + use_texture=True, + ): + # Set box sizes + self.box1_size = np.array(box1_size) + self.box2_size = np.array(box2_size) + + # Set box densities + self.box1_density = 10000.0 + self.box2_density = 100.0 + + # Set texture attributes + self.use_texture = use_texture + self.box1_material = None + self.box2_material = None + self.box1_rgba = RED + self.box2_rgba = BLUE + + # Define materials we want to use for this object + if self.use_texture: + # Remove RGBAs + self.box1_rgba = None + self.box2_rgba = None + + # Set materials for each box + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + self.box1_material = CustomMaterial( + texture="WoodRed", + tex_name="box1_tex", + mat_name="box1_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.box2_material = CustomMaterial( + texture="WoodBlue", + tex_name="box2_tex", + mat_name="box2_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + + # Create objects + objects = [] + for i, (size, mat, rgba, density) in enumerate( + zip( + (self.box1_size, self.box2_size), + (self.box1_material, self.box2_material), + (self.box1_rgba, self.box2_rgba), + (self.box1_density, self.box2_density), + ) + ): + objects.append( + BoxObject( + name=f"box{i + 1}", + size=size, + rgba=rgba, + material=mat, + ) + ) + + # Define slide joint + rel_joint_pos = [0, 0, 0] # at second box + joint_lim = self.box1_size[1] - self.box2_size[1] + slide_joint = { + "name": "box_slide", + "type": "slide", + "axis": "0 1 0", # y-axis slide + "pos": array_to_string(rel_joint_pos), + "springref": "0", + "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio + "limited": "true", + "range": "{} {}".format(-joint_lim, joint_lim), + } + + # Define positions -- second box should lie on top of first box + positions = [ + np.zeros(3), # First box is centered at top-level body anyways + np.array([0, 0, self.box1_size[2] + self.box2_size[2]]), + ] + + quats = [ + None, # Default quaternion for box 1 + None, # Default quaternion for box 2 + ] + + # Define parents -- which body each is aligned to + parents = [ + None, # box 1 attached to top-level body + objects[0].root_body, # box 2 attached to box 1 + ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=positions, + object_quats=quats, + object_parents=parents, + body_joints={objects[1].root_body: [slide_joint]}, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/socket.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/socket.py new file mode 100644 index 0000000000000000000000000000000000000000..4869a231c1d8db82eed3bb02609a3bb44b0bc4ba --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/socket.py @@ -0,0 +1,334 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial +from .stacked_cylinder import StackedCylinderObject + + +class SocketObject(CompositeBodyObject): + """ + Box geom connected to series of geoms with ball joints (wire) and connected to + cylinder representing plug. + """ + + def __init__( + self, + name, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + socket_base_size=(0.02, 0.02, 0.03), + wire_box_geom_size=(0.02, 0.005, 0.005), + wire_box_geom_rgba=(0.0, 0.0, 0.0, 1.0), + num_box_geoms_up=6, + num_box_geoms_left=2, + num_box_geoms_down=9, + merge_box_geoms=False, + merge_size=1, + cylinder_args=None, + ): + + # Object properties + + # box geom used for socket base + self.socket_base_size = socket_base_size + + # box geoms used for wire + self.wire_box_geom_size = wire_box_geom_size + self.wire_box_geom_rgba = wire_box_geom_rgba + + # wire parameters - number of geoms to use for up, left, and down portions + self.num_box_geoms_up = num_box_geoms_up + self.num_box_geoms_left = num_box_geoms_left + self.num_box_geoms_down = num_box_geoms_down + + # if true, merge the box geoms along each direction of the wire into a single box geom + self.merge_box_geoms = merge_box_geoms + + # number of box geoms to use for each merged size (set to higher than 1 to merge the geoms into more + # than one box geom) + self.merge_size = merge_size + + if cylinder_args is None: + # default cylinder args + cylinder_args = dict( + # bottom cylinder radius and half-height + radius_1=0.03, + height_1=0.075, + # top cylinder radius and half-height + radius_2=0.02, + height_2=0.025, + rgba=[0.839, 0.839, 0.839, 1], + density=1000.0, + # add square base + square_base_width=0.03, + square_base_height=0.005, + ) + self.cylinder_args = dict(cylinder_args) + self.cylinder_args["joints"] = None + + # materials + box_geom_material = CustomMaterial( + texture="Metal", + tex_name="metal", + mat_name="MatMetal", + tex_attrib={"type": "cube"}, + mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"}, + ) + socket_material = CustomMaterial( + texture="WoodLight", + tex_name="lightwood", + mat_name="lightwood_mat", + tex_attrib={"type": "cube"}, + mat_attrib={"texrepeat": "1 1", "specular": "0.4", "shininess": "0.1"}, + ) + + # params for ball joints used + + # + ball_joint_spec = { + "type": "ball", + "pos": "{} 0 0".format(self.wire_box_geom_size[0]), + "springref": "0", + "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio + "limited": "true", + "range": "0 {}".format(np.pi / 4), + } + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + object_joints = dict() + + # NOTE: For absolute object locations (objects not defined relative to parent) we will use the socket base frame + # as a frame of reference, and add an offset from the center of the object (approximated via full width) + # to it. + + # get an approximate x-y bounding box below, and place the center there, and define offset relative to stove base center + approx_full_width = self.num_box_geoms_left * (2.0 * self.wire_box_geom_size[0]) + ( + 2.0 * self.socket_base_size[1] + ) + approx_full_height = (self.num_box_geoms_down + 2) * (2.0 * self.wire_box_geom_size[0]) + + base_x_off = ( + self.socket_base_size[0] + (self.num_box_geoms_up) * (2.0 * self.wire_box_geom_size[0]) + ) - (approx_full_height / 2.0) + base_y_off = (self.num_box_geoms_left * self.wire_box_geom_size[0]) + self.socket_base_size[ + 1 + ] + + # base of socket + self.socket_base = BoxObject( + name="stove_base", + size=list(self.socket_base_size), + rgba=rgba, + material=socket_material, + joints=None, + ) + objects.append(self.socket_base) + object_locations.append([base_x_off, base_y_off, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # chain above base + chain_ind = 0 + up_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_up - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + up_chain_size[0] *= self.num_box_geoms_up + up_chain_size[0] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(up_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + objects.append(chain_obj) + object_locations.append( + [ + base_x_off - (self.socket_base_size[0] + up_chain_size[0]), + base_y_off, + 0.0, + ] + ) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + if self.merge_box_geoms: + # add ball joint and make sure to place it at the edge of the geom + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(up_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(up_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-2.0 * up_chain_size[0], 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + # add ball joint and make sure to place it at the edge of the geom + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(up_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + # add chain in left direction + rot_quat = T.convert_quat( + T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz" + ) + left_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_left - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + left_chain_size[0] *= self.num_box_geoms_left + # HACK: merge entire left chain since this side is small + left_merge_size = 1 + left_chain_size[0] /= left_merge_size + # number of additional geoms to add + num_geoms_iter = left_merge_size - 1 + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(left_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-up_chain_size[0], -left_chain_size[0], 0.0]) + object_quats.append(rot_quat) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(left_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(left_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-2.0 * left_chain_size[0], 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(left_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + # add chain in downward direction + rot_quat = T.convert_quat( + T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz" + ) + down_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_down - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + down_chain_size[0] *= self.num_box_geoms_down + down_chain_size[0] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(down_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-left_chain_size[0], -down_chain_size[0], 0.0]) + object_quats.append(rot_quat) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(down_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(down_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-2.0 * down_chain_size[0], 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(down_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + # add cylinder object + self.cylinder_obj = StackedCylinderObject( + name="cylinder_obj", + **self.cylinder_args, + ) + + x_off = -(down_chain_size[0] + self.cylinder_obj.square_base_width) + y_off = 0.0 + z_off = ((self.cylinder_obj.h1 + self.cylinder_obj.h2) / 2.0) - down_chain_size[2] + parent = objects[-1].root_body + objects.append(self.cylinder_obj) + object_locations.append([x_off, y_off, z_off]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + # # add debug site to see object center + # sites = [ + # dict( + # name="TMP", + # pos=array_to_string([0., 0., 0.]), + # size="{}".format(0.1), + # rgba=array_to_string([1., 0., 0., 1.]), + # ) + # ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + body_joints=object_joints, + # sites=sites, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/spray_bottle.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/spray_bottle.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d2e1e2c665d06b6a87378249e941645ee1fdda --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/spray_bottle.py @@ -0,0 +1,207 @@ +import numpy as np + +from robosuite.models.objects import ( + BoxObject, + CompositeBodyObject, + CylinderObject, + ConeObject, +) +from robosuite.utils.mjcf_utils import BLUE, RED, CustomMaterial, array_to_string + + +class SprayBottleObject(CompositeBodyObject): + """ + A spray bottle object where the trigger is modeled via a slide joint. + """ + + def __init__( + self, + name, + base_cylinder_radius, + base_cylinder_height, + cone_outer_radius, + cone_inner_radius, + cone_height, + cone_ngeoms, + neck_height, + top_length, + top_thickness, + trigger_height, + trigger_width, + trigger_length, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + square_base_width=None, + square_base_height=None, + ): + # Sizes + self.base_cylinder_radius = base_cylinder_radius + self.base_cylinder_height = base_cylinder_height + self.cone_outer_radius = cone_outer_radius + self.cone_inner_radius = cone_inner_radius + self.cone_height = cone_height + self.cone_ngeoms = cone_ngeoms + self.neck_height = neck_height + self.top_length = top_length + self.top_thickness = top_thickness + self.trigger_height = trigger_height + self.trigger_width = trigger_width + self.trigger_length = trigger_length + + # whether to add square base + self.add_square_base = (square_base_width is not None) and (square_base_height is not None) + + # half-width and half-height for square base + self.square_base_width = square_base_width + self.square_base_height = square_base_height + + assert self.top_length > self.cone_inner_radius, "top needs to stick out past neck" + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # base cylinder + self.base_cylinder = CylinderObject( + name="base_cylinder", + size=[self.base_cylinder_radius, self.base_cylinder_height], + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + # solimp=[0.998, 0.998, 0.001], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(self.base_cylinder) + object_locations.append([0.0, 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # cone that is part of neck + # z_cone = self.base_cylinder_height # cone frame is bottom center of cone + z_cone = self.base_cylinder_height + (self.cone_height / 2.0) + self.neck_cone = ConeObject( + name="neck_cone", + outer_radius=self.cone_outer_radius, + inner_radius=self.cone_inner_radius, + height=self.cone_height, # full height, not half-height + ngeoms=self.cone_ngeoms, + use_box=False, + rgba=rgba, + material=material, + density=density, + solref=(0.02, 1.0), + # solimp=[0.998, 0.998, 0.001], + solimp=(0.9, 0.95, 0.001), + friction=friction, + ) + objects.append(self.neck_cone) + object_locations.append([0.0, 0.0, z_cone]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # cylinder that is part of neck + z_cyl = self.base_cylinder_height + self.cone_height + self.neck_height + self.neck_cylinder = CylinderObject( + name="neck_cylinder", + size=[self.cone_inner_radius, self.neck_height], # match cone radius + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + # solimp=[0.998, 0.998, 0.001], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(self.neck_cylinder) + object_locations.append([0.0, 0.0, z_cyl]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # top box object + box_x_off = -(self.top_length - self.cone_inner_radius) + box_z_off = z_cyl + self.neck_height + self.top_thickness + self.top_box = BoxObject( + name="top_box", + size=[self.top_length, self.cone_inner_radius, self.top_thickness], + density=density, + friction=friction, + rgba=rgba, + material=material, + joints=None, + ) + objects.append(self.top_box) + object_locations.append([box_x_off, 0.0, box_z_off]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # trigger object, which is defined relative to top box object + trigger_x_off = -(0.5 * self.top_length) # place halfway along length of top object + trigger_z_off = -(self.top_thickness + self.trigger_height) + self.trigger = BoxObject( + name="trigger", + size=[self.trigger_length, self.trigger_width, self.trigger_height], + density=density, + friction=friction, + rgba=rgba, + material=material, + joints=None, + ) + objects.append(self.trigger) + object_locations.append([trigger_x_off, 0.0, trigger_z_off]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(objects[-2].root_body) # NOTE: relative to top box object + + # define slide joint for trigger + rel_joint_pos = [0, 0, 0] # at trigger + joint_lim_min = 0.0 + joint_lim_max = ( + self.top_length + ) # trigger was shifted to left by 0.5 * top_length, so allow it to go to right by top_length + slide_joint = { + "name": "trigger_slide", + "type": "slide", + "axis": "1 0 0", # x-axis slide + "pos": array_to_string(rel_joint_pos), + "springref": "0", + "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio + "limited": "true", + "range": "{} {}".format(joint_lim_min, joint_lim_max), + } + + if self.add_square_base: + # add square base underneath bottom cylinder + s1_offset = -(self.square_base_height + self.base_cylinder_height) + self.square_base = BoxObject( + name="square_base", + size=[ + self.square_base_width, + self.square_base_width, + self.square_base_height, + ], + rgba=rgba, + material=material, + ) + objects.append(self.square_base) + object_locations.append([0.0, 0.0, s1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + body_joints={objects[-1].root_body: [slide_joint]}, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stacked_box.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stacked_box.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c7991c3a6056531e7758586df1f6a5538e3d45 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stacked_box.py @@ -0,0 +1,111 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject, Bin +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class StackedBoxObject(CompositeBodyObject): + """ + Two boxes - one stacked on top of the other. + """ + + def __init__( + self, + name, + box_1_size, + box_2_size, + joints="default", + box_1_rgba=None, + box_2_rgba=None, + box_1_material=None, + box_2_material=None, + density=100.0, + friction=None, + make_box_2_transparent=False, + ): + + # Object properties + + # half-sizes of first (bottom) box + self.box_1_size = list(box_1_size) + + # half-sizes of second (top) box + self.box_2_size = list(box_2_size) + + # maybe make box 2 have transparent top and bottom walls + self.make_box_2_transparent = make_box_2_transparent + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # NOTE: we will place the object frame at the vertical center of the two stacked boxes + z_center = (self.box_1_size[2] + self.box_2_size[2]) / 2.0 + b1_offset = self.box_1_size[2] - z_center + b2_offset = 2.0 * self.box_1_size[2] + self.box_2_size[2] - z_center + + # first (bottom) box + self.box_1 = BoxObject( + name="box_1", + size=self.box_1_size, + rgba=box_1_rgba, + material=box_1_material, + density=density, + friction=friction, + joints=None, + ) + objects.append(self.box_1) + object_locations.append([0.0, 0.0, b1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # second (top) box + if self.make_box_2_transparent: + self.box_2 = Bin( + name="box_2", + bin_size=( + 2.0 * self.box_2_size[0], + 2.0 * self.box_2_size[1], + 2.0 * self.box_2_size[2], + ), + wall_thickness=0.01, + transparent_walls=False, + friction=friction, + density=density, + use_texture=True, + rgba=box_2_rgba, + material=box_2_material, + upside_down=False, + add_second_base=True, + transparent_base=True, + ) + else: + self.box_2 = BoxObject( + name="box_2", + size=self.box_2_size, + rgba=box_2_rgba, + material=box_2_material, + density=density, + friction=friction, + joints=None, + ) + objects.append(self.box_2) + object_locations.append([0.0, 0.0, b2_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + # total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stacked_cylinder.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stacked_cylinder.py new file mode 100644 index 0000000000000000000000000000000000000000..cf8cf143dd483f32697707b29eb1c5eadcc08323 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stacked_cylinder.py @@ -0,0 +1,127 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class StackedCylinderObject(CompositeBodyObject): + """ + Two cylinders - one stacked on top of the other. + Optionally add a square base for stability. + """ + + def __init__( + self, + name, + radius_1, + radius_2, + height_1, + height_2, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + square_base_width=None, + square_base_height=None, + ): + + # Object properties + + # radius of first (bottom) cylinder and second (top) cylinder + self.r1 = radius_1 + self.r2 = radius_2 + + # half-height of first (bottom) cylinder and second (top) cylinder + self.h1 = height_1 + self.h2 = height_2 + + # whether to add square base + self.add_square_base = (square_base_width is not None) and (square_base_height is not None) + + # half-width and half-height for square base + self.square_base_width = square_base_width + self.square_base_height = square_base_height + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # NOTE: we will place the object frame at the vertical center of the two stacked cylinders + z_center = (self.h1 + self.h2) / 2.0 + c1_offset = self.h1 - z_center + c2_offset = 2.0 * self.h1 + self.h2 - z_center + + # first (bottom) cylinder + self.cylinder_1 = CylinderObject( + name="cylinder_1", + size=[self.r1, self.h1], + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + solimp=[0.9, 0.95, 0.001], + # solimp=[0.998, 0.998, 0.001], + joints=None, + ) + objects.append(self.cylinder_1) + object_locations.append([0.0, 0.0, c1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # second (top) cylinder + self.cylinder_2 = CylinderObject( + name="cylinder_2", + size=[self.r2, self.h2], + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + # solimp=[0.998, 0.998, 0.001], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(self.cylinder_2) + object_locations.append([0.0, 0.0, c2_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # # total size of object + # max_r = max(self.r1, self.r2) + # body_total_size = [max_r, max_r, self.h1 + self.h2] + + if self.add_square_base: + # add square base underneath bottom cylinder + s1_offset = c1_offset - (self.square_base_height + self.h1) + self.square_base = BoxObject( + name="square_base", + size=[ + self.square_base_width, + self.square_base_width, + self.square_base_height, + ], + rgba=rgba, + material=material, + ) + objects.append(self.square_base) + object_locations.append([0.0, 0.0, s1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + # total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stove_plug.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stove_plug.py new file mode 100644 index 0000000000000000000000000000000000000000..4f71ef952fd721ec3e330fc09f150423a4f3151d --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/composite_body/stove_plug.py @@ -0,0 +1,396 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial +from .inverse_stacked_cylinder import InverseStackedCylinderObject +from .lightbulb import LightbulbObject + +import robosuite_task_zoo +from robosuite_task_zoo.models.kitchen import StoveObject + + +class StoveObjectNew(StoveObject): + """ + Override some offsets for placement sampler. + """ + + @property + def bottom_offset(self): + # unused since we directly hardcode z + return np.array([0, 0, -0.02]) + + @property + def top_offset(self): + # unused since we directly hardcode z + return np.array([0, 0, 0.02]) + + @property + def horizontal_radius(self): + return 0.1 + + +class StovePlugObject(CompositeBodyObject): + """ + Stove on wooden block with chain (plug) connected. Optionally replace the stove + with a lightbulb if @lightbulb_args is provided. + """ + + def __init__( + self, + name, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + stove_base_size=(0.12, 0.12, 0.01), + stove_z_half_size=0.025, + wire_box_geom_size=(0.005, 0.02, 0.005), + wire_box_geom_rgba=(0.0, 0.0, 0.0, 1.0), + num_box_geoms_left=5, + num_box_geoms_vert=8, + num_box_geoms_right=8, + merge_box_geoms=False, + merge_size=1, + cylinder_args=None, + lightbulb_args=None, + ): + + # Object properties + + # half sizes for stove base box object + # self.stove_base_size = (0.1, 0.1, 0.02) + self.stove_base_size = stove_base_size + self.stove_z_half_size = stove_z_half_size # note: estimated approximately + + # box geoms used for wire + self.wire_box_geom_size = wire_box_geom_size + self.wire_box_geom_rgba = wire_box_geom_rgba + + # wire parameters - number of geoms to use for left, down, and right portions + self.num_box_geoms_left = num_box_geoms_left + self.num_box_geoms_vert = num_box_geoms_vert + self.num_box_geoms_right = num_box_geoms_right + + # if true, merge the box geoms along each direction of the wire into a single box geom + self.merge_box_geoms = merge_box_geoms + + # number of box geoms to use for each merged size (set to higher than 1 to merge the geoms into more + # than one box geom) + self.merge_size = merge_size + + if cylinder_args is None: + # default cylinder args + cylinder_args = dict( + # bottom cylinder radius and half-height + radius_1=0.03, + height_1=0.01, + # top hollow cylinder inner radius and half-height + radius_2=0.025, + height_2=0.025, + # NOTE: reduce to 8 geoms if desired + ngeoms=64, + rgba=[0.839, 0.839, 0.839, 1], + density=1000.0, + # add square base + square_base_width=0.03, + square_base_height=0.005, + ) + self.cylinder_args = dict(cylinder_args) + self.cylinder_args["joints"] = None + + self.use_lightbulb = lightbulb_args is not None + if self.use_lightbulb: + self.lightbulb_args = dict(lightbulb_args) + self.lightbulb_args["joints"] = None + + # materials + box_geom_material = CustomMaterial( + texture="Metal", + tex_name="metal", + mat_name="MatMetal", + tex_attrib={"type": "cube"}, + mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"}, + ) + stove_base_material = CustomMaterial( + texture="WoodLight", + tex_name="lightwood", + mat_name="lightwood_mat", + tex_attrib={"type": "cube"}, + mat_attrib={"texrepeat": "1 1", "specular": "0.4", "shininess": "0.1"}, + ) + + # params for ball joints used + + # + ball_joint_spec = { + "type": "ball", + "pos": "0 {} 0".format(self.wire_box_geom_size[1]), + "springref": "0", + "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio + "limited": "true", + "range": "0 {}".format(np.pi / 4), + } + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + object_joints = dict() + + # NOTE: For absolute object locations (objects not defined relative to parent) we will use the stove base frame + # as a frame of reference, and add an offset from the center of the object (approximated via full width) + # to it. + + # get an approximate x-y bounding box below, and place the center there, and define offset relative to stove base cente + approx_full_width = self.num_box_geoms_left * (2.0 * self.wire_box_geom_size[1]) + ( + 2.0 * self.stove_base_size[1] + ) + approx_full_height = (self.num_box_geoms_vert + 2) * (2.0 * self.wire_box_geom_size[1]) + + stove_base_x_off = -(approx_full_height / 2.0) + self.stove_base_size[0] + stove_base_y_off = (approx_full_width / 2.0) - self.stove_base_size[1] + + # base of stove + self.stove_base = BoxObject( + name="stove_base", + size=list(self.stove_base_size), + rgba=rgba, + material=stove_base_material, + joints=None, + ) + objects.append(self.stove_base) + object_locations.append([stove_base_x_off, stove_base_y_off, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + if self.use_lightbulb: + # lightbulb + self.lightbulb = LightbulbObject( + name="lightbulb", + **self.lightbulb_args, + ) + objects.append(self.lightbulb) + object_locations.append( + [ + stove_base_x_off, + stove_base_y_off, + (self.stove_base_size[2] + self.lightbulb.z_center), + ] + ) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + else: + # stove + self.stove = StoveObjectNew( + name="new_stove", + joints=None, + ) + objects.append(self.stove) + object_locations.append( + [ + stove_base_x_off, + stove_base_y_off, + (self.stove_base_size[2] + self.stove_z_half_size), + ] + ) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # chain to the left of stove base + chain_ind = 0 + left_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_left - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + left_chain_size[1] *= self.num_box_geoms_left + left_chain_size[1] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + left_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(left_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + objects.append(left_chain_obj) + object_locations.append( + [ + stove_base_x_off - 0.75 * self.stove_base_size[0], + stove_base_y_off - (self.stove_base_size[1] + left_chain_size[1]), + 0.0, + ] + ) + # object_locations.append([0., -(self.stove_base_size[1] + left_chain_size[1]), 0.]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + if self.merge_box_geoms: + # add ball joint and make sure to place it at the edge of the geom + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(left_chain_size[1]) + object_joints[left_chain_obj.root_body] = [ball_joint] + for i in range(num_geoms_iter): + left_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(left_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(left_chain_obj) + object_locations.append([0.0, -2.0 * left_chain_size[1], 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + # add ball joint and make sure to place it at the edge of the geom + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(left_chain_size[1]) + object_joints[left_chain_obj.root_body] = [ball_joint] + + # add chain in downward direction + rot_quat = T.convert_quat( + T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz" + ) + vert_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_vert - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + vert_chain_size[1] *= self.num_box_geoms_vert + vert_chain_size[1] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + vert_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(vert_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(vert_chain_obj) + object_locations.append([vert_chain_size[1], -left_chain_size[1], 0.0]) + object_quats.append(rot_quat) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(vert_chain_size[1]) + object_joints[vert_chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + vert_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(vert_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(vert_chain_obj) + object_locations.append([0.0, -2.0 * vert_chain_size[1], 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(vert_chain_size[1]) + object_joints[vert_chain_obj.root_body] = [ball_joint] + + # add chain in rightward direction + rot_quat = T.convert_quat( + T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz" + ) + right_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_right - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + right_chain_size[1] *= self.num_box_geoms_right + right_chain_size[1] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + right_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(right_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(right_chain_obj) + object_locations.append([right_chain_size[1], -vert_chain_size[1], 0.0]) + object_quats.append(rot_quat) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(right_chain_size[1]) + object_joints[right_chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + right_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(right_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(right_chain_obj) + object_locations.append([0.0, -2.0 * right_chain_size[1], 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(right_chain_size[1]) + object_joints[right_chain_obj.root_body] = [ball_joint] + + # add cylinder object + self.cylinder_obj = InverseStackedCylinderObject( + name="cylinder_obj", + **self.cylinder_args, + ) + + x_off = 0.0 + y_off = -(right_chain_size[1] + self.cylinder_obj.square_base_width) + z_off = ((self.cylinder_obj.h1 + self.cylinder_obj.h2) / 2.0) - right_chain_size[2] + parent = objects[-1].root_body + objects.append(self.cylinder_obj) + object_locations.append([x_off, y_off, z_off]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + # # add debug site to see object center + # sites = [ + # dict( + # name="TMP", + # pos=array_to_string([0., 0., 0.]), + # size="{}".format(0.1), + # rgba=array_to_string([1., 0., 0., 1.]), + # ) + # ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + body_joints=object_joints, + # sites=sites, + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/objects.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/objects.py new file mode 100644 index 0000000000000000000000000000000000000000..2a07649d8670e763efd37d42b00dae90eb2f910b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/objects.py @@ -0,0 +1,276 @@ +import os +import time +import xml.etree.ElementTree as ET + +import mujoco +import numpy as np +import robosuite +import robosuite.utils.transform_utils as T +from robosuite.models.objects import MujocoXMLObject +from robosuite.utils.mjcf_utils import array_to_string, string_to_array +from robosuite.environments.robot_env import RobotEnv + + +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, + static=False, + ): + # 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() + + # write modified xml (and make sure to postprocess any paths just in case) + xml_str = ET.tostring(root, encoding="utf8").decode("utf8") + xml_str = self.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() + + # initialize object with new xml we wrote + super().__init__( + fname=new_xml_path, + name=name, + joints=None if static else [dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=False, + scale=scale, + ) + + self.spawns = [] + self._disabled_spawns = set() + for s in self.worldbody.findall("./body/body/geom"): + geom_name = s.get("name") + if geom_name and geom_name.startswith("{}spawn_".format(self.naming_prefix)): + self.spawns.append(s) + + # clean up xml - we don't need it anymore + if os.path.exists(new_xml_path): + os.remove(new_xml_path) + + def postprocess_model_xml(self, 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) + """ + + 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) + + return ET.tostring(root, encoding="utf8").decode("utf8") + + 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 + + def get_joint(self, joint_name: str): + _, _, joints = self._get_elements_by_name( + geom_names=[], body_names=[], joint_names=[joint_name] + ) + return joints[joint_name] + + @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) -> list[np.ndarray]: + """ + Get the full 8 bounding box points of the object + rot: a rotation matrix + """ + 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] + return self._get_bbox_points( + bottom_offset=bottom_offset, + top_offset=top_offset, + radius=horiz_radius, + trans=trans, + rot=rot, + ) + + @staticmethod + def _get_bbox_points( + bottom_offset, top_offset, radius, trans=None, rot=None + ) -> list[np.ndarray]: + """ + Helper function to get the full 8 bounding box points of the object. + """ + center = np.mean([bottom_offset, top_offset], axis=0) + half_size = [radius[0], radius[1], top_offset[2] - center[2]] + + 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 points + + @staticmethod + def get_spawn_bottom_offset(site: ET.Element) -> np.array: + """ + Get bottom offset of the spawn zone. + """ + site_pos = string_to_array(site.get("pos")) + site_size = string_to_array(site.get("size")) if site.get("type") == "box" else np.zeros(3) + return site_pos - np.array([0, 0, site_size[-1]]) + + def get_random_spawn(self, rng, exclude_disabled: bool = False) -> tuple[int, ET.Element]: + """ + Get random spawn site. + """ + options = [o for o in range(0, len(self.spawns))] + if exclude_disabled: + options = [o for o in options if o not in self._disabled_spawns] + spawn_id = rng.choice(options) + return spawn_id, self.spawns[spawn_id] + + def set_spawn_active(self, spawn_id: int, active: bool): + """ + Update the activity state of a spawn site. Disabled sites are excluded from random sampling. + """ + if active and spawn_id in self._disabled_spawns: + self._disabled_spawns.remove(spawn_id) + elif not active: + self._disabled_spawns.add(spawn_id) + + def closest_spawn_id(self, env: RobotEnv, obj: "MJCFObject", max_distance: float = 1.0) -> int: + if len(self.spawns) == 0: + return -1 + if not env.check_contact(self, obj): + return -1 + obj_pos = env.sim.data.body_xpos[env.sim.model.body_name2id(obj.root_body)] + distances = [] + for spawn_id in range(len(self.spawns)): + spawn_pos = env.sim.data.get_geom_xpos(self.spawns[spawn_id].get("name")) + distance = np.linalg.norm(spawn_pos - obj_pos) + distances.append((spawn_id, distance)) + distances = sorted(distances, key=lambda item: item[1]) + obj_geom_ids = [env.sim.model.geom_name2id(g) for g in obj.contact_geoms] + for spawn_id, distance in distances: + spawn_geom_id = env.sim.model.geom_name2id(self.spawns[spawn_id].get("name")) + for obj_geom_id in obj_geom_ids: + real_distance = mujoco.mj_geomDistance( + m=env.sim.model._model, + d=env.sim.data._data, + geom1=spawn_geom_id, + geom2=obj_geom_id, + distmax=max_distance, + fromto=None, + ) + if real_distance <= 0: + return spawn_id + if real_distance >= max_distance: + return -1 + return -1 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/xml_objects.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/xml_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..347232df1b5f040563a4e2e433fd2728939adcfc --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/objects/xml_objects.py @@ -0,0 +1,268 @@ +import os +import time +import xml.etree.ElementTree as ET +import numpy as np +from robosuite.models.objects import MujocoXMLObject +from robosuite.utils.mjcf_utils import array_to_string, find_elements, string_to_array +import robocasa + +XML_ASSETS_BASE_PATH = os.path.join(robocasa.__path__[0], "models/assets/gear_kitchen") + + +class BlenderObject(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, + ): + # 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.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)) + + # 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__( + fname=new_xml_path, + name=name, + joints=[dict(type="free", damping="0.0005")], + 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(BlenderObject, 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)) + + return geom_pairs + + +class CoffeeMachinePodObject(MujocoXMLObject): + """ + Coffee pod object (used in Coffee task). + """ + + def __init__(self, name, margin=1.0): + self._horizontal_radius_margin = margin + super().__init__( + os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_pod.xml"), + # name=name, joints=[dict(type="free", damping="0.0005")], + name=name, + joints=[dict(type="free")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + @property + def horizontal_radius(self): + horizontal_radius_site = self.worldbody.find( + "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) + ) + return ( + self._horizontal_radius_margin * string_to_array(horizontal_radius_site.get("pos"))[0] + ) + + +class CoffeeMachineBodyObject(MujocoXMLObject): + """ + Coffee machine body piece (used in Coffee task). Note that the piece is rigid (no joint is added). + """ + + def __init__(self, name): + super().__init__( + os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_body.xml"), + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class CoffeeMachineLidObject(MujocoXMLObject): + """ + Coffee machine lid piece (used in Coffee task). + """ + + def __init__(self, name): + super().__init__( + os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_lid.xml"), + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class CoffeeMachineBaseObject(MujocoXMLObject): + """ + Coffee machine base piece (used in Coffee task). Note that the piece is rigid (no joint is added). + """ + + def __init__(self, name): + super().__init__( + os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_base.xml"), + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class DrawerObject(MujocoXMLObject): + """ + Custom version of cabinet object that differs from BUDs. It has manually specified top, bottom, and horizontal sites. + """ + + def __init__(self, name, joints=None): + + # original cabinet xml + # path_to_cabinet_xml = os.path.join(robosuite_task_zoo.__path__[0], "models/hammer_place/cabinet.xml") + + # our custom cabinet xml - names the drawer bottom geom for easy contact checking + # path_to_cabinet_xml = os.path.join(mimicgen.__path__[0], "envs/robosuite/assets/cabinet.xml") + path_to_cabinet_xml = os.path.join(XML_ASSETS_BASE_PATH, "objects/cabinet.xml") + + # path to modified xml from Danfei's student + # path_to_cabinet_xml = os.path.join(XML_ASSETS_BASE_PATH, "objects/cabinet1.xml") + + super().__init__( + path_to_cabinet_xml, + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + # NOTE: had to manually set these to get placement sampler working okay + @property + def bottom_offset(self): + return np.array([0, 0, -0.065]) + + @property + def top_offset(self): + return np.array([0, 0, 0.065]) + + @property + def horizontal_radius(self): + return 0.15 + + @property + def body_size(self): + return (0.5, 0.4, 0.3) + + +class LongDrawerObject(MujocoXMLObject): + """ + Drawer that has longer platform for easier grasping of objects inside. + """ + + def __init__(self, name, joints=None): + + # our custom cabinet xml - has some longer geoms for the drawer platform + path_to_cabinet_xml = os.path.join(XML_ASSETS_BASE_PATH, "objects/drawer_long.xml") + + super().__init__( + path_to_cabinet_xml, + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + # NOTE: had to manually set these to get placement sampler working okay + @property + def bottom_offset(self): + return np.array([0, 0, -0.065]) + + @property + def top_offset(self): + return np.array([0, 0, 0.065]) + + @property + def horizontal_radius(self): + # TODO: this might need to change now + return 0.15 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ecb1911fdd586237122f9d63bdffad48afcaaf6b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/__init__.py @@ -0,0 +1,779 @@ +from numpy import dtype, ndarray + + +from typing import Any + + +import mujoco +import numpy as np + +from robosuite.controllers.parts.generic.joint_pos import JointPositionController +from robosuite.controllers.parts.gripper.simple_grip import SimpleGripController +from robosuite.controllers.composite.composite_controller import HybridMobileBase +from robosuite.models.grippers import ( + PandaGripper, + InspireLeftHand, + InspireRightHand, + FourierLeftHand, + FourierRightHand, +) + +from robocasa.models.grippers import G1ThreeFingerLeftHand, G1ThreeFingerRightHand + +from .manipulators import * + + +# This function returns in the order of the gripper XML's actuators. +def unformat_gripper_space(gripper, formatted_action): + formatted_action = np.array(formatted_action) + if isinstance(gripper, InspireLeftHand) or isinstance(gripper, InspireRightHand): + action = formatted_action[[0, 2, 4, 6, 8, 11]] + elif isinstance(gripper, FourierLeftHand) or isinstance(gripper, FourierRightHand): + action = formatted_action[[0, 1, 4, 6, 8, 10]] + elif isinstance(gripper, PandaGripper): + action = formatted_action + else: + raise TypeError + return action + + +def remove_mimic_joints(gripper, formatted_action) -> ndarray[Any, dtype[Any]]: + """_summary_ + + This is to remove the mimic joints from the actuator-ordered action + """ + formatted_action = np.array(formatted_action) + if isinstance(gripper, InspireLeftHand) or isinstance(gripper, InspireRightHand): + raise NotImplementedError + elif isinstance(gripper, FourierLeftHand) or isinstance(gripper, FourierRightHand): + action = formatted_action[[0, 2, 4, 6, 8, 10]] + elif isinstance(gripper, G1ThreeFingerLeftHand) or isinstance(gripper, G1ThreeFingerRightHand): + action = formatted_action + elif isinstance(gripper, PandaGripper): + action = formatted_action + return action + + +def _reconstruct_latest_action_gr1_impl(robot, verbose=False): + action_dict = {} + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + + for part_name, controller in cc.part_controllers.items(): + if isinstance(controller, JointPositionController): + assert controller.input_type == "absolute" + act = controller.goal_qpos + elif isinstance(controller, SimpleGripController): + assert not controller.use_action_scaling + act = unformat_gripper_space(cc.grippers[part_name], controller.goal_qvel) + else: + raise TypeError + action_dict[f"{pf}{part_name}"] = act + + if verbose: + print("Actions:", [(k, len(action_dict[k])) for k in action_dict]) + + return action_dict + + +def _reconstruct_latest_action_panda_impl(robot, action, verbose=False): + action_dict = {} + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + + for part_name, controller in cc.part_controllers.items(): + start_idx, end_idx = cc._action_split_indexes[part_name] + act = action[start_idx:end_idx] + # split action deeper for OSC + action_dict[f"{pf}{part_name}"] = act + + if verbose: + print("Actions:", [(k, len(action_dict[k])) for k in action_dict]) + + return action_dict + + +# This function tries to get all joints value, but sometimes we want to keep original action +# The function must be called after robot.control() +def reconstruct_latest_actions(env, actions=None, verbose=False): + if actions is None: + actions = np.zeros(env.action_dim) + action_dict = {} + cutoff = 0 + for robot in env.robots: + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + robot_action = actions[cutoff : cutoff + robot.action_dim] + cutoff += robot.action_dim + if "GR1" in robot.name: + action_dict.update(_reconstruct_latest_action_gr1_impl(robot)) + elif "Panda" in robot.name: + action_dict.update(_reconstruct_latest_action_panda_impl(robot, robot_action)) + else: + raise ValueError(f"Unknown robot name: {robot.name}") + if isinstance(cc, HybridMobileBase): + action_dict[f"{pf}base_mode"] = robot_action[-1] + + if verbose: + print("Actions:", [(k, len(action_dict[k])) for k in action_dict]) + + return action_dict + + +def gather_robot_observations(env, verbose=False, format_gripper_space=True): + observations = {} + + for robot_id, robot in enumerate(env.robots): + sim = robot.sim + gripper_names = {robot.get_gripper_name(arm): robot.gripper[arm] for arm in robot.arms} + for part_name, indexes in robot._ref_joints_indexes_dict.items(): + qpos_values = [] + for joint_id in indexes: + qpos_addr = sim.model.jnt_qposadr[joint_id] + # https://mujoco.readthedocs.io/en/stable/APIreference/APItypes.html#mjtjoint + joint_type = sim.model.jnt_type[joint_id] + if joint_type == mujoco.mjtJoint.mjJNT_FREE: + qpos_size = 7 # Free joint has 7 DOFs + elif joint_type == mujoco.mjtJoint.mjJNT_BALL: + qpos_size = 4 # Ball joint has 4 DOFs (quaternion) + else: + qpos_size = 1 # Revolute or prismatic joint has 1 DOF + qpos_values = np.append( + qpos_values, sim.data.qpos[qpos_addr : qpos_addr + qpos_size] + ) + if part_name in gripper_names.keys(): + gripper = gripper_names[part_name] + # Reverse the order to match the real robot + # TODO: how to adapt to other grippers? + if format_gripper_space: + qpos_values = unformat_gripper_space(gripper, qpos_values)[::-1] + if len(qpos_values) > 0: + observations[f"robot{robot_id}_{part_name}"] = qpos_values + + if verbose: + print("States:", [(k, len(observations[k])) for k in observations]) + + return observations + + +from gymnasium import spaces + + +class RobotKeyConverter: + @classmethod + def get_camera_config(cls): + raise NotImplementedError + + @classmethod + def map_obs(cls, input_obs): + raise NotImplementedError + + @classmethod + def map_action(cls, input_action): + raise NotImplementedError + + @classmethod + def unmap_action(cls, input_action): + raise NotImplementedError + + @classmethod + def get_metadata(cls, name): + raise NotImplementedError + + @classmethod + def map_obs_in_eval(cls, input_obs): + output_obs = {} + mapped_obs = cls.map_obs(input_obs) + for k, v in mapped_obs.items(): + assert k.startswith("hand.") or k.startswith("body.") + output_obs["state." + k[5:]] = v + return output_obs + + @classmethod + def get_missing_keys_in_dumping_dataset(cls): + return {} + + @classmethod + def convert_to_float64(cls, input): + for k, v in input.items(): + if isinstance(v, np.ndarray) and v.dtype == np.float32: + input[k] = v.astype(np.float64) + return input + + @classmethod + def deduce_observation_space(cls, env): + # 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 = ( + env.viewer._get_observations(force_update=True) + if env.viewer_get_obs + else env._get_observations(force_update=True) + ) + obs.update(gather_robot_observations(env)) + obs = cls.map_obs(obs) + observation_space = spaces.Dict() + + for k, v in obs.items(): + if k.startswith("hand.") or k.startswith("body."): + observation_space["state." + k[5:]] = spaces.Box( + low=-1, high=1, shape=(len(v),), dtype=np.float32 + ) + else: + raise ValueError(f"Unknown key: {k}") + + return observation_space + + @classmethod + def deduce_action_space(cls, env): + action = cls.map_action(reconstruct_latest_actions(env)) + action_space = spaces.Dict() + for k, v in action.items(): + if isinstance(v, np.int64): + action_space["action." + k[5:]] = spaces.Discrete(2) + elif isinstance(v, np.ndarray): + action_space["action." + k[5:]] = spaces.Box( + low=-1, high=1, shape=(len(v),), dtype=np.float32 + ) + else: + raise ValueError(f"Unknown type: {type(v)}") + return action_space + + +class GR1ArmsOnlyKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = ["video.ego_view_pad_res256_freq20"] + camera_names = [ + "egoview", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_hand": input_obs["robot0_right_gripper"], + "hand.left_hand": input_obs["robot0_left_gripper"], + "body.right_arm": input_obs["robot0_right"], + "body.left_arm": input_obs["robot0_left"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.left_hand": input_action["robot0_left_gripper"], + "hand.right_hand": input_action["robot0_right_gripper"], + "body.left_arm": input_action["robot0_left"], + "body.right_arm": input_action["robot0_right"], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_left_gripper": input_action["action.left_hand"], + "robot0_right_gripper": input_action["action.right_hand"], + "robot0_left": input_action["action.left_arm"], + "robot0_right": input_action["action.right_arm"], + } + return output_action + + @classmethod + def get_missing_keys_in_dumping_dataset(cls): + return { + "body.waist": np.zeros(3, dtype=np.float64), + "body.neck": np.zeros(3, dtype=np.float64), + "body.right_leg": np.zeros(6, dtype=np.float64), + "body.left_leg": np.zeros(6, dtype=np.float64), + } + + @classmethod + def get_metadata(cls, name): + return { + "absolute": True, + "rotation_type": None, + } + + +class GR1ArmsAndWaistKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = ["video.ego_view_pad_res256_freq20"] + camera_names = [ + "egoview", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_hand": input_obs["robot0_right_gripper"], + "hand.left_hand": input_obs["robot0_left_gripper"], + "body.right_arm": input_obs["robot0_right"], + "body.left_arm": input_obs["robot0_left"], + "body.waist": input_obs["robot0_torso"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.left_hand": input_action["robot0_left_gripper"], + "hand.right_hand": input_action["robot0_right_gripper"], + "body.left_arm": input_action["robot0_left"], + "body.right_arm": input_action["robot0_right"], + "body.waist": input_action["robot0_torso"], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_left_gripper": input_action["action.left_hand"], + "robot0_right_gripper": input_action["action.right_hand"], + "robot0_left": input_action["action.left_arm"], + "robot0_right": input_action["action.right_arm"], + "robot0_torso": input_action["action.waist"], + } + return output_action + + @classmethod + def get_missing_keys_in_dumping_dataset(cls): + return { + "body.neck": np.zeros(3, dtype=np.float64), + "body.right_leg": np.zeros(6, dtype=np.float64), + "body.left_leg": np.zeros(6, dtype=np.float64), + } + + @classmethod + def get_metadata(cls, name): + return { + "absolute": True, + "rotation_type": None, + } + + +class GR1FixedLowerBodyKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = ["video.agentview_pad_res256_freq20"] + camera_names = [ + "agentview", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_hand": input_obs["robot0_right_gripper"], + "hand.left_hand": input_obs["robot0_left_gripper"], + "body.right_arm": input_obs["robot0_right"], + "body.left_arm": input_obs["robot0_left"], + "body.waist": input_obs["robot0_torso"], + "body.neck": input_obs["robot0_head"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.left_hand": input_action["robot0_left_gripper"], + "hand.right_hand": input_action["robot0_right_gripper"], + "body.left_arm": input_action["robot0_left"], + "body.right_arm": input_action["robot0_right"], + "body.waist": input_action["robot0_torso"], + "body.neck": input_action["robot0_head"], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_left_gripper": input_action["action.left_hand"], + "robot0_right_gripper": input_action["action.right_hand"], + "robot0_left": input_action["action.left_arm"], + "robot0_right": input_action["action.right_arm"], + "robot0_torso": input_action["action.waist"], + "robot0_head": input_action["action.neck"], + } + return output_action + + @classmethod + def get_missing_keys_in_dumping_dataset(cls): + return { + "body.right_leg": np.zeros(6, dtype=np.float64), + "body.left_leg": np.zeros(6, dtype=np.float64), + } + + @classmethod + def get_metadata(cls, name): + return { + "absolute": True, + "rotation_type": None, + } + + +class PandaOmronKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = [ + "video.res256_image_side_0", + "video.res256_image_side_1", + "video.res256_image_wrist_0", + ] + camera_names = [ + "robot0_agentview_left", + "robot0_agentview_right", + "robot0_eye_in_hand", + ] + camera_widths, camera_heights = 512, 512 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.gripper_qpos": input_obs["robot0_gripper_qpos"], + "body.base_position": input_obs["robot0_base_pos"], + "body.base_rotation": input_obs["robot0_base_quat"], + "body.end_effector_position_relative": input_obs["robot0_base_to_eef_pos"], + "body.end_effector_rotation_relative": input_obs["robot0_base_to_eef_quat"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.gripper_close": ( + np.int64(0) if input_action["robot0_right_gripper"] < 0 else np.int64(1) + ), + "body.end_effector_position": input_action["robot0_right"][..., 0:3], + "body.end_effector_rotation": input_action["robot0_right"][..., 3:6], + "body.base_motion": np.concatenate( + ( + input_action["robot0_base"], + input_action["robot0_torso"], + ), + axis=-1, + ), + "body.control_mode": ( + np.int64(0) if input_action["robot0_base_mode"] < 0 else np.int64(1) + ), + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_right_gripper": (-1.0 if input_action["action.gripper_close"] < 0.5 else 1.0), + "robot0_right": np.concatenate( + ( + input_action["action.end_effector_position"], + input_action["action.end_effector_rotation"], + ), + axis=-1, + ), + "robot0_base": input_action["action.base_motion"][..., 0:3], + "robot0_torso": input_action["action.base_motion"][..., 3:4], + "robot0_base_mode": (-1.0 if input_action["action.control_mode"] < 0.5 else 1.0), + } + return output_action + + @classmethod + def get_metadata(cls, name): + # This function and import is only enabled in gr00t exporter + from decoupled_wbc.data.schema.raw.metadata import RotationType + + if name in [ + "body.base_position", + "body.end_effector_position_relative", + "body.end_effector_position", + ]: + return { + "absolute": False, + "rotation_type": None, + } + elif name in ["body.base_rotation", "body.end_effector_rotation_relative"]: + return { + "absolute": False, + "rotation_type": RotationType.QUATERNION, + } + elif name in ["body.end_effector_rotation"]: + return { + "absolute": False, + "rotation_type": RotationType.AXIS_ANGLE, + } + else: + return { + "absolute": True, + "rotation_type": None, + } + + +class PandaPandaKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = [ + "video.agentview_pad_res256_freq20", + "video.robot0_eye_in_hand_pad_res256_freq20", + "video.robot1_eye_in_hand_pad_res256_freq20", + ] + camera_names = [ + "agentview", + "robot0_eye_in_hand", + "robot1_eye_in_hand", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_gripper_qpos": input_obs["robot0_right_gripper"], + "hand.left_gripper_qpos": input_obs["robot1_right_gripper"], + "body.right_arm_eef_pos": input_obs["robot0_eef_pos"], + "body.right_arm_eef_quat": input_obs["robot0_eef_quat"], + "body.right_arm_joint_pos": input_obs["robot0_joint_pos"], + "body.left_arm_eef_pos": input_obs["robot1_eef_pos"], + "body.left_arm_eef_quat": input_obs["robot1_eef_quat"], + "body.left_arm_joint_pos": input_obs["robot1_joint_pos"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.right_gripper_close": ( + np.int64(0) if input_action["robot0_right_gripper"] < 0 else np.int64(1) + ), + "hand.left_gripper_close": ( + np.int64(0) if input_action["robot1_right_gripper"] < 0 else np.int64(1) + ), + "body.right_arm_eef_pos": input_action["robot0_right"][..., 0:3], + "body.right_arm_eef_rot": input_action["robot0_right"][..., 3:6], + "body.left_arm_eef_pos": input_action["robot1_right"][..., 0:3], + "body.left_arm_eef_rot": input_action["robot1_right"][..., 3:6], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_right_gripper": ( + -1.0 if input_action["action.right_gripper_close"] < 0.5 else 1.0 + ), + "robot1_right_gripper": ( + -1.0 if input_action["action.left_gripper_close"] < 0.5 else 1.0 + ), + "robot0_right": np.concatenate( + ( + input_action["action.right_arm_eef_pos"], + input_action["action.right_arm_eef_rot"], + ), + axis=-1, + ), + "robot1_right": np.concatenate( + ( + input_action["action.left_arm_eef_pos"], + input_action["action.left_arm_eef_rot"], + ), + axis=-1, + ), + } + return output_action + + @classmethod + def get_metadata(cls, name): + # This function and import is only enabled in gr00t exporter + from decoupled_wbc.data.schema.raw.metadata import RotationType + + if name in ["body.right_arm_eef_pos", "body.left_arm_eef_pos"]: + return { + "absolute": False, + "rotation_type": None, + } + elif name in ["body.right_arm_eef_quat", "body.right_arm_eef_quat"]: + return { + "absolute": False, + "rotation_type": RotationType.QUATERNION, + } + elif name in ["body.right_arm_eef_rot", "body.left_arm_eef_rot"]: + return { + "absolute": False, + "rotation_type": RotationType.AXIS_ANGLE, + } + else: + return { + "absolute": True, + "rotation_type": None, + } + + +class PandaDexRHPandaDexRHKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = [ + "video.agentview_pad_res256_freq20", + "video.robot0_eye_in_hand_pad_res256_freq20", + "video.robot1_eye_in_hand_pad_res256_freq20", + ] + camera_names = [ + "agentview", + "robot0_eye_in_hand", + "robot1_eye_in_hand", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_hand": input_obs["robot0_right_gripper"], + "hand.left_hand": input_obs["robot1_right_gripper"], + "body.right_arm_eef_pos": input_obs["robot0_eef_pos"], + "body.right_arm_eef_quat": input_obs["robot0_eef_quat"], + "body.right_arm_joint_pos": input_obs["robot0_joint_pos"], + "body.left_arm_eef_pos": input_obs["robot1_eef_pos"], + "body.left_arm_eef_quat": input_obs["robot1_eef_quat"], + "body.left_arm_joint_pos": input_obs["robot1_joint_pos"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.right_hand": input_action["robot0_right_gripper"], + "hand.left_hand": input_action["robot1_right_gripper"], + "body.right_arm_eef_pos": input_action["robot0_right"][0:3], + "body.right_arm_eef_rot": input_action["robot0_right"][3:6], + "body.left_arm_eef_pos": input_action["robot1_right"][0:3], + "body.left_arm_eef_rot": input_action["robot1_right"][3:6], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_right_gripper": input_action["action.right_hand"], + "robot1_right_gripper": input_action["action.left_hand"], + "robot0_right": np.concatenate( + ( + input_action["action.right_arm_eef_pos"], + input_action["action.right_arm_eef_rot"], + ), + axis=-1, + ), + "robot1_right": np.concatenate( + ( + input_action["action.left_arm_eef_pos"], + input_action["action.left_arm_eef_rot"], + ), + axis=-1, + ), + } + return output_action + + @classmethod + def get_metadata(cls, name): + # This function and import is only enabled in gr00t exporter + from decoupled_wbc.data.schema.raw.metadata import RotationType + + if name in ["body.right_arm_eef_pos", "body.left_arm_eef_pos"]: + return { + "absolute": False, + "rotation_type": None, + } + elif name in ["body.right_arm_eef_quat", "body.right_arm_eef_quat"]: + return { + "absolute": False, + "rotation_type": RotationType.QUATERNION, + } + elif name in ["body.right_arm_eef_rot", "body.left_arm_eef_rot"]: + return { + "absolute": False, + "rotation_type": RotationType.AXIS_ANGLE, + } + else: + return { + "absolute": True, + "rotation_type": None, + } + + +# The values are only used in gr00t dataset embodiment tag and env name +GR00T_ROBOCASA_ENVS_GR1_ARMS_ONLY = { + "GR1ArmsOnly": "gr1_arms_only_fourier_hands", + "GR1ArmsOnlyInspireHands": "gr1_arms_only_inspire_hands", + "GR1ArmsOnlyFourierHands": "gr1_arms_only_fourier_hands", +} +GR00T_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST = { + "GR1ArmsAndWaistFourierHands": "gr1_arms_waist_fourier_hands", +} +GR00T_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY = { + "GR1FixedLowerBody": "gr1_fixed_lower_body_fourier_hands", + "GR1FixedLowerBodyInspireHands": "gr1_fixed_lower_body_inspire_hands", + "GR1FixedLowerBodyFourierHands": "gr1_fixed_lower_body_fourier_hands", +} +GR00T_ROBOCASA_ENVS_PANDA = { + "PandaMobile": "panda_mobile", + "PandaOmron": "panda_omron", +} +GR00T_ROBOCASA_ENVS_BIMANUAL_GRIPPER = { + "Panda_Panda": "bimanual_panda_parallel_gripper", +} +GR00T_ROBOCASA_ENVS_BIMANUAL_HAND = { + "PandaDexRH_PandaDexLH": "bimanual_panda_inspire_hand", +} +GR00T_ROBOCASA_ENVS_G1 = { + "G1": "g1_sim", + "G1ArmsOnly": "g1_sim", + "G1FixedLowerBody": "g1_sim", + "G1FixedBase": "g1_sim", +} +GR00T_ROBOCASA_ENVS_ROBOTS = { + **GR00T_ROBOCASA_ENVS_GR1_ARMS_ONLY, + **GR00T_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST, + **GR00T_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY, + **GR00T_ROBOCASA_ENVS_PANDA, + **GR00T_ROBOCASA_ENVS_BIMANUAL_GRIPPER, + **GR00T_ROBOCASA_ENVS_BIMANUAL_HAND, + **GR00T_ROBOCASA_ENVS_G1, +} +GR00T_LOCOMANIP_ENVS_ROBOTS = {**GR00T_ROBOCASA_ENVS_G1} + + +def make_key_converter(robots_name): + if robots_name in GR00T_ROBOCASA_ENVS_GR1_ARMS_ONLY: + return GR1ArmsOnlyKeyConverter + elif robots_name in GR00T_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST: + return GR1ArmsAndWaistKeyConverter + elif robots_name in GR00T_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY: + return GR1FixedLowerBodyKeyConverter + elif robots_name in GR00T_ROBOCASA_ENVS_PANDA: + return PandaOmronKeyConverter + elif robots_name in GR00T_ROBOCASA_ENVS_BIMANUAL_GRIPPER: + return PandaPandaKeyConverter + elif robots_name in GR00T_ROBOCASA_ENVS_BIMANUAL_HAND: + return PandaDexRHPandaDexRHKeyConverter + else: + raise ValueError(f"Unknown robot name: {robots_name}")