file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/controllers/joint_impedance.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import torch
from collections.abc import Sequence
from dataclasses import MISSING
from omni.isaac.orbit.utils import configclass
@configclass
class JointImpedanceControllerCfg:
"""Configuration for joint impedance regulation controller."""
command_type: str = "p_abs"
"""Type of command: p_abs (absolute) or p_rel (relative)."""
dof_pos_offset: Sequence[float] | None = None
"""Offset to DOF position command given to controller. (default: None).
If None then position offsets are set to zero.
"""
impedance_mode: str = MISSING
"""Type of gains: "fixed", "variable", "variable_kp"."""
inertial_compensation: bool = False
"""Whether to perform inertial compensation (inverse dynamics)."""
gravity_compensation: bool = False
"""Whether to perform gravity compensation."""
stiffness: float | Sequence[float] = MISSING
"""The positional gain for determining desired torques based on joint position error."""
damping_ratio: float | Sequence[float] | None = None
"""The damping ratio is used in-conjunction with positional gain to compute desired torques
based on joint velocity error.
The following math operation is performed for computing velocity gains:
:math:`d_gains = 2 * sqrt(p_gains) * damping_ratio`.
"""
stiffness_limits: tuple[float, float] = (0, 300)
"""Minimum and maximum values for positional gains.
Note: Used only when :obj:`impedance_mode` is "variable" or "variable_kp".
"""
damping_ratio_limits: tuple[float, float] = (0, 100)
"""Minimum and maximum values for damping ratios used to compute velocity gains.
Note: Used only when :obj:`impedance_mode` is "variable".
"""
class JointImpedanceController:
"""Joint impedance regulation control.
Reference:
[1] https://ethz.ch/content/dam/ethz/special-interest/mavt/robotics-n-intelligent-systems/rsl-dam/documents/RobotDynamics2017/RD_HS2017script.pdf
"""
def __init__(self, cfg: JointImpedanceControllerCfg, num_robots: int, dof_pos_limits: torch.Tensor, device: str):
"""Initialize joint impedance controller.
Args:
cfg: The configuration for the controller.
num_robots: The number of robots to control.
dof_pos_limits: The joint position limits for each robot. This is a tensor of shape
(num_robots, num_dof, 2) where the last dimension contains the lower and upper limits.
device: The device to use for computations.
Raises:
ValueError: When the shape of :obj:`dof_pos_limits` is not (num_robots, num_dof, 2).
"""
# check valid inputs
if len(dof_pos_limits.shape) != 3:
raise ValueError(f"Joint position limits has shape '{dof_pos_limits.shape}'. Expected length of shape = 3.")
# store inputs
self.cfg = cfg
self.num_robots = num_robots
self.num_dof = dof_pos_limits.shape[1] # (num_robots, num_dof, 2)
self._device = device
# create buffers
# -- commands
self._dof_pos_target = torch.zeros(self.num_robots, self.num_dof, device=self._device)
# -- offsets
self._dof_pos_offset = torch.zeros(self.num_robots, self.num_dof, device=self._device)
# -- limits
self._dof_pos_limits = dof_pos_limits
# -- positional gains
self._p_gains = torch.zeros(self.num_robots, self.num_dof, device=self._device)
self._p_gains[:] = torch.tensor(self.cfg.stiffness, device=self._device)
# -- velocity gains
self._d_gains = torch.zeros(self.num_robots, self.num_dof, device=self._device)
self._d_gains[:] = 2 * torch.sqrt(self._p_gains) * torch.tensor(self.cfg.damping_ratio, device=self._device)
# -- position offsets
if self.cfg.dof_pos_offset is not None:
self._dof_pos_offset[:] = torch.tensor(self.cfg.dof_pos_offset, device=self._device)
# -- position gain limits
self._p_gains_limits = torch.zeros_like(self._dof_pos_limits)
self._p_gains_limits[..., 0] = self.cfg.stiffness_limits[0]
self._p_gains_limits[..., 1] = self.cfg.stiffness_limits[1]
# -- damping ratio limits
self._damping_ratio_limits = torch.zeros_like(self._dof_pos_limits)
self._damping_ratio_limits[..., 0] = self.cfg.damping_ratio_limits[0]
self._damping_ratio_limits[..., 1] = self.cfg.damping_ratio_limits[1]
"""
Properties.
"""
@property
def num_actions(self) -> int:
"""Dimension of the action space of controller."""
# impedance mode
if self.cfg.impedance_mode == "fixed":
# joint positions
return self.num_dof
elif self.cfg.impedance_mode == "variable_kp":
# joint positions + stiffness
return self.num_dof * 2
elif self.cfg.impedance_mode == "variable":
# joint positions + stiffness + damping
return self.num_dof * 3
else:
raise ValueError(f"Invalid impedance mode: {self.cfg.impedance_mode}.")
"""
Operations.
"""
def initialize(self):
"""Initialize the internals."""
pass
def reset_idx(self, robot_ids: torch.Tensor = None):
"""Reset the internals."""
pass
def set_command(self, command: torch.Tensor):
"""Set target end-effector pose command.
Args:
command: The command to set. This is a tensor of shape (num_robots, num_actions) where
:obj:`num_actions` is the dimension of the action space of the controller.
"""
# check input size
if command.shape != (self.num_robots, self.num_actions):
raise ValueError(
f"Invalid command shape '{command.shape}'. Expected: '{(self.num_robots, self.num_actions)}'."
)
# impedance mode
if self.cfg.impedance_mode == "fixed":
# joint positions
self._dof_pos_target[:] = command
elif self.cfg.impedance_mode == "variable_kp":
# split input command
dof_pos_command, stiffness = torch.tensor_split(command, 2, dim=-1)
# format command
stiffness = stiffness.clip_(min=self._p_gains_limits[0], max=self._p_gains_limits[1])
# joint positions + stiffness
self._dof_pos_target[:] = dof_pos_command
self._p_gains[:] = stiffness
self._d_gains[:] = 2 * torch.sqrt(self._p_gains) # critically damped
elif self.cfg.impedance_mode == "variable":
# split input command
dof_pos_command, stiffness, damping_ratio = torch.tensor_split(command, 3, dim=-1)
# format command
stiffness = stiffness.clip_(min=self._p_gains_limits[0], max=self._p_gains_limits[1])
damping_ratio = damping_ratio.clip_(min=self._damping_ratio_limits[0], max=self._damping_ratio_limits[1])
# joint positions + stiffness + damping
self._dof_pos_target[:] = dof_pos_command
self._p_gains[:] = stiffness
self._d_gains[:] = 2 * torch.sqrt(self._p_gains) * damping_ratio
else:
raise ValueError(f"Invalid impedance mode: {self.cfg.impedance_mode}.")
def compute(
self,
dof_pos: torch.Tensor,
dof_vel: torch.Tensor,
mass_matrix: torch.Tensor | None = None,
gravity: torch.Tensor | None = None,
) -> torch.Tensor:
"""Performs inference with the controller.
Args:
dof_pos: The current joint positions.
dof_vel: The current joint velocities.
mass_matrix: The joint-space inertial matrix. Defaults to None.
gravity: The joint-space gravity vector. Defaults to None.
Raises:
ValueError: When the command type is invalid.
Returns:
The target joint torques commands.
"""
# resolve the command type
if self.cfg.command_type == "p_abs":
desired_dof_pos = self._dof_pos_target + self._dof_pos_offset
elif self.cfg.command_type == "p_rel":
desired_dof_pos = self._dof_pos_target + dof_pos
else:
raise ValueError(f"Invalid dof position command mode: {self.cfg.command_type}.")
# compute errors
desired_dof_pos = desired_dof_pos.clip_(min=self._dof_pos_limits[..., 0], max=self._dof_pos_limits[..., 1])
dof_pos_error = desired_dof_pos - dof_pos
dof_vel_error = -dof_vel
# compute acceleration
des_dof_acc = self._p_gains * dof_pos_error + self._d_gains * dof_vel_error
# compute torques
# -- inertial compensation
if self.cfg.inertial_compensation:
# inverse dynamics control
desired_torques = mass_matrix @ des_dof_acc
else:
# decoupled spring-mass control
desired_torques = des_dof_acc
# -- gravity compensation (bias correction)
if self.cfg.gravity_compensation:
desired_torques += gravity
return desired_torques
| 9,284 | Python | 39.369565 | 153 | 0.615037 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/controllers/config/rmp_flow.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import os
from omni.isaac.core.utils.extensions import get_extension_path_from_name
from omni.isaac.orbit.controllers.rmp_flow import RmpFlowControllerCfg
# Note: RMP-Flow config files for supported robots are stored in the motion_generation extension
_RMP_CONFIG_DIR = os.path.join(get_extension_path_from_name("omni.isaac.motion_generation"), "motion_policy_configs")
# Path to current directory
_CUR_DIR = os.path.dirname(os.path.realpath(__file__))
FRANKA_RMPFLOW_CFG = RmpFlowControllerCfg(
config_file=os.path.join(_RMP_CONFIG_DIR, "franka", "rmpflow", "franka_rmpflow_common.yaml"),
urdf_file=os.path.join(_CUR_DIR, "data", "lula_franka_gen.urdf"),
collision_file=os.path.join(_RMP_CONFIG_DIR, "franka", "rmpflow", "robot_descriptor.yaml"),
frame_name="panda_end_effector",
evaluations_per_frame=5,
)
"""Configuration of RMPFlow for Franka arm (default from `omni.isaac.motion_generation`)."""
UR10_RMPFLOW_CFG = RmpFlowControllerCfg(
config_file=os.path.join(_RMP_CONFIG_DIR, "ur10", "rmpflow", "ur10_rmpflow_config.yaml"),
urdf_file=os.path.join(_RMP_CONFIG_DIR, "ur10", "ur10_robot.urdf"),
collision_file=os.path.join(_RMP_CONFIG_DIR, "ur10", "rmpflow", "ur10_robot_description.yaml"),
frame_name="ee_link",
evaluations_per_frame=5,
)
"""Configuration of RMPFlow for UR10 arm (default from `omni.isaac.motion_generation`)."""
| 1,506 | Python | 40.86111 | 117 | 0.730412 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/controllers/config/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
| 122 | Python | 23.599995 | 56 | 0.745902 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package containing simulation-specific functionalities.
These include:
* Ability to spawn different objects and materials into Omniverse
* Define and modify various schemas on USD prims
* Converters to obtain USD file from other file formats (such as URDF, OBJ, STL, FBX)
* Utility class to control the simulator
.. note::
Currently, only a subset of all possible schemas and prims in Omniverse are supported.
We are expanding the these set of functions on a need basis. In case, there are
specific prims or schemas that you would like to include, please open an issue on GitHub
as a feature request elaborating on the required application.
To make it convenient to use the module, we recommend importing the module as follows:
.. code-block:: python
import omni.isaac.orbit.sim as sim_utils
"""
from .converters import * # noqa: F401, F403
from .schemas import * # noqa: F401, F403
from .simulation_cfg import PhysxCfg, SimulationCfg # noqa: F401, F403
from .simulation_context import SimulationContext, build_simulation_context # noqa: F401, F403
from .spawners import * # noqa: F401, F403
from .utils import * # noqa: F401, F403
| 1,296 | Python | 36.057142 | 95 | 0.75463 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/utils.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module with USD-related utilities."""
from __future__ import annotations
import functools
import inspect
import re
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
import carb
import omni.isaac.core.utils.stage as stage_utils
import omni.kit.commands
from omni.isaac.cloner import Cloner
from pxr import PhysxSchema, Sdf, Semantics, Usd, UsdGeom, UsdPhysics, UsdShade
from omni.isaac.orbit.utils.string import to_camel_case
from . import schemas
if TYPE_CHECKING:
from .spawners.spawner_cfg import SpawnerCfg
"""
Attribute - Setters.
"""
def safe_set_attribute_on_usd_schema(schema_api: Usd.APISchemaBase, name: str, value: Any, camel_case: bool):
"""Set the value of an attribute on its USD schema if it exists.
A USD API schema serves as an interface or API for authoring and extracting a set of attributes.
They typically derive from the :class:`pxr.Usd.SchemaBase` class. This function checks if the
attribute exists on the schema and sets the value of the attribute if it exists.
Args:
schema_api: The USD schema to set the attribute on.
name: The name of the attribute.
value: The value to set the attribute to.
camel_case: Whether to convert the attribute name to camel case.
Raises:
TypeError: When the input attribute name does not exist on the provided schema API.
"""
# if value is None, do nothing
if value is None:
return
# convert attribute name to camel case
if camel_case:
attr_name = to_camel_case(name, to="CC")
else:
attr_name = name
# retrieve the attribute
# reference: https://openusd.org/dev/api/_usd__page__common_idioms.html#Usd_Create_Or_Get_Property
attr = getattr(schema_api, f"Create{attr_name}Attr", None)
# check if attribute exists
if attr is not None:
attr().Set(value)
else:
# think: do we ever need to create the attribute if it doesn't exist?
# currently, we are not doing this since the schemas are already created with some defaults.
carb.log_error(f"Attribute '{attr_name}' does not exist on prim '{schema_api.GetPath()}'.")
raise TypeError(f"Attribute '{attr_name}' does not exist on prim '{schema_api.GetPath()}'.")
def safe_set_attribute_on_usd_prim(prim: Usd.Prim, attr_name: str, value: Any, camel_case: bool):
"""Set the value of a attribute on its USD prim.
The function creates a new attribute if it does not exist on the prim. This is because in some cases (such
as with shaders), their attributes are not exposed as USD prim properties that can be altered. This function
allows us to set the value of the attributes in these cases.
Args:
prim: The USD prim to set the attribute on.
attr_name: The name of the attribute.
value: The value to set the attribute to.
camel_case: Whether to convert the attribute name to camel case.
"""
# if value is None, do nothing
if value is None:
return
# convert attribute name to camel case
if camel_case:
attr_name = to_camel_case(attr_name, to="cC")
# resolve sdf type based on value
if isinstance(value, bool):
sdf_type = Sdf.ValueTypeNames.Bool
elif isinstance(value, int):
sdf_type = Sdf.ValueTypeNames.Int
elif isinstance(value, float):
sdf_type = Sdf.ValueTypeNames.Float
elif isinstance(value, (tuple, list)) and len(value) == 3 and any(isinstance(v, float) for v in value):
sdf_type = Sdf.ValueTypeNames.Float3
elif isinstance(value, (tuple, list)) and len(value) == 2 and any(isinstance(v, float) for v in value):
sdf_type = Sdf.ValueTypeNames.Float2
else:
raise NotImplementedError(
f"Cannot set attribute '{attr_name}' with value '{value}'. Please modify the code to support this type."
)
# change property
omni.kit.commands.execute(
"ChangePropertyCommand",
prop_path=Sdf.Path(f"{prim.GetPath()}.{attr_name}"),
value=value,
prev=None,
type_to_create_if_not_exist=sdf_type,
usd_context_name=prim.GetStage(),
)
"""
Decorators.
"""
def apply_nested(func: Callable) -> Callable:
"""Decorator to apply a function to all prims under a specified prim-path.
The function iterates over the provided prim path and all its children to apply input function
to all prims under the specified prim path.
If the function succeeds to apply to a prim, it will not look at the children of that prim.
This is based on the physics behavior that nested schemas are not allowed. For example, a parent prim
and its child prim cannot both have a rigid-body schema applied on them, or it is not possible to
have nested articulations.
While traversing the prims under the specified prim path, the function will throw a warning if it
does not succeed to apply the function to any prim. This is because the user may have intended to
apply the function to a prim that does not have valid attributes, or the prim may be an instanced prim.
Args:
func: The function to apply to all prims under a specified prim-path. The function
must take the prim-path and other arguments. It should return a boolean indicating whether
the function succeeded or not.
Returns:
The wrapped function that applies the function to all prims under a specified prim-path.
Raises:
ValueError: If the prim-path does not exist on the stage.
"""
@functools.wraps(func)
def wrapper(prim_path: str | Sdf.Path, *args, **kwargs):
# map args and kwargs to function signature so we can get the stage
# note: we do this to check if stage is given in arg or kwarg
sig = inspect.signature(func)
bound_args = sig.bind(prim_path, *args, **kwargs)
# get current stage
stage = bound_args.arguments.get("stage")
if stage is None:
stage = stage_utils.get_current_stage()
# get USD prim
prim: Usd.Prim = stage.GetPrimAtPath(prim_path)
# check if prim is valid
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim_path}' is not valid.")
# add iterable to check if property was applied on any of the prims
count_success = 0
instanced_prim_paths = []
# iterate over all prims under prim-path
all_prims = [prim]
while len(all_prims) > 0:
# get current prim
child_prim = all_prims.pop(0)
child_prim_path = child_prim.GetPath().pathString # type: ignore
# check if prim is a prototype
if child_prim.IsInstance():
instanced_prim_paths.append(child_prim_path)
continue
# set properties
success = func(child_prim_path, *args, **kwargs)
# if successful, do not look at children
# this is based on the physics behavior that nested schemas are not allowed
if not success:
all_prims += child_prim.GetChildren()
else:
count_success += 1
# check if we were successful in applying the function to any prim
if count_success == 0:
carb.log_warn(
f"Could not perform '{func.__name__}' on any prims under: '{prim_path}'."
" This might be because of the following reasons:"
"\n\t(1) The desired attribute does not exist on any of the prims."
"\n\t(2) The desired attribute exists on an instanced prim."
f"\n\t\tDiscovered list of instanced prim paths: {instanced_prim_paths}"
)
return wrapper
def clone(func: Callable) -> Callable:
"""Decorator for cloning a prim based on matching prim paths of the prim's parent.
The decorator checks if the parent prim path matches any prim paths in the stage. If so, it clones the
spawned prim at each matching prim path. For example, if the input prim path is: ``/World/Table_[0-9]/Bottle``,
the decorator will clone the prim at each matching prim path of the parent prim: ``/World/Table_0/Bottle``,
``/World/Table_1/Bottle``, etc.
Note:
For matching prim paths, the decorator assumes that valid prims exist for all matching prim paths.
In case no matching prim paths are found, the decorator raises a ``RuntimeError``.
Args:
func: The function to decorate.
Returns:
The decorated function that spawns the prim and clones it at each matching prim path.
It returns the spawned source prim, i.e., the first prim in the list of matching prim paths.
"""
@functools.wraps(func)
def wrapper(prim_path: str | Sdf.Path, cfg: SpawnerCfg, *args, **kwargs):
# cast prim_path to str type in case its an Sdf.Path
prim_path = str(prim_path)
# check prim path is global
if not prim_path.startswith("/"):
raise ValueError(f"Prim path '{prim_path}' is not global. It must start with '/'.")
# resolve: {SPAWN_NS}/AssetName
# note: this assumes that the spawn namespace already exists in the stage
root_path, asset_path = prim_path.rsplit("/", 1)
# check if input is a regex expression
# note: a valid prim path can only contain alphanumeric characters, underscores, and forward slashes
is_regex_expression = re.match(r"^[a-zA-Z0-9/_]+$", root_path) is None
# resolve matching prims for source prim path expression
if is_regex_expression and root_path != "":
source_prim_paths = find_matching_prim_paths(root_path)
# if no matching prims are found, raise an error
if len(source_prim_paths) == 0:
raise RuntimeError(
f"Unable to find source prim path: '{root_path}'. Please create the prim before spawning."
)
else:
source_prim_paths = [root_path]
# resolve prim paths for spawning and cloning
prim_paths = [f"{source_prim_path}/{asset_path}" for source_prim_path in source_prim_paths]
# spawn single instance
prim = func(prim_paths[0], cfg, *args, **kwargs)
# set the prim visibility
if hasattr(cfg, "visible"):
imageable = UsdGeom.Imageable(prim)
if cfg.visible:
imageable.MakeVisible()
else:
imageable.MakeInvisible()
# set the semantic annotations
if hasattr(cfg, "semantic_tags") and cfg.semantic_tags is not None:
# note: taken from replicator scripts.utils.utils.py
for semantic_type, semantic_value in cfg.semantic_tags:
# deal with spaces by replacing them with underscores
semantic_type_sanitized = semantic_type.replace(" ", "_")
semantic_value_sanitized = semantic_value.replace(" ", "_")
# set the semantic API for the instance
instance_name = f"{semantic_type_sanitized}_{semantic_value_sanitized}"
sem = Semantics.SemanticsAPI.Apply(prim, instance_name)
# create semantic type and data attributes
sem.CreateSemanticTypeAttr()
sem.CreateSemanticDataAttr()
sem.GetSemanticTypeAttr().Set(semantic_type)
sem.GetSemanticDataAttr().Set(semantic_value)
# activate rigid body contact sensors
if hasattr(cfg, "activate_contact_sensors") and cfg.activate_contact_sensors:
schemas.activate_contact_sensors(prim_paths[0], cfg.activate_contact_sensors)
# clone asset using cloner API
if len(prim_paths) > 1:
cloner = Cloner()
# clone the prim
cloner.clone(prim_paths[0], prim_paths[1:], replicate_physics=False, copy_from_source=cfg.copy_from_source)
# return the source prim
return prim
return wrapper
"""
Material bindings.
"""
@apply_nested
def bind_visual_material(
prim_path: str | Sdf.Path,
material_path: str | Sdf.Path,
stage: Usd.Stage | None = None,
stronger_than_descendants: bool = True,
):
"""Bind a visual material to a prim.
This function is a wrapper around the USD command `BindMaterialCommand`_.
.. note::
The function is decorated with :meth:`apply_nested` to allow applying the function to a prim path
and all its descendants.
.. _BindMaterialCommand: https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd.commands/omni.usd.commands.BindMaterialCommand.html
Args:
prim_path: The prim path where to apply the material.
material_path: The prim path of the material to apply.
stage: The stage where the prim and material exist.
Defaults to None, in which case the current stage is used.
stronger_than_descendants: Whether the material should override the material of its descendants.
Defaults to True.
Raises:
ValueError: If the provided prim paths do not exist on stage.
"""
# resolve stage
if stage is None:
stage = stage_utils.get_current_stage()
# check if prim and material exists
if not stage.GetPrimAtPath(prim_path).IsValid():
raise ValueError(f"Target prim '{material_path}' does not exist.")
if not stage.GetPrimAtPath(material_path).IsValid():
raise ValueError(f"Visual material '{material_path}' does not exist.")
# resolve token for weaker than descendants
if stronger_than_descendants:
binding_strength = "strongerThanDescendants"
else:
binding_strength = "weakerThanDescendants"
# obtain material binding API
# note: we prefer using the command here as it is more robust than the USD API
success, _ = omni.kit.commands.execute(
"BindMaterialCommand",
prim_path=prim_path,
material_path=material_path,
strength=binding_strength,
stage=stage,
)
# return success
return success
@apply_nested
def bind_physics_material(
prim_path: str | Sdf.Path,
material_path: str | Sdf.Path,
stage: Usd.Stage | None = None,
stronger_than_descendants: bool = True,
):
"""Bind a physics material to a prim.
`Physics material`_ can be applied only to a prim with physics-enabled on them. This includes having
collision APIs, or deformable body APIs, or being a particle system. In case the prim does not have
any of these APIs, the function will not apply the material and return False.
.. note::
The function is decorated with :meth:`apply_nested` to allow applying the function to a prim path
and all its descendants.
.. _Physics material: https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/simulation-control/physics-settings.html#physics-materials
Args:
prim_path: The prim path where to apply the material.
material_path: The prim path of the material to apply.
stage: The stage where the prim and material exist.
Defaults to None, in which case the current stage is used.
stronger_than_descendants: Whether the material should override the material of its descendants.
Defaults to True.
Raises:
ValueError: If the provided prim paths do not exist on stage.
"""
# resolve stage
if stage is None:
stage = stage_utils.get_current_stage()
# check if prim and material exists
if not stage.GetPrimAtPath(prim_path).IsValid():
raise ValueError(f"Target prim '{material_path}' does not exist.")
if not stage.GetPrimAtPath(material_path).IsValid():
raise ValueError(f"Physics material '{material_path}' does not exist.")
# get USD prim
prim = stage.GetPrimAtPath(prim_path)
# check if prim has collision applied on it
has_physics_scene_api = prim.HasAPI(PhysxSchema.PhysxSceneAPI)
has_collider = prim.HasAPI(UsdPhysics.CollisionAPI)
has_deformable_body = prim.HasAPI(PhysxSchema.PhysxDeformableBodyAPI)
has_particle_system = prim.IsA(PhysxSchema.PhysxParticleSystem)
if not (has_physics_scene_api or has_collider or has_deformable_body or has_particle_system):
carb.log_verbose(
f"Cannot apply physics material '{material_path}' on prim '{prim_path}'. It is neither a"
" PhysX scene, collider, a deformable body, nor a particle system."
)
return False
# obtain material binding API
if prim.HasAPI(UsdShade.MaterialBindingAPI):
material_binding_api = UsdShade.MaterialBindingAPI(prim)
else:
material_binding_api = UsdShade.MaterialBindingAPI.Apply(prim)
# obtain the material prim
material = UsdShade.Material(stage.GetPrimAtPath(material_path))
# resolve token for weaker than descendants
if stronger_than_descendants:
binding_strength = UsdShade.Tokens.strongerThanDescendants
else:
binding_strength = UsdShade.Tokens.weakerThanDescendants
# apply the material
material_binding_api.Bind(material, bindingStrength=binding_strength, materialPurpose="physics") # type: ignore
# return success
return True
"""
Exporting.
"""
def export_prim_to_file(
path: str | Sdf.Path,
source_prim_path: str | Sdf.Path,
target_prim_path: str | Sdf.Path | None = None,
stage: Usd.Stage | None = None,
):
"""Exports a prim from a given stage to a USD file.
The function creates a new layer at the provided path and copies the prim to the layer.
It sets the copied prim as the default prim in the target layer. Additionally, it updates
the stage up-axis and meters-per-unit to match the current stage.
Args:
path: The filepath path to export the prim to.
source_prim_path: The prim path to export.
target_prim_path: The prim path to set as the default prim in the target layer.
Defaults to None, in which case the source prim path is used.
stage: The stage where the prim exists. Defaults to None, in which case the
current stage is used.
Raises:
ValueError: If the prim paths are not global (i.e: do not start with '/').
"""
# automatically casting to str in case args
# are path types
path = str(path)
source_prim_path = str(source_prim_path)
if target_prim_path is not None:
target_prim_path = str(target_prim_path)
if not source_prim_path.startswith("/"):
raise ValueError(f"Source prim path '{source_prim_path}' is not global. It must start with '/'.")
if target_prim_path is not None and not target_prim_path.startswith("/"):
raise ValueError(f"Target prim path '{target_prim_path}' is not global. It must start with '/'.")
# get current stage
if stage is None:
stage: Usd.Stage = omni.usd.get_context().get_stage()
# get root layer
source_layer = stage.GetRootLayer()
# only create a new layer if it doesn't exist already
target_layer = Sdf.Find(path)
if target_layer is None:
target_layer = Sdf.Layer.CreateNew(path)
# open the target stage
target_stage = Usd.Stage.Open(target_layer)
# update stage data
UsdGeom.SetStageUpAxis(target_stage, UsdGeom.GetStageUpAxis(stage))
UsdGeom.SetStageMetersPerUnit(target_stage, UsdGeom.GetStageMetersPerUnit(stage))
# specify the prim to copy
source_prim_path = Sdf.Path(source_prim_path)
if target_prim_path is None:
target_prim_path = source_prim_path
# copy the prim
Sdf.CreatePrimInLayer(target_layer, target_prim_path)
Sdf.CopySpec(source_layer, source_prim_path, target_layer, target_prim_path)
# set the default prim
target_layer.defaultPrim = Sdf.Path(target_prim_path).name
# resolve all paths relative to layer path
omni.usd.resolve_paths(source_layer.identifier, target_layer.identifier)
# save the stage
target_layer.Save()
"""
USD Prim properties.
"""
def make_uninstanceable(prim_path: str | Sdf.Path, stage: Usd.Stage | None = None):
"""Check if a prim and its descendants are instanced and make them uninstanceable.
This function checks if the prim at the specified prim path and its descendants are instanced.
If so, it makes the respective prim uninstanceable by disabling instancing on the prim.
This is useful when we want to modify the properties of a prim that is instanced. For example, if we
want to apply a different material on an instanced prim, we need to make the prim uninstanceable first.
Args:
prim_path: The prim path to check.
stage: The stage where the prim exists. Defaults to None, in which case the current stage is used.
Raises:
ValueError: If the prim path is not global (i.e: does not start with '/').
"""
# make paths str type if they aren't already
prim_path = str(prim_path)
# check if prim path is global
if not prim_path.startswith("/"):
raise ValueError(f"Prim path '{prim_path}' is not global. It must start with '/'.")
# get current stage
if stage is None:
stage = stage_utils.get_current_stage()
# get prim
prim: Usd.Prim = stage.GetPrimAtPath(prim_path)
# check if prim is valid
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim_path}' is not valid.")
# iterate over all prims under prim-path
all_prims = [prim]
while len(all_prims) > 0:
# get current prim
child_prim = all_prims.pop(0)
# check if prim is instanced
if child_prim.IsInstance():
# make the prim uninstanceable
child_prim.SetInstanceable(False)
# add children to list
all_prims += child_prim.GetChildren()
"""
USD Stage traversal.
"""
def get_first_matching_child_prim(
prim_path: str | Sdf.Path, predicate: Callable[[Usd.Prim], bool], stage: Usd.Stage | None = None
) -> Usd.Prim | None:
"""Recursively get the first USD Prim at the path string that passes the predicate function
Args:
prim_path: The path of the prim in the stage.
predicate: The function to test the prims against. It takes a prim as input and returns a boolean.
stage: The stage where the prim exists. Defaults to None, in which case the current stage is used.
Returns:
The first prim on the path that passes the predicate. If no prim passes the predicate, it returns None.
Raises:
ValueError: If the prim path is not global (i.e: does not start with '/').
"""
# make paths str type if they aren't already
prim_path = str(prim_path)
# check if prim path is global
if not prim_path.startswith("/"):
raise ValueError(f"Prim path '{prim_path}' is not global. It must start with '/'.")
# get current stage
if stage is None:
stage = stage_utils.get_current_stage()
# get prim
prim = stage.GetPrimAtPath(prim_path)
# check if prim is valid
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim_path}' is not valid.")
# iterate over all prims under prim-path
all_prims = [prim]
while len(all_prims) > 0:
# get current prim
child_prim = all_prims.pop(0)
# check if prim passes predicate
if predicate(child_prim):
return child_prim
# add children to list
all_prims += child_prim.GetChildren()
return None
def get_all_matching_child_prims(
prim_path: str | Sdf.Path,
predicate: Callable[[Usd.Prim], bool] = lambda _: True,
depth: int | None = None,
stage: Usd.Stage | None = None,
) -> list[Usd.Prim]:
"""Performs a search starting from the root and returns all the prims matching the predicate.
Args:
prim_path: The root prim path to start the search from.
predicate: The predicate that checks if the prim matches the desired criteria. It takes a prim as input
and returns a boolean. Defaults to a function that always returns True.
depth: The maximum depth for traversal, should be bigger than zero if specified.
Defaults to None (i.e: traversal happens till the end of the tree).
stage: The stage where the prim exists. Defaults to None, in which case the current stage is used.
Returns:
A list containing all the prims matching the predicate.
Raises:
ValueError: If the prim path is not global (i.e: does not start with '/').
"""
# make paths str type if they aren't already
prim_path = str(prim_path)
# check if prim path is global
if not prim_path.startswith("/"):
raise ValueError(f"Prim path '{prim_path}' is not global. It must start with '/'.")
# get current stage
if stage is None:
stage = stage_utils.get_current_stage()
# get prim
prim = stage.GetPrimAtPath(prim_path)
# check if prim is valid
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim_path}' is not valid.")
# check if depth is valid
if depth is not None and depth <= 0:
raise ValueError(f"Depth must be bigger than zero, got {depth}.")
# iterate over all prims under prim-path
# list of tuples (prim, current_depth)
all_prims_queue = [(prim, 0)]
output_prims = []
while len(all_prims_queue) > 0:
# get current prim
child_prim, current_depth = all_prims_queue.pop(0)
# check if prim passes predicate
if predicate(child_prim):
output_prims.append(child_prim)
# add children to list
if depth is None or current_depth < depth:
all_prims_queue += [(child, current_depth + 1) for child in child_prim.GetChildren()]
return output_prims
def find_first_matching_prim(prim_path_regex: str, stage: Usd.Stage | None = None) -> Usd.Prim | None:
"""Find the first matching prim in the stage based on input regex expression.
Args:
prim_path_regex: The regex expression for prim path.
stage: The stage where the prim exists. Defaults to None, in which case the current stage is used.
Returns:
The first prim that matches input expression. If no prim matches, returns None.
Raises:
ValueError: If the prim path is not global (i.e: does not start with '/').
"""
# check prim path is global
if not prim_path_regex.startswith("/"):
raise ValueError(f"Prim path '{prim_path_regex}' is not global. It must start with '/'.")
# get current stage
if stage is None:
stage = stage_utils.get_current_stage()
# need to wrap the token patterns in '^' and '$' to prevent matching anywhere in the string
pattern = f"^{prim_path_regex}$"
compiled_pattern = re.compile(pattern)
# obtain matching prim (depth-first search)
for prim in stage.Traverse():
# check if prim passes predicate
if compiled_pattern.match(prim.GetPath().pathString) is not None:
return prim
return None
def find_matching_prims(prim_path_regex: str, stage: Usd.Stage | None = None) -> list[Usd.Prim]:
"""Find all the matching prims in the stage based on input regex expression.
Args:
prim_path_regex: The regex expression for prim path.
stage: The stage where the prim exists. Defaults to None, in which case the current stage is used.
Returns:
A list of prims that match input expression.
Raises:
ValueError: If the prim path is not global (i.e: does not start with '/').
"""
# check prim path is global
if not prim_path_regex.startswith("/"):
raise ValueError(f"Prim path '{prim_path_regex}' is not global. It must start with '/'.")
# get current stage
if stage is None:
stage = stage_utils.get_current_stage()
# need to wrap the token patterns in '^' and '$' to prevent matching anywhere in the string
tokens = prim_path_regex.split("/")[1:]
tokens = [f"^{token}$" for token in tokens]
# iterate over all prims in stage (breath-first search)
all_prims = [stage.GetPseudoRoot()]
output_prims = []
for index, token in enumerate(tokens):
token_compiled = re.compile(token)
for prim in all_prims:
for child in prim.GetAllChildren():
if token_compiled.match(child.GetName()) is not None:
output_prims.append(child)
if index < len(tokens) - 1:
all_prims = output_prims
output_prims = []
return output_prims
def find_matching_prim_paths(prim_path_regex: str, stage: Usd.Stage | None = None) -> list[str]:
"""Find all the matching prim paths in the stage based on input regex expression.
Args:
prim_path_regex: The regex expression for prim path.
stage: The stage where the prim exists. Defaults to None, in which case the current stage is used.
Returns:
A list of prim paths that match input expression.
Raises:
ValueError: If the prim path is not global (i.e: does not start with '/').
"""
# obtain matching prims
output_prims = find_matching_prims(prim_path_regex, stage)
# convert prims to prim paths
output_prim_paths = []
for prim in output_prims:
output_prim_paths.append(prim.GetPath().pathString)
return output_prim_paths
def find_global_fixed_joint_prim(
prim_path: str | Sdf.Path, check_enabled_only: bool = False, stage: Usd.Stage | None = None
) -> UsdPhysics.Joint | None:
"""Find the fixed joint prim under the specified prim path that connects the target to the simulation world.
A joint is a connection between two bodies. A fixed joint is a joint that does not allow relative motion
between the two bodies. When a fixed joint has only one target body, it is considered to attach the body
to the simulation world.
This function finds the fixed joint prim that has only one target under the specified prim path. If no such
fixed joint prim exists, it returns None.
Args:
prim_path: The prim path to search for the fixed joint prim.
check_enabled_only: Whether to consider only enabled fixed joints. Defaults to False.
If False, then all joints (enabled or disabled) are considered.
stage: The stage where the prim exists. Defaults to None, in which case the current stage is used.
Returns:
The fixed joint prim that has only one target. If no such fixed joint prim exists, it returns None.
Raises:
ValueError: If the prim path is not global (i.e: does not start with '/').
ValueError: If the prim path does not exist on the stage.
"""
# check prim path is global
if not prim_path.startswith("/"):
raise ValueError(f"Prim path '{prim_path}' is not global. It must start with '/'.")
# get current stage
if stage is None:
stage = stage_utils.get_current_stage()
# check if prim exists
prim = stage.GetPrimAtPath(prim_path)
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim_path}' is not valid.")
fixed_joint_prim = None
# we check all joints under the root prim and classify the asset as fixed base if there exists
# a fixed joint that has only one target (i.e. the root link).
for prim in Usd.PrimRange(prim):
# note: ideally checking if it is FixedJoint would have been enough, but some assets use "Joint" as the
# schema name which makes it difficult to distinguish between the two.
joint_prim = UsdPhysics.Joint(prim)
if joint_prim:
# if check_enabled_only is True, we only consider enabled joints
if check_enabled_only and not joint_prim.GetJointEnabledAttr().Get():
continue
# check body 0 and body 1 exist
body_0_exist = joint_prim.GetBody0Rel().GetTargets() != []
body_1_exist = joint_prim.GetBody1Rel().GetTargets() != []
# if either body 0 or body 1 does not exist, we have a fixed joint that connects to the world
if not (body_0_exist and body_1_exist):
fixed_joint_prim = joint_prim
break
return fixed_joint_prim
"""
USD Variants.
"""
def select_usd_variants(prim_path: str, variants: object | dict[str, str], stage: Usd.Stage | None = None):
"""Sets the variant selections from the specified variant sets on a USD prim.
`USD Variants`_ are a very powerful tool in USD composition that allows prims to have different options on
a single asset. This can be done by modifying variations of the same prim parameters per variant option in a set.
This function acts as a script-based utility to set the variant selections for the specified variant sets on a
USD prim.
The function takes a dictionary or a config class mapping variant set names to variant selections. For instance,
if we have a prim at ``"/World/Table"`` with two variant sets: "color" and "size", we can set the variant
selections as follows:
.. code-block:: python
select_usd_variants(
prim_path="/World/Table",
variants={
"color": "red",
"size": "large",
},
)
Alternatively, we can use a config class to define the variant selections:
.. code-block:: python
@configclass
class TableVariants:
color: Literal["blue", "red"] = "red"
size: Literal["small", "large"] = "large"
select_usd_variants(
prim_path="/World/Table",
variants=TableVariants(),
)
Args:
prim_path: The path of the USD prim.
variants: A dictionary or config class mapping variant set names to variant selections.
stage: The USD stage. Defaults to None, in which case, the current stage is used.
Raises:
ValueError: If the prim at the specified path is not valid.
.. _USD Variants: https://graphics.pixar.com/usd/docs/USD-Glossary.html#USDGlossary-Variant
"""
# Resolve stage
if stage is None:
stage = stage_utils.get_current_stage()
# Obtain prim
prim = stage.GetPrimAtPath(prim_path)
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim_path}' is not valid.")
# Convert to dict if we have a configclass object.
if not isinstance(variants, dict):
variants = variants.to_dict()
existing_variant_sets = prim.GetVariantSets()
for variant_set_name, variant_selection in variants.items():
# Check if the variant set exists on the prim.
if not existing_variant_sets.HasVariantSet(variant_set_name):
carb.log_warn(f"Variant set '{variant_set_name}' does not exist on prim '{prim_path}'.")
continue
variant_set = existing_variant_sets.GetVariantSet(variant_set_name)
# Only set the variant selection if it is different from the current selection.
if variant_set.GetVariantSelection() != variant_selection:
variant_set.SetVariantSelection(variant_selection)
carb.log_info(
f"Setting variant selection '{variant_selection}' for variant set '{variant_set_name}' on"
f" prim '{prim_path}'."
)
| 35,488 | Python | 40.314319 | 148 | 0.658279 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/simulation_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Base configuration of the environment.
This module defines the general configuration of the environment. It includes parameters for
configuring the environment instances, viewer settings, and simulation parameters.
"""
from typing import Literal
from omni.isaac.orbit.utils import configclass
from .spawners.materials import RigidBodyMaterialCfg
@configclass
class PhysxCfg:
"""Configuration for PhysX solver-related parameters.
These parameters are used to configure the PhysX solver. For more information, see the `PhysX 5 SDK
documentation`_.
PhysX 5 supports GPU-accelerated physics simulation. This is enabled by default, but can be disabled
through the flag `use_gpu`. Unlike CPU PhysX, the GPU simulation feature is not able to dynamically
grow all the buffers. Therefore, it is necessary to provide a reasonable estimate of the buffer sizes
for GPU features. If insufficient buffer sizes are provided, the simulation will fail with errors and
lead to adverse behaviors. The buffer sizes can be adjusted through the `gpu_*` parameters.
.. _PhysX 5 SDK documentation: https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/_api_build/class_px_scene_desc.html
"""
use_gpu: bool = True
"""Enable/disable GPU accelerated dynamics simulation. Default is True.
This enables GPU-accelerated implementations for broad-phase collision checks, contact generation,
shape and body management, and constrained solver.
"""
solver_type: Literal[0, 1] = 1
"""The type of solver to use.Default is 1 (TGS).
Available solvers:
* :obj:`0`: PGS (Projective Gauss-Seidel)
* :obj:`1`: TGS (Truncated Gauss-Seidel)
"""
min_position_iteration_count: int = 1
"""Minimum number of solver position iterations (rigid bodies, cloth, particles etc.). Default is 1.
.. note::
Each physics actor in Omniverse specifies its own solver iteration count. The solver takes
the number of iterations specified by the actor with the highest iteration and clamps it to
the range ``[min_position_iteration_count, max_position_iteration_count]``.
"""
max_position_iteration_count: int = 255
"""Maximum number of solver position iterations (rigid bodies, cloth, particles etc.). Default is 255.
.. note::
Each physics actor in Omniverse specifies its own solver iteration count. The solver takes
the number of iterations specified by the actor with the highest iteration and clamps it to
the range ``[min_position_iteration_count, max_position_iteration_count]``.
"""
min_velocity_iteration_count: int = 0
"""Minimum number of solver position iterations (rigid bodies, cloth, particles etc.). Default is 0.
.. note::
Each physics actor in Omniverse specifies its own solver iteration count. The solver takes
the number of iterations specified by the actor with the highest iteration and clamps it to
the range ``[min_velocity_iteration_count, max_velocity_iteration_count]``.
"""
max_velocity_iteration_count: int = 255
"""Maximum number of solver position iterations (rigid bodies, cloth, particles etc.). Default is 255.
.. note::
Each physics actor in Omniverse specifies its own solver iteration count. The solver takes
the number of iterations specified by the actor with the highest iteration and clamps it to
the range ``[min_velocity_iteration_count, max_velocity_iteration_count]``.
"""
enable_ccd: bool = False
"""Enable a second broad-phase pass that makes it possible to prevent objects from tunneling through each other.
Default is False."""
enable_stabilization: bool = True
"""Enable/disable additional stabilization pass in solver. Default is True."""
enable_enhanced_determinism: bool = False
"""Enable/disable improved determinism at the expense of performance. Defaults to False.
For more information on PhysX determinism, please check `here`_.
.. _here: https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/docs/RigidBodyDynamics.html#enhanced-determinism
"""
bounce_threshold_velocity: float = 0.5
"""Relative velocity threshold for contacts to bounce (in m/s). Default is 0.5 m/s."""
friction_offset_threshold: float = 0.04
"""Threshold for contact point to experience friction force (in m). Default is 0.04 m."""
friction_correlation_distance: float = 0.025
"""Distance threshold for merging contacts into a single friction anchor point (in m). Default is 0.025 m."""
gpu_max_rigid_contact_count: int = 2**23
"""Size of rigid contact stream buffer allocated in pinned host memory. Default is 2 ** 23."""
gpu_max_rigid_patch_count: int = 5 * 2**15
"""Size of the rigid contact patch stream buffer allocated in pinned host memory. Default is 5 * 2 ** 15."""
gpu_found_lost_pairs_capacity: int = 2**21
"""Capacity of found and lost buffers allocated in GPU global memory. Default is 2 ** 21.
This is used for the found/lost pair reports in the BP.
"""
gpu_found_lost_aggregate_pairs_capacity: int = 2**25
"""Capacity of found and lost buffers in aggregate system allocated in GPU global memory.
Default is 2 ** 25.
This is used for the found/lost pair reports in AABB manager.
"""
gpu_total_aggregate_pairs_capacity: int = 2**21
"""Capacity of total number of aggregate pairs allocated in GPU global memory. Default is 2 ** 21."""
gpu_collision_stack_size: int = 2**26
"""Size of the collision stack buffer allocated in pinned host memory. Default is 2 ** 26."""
gpu_heap_capacity: int = 2**26
"""Initial capacity of the GPU and pinned host memory heaps. Additional memory will be allocated
if more memory is required. Default is 2 ** 26."""
gpu_temp_buffer_capacity: int = 2**24
"""Capacity of temp buffer allocated in pinned host memory. Default is 2 ** 24."""
gpu_max_num_partitions: int = 8
"""Limitation for the partitions in the GPU dynamics pipeline. Default is 8.
This variable must be power of 2. A value greater than 32 is currently not supported. Range: (1, 32)
"""
gpu_max_soft_body_contacts: int = 2**20
"""Size of soft body contacts stream buffer allocated in pinned host memory. Default is 2 ** 20."""
gpu_max_particle_contacts: int = 2**20
"""Size of particle contacts stream buffer allocated in pinned host memory. Default is 2 ** 20."""
@configclass
class SimulationCfg:
"""Configuration for simulation physics."""
physics_prim_path: str = "/physicsScene"
"""The prim path where the USD PhysicsScene is created. Default is "/physicsScene"."""
dt: float = 1.0 / 60.0
"""The physics simulation time-step (in seconds). Default is 0.0167 seconds."""
substeps: int = 1
"""The number of physics simulation steps per rendering step. Default is 1."""
gravity: tuple[float, float, float] = (0.0, 0.0, -9.81)
"""The gravity vector (in m/s^2). Default is (0.0, 0.0, -9.81).
If set to (0.0, 0.0, 0.0), gravity is disabled.
"""
enable_scene_query_support: bool = False
"""Enable/disable scene query support for collision shapes. Default is False.
This flag allows performing collision queries (raycasts, sweeps, and overlaps) on actors and
attached shapes in the scene. This is useful for implementing custom collision detection logic
outside of the physics engine.
If set to False, the physics engine does not create the scene query manager and the scene query
functionality will not be available. However, this provides some performance speed-up.
Note:
This flag is overridden to True inside the :class:`SimulationContext` class when running the simulation
with the GUI enabled. This is to allow certain GUI features to work properly.
"""
use_fabric: bool = True
"""Enable/disable reading of physics buffers directly. Default is True.
When running the simulation, updates in the states in the scene is normally synchronized with USD.
This leads to an overhead in reading the data and does not scale well with massive parallelization.
This flag allows disabling the synchronization and reading the data directly from the physics buffers.
It is recommended to set this flag to :obj:`True` when running the simulation with a large number
of primitives in the scene.
Note:
When enabled, the GUI will not update the physics parameters in real-time. To enable real-time
updates, please set this flag to :obj:`False`.
"""
disable_contact_processing: bool = False
"""Enable/disable contact processing. Default is False.
By default, the physics engine processes all the contacts in the scene. However, reporting this contact
information can be expensive due to its combinatorial complexity. This flag allows disabling the contact
processing and querying the contacts manually by the user over a limited set of primitives in the scene.
.. note::
It is required to set this flag to :obj:`True` when using the TensorAPIs for contact reporting.
"""
use_gpu_pipeline: bool = True
"""Enable/disable GPU pipeline. Default is True.
If set to False, the physics data will be read as CPU buffers.
"""
device: str = "cuda:0"
"""The device for running the simulation/environment. Default is ``"cuda:0"``."""
physx: PhysxCfg = PhysxCfg()
"""PhysX solver settings. Default is PhysxCfg()."""
physics_material: RigidBodyMaterialCfg = RigidBodyMaterialCfg()
"""Default physics material settings for rigid bodies. Default is RigidBodyMaterialCfg().
The physics engine defaults to this physics material for all the rigid body prims that do not have any
physics material specified on them.
The material is created at the path: ``{physics_prim_path}/defaultMaterial``.
"""
| 10,099 | Python | 40.735537 | 123 | 0.710664 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/simulation_context.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import builtins
import enum
import numpy as np
import sys
import traceback
import weakref
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
import carb
import omni.isaac.core.utils.stage as stage_utils
import omni.physx
from omni.isaac.core.simulation_context import SimulationContext as _SimulationContext
from omni.isaac.core.utils.viewports import set_camera_view
from omni.isaac.version import get_version
from pxr import Gf, PhysxSchema, Usd, UsdPhysics
from .simulation_cfg import SimulationCfg
from .spawners import DomeLightCfg, GroundPlaneCfg
from .utils import bind_physics_material
class SimulationContext(_SimulationContext):
"""A class to control simulation-related events such as physics stepping and rendering.
The simulation context helps control various simulation aspects. This includes:
* configure the simulator with different settings such as the physics time-step, the number of physics substeps,
and the physics solver parameters (for more information, see :class:`omni.isaac.orbit.sim.SimulationCfg`)
* playing, pausing, stepping and stopping the simulation
* adding and removing callbacks to different simulation events such as physics stepping, rendering, etc.
This class inherits from the :class:`omni.isaac.core.simulation_context.SimulationContext` class and
adds additional functionalities such as setting up the simulation context with a configuration object,
exposing other commonly used simulator-related functions, and performing version checks of Isaac Sim
to ensure compatibility between releases.
The simulation context is a singleton object. This means that there can only be one instance
of the simulation context at any given time. This is enforced by the parent class. Therefore, it is
not possible to create multiple instances of the simulation context. Instead, the simulation context
can be accessed using the ``instance()`` method.
.. attention::
Since we only support the ``torch <https://pytorch.org/>``_ backend for simulation, the
simulation context is configured to use the ``torch`` backend by default. This means that
all the data structures used in the simulation are ``torch.Tensor`` objects.
The simulation context can be used in two different modes of operations:
1. **Standalone python script**: In this mode, the user has full control over the simulation and
can trigger stepping events synchronously (i.e. as a blocking call). In this case the user
has to manually call :meth:`step` step the physics simulation and :meth:`render` to
render the scene.
2. **Omniverse extension**: In this mode, the user has limited control over the simulation stepping
and all the simulation events are triggered asynchronously (i.e. as a non-blocking call). In this
case, the user can only trigger the simulation to start, pause, and stop. The simulation takes
care of stepping the physics simulation and rendering the scene.
Based on above, for most functions in this class there is an equivalent function that is suffixed
with ``_async``. The ``_async`` functions are used in the Omniverse extension mode and
the non-``_async`` functions are used in the standalone python script mode.
"""
class RenderMode(enum.IntEnum):
"""Different rendering modes for the simulation.
Render modes correspond to how the viewport and other UI elements (such as listeners to keyboard or mouse
events) are updated. There are three main components that can be updated when the simulation is rendered:
1. **UI elements and other extensions**: These are UI elements (such as buttons, sliders, etc.) and other
extensions that are running in the background that need to be updated when the simulation is running.
2. **Cameras**: These are typically based on Hydra textures and are used to render the scene from different
viewpoints. They can be attached to a viewport or be used independently to render the scene.
3. **Viewports**: These are windows where you can see the rendered scene.
Updating each of the above components has a different overhead. For example, updating the viewports is
computationally expensive compared to updating the UI elements. Therefore, it is useful to be able to
control what is updated when the simulation is rendered. This is where the render mode comes in. There are
four different render modes:
* :attr:`NO_GUI_OR_RENDERING`: The simulation is running without a GUI and off-screen rendering flag is disabled,
so none of the above are updated.
* :attr:`NO_RENDERING`: No rendering, where only 1 is updated at a lower rate.
* :attr:`PARTIAL_RENDERING`: Partial rendering, where only 1 and 2 are updated.
* :attr:`FULL_RENDERING`: Full rendering, where everything (1, 2, 3) is updated.
.. _Viewports: https://docs.omniverse.nvidia.com/extensions/latest/ext_viewport.html
"""
NO_GUI_OR_RENDERING = -1
"""The simulation is running without a GUI and off-screen rendering is disabled."""
NO_RENDERING = 0
"""No rendering, where only other UI elements are updated at a lower rate."""
PARTIAL_RENDERING = 1
"""Partial rendering, where the simulation cameras and UI elements are updated."""
FULL_RENDERING = 2
"""Full rendering, where all the simulation viewports, cameras and UI elements are updated."""
def __init__(self, cfg: SimulationCfg | None = None):
"""Creates a simulation context to control the simulator.
Args:
cfg: The configuration of the simulation. Defaults to None,
in which case the default configuration is used.
"""
# store input
if cfg is None:
cfg = SimulationCfg()
self.cfg = cfg
# check that simulation is running
if stage_utils.get_current_stage() is None:
raise RuntimeError("The stage has not been created. Did you run the simulator?")
# set flags for simulator
# acquire settings interface
carb_settings_iface = carb.settings.get_settings()
# enable hydra scene-graph instancing
# note: this allows rendering of instanceable assets on the GUI
carb_settings_iface.set_bool("/persistent/omnihydra/useSceneGraphInstancing", True)
# change dispatcher to use the default dispatcher in PhysX SDK instead of carb tasking
# note: dispatcher handles how threads are launched for multi-threaded physics
carb_settings_iface.set_bool("/physics/physxDispatcher", True)
# disable contact processing in omni.physx if requested
# note: helpful when creating contact reporting over limited number of objects in the scene
if self.cfg.disable_contact_processing:
carb_settings_iface.set_bool("/physics/disableContactProcessing", True)
# enable custom geometry for cylinder and cone collision shapes to allow contact reporting for them
# reason: cylinders and cones aren't natively supported by PhysX so we need to use custom geometry flags
# reference: https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/docs/Geometry.html?highlight=capsule#geometry
carb_settings_iface.set_bool("/physics/collisionConeCustomGeometry", False)
carb_settings_iface.set_bool("/physics/collisionCylinderCustomGeometry", False)
# note: we read this once since it is not expected to change during runtime
# read flag for whether a local GUI is enabled
self._local_gui = carb_settings_iface.get("/app/window/enabled")
# read flag for whether livestreaming GUI is enabled
self._livestream_gui = carb_settings_iface.get("/app/livestream/enabled")
# read flag for whether the orbit viewport capture pipeline will be used,
# casting None to False if the flag doesn't exist
# this flag is set from the AppLauncher class
self._offscreen_render = bool(carb_settings_iface.get("/orbit/render/offscreen"))
# flag for whether any GUI will be rendered (local, livestreamed or viewport)
self._has_gui = self._local_gui or self._livestream_gui
# store the default render mode
if not self._has_gui and not self._offscreen_render:
# set default render mode
# note: this is the terminal state: cannot exit from this render mode
self.render_mode = self.RenderMode.NO_GUI_OR_RENDERING
# set viewport context to None
self._viewport_context = None
self._viewport_window = None
elif not self._has_gui and self._offscreen_render:
# set default render mode
# note: this is the terminal state: cannot exit from this render mode
self.render_mode = self.RenderMode.PARTIAL_RENDERING
# set viewport context to None
self._viewport_context = None
self._viewport_window = None
else:
# note: need to import here in case the UI is not available (ex. headless mode)
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport
# set default render mode
# note: this can be changed by calling the `set_render_mode` function
self.render_mode = self.RenderMode.FULL_RENDERING
# acquire viewport context
self._viewport_context = get_active_viewport()
self._viewport_context.updates_enabled = True # pyright: ignore [reportOptionalMemberAccess]
# acquire viewport window
# TODO @mayank: Why not just use get_active_viewport_and_window() directly?
self._viewport_window = ui.Workspace.get_window("Viewport")
# counter for periodic rendering
self._render_throttle_counter = 0
# rendering frequency in terms of number of render calls
self._render_throttle_period = 5
# override enable scene querying if rendering is enabled
# this is needed for some GUI features
if self._has_gui:
self.cfg.enable_scene_query_support = True
# set up flatcache/fabric interface (default is None)
# this is needed to flush the flatcache data into Hydra manually when calling `render()`
# ref: https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_physics.html
# note: need to do this here because super().__init__ calls render and this variable is needed
self._fabric_iface = None
# read isaac sim version (this includes build tag, release tag etc.)
# note: we do it once here because it reads the VERSION file from disk and is not expected to change.
self._isaacsim_version = get_version()
# add callback to deal the simulation app when simulation is stopped.
# this is needed because physics views go invalid once we stop the simulation
if not builtins.ISAAC_LAUNCHED_FROM_TERMINAL:
timeline_event_stream = omni.timeline.get_timeline_interface().get_timeline_event_stream()
self._app_control_on_stop_handle = timeline_event_stream.create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.STOP),
lambda *args, obj=weakref.proxy(self): obj._app_control_on_stop_callback(*args),
order=15,
)
else:
self._app_control_on_stop_handle = None
# flatten out the simulation dictionary
sim_params = self.cfg.to_dict()
if sim_params is not None:
if "physx" in sim_params:
physx_params = sim_params.pop("physx")
sim_params.update(physx_params)
# create a simulation context to control the simulator
super().__init__(
stage_units_in_meters=1.0,
physics_dt=self.cfg.dt,
rendering_dt=self.cfg.dt * self.cfg.substeps,
backend="torch",
sim_params=sim_params,
physics_prim_path=self.cfg.physics_prim_path,
device=self.cfg.device,
)
"""
Operations - New.
"""
def has_gui(self) -> bool:
"""Returns whether the simulation has a GUI enabled.
True if the simulation has a GUI enabled either locally or live-streamed.
"""
return self._has_gui
def has_rtx_sensors(self) -> bool:
"""Returns whether the simulation has any RTX-rendering related sensors.
This function returns the value of the simulation parameter ``"/orbit/render/rtx_sensors"``.
The parameter is set to True when instances of RTX-related sensors (cameras or LiDARs) are
created using Orbit's sensor classes.
True if the simulation has RTX sensors (such as USD Cameras or LiDARs).
For more information, please check `NVIDIA RTX documentation`_.
.. _NVIDIA RTX documentation: https://www.nvidia.com/design-visualization/solutions/rendering/
"""
return self._settings.get_as_bool("/orbit/render/rtx_sensors")
def is_fabric_enabled(self) -> bool:
"""Returns whether the fabric interface is enabled.
When fabric interface is enabled, USD read/write operations are disabled. Instead all applications
read and write the simulation state directly from the fabric interface. This reduces a lot of overhead
that occurs during USD read/write operations.
For more information, please check `Fabric documentation`_.
.. _Fabric documentation: https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usd_fabric_usdrt.html
"""
return self._fabric_iface is not None
def get_version(self) -> tuple[int, int, int]:
"""Returns the version of the simulator.
This is a wrapper around the ``omni.isaac.version.get_version()`` function.
The returned tuple contains the following information:
* Major version (int): This is the year of the release (e.g. 2022).
* Minor version (int): This is the half-year of the release (e.g. 1 or 2).
* Patch version (int): This is the patch number of the release (e.g. 0).
"""
return int(self._isaacsim_version[2]), int(self._isaacsim_version[3]), int(self._isaacsim_version[4])
"""
Operations - New utilities.
"""
@staticmethod
def set_camera_view(
eye: tuple[float, float, float],
target: tuple[float, float, float],
camera_prim_path: str = "/OmniverseKit_Persp",
):
"""Set the location and target of the viewport camera in the stage.
Note:
This is a wrapper around the :math:`omni.isaac.core.utils.viewports.set_camera_view` function.
It is provided here for convenience to reduce the amount of imports needed.
Args:
eye: The location of the camera eye.
target: The location of the camera target.
camera_prim_path: The path to the camera primitive in the stage. Defaults to
"/OmniverseKit_Persp".
"""
set_camera_view(eye, target, camera_prim_path)
def set_render_mode(self, mode: RenderMode):
"""Change the current render mode of the simulation.
Please see :class:`RenderMode` for more information on the different render modes.
.. note::
When no GUI is available (locally or livestreamed), we do not need to choose whether the viewport
needs to render or not (since there is no GUI). Thus, in this case, calling the function will not
change the render mode.
Args:
mode (RenderMode): The rendering mode. If different than SimulationContext's rendering mode,
SimulationContext's mode is changed to the new mode.
Raises:
ValueError: If the input mode is not supported.
"""
# check if mode change is possible -- not possible when no GUI is available
if not self._has_gui:
carb.log_warn(
f"Cannot change render mode when GUI is disabled. Using the default render mode: {self.render_mode}."
)
return
# check if there is a mode change
# note: this is mostly needed for GUI when we want to switch between full rendering and no rendering.
if mode != self.render_mode:
if mode == self.RenderMode.FULL_RENDERING:
# display the viewport and enable updates
self._viewport_context.updates_enabled = True # pyright: ignore [reportOptionalMemberAccess]
self._viewport_window.visible = True # pyright: ignore [reportOptionalMemberAccess]
elif mode == self.RenderMode.PARTIAL_RENDERING:
# hide the viewport and disable updates
self._viewport_context.updates_enabled = False # pyright: ignore [reportOptionalMemberAccess]
self._viewport_window.visible = False # pyright: ignore [reportOptionalMemberAccess]
elif mode == self.RenderMode.NO_RENDERING:
# hide the viewport and disable updates
if self._viewport_context is not None:
self._viewport_context.updates_enabled = False # pyright: ignore [reportOptionalMemberAccess]
self._viewport_window.visible = False # pyright: ignore [reportOptionalMemberAccess]
# reset the throttle counter
self._render_throttle_counter = 0
else:
raise ValueError(f"Unsupported render mode: {mode}! Please check `RenderMode` for details.")
# update render mode
self.render_mode = mode
def set_setting(self, name: str, value: Any):
"""Set simulation settings using the Carbonite SDK.
.. note::
If the input setting name does not exist, it will be created. If it does exist, the value will be
overwritten. Please make sure to use the correct setting name.
To understand the settings interface, please refer to the
`Carbonite SDK <https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/settings.html>`_
documentation.
Args:
name: The name of the setting.
value: The value of the setting.
"""
self._settings.set(name, value)
def get_setting(self, name: str) -> Any:
"""Read the simulation setting using the Carbonite SDK.
Args:
name: The name of the setting.
Returns:
The value of the setting.
"""
return self._settings.get(name)
"""
Operations - Override (standalone)
"""
def reset(self, soft: bool = False):
super().reset(soft=soft)
# perform additional rendering steps to warm up replicator buffers
# this is only needed for the first time we set the simulation
if not soft:
for _ in range(2):
self.render()
def step(self, render: bool = True):
"""Steps the physics simulation with the pre-defined time-step.
.. note::
This function blocks if the timeline is paused. It only returns when the timeline is playing.
Args:
render: Whether to render the scene after stepping the physics simulation.
If set to False, the scene is not rendered and only the physics simulation is stepped.
"""
# check if the simulation timeline is paused. in that case keep stepping until it is playing
if not self.is_playing():
# step the simulator (but not the physics) to have UI still active
while not self.is_playing():
self.render()
# meantime if someone stops, break out of the loop
if self.is_stopped():
break
# need to do one step to refresh the app
# reason: physics has to parse the scene again and inform other extensions like hydra-delegate.
# without this the app becomes unresponsive.
# FIXME: This steps physics as well, which we is not good in general.
self.app.update()
# step the simulation
super().step(render=render)
def render(self, mode: RenderMode | None = None):
"""Refreshes the rendering components including UI elements and view-ports depending on the render mode.
This function is used to refresh the rendering components of the simulation. This includes updating the
view-ports, UI elements, and other extensions (besides physics simulation) that are running in the
background. The rendering components are refreshed based on the render mode.
Please see :class:`RenderMode` for more information on the different render modes.
Args:
mode: The rendering mode. Defaults to None, in which case the current rendering mode is used.
"""
# check if we need to change the render mode
if mode is not None:
self.set_render_mode(mode)
# render based on the render mode
if self.render_mode == self.RenderMode.NO_GUI_OR_RENDERING:
# we never want to render anything here (this is for complete headless mode)
pass
elif self.render_mode == self.RenderMode.NO_RENDERING:
# throttle the rendering frequency to keep the UI responsive
self._render_throttle_counter += 1
if self._render_throttle_counter % self._render_throttle_period == 0:
self._render_throttle_counter = 0
# here we don't render viewport so don't need to flush fabric data
# note: we don't call super().render() anymore because they do flush the fabric data
self.set_setting("/app/player/playSimulations", False)
self._app.update()
self.set_setting("/app/player/playSimulations", True)
else:
# manually flush the fabric data to update Hydra textures
if self._fabric_iface is not None:
self._fabric_iface.update(0.0, 0.0)
# render the simulation
# note: we don't call super().render() anymore because they do above operation inside
# and we don't want to do it twice. We may remove it once we drop support for Isaac Sim 2022.2.
self.set_setting("/app/player/playSimulations", False)
self._app.update()
self.set_setting("/app/player/playSimulations", True)
"""
Operations - Override (extension)
"""
async def reset_async(self, soft: bool = False):
# need to load all "physics" information from the USD file
if not soft:
omni.physx.acquire_physx_interface().force_load_physics_from_usd()
# play the simulation
await super().reset_async(soft=soft)
"""
Initialization/Destruction - Override.
"""
def _init_stage(self, *args, **kwargs) -> Usd.Stage:
_ = super()._init_stage(*args, **kwargs)
# set additional physx parameters and bind material
self._set_additional_physx_params()
# load flatcache/fabric interface
self._load_fabric_interface()
# return the stage
return self.stage
async def _initialize_stage_async(self, *args, **kwargs) -> Usd.Stage:
await super()._initialize_stage_async(*args, **kwargs)
# set additional physx parameters and bind material
self._set_additional_physx_params()
# load flatcache/fabric interface
self._load_fabric_interface()
# return the stage
return self.stage
@classmethod
def clear_instance(cls):
# clear the callback
if cls._instance is not None:
if cls._instance._app_control_on_stop_handle is not None:
cls._instance._app_control_on_stop_handle.unsubscribe()
cls._instance._app_control_on_stop_handle = None
# call parent to clear the instance
super().clear_instance()
"""
Helper Functions
"""
def _set_additional_physx_params(self):
"""Sets additional PhysX parameters that are not directly supported by the parent class."""
# obtain the physics scene api
physics_scene: UsdPhysics.Scene = self._physics_context._physics_scene
physx_scene_api: PhysxSchema.PhysxSceneAPI = self._physics_context._physx_scene_api
# assert that scene api is not None
if physx_scene_api is None:
raise RuntimeError("Physics scene API is None! Please create the scene first.")
# set parameters not directly supported by the constructor
# -- Continuous Collision Detection (CCD)
# ref: https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/docs/AdvancedCollisionDetection.html?highlight=ccd#continuous-collision-detection
self._physics_context.enable_ccd(self.cfg.physx.enable_ccd)
# -- GPU collision stack size
physx_scene_api.CreateGpuCollisionStackSizeAttr(self.cfg.physx.gpu_collision_stack_size)
# -- Improved determinism by PhysX
physx_scene_api.CreateEnableEnhancedDeterminismAttr(self.cfg.physx.enable_enhanced_determinism)
# -- Gravity
# note: Isaac sim only takes the "up-axis" as the gravity direction. But physics allows any direction so we
# need to convert the gravity vector to a direction and magnitude pair explicitly.
gravity = np.asarray(self.cfg.gravity)
gravity_magnitude = np.linalg.norm(gravity)
# Avoid division by zero
if gravity_magnitude != 0.0:
gravity_direction = gravity / gravity_magnitude
else:
gravity_direction = gravity
physics_scene.CreateGravityDirectionAttr(Gf.Vec3f(*gravity_direction))
physics_scene.CreateGravityMagnitudeAttr(gravity_magnitude)
# position iteration count
physx_scene_api.CreateMinPositionIterationCountAttr(self.cfg.physx.min_position_iteration_count)
physx_scene_api.CreateMaxPositionIterationCountAttr(self.cfg.physx.max_position_iteration_count)
# velocity iteration count
physx_scene_api.CreateMinVelocityIterationCountAttr(self.cfg.physx.min_velocity_iteration_count)
physx_scene_api.CreateMaxVelocityIterationCountAttr(self.cfg.physx.max_velocity_iteration_count)
# create the default physics material
# this material is used when no material is specified for a primitive
# check: https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/simulation-control/physics-settings.html#physics-materials
material_path = f"{self.cfg.physics_prim_path}/defaultMaterial"
self.cfg.physics_material.func(material_path, self.cfg.physics_material)
# bind the physics material to the scene
bind_physics_material(self.cfg.physics_prim_path, material_path)
def _load_fabric_interface(self):
"""Loads the fabric interface if enabled."""
if self.cfg.use_fabric:
from omni.physxfabric import get_physx_fabric_interface
# acquire fabric interface
self._fabric_iface = get_physx_fabric_interface()
"""
Callbacks.
"""
def _app_control_on_stop_callback(self, event: carb.events.IEvent):
"""Callback to deal with the app when the simulation is stopped.
Once the simulation is stopped, the physics handles go invalid. After that, it is not possible to
resume the simulation from the last state. This leaves the app in an inconsistent state, where
two possible actions can be taken:
1. **Keep the app rendering**: In this case, the simulation is kept running and the app is not shutdown.
However, the physics is not updated and the script cannot be resumed from the last state. The
user has to manually close the app to stop the simulation.
2. **Shutdown the app**: This is the default behavior. In this case, the app is shutdown and
the simulation is stopped.
Note:
This callback is used only when running the simulation in a standalone python script. In an extension,
it is expected that the user handles the extension shutdown.
"""
# check if the simulation is stopped
if event.type == int(omni.timeline.TimelineEventType.STOP):
# keep running the simulator when configured to not shutdown the app
if self._has_gui and sys.exc_info()[0] is None:
self.app.print_and_log(
"Simulation is stopped. The app will keep running with physics disabled."
" Press Ctrl+C or close the window to exit the app."
)
while self.app.is_running():
self.render()
# make sure that any replicator workflows finish rendering/writing
if not builtins.ISAAC_LAUNCHED_FROM_TERMINAL:
try:
import omni.replicator.core as rep
rep_status = rep.orchestrator.get_status()
if rep_status not in [rep.orchestrator.Status.STOPPED, rep.orchestrator.Status.STOPPING]:
rep.orchestrator.stop()
if rep_status != rep.orchestrator.Status.STOPPED:
rep.orchestrator.wait_until_complete()
except Exception:
pass
# clear the instance and all callbacks
# note: clearing callbacks is important to prevent memory leaks
self.clear_all_callbacks()
# workaround for exit issues, clean the stage first:
if omni.usd.get_context().can_close_stage():
omni.usd.get_context().close_stage()
# print logging information
self.app.print_and_log("Simulation is stopped. Shutting down the app.")
# shutdown the simulator
self.app.shutdown()
# disabled on linux to avoid a crash
carb.get_framework().unload_all_plugins()
@contextmanager
def build_simulation_context(
create_new_stage: bool = True,
gravity_enabled: bool = True,
device: str = "cuda:0",
dt: float = 0.01,
sim_cfg: SimulationCfg | None = None,
add_ground_plane: bool = False,
add_lighting: bool = False,
auto_add_lighting: bool = False,
) -> Iterator[SimulationContext]:
"""Context manager to build a simulation context with the provided settings.
This function facilitates the creation of a simulation context and provides flexibility in configuring various
aspects of the simulation, such as time step, gravity, device, and scene elements like ground plane and
lighting.
If :attr:`sim_cfg` is None, then an instance of :class:`SimulationCfg` is created with default settings, with parameters
overwritten based on arguments to the function.
An example usage of the context manager function:
.. code-block:: python
with build_simulation_context() as sim:
# Design the scene
# Play the simulation
sim.reset()
while sim.is_playing():
sim.step()
Args:
create_new_stage: Whether to create a new stage. Defaults to True.
gravity_enabled: Whether to enable gravity in the simulation. Defaults to True.
device: Device to run the simulation on. Defaults to "cuda:0".
dt: Time step for the simulation: Defaults to 0.01.
sim_cfg: :class:`omni.isaac.orbit.sim.SimulationCfg` to use for the simulation. Defaults to None.
add_ground_plane: Whether to add a ground plane to the simulation. Defaults to False.
add_lighting: Whether to add a dome light to the simulation. Defaults to False.
auto_add_lighting: Whether to automatically add a dome light to the simulation if the simulation has a GUI.
Defaults to False. This is useful for debugging tests in the GUI.
Yields:
The simulation context to use for the simulation.
"""
try:
if create_new_stage:
stage_utils.create_new_stage()
if sim_cfg is None:
# Construct one and overwrite the dt, gravity, and device
sim_cfg = SimulationCfg(dt=dt)
# Set up gravity
if gravity_enabled:
sim_cfg.gravity = (0.0, 0.0, -9.81)
else:
sim_cfg.gravity = (0.0, 0.0, 0.0)
# Set device
sim_cfg.device = device
# Construct simulation context
sim = SimulationContext(sim_cfg)
if add_ground_plane:
# Ground-plane
cfg = GroundPlaneCfg()
cfg.func("/World/defaultGroundPlane", cfg)
if add_lighting or (auto_add_lighting and sim.has_gui()):
# Lighting
cfg = DomeLightCfg(
color=(0.1, 0.1, 0.1),
enable_color_temperature=True,
color_temperature=5500,
intensity=10000,
)
# Dome light named specifically to avoid conflicts
cfg.func(prim_path="/World/defaultDomeLight", cfg=cfg, translation=(0.0, 0.0, 10.0))
yield sim
except Exception:
carb.log_error(traceback.format_exc())
raise
finally:
if not sim.has_gui():
# Stop simulation only if we aren't rendering otherwise the app will hang indefinitely
sim.stop()
# Clear the stage
sim.clear_all_callbacks()
sim.clear_instance()
| 34,037 | Python | 47.008463 | 149 | 0.653642 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/schemas/schemas_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from typing import Literal
from omni.isaac.orbit.utils import configclass
@configclass
class ArticulationRootPropertiesCfg:
"""Properties to apply to the root of an articulation.
See :meth:`modify_articulation_root_properties` for more information.
.. note::
If the values are None, they are not modified. This is useful when you want to set only a subset of
the properties and leave the rest as-is.
"""
articulation_enabled: bool | None = None
"""Whether to enable or disable articulation."""
enabled_self_collisions: bool | None = None
"""Whether to enable or disable self-collisions."""
solver_position_iteration_count: int | None = None
"""Solver position iteration counts for the body."""
solver_velocity_iteration_count: int | None = None
"""Solver position iteration counts for the body."""
sleep_threshold: float | None = None
"""Mass-normalized kinetic energy threshold below which an actor may go to sleep."""
stabilization_threshold: float | None = None
"""The mass-normalized kinetic energy threshold below which an articulation may participate in stabilization."""
fix_root_link: bool | None = None
"""Whether to fix the root link of the articulation.
* If set to None, the root link is not modified.
* If the articulation already has a fixed root link, this flag will enable or disable the fixed joint.
* If the articulation does not have a fixed root link, this flag will create a fixed joint between the world
frame and the root link. The joint is created with the name "FixedJoint" under the articulation prim.
.. note::
This is a non-USD schema property. It is handled by the :meth:`modify_articulation_root_properties` function.
"""
@configclass
class RigidBodyPropertiesCfg:
"""Properties to apply to a rigid body.
See :meth:`modify_rigid_body_properties` for more information.
.. note::
If the values are None, they are not modified. This is useful when you want to set only a subset of
the properties and leave the rest as-is.
"""
rigid_body_enabled: bool | None = None
"""Whether to enable or disable the rigid body."""
kinematic_enabled: bool | None = None
"""Determines whether the body is kinematic or not.
A kinematic body is a body that is moved through animated poses or through user defined poses. The simulation
still derives velocities for the kinematic body based on the external motion.
For more information on kinematic bodies, please refer to the `documentation <https://openusd.org/release/wp_rigid_body_physics.html#kinematic-bodies>`_.
"""
disable_gravity: bool | None = None
"""Disable gravity for the actor."""
linear_damping: float | None = None
"""Linear damping for the body."""
angular_damping: float | None = None
"""Angular damping for the body."""
max_linear_velocity: float | None = None
"""Maximum linear velocity for rigid bodies (in m/s)."""
max_angular_velocity: float | None = None
"""Maximum angular velocity for rigid bodies (in deg/s)."""
max_depenetration_velocity: float | None = None
"""Maximum depenetration velocity permitted to be introduced by the solver (in m/s)."""
max_contact_impulse: float | None = None
"""The limit on the impulse that may be applied at a contact."""
enable_gyroscopic_forces: bool | None = None
"""Enables computation of gyroscopic forces on the rigid body."""
retain_accelerations: bool | None = None
"""Carries over forces/accelerations over sub-steps."""
solver_position_iteration_count: int | None = None
"""Solver position iteration counts for the body."""
solver_velocity_iteration_count: int | None = None
"""Solver position iteration counts for the body."""
sleep_threshold: float | None = None
"""Mass-normalized kinetic energy threshold below which an actor may go to sleep."""
stabilization_threshold: float | None = None
"""The mass-normalized kinetic energy threshold below which an actor may participate in stabilization."""
@configclass
class CollisionPropertiesCfg:
"""Properties to apply to colliders in a rigid body.
See :meth:`modify_collision_properties` for more information.
.. note::
If the values are None, they are not modified. This is useful when you want to set only a subset of
the properties and leave the rest as-is.
"""
collision_enabled: bool | None = None
"""Whether to enable or disable collisions."""
contact_offset: float | None = None
"""Contact offset for the collision shape (in m).
The collision detector generates contact points as soon as two shapes get closer than the sum of their
contact offsets. This quantity should be non-negative which means that contact generation can potentially start
before the shapes actually penetrate.
"""
rest_offset: float | None = None
"""Rest offset for the collision shape (in m).
The rest offset quantifies how close a shape gets to others at rest, At rest, the distance between two
vertically stacked objects is the sum of their rest offsets. If a pair of shapes have a positive rest
offset, the shapes will be separated at rest by an air gap.
"""
torsional_patch_radius: float | None = None
"""Radius of the contact patch for applying torsional friction (in m).
It is used to approximate rotational friction introduced by the compression of contacting surfaces.
If the radius is zero, no torsional friction is applied.
"""
min_torsional_patch_radius: float | None = None
"""Minimum radius of the contact patch for applying torsional friction (in m)."""
@configclass
class MassPropertiesCfg:
"""Properties to define explicit mass properties of a rigid body.
See :meth:`modify_mass_properties` for more information.
.. note::
If the values are None, they are not modified. This is useful when you want to set only a subset of
the properties and leave the rest as-is.
"""
mass: float | None = None
"""The mass of the rigid body (in kg).
Note:
If non-zero, the mass is ignored and the density is used to compute the mass.
"""
density: float | None = None
"""The density of the rigid body (in kg/m^3).
The density indirectly defines the mass of the rigid body. It is generally computed using the collision
approximation of the body.
"""
@configclass
class JointDrivePropertiesCfg:
"""Properties to define the drive mechanism of a joint.
See :meth:`modify_joint_drive_properties` for more information.
.. note::
If the values are None, they are not modified. This is useful when you want to set only a subset of
the properties and leave the rest as-is.
"""
drive_type: Literal["force", "acceleration"] | None = None
"""Joint drive type to apply.
If the drive type is "force", then the joint is driven by a force. If the drive type is "acceleration",
then the joint is driven by an acceleration (usually used for kinematic joints).
"""
@configclass
class FixedTendonPropertiesCfg:
"""Properties to define fixed tendons of an articulation.
See :meth:`modify_fixed_tendon_properties` for more information.
.. note::
If the values are None, they are not modified. This is useful when you want to set only a subset of
the properties and leave the rest as-is.
"""
tendon_enabled: bool | None = None
"""Whether to enable or disable the tendon."""
stiffness: float | None = None
"""Spring stiffness term acting on the tendon's length."""
damping: float | None = None
"""The damping term acting on both the tendon length and the tendon-length limits."""
limit_stiffness: float | None = None
"""Limit stiffness term acting on the tendon's length limits."""
offset: float | None = None
"""Length offset term for the tendon.
It defines an amount to be added to the accumulated length computed for the tendon. This allows the application
to actuate the tendon by shortening or lengthening it.
"""
rest_length: float | None = None
"""Spring rest length of the tendon."""
| 8,413 | Python | 40.043902 | 157 | 0.698918 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/schemas/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing utilities for schemas used in Omniverse.
We wrap the USD schemas for PhysX and USD Physics in a more convenient API for setting the parameters from
Python. This is done so that configuration objects can define the schema properties to set and make it easier
to tune the physics parameters without requiring to open Omniverse Kit and manually set the parameters into
the respective USD attributes.
.. caution::
Schema properties cannot be applied on prims that are prototypes as they are read-only prims. This
particularly affects instanced assets where some of the prims (usually the visual and collision meshes)
are prototypes so that the instancing can be done efficiently.
In such cases, it is assumed that the prototypes have sim-ready properties on them that don't need to be modified.
Trying to set properties into prototypes will throw a warning saying that the prim is a prototype and the
properties cannot be set.
The schemas are defined in the following links:
* `UsdPhysics schema <https://openusd.org/dev/api/usd_physics_page_front.html>`_
* `PhysxSchema schema <https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/index.html>`_
Locally, the schemas are defined in the following files:
* ``_isaac_sim/kit/extsPhysics/omni.usd.schema.physics/plugins/UsdPhysics/resources/UsdPhysics/schema.usda``
* ``_isaac_sim/kit/extsPhysics/omni.usd.schema.physx/plugins/PhysxSchema/resources/PhysxSchema/schema.usda``
"""
from .schemas import (
activate_contact_sensors,
define_articulation_root_properties,
define_collision_properties,
define_mass_properties,
define_rigid_body_properties,
modify_articulation_root_properties,
modify_collision_properties,
modify_fixed_tendon_properties,
modify_joint_drive_properties,
modify_mass_properties,
modify_rigid_body_properties,
)
from .schemas_cfg import (
ArticulationRootPropertiesCfg,
CollisionPropertiesCfg,
FixedTendonPropertiesCfg,
JointDrivePropertiesCfg,
MassPropertiesCfg,
RigidBodyPropertiesCfg,
)
| 2,223 | Python | 38.714285 | 118 | 0.774629 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/schemas/schemas.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# needed to import for allowing type-hinting: Usd.Stage | None
from __future__ import annotations
import carb
import omni.isaac.core.utils.stage as stage_utils
import omni.physx.scripts.utils as physx_utils
from pxr import PhysxSchema, Usd, UsdPhysics
from ..utils import apply_nested, find_global_fixed_joint_prim, safe_set_attribute_on_usd_schema
from . import schemas_cfg
"""
Articulation root properties.
"""
def define_articulation_root_properties(
prim_path: str, cfg: schemas_cfg.ArticulationRootPropertiesCfg, stage: Usd.Stage | None = None
):
"""Apply the articulation root schema on the input prim and set its properties.
See :func:`modify_articulation_root_properties` for more details on how the properties are set.
Args:
prim_path: The prim path where to apply the articulation root schema.
cfg: The configuration for the articulation root.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Raises:
ValueError: When the prim path is not valid.
TypeError: When the prim already has conflicting API schemas.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get articulation USD prim
prim = stage.GetPrimAtPath(prim_path)
# check if prim path is valid
if not prim.IsValid():
raise ValueError(f"Prim path '{prim_path}' is not valid.")
# check if prim has articulation applied on it
if not UsdPhysics.ArticulationRootAPI(prim):
UsdPhysics.ArticulationRootAPI.Apply(prim)
# set articulation root properties
modify_articulation_root_properties(prim_path, cfg, stage)
@apply_nested
def modify_articulation_root_properties(
prim_path: str, cfg: schemas_cfg.ArticulationRootPropertiesCfg, stage: Usd.Stage | None = None
) -> bool:
"""Modify PhysX parameters for an articulation root prim.
The `articulation root`_ marks the root of an articulation tree. For floating articulations, this should be on
the root body. For fixed articulations, this API can be on a direct or indirect parent of the root joint
which is fixed to the world.
The schema comprises of attributes that belong to the `ArticulationRootAPI`_ and `PhysxArticulationAPI`_.
schemas. The latter contains the PhysX parameters for the articulation root.
The properties are applied to the articulation root prim. The common properties (such as solver position
and velocity iteration counts, sleep threshold, stabilization threshold) take precedence over those specified
in the rigid body schemas for all the rigid bodies in the articulation.
.. caution::
When the attribute :attr:`schemas_cfg.ArticulationRootPropertiesCfg.fix_root_link` is set to True,
a fixed joint is created between the root link and the world frame (if it does not already exist). However,
to deal with physics parser limitations, the articulation root schema needs to be applied to the parent of
the root link.
.. note::
This function is decorated with :func:`apply_nested` that set the properties to all the prims
(that have the schema applied on them) under the input prim path.
.. _articulation root: https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/docs/Articulations.html
.. _ArticulationRootAPI: https://openusd.org/dev/api/class_usd_physics_articulation_root_a_p_i.html
.. _PhysxArticulationAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/class_physx_schema_physx_articulation_a_p_i.html
Args:
prim_path: The prim path to the articulation root.
cfg: The configuration for the articulation root.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Returns:
True if the properties were successfully set, False otherwise.
Raises:
NotImplementedError: When the root prim is not a rigid body and a fixed joint is to be created.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get articulation USD prim
articulation_prim = stage.GetPrimAtPath(prim_path)
# check if prim has articulation applied on it
if not UsdPhysics.ArticulationRootAPI(articulation_prim):
return False
# retrieve the articulation api
physx_articulation_api = PhysxSchema.PhysxArticulationAPI(articulation_prim)
if not physx_articulation_api:
physx_articulation_api = PhysxSchema.PhysxArticulationAPI.Apply(articulation_prim)
# convert to dict
cfg = cfg.to_dict()
# extract non-USD properties
fix_root_link = cfg.pop("fix_root_link", None)
# set into physx api
for attr_name, value in cfg.items():
safe_set_attribute_on_usd_schema(physx_articulation_api, attr_name, value, camel_case=True)
# fix root link based on input
# we do the fixed joint processing later to not interfere with setting other properties
if fix_root_link is not None:
# check if a global fixed joint exists under the root prim
existing_fixed_joint_prim = find_global_fixed_joint_prim(prim_path)
# if we found a fixed joint, enable/disable it based on the input
# otherwise, create a fixed joint between the world and the root link
if existing_fixed_joint_prim is not None:
carb.log_info(
f"Found an existing fixed joint for the articulation: '{prim_path}'. Setting it to: {fix_root_link}."
)
existing_fixed_joint_prim.GetJointEnabledAttr().Set(fix_root_link)
elif fix_root_link:
carb.log_info(f"Creating a fixed joint for the articulation: '{prim_path}'.")
# note: we have to assume that the root prim is a rigid body,
# i.e. we don't handle the case where the root prim is not a rigid body but has articulation api on it
# Currently, there is no obvious way to get first rigid body link identified by the PhysX parser
if not articulation_prim.HasAPI(UsdPhysics.RigidBodyAPI):
raise NotImplementedError(
f"The articulation prim '{prim_path}' does not have the RigidBodyAPI applied."
" To create a fixed joint, we need to determine the first rigid body link in"
" the articulation tree. However, this is not implemented yet."
)
# create a fixed joint between the root link and the world frame
physx_utils.createJoint(stage=stage, joint_type="Fixed", from_prim=None, to_prim=articulation_prim)
# Having a fixed joint on a rigid body is not treated as "fixed base articulation".
# instead, it is treated as a part of the maximal coordinate tree.
# Moving the articulation root to the parent solves this issue. This is a limitation of the PhysX parser.
# get parent prim
parent_prim = articulation_prim.GetParent()
# apply api to parent
UsdPhysics.ArticulationRootAPI.Apply(parent_prim)
PhysxSchema.PhysxArticulationAPI.Apply(parent_prim)
# copy the attributes
# -- usd attributes
usd_articulation_api = UsdPhysics.ArticulationRootAPI(articulation_prim)
for attr_name in usd_articulation_api.GetSchemaAttributeNames():
attr = articulation_prim.GetAttribute(attr_name)
parent_prim.GetAttribute(attr_name).Set(attr.Get())
# -- physx attributes
physx_articulation_api = PhysxSchema.PhysxArticulationAPI(articulation_prim)
for attr_name in physx_articulation_api.GetSchemaAttributeNames():
attr = articulation_prim.GetAttribute(attr_name)
parent_prim.GetAttribute(attr_name).Set(attr.Get())
# remove api from root
articulation_prim.RemoveAPI(UsdPhysics.ArticulationRootAPI)
articulation_prim.RemoveAPI(PhysxSchema.PhysxArticulationAPI)
# success
return True
"""
Rigid body properties.
"""
def define_rigid_body_properties(
prim_path: str, cfg: schemas_cfg.RigidBodyPropertiesCfg, stage: Usd.Stage | None = None
):
"""Apply the rigid body schema on the input prim and set its properties.
See :func:`modify_rigid_body_properties` for more details on how the properties are set.
Args:
prim_path: The prim path where to apply the rigid body schema.
cfg: The configuration for the rigid body.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Raises:
ValueError: When the prim path is not valid.
TypeError: When the prim already has conflicting API schemas.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get USD prim
prim = stage.GetPrimAtPath(prim_path)
# check if prim path is valid
if not prim.IsValid():
raise ValueError(f"Prim path '{prim_path}' is not valid.")
# check if prim has rigid body applied on it
if not UsdPhysics.RigidBodyAPI(prim):
UsdPhysics.RigidBodyAPI.Apply(prim)
# set rigid body properties
modify_rigid_body_properties(prim_path, cfg, stage)
@apply_nested
def modify_rigid_body_properties(
prim_path: str, cfg: schemas_cfg.RigidBodyPropertiesCfg, stage: Usd.Stage | None = None
) -> bool:
"""Modify PhysX parameters for a rigid body prim.
A `rigid body`_ is a single body that can be simulated by PhysX. It can be either dynamic or kinematic.
A dynamic body responds to forces and collisions. A `kinematic body`_ can be moved by the user, but does not
respond to forces. They are similar to having static bodies that can be moved around.
The schema comprises of attributes that belong to the `RigidBodyAPI`_ and `PhysxRigidBodyAPI`_.
schemas. The latter contains the PhysX parameters for the rigid body.
.. note::
This function is decorated with :func:`apply_nested` that sets the properties to all the prims
(that have the schema applied on them) under the input prim path.
.. _rigid body: https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/docs/RigidBodyOverview.html
.. _kinematic body: https://openusd.org/release/wp_rigid_body_physics.html#kinematic-bodies
.. _RigidBodyAPI: https://openusd.org/dev/api/class_usd_physics_rigid_body_a_p_i.html
.. _PhysxRigidBodyAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/class_physx_schema_physx_rigid_body_a_p_i.html
Args:
prim_path: The prim path to the rigid body.
cfg: The configuration for the rigid body.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Returns:
True if the properties were successfully set, False otherwise.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get rigid-body USD prim
rigid_body_prim = stage.GetPrimAtPath(prim_path)
# check if prim has rigid-body applied on it
if not UsdPhysics.RigidBodyAPI(rigid_body_prim):
return False
# retrieve the USD rigid-body api
usd_rigid_body_api = UsdPhysics.RigidBodyAPI(rigid_body_prim)
# retrieve the physx rigid-body api
physx_rigid_body_api = PhysxSchema.PhysxRigidBodyAPI(rigid_body_prim)
if not physx_rigid_body_api:
physx_rigid_body_api = PhysxSchema.PhysxRigidBodyAPI.Apply(rigid_body_prim)
# convert to dict
cfg = cfg.to_dict()
# set into USD API
for attr_name in ["rigid_body_enabled", "kinematic_enabled"]:
value = cfg.pop(attr_name, None)
safe_set_attribute_on_usd_schema(usd_rigid_body_api, attr_name, value, camel_case=True)
# set into PhysX API
for attr_name, value in cfg.items():
safe_set_attribute_on_usd_schema(physx_rigid_body_api, attr_name, value, camel_case=True)
# success
return True
"""
Collision properties.
"""
def define_collision_properties(
prim_path: str, cfg: schemas_cfg.CollisionPropertiesCfg, stage: Usd.Stage | None = None
):
"""Apply the collision schema on the input prim and set its properties.
See :func:`modify_collision_properties` for more details on how the properties are set.
Args:
prim_path: The prim path where to apply the rigid body schema.
cfg: The configuration for the collider.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Raises:
ValueError: When the prim path is not valid.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get USD prim
prim = stage.GetPrimAtPath(prim_path)
# check if prim path is valid
if not prim.IsValid():
raise ValueError(f"Prim path '{prim_path}' is not valid.")
# check if prim has collision applied on it
if not UsdPhysics.CollisionAPI(prim):
UsdPhysics.CollisionAPI.Apply(prim)
# set collision properties
modify_collision_properties(prim_path, cfg, stage)
@apply_nested
def modify_collision_properties(
prim_path: str, cfg: schemas_cfg.CollisionPropertiesCfg, stage: Usd.Stage | None = None
) -> bool:
"""Modify PhysX properties of collider prim.
These properties are based on the `UsdPhysics.CollisionAPI`_ and `PhysxSchema.PhysxCollisionAPI`_ schemas.
For more information on the properties, please refer to the official documentation.
Tuning these parameters influence the contact behavior of the rigid body. For more information on
tune them and their effect on the simulation, please refer to the
`PhysX documentation <https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/docs/AdvancedCollisionDetection.html>`__.
.. note::
This function is decorated with :func:`apply_nested` that sets the properties to all the prims
(that have the schema applied on them) under the input prim path.
.. _UsdPhysics.CollisionAPI: https://openusd.org/dev/api/class_usd_physics_collision_a_p_i.html
.. _PhysxSchema.PhysxCollisionAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/class_physx_schema_physx_collision_a_p_i.html
Args:
prim_path: The prim path of parent.
cfg: The configuration for the collider.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Returns:
True if the properties were successfully set, False otherwise.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get USD prim
collider_prim = stage.GetPrimAtPath(prim_path)
# check if prim has collision applied on it
if not UsdPhysics.CollisionAPI(collider_prim):
return False
# retrieve the USD collision api
usd_collision_api = UsdPhysics.CollisionAPI(collider_prim)
# retrieve the collision api
physx_collision_api = PhysxSchema.PhysxCollisionAPI(collider_prim)
if not physx_collision_api:
physx_collision_api = PhysxSchema.PhysxCollisionAPI.Apply(collider_prim)
# convert to dict
cfg = cfg.to_dict()
# set into USD API
for attr_name in ["collision_enabled"]:
value = cfg.pop(attr_name, None)
safe_set_attribute_on_usd_schema(usd_collision_api, attr_name, value, camel_case=True)
# set into PhysX API
for attr_name, value in cfg.items():
safe_set_attribute_on_usd_schema(physx_collision_api, attr_name, value, camel_case=True)
# success
return True
"""
Mass properties.
"""
def define_mass_properties(prim_path: str, cfg: schemas_cfg.MassPropertiesCfg, stage: Usd.Stage | None = None):
"""Apply the mass schema on the input prim and set its properties.
See :func:`modify_mass_properties` for more details on how the properties are set.
Args:
prim_path: The prim path where to apply the rigid body schema.
cfg: The configuration for the mass properties.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Raises:
ValueError: When the prim path is not valid.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get USD prim
prim = stage.GetPrimAtPath(prim_path)
# check if prim path is valid
if not prim.IsValid():
raise ValueError(f"Prim path '{prim_path}' is not valid.")
# check if prim has mass applied on it
if not UsdPhysics.MassAPI(prim):
UsdPhysics.MassAPI.Apply(prim)
# set mass properties
modify_mass_properties(prim_path, cfg, stage)
@apply_nested
def modify_mass_properties(prim_path: str, cfg: schemas_cfg.MassPropertiesCfg, stage: Usd.Stage | None = None) -> bool:
"""Set properties for the mass of a rigid body prim.
These properties are based on the `UsdPhysics.MassAPI` schema. If the mass is not defined, the density is used
to compute the mass. However, in that case, a collision approximation of the rigid body is used to
compute the density. For more information on the properties, please refer to the
`documentation <https://openusd.org/release/wp_rigid_body_physics.html#body-mass-properties>`__.
.. caution::
The mass of an object can be specified in multiple ways and have several conflicting settings
that are resolved based on precedence. Please make sure to understand the precedence rules
before using this property.
.. note::
This function is decorated with :func:`apply_nested` that sets the properties to all the prims
(that have the schema applied on them) under the input prim path.
.. UsdPhysics.MassAPI: https://openusd.org/dev/api/class_usd_physics_mass_a_p_i.html
Args:
prim_path: The prim path of the rigid body.
cfg: The configuration for the mass properties.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Returns:
True if the properties were successfully set, False otherwise.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get USD prim
rigid_prim = stage.GetPrimAtPath(prim_path)
# check if prim has mass API applied on it
if not UsdPhysics.MassAPI(rigid_prim):
return False
# retrieve the USD mass api
usd_physics_mass_api = UsdPhysics.MassAPI(rigid_prim)
# convert to dict
cfg = cfg.to_dict()
# set into USD API
for attr_name in ["mass", "density"]:
value = cfg.pop(attr_name, None)
safe_set_attribute_on_usd_schema(usd_physics_mass_api, attr_name, value, camel_case=True)
# success
return True
"""
Contact sensor.
"""
def activate_contact_sensors(prim_path: str, threshold: float = 0.0, stage: Usd.Stage = None):
"""Activate the contact sensor on all rigid bodies under a specified prim path.
This function adds the PhysX contact report API to all rigid bodies under the specified prim path.
It also sets the force threshold beyond which the contact sensor reports the contact. The contact
reporting API can only be added to rigid bodies.
Args:
prim_path: The prim path under which to search and prepare contact sensors.
threshold: The threshold for the contact sensor. Defaults to 0.0.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Raises:
ValueError: If the input prim path is not valid.
ValueError: If there are no rigid bodies under the prim path.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get prim
prim: Usd.Prim = stage.GetPrimAtPath(prim_path)
# check if prim is valid
if not prim.IsValid():
raise ValueError(f"Prim path '{prim_path}' is not valid.")
# iterate over all children
num_contact_sensors = 0
all_prims = [prim]
while len(all_prims) > 0:
# get current prim
child_prim = all_prims.pop(0)
# check if prim is a rigid body
# nested rigid bodies are not allowed by SDK so we can safely assume that
# if a prim has a rigid body API, it is a rigid body and we don't need to
# check its children
if child_prim.HasAPI(UsdPhysics.RigidBodyAPI):
# set sleep threshold to zero
rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, prim.GetPrimPath())
rb.CreateSleepThresholdAttr().Set(0.0)
# add contact report API with threshold of zero
if not child_prim.HasAPI(PhysxSchema.PhysxContactReportAPI):
carb.log_verbose(f"Adding contact report API to prim: '{child_prim.GetPrimPath()}'")
cr_api = PhysxSchema.PhysxContactReportAPI.Apply(child_prim)
else:
carb.log_verbose(f"Contact report API already exists on prim: '{child_prim.GetPrimPath()}'")
cr_api = PhysxSchema.PhysxContactReportAPI.Get(stage, child_prim.GetPrimPath())
# set threshold to zero
cr_api.CreateThresholdAttr().Set(threshold)
# increment number of contact sensors
num_contact_sensors += 1
else:
# add all children to tree
all_prims += child_prim.GetChildren()
# check if no contact sensors were found
if num_contact_sensors == 0:
raise ValueError(
f"No contact sensors added to the prim: '{prim_path}'. This means that no rigid bodies"
" are present under this prim. Please check the prim path."
)
# success
return True
"""
Joint drive properties.
"""
@apply_nested
def modify_joint_drive_properties(
prim_path: str, drive_props: schemas_cfg.JointDrivePropertiesCfg, stage: Usd.Stage | None = None
) -> bool:
"""Modify PhysX parameters for a joint prim.
This function checks if the input prim is a prismatic or revolute joint and applies the joint drive schema
on it. If the joint is a tendon (i.e., it has the `PhysxTendonAxisAPI`_ schema applied on it), then the joint
drive schema is not applied.
Based on the configuration, this method modifies the properties of the joint drive. These properties are
based on the `UsdPhysics.DriveAPI`_ schema. For more information on the properties, please refer to the
official documentation.
.. caution::
We highly recommend modifying joint properties of articulations through the functionalities in the
:mod:`omni.isaac.orbit.actuators` module. The methods here are for setting simulation low-level
properties only.
.. _UsdPhysics.DriveAPI: https://openusd.org/dev/api/class_usd_physics_drive_a_p_i.html
.. _PhysxTendonAxisAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/class_physx_schema_physx_tendon_axis_a_p_i.html
Args:
prim_path: The prim path where to apply the joint drive schema.
drive_props: The configuration for the joint drive.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Returns:
True if the properties were successfully set, False otherwise.
Raises:
ValueError: If the input prim path is not valid.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get USD prim
prim = stage.GetPrimAtPath(prim_path)
# check if prim path is valid
if not prim.IsValid():
raise ValueError(f"Prim path '{prim_path}' is not valid.")
# check if prim has joint drive applied on it
if prim.IsA(UsdPhysics.RevoluteJoint):
drive_api_name = "angular"
elif prim.IsA(UsdPhysics.PrismaticJoint):
drive_api_name = "linear"
else:
return False
# check that prim is not a tendon child prim
# note: root prim is what "controls" the tendon so we still want to apply the drive to it
if prim.HasAPI(PhysxSchema.PhysxTendonAxisAPI) and not prim.HasAPI(PhysxSchema.PhysxTendonAxisRootAPI):
return False
# check if prim has joint drive applied on it
usd_drive_api = UsdPhysics.DriveAPI(prim, drive_api_name)
if not usd_drive_api:
usd_drive_api = UsdPhysics.DriveAPI.Apply(prim, drive_api_name)
# change the drive type to input
if drive_props.drive_type is not None:
usd_drive_api.CreateTypeAttr().Set(drive_props.drive_type)
return True
"""
Fixed tendon properties.
"""
@apply_nested
def modify_fixed_tendon_properties(
prim_path: str, cfg: schemas_cfg.FixedTendonPropertiesCfg, stage: Usd.Stage | None = None
) -> bool:
"""Modify PhysX parameters for a fixed tendon attachment prim.
A `fixed tendon`_ can be used to link multiple degrees of freedom of articulation joints
through length and limit constraints. For instance, it can be used to set up an equality constraint
between a driven and passive revolute joints.
The schema comprises of attributes that belong to the `PhysxTendonAxisRootAPI`_ schema.
.. note::
This function is decorated with :func:`apply_nested` that sets the properties to all the prims
(that have the schema applied on them) under the input prim path.
.. _fixed tendon: https://nvidia-omniverse.github.io/PhysX/physx/5.3.1/_api_build/class_px_articulation_fixed_tendon.html
.. _PhysxTendonAxisRootAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/class_physx_schema_physx_tendon_axis_root_a_p_i.html
Args:
prim_path: The prim path to the tendon attachment.
cfg: The configuration for the tendon attachment.
stage: The stage where to find the prim. Defaults to None, in which case the
current stage is used.
Returns:
True if the properties were successfully set, False otherwise.
Raises:
ValueError: If the input prim path is not valid.
"""
# obtain stage
if stage is None:
stage = stage_utils.get_current_stage()
# get USD prim
tendon_prim = stage.GetPrimAtPath(prim_path)
# check if prim has fixed tendon applied on it
has_root_fixed_tendon = tendon_prim.HasAPI(PhysxSchema.PhysxTendonAxisRootAPI)
if not has_root_fixed_tendon:
return False
# resolve all available instances of the schema since it is multi-instance
for schema_name in tendon_prim.GetAppliedSchemas():
# only consider the fixed tendon schema
if "PhysxTendonAxisRootAPI" not in schema_name:
continue
# retrieve the USD tendon api
instance_name = schema_name.split(":")[-1]
physx_tendon_axis_api = PhysxSchema.PhysxTendonAxisRootAPI(tendon_prim, instance_name)
# convert to dict
cfg = cfg.to_dict()
# set into PhysX API
for attr_name, value in cfg.items():
safe_set_attribute_on_usd_schema(physx_tendon_axis_api, attr_name, value, camel_case=True)
# success
return True
| 27,437 | Python | 40.954128 | 157 | 0.686555 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/spawner_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from collections.abc import Callable
from dataclasses import MISSING
from pxr import Usd
from omni.isaac.orbit.sim import schemas
from omni.isaac.orbit.utils import configclass
@configclass
class SpawnerCfg:
"""Configuration parameters for spawning an asset.
Spawning an asset is done by calling the :attr:`func` function. The function takes in the
prim path to spawn the asset at, the configuration instance and transformation, and returns the
prim path of the spawned asset.
The function is typically decorated with :func:`omni.isaac.orbit.sim.spawner.utils.clone` decorator
that checks if input prim path is a regex expression and spawns the asset at all matching prims.
For this, the decorator uses the Cloner API from Isaac Sim and handles the :attr:`copy_from_source`
parameter.
"""
func: Callable[..., Usd.Prim] = MISSING
"""Function to use for spawning the asset.
The function takes in the prim path (or expression) to spawn the asset at, the configuration instance
and transformation, and returns the source prim spawned.
"""
visible: bool = True
"""Whether the spawned asset should be visible. Defaults to True."""
semantic_tags: list[tuple[str, str]] | None = None
"""List of semantic tags to add to the spawned asset. Defaults to None,
which means no semantic tags will be added.
The semantic tags follow the `Replicator Semantic` tagging system. Each tag is a tuple of the
form ``(type, data)``, where ``type`` is the type of the tag and ``data`` is the semantic label
associated with the tag. For example, to annotate a spawned asset in the class avocado, the semantic
tag would be ``[("class", "avocado")]``.
You can specify multiple semantic tags by passing in a list of tags. For example, to annotate a
spawned asset in the class avocado and the color green, the semantic tags would be
``[("class", "avocado"), ("color", "green")]``.
.. seealso::
For more information on the semantics filter, see the documentation for the `semantics schema editor`_.
.. _semantics schema editor: https://docs.omniverse.nvidia.com/extensions/latest/ext_replicator/semantics_schema_editor.html#semantics-filtering
"""
copy_from_source: bool = True
"""Whether to copy the asset from the source prim or inherit it. Defaults to True.
This parameter is only used when cloning prims. If False, then the asset will be inherited from
the source prim, i.e. all USD changes to the source prim will be reflected in the cloned prims.
.. versionadded:: 2023.1
This parameter is only supported from Isaac Sim 2023.1 onwards. If you are using an older
version of Isaac Sim, this parameter will be ignored.
"""
@configclass
class RigidObjectSpawnerCfg(SpawnerCfg):
"""Configuration parameters for spawning a rigid asset.
Note:
By default, all properties are set to None. This means that no properties will be added or modified
to the prim outside of the properties available by default when spawning the prim.
"""
mass_props: schemas.MassPropertiesCfg | None = None
"""Mass properties."""
rigid_props: schemas.RigidBodyPropertiesCfg | None = None
"""Rigid body properties.
For making a rigid object static, set the :attr:`schemas.RigidBodyPropertiesCfg.kinematic_enabled`
as True. This will make the object static and will not be affected by gravity or other forces.
"""
collision_props: schemas.CollisionPropertiesCfg | None = None
"""Properties to apply to all collision meshes."""
activate_contact_sensors: bool = False
"""Activate contact reporting on all rigid bodies. Defaults to False.
This adds the PhysxContactReporter API to all the rigid bodies in the given prim path and its children.
"""
| 4,017 | Python | 38.392156 | 148 | 0.721683 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing utilities for creating prims in Omniverse.
Spawners are used to create prims into Omniverse simulator. At their core, they are calling the
USD Python API or Omniverse Kit Commands to create prims. However, they also provide a convenient
interface for creating prims from their respective config classes.
There are two main ways of using the spawners:
1. Using the function from the module
.. code-block:: python
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
# spawn from USD file
cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/FrankaEmika/panda_instanceable.usd")
prim_path = "/World/myAsset"
# spawn using the function from the module
sim_utils.spawn_from_usd(prim_path, cfg)
2. Using the `func` reference in the config class
.. code-block:: python
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
# spawn from USD file
cfg = sim_utils.UsdFileCfg(usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/FrankaEmika/panda_instanceable.usd")
prim_path = "/World/myAsset"
# use the `func` reference in the config class
cfg.func(prim_path, cfg)
For convenience, we recommend using the second approach, as it allows to easily change the config
class and the function call in a single line of code.
Depending on the type of prim, the spawning-functions can also deal with the creation of prims
over multiple prim path. These need to be provided as a regex prim path expressions, which are
resolved based on the parent prim paths using the :meth:`omni.isaac.orbit.sim.utils.clone` function decorator.
For example:
* ``/World/Table_[1,2]/Robot`` will create the prims ``/World/Table_1/Robot`` and ``/World/Table_2/Robot``
only if the parent prim ``/World/Table_1`` and ``/World/Table_2`` exist.
* ``/World/Robot_[1,2]`` will **NOT** create the prims ``/World/Robot_1`` and
``/World/Robot_2`` as the prim path expression can be resolved to multiple prims.
"""
from .from_files import * # noqa: F401, F403
from .lights import * # noqa: F401, F403
from .materials import * # noqa: F401, F403
from .sensors import * # noqa: F401, F403
from .shapes import * # noqa: F401, F403
from .spawner_cfg import * # noqa: F401, F403
| 2,479 | Python | 38.365079 | 111 | 0.73215 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/sensors/sensors.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import omni.isaac.core.utils.prims as prim_utils
import omni.kit.commands
from pxr import Sdf, Usd
from omni.isaac.orbit.sim.utils import clone
from omni.isaac.orbit.utils import to_camel_case
if TYPE_CHECKING:
from . import sensors_cfg
CUSTOM_PINHOLE_CAMERA_ATTRIBUTES = {
"projection_type": ("cameraProjectionType", Sdf.ValueTypeNames.Token),
}
"""Custom attributes for pinhole camera model.
The dictionary maps the attribute name in the configuration to the attribute name in the USD prim.
"""
CUSTOM_FISHEYE_CAMERA_ATTRIBUTES = {
"projection_type": ("cameraProjectionType", Sdf.ValueTypeNames.Token),
"fisheye_nominal_width": ("fthetaWidth", Sdf.ValueTypeNames.Float),
"fisheye_nominal_height": ("fthetaHeight", Sdf.ValueTypeNames.Float),
"fisheye_optical_centre_x": ("fthetaCx", Sdf.ValueTypeNames.Float),
"fisheye_optical_centre_y": ("fthetaCy", Sdf.ValueTypeNames.Float),
"fisheye_max_fov": ("fthetaMaxFov", Sdf.ValueTypeNames.Float),
"fisheye_polynomial_a": ("fthetaPolyA", Sdf.ValueTypeNames.Float),
"fisheye_polynomial_b": ("fthetaPolyB", Sdf.ValueTypeNames.Float),
"fisheye_polynomial_c": ("fthetaPolyC", Sdf.ValueTypeNames.Float),
"fisheye_polynomial_d": ("fthetaPolyD", Sdf.ValueTypeNames.Float),
"fisheye_polynomial_e": ("fthetaPolyE", Sdf.ValueTypeNames.Float),
"fisheye_polynomial_f": ("fthetaPolyF", Sdf.ValueTypeNames.Float),
}
"""Custom attributes for fisheye camera model.
The dictionary maps the attribute name in the configuration to the attribute name in the USD prim.
"""
@clone
def spawn_camera(
prim_path: str,
cfg: sensors_cfg.PinholeCameraCfg | sensors_cfg.FisheyeCameraCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Create a USD camera prim with given projection type.
The function creates various attributes on the camera prim that specify the camera's properties.
These are later used by ``omni.replicator.core`` to render the scene with the given camera.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which case
this is set to the origin.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case this is set to identity.
Returns:
The created prim.
Raises:
ValueError: If a prim already exists at the given path.
"""
# spawn camera if it doesn't exist.
if not prim_utils.is_prim_path_valid(prim_path):
prim_utils.create_prim(prim_path, "Camera", translation=translation, orientation=orientation)
else:
raise ValueError(f"A prim already exists at path: '{prim_path}'.")
# lock camera from viewport (this disables viewport movement for camera)
if cfg.lock_camera:
omni.kit.commands.execute(
"ChangePropertyCommand",
prop_path=Sdf.Path(f"{prim_path}.omni:kit:cameraLock"),
value=True,
prev=None,
type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool,
)
# decide the custom attributes to add
if cfg.projection_type == "pinhole":
attribute_types = CUSTOM_PINHOLE_CAMERA_ATTRIBUTES
else:
attribute_types = CUSTOM_FISHEYE_CAMERA_ATTRIBUTES
# custom attributes in the config that are not USD Camera parameters
non_usd_cfg_param_names = ["func", "copy_from_source", "lock_camera", "visible", "semantic_tags"]
# get camera prim
prim = prim_utils.get_prim_at_path(prim_path)
# create attributes for the fisheye camera model
# note: for pinhole those are already part of the USD camera prim
for attr_name, attr_type in attribute_types.values():
# check if attribute does not exist
if prim.GetAttribute(attr_name).Get() is None:
# create attribute based on type
prim.CreateAttribute(attr_name, attr_type)
# set attribute values
for param_name, param_value in cfg.__dict__.items():
# check if value is valid
if param_value is None or param_name in non_usd_cfg_param_names:
continue
# obtain prim property name
if param_name in attribute_types:
# check custom attributes
prim_prop_name = attribute_types[param_name][0]
else:
# convert attribute name in prim to cfg name
prim_prop_name = to_camel_case(param_name, to="cC")
# get attribute from the class
prim.GetAttribute(prim_prop_name).Set(param_value)
# return the prim
return prim_utils.get_prim_at_path(prim_path)
| 5,404 | Python | 40.576923 | 115 | 0.687454 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/sensors/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for spawners that spawn sensors in the simulation.
Currently, the following sensors are supported:
* Camera: A USD camera prim with settings for pinhole or fisheye projections.
"""
from .sensors import spawn_camera
from .sensors_cfg import FisheyeCameraCfg, PinholeCameraCfg
| 416 | Python | 25.062498 | 77 | 0.778846 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/sensors/sensors_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from collections.abc import Callable
from typing import Literal
from omni.isaac.orbit.sim.spawners.spawner_cfg import SpawnerCfg
from omni.isaac.orbit.utils import configclass
from . import sensors
@configclass
class PinholeCameraCfg(SpawnerCfg):
"""Configuration parameters for a USD camera prim with pinhole camera settings.
For more information on the parameters, please refer to the `camera documentation <https://docs.omniverse.nvidia.com/materials-and-rendering/latest/cameras.html>`__.
.. note::
The default values are taken from the `Replicator camera <https://docs.omniverse.nvidia.com/py/replicator/1.9.8/source/extensions/omni.replicator.core/docs/API.html#omni.replicator.core.create.camera>`__
function.
"""
func: Callable = sensors.spawn_camera
projection_type: str = "pinhole"
"""Type of projection to use for the camera. Defaults to "pinhole".
Note:
Currently only "pinhole" is supported.
"""
clipping_range: tuple[float, float] = (0.01, 1e6)
"""Near and far clipping distances (in m). Defaults to (0.01, 1e6).
The minimum clipping range will shift the camera forward by the specified distance. Don't set it too high to
avoid issues for distance related data types (e.g., ``distance_to_image_plane``).
"""
focal_length: float = 24.0
"""Perspective focal length (in cm). Defaults to 24.0cm.
Longer lens lengths narrower FOV, shorter lens lengths wider FOV.
"""
focus_distance: float = 400.0
"""Distance from the camera to the focus plane (in m). Defaults to 400.0.
The distance at which perfect sharpness is achieved.
"""
f_stop: float = 0.0
"""Lens aperture. Defaults to 0.0, which turns off focusing.
Controls Distance Blurring. Lower Numbers decrease focus range, larger numbers increase it.
"""
horizontal_aperture: float = 20.955
"""Horizontal aperture (in mm). Defaults to 20.955mm.
Emulates sensor/film width on a camera.
Note:
The default value is the horizontal aperture of a 35 mm spherical projector.
"""
horizontal_aperture_offset: float = 0.0
"""Offsets Resolution/Film gate horizontally. Defaults to 0.0."""
vertical_aperture_offset: float = 0.0
"""Offsets Resolution/Film gate vertically. Defaults to 0.0."""
lock_camera: bool = True
"""Locks the camera in the Omniverse viewport. Defaults to True.
If True, then the camera remains fixed at its configured transform. This is useful when wanting to view
the camera output on the GUI and not accidentally moving the camera through the GUI interactions.
"""
@configclass
class FisheyeCameraCfg(PinholeCameraCfg):
"""Configuration parameters for a USD camera prim with `fish-eye camera`_ settings.
For more information on the parameters, please refer to the
`camera documentation <https://docs.omniverse.nvidia.com/materials-and-rendering/latest/cameras.html#fisheye-properties>`__.
.. note::
The default values are taken from the `Replicator camera <https://docs.omniverse.nvidia.com/py/replicator/1.9.8/source/extensions/omni.replicator.core/docs/API.html#omni.replicator.core.create.camera>`__
function.
.. _fish-eye camera: https://en.wikipedia.org/wiki/Fisheye_lens
"""
func: Callable = sensors.spawn_camera
projection_type: Literal[
"fisheye_orthographic", "fisheye_equidistant", "fisheye_equisolid", "fisheye_polynomial", "fisheye_spherical"
] = "fisheye_polynomial"
r"""Type of projection to use for the camera. Defaults to "fisheye_polynomial".
Available options:
- ``"fisheye_orthographic"``: Fisheye camera model using orthographic correction.
- ``"fisheye_equidistant"``: Fisheye camera model using equidistant correction.
- ``"fisheye_equisolid"``: Fisheye camera model using equisolid correction.
- ``"fisheye_polynomial"``: Fisheye camera model with :math:`360^{\circ}` spherical projection.
- ``"fisheye_spherical"``: Fisheye camera model with :math:`360^{\circ}` full-frame projection.
"""
fisheye_nominal_width: float = 1936.0
"""Nominal width of fisheye lens model (in pixels). Defaults to 1936.0."""
fisheye_nominal_height: float = 1216.0
"""Nominal height of fisheye lens model (in pixels). Defaults to 1216.0."""
fisheye_optical_centre_x: float = 970.94244
"""Horizontal optical centre position of fisheye lens model (in pixels). Defaults to 970.94244."""
fisheye_optical_centre_y: float = 600.37482
"""Vertical optical centre position of fisheye lens model (in pixels). Defaults to 600.37482."""
fisheye_max_fov: float = 200.0
"""Maximum field of view of fisheye lens model (in degrees). Defaults to 200.0 degrees."""
fisheye_polynomial_a: float = 0.0
"""First component of fisheye polynomial. Defaults to 0.0."""
fisheye_polynomial_b: float = 0.00245
"""Second component of fisheye polynomial. Defaults to 0.00245."""
fisheye_polynomial_c: float = 0.0
"""Third component of fisheye polynomial. Defaults to 0.0."""
fisheye_polynomial_d: float = 0.0
"""Fourth component of fisheye polynomial. Defaults to 0.0."""
fisheye_polynomial_e: float = 0.0
"""Fifth component of fisheye polynomial. Defaults to 0.0."""
fisheye_polynomial_f: float = 0.0
"""Sixth component of fisheye polynomial. Defaults to 0.0."""
| 5,523 | Python | 42.84127 | 211 | 0.706319 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/lights/lights_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from collections.abc import Callable
from dataclasses import MISSING
from typing import Literal
from omni.isaac.orbit.sim.spawners.spawner_cfg import SpawnerCfg
from omni.isaac.orbit.utils import configclass
from . import lights
@configclass
class LightCfg(SpawnerCfg):
"""Configuration parameters for creating a light in the scene.
Please refer to the documentation on `USD LuxLight <https://openusd.org/dev/api/class_usd_lux_light_a_p_i.html>`_
for more information.
.. note::
The default values for the attributes are those specified in the their official documentation.
"""
func: Callable = lights.spawn_light
prim_type: str = MISSING
"""The prim type name for the light prim."""
color: tuple[float, float, float] = (1.0, 1.0, 1.0)
"""The color of emitted light, in energy-linear terms. Defaults to white."""
enable_color_temperature: bool = False
"""Enables color temperature. Defaults to false."""
color_temperature: float = 6500.0
"""Color temperature (in Kelvin) representing the white point. The valid range is [1000, 10000]. Defaults to 6500K.
The `color temperature <https://en.wikipedia.org/wiki/Color_temperature>`_ corresponds to the warmth
or coolness of light. Warmer light has a lower color temperature, while cooler light has a higher
color temperature.
Note:
It only takes effect when :attr:`enable_color_temperature` is true.
"""
normalize: bool = False
"""Normalizes power by the surface area of the light. Defaults to false.
This makes it easier to independently adjust the power and shape of the light, by causing the power
to not vary with the area or angular size of the light.
"""
exposure: float = 0.0
"""Scales the power of the light exponentially as a power of 2. Defaults to 0.0.
The result is multiplied against the intensity.
"""
intensity: float = 1.0
"""Scales the power of the light linearly. Defaults to 1.0."""
@configclass
class DiskLightCfg(LightCfg):
"""Configuration parameters for creating a disk light in the scene.
A disk light is a light source that emits light from a disk. It is useful for simulating
fluorescent lights. For more information, please refer to the documentation on
`USDLux DiskLight <https://openusd.org/dev/api/class_usd_lux_disk_light.html>`_.
.. note::
The default values for the attributes are those specified in the their official documentation.
"""
prim_type = "DiskLight"
radius: float = 0.5
"""Radius of the disk (in m). Defaults to 0.5m."""
@configclass
class DistantLightCfg(LightCfg):
"""Configuration parameters for creating a distant light in the scene.
A distant light is a light source that is infinitely far away, and emits parallel rays of light.
It is useful for simulating sun/moon light. For more information, please refer to the documentation on
`USDLux DistantLight <https://openusd.org/dev/api/class_usd_lux_distant_light.html>`_.
.. note::
The default values for the attributes are those specified in the their official documentation.
"""
prim_type = "DistantLight"
angle: float = 0.53
"""Angular size of the light (in degrees). Defaults to 0.53 degrees.
As an example, the Sun is approximately 0.53 degrees as seen from Earth.
Higher values broaden the light and therefore soften shadow edges.
"""
@configclass
class DomeLightCfg(LightCfg):
"""Configuration parameters for creating a dome light in the scene.
A dome light is a light source that emits light inwards from all directions. It is also possible to
attach a texture to the dome light, which will be used to emit light. For more information, please refer
to the documentation on `USDLux DomeLight <https://openusd.org/dev/api/class_usd_lux_dome_light.html>`_.
.. note::
The default values for the attributes are those specified in the their official documentation.
"""
prim_type = "DomeLight"
texture_file: str | None = None
"""A color texture to use on the dome, such as an HDR (high dynamic range) texture intended
for IBL (image based lighting). Defaults to None.
If None, the dome will emit a uniform color.
"""
texture_format: Literal["automatic", "latlong", "mirroredBall", "angular", "cubeMapVerticalCross"] = "automatic"
"""The parametrization format of the color map file. Defaults to "automatic".
Valid values are:
* ``"automatic"``: Tries to determine the layout from the file itself. For example, Renderman texture files embed an explicit parameterization.
* ``"latlong"``: Latitude as X, longitude as Y.
* ``"mirroredBall"``: An image of the environment reflected in a sphere, using an implicitly orthogonal projection.
* ``"angular"``: Similar to mirroredBall but the radial dimension is mapped linearly to the angle, providing better sampling at the edges.
* ``"cubeMapVerticalCross"``: A cube map with faces laid out as a vertical cross.
"""
@configclass
class CylinderLightCfg(LightCfg):
"""Configuration parameters for creating a cylinder light in the scene.
A cylinder light is a light source that emits light from a cylinder. It is useful for simulating
fluorescent lights. For more information, please refer to the documentation on
`USDLux CylinderLight <https://openusd.org/dev/api/class_usd_lux_cylinder_light.html>`_.
.. note::
The default values for the attributes are those specified in the their official documentation.
"""
prim_type = "CylinderLight"
length: float = 1.0
"""Length of the cylinder (in m). Defaults to 1.0m."""
radius: float = 0.5
"""Radius of the cylinder (in m). Defaults to 0.5m."""
treat_as_line: bool = False
"""Treats the cylinder as a line source, i.e. a zero-radius cylinder. Defaults to false."""
@configclass
class SphereLightCfg(LightCfg):
"""Configuration parameters for creating a sphere light in the scene.
A sphere light is a light source that emits light outward from a sphere. For more information,
please refer to the documentation on
`USDLux SphereLight <https://openusd.org/dev/api/class_usd_lux_sphere_light.html>`_.
.. note::
The default values for the attributes are those specified in the their official documentation.
"""
prim_type = "SphereLight"
radius: float = 0.5
"""Radius of the sphere. Defaults to 0.5m."""
treat_as_point: bool = False
"""Treats the sphere as a point source, i.e. a zero-radius sphere. Defaults to false."""
| 6,765 | Python | 35.972677 | 147 | 0.708056 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/lights/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for spawners that spawn lights in the simulation.
There are various different kinds of lights that can be spawned into the USD stage.
Please check the Omniverse documentation for `lighting overview
<https://docs.omniverse.nvidia.com/materials-and-rendering/latest/103/lighting.html>`_.
"""
from .lights import spawn_light
from .lights_cfg import CylinderLightCfg, DiskLightCfg, DistantLightCfg, DomeLightCfg, LightCfg, SphereLightCfg
| 573 | Python | 37.266664 | 111 | 0.794066 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/lights/lights.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import omni.isaac.core.utils.prims as prim_utils
from pxr import Usd, UsdLux
from omni.isaac.orbit.sim.utils import clone, safe_set_attribute_on_usd_prim
if TYPE_CHECKING:
from . import lights_cfg
@clone
def spawn_light(
prim_path: str,
cfg: lights_cfg.LightCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Create a light prim at the specified prim path with the specified configuration.
The created prim is based on the `USD.LuxLight <https://openusd.org/dev/api/class_usd_lux_light_a_p_i.html>`_ API.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration for the light source.
translation: The translation of the prim. Defaults to None, in which case this is set to the origin.
orientation: The orientation of the prim as (w, x, y, z). Defaults to None, in which case this
is set to identity.
Raises:
ValueError: When a prim already exists at the specified prim path.
"""
# check if prim already exists
if prim_utils.is_prim_path_valid(prim_path):
raise ValueError(f"A prim already exists at path: '{prim_path}'.")
# create the prim
prim = prim_utils.create_prim(prim_path, prim_type=cfg.prim_type, translation=translation, orientation=orientation)
# convert to dict
cfg = cfg.to_dict()
# delete spawner func specific parameters
del cfg["prim_type"]
# delete custom attributes in the config that are not USD parameters
non_usd_cfg_param_names = ["func", "copy_from_source", "visible", "semantic_tags"]
for param_name in non_usd_cfg_param_names:
del cfg[param_name]
# set into USD API
for attr_name, value in cfg.items():
# special operation for texture properties
# note: this is only used for dome light
if "texture" in attr_name:
light_prim = UsdLux.DomeLight(prim)
if attr_name == "texture_file":
light_prim.CreateTextureFileAttr(value)
elif attr_name == "texture_format":
light_prim.CreateTextureFormatAttr(value)
else:
raise ValueError(f"Unsupported texture attribute: '{attr_name}'.")
else:
prim_prop_name = f"inputs:{attr_name}"
# set the attribute
safe_set_attribute_on_usd_prim(prim, prim_prop_name, value, camel_case=True)
# return the prim
return prim
| 3,120 | Python | 39.01282 | 119 | 0.666346 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/shapes/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for spawning primitive shapes in the simulation.
NVIDIA Omniverse provides various primitive shapes that can be used to create USDGeom prims. Based
on the configuration, the spawned prim can be:
* a visual mesh (no physics)
* a static collider (no rigid body)
* a rigid body (with collision and rigid body properties).
"""
from .shapes import spawn_capsule, spawn_cone, spawn_cuboid, spawn_cylinder, spawn_sphere
from .shapes_cfg import CapsuleCfg, ConeCfg, CuboidCfg, CylinderCfg, ShapeCfg, SphereCfg
| 643 | Python | 32.894735 | 98 | 0.772939 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/shapes/shapes_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from collections.abc import Callable
from dataclasses import MISSING
from typing import Literal
from omni.isaac.orbit.sim.spawners import materials
from omni.isaac.orbit.sim.spawners.spawner_cfg import RigidObjectSpawnerCfg
from omni.isaac.orbit.utils import configclass
from . import shapes
@configclass
class ShapeCfg(RigidObjectSpawnerCfg):
"""Configuration parameters for a USD Geometry or Geom prim."""
visual_material_path: str = "material"
"""Path to the visual material to use for the prim. Defaults to "material".
If the path is relative, then it will be relative to the prim's path.
This parameter is ignored if `visual_material` is not None.
"""
visual_material: materials.VisualMaterialCfg | None = None
"""Visual material properties.
Note:
If None, then no visual material will be added.
"""
physics_material_path: str = "material"
"""Path to the physics material to use for the prim. Defaults to "material".
If the path is relative, then it will be relative to the prim's path.
This parameter is ignored if `physics_material` is not None.
"""
physics_material: materials.PhysicsMaterialCfg | None = None
"""Physics material properties.
Note:
If None, then no physics material will be added.
"""
@configclass
class SphereCfg(ShapeCfg):
"""Configuration parameters for a sphere prim.
See :meth:`spawn_sphere` for more information.
"""
func: Callable = shapes.spawn_sphere
radius: float = MISSING
"""Radius of the sphere (in m)."""
@configclass
class CuboidCfg(ShapeCfg):
"""Configuration parameters for a cuboid prim.
See :meth:`spawn_cuboid` for more information.
"""
func: Callable = shapes.spawn_cuboid
size: tuple[float, float, float] = MISSING
"""Size of the cuboid."""
@configclass
class CylinderCfg(ShapeCfg):
"""Configuration parameters for a cylinder prim.
See :meth:`spawn_cylinder` for more information.
"""
func: Callable = shapes.spawn_cylinder
radius: float = MISSING
"""Radius of the cylinder (in m)."""
height: float = MISSING
"""Height of the cylinder (in m)."""
axis: Literal["X", "Y", "Z"] = "Z"
"""Axis of the cylinder. Defaults to "Z"."""
@configclass
class CapsuleCfg(ShapeCfg):
"""Configuration parameters for a capsule prim.
See :meth:`spawn_capsule` for more information.
"""
func: Callable = shapes.spawn_capsule
radius: float = MISSING
"""Radius of the capsule (in m)."""
height: float = MISSING
"""Height of the capsule (in m)."""
axis: Literal["X", "Y", "Z"] = "Z"
"""Axis of the capsule. Defaults to "Z"."""
@configclass
class ConeCfg(ShapeCfg):
"""Configuration parameters for a cone prim.
See :meth:`spawn_cone` for more information.
"""
func: Callable = shapes.spawn_cone
radius: float = MISSING
"""Radius of the cone (in m)."""
height: float = MISSING
"""Height of the v (in m)."""
axis: Literal["X", "Y", "Z"] = "Z"
"""Axis of the cone. Defaults to "Z"."""
| 3,222 | Python | 25.203252 | 80 | 0.667287 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/shapes/shapes.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import omni.isaac.core.utils.prims as prim_utils
from pxr import Usd
from omni.isaac.orbit.sim import schemas
from omni.isaac.orbit.sim.utils import bind_physics_material, bind_visual_material, clone
if TYPE_CHECKING:
from . import shapes_cfg
@clone
def spawn_sphere(
prim_path: str,
cfg: shapes_cfg.SphereCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Create a USDGeom-based sphere prim with the given attributes.
For more information, see `USDGeomSphere <https://openusd.org/dev/api/class_usd_geom_sphere.html>`_.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which case
this is set to the origin.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case this is set to identity.
Returns:
The created prim.
Raises:
ValueError: If a prim already exists at the given path.
"""
# spawn sphere if it doesn't exist.
attributes = {"radius": cfg.radius}
_spawn_geom_from_prim_type(prim_path, cfg, "Sphere", attributes, translation, orientation)
# return the prim
return prim_utils.get_prim_at_path(prim_path)
@clone
def spawn_cuboid(
prim_path: str,
cfg: shapes_cfg.CuboidCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Create a USDGeom-based cuboid prim with the given attributes.
For more information, see `USDGeomCube <https://openusd.org/dev/api/class_usd_geom_cube.html>`_.
Note:
Since USD only supports cubes, we set the size of the cube to the minimum of the given size and
scale the cube accordingly.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which case
this is set to the origin.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case this is set to identity.
Returns:
The created prim.
Raises:
If a prim already exists at the given path.
"""
# resolve the scale
size = min(cfg.size)
scale = [dim / size for dim in cfg.size]
# spawn cuboid if it doesn't exist.
attributes = {"size": size}
_spawn_geom_from_prim_type(prim_path, cfg, "Cube", attributes, translation, orientation, scale)
# return the prim
return prim_utils.get_prim_at_path(prim_path)
@clone
def spawn_cylinder(
prim_path: str,
cfg: shapes_cfg.CylinderCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Create a USDGeom-based cylinder prim with the given attributes.
For more information, see `USDGeomCylinder <https://openusd.org/dev/api/class_usd_geom_cylinder.html>`_.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which case
this is set to the origin.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case this is set to identity.
Returns:
The created prim.
Raises:
ValueError: If a prim already exists at the given path.
"""
# spawn cylinder if it doesn't exist.
attributes = {"radius": cfg.radius, "height": cfg.height, "axis": cfg.axis.upper()}
_spawn_geom_from_prim_type(prim_path, cfg, "Cylinder", attributes, translation, orientation)
# return the prim
return prim_utils.get_prim_at_path(prim_path)
@clone
def spawn_capsule(
prim_path: str,
cfg: shapes_cfg.CapsuleCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Create a USDGeom-based capsule prim with the given attributes.
For more information, see `USDGeomCapsule <https://openusd.org/dev/api/class_usd_geom_capsule.html>`_.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which case
this is set to the origin.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case this is set to identity.
Returns:
The created prim.
Raises:
ValueError: If a prim already exists at the given path.
"""
# spawn capsule if it doesn't exist.
attributes = {"radius": cfg.radius, "height": cfg.height, "axis": cfg.axis.upper()}
_spawn_geom_from_prim_type(prim_path, cfg, "Capsule", attributes, translation, orientation)
# return the prim
return prim_utils.get_prim_at_path(prim_path)
@clone
def spawn_cone(
prim_path: str,
cfg: shapes_cfg.ConeCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Create a USDGeom-based cone prim with the given attributes.
For more information, see `USDGeomCone <https://openusd.org/dev/api/class_usd_geom_cone.html>`_.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which case
this is set to the origin.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case this is set to identity.
Returns:
The created prim.
Raises:
ValueError: If a prim already exists at the given path.
"""
# spawn cone if it doesn't exist.
attributes = {"radius": cfg.radius, "height": cfg.height, "axis": cfg.axis.upper()}
_spawn_geom_from_prim_type(prim_path, cfg, "Cone", attributes, translation, orientation)
# return the prim
return prim_utils.get_prim_at_path(prim_path)
"""
Helper functions.
"""
def _spawn_geom_from_prim_type(
prim_path: str,
cfg: shapes_cfg.ShapeCfg,
prim_type: str,
attributes: dict,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
scale: tuple[float, float, float] | None = None,
):
"""Create a USDGeom-based prim with the given attributes.
To make the asset instanceable, we must follow a certain structure dictated by how USD scene-graph
instancing and physics work. The rigid body component must be added to each instance and not the
referenced asset (i.e. the prototype prim itself). This is because the rigid body component defines
properties that are specific to each instance and cannot be shared under the referenced asset. For
more information, please check the `documentation <https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/rigid-bodies.html#instancing-rigid-bodies>`_.
Due to the above, we follow the following structure:
* ``{prim_path}`` - The root prim that is an Xform with the rigid body and mass APIs if configured.
* ``{prim_path}/geometry`` - The prim that contains the mesh and optionally the materials if configured.
If instancing is enabled, this prim will be an instanceable reference to the prototype prim.
Args:
prim_path: The prim path to spawn the asset at.
cfg: The config containing the properties to apply.
prim_type: The type of prim to create.
attributes: The attributes to apply to the prim.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which case
this is set to the origin.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case this is set to identity.
scale: The scale to apply to the prim. Defaults to None, in which case this is set to identity.
Raises:
ValueError: If a prim already exists at the given path.
"""
# spawn geometry if it doesn't exist.
if not prim_utils.is_prim_path_valid(prim_path):
prim_utils.create_prim(prim_path, prim_type="Xform", translation=translation, orientation=orientation)
else:
raise ValueError(f"A prim already exists at path: '{prim_path}'.")
# create all the paths we need for clarity
geom_prim_path = prim_path + "/geometry"
mesh_prim_path = geom_prim_path + "/mesh"
# create the geometry prim
prim_utils.create_prim(mesh_prim_path, prim_type, scale=scale, attributes=attributes)
# apply collision properties
if cfg.collision_props is not None:
schemas.define_collision_properties(mesh_prim_path, cfg.collision_props)
# apply visual material
if cfg.visual_material is not None:
if not cfg.visual_material_path.startswith("/"):
material_path = f"{geom_prim_path}/{cfg.visual_material_path}"
else:
material_path = cfg.visual_material_path
# create material
cfg.visual_material.func(material_path, cfg.visual_material)
# apply material
bind_visual_material(mesh_prim_path, material_path)
# apply physics material
if cfg.physics_material is not None:
if not cfg.physics_material_path.startswith("/"):
material_path = f"{geom_prim_path}/{cfg.physics_material_path}"
else:
material_path = cfg.physics_material_path
# create material
cfg.physics_material.func(material_path, cfg.physics_material)
# apply material
bind_physics_material(mesh_prim_path, material_path)
# note: we apply rigid properties in the end to later make the instanceable prim
# apply mass properties
if cfg.mass_props is not None:
schemas.define_mass_properties(prim_path, cfg.mass_props)
# apply rigid body properties
if cfg.rigid_props is not None:
schemas.define_rigid_body_properties(prim_path, cfg.rigid_props)
| 12,870 | Python | 41.619205 | 164 | 0.678477 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/from_files/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for spawners that spawn assets from files.
Currently, the following spawners are supported:
* :class:`UsdFileCfg`: Spawn an asset from a USD file.
* :class:`UrdfFileCfg`: Spawn an asset from a URDF file.
* :class:`GroundPlaneCfg`: Spawn a ground plane using the grid-world USD file.
"""
from .from_files import spawn_from_urdf, spawn_from_usd, spawn_ground_plane
from .from_files_cfg import GroundPlaneCfg, UrdfFileCfg, UsdFileCfg
| 572 | Python | 30.833332 | 78 | 0.756993 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/from_files/from_files.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import carb
import omni.isaac.core.utils.prims as prim_utils
import omni.isaac.core.utils.stage as stage_utils
import omni.kit.commands
from pxr import Gf, Sdf, Usd
from omni.isaac.orbit.sim import converters, schemas
from omni.isaac.orbit.sim.utils import bind_physics_material, bind_visual_material, clone, select_usd_variants
if TYPE_CHECKING:
from . import from_files_cfg
@clone
def spawn_from_usd(
prim_path: str,
cfg: from_files_cfg.UsdFileCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Spawn an asset from a USD file and override the settings with the given config.
In the case of a USD file, the asset is spawned at the default prim specified in the USD file.
If a default prim is not specified, then the asset is spawned at the root prim.
In case a prim already exists at the given prim path, then the function does not create a new prim
or throw an error that the prim already exists. Instead, it just takes the existing prim and overrides
the settings with the given config.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which
case the translation specified in the USD file is used.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case the orientation specified in the USD file is used.
Returns:
The prim of the spawned asset.
Raises:
FileNotFoundError: If the USD file does not exist at the given path.
"""
# spawn asset from the given usd file
return _spawn_from_usd_file(prim_path, cfg.usd_path, cfg, translation, orientation)
@clone
def spawn_from_urdf(
prim_path: str,
cfg: from_files_cfg.UrdfFileCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Spawn an asset from a URDF file and override the settings with the given config.
It uses the :class:`UrdfConverter` class to create a USD file from URDF. This file is then imported
at the specified prim path.
In case a prim already exists at the given prim path, then the function does not create a new prim
or throw an error that the prim already exists. Instead, it just takes the existing prim and overrides
the settings with the given config.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which
case the translation specified in the generated USD file is used.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case the orientation specified in the generated USD file is used.
Returns:
The prim of the spawned asset.
Raises:
FileNotFoundError: If the URDF file does not exist at the given path.
"""
# urdf loader to convert urdf to usd
urdf_loader = converters.UrdfConverter(cfg)
# spawn asset from the generated usd file
return _spawn_from_usd_file(prim_path, urdf_loader.usd_path, cfg, translation, orientation)
def spawn_ground_plane(
prim_path: str,
cfg: from_files_cfg.GroundPlaneCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Spawns a ground plane into the scene.
This function loads the USD file containing the grid plane asset from Isaac Sim. It may
not work with other assets for ground planes. In those cases, please use the `spawn_from_usd`
function.
Note:
This function takes keyword arguments to be compatible with other spawners. However, it does not
use any of the kwargs.
Args:
prim_path: The path to spawn the asset at.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which
case the translation specified in the USD file is used.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case the orientation specified in the USD file is used.
Returns:
The prim of the spawned asset.
Raises:
ValueError: If the prim path already exists.
"""
# Spawn Ground-plane
if not prim_utils.is_prim_path_valid(prim_path):
prim_utils.create_prim(prim_path, usd_path=cfg.usd_path, translation=translation, orientation=orientation)
else:
raise ValueError(f"A prim already exists at path: '{prim_path}'.")
# Create physics material
if cfg.physics_material is not None:
cfg.physics_material.func(f"{prim_path}/physicsMaterial", cfg.physics_material)
# Apply physics material to ground plane
collision_prim_path = prim_utils.get_prim_path(
prim_utils.get_first_matching_child_prim(
prim_path, predicate=lambda x: prim_utils.get_prim_type_name(x) == "Plane"
)
)
bind_physics_material(collision_prim_path, f"{prim_path}/physicsMaterial")
# Scale only the mesh
# Warning: This is specific to the default grid plane asset.
if prim_utils.is_prim_path_valid(f"{prim_path}/Enviroment"):
# compute scale from size
scale = (cfg.size[0] / 100.0, cfg.size[1] / 100.0, 1.0)
# apply scale to the mesh
omni.kit.commands.execute(
"ChangeProperty",
prop_path=Sdf.Path(f"{prim_path}/Enviroment.xformOp:scale"),
value=scale,
prev=None,
)
# Change the color of the plane
# Warning: This is specific to the default grid plane asset.
if cfg.color is not None:
prop_path = f"{prim_path}/Looks/theGrid/Shader.inputs:diffuse_tint"
# change the color
omni.kit.commands.execute(
"ChangePropertyCommand",
prop_path=Sdf.Path(prop_path),
value=Gf.Vec3f(*cfg.color),
prev=None,
type_to_create_if_not_exist=Sdf.ValueTypeNames.Color3f,
)
# Remove the light from the ground plane
# It isn't bright enough and messes up with the user's lighting settings
omni.kit.commands.execute("ToggleVisibilitySelectedPrims", selected_paths=[f"{prim_path}/SphereLight"])
# return the prim
return prim_utils.get_prim_at_path(prim_path)
"""
Helper functions.
"""
def _spawn_from_usd_file(
prim_path: str,
usd_path: str,
cfg: from_files_cfg.FileCfg,
translation: tuple[float, float, float] | None = None,
orientation: tuple[float, float, float, float] | None = None,
) -> Usd.Prim:
"""Spawn an asset from a USD file and override the settings with the given config.
In case a prim already exists at the given prim path, then the function does not create a new prim
or throw an error that the prim already exists. Instead, it just takes the existing prim and overrides
the settings with the given config.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
usd_path: The path to the USD file to spawn the asset from.
cfg: The configuration instance.
translation: The translation to apply to the prim w.r.t. its parent prim. Defaults to None, in which
case the translation specified in the generated USD file is used.
orientation: The orientation in (w, x, y, z) to apply to the prim w.r.t. its parent prim. Defaults to None,
in which case the orientation specified in the generated USD file is used.
Returns:
The prim of the spawned asset.
Raises:
FileNotFoundError: If the USD file does not exist at the given path.
"""
# check file path exists
stage: Usd.Stage = stage_utils.get_current_stage()
if not stage.ResolveIdentifierToEditTarget(usd_path):
raise FileNotFoundError(f"USD file not found at path: '{usd_path}'.")
# spawn asset if it doesn't exist.
if not prim_utils.is_prim_path_valid(prim_path):
# add prim as reference to stage
prim_utils.create_prim(
prim_path,
usd_path=usd_path,
translation=translation,
orientation=orientation,
scale=cfg.scale,
)
else:
carb.log_warn(f"A prim already exists at prim path: '{prim_path}'.")
# modify variants
if hasattr(cfg, "variants") and cfg.variants is not None:
select_usd_variants(prim_path, cfg.variants)
# modify rigid body properties
if cfg.rigid_props is not None:
schemas.modify_rigid_body_properties(prim_path, cfg.rigid_props)
# modify collision properties
if cfg.collision_props is not None:
schemas.modify_collision_properties(prim_path, cfg.collision_props)
# modify mass properties
if cfg.mass_props is not None:
schemas.modify_mass_properties(prim_path, cfg.mass_props)
# modify articulation root properties
if cfg.articulation_props is not None:
schemas.modify_articulation_root_properties(prim_path, cfg.articulation_props)
# modify tendon properties
if cfg.fixed_tendons_props is not None:
schemas.modify_fixed_tendon_properties(prim_path, cfg.fixed_tendons_props)
# define drive API on the joints
# note: these are only for setting low-level simulation properties. all others should be set or are
# and overridden by the articulation/actuator properties.
if cfg.joint_drive_props is not None:
schemas.modify_joint_drive_properties(prim_path, cfg.joint_drive_props)
# apply visual material
if cfg.visual_material is not None:
if not cfg.visual_material_path.startswith("/"):
material_path = f"{prim_path}/{cfg.visual_material_path}"
else:
material_path = cfg.visual_material_path
# create material
cfg.visual_material.func(material_path, cfg.visual_material)
# apply material
bind_visual_material(prim_path, material_path)
# return the prim
return prim_utils.get_prim_at_path(prim_path)
| 11,587 | Python | 41.138182 | 115 | 0.680245 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/from_files/from_files_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from collections.abc import Callable
from dataclasses import MISSING
from omni.isaac.orbit.sim import converters, schemas
from omni.isaac.orbit.sim.spawners import materials
from omni.isaac.orbit.sim.spawners.spawner_cfg import RigidObjectSpawnerCfg, SpawnerCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
from . import from_files
@configclass
class FileCfg(RigidObjectSpawnerCfg):
"""Configuration parameters for spawning an asset from a file.
Note:
By default, all properties are set to None. This means that no properties will be added or modified
to the prim outside of the properties available by default when spawning the prim.
"""
scale: tuple[float, float, float] | None = None
"""Scale of the asset. Defaults to None, in which case the scale is not modified."""
articulation_props: schemas.ArticulationRootPropertiesCfg | None = None
"""Properties to apply to the articulation root."""
fixed_tendons_props: schemas.FixedTendonsPropertiesCfg | None = None
"""Properties to apply to the fixed tendons (if any)."""
joint_drive_props: schemas.JointDrivePropertiesCfg | None = None
"""Properties to apply to a joint."""
visual_material_path: str = "material"
"""Path to the visual material to use for the prim. Defaults to "material".
If the path is relative, then it will be relative to the prim's path.
This parameter is ignored if `visual_material` is not None.
"""
visual_material: materials.VisualMaterialCfg | None = None
"""Visual material properties to override the visual material properties in the URDF file.
Note:
If None, then no visual material will be added.
"""
@configclass
class UsdFileCfg(FileCfg):
"""USD file to spawn asset from.
See :meth:`spawn_from_usd` for more information.
.. note::
The configuration parameters include various properties. If not `None`, these properties
are modified on the spawned prim in a nested manner.
"""
func: Callable = from_files.spawn_from_usd
usd_path: str = MISSING
"""Path to the USD file to spawn asset from."""
variants: object | dict[str, str] | None = None
"""Variants to select from in the input USD file. Defaults to None, in which case no variants are applied.
This can either be a configclass object, in which case each attribute is used as a variant set name and its specified value,
or a dictionary mapping between the two. Please check the :meth:`~omni.isaac.orbit.sim.utils.select_usd_variants` function
for more information.
"""
@configclass
class UrdfFileCfg(FileCfg, converters.UrdfConverterCfg):
"""URDF file to spawn asset from.
It uses the :class:`UrdfConverter` class to create a USD file from URDF and spawns the imported
USD file. See :meth:`spawn_from_urdf` for more information.
.. note::
The configuration parameters include various properties. If not `None`, these properties
are modified on the spawned prim in a nested manner.
"""
func: Callable = from_files.spawn_from_urdf
"""
Spawning ground plane.
"""
@configclass
class GroundPlaneCfg(SpawnerCfg):
"""Create a ground plane prim.
This uses the USD for the standard grid-world ground plane from Isaac Sim by default.
"""
func: Callable = from_files.spawn_ground_plane
usd_path: str = f"{ISAAC_NUCLEUS_DIR}/Environments/Grid/default_environment.usd"
"""Path to the USD file to spawn asset from. Defaults to the grid-world ground plane."""
color: tuple[float, float, float] | None = (0.0, 0.0, 0.0)
"""The color of the ground plane. Defaults to (0.0, 0.0, 0.0).
If None, then the color remains unchanged.
"""
size: tuple[float, float] = (100.0, 100.0)
"""The size of the ground plane. Defaults to 100 m x 100 m."""
physics_material: materials.RigidBodyMaterialCfg = materials.RigidBodyMaterialCfg()
"""Physics material properties. Defaults to the default rigid body material."""
| 4,245 | Python | 33.241935 | 128 | 0.712367 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/materials/visual_materials_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from collections.abc import Callable
from dataclasses import MISSING
from omni.isaac.orbit.utils import configclass
from . import visual_materials
@configclass
class VisualMaterialCfg:
"""Configuration parameters for creating a visual material."""
func: Callable = MISSING
"""The function to use for creating the material."""
@configclass
class PreviewSurfaceCfg(VisualMaterialCfg):
"""Configuration parameters for creating a preview surface.
See :meth:`spawn_preview_surface` for more information.
"""
func: Callable = visual_materials.spawn_preview_surface
diffuse_color: tuple[float, float, float] = (0.18, 0.18, 0.18)
"""The RGB diffusion color. This is the base color of the surface. Defaults to a dark gray."""
emissive_color: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""The RGB emission component of the surface. Defaults to black."""
roughness: float = 0.5
"""The roughness for specular lobe. Ranges from 0 (smooth) to 1 (rough). Defaults to 0.5."""
metallic: float = 0.0
"""The metallic component. Ranges from 0 (dielectric) to 1 (metal). Defaults to 0."""
opacity: float = 1.0
"""The opacity of the surface. Ranges from 0 (transparent) to 1 (opaque). Defaults to 1.
Note:
Opacity only affects the surface's appearance during interactive rendering.
"""
@configclass
class MdlFileCfg(VisualMaterialCfg):
"""Configuration parameters for loading an MDL material from a file.
See :meth:`spawn_from_mdl_file` for more information.
"""
func: Callable = visual_materials.spawn_from_mdl_file
mdl_path: str = MISSING
"""The path to the MDL material.
NVIDIA Omniverse provides various MDL materials in the NVIDIA Nucleus.
To use these materials, you can set the path of the material in the nucleus directory
using the ``{NVIDIA_NUCLEUS_DIR}`` variable. This is internally resolved to the path of the
NVIDIA Nucleus directory on the host machine through the attribute
:attr:`omni.isaac.orbit.utils.assets.NVIDIA_NUCLEUS_DIR`.
For example, to use the "Aluminum_Anodized" material, you can set the path to:
``{NVIDIA_NUCLEUS_DIR}/Materials/Base/Metals/Aluminum_Anodized.mdl``.
"""
project_uvw: bool | None = None
"""Whether to project the UVW coordinates of the material. Defaults to None.
If None, then the default setting in the MDL material will be used.
"""
albedo_brightness: float | None = None
"""Multiplier for the diffuse color of the material. Defaults to None.
If None, then the default setting in the MDL material will be used.
"""
texture_scale: tuple[float, float] | None = None
"""The scale of the texture. Defaults to None.
If None, then the default setting in the MDL material will be used.
"""
@configclass
class GlassMdlCfg(VisualMaterialCfg):
"""Configuration parameters for loading a glass MDL material.
This is a convenience class for loading a glass MDL material. For more information on
glass materials, see the `documentation <https://docs.omniverse.nvidia.com/materials-and-rendering/latest/materials.html#omniglass>`__.
.. note::
The default values are taken from the glass material in the NVIDIA Nucleus.
"""
func: Callable = visual_materials.spawn_from_mdl_file
mdl_path: str = "OmniGlass.mdl"
"""The path to the MDL material. Defaults to the glass material in the NVIDIA Nucleus."""
glass_color: tuple[float, float, float] = (1.0, 1.0, 1.0)
"""The RGB color or tint of the glass. Defaults to white."""
frosting_roughness: float = 0.0
"""The amount of reflectivity of the surface. Ranges from 0 (perfectly clear) to 1 (frosted).
Defaults to 0."""
thin_walled: bool = False
"""Whether to perform thin-walled refraction. Defaults to False."""
glass_ior: float = 1.491
"""The incidence of refraction to control how much light is bent when passing through the glass.
Defaults to 1.491, which is the IOR of glass.
"""
| 4,164 | Python | 36.522522 | 139 | 0.70317 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/materials/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for spawners that spawn USD-based and PhysX-based materials.
`Materials`_ are used to define the appearance and physical properties of objects in the simulation.
In Omniverse, they are defined using NVIDIA's `Material Definition Language (MDL)`_. MDL is based on
the physically-based rendering (PBR) model, which is a set of equations that describe how light
interacts with a surface. The PBR model is used to create realistic-looking materials.
While MDL is primarily used for defining the appearance of objects, it can be extended to define
the physical properties of objects. For example, the friction and restitution coefficients of a
rubber material. A `physics material`_ can be assigned to a physics object to
define its physical properties. There are different kinds of physics materials, such as rigid body
material, deformable material, and fluid material.
In order to apply a material to an object, we "bind" the geometry of the object to the material.
For this, we use the `USD Material Binding API`_. The material binding API takes in the path to
the geometry and the path to the material, and binds them together.
For physics material, the material is bound to the physics object with the 'physics' purpose.
When parsing physics material properties on an object, the following priority is used:
1. Material binding with a 'physics' purpose (physics material)
2. Material binding with no purpose (visual material)
3. Material binding with a 'physics' purpose on the `Physics Scene`_ prim.
4. Default values of material properties inside PhysX.
Usage:
.. code-block:: python
import omni.isaac.core.utils.prims as prim_utils
import omni.isaac.orbit.sim as sim_utils
# create a visual material
visual_material_cfg = sim_utils.GlassMdlCfg(glass_ior=1.0, thin_walled=True)
visual_material_cfg.func("/World/Looks/glassMaterial", visual_material_cfg)
# create a mesh prim
cube_cfg = sim_utils.CubeCfg(size=[1.0, 1.0, 1.0])
cube_cfg.func("/World/Primitives/Cube", cube_cfg)
# bind the cube to the visual material
sim_utils.bind_visual_material("/World/Primitives/Cube", "/World/Looks/glassMaterial")
.. _Material Definition Language (MDL): https://raytracing-docs.nvidia.com/mdl/introduction/index.html#mdl_introduction#
.. _Materials: https://docs.omniverse.nvidia.com/materials-and-rendering/latest/materials.html
.. _physics material: https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/simulation-control/physics-settings.html#physics-materials
.. _USD Material Binding API: https://openusd.org/dev/api/class_usd_shade_material_binding_a_p_i.html
.. _Physics Scene: https://openusd.org/dev/api/usd_physics_page_front.html
"""
from .physics_materials import spawn_rigid_body_material
from .physics_materials_cfg import PhysicsMaterialCfg, RigidBodyMaterialCfg
from .visual_materials import spawn_from_mdl_file, spawn_preview_surface
from .visual_materials_cfg import GlassMdlCfg, MdlFileCfg, PreviewSurfaceCfg, VisualMaterialCfg
| 3,185 | Python | 51.229507 | 144 | 0.767347 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/materials/physics_materials.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import omni.isaac.core.utils.prims as prim_utils
import omni.isaac.core.utils.stage as stage_utils
from pxr import PhysxSchema, Usd, UsdPhysics, UsdShade
from omni.isaac.orbit.sim.utils import clone, safe_set_attribute_on_usd_schema
if TYPE_CHECKING:
from . import physics_materials_cfg
@clone
def spawn_rigid_body_material(prim_path: str, cfg: physics_materials_cfg.RigidBodyMaterialCfg) -> Usd.Prim:
"""Create material with rigid-body physics properties.
Rigid body materials are used to define the physical properties to meshes of a rigid body. These
include the friction, restitution, and their respective combination modes. For more information on
rigid body material, please refer to the `documentation on PxMaterial <https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/_build/physx/latest/class_px_material.html>`_.
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration for the physics material.
Returns:
The spawned rigid body material prim.
Raises:
ValueError: When a prim already exists at the specified prim path and is not a material.
"""
# create material prim if no prim exists
if not prim_utils.is_prim_path_valid(prim_path):
_ = UsdShade.Material.Define(stage_utils.get_current_stage(), prim_path)
# obtain prim
prim = prim_utils.get_prim_at_path(prim_path)
# check if prim is a material
if not prim.IsA(UsdShade.Material):
raise ValueError(f"A prim already exists at path: '{prim_path}' but is not a material.")
# retrieve the USD rigid-body api
usd_physics_material_api = UsdPhysics.MaterialAPI(prim)
if not usd_physics_material_api:
usd_physics_material_api = UsdPhysics.MaterialAPI.Apply(prim)
# retrieve the collision api
physx_material_api = PhysxSchema.PhysxMaterialAPI(prim)
if not physx_material_api:
physx_material_api = PhysxSchema.PhysxMaterialAPI.Apply(prim)
# convert to dict
cfg = cfg.to_dict()
del cfg["func"]
# set into USD API
for attr_name in ["static_friction", "dynamic_friction", "restitution"]:
value = cfg.pop(attr_name, None)
safe_set_attribute_on_usd_schema(usd_physics_material_api, attr_name, value, camel_case=True)
# set into PhysX API
for attr_name, value in cfg.items():
safe_set_attribute_on_usd_schema(physx_material_api, attr_name, value, camel_case=True)
# return the prim
return prim
| 3,080 | Python | 40.635135 | 174 | 0.713312 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/materials/visual_materials.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import omni.isaac.core.utils.prims as prim_utils
import omni.kit.commands
from pxr import Usd
from omni.isaac.orbit.sim.utils import clone, safe_set_attribute_on_usd_prim
from omni.isaac.orbit.utils.assets import NVIDIA_NUCLEUS_DIR
if TYPE_CHECKING:
from . import visual_materials_cfg
@clone
def spawn_preview_surface(prim_path: str, cfg: visual_materials_cfg.PreviewSurfaceCfg) -> Usd.Prim:
"""Create a preview surface prim and override the settings with the given config.
A preview surface is a physically-based surface that handles simple shaders while supporting
both *specular* and *metallic* workflows. All color inputs are in linear color space (RGB).
For more information, see the `documentation <https://openusd.org/release/spec_usdpreviewsurface.html>`__.
The function calls the USD command `CreatePreviewSurfaceMaterialPrim`_ to create the prim.
.. _CreatePreviewSurfaceMaterialPrim: https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd.commands/omni.usd.commands.CreatePreviewSurfaceMaterialPrimCommand.html
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
Returns:
The created prim.
Raises:
ValueError: If a prim already exists at the given path.
"""
# spawn material if it doesn't exist.
if not prim_utils.is_prim_path_valid(prim_path):
omni.kit.commands.execute("CreatePreviewSurfaceMaterialPrim", mtl_path=prim_path, select_new_prim=False)
else:
raise ValueError(f"A prim already exists at path: '{prim_path}'.")
# obtain prim
prim = prim_utils.get_prim_at_path(f"{prim_path}/Shader")
# apply properties
cfg = cfg.to_dict()
del cfg["func"]
for attr_name, attr_value in cfg.items():
safe_set_attribute_on_usd_prim(prim, f"inputs:{attr_name}", attr_value, camel_case=True)
# return prim
return prim
@clone
def spawn_from_mdl_file(prim_path: str, cfg: visual_materials_cfg.MdlMaterialCfg) -> Usd.Prim:
"""Load a material from its MDL file and override the settings with the given config.
NVIDIA's `Material Definition Language (MDL) <https://www.nvidia.com/en-us/design-visualization/technologies/material-definition-language/>`__
is a language for defining physically-based materials. The MDL file format is a binary format
that can be loaded by Omniverse and other applications such as Adobe Substance Designer.
To learn more about MDL, see the `documentation <https://docs.omniverse.nvidia.com/materials-and-rendering/latest/materials.html>`_.
The function calls the USD command `CreateMdlMaterialPrim`_ to create the prim.
.. _CreateMdlMaterialPrim: https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd.commands/omni.usd.commands.CreateMdlMaterialPrimCommand.html
.. note::
This function is decorated with :func:`clone` that resolves prim path into list of paths
if the input prim path is a regex pattern. This is done to support spawning multiple assets
from a single and cloning the USD prim at the given path expression.
Args:
prim_path: The prim path or pattern to spawn the asset at. If the prim path is a regex pattern,
then the asset is spawned at all the matching prim paths.
cfg: The configuration instance.
Returns:
The created prim.
Raises:
ValueError: If a prim already exists at the given path.
"""
# spawn material if it doesn't exist.
if not prim_utils.is_prim_path_valid(prim_path):
# extract material name from path
material_name = cfg.mdl_path.split("/")[-1].split(".")[0]
omni.kit.commands.execute(
"CreateMdlMaterialPrim",
mtl_url=cfg.mdl_path.format(NVIDIA_NUCLEUS_DIR=NVIDIA_NUCLEUS_DIR),
mtl_name=material_name,
mtl_path=prim_path,
select_new_prim=False,
)
else:
raise ValueError(f"A prim already exists at path: '{prim_path}'.")
# obtain prim
prim = prim_utils.get_prim_at_path(f"{prim_path}/Shader")
# apply properties
cfg = cfg.to_dict()
del cfg["func"]
del cfg["mdl_path"]
for attr_name, attr_value in cfg.items():
safe_set_attribute_on_usd_prim(prim, f"inputs:{attr_name}", attr_value, camel_case=False)
# return prim
return prim
| 4,978 | Python | 41.555555 | 181 | 0.702893 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/spawners/materials/physics_materials_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from collections.abc import Callable
from dataclasses import MISSING
from typing import Literal
from omni.isaac.orbit.utils import configclass
from . import physics_materials
@configclass
class PhysicsMaterialCfg:
"""Configuration parameters for creating a physics material.
Physics material are PhysX schemas that can be applied to a USD material prim to define the
physical properties related to the material. For example, the friction coefficient, restitution
coefficient, etc. For more information on physics material, please refer to the
`PhysX documentation <https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/_build/physx/latest/class_px_base_material.html>`_.
"""
func: Callable = MISSING
"""Function to use for creating the material."""
@configclass
class RigidBodyMaterialCfg(PhysicsMaterialCfg):
"""Physics material parameters for rigid bodies.
See :meth:`spawn_rigid_body_material` for more information.
Note:
The default values are the `default values used by PhysX 5
<https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/rigid-bodies.html#rigid-body-materials>`_.
"""
func: Callable = physics_materials.spawn_rigid_body_material
static_friction: float = 0.5
"""The static friction coefficient. Defaults to 0.5."""
dynamic_friction: float = 0.5
"""The dynamic friction coefficient. Defaults to 0.5."""
restitution: float = 0.0
"""The restitution coefficient. Defaults to 0.0."""
improve_patch_friction: bool = True
"""Whether to enable patch friction. Defaults to True."""
friction_combine_mode: Literal["average", "min", "multiply", "max"] = "average"
"""Determines the way friction will be combined during collisions. Defaults to `"average"`.
.. attention::
When two physics materials with different combine modes collide, the combine mode with the higher
priority will be used. The priority order is provided `here
<https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/_build/physx/latest/struct_px_combine_mode.html#pxcombinemode>`_.
"""
restitution_combine_mode: Literal["average", "min", "multiply", "max"] = "average"
"""Determines the way restitution coefficient will be combined during collisions. Defaults to `"average"`.
.. attention::
When two physics materials with different combine modes collide, the combine mode with the higher
priority will be used. The priority order is provided `here
<https://nvidia-omniverse.github.io/PhysX/physx/5.2.1/_build/physx/latest/struct_px_combine_mode.html#pxcombinemode>`_.
"""
compliant_contact_stiffness: float = 0.0
"""Spring stiffness for a compliant contact model using implicit springs. Defaults to 0.0.
A higher stiffness results in behavior closer to a rigid contact. The compliant contact model is only enabled
if the stiffness is larger than 0.
"""
compliant_contact_damping: float = 0.0
"""Damping coefficient for a compliant contact model using implicit springs. Defaults to 0.0.
Irrelevant if compliant contacts are disabled when :obj:`compliant_contact_stiffness` is set to zero and
rigid contacts are active.
"""
| 3,373 | Python | 37.781609 | 130 | 0.723095 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/converters/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing converters for converting various file types to USD.
In order to support direct loading of various file types into Omniverse, we provide a set of
converters that can convert the file into a USD file. The converters are implemented as
sub-classes of the :class:`AssetConverterBase` class.
The following converters are currently supported:
* :class:`UrdfConverter`: Converts a URDF file into a USD file.
* :class:`MeshConverter`: Converts a mesh file into a USD file. This supports OBJ, STL and FBX files.
"""
from .asset_converter_base import AssetConverterBase
from .asset_converter_base_cfg import AssetConverterBaseCfg
from .mesh_converter import MeshConverter
from .mesh_converter_cfg import MeshConverterCfg
from .urdf_converter import UrdfConverter
from .urdf_converter_cfg import UrdfConverterCfg
| 956 | Python | 37.279999 | 101 | 0.799163 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/converters/asset_converter_base_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from omni.isaac.orbit.utils import configclass
@configclass
class AssetConverterBaseCfg:
"""The base configuration class for asset converters."""
asset_path: str = MISSING
"""The absolute path to the asset file to convert into USD."""
usd_dir: str | None = None
"""The output directory path to store the generated USD file. Defaults to None.
If None, it is resolved as ``/tmp/Orbit/usd_{date}_{time}_{random}``, where
the parameters in braces are runtime generated.
"""
usd_file_name: str | None = None
"""The name of the generated usd file. Defaults to None.
If None, it is resolved from the asset file name. For example, if the asset file
name is ``"my_asset.urdf"``, then the generated USD file name is ``"my_asset.usd"``.
If the providing file name does not end with ".usd" or ".usda", then the extension
".usd" is appended to the file name.
"""
force_usd_conversion: bool = False
"""Force the conversion of the asset file to usd. Defaults to False.
If True, then the USD file is always generated. It will overwrite the existing USD file if it exists.
"""
make_instanceable: bool = True
"""Make the generated USD file instanceable. Defaults to True.
Note:
Instancing helps reduce the memory footprint of the asset when multiple copies of the asset are
used in the scene. For more information, please check the USD documentation on
`scene-graph instancing <https://openusd.org/dev/api/_usd__page__scenegraph_instancing.html>`_.
"""
| 1,719 | Python | 34.10204 | 105 | 0.694008 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/converters/asset_converter_base.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import abc
import hashlib
import json
import os
import pathlib
import random
from datetime import datetime
from omni.isaac.orbit.sim.converters.asset_converter_base_cfg import AssetConverterBaseCfg
from omni.isaac.orbit.utils.assets import check_file_path
from omni.isaac.orbit.utils.io import dump_yaml
class AssetConverterBase(abc.ABC):
"""Base class for converting an asset file from different formats into USD format.
This class provides a common interface for converting an asset file into USD. It does not
provide any implementation for the conversion. The derived classes must implement the
:meth:`_convert_asset` method to provide the actual conversion.
The file conversion is lazy if the output directory (:obj:`AssetConverterBaseCfg.usd_dir`) is provided.
In the lazy conversion, the USD file is re-generated only if:
* The asset file is modified.
* The configuration parameters are modified.
* The USD file does not exist.
To override this behavior to force conversion, the flag :obj:`AssetConverterBaseCfg.force_usd_conversion`
can be set to True.
When no output directory is defined, lazy conversion is deactivated and the generated USD file is
stored in folder ``/tmp/Orbit/usd_{date}_{time}_{random}``, where the parameters in braces are generated
at runtime. The random identifiers help avoid a race condition where two simultaneously triggered conversions
try to use the same directory for reading/writing the generated files.
.. note::
Changes to the parameters :obj:`AssetConverterBaseCfg.asset_path`, :obj:`AssetConverterBaseCfg.usd_dir`, and
:obj:`AssetConverterBaseCfg.usd_file_name` are not considered as modifications in the configuration instance that
trigger USD file re-generation.
"""
def __init__(self, cfg: AssetConverterBaseCfg):
"""Initializes the class.
Args:
cfg: The configuration instance for converting an asset file to USD format.
Raises:
ValueError: When provided asset file does not exist.
"""
# check if the asset file exists
if not check_file_path(cfg.asset_path):
raise ValueError(f"The asset path does not exist: {cfg.asset_path}")
# save the inputs
self.cfg = cfg
# resolve USD directory name
if cfg.usd_dir is None:
# a folder in "/tmp/Orbit" by the name: usd_{date}_{time}_{random}
time_tag = datetime.now().strftime("%Y%m%d_%H%M%S")
self._usd_dir = f"/tmp/Orbit/usd_{time_tag}_{random.randrange(10000)}"
else:
self._usd_dir = cfg.usd_dir
# resolve the file name from asset file name if not provided
if cfg.usd_file_name is None:
usd_file_name = pathlib.PurePath(cfg.asset_path).stem
else:
usd_file_name = cfg.usd_file_name
# add USD extension if not provided
if not (usd_file_name.endswith(".usd") or usd_file_name.endswith(".usda")):
self._usd_file_name = usd_file_name + ".usd"
else:
self._usd_file_name = usd_file_name
# create the USD directory
os.makedirs(self.usd_dir, exist_ok=True)
# check if usd files exist
self._usd_file_exists = os.path.isfile(self.usd_path)
# path to read/write asset hash file
self._dest_hash_path = os.path.join(self.usd_dir, ".asset_hash")
# create asset hash to check if the asset has changed
self._asset_hash = self._config_to_hash(cfg)
# read the saved hash
try:
with open(self._dest_hash_path) as f:
existing_asset_hash = f.readline()
self._is_same_asset = existing_asset_hash == self._asset_hash
except FileNotFoundError:
self._is_same_asset = False
# convert the asset to USD if the hash is different or USD file does not exist
if cfg.force_usd_conversion or not self._usd_file_exists or not self._is_same_asset:
# write the updated hash
with open(self._dest_hash_path, "w") as f:
f.write(self._asset_hash)
# convert the asset to USD
self._convert_asset(cfg)
# dump the configuration to a file
dump_yaml(os.path.join(self.usd_dir, "config.yaml"), cfg.to_dict())
# add comment to top of the saved config file with information about the converter
current_date = datetime.now().strftime("%Y-%m-%d")
current_time = datetime.now().strftime("%H:%M:%S")
generation_comment = (
f"##\n# Generated by {self.__class__.__name__} on {current_date} at {current_time}.\n##\n"
)
with open(os.path.join(self.usd_dir, "config.yaml"), "a") as f:
f.write(generation_comment)
"""
Properties.
"""
@property
def usd_dir(self) -> str:
"""The absolute path to the directory where the generated USD files are stored."""
return self._usd_dir
@property
def usd_file_name(self) -> str:
"""The file name of the generated USD file."""
return self._usd_file_name
@property
def usd_path(self) -> str:
"""The absolute path to the generated USD file."""
return os.path.join(self.usd_dir, self.usd_file_name)
@property
def usd_instanceable_meshes_path(self) -> str:
"""The relative path to the USD file with meshes.
The path is with respect to the USD directory :attr:`usd_dir`. This is to ensure that the
mesh references in the generated USD file are resolved relatively. Otherwise, it becomes
difficult to move the USD asset to a different location.
"""
return os.path.join(".", "Props", "instanceable_meshes.usd")
"""
Implementation specifics.
"""
@abc.abstractmethod
def _convert_asset(self, cfg: AssetConverterBaseCfg):
"""Converts the asset file to USD.
Args:
cfg: The configuration instance for the input asset to USD conversion.
"""
raise NotImplementedError()
"""
Private helpers.
"""
@staticmethod
def _config_to_hash(cfg: AssetConverterBaseCfg) -> str:
"""Converts the configuration object and asset file to an MD5 hash of a string.
.. warning::
It only checks the main asset file (:attr:`cfg.asset_path`).
Args:
config : The asset converter configuration object.
Returns:
An MD5 hash of a string.
"""
# convert to dict and remove path related info
config_dic = cfg.to_dict()
_ = config_dic.pop("asset_path")
_ = config_dic.pop("usd_dir")
_ = config_dic.pop("usd_file_name")
# convert config dic to bytes
config_bytes = json.dumps(config_dic).encode()
# hash config
md5 = hashlib.md5()
md5.update(config_bytes)
# read the asset file to observe changes
with open(cfg.asset_path, "rb") as f:
while True:
# read 64kb chunks to avoid memory issues for the large files!
data = f.read(65536)
if not data:
break
md5.update(data)
# return the hash
return md5.hexdigest()
| 7,505 | Python | 37.101523 | 121 | 0.62545 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/converters/mesh_converter_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.sim.converters.asset_converter_base_cfg import AssetConverterBaseCfg
from omni.isaac.orbit.sim.schemas import schemas_cfg
from omni.isaac.orbit.utils import configclass
@configclass
class MeshConverterCfg(AssetConverterBaseCfg):
"""The configuration class for MeshConverter."""
mass_props: schemas_cfg.MassPropertiesCfg = None
"""Mass properties to apply to the USD. Defaults to None.
Note:
If None, then no mass properties will be added.
"""
rigid_props: schemas_cfg.RigidBodyPropertiesCfg = None
"""Rigid body properties to apply to the USD. Defaults to None.
Note:
If None, then no rigid body properties will be added.
"""
collision_props: schemas_cfg.CollisionPropertiesCfg = None
"""Collision properties to apply to the USD. Defaults to None.
Note:
If None, then no collision properties will be added.
"""
collision_approximation: str = "convexDecomposition"
"""Collision approximation method to use. Defaults to "convexDecomposition".
Valid options are:
"convexDecomposition", "convexHull", "boundingCube",
"boundingSphere", "meshSimplification", or "none"
"none" causes no collision mesh to be added.
"""
| 1,372 | Python | 29.51111 | 90 | 0.718659 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/converters/mesh_converter.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import asyncio
import os
import omni
import omni.kit.commands
import omni.usd
from omni.isaac.core.utils.extensions import enable_extension
from pxr import Gf, Usd, UsdGeom, UsdPhysics, UsdUtils
from omni.isaac.orbit.sim.converters.asset_converter_base import AssetConverterBase
from omni.isaac.orbit.sim.converters.mesh_converter_cfg import MeshConverterCfg
from omni.isaac.orbit.sim.schemas import schemas
from omni.isaac.orbit.sim.utils import export_prim_to_file
class MeshConverter(AssetConverterBase):
"""Converter for a mesh file in OBJ / STL / FBX format to a USD file.
This class wraps around the `omni.kit.asset_converter`_ extension to provide a lazy implementation
for mesh to USD conversion. It stores the output USD file in an instanceable format since that is
what is typically used in all learning related applications.
To make the asset instanceable, we must follow a certain structure dictated by how USD scene-graph
instancing and physics work. The rigid body component must be added to each instance and not the
referenced asset (i.e. the prototype prim itself). This is because the rigid body component defines
properties that are specific to each instance and cannot be shared under the referenced asset. For
more information, please check the `documentation <https://docs.omniverse.nvidia.com/extensions/latest/ext_physics/rigid-bodies.html#instancing-rigid-bodies>`_.
Due to the above, we follow the following structure:
* ``{prim_path}`` - The root prim that is an Xform with the rigid body and mass APIs if configured.
* ``{prim_path}/geometry`` - The prim that contains the mesh and optionally the materials if configured.
If instancing is enabled, this prim will be an instanceable reference to the prototype prim.
.. _omni.kit.asset_converter: https://docs.omniverse.nvidia.com/extensions/latest/ext_asset-converter.html
.. caution::
When converting STL files, Z-up convention is assumed, even though this is not the default for many CAD
export programs. Asset orientation convention can either be modified directly in the CAD program's export
process or an offset can be added within the config in Orbit.
"""
cfg: MeshConverterCfg
"""The configuration instance for mesh to USD conversion."""
def __init__(self, cfg: MeshConverterCfg):
"""Initializes the class.
Args:
cfg: The configuration instance for mesh to USD conversion.
"""
super().__init__(cfg=cfg)
"""
Implementation specific methods.
"""
def _convert_asset(self, cfg: MeshConverterCfg):
"""Generate USD from OBJ, STL or FBX.
It stores the asset in the following format:
/file_name (default prim)
|- /geometry <- Made instanceable if requested
|- /Looks
|- /mesh
Args:
cfg: The configuration for conversion of mesh to USD.
Raises:
RuntimeError: If the conversion using the Omniverse asset converter fails.
"""
# resolve mesh name and format
mesh_file_basename, mesh_file_format = os.path.basename(cfg.asset_path).split(".")
mesh_file_format = mesh_file_format.lower()
# Convert USD
status = asyncio.get_event_loop().run_until_complete(
self._convert_mesh_to_usd(in_file=cfg.asset_path, out_file=self.usd_path)
)
if not status:
raise RuntimeError(f"Failed to convert asset: {cfg.asset_path}! Please check the logs for more details.")
# Open converted USD stage
# note: This opens a new stage and does not use the stage created earlier by the user
# create a new stage
stage = Usd.Stage.Open(self.usd_path)
# add USD to stage cache
stage_id = UsdUtils.StageCache.Get().Insert(stage)
# need to make kwargs for compatibility with 2023
stage_kwargs = {"stage": stage}
stage_or_context_kwargs = {"stage_or_context": stage}
# FIXME: we need to hack this into command because Kit 105 has a bug.
from omni.usd.commands import MovePrimCommand
MovePrimCommand._selection = None # type: ignore
# Set stage up-axis to Z
# note: later we need to rotate the mesh so that it is Z-up in the world
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
# Move all meshes to underneath a new Xform so that we can make it instanceable later if requested
# Get the default prim (which is the root prim) -- "/World"
old_xform_prim = stage.GetDefaultPrim()
# Create a path called "/{mesh_file_basename}/geometry" and move the mesh to it
new_xform_prim = stage.DefinePrim(f"/{mesh_file_basename}", "Xform")
geom_undef_prim = stage.DefinePrim(f"{new_xform_prim.GetPath()}/geometry")
# Move Looks to underneath new Xform
omni.kit.commands.execute(
"MovePrim",
path_from=f"{old_xform_prim.GetPath()}/Looks",
path_to=f"{geom_undef_prim.GetPath()}/Looks",
destructive=True,
**stage_or_context_kwargs,
)
# Move all meshes to underneath new Xform
for child_mesh_prim in old_xform_prim.GetChildren():
# Get mesh prim path
old_child_mesh_prim_path = child_mesh_prim.GetPath().pathString
new_child_mesh_prim_path = f"{geom_undef_prim.GetPath()}/{old_child_mesh_prim_path.split('/')[-1]}"
# Move mesh to underneath new Xform
omni.kit.commands.execute(
"MovePrim",
path_from=old_child_mesh_prim_path,
path_to=new_child_mesh_prim_path,
destructive=True,
**stage_or_context_kwargs,
)
# Apply default Xform rotation to mesh
omni.kit.commands.execute(
"CreateDefaultXformOnPrimCommand",
prim_path=new_child_mesh_prim_path,
**stage_kwargs,
)
# Get new mesh prim
child_mesh_prim = stage.GetPrimAtPath(new_child_mesh_prim_path)
# Rotate mesh so that it is Z-up in the world
attr_rotate = child_mesh_prim.GetAttribute("xformOp:orient")
attr_rotate.Set(Gf.Quatd(0.5, 0.5, 0.5, 0.5))
# Apply collider properties to mesh
if cfg.collision_props is not None:
# -- Collision approximation to mesh
# TODO: https://github.com/isaac-orbit/orbit/issues/163 Move this to a new Schema
mesh_collision_api = UsdPhysics.MeshCollisionAPI.Apply(child_mesh_prim)
mesh_collision_api.GetApproximationAttr().Set(cfg.collision_approximation)
# -- Collider properties such as offset, scale, etc.
schemas.define_collision_properties(
prim_path=child_mesh_prim.GetPath(), cfg=cfg.collision_props, stage=stage
)
# Delete the old Xform and make the new Xform the default prim
stage.SetDefaultPrim(new_xform_prim)
omni.kit.commands.execute("DeletePrims", paths=[old_xform_prim.GetPath().pathString], stage=stage)
# Handle instanceable
# Create a new Xform prim that will be the prototype prim
if cfg.make_instanceable:
# Export Xform to a file so we can reference it from all instances
export_prim_to_file(
path=os.path.join(self.usd_dir, self.usd_instanceable_meshes_path),
source_prim_path=geom_undef_prim.GetPath(),
stage=stage,
)
# Delete the original prim that will now be a reference
geom_undef_prim_path = geom_undef_prim.GetPath().pathString
omni.kit.commands.execute("DeletePrims", paths=[geom_undef_prim_path], stage=stage)
# Update references to exported Xform and make it instanceable
geom_undef_prim = stage.DefinePrim(geom_undef_prim_path)
geom_undef_prim.GetReferences().AddReference(
self.usd_instanceable_meshes_path, primPath=geom_undef_prim_path
)
geom_undef_prim.SetInstanceable(True)
# Apply mass and rigid body properties after everything else
# Properties are applied to the top level prim to avoid the case where all instances of this
# asset unintentionally share the same rigid body properties
# apply mass properties
if cfg.mass_props is not None:
schemas.define_mass_properties(prim_path=new_xform_prim.GetPath(), cfg=cfg.mass_props, stage=stage)
# apply rigid body properties
if cfg.rigid_props is not None:
schemas.define_rigid_body_properties(prim_path=new_xform_prim.GetPath(), cfg=cfg.rigid_props, stage=stage)
# Save changes to USD stage
stage.Save()
if stage_id is not None:
UsdUtils.StageCache.Get().Erase(stage_id)
"""
Helper methods.
"""
@staticmethod
async def _convert_mesh_to_usd(in_file: str, out_file: str, load_materials: bool = True) -> bool:
"""Convert mesh from supported file types to USD.
This function uses the Omniverse Asset Converter extension to convert a mesh file to USD.
It is an asynchronous function and should be called using `asyncio.get_event_loop().run_until_complete()`.
The converted asset is stored in the USD format in the specified output file.
The USD file has Y-up axis and is scaled to meters.
The asset hierarchy is arranged as follows:
.. code-block:: none
/World (default prim)
|- /Looks
|- /Mesh
Args:
in_file: The file to convert.
out_file: The path to store the output file.
load_materials: Set to True to enable attaching materials defined in the input file
to the generated USD mesh. Defaults to True.
Returns:
True if the conversion succeeds.
"""
enable_extension("omni.kit.asset_converter")
enable_extension("omni.isaac.unit_converter")
import omni.kit.asset_converter
from omni.isaac.unit_converter.unit_conversion_utils import set_stage_meters_per_unit
# Create converter context
converter_context = omni.kit.asset_converter.AssetConverterContext()
# Set up converter settings
# Don't import/export materials
converter_context.ignore_materials = not load_materials
converter_context.ignore_animations = True
converter_context.ignore_camera = True
converter_context.ignore_light = True
# Merge all meshes into one
converter_context.merge_all_meshes = True
# Sets world units to meters, this will also scale asset if it's centimeters model.
# This does not work right now :(, so we need to scale the mesh manually
converter_context.use_meter_as_world_unit = True
converter_context.baking_scales = True
# Uses double precision for all transform ops.
converter_context.use_double_precision_to_usd_transform_op = True
# Create converter task
instance = omni.kit.asset_converter.get_instance()
task = instance.create_converter_task(in_file, out_file, None, converter_context)
# Start conversion task and wait for it to finish
success = True
while True:
success = await task.wait_until_finished()
if not success:
await asyncio.sleep(0.1)
else:
break
# Open converted USD stage
stage = Usd.Stage.Open(out_file)
# Set stage units to 1.0
set_stage_meters_per_unit(stage, 1.0)
# Save changes to USD stage
stage.Save()
return success
| 12,049 | Python | 44.131086 | 164 | 0.646693 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/converters/urdf_converter.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import os
import omni.kit.commands
import omni.usd
from omni.isaac.core.utils.extensions import enable_extension
from pxr import Usd
from .asset_converter_base import AssetConverterBase
from .urdf_converter_cfg import UrdfConverterCfg
_DRIVE_TYPE = {
"none": 0,
"position": 1,
"velocity": 2,
}
"""Mapping from drive type name to URDF importer drive number."""
_NORMALS_DIVISION = {
"catmullClark": 0,
"loop": 1,
"bilinear": 2,
"none": 3,
}
"""Mapping from normals division name to urdf importer normals division number."""
class UrdfConverter(AssetConverterBase):
"""Converter for a URDF description file to a USD file.
This class wraps around the `omni.isaac.urdf_importer`_ extension to provide a lazy implementation
for URDF to USD conversion. It stores the output USD file in an instanceable format since that is
what is typically used in all learning related applications.
.. caution::
The current lazy conversion implementation does not automatically trigger USD generation if
only the mesh files used by the URDF are modified. To force generation, either set
:obj:`AssetConverterBaseCfg.force_usd_conversion` to True or delete the output directory.
.. note::
From Isaac Sim 2023.1 onwards, the extension name changed from ``omni.isaac.urdf`` to
``omni.importer.urdf``. This converter class automatically detects the version of Isaac Sim
and uses the appropriate extension.
The new extension supports a custom XML tag``"dont_collapse"`` for joints. Setting this parameter
to true in the URDF joint tag prevents the child link from collapsing when the associated joint type
is "fixed".
.. _omni.isaac.urdf_importer: https://docs.omniverse.nvidia.com/isaacsim/latest/ext_omni_isaac_urdf.html
"""
cfg: UrdfConverterCfg
"""The configuration instance for URDF to USD conversion."""
def __init__(self, cfg: UrdfConverterCfg):
"""Initializes the class.
Args:
cfg: The configuration instance for URDF to USD conversion.
"""
super().__init__(cfg=cfg)
"""
Implementation specific methods.
"""
def _convert_asset(self, cfg: UrdfConverterCfg):
"""Calls underlying Omniverse command to convert URDF to USD.
Args:
cfg: The URDF conversion configuration.
"""
import_config = self._get_urdf_import_config(cfg)
omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=cfg.asset_path,
import_config=import_config,
dest_path=self.usd_path,
)
# fix the issue that material paths are not relative
if self.cfg.make_instanceable:
instanced_usd_path = os.path.join(self.usd_dir, self.usd_instanceable_meshes_path)
stage = Usd.Stage.Open(instanced_usd_path)
# resolve all paths relative to layer path
source_layer = stage.GetRootLayer()
omni.usd.resolve_paths(source_layer.identifier, source_layer.identifier)
stage.Save()
# fix the issue that material paths are not relative
# note: This issue seems to have popped up in Isaac Sim 2023.1.1
stage = Usd.Stage.Open(self.usd_path)
# resolve all paths relative to layer path
source_layer = stage.GetRootLayer()
omni.usd.resolve_paths(source_layer.identifier, source_layer.identifier)
stage.Save()
"""
Helper methods.
"""
def _get_urdf_import_config(self, cfg: UrdfConverterCfg) -> omni.importer.urdf.ImportConfig:
"""Create and fill URDF ImportConfig with desired settings
Args:
cfg: The URDF conversion configuration.
Returns:
The constructed ``ImportConfig`` object containing the desired settings.
"""
# Enable urdf extension
enable_extension("omni.importer.urdf")
from omni.importer.urdf import _urdf as omni_urdf
import_config = omni_urdf.ImportConfig()
# set the unit scaling factor, 1.0 means meters, 100.0 means cm
import_config.set_distance_scale(1.0)
# set imported robot as default prim
import_config.set_make_default_prim(True)
# add a physics scene to the stage on import if none exists
import_config.set_create_physics_scene(False)
# -- instancing settings
# meshes will be placed in a separate usd file
import_config.set_make_instanceable(cfg.make_instanceable)
import_config.set_instanceable_usd_path(self.usd_instanceable_meshes_path)
# -- asset settings
# default density used for links, use 0 to auto-compute
import_config.set_density(cfg.link_density)
# import inertia tensor from urdf, if it is not specified in urdf it will import as identity
import_config.set_import_inertia_tensor(cfg.import_inertia_tensor)
# decompose a convex mesh into smaller pieces for a closer fit
import_config.set_convex_decomp(cfg.convex_decompose_mesh)
import_config.set_subdivision_scheme(_NORMALS_DIVISION["bilinear"])
# -- physics settings
# create fix joint for base link
import_config.set_fix_base(cfg.fix_base)
# consolidating links that are connected by fixed joints
import_config.set_merge_fixed_joints(cfg.merge_fixed_joints)
# self collisions between links in the articulation
import_config.set_self_collision(cfg.self_collision)
# default drive type used for joints
import_config.set_default_drive_type(_DRIVE_TYPE[cfg.default_drive_type])
# default proportional gains
import_config.set_default_drive_strength(cfg.default_drive_stiffness)
# default derivative gains
import_config.set_default_position_drive_damping(cfg.default_drive_damping)
return import_config
| 6,114 | Python | 37.21875 | 108 | 0.67599 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/sim/converters/urdf_converter_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from typing import Literal
from omni.isaac.orbit.sim.converters.asset_converter_base_cfg import AssetConverterBaseCfg
from omni.isaac.orbit.utils import configclass
@configclass
class UrdfConverterCfg(AssetConverterBaseCfg):
"""The configuration class for UrdfConverter."""
link_density = 0.0
"""Default density used for links. Defaults to 0.
This setting is only effective if ``"inertial"`` properties are missing in the URDF.
"""
import_inertia_tensor: bool = True
"""Import the inertia tensor from urdf. Defaults to True.
If the ``"inertial"`` tag is missing, then it is imported as an identity.
"""
convex_decompose_mesh = False
"""Decompose a convex mesh into smaller pieces for a closer fit. Defaults to False."""
fix_base: bool = MISSING
"""Create a fix joint to the root/base link. Defaults to True."""
merge_fixed_joints: bool = False
"""Consolidate links that are connected by fixed joints. Defaults to False."""
self_collision: bool = False
"""Activate self-collisions between links of the articulation. Defaults to False."""
default_drive_type: Literal["none", "position", "velocity"] = "none"
"""The drive type used for joints. Defaults to ``"none"``.
The drive type dictates the loaded joint PD gains and USD attributes for joint control:
* ``"none"``: The joint stiffness and damping are set to 0.0.
* ``"position"``: The joint stiff and damping are set based on the URDF file or provided configuration.
* ``"velocity"``: The joint stiff is set to zero and damping is based on the URDF file or provided configuration.
"""
default_drive_stiffness: float = 0.0
"""The default stiffness of the joint drive. Defaults to 0.0."""
default_drive_damping: float = 0.0
"""The default damping of the joint drive. Defaults to 0.0.
Note:
If set to zero, the values parsed from the URDF joint tag ``"<dynamics><damping>"`` are used.
Otherwise, it is overridden by the configured value.
"""
| 2,199 | Python | 35.065573 | 117 | 0.698499 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/app/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package containing app-specific functionalities.
These include:
* Ability to launch the simulation app with different configurations
* Run tests with the simulation app
"""
from .app_launcher import AppLauncher # noqa: F401, F403
from .runners import run_tests # noqa: F401, F403
| 416 | Python | 23.52941 | 68 | 0.759615 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/app/app_launcher.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package with the utility class to configure the :class:`omni.isaac.kit.SimulationApp`.
The :class:`AppLauncher` parses environment variables and input CLI arguments to launch the simulator in
various different modes. This includes with or without GUI and switching between different Omniverse remote
clients. Some of these require the extensions to be loaded in a specific order, otherwise a segmentation
fault occurs. The launched :class:`omni.isaac.kit.SimulationApp` instance is accessible via the
:attr:`AppLauncher.app` property.
"""
import argparse
import faulthandler
import os
import re
import signal
import sys
from typing import Any, Literal
from omni.isaac.kit import SimulationApp
class AppLauncher:
"""A utility class to launch Isaac Sim application based on command-line arguments and environment variables.
The class resolves the simulation app settings that appear through environments variables,
command-line arguments (CLI) or as input keyword arguments. Based on these settings, it launches the
simulation app and configures the extensions to load (as a part of post-launch setup).
The input arguments provided to the class are given higher priority than the values set
from the corresponding environment variables. This provides flexibility to deal with different
users' preferences.
.. note::
Explicitly defined arguments are only given priority when their value is set to something outside
their default configuration. For example, the ``livestream`` argument is -1 by default. It only
overrides the ``LIVESTREAM`` environment variable when ``livestream`` argument is set to a
value >-1. In other words, if ``livestream=-1``, then the value from the environment variable
``LIVESTREAM`` is used.
"""
def __init__(self, launcher_args: argparse.Namespace | dict | None = None, **kwargs):
"""Create a `SimulationApp`_ instance based on the input settings.
Args:
launcher_args: Input arguments to parse using the AppLauncher and set into the SimulationApp.
Defaults to None, which is equivalent to passing an empty dictionary. A detailed description of
the possible arguments is available in the `SimulationApp`_ documentation.
**kwargs : Additional keyword arguments that will be merged into :attr:`launcher_args`.
They serve as a convenience for those who want to pass some arguments using the argparse
interface and others directly into the AppLauncher. Duplicated arguments with
the :attr:`launcher_args` will raise a ValueError.
Raises:
ValueError: If there are common/duplicated arguments between ``launcher_args`` and ``kwargs``.
ValueError: If combination of ``launcher_args`` and ``kwargs`` are missing the necessary arguments
that are needed by the AppLauncher to resolve the desired app configuration.
ValueError: If incompatible or undefined values are assigned to relevant environment values,
such as ``LIVESTREAM``.
.. _argparse.Namespace: https://docs.python.org/3/library/argparse.html?highlight=namespace#argparse.Namespace
.. _SimulationApp: https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.kit/docs/index.html
"""
# Enable call-stack on crash
faulthandler.enable()
# We allow users to pass either a dict or an argparse.Namespace into
# __init__, anticipating that these will be all of the argparse arguments
# used by the calling script. Those which we appended via add_app_launcher_args
# will be used to control extension loading logic. Additional arguments are allowed,
# and will be passed directly to the SimulationApp initialization.
#
# We could potentially require users to enter each argument they want passed here
# as a kwarg, but this would require them to pass livestream, headless, and
# any other options we choose to add here explicitly, and with the correct keywords.
#
# @hunter: I feel that this is cumbersome and could introduce error, and would prefer to do
# some sanity checking in the add_app_launcher_args function
if launcher_args is None:
launcher_args = {}
elif isinstance(launcher_args, argparse.Namespace):
launcher_args = launcher_args.__dict__
# Check that arguments are unique
if len(kwargs) > 0:
if not set(kwargs.keys()).isdisjoint(launcher_args.keys()):
overlapping_args = set(kwargs.keys()).intersection(launcher_args.keys())
raise ValueError(
f"Input `launcher_args` and `kwargs` both provided common attributes: {overlapping_args}."
" Please ensure that each argument is supplied to only one of them, as the AppLauncher cannot"
" discern priority between them."
)
launcher_args.update(kwargs)
# Define config members that are read from env-vars or keyword args
self._headless: bool # 0: GUI, 1: Headless
self._livestream: Literal[0, 1, 2, 3] # 0: Disabled, 1: Native, 2: Websocket, 3: WebRTC
self._offscreen_render: bool # 0: Disabled, 1: Enabled
self._sim_experience_file: str # Experience file to load
# Integrate env-vars and input keyword args into simulation app config
self._config_resolution(launcher_args)
# Create SimulationApp, passing the resolved self._config to it for initialization
self._create_app()
# Load IsaacSim extensions
self._load_extensions()
# Hide the stop button in the toolbar
self._hide_stop_button()
# Set up signal handlers for graceful shutdown
# -- during interrupts
signal.signal(signal.SIGINT, self._interrupt_signal_handle_callback)
# -- during explicit `kill` commands
signal.signal(signal.SIGTERM, self._abort_signal_handle_callback)
# -- during segfaults
signal.signal(signal.SIGABRT, self._abort_signal_handle_callback)
signal.signal(signal.SIGSEGV, self._abort_signal_handle_callback)
"""
Properties.
"""
@property
def app(self) -> SimulationApp:
"""The launched SimulationApp."""
if self._app is not None:
return self._app
else:
raise RuntimeError("The `AppLauncher.app` member cannot be retrieved until the class is initialized.")
"""
Operations.
"""
@staticmethod
def add_app_launcher_args(parser: argparse.ArgumentParser) -> None:
"""Utility function to configure AppLauncher arguments with an existing argument parser object.
This function takes an ``argparse.ArgumentParser`` object and does some sanity checking on the existing
arguments for ingestion by the SimulationApp. It then appends custom command-line arguments relevant
to the SimulationApp to the input :class:`argparse.ArgumentParser` instance. This allows overriding the
environment variables using command-line arguments.
Currently, it adds the following parameters to the argparser object:
* ``headless`` (bool): If True, the app will be launched in headless (no-gui) mode. The values map the same
as that for the ``HEADLESS`` environment variable. If False, then headless mode is determined by the
``HEADLESS`` environment variable.
* ``livestream`` (int): If one of {0, 1, 2, 3}, then livestreaming and headless mode is enabled. The values
map the same as that for the ``LIVESTREAM`` environment variable. If :obj:`-1`, then livestreaming is
determined by the ``LIVESTREAM`` environment variable.
* ``offscreen_render`` (bool): If True, the app will be launched in offscreen-render mode. The values
map the same as that for the ``OFFSCREEN_RENDER`` environment variable. If False, then offscreen-render
mode is determined by the ``OFFSCREEN_RENDER`` environment variable.
* ``experience`` (str): The experience file to load when launching the SimulationApp. If a relative path
is provided, it is resolved relative to the ``apps`` folder in Isaac Sim and Orbit (in that order).
If provided as an empty string, the experience file is determined based on the headless flag:
* If headless is True, the experience file is set to ``orbit.python.headless.kit``.
* If headless is False, the experience file is set to ``orbit.python.kit``.
Args:
parser: An argument parser instance to be extended with the AppLauncher specific options.
"""
# If the passed parser has an existing _HelpAction when passed,
# we here remove the options which would invoke it,
# to be added back after the additional AppLauncher args
# have been added. This is equivalent to
# initially constructing the ArgParser with add_help=False,
# but this means we don't have to require that behavior
# in users and can handle it on our end.
# We do this because calling parse_known_args() will handle
# any -h/--help options being passed and then exit immediately,
# before the additional arguments can be added to the help readout.
parser_help = None
if len(parser._actions) > 0 and isinstance(parser._actions[0], argparse._HelpAction): # type: ignore
parser_help = parser._actions[0]
parser._option_string_actions.pop("-h")
parser._option_string_actions.pop("--help")
# Parse known args for potential name collisions/type mismatches
# between the config fields SimulationApp expects and the ArgParse
# arguments that the user passed.
known, _ = parser.parse_known_args()
config = vars(known)
if len(config) == 0:
print(
"[WARN][AppLauncher]: There are no arguments attached to the ArgumentParser object."
" If you have your own arguments, please load your own arguments before calling the"
" `AppLauncher.add_app_launcher_args` method. This allows the method to check the validity"
" of the arguments and perform checks for argument names."
)
else:
AppLauncher._check_argparser_config_params(config)
# Add custom arguments to the parser
arg_group = parser.add_argument_group(
"app_launcher arguments",
description="Arguments for the AppLauncher. For more details, please check the documentation.",
)
arg_group.add_argument(
"--headless",
action="store_true",
default=AppLauncher._APPLAUNCHER_CFG_INFO["headless"][1],
help="Force display off at all times.",
)
arg_group.add_argument(
"--livestream",
type=int,
default=AppLauncher._APPLAUNCHER_CFG_INFO["livestream"][1],
choices={0, 1, 2, 3},
help="Force enable livestreaming. Mapping corresponds to that for the `LIVESTREAM` environment variable.",
)
arg_group.add_argument(
"--offscreen_render",
action="store_true",
default=AppLauncher._APPLAUNCHER_CFG_INFO["offscreen_render"][1],
help="Enable offscreen rendering when running without a GUI.",
)
arg_group.add_argument(
"--verbose", # Note: This is read by SimulationApp through sys.argv
action="store_true",
help="Enable verbose terminal output from the SimulationApp.",
)
arg_group.add_argument(
"--experience",
type=str,
default="",
help=(
"The experience file to load when launching the SimulationApp. If an empty string is provided,"
" the experience file is determined based on the headless flag. If a relative path is provided,"
" it is resolved relative to the `apps` folder in Isaac Sim and Orbit (in that order)."
),
)
# Corresponding to the beginning of the function,
# if we have removed -h/--help handling, we add it back.
if parser_help is not None:
parser._option_string_actions["-h"] = parser_help
parser._option_string_actions["--help"] = parser_help
"""
Internal functions.
"""
_APPLAUNCHER_CFG_INFO: dict[str, tuple[list[type], Any]] = {
"headless": ([bool], False),
"livestream": ([int], -1),
"offscreen_render": ([bool], False),
"experience": ([str], ""),
}
"""A dictionary of arguments added manually by the :meth:`AppLauncher.add_app_launcher_args` method.
The values are a tuple of the expected type and default value. This is used to check against name collisions
for arguments passed to the :class:`AppLauncher` class as well as for type checking.
They have corresponding environment variables as detailed in the documentation.
"""
# TODO: Find some internally managed NVIDIA list of these types.
# SimulationApp.DEFAULT_LAUNCHER_CONFIG almost works, except that
# it is ambiguous where the default types are None
_SIM_APP_CFG_TYPES: dict[str, list[type]] = {
"headless": [bool],
"active_gpu": [int, type(None)],
"physics_gpu": [int],
"multi_gpu": [bool],
"sync_loads": [bool],
"width": [int],
"height": [int],
"window_width": [int],
"window_height": [int],
"display_options": [int],
"subdiv_refinement_level": [int],
"renderer": [str],
"anti_aliasing": [int],
"samples_per_pixel_per_frame": [int],
"denoiser": [bool],
"max_bounces": [int],
"max_specular_transmission_bounces": [int],
"max_volume_bounces": [int],
"open_usd": [str, type(None)],
"livesync_usd": [str, type(None)],
"fast_shutdown": [bool],
"experience": [str],
}
"""A dictionary containing the type of arguments passed to SimulationApp.
This is used to check against name collisions for arguments passed to the :class:`AppLauncher` class
as well as for type checking. It corresponds closely to the :attr:`SimulationApp.DEFAULT_LAUNCHER_CONFIG`,
but specifically denotes where None types are allowed.
"""
@staticmethod
def _check_argparser_config_params(config: dict) -> None:
"""Checks that input argparser object has parameters with valid settings with no name conflicts.
First, we inspect the dictionary to ensure that the passed ArgParser object is not attempting to add arguments
which should be assigned by calling :meth:`AppLauncher.add_app_launcher_args`.
Then, we check that if the key corresponds to a config setting expected by SimulationApp, then the type of
that key's value corresponds to the type expected by the SimulationApp. If it passes the check, the function
prints out that the setting with be passed to the SimulationApp. Otherwise, we raise a ValueError exception.
Args:
config: A configuration parameters which will be passed to the SimulationApp constructor.
Raises:
ValueError: If a key is an already existing field in the configuration parameters but
should be added by calling the :meth:`AppLauncher.add_app_launcher_args.
ValueError: If keys corresponding to those used to initialize SimulationApp
(as found in :attr:`_SIM_APP_CFG_TYPES`) are of the wrong value type.
"""
# check that no config key conflicts with AppLauncher config names
applauncher_keys = set(AppLauncher._APPLAUNCHER_CFG_INFO.keys())
for key, value in config.items():
if key in applauncher_keys:
raise ValueError(
f"The passed ArgParser object already has the field '{key}'. This field will be added by"
" `AppLauncher.add_app_launcher_args()`, and should not be added directly. Please remove the"
" argument or rename it to a non-conflicting name."
)
# check that type of the passed keys are valid
simulationapp_keys = set(AppLauncher._SIM_APP_CFG_TYPES.keys())
for key, value in config.items():
if key in simulationapp_keys:
given_type = type(value)
expected_types = AppLauncher._SIM_APP_CFG_TYPES[key]
if type(value) not in set(expected_types):
raise ValueError(
f"Invalid value type for the argument '{key}': {given_type}. Expected one of {expected_types},"
" if intended to be ingested by the SimulationApp object. Please change the type if this"
" intended for the SimulationApp or change the name of the argument to avoid name conflicts."
)
# Print out values which will be used
print(f"[INFO][AppLauncher]: The argument '{key}' will be used to configure the SimulationApp.")
def _config_resolution(self, launcher_args: dict):
"""Resolve the input arguments and environment variables.
Args:
launcher_args: A dictionary of all input arguments passed to the class object.
"""
# Handle all control logic resolution
# --LIVESTREAM logic--
#
livestream_env = int(os.environ.get("LIVESTREAM", 0))
livestream_arg = launcher_args.pop("livestream", AppLauncher._APPLAUNCHER_CFG_INFO["livestream"][1])
livestream_valid_vals = {0, 1, 2, 3}
# Value checking on LIVESTREAM
if livestream_env not in livestream_valid_vals:
raise ValueError(
f"Invalid value for environment variable `LIVESTREAM`: {livestream_env} ."
f" Expected: {livestream_valid_vals}."
)
# We allow livestream kwarg to supersede LIVESTREAM envvar
if livestream_arg >= 0:
if livestream_arg in livestream_valid_vals:
self._livestream = livestream_arg
# print info that we overrode the env-var
print(
f"[INFO][AppLauncher]: Input keyword argument `livestream={livestream_arg}` has overridden"
f" the environment variable `LIVESTREAM={livestream_env}`."
)
else:
raise ValueError(
f"Invalid value for input keyword argument `livestream`: {livestream_arg} ."
f" Expected: {livestream_valid_vals}."
)
else:
self._livestream = livestream_env
# --HEADLESS logic--
#
# Resolve headless execution of simulation app
# HEADLESS is initially passed as an int instead of
# the bool of headless_arg to avoid messy string processing,
headless_env = int(os.environ.get("HEADLESS", 0))
headless_arg = launcher_args.pop("headless", AppLauncher._APPLAUNCHER_CFG_INFO["headless"][1])
headless_valid_vals = {0, 1}
# Value checking on HEADLESS
if headless_env not in headless_valid_vals:
raise ValueError(
f"Invalid value for environment variable `HEADLESS`: {headless_env} . Expected: {headless_valid_vals}."
)
# We allow headless kwarg to supersede HEADLESS envvar if headless_arg does not have the default value
# Note: Headless is always true when livestreaming
if headless_arg is True:
self._headless = headless_arg
elif self._livestream in {1, 2, 3}:
# we are always headless on the host machine
self._headless = True
# inform who has toggled the headless flag
if self._livestream == livestream_arg:
print(
f"[INFO][AppLauncher]: Input keyword argument `livestream={self._livestream}` has implicitly"
f" overridden the environment variable `HEADLESS={headless_env}` to True."
)
elif self._livestream == livestream_env:
print(
f"[INFO][AppLauncher]: Environment variable `LIVESTREAM={self._livestream}` has implicitly"
f" overridden the environment variable `HEADLESS={headless_env}` to True."
)
else:
# Headless needs to be a bool to be ingested by SimulationApp
self._headless = bool(headless_env)
# Headless needs to be passed to the SimulationApp so we keep it here
launcher_args["headless"] = self._headless
# --OFFSCREEN_RENDER logic--
#
# off-screen rendering
offscreen_render_env = int(os.environ.get("OFFSCREEN_RENDER", 0))
offscreen_render_arg = launcher_args.pop(
"offscreen_render", AppLauncher._APPLAUNCHER_CFG_INFO["offscreen_render"][1]
)
offscreen_render_valid_vals = {0, 1}
if offscreen_render_env not in offscreen_render_valid_vals:
raise ValueError(
f"Invalid value for environment variable `OFFSCREEN_RENDER`: {offscreen_render_env} ."
f"Expected: {offscreen_render_valid_vals} ."
)
# We allow offscreen_render kwarg to supersede OFFSCREEN_RENDER envvar
if offscreen_render_arg is True:
self._offscreen_render = offscreen_render_arg
else:
self._offscreen_render = bool(offscreen_render_env)
# Check if input keywords contain an 'experience' file setting
# Note: since experience is taken as a separate argument by Simulation App, we store it separately
self._sim_experience_file = launcher_args.pop("experience", "")
# If nothing is provided resolve the experience file based on the headless flag
kit_app_exp_path = os.environ["EXP_PATH"]
orbit_app_exp_path = os.path.join(os.environ["ORBIT_PATH"], "source", "apps")
if self._sim_experience_file == "":
# check if the headless flag is set
if self._headless and not self._livestream:
self._sim_experience_file = os.path.join(orbit_app_exp_path, "orbit.python.headless.kit")
else:
self._sim_experience_file = os.path.join(orbit_app_exp_path, "orbit.python.kit")
elif not os.path.isabs(self._sim_experience_file):
option_1_app_exp_path = os.path.join(kit_app_exp_path, self._sim_experience_file)
option_2_app_exp_path = os.path.join(orbit_app_exp_path, self._sim_experience_file)
if os.path.exists(option_1_app_exp_path):
self._sim_experience_file = option_1_app_exp_path
elif os.path.exists(option_2_app_exp_path):
self._sim_experience_file = option_2_app_exp_path
else:
raise FileNotFoundError(
f"Invalid value for input keyword argument `experience`: {self._sim_experience_file}."
"\n No such file exists in either the Kit or Orbit experience paths. Checked paths:"
f"\n\t [1]: {option_1_app_exp_path}"
f"\n\t [2]: {option_2_app_exp_path}"
)
elif not os.path.exists(self._sim_experience_file):
raise FileNotFoundError(
f"Invalid value for input keyword argument `experience`: {self._sim_experience_file}."
" The file does not exist."
)
print(f"[INFO][AppLauncher]: Loading experience file: {self._sim_experience_file}")
# Remove all values from input keyword args which are not meant for SimulationApp
# Assign all the passed settings to a dictionary for the simulation app
self._sim_app_config = {
key: launcher_args[key] for key in set(AppLauncher._SIM_APP_CFG_TYPES.keys()) & set(launcher_args.keys())
}
def _create_app(self):
"""Launch and create the SimulationApp based on the parsed simulation config."""
# Initialize SimulationApp
# hack sys module to make sure that the SimulationApp is initialized correctly
# this is to avoid the warnings from the simulation app about not ok modules
r = re.compile(".*orbit.*")
found_modules = list(filter(r.match, list(sys.modules.keys())))
found_modules += ["omni.isaac.kit.app_framework"]
# remove orbit modules from sys.modules
hacked_modules = dict()
for key in found_modules:
hacked_modules[key] = sys.modules[key]
del sys.modules[key]
# launch simulation app
self._app = SimulationApp(self._sim_app_config, experience=self._sim_experience_file)
# add orbit modules back to sys.modules
for key, value in hacked_modules.items():
sys.modules[key] = value
def _load_extensions(self):
"""Load correct extensions based on AppLauncher's resolved config member variables."""
# These have to be loaded after SimulationApp is initialized
import carb
from omni.isaac.core.utils.extensions import enable_extension
# Retrieve carb settings for modification
carb_settings_iface = carb.settings.get_settings()
if self._livestream >= 1:
# Ensure that a viewport exists in case an experience has been
# loaded which does not load it by default
enable_extension("omni.kit.viewport.window")
# Set carb settings to allow for livestreaming
carb_settings_iface.set_bool("/app/livestream/enabled", True)
carb_settings_iface.set_bool("/app/window/drawMouse", True)
carb_settings_iface.set_bool("/ngx/enabled", False)
carb_settings_iface.set_string("/app/livestream/proto", "ws")
carb_settings_iface.set_int("/app/livestream/websocket/framerate_limit", 120)
# Note: Only one livestream extension can be enabled at a time
if self._livestream == 1:
# Enable Native Livestream extension
# Default App: Streaming Client from the Omniverse Launcher
enable_extension("omni.kit.livestream.native")
enable_extension("omni.services.streaming.manager")
elif self._livestream == 2:
# Enable WebSocket Livestream extension
# Default URL: http://localhost:8211/streaming/client/
enable_extension("omni.services.streamclient.websocket")
elif self._livestream == 3:
# Enable WebRTC Livestream extension
# Default URL: http://localhost:8211/streaming/webrtc-client/
enable_extension("omni.services.streamclient.webrtc")
else:
raise ValueError(f"Invalid value for livestream: {self._livestream}. Expected: 1, 2, 3 .")
else:
carb_settings_iface.set_bool("/app/livestream/enabled", False)
# set carb setting to indicate orbit's offscreen_render pipeline should be enabled
# this flag is used by the SimulationContext class to enable the offscreen_render pipeline
# when the render() method is called.
carb_settings_iface.set_bool("/orbit/render/offscreen", self._offscreen_render)
# set carb setting to indicate no RTX sensors are used
# this flag is set to True when an RTX-rendering related sensor is created
# for example: the `Camera` sensor class
carb_settings_iface.set_bool("/orbit/render/rtx_sensors", False)
# enable extensions for off-screen rendering
# Depending on the app file, some extensions might not be available in it.
# Thus, we manually enable these extensions to make sure they are available.
# note: enabling extensions is order-sensitive. please do not change the order!
if self._offscreen_render or not self._headless or self._livestream >= 1:
# extension to enable UI buttons (otherwise we get attribute errors)
enable_extension("omni.kit.window.toolbar")
if self._offscreen_render or not self._headless:
# extension to make RTX realtime and path-traced renderers
enable_extension("omni.kit.viewport.rtx")
# extension to make HydraDelegate renderers
enable_extension("omni.kit.viewport.pxr")
# enable viewport extension if full rendering is enabled
enable_extension("omni.kit.viewport.bundle")
# extension for window status bar
enable_extension("omni.kit.window.status_bar")
# enable replicator extension
# note: moved here since it requires to have the viewport extension to be enabled first.
enable_extension("omni.replicator.core")
# enable UI tools
# note: we need to always import this even with headless to make
# the module for orbit.envs.ui work
enable_extension("omni.isaac.ui")
# enable animation recording extension
if not self._headless or self._livestream >= 1:
enable_extension("omni.kit.stagerecorder.core")
# set the nucleus directory manually to the latest published Nucleus
# note: this is done to ensure prior versions of Isaac Sim still use the latest assets
carb_settings_iface.set_string(
"/persistent/isaac/asset_root/default",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2023.1.1",
)
carb_settings_iface.set_string(
"/persistent/isaac/asset_root/nvidia",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/2023.1.1",
)
def _hide_stop_button(self):
"""Hide the stop button in the toolbar.
For standalone executions, having a stop button is confusing since it invalidates the whole simulation.
Thus, we hide the button so that users don't accidentally click it.
"""
# when we are truly headless, then we can't import the widget toolbar
# thus, we only hide the stop button when we are not headless (i.e. GUI is enabled)
if self._livestream >= 1 or not self._headless:
import omni.kit.widget.toolbar
# grey out the stop button because we don't want to stop the simulation manually in standalone mode
toolbar = omni.kit.widget.toolbar.get_instance()
play_button_group = toolbar._builtin_tools._play_button_group # type: ignore
if play_button_group is not None:
play_button_group._stop_button.visible = False # type: ignore
play_button_group._stop_button.enabled = False # type: ignore
play_button_group._stop_button = None # type: ignore
def _interrupt_signal_handle_callback(self, signal, frame):
"""Handle the interrupt signal from the keyboard."""
# close the app
self._app.close()
# raise the error for keyboard interrupt
raise KeyboardInterrupt
def _abort_signal_handle_callback(self, signal, frame):
"""Handle the abort/segmentation/kill signals."""
# close the app
self._app.close()
| 31,781 | Python | 51.016367 | 121 | 0.639659 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/app/runners.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module with runners to simplify running main via unittest."""
import unittest
def run_tests(verbosity: int = 2, **kwargs):
"""Wrapper for running tests via ``unittest``.
Args:
verbosity: Verbosity level for the test runner.
**kwargs: Additional arguments to pass to the `unittest.main` function.
"""
# run main
unittest.main(verbosity=verbosity, exit=True, **kwargs)
| 537 | Python | 25.899999 | 79 | 0.689013 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/actuators/actuator_pd.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from collections.abc import Sequence
from typing import TYPE_CHECKING
from omni.isaac.core.utils.types import ArticulationActions
from .actuator_base import ActuatorBase
if TYPE_CHECKING:
from .actuator_cfg import DCMotorCfg, IdealPDActuatorCfg, ImplicitActuatorCfg
"""
Implicit Actuator Models.
"""
class ImplicitActuator(ActuatorBase):
"""Implicit actuator model that is handled by the simulation.
This performs a similar function as the :class:`IdealPDActuator` class. However, the PD control is handled
implicitly by the simulation which performs continuous-time integration of the PD control law. This is
generally more accurate than the explicit PD control law used in :class:`IdealPDActuator` when the simulation
time-step is large.
.. note::
The articulation class sets the stiffness and damping parameters from the configuration into the simulation.
Thus, the parameters are not used in this class.
.. caution::
The class is only provided for consistency with the other actuator models. It does not implement any
functionality and should not be used. All values should be set to the simulation directly.
"""
cfg: ImplicitActuatorCfg
"""The configuration for the actuator model."""
"""
Operations.
"""
def reset(self, *args, **kwargs):
# This is a no-op. There is no state to reset for implicit actuators.
pass
def compute(
self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor
) -> ArticulationActions:
"""Compute the aproximmate torques for the actuated joint (physX does not compute this explicitly)."""
# store approximate torques for reward computation
error_pos = control_action.joint_positions - joint_pos
error_vel = control_action.joint_velocities - joint_vel
self.computed_effort = self.stiffness * error_pos + self.damping * error_vel + control_action.joint_efforts
# clip the torques based on the motor limits
self.applied_effort = self._clip_effort(self.computed_effort)
return control_action
"""
Explicit Actuator Models.
"""
class IdealPDActuator(ActuatorBase):
r"""Ideal torque-controlled actuator model with a simple saturation model.
It employs the following model for computing torques for the actuated joint :math:`j`:
.. math::
\tau_{j, computed} = k_p * (q - q_{des}) + k_d * (\dot{q} - \dot{q}_{des}) + \tau_{ff}
where, :math:`k_p` and :math:`k_d` are joint stiffness and damping gains, :math:`q` and :math:`\dot{q}`
are the current joint positions and velocities, :math:`q_{des}`, :math:`\dot{q}_{des}` and :math:`\tau_{ff}`
are the desired joint positions, velocities and torques commands.
The clipping model is based on the maximum torque applied by the motor. It is implemented as:
.. math::
\tau_{j, max} & = \gamma \times \tau_{motor, max} \\
\tau_{j, applied} & = clip(\tau_{computed}, -\tau_{j, max}, \tau_{j, max})
where the clipping function is defined as :math:`clip(x, x_{min}, x_{max}) = min(max(x, x_{min}), x_{max})`.
The parameters :math:`\gamma` is the gear ratio of the gear box connecting the motor and the actuated joint ends,
and :math:`\tau_{motor, max}` is the maximum motor effort possible. These parameters are read from
the configuration instance passed to the class.
"""
cfg: IdealPDActuatorCfg
"""The configuration for the actuator model."""
"""
Operations.
"""
def reset(self, env_ids: Sequence[int]):
pass
def compute(
self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor
) -> ArticulationActions:
# compute errors
error_pos = control_action.joint_positions - joint_pos
error_vel = control_action.joint_velocities - joint_vel
# calculate the desired joint torques
self.computed_effort = self.stiffness * error_pos + self.damping * error_vel + control_action.joint_efforts
# clip the torques based on the motor limits
self.applied_effort = self._clip_effort(self.computed_effort)
# set the computed actions back into the control action
control_action.joint_efforts = self.applied_effort
control_action.joint_positions = None
control_action.joint_velocities = None
return control_action
class DCMotor(IdealPDActuator):
r"""
Direct control (DC) motor actuator model with velocity-based saturation model.
It uses the same model as the :class:`IdealActuator` for computing the torques from input commands.
However, it implements a saturation model defined by DC motor characteristics.
A DC motor is a type of electric motor that is powered by direct current electricity. In most cases,
the motor is connected to a constant source of voltage supply, and the current is controlled by a rheostat.
Depending on various design factors such as windings and materials, the motor can draw a limited maximum power
from the electronic source, which limits the produced motor torque and speed.
A DC motor characteristics are defined by the following parameters:
* Continuous-rated speed (:math:`\dot{q}_{motor, max}`) : The maximum-rated speed of the motor.
* Continuous-stall torque (:math:`\tau_{motor, max}`): The maximum-rated torque produced at 0 speed.
* Saturation torque (:math:`\tau_{motor, sat}`): The maximum torque that can be outputted for a short period.
Based on these parameters, the instantaneous minimum and maximum torques are defined as follows:
.. math::
\tau_{j, max}(\dot{q}) & = clip \left (\tau_{j, sat} \times \left(1 -
\frac{\dot{q}}{\dot{q}_{j, max}}\right), 0.0, \tau_{j, max} \right) \\
\tau_{j, min}(\dot{q}) & = clip \left (\tau_{j, sat} \times \left( -1 -
\frac{\dot{q}}{\dot{q}_{j, max}}\right), - \tau_{j, max}, 0.0 \right)
where :math:`\gamma` is the gear ratio of the gear box connecting the motor and the actuated joint ends,
:math:`\dot{q}_{j, max} = \gamma^{-1} \times \dot{q}_{motor, max}`, :math:`\tau_{j, max} =
\gamma \times \tau_{motor, max}` and :math:`\tau_{j, peak} = \gamma \times \tau_{motor, peak}`
are the maximum joint velocity, maximum joint torque and peak torque, respectively. These parameters
are read from the configuration instance passed to the class.
Using these values, the computed torques are clipped to the minimum and maximum values based on the
instantaneous joint velocity:
.. math::
\tau_{j, applied} = clip(\tau_{computed}, \tau_{j, min}(\dot{q}), \tau_{j, max}(\dot{q}))
"""
cfg: DCMotorCfg
"""The configuration for the actuator model."""
def __init__(self, cfg: DCMotorCfg, *args, **kwargs):
super().__init__(cfg, *args, **kwargs)
# parse configuration
if self.cfg.saturation_effort is not None:
self._saturation_effort = self.cfg.saturation_effort
else:
self._saturation_effort = torch.inf
# prepare joint vel buffer for max effort computation
self._joint_vel = torch.zeros_like(self.computed_effort)
# create buffer for zeros effort
self._zeros_effort = torch.zeros_like(self.computed_effort)
# check that quantities are provided
if self.cfg.velocity_limit is None:
raise ValueError("The velocity limit must be provided for the DC motor actuator model.")
"""
Operations.
"""
def compute(
self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor
) -> ArticulationActions:
# save current joint vel
self._joint_vel[:] = joint_vel
# calculate the desired joint torques
return super().compute(control_action, joint_pos, joint_vel)
"""
Helper functions.
"""
def _clip_effort(self, effort: torch.Tensor) -> torch.Tensor:
# compute torque limits
# -- max limit
max_effort = self._saturation_effort * (1.0 - self._joint_vel / self.velocity_limit)
max_effort = torch.clip(max_effort, min=self._zeros_effort, max=self.effort_limit)
# -- min limit
min_effort = self._saturation_effort * (-1.0 - self._joint_vel / self.velocity_limit)
min_effort = torch.clip(min_effort, min=-self.effort_limit, max=self._zeros_effort)
# clip the torques based on the motor limits
return torch.clip(effort, min=min_effort, max=max_effort)
| 8,791 | Python | 40.276995 | 117 | 0.67171 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/actuators/actuator_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from collections.abc import Iterable
from dataclasses import MISSING
from typing import Literal
from omni.isaac.orbit.utils import configclass
from . import actuator_net, actuator_pd
from .actuator_base import ActuatorBase
@configclass
class ActuatorBaseCfg:
"""Configuration for default actuators in an articulation."""
class_type: type[ActuatorBase] = MISSING
"""The associated actuator class.
The class should inherit from :class:`omni.isaac.orbit.actuators.ActuatorBase`.
"""
joint_names_expr: list[str] = MISSING
"""Articulation's joint names that are part of the group.
Note:
This can be a list of joint names or a list of regex expressions (e.g. ".*").
"""
effort_limit: dict[str, float] | float | None = None
"""Force/Torque limit of the joints in the group. Defaults to None.
If None, the limit is set to the value specified in the USD joint prim.
"""
velocity_limit: dict[str, float] | float | None = None
"""Velocity limit of the joints in the group. Defaults to None.
If None, the limit is set to the value specified in the USD joint prim.
"""
stiffness: dict[str, float] | float | None = MISSING
"""Stiffness gains (also known as p-gain) of the joints in the group.
If None, the stiffness is set to the value from the USD joint prim.
"""
damping: dict[str, float] | float | None = MISSING
"""Damping gains (also known as d-gain) of the joints in the group.
If None, the damping is set to the value from the USD joint prim.
"""
armature: dict[str, float] | float | None = None
"""Armature of the joints in the group. Defaults to None.
If None, the armature is set to the value from the USD joint prim.
"""
friction: dict[str, float] | float | None = None
"""Joint friction of the joints in the group. Defaults to None.
If None, the joint friction is set to the value from the USD joint prim.
"""
"""
Implicit Actuator Models.
"""
@configclass
class ImplicitActuatorCfg(ActuatorBaseCfg):
"""Configuration for an implicit actuator.
Note:
The PD control is handled implicitly by the simulation.
"""
class_type: type = actuator_pd.ImplicitActuator
"""
Explicit Actuator Models.
"""
@configclass
class IdealPDActuatorCfg(ActuatorBaseCfg):
"""Configuration for an ideal PD actuator."""
class_type: type = actuator_pd.IdealPDActuator
@configclass
class DCMotorCfg(IdealPDActuatorCfg):
"""Configuration for direct control (DC) motor actuator model."""
class_type: type = actuator_pd.DCMotor
saturation_effort: float = MISSING
"""Peak motor force/torque of the electric DC motor (in N-m)."""
@configclass
class ActuatorNetLSTMCfg(DCMotorCfg):
"""Configuration for LSTM-based actuator model."""
class_type: type = actuator_net.ActuatorNetLSTM
# we don't use stiffness and damping for actuator net
stiffness = None
damping = None
network_file: str = MISSING
"""Path to the file containing network weights."""
@configclass
class ActuatorNetMLPCfg(DCMotorCfg):
"""Configuration for MLP-based actuator model."""
class_type: type = actuator_net.ActuatorNetMLP
# we don't use stiffness and damping for actuator net
stiffness = None
damping = None
network_file: str = MISSING
"""Path to the file containing network weights."""
pos_scale: float = MISSING
"""Scaling of the joint position errors input to the network."""
vel_scale: float = MISSING
"""Scaling of the joint velocities input to the network."""
torque_scale: float = MISSING
"""Scaling of the joint efforts output from the network."""
input_order: Literal["pos_vel", "vel_pos"] = MISSING
"""Order of the inputs to the network.
The order can be one of the following:
* ``"pos_vel"``: joint position errors followed by joint velocities
* ``"vel_pos"``: joint velocities followed by joint position errors
"""
input_idx: Iterable[int] = MISSING
"""
Indices of the actuator history buffer passed as inputs to the network.
The index *0* corresponds to current time-step, while *n* corresponds to n-th
time-step in the past. The allocated history length is `max(input_idx) + 1`.
"""
| 4,420 | Python | 27.339743 | 85 | 0.688462 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/actuators/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package for different actuator models.
Actuator models are used to model the behavior of the actuators in an articulation. These
are usually meant to be used in simulation to model different actuator dynamics and delays.
There are two main categories of actuator models that are supported:
- **Implicit**: Motor model with ideal PD from the physics engine. This is similar to having a continuous time
PD controller. The motor model is implicit in the sense that the motor model is not explicitly defined by the user.
- **Explicit**: Motor models based on physical drive models.
- **Physics-based**: Derives the motor models based on first-principles.
- **Neural Network-based**: Learned motor models from actuator data.
Every actuator model inherits from the :class:`omni.isaac.orbit.actuators.ActuatorBase` class,
which defines the common interface for all actuator models. The actuator models are handled
and called by the :class:`omni.isaac.orbit.assets.Articulation` class.
"""
from .actuator_base import ActuatorBase
from .actuator_cfg import (
ActuatorBaseCfg,
ActuatorNetLSTMCfg,
ActuatorNetMLPCfg,
DCMotorCfg,
IdealPDActuatorCfg,
ImplicitActuatorCfg,
)
from .actuator_net import ActuatorNetLSTM, ActuatorNetMLP
from .actuator_pd import DCMotor, IdealPDActuator, ImplicitActuator
| 1,453 | Python | 39.388888 | 117 | 0.781142 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/actuators/actuator_base.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import TYPE_CHECKING
from omni.isaac.core.utils.types import ArticulationActions
import omni.isaac.orbit.utils.string as string_utils
if TYPE_CHECKING:
from .actuator_cfg import ActuatorBaseCfg
class ActuatorBase(ABC):
"""Base class for actuator models over a collection of actuated joints in an articulation.
Actuator models augment the simulated articulation joints with an external drive dynamics model.
The model is used to convert the user-provided joint commands (positions, velocities and efforts)
into the desired joint positions, velocities and efforts that are applied to the simulated articulation.
The base class provides the interface for the actuator models. It is responsible for parsing the
actuator parameters from the configuration and storing them as buffers. It also provides the
interface for resetting the actuator state and computing the desired joint commands for the simulation.
For each actuator model, a corresponding configuration class is provided. The configuration class
is used to parse the actuator parameters from the configuration. It also specifies the joint names
for which the actuator model is applied. These names can be specified as regular expressions, which
are matched against the joint names in the articulation.
To see how the class is used, check the :class:`omni.isaac.orbit.assets.Articulation` class.
"""
computed_effort: torch.Tensor
"""The computed effort for the actuator group. Shape is (num_envs, num_joints)."""
applied_effort: torch.Tensor
"""The applied effort for the actuator group. Shape is (num_envs, num_joints)."""
effort_limit: torch.Tensor
"""The effort limit for the actuator group. Shape is (num_envs, num_joints)."""
velocity_limit: torch.Tensor
"""The velocity limit for the actuator group. Shape is (num_envs, num_joints)."""
stiffness: torch.Tensor
"""The stiffness (P gain) of the PD controller. Shape is (num_envs, num_joints)."""
damping: torch.Tensor
"""The damping (D gain) of the PD controller. Shape is (num_envs, num_joints)."""
armature: torch.Tensor
"""The armature of the actuator joints. Shape is (num_envs, num_joints)."""
friction: torch.Tensor
"""The joint friction of the actuator joints. Shape is (num_envs, num_joints)."""
def __init__(
self,
cfg: ActuatorBaseCfg,
joint_names: list[str],
joint_ids: slice | Sequence[int],
num_envs: int,
device: str,
stiffness: torch.Tensor | float = 0.0,
damping: torch.Tensor | float = 0.0,
armature: torch.Tensor | float = 0.0,
friction: torch.Tensor | float = 0.0,
effort_limit: torch.Tensor | float = torch.inf,
velocity_limit: torch.Tensor | float = torch.inf,
):
"""Initialize the actuator.
Note:
The actuator parameters are parsed from the configuration and stored as buffers. If the parameters
are not specified in the configuration, then the default values provided in the arguments are used.
Args:
cfg: The configuration of the actuator model.
joint_names: The joint names in the articulation.
joint_ids: The joint indices in the articulation. If :obj:`slice(None)`, then all
the joints in the articulation are part of the group.
num_envs: Number of articulations in the view.
device: Device used for processing.
stiffness: The default joint stiffness (P gain). Defaults to 0.0.
If a tensor, then the shape is (num_envs, num_joints).
damping: The default joint damping (D gain). Defaults to 0.0.
If a tensor, then the shape is (num_envs, num_joints).
armature: The default joint armature. Defaults to 0.0.
If a tensor, then the shape is (num_envs, num_joints).
friction: The default joint friction. Defaults to 0.0.
If a tensor, then the shape is (num_envs, num_joints).
effort_limit: The default effort limit. Defaults to infinity.
If a tensor, then the shape is (num_envs, num_joints).
velocity_limit: The default velocity limit. Defaults to infinity.
If a tensor, then the shape is (num_envs, num_joints).
"""
# save parameters
self.cfg = cfg
self._num_envs = num_envs
self._device = device
self._joint_names = joint_names
self._joint_indices = joint_ids
# parse joint stiffness and damping
self.stiffness = self._parse_joint_parameter(self.cfg.stiffness, stiffness)
self.damping = self._parse_joint_parameter(self.cfg.damping, damping)
# parse joint armature and friction
self.armature = self._parse_joint_parameter(self.cfg.armature, armature)
self.friction = self._parse_joint_parameter(self.cfg.friction, friction)
# parse joint limits
# note: for velocity limits, we don't have USD parameter, so default is infinity
self.effort_limit = self._parse_joint_parameter(self.cfg.effort_limit, effort_limit)
self.velocity_limit = self._parse_joint_parameter(self.cfg.velocity_limit, velocity_limit)
# create commands buffers for allocation
self.computed_effort = torch.zeros(self._num_envs, self.num_joints, device=self._device)
self.applied_effort = torch.zeros_like(self.computed_effort)
def __str__(self) -> str:
"""Returns: A string representation of the actuator group."""
# resolve joint indices for printing
joint_indices = self.joint_indices
if joint_indices == slice(None):
joint_indices = list(range(self.num_joints))
return (
f"<class {self.__class__.__name__}> object:\n"
f"\tNumber of joints : {self.num_joints}\n"
f"\tJoint names expression: {self.cfg.joint_names_expr}\n"
f"\tJoint names : {self.joint_names}\n"
f"\tJoint indices : {joint_indices}\n"
)
"""
Properties.
"""
@property
def num_joints(self) -> int:
"""Number of actuators in the group."""
return len(self._joint_names)
@property
def joint_names(self) -> list[str]:
"""Articulation's joint names that are part of the group."""
return self._joint_names
@property
def joint_indices(self) -> slice | Sequence[int]:
"""Articulation's joint indices that are part of the group.
Note:
If :obj:`slice(None)` is returned, then the group contains all the joints in the articulation.
We do this to avoid unnecessary indexing of the joints for performance reasons.
"""
return self._joint_indices
"""
Operations.
"""
@abstractmethod
def reset(self, env_ids: Sequence[int]):
"""Reset the internals within the group.
Args:
env_ids: List of environment IDs to reset.
"""
raise NotImplementedError
@abstractmethod
def compute(
self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor
) -> ArticulationActions:
"""Process the actuator group actions and compute the articulation actions.
It computes the articulation actions based on the actuator model type
Args:
control_action: The joint action instance comprising of the desired joint positions, joint velocities
and (feed-forward) joint efforts.
joint_pos: The current joint positions of the joints in the group. Shape is (num_envs, num_joints).
joint_vel: The current joint velocities of the joints in the group. Shape is (num_envs, num_joints).
Returns:
The computed desired joint positions, joint velocities and joint efforts.
"""
raise NotImplementedError
"""
Helper functions.
"""
def _parse_joint_parameter(
self, cfg_value: float | dict[str, float] | None, default_value: float | torch.Tensor | None
) -> torch.Tensor:
"""Parse the joint parameter from the configuration.
Args:
cfg_value: The parameter value from the configuration. If None, then use the default value.
default_value: The default value to use if the parameter is None. If it is also None,
then an error is raised.
Returns:
The parsed parameter value.
Raises:
TypeError: If the parameter value is not of the expected type.
TypeError: If the default value is not of the expected type.
ValueError: If the parameter value is None and no default value is provided.
"""
# create parameter buffer
param = torch.zeros(self._num_envs, self.num_joints, device=self._device)
# parse the parameter
if cfg_value is not None:
if isinstance(cfg_value, (float, int)):
# if float, then use the same value for all joints
param[:] = float(cfg_value)
elif isinstance(cfg_value, dict):
# if dict, then parse the regular expression
indices, _, values = string_utils.resolve_matching_names_values(cfg_value, self.joint_names)
# note: need to specify type to be safe (e.g. values are ints, but we want floats)
param[:, indices] = torch.tensor(values, dtype=torch.float, device=self._device)
else:
raise TypeError(f"Invalid type for parameter value: {type(cfg_value)}. Expected float or dict.")
elif default_value is not None:
if isinstance(default_value, (float, int)):
# if float, then use the same value for all joints
param[:] = float(default_value)
elif isinstance(default_value, torch.Tensor):
# if tensor, then use the same tensor for all joints
param[:] = default_value.float()
else:
raise TypeError(f"Invalid type for default value: {type(default_value)}. Expected float or Tensor.")
else:
raise ValueError("The parameter value is None and no default value is provided.")
return param
def _clip_effort(self, effort: torch.Tensor) -> torch.Tensor:
"""Clip the desired torques based on the motor limits.
Args:
desired_torques: The desired torques to clip.
Returns:
The clipped torques.
"""
return torch.clip(effort, min=-self.effort_limit, max=self.effort_limit)
| 10,995 | Python | 43.160642 | 116 | 0.643838 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/actuators/actuator_net.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Neural network models for actuators.
Currently, the following models are supported:
* Multi-Layer Perceptron (MLP)
* Long Short-Term Memory (LSTM)
"""
from __future__ import annotations
import torch
from collections.abc import Sequence
from typing import TYPE_CHECKING
from omni.isaac.core.utils.types import ArticulationActions
from omni.isaac.orbit.utils.assets import read_file
from .actuator_pd import DCMotor
if TYPE_CHECKING:
from .actuator_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg
class ActuatorNetLSTM(DCMotor):
"""Actuator model based on recurrent neural network (LSTM).
Unlike the MLP implementation :cite:t:`hwangbo2019learning`, this class implements
the learned model as a temporal neural network (LSTM) based on the work from
:cite:t:`rudin2022learning`. This removes the need of storing a history as the
hidden states of the recurrent network captures the history.
Note:
Only the desired joint positions are used as inputs to the network.
"""
cfg: ActuatorNetLSTMCfg
"""The configuration of the actuator model."""
def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs):
super().__init__(cfg, *args, **kwargs)
# load the model from JIT file
file_bytes = read_file(self.cfg.network_file)
self.network = torch.jit.load(file_bytes, map_location=self._device)
# extract number of lstm layers and hidden dim from the shape of weights
num_layers = len(self.network.lstm.state_dict()) // 4
hidden_dim = self.network.lstm.state_dict()["weight_hh_l0"].shape[1]
# create buffers for storing LSTM inputs
self.sea_input = torch.zeros(self._num_envs * self.num_joints, 1, 2, device=self._device)
self.sea_hidden_state = torch.zeros(
num_layers, self._num_envs * self.num_joints, hidden_dim, device=self._device
)
self.sea_cell_state = torch.zeros(num_layers, self._num_envs * self.num_joints, hidden_dim, device=self._device)
# reshape via views (doesn't change the actual memory layout)
layer_shape_per_env = (num_layers, self._num_envs, self.num_joints, hidden_dim)
self.sea_hidden_state_per_env = self.sea_hidden_state.view(layer_shape_per_env)
self.sea_cell_state_per_env = self.sea_cell_state.view(layer_shape_per_env)
"""
Operations.
"""
def reset(self, env_ids: Sequence[int]):
# reset the hidden and cell states for the specified environments
with torch.no_grad():
self.sea_hidden_state_per_env[:, env_ids] = 0.0
self.sea_cell_state_per_env[:, env_ids] = 0.0
def compute(
self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor
) -> ArticulationActions:
# compute network inputs
self.sea_input[:, 0, 0] = (control_action.joint_positions - joint_pos).flatten()
self.sea_input[:, 0, 1] = joint_vel.flatten()
# save current joint vel for dc-motor clipping
self._joint_vel[:] = joint_vel
# run network inference
with torch.inference_mode():
torques, (self.sea_hidden_state[:], self.sea_cell_state[:]) = self.network(
self.sea_input, (self.sea_hidden_state, self.sea_cell_state)
)
self.computed_effort = torques.reshape(self._num_envs, self.num_joints)
# clip the computed effort based on the motor limits
self.applied_effort = self._clip_effort(self.computed_effort)
# return torques
control_action.joint_efforts = self.applied_effort
control_action.joint_positions = None
control_action.joint_velocities = None
return control_action
class ActuatorNetMLP(DCMotor):
"""Actuator model based on multi-layer perceptron and joint history.
Many times the analytical model is not sufficient to capture the actuator dynamics, the
delay in the actuator response, or the non-linearities in the actuator. In these cases,
a neural network model can be used to approximate the actuator dynamics. This model is
trained using data collected from the physical actuator and maps the joint state and the
desired joint command to the produced torque by the actuator.
This class implements the learned model as a neural network based on the work from
:cite:t:`hwangbo2019learning`. The class stores the history of the joint positions errors
and velocities which are used to provide input to the neural network. The model is loaded
as a TorchScript.
Note:
Only the desired joint positions are used as inputs to the network.
"""
cfg: ActuatorNetMLPCfg
"""The configuration of the actuator model."""
def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs):
super().__init__(cfg, *args, **kwargs)
# load the model from JIT file
file_bytes = read_file(self.cfg.network_file)
self.network = torch.jit.load(file_bytes, map_location=self._device)
# create buffers for MLP history
history_length = max(self.cfg.input_idx) + 1
self._joint_pos_error_history = torch.zeros(
self._num_envs, history_length, self.num_joints, device=self._device
)
self._joint_vel_history = torch.zeros(self._num_envs, history_length, self.num_joints, device=self._device)
"""
Operations.
"""
def reset(self, env_ids: Sequence[int]):
# reset the history for the specified environments
self._joint_pos_error_history[env_ids] = 0.0
self._joint_vel_history[env_ids] = 0.0
def compute(
self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor
) -> ArticulationActions:
# move history queue by 1 and update top of history
# -- positions
self._joint_pos_error_history = self._joint_pos_error_history.roll(1, 1)
self._joint_pos_error_history[:, 0] = control_action.joint_positions - joint_pos
# -- velocity
self._joint_vel_history = self._joint_vel_history.roll(1, 1)
self._joint_vel_history[:, 0] = joint_vel
# save current joint vel for dc-motor clipping
self._joint_vel[:] = joint_vel
# compute network inputs
# -- positions
pos_input = torch.cat([self._joint_pos_error_history[:, i].unsqueeze(2) for i in self.cfg.input_idx], dim=2)
pos_input = pos_input.view(self._num_envs * self.num_joints, -1)
# -- velocity
vel_input = torch.cat([self._joint_vel_history[:, i].unsqueeze(2) for i in self.cfg.input_idx], dim=2)
vel_input = vel_input.view(self._num_envs * self.num_joints, -1)
# -- scale and concatenate inputs
if self.cfg.input_order == "pos_vel":
network_input = torch.cat([pos_input * self.cfg.pos_scale, vel_input * self.cfg.vel_scale], dim=1)
elif self.cfg.input_order == "vel_pos":
network_input = torch.cat([vel_input * self.cfg.vel_scale, pos_input * self.cfg.pos_scale], dim=1)
else:
raise ValueError(
f"Invalid input order for MLP actuator net: {self.cfg.input_order}. Must be 'pos_vel' or 'vel_pos'."
)
# run network inference
torques = self.network(network_input).view(self._num_envs, self.num_joints)
self.computed_effort = torques.view(self._num_envs, self.num_joints) * self.cfg.torque_scale
# clip the computed effort based on the motor limits
self.applied_effort = self._clip_effort(self.computed_effort)
# return torques
control_action.joint_efforts = self.applied_effort
control_action.joint_positions = None
control_action.joint_velocities = None
return control_action
| 7,933 | Python | 40.757895 | 120 | 0.663053 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/scene/interactive_scene_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from omni.isaac.orbit.utils.configclass import configclass
@configclass
class InteractiveSceneCfg:
"""Configuration for the interactive scene.
The users can inherit from this class to add entities to their scene. This is then parsed by the
:class:`InteractiveScene` class to create the scene.
.. note::
The adding of entities to the scene is sensitive to the order of the attributes in the configuration.
Please make sure to add the entities in the order you want them to be added to the scene.
The recommended order of specification is terrain, physics-related assets (articulations and rigid bodies),
sensors and non-physics-related assets (lights).
For example, to add a robot to the scene, the user can create a configuration class as follows:
.. code-block:: python
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import AssetBaseCfg
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.sensors.ray_caster import GridPatternCfg, RayCasterCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_assets.anymal import ANYMAL_C_CFG
@configclass
class MySceneCfg(InteractiveSceneCfg):
# terrain - flat terrain plane
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
)
# articulation - robot 1
robot_1 = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot_1")
# articulation - robot 2
robot_2 = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot_2")
robot_2.init_state.pos = (0.0, 1.0, 0.6)
# sensor - ray caster attached to the base of robot 1 that scans the ground
height_scanner = RayCasterCfg(
prim_path="{ENV_REGEX_NS}/Robot_1/base",
offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)),
attach_yaw_only=True,
pattern_cfg=GridPatternCfg(resolution=0.1, size=[1.6, 1.0]),
debug_vis=True,
mesh_prim_paths=["/World/ground"],
)
# extras - light
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)),
init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, 500.0)),
)
"""
num_envs: int = MISSING
"""Number of environment instances handled by the scene."""
env_spacing: float = MISSING
"""Spacing between environments.
This is the default distance between environment origins in the scene. Used only when the
number of environments is greater than one.
"""
lazy_sensor_update: bool = True
"""Whether to update sensors only when they are accessed. Default is True.
If true, the sensor data is only updated when their attribute ``data`` is accessed. Otherwise, the sensor
data is updated every time sensors are updated.
"""
replicate_physics: bool = True
"""Enable/disable replication of physics schemas when using the Cloner APIs. Default is True."""
| 3,411 | Python | 37.337078 | 115 | 0.647318 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/scene/interactive_scene.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import builtins
import torch
from collections.abc import Sequence
from typing import Any
import carb
import omni.usd
from omni.isaac.cloner import GridCloner
from omni.isaac.core.prims import XFormPrimView
from pxr import PhysxSchema
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import Articulation, ArticulationCfg, AssetBaseCfg, RigidObject, RigidObjectCfg
from omni.isaac.orbit.sensors import ContactSensorCfg, FrameTransformerCfg, SensorBase, SensorBaseCfg
from omni.isaac.orbit.terrains import TerrainImporter, TerrainImporterCfg
from .interactive_scene_cfg import InteractiveSceneCfg
class InteractiveScene:
"""A scene that contains entities added to the simulation.
The interactive scene parses the :class:`InteractiveSceneCfg` class to create the scene.
Based on the specified number of environments, it clones the entities and groups them into different
categories (e.g., articulations, sensors, etc.).
Each entity is registered to scene based on its name in the configuration class. For example, if the user
specifies a robot in the configuration class as follows:
.. code-block:: python
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_assets.anymal import ANYMAL_C_CFG
@configclass
class MySceneCfg(InteractiveSceneCfg):
robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
Then the robot can be accessed from the scene as follows:
.. code-block:: python
from omni.isaac.orbit.scene import InteractiveScene
# create 128 environments
scene = InteractiveScene(cfg=MySceneCfg(num_envs=128))
# access the robot from the scene
robot = scene["robot"]
# access the robot based on its type
robot = scene.articulations["robot"]
.. note::
It is important to note that the scene only performs common operations on the entities. For example,
resetting the internal buffers, writing the buffers to the simulation and updating the buffers from the
simulation. The scene does not perform any task specific to the entity. For example, it does not apply
actions to the robot or compute observations from the robot. These tasks are handled by different
modules called "managers" in the framework. Please refer to the :mod:`omni.isaac.orbit.managers` sub-package
for more details.
"""
def __init__(self, cfg: InteractiveSceneCfg):
"""Initializes the scene.
Args:
cfg: The configuration class for the scene.
"""
# store inputs
self.cfg = cfg
# initialize scene elements
self._terrain = None
self._articulations = dict()
self._rigid_objects = dict()
self._sensors = dict()
self._extras = dict()
# obtain the current stage
self.stage = omni.usd.get_context().get_stage()
# prepare cloner for environment replication
self.cloner = GridCloner(spacing=self.cfg.env_spacing)
self.cloner.define_base_env(self.env_ns)
self.env_prim_paths = self.cloner.generate_paths(f"{self.env_ns}/env", self.cfg.num_envs)
# create source prim
self.stage.DefinePrim(self.env_prim_paths[0], "Xform")
# clone the env xform
env_origins = self.cloner.clone(
source_prim_path=self.env_prim_paths[0],
prim_paths=self.env_prim_paths,
replicate_physics=False,
copy_from_source=True,
)
self._default_env_origins = torch.tensor(env_origins, device=self.device, dtype=torch.float32)
# add entities from config
self._add_entities_from_cfg()
# replicate physics if we have more than one environment
# this is done to make scene initialization faster at play time
if self.cfg.replicate_physics and self.cfg.num_envs > 1:
self.cloner.replicate_physics(
source_prim_path=self.env_prim_paths[0],
prim_paths=self.env_prim_paths,
base_env_path=self.env_ns,
root_path=self.env_regex_ns.replace(".*", ""),
)
# obtain the current physics scene
physics_scene_prim_path = None
for prim in self.stage.Traverse():
if prim.HasAPI(PhysxSchema.PhysxSceneAPI):
physics_scene_prim_path = prim.GetPrimPath()
carb.log_info(f"Physics scene prim path: {physics_scene_prim_path}")
break
# filter collisions within each environment instance
self.cloner.filter_collisions(
physics_scene_prim_path,
"/World/collisions",
self.env_prim_paths,
global_paths=self._global_prim_paths,
)
def __str__(self) -> str:
"""Returns a string representation of the scene."""
msg = f"<class {self.__class__.__name__}>\n"
msg += f"\tNumber of environments: {self.cfg.num_envs}\n"
msg += f"\tEnvironment spacing : {self.cfg.env_spacing}\n"
msg += f"\tSource prim name : {self.env_prim_paths[0]}\n"
msg += f"\tGlobal prim paths : {self._global_prim_paths}\n"
msg += f"\tReplicate physics : {self.cfg.replicate_physics}"
return msg
"""
Properties.
"""
@property
def physics_dt(self) -> float:
"""The physics timestep of the scene."""
return sim_utils.SimulationContext.instance().get_physics_dt() # pyright: ignore [reportOptionalMemberAccess]
@property
def device(self) -> str:
"""The device on which the scene is created."""
return sim_utils.SimulationContext.instance().device # pyright: ignore [reportOptionalMemberAccess]
@property
def env_ns(self) -> str:
"""The namespace ``/World/envs`` in which all environments created.
The environments are present w.r.t. this namespace under "env_{N}" prim,
where N is a natural number.
"""
return "/World/envs"
@property
def env_regex_ns(self) -> str:
"""The namespace ``/World/envs/env_.*`` in which all environments created."""
return f"{self.env_ns}/env_.*"
@property
def num_envs(self) -> int:
"""The number of environments handled by the scene."""
return self.cfg.num_envs
@property
def env_origins(self) -> torch.Tensor:
"""The origins of the environments in the scene. Shape is (num_envs, 3)."""
if self._terrain is not None:
return self._terrain.env_origins
else:
return self._default_env_origins
@property
def terrain(self) -> TerrainImporter | None:
"""The terrain in the scene. If None, then the scene has no terrain.
Note:
We treat terrain separate from :attr:`extras` since terrains define environment origins and are
handled differently from other miscellaneous entities.
"""
return self._terrain
@property
def articulations(self) -> dict[str, Articulation]:
"""A dictionary of articulations in the scene."""
return self._articulations
@property
def rigid_objects(self) -> dict[str, RigidObject]:
"""A dictionary of rigid objects in the scene."""
return self._rigid_objects
@property
def sensors(self) -> dict[str, SensorBase]:
"""A dictionary of the sensors in the scene, such as cameras and contact reporters."""
return self._sensors
@property
def extras(self) -> dict[str, XFormPrimView]:
"""A dictionary of miscellaneous simulation objects that neither inherit from assets nor sensors.
The keys are the names of the miscellaneous objects, and the values are the `XFormPrimView`_
of the corresponding prims.
As an example, lights or other props in the scene that do not have any attributes or properties that you
want to alter at runtime can be added to this dictionary.
Note:
These are not reset or updated by the scene. They are mainly other prims that are not necessarily
handled by the interactive scene, but are useful to be accessed by the user.
.. _XFormPrimView: https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.core/docs/index.html#omni.isaac.core.prims.XFormPrimView
"""
return self._extras
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None):
"""Resets the scene entities.
Args:
env_ids: The indices of the environments to reset.
Defaults to None (all instances).
"""
# -- assets
for articulation in self._articulations.values():
articulation.reset(env_ids)
for rigid_object in self._rigid_objects.values():
rigid_object.reset(env_ids)
# -- sensors
for sensor in self._sensors.values():
sensor.reset(env_ids)
# -- flush physics sim view if called in extension mode
# this is needed when using PhysX GPU pipeline since the data needs to be sent to the underlying
# PhysX buffers that might live on a separate device
# note: In standalone mode, this method is called in the `step()` method of the simulation context.
# So we only need to flush when running in extension mode.
if builtins.ISAAC_LAUNCHED_FROM_TERMINAL:
sim_utils.SimulationContext.instance().physics_sim_view.flush() # pyright: ignore [reportOptionalMemberAccess]
def write_data_to_sim(self):
"""Writes the data of the scene entities to the simulation."""
# -- assets
for articulation in self._articulations.values():
articulation.write_data_to_sim()
for rigid_object in self._rigid_objects.values():
rigid_object.write_data_to_sim()
# -- flush physics sim view if called in extension mode
# this is needed when using PhysX GPU pipeline since the data needs to be sent to the underlying
# PhysX buffers that might live on a separate device
# note: In standalone mode, this method is called in the `step()` method of the simulation context.
# So we only need to flush when running in extension mode.
if builtins.ISAAC_LAUNCHED_FROM_TERMINAL:
sim_utils.SimulationContext.instance().physics_sim_view.flush() # pyright: ignore [reportOptionalMemberAccess]
def update(self, dt: float) -> None:
"""Update the scene entities.
Args:
dt: The amount of time passed from last :meth:`update` call.
"""
# -- assets
for articulation in self._articulations.values():
articulation.update(dt)
for rigid_object in self._rigid_objects.values():
rigid_object.update(dt)
# -- sensors
for sensor in self._sensors.values():
sensor.update(dt, force_recompute=not self.cfg.lazy_sensor_update)
"""
Operations: Iteration.
"""
def keys(self) -> list[str]:
"""Returns the keys of the scene entities.
Returns:
The keys of the scene entities.
"""
all_keys = ["terrain"]
for asset_family in [self._articulations, self._rigid_objects, self._sensors, self._extras]:
all_keys += list(asset_family.keys())
return all_keys
def __getitem__(self, key: str) -> Any:
"""Returns the scene entity with the given key.
Args:
key: The key of the scene entity.
Returns:
The scene entity.
"""
# check if it is a terrain
if key == "terrain":
return self._terrain
all_keys = ["terrain"]
# check if it is in other dictionaries
for asset_family in [self._articulations, self._rigid_objects, self._sensors, self._extras]:
out = asset_family.get(key)
# if found, return
if out is not None:
return out
all_keys += list(asset_family.keys())
# if not found, raise error
raise KeyError(f"Scene entity with key '{key}' not found. Available Entities: '{all_keys}'")
"""
Internal methods.
"""
def _add_entities_from_cfg(self):
"""Add scene entities from the config."""
# store paths that are in global collision filter
self._global_prim_paths = list()
# parse the entire scene config and resolve regex
for asset_name, asset_cfg in self.cfg.__dict__.items():
# skip keywords
# note: easier than writing a list of keywords: [num_envs, env_spacing, lazy_sensor_update]
if asset_name in InteractiveSceneCfg.__dataclass_fields__ or asset_cfg is None:
continue
# resolve regex
asset_cfg.prim_path = asset_cfg.prim_path.format(ENV_REGEX_NS=self.env_regex_ns)
# create asset
if isinstance(asset_cfg, TerrainImporterCfg):
# terrains are special entities since they define environment origins
asset_cfg.num_envs = self.cfg.num_envs
asset_cfg.env_spacing = self.cfg.env_spacing
self._terrain = asset_cfg.class_type(asset_cfg)
elif isinstance(asset_cfg, ArticulationCfg):
self._articulations[asset_name] = asset_cfg.class_type(asset_cfg)
elif isinstance(asset_cfg, RigidObjectCfg):
self._rigid_objects[asset_name] = asset_cfg.class_type(asset_cfg)
elif isinstance(asset_cfg, SensorBaseCfg):
# Update target frame path(s)' regex name space for FrameTransformer
if isinstance(asset_cfg, FrameTransformerCfg):
updated_target_frames = []
for target_frame in asset_cfg.target_frames:
target_frame.prim_path = target_frame.prim_path.format(ENV_REGEX_NS=self.env_regex_ns)
updated_target_frames.append(target_frame)
asset_cfg.target_frames = updated_target_frames
elif isinstance(asset_cfg, ContactSensorCfg):
updated_filter_prim_paths_expr = []
for filter_prim_path in asset_cfg.filter_prim_paths_expr:
updated_filter_prim_paths_expr.append(filter_prim_path.format(ENV_REGEX_NS=self.env_regex_ns))
asset_cfg.filter_prim_paths_expr = updated_filter_prim_paths_expr
self._sensors[asset_name] = asset_cfg.class_type(asset_cfg)
elif isinstance(asset_cfg, AssetBaseCfg):
# manually spawn asset
if asset_cfg.spawn is not None:
asset_cfg.spawn.func(
asset_cfg.prim_path,
asset_cfg.spawn,
translation=asset_cfg.init_state.pos,
orientation=asset_cfg.init_state.rot,
)
# store xform prim view corresponding to this asset
# all prims in the scene are Xform prims (i.e. have a transform component)
self._extras[asset_name] = XFormPrimView(asset_cfg.prim_path, reset_xform_properties=False)
else:
raise ValueError(f"Unknown asset config type for {asset_name}: {asset_cfg}")
# store global collision paths
if hasattr(asset_cfg, "collision_group") and asset_cfg.collision_group == -1:
asset_paths = sim_utils.find_matching_prim_paths(asset_cfg.prim_path)
self._global_prim_paths += asset_paths
| 15,934 | Python | 41.380319 | 158 | 0.625518 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/scene/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package containing an interactive scene definition.
A scene is a collection of entities (e.g., terrain, articulations, sensors, lights, etc.) that can be added to the
simulation. However, only a subset of these entities are of direct interest for the user to interact with.
For example, the user may want to interact with a robot in the scene, but not with the terrain or the lights.
For this reason, we integrate the different entities into a single class called :class:`InteractiveScene`.
The interactive scene performs the following tasks:
1. It parses the configuration class :class:`InteractiveSceneCfg` to create the scene. This configuration class is
inherited by the user to add entities to the scene.
2. It clones the entities based on the number of environments specified by the user.
3. It clubs the entities into different groups based on their type (e.g., articulations, sensors, etc.).
4. It provides a set of methods to unify the common operations on the entities in the scene (e.g., resetting internal
buffers, writing buffers to simulation and updating buffers from simulation).
The interactive scene can be passed around to different modules in the framework to perform different tasks.
For instance, computing the observations based on the state of the scene, or randomizing the scene, or applying
actions to the scene. All these are handled by different "managers" in the framework. Please refer to the
:mod:`omni.isaac.orbit.managers` sub-package for more details.
"""
from .interactive_scene import InteractiveScene
from .interactive_scene_cfg import InteractiveSceneCfg
| 1,734 | Python | 56.833331 | 117 | 0.790657 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/terrain_generator_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Configuration classes defining the different terrains available. Each configuration class must
inherit from ``omni.isaac.orbit.terrains.terrains_cfg.TerrainConfig`` and define the following attributes:
- ``name``: Name of the terrain. This is used for the prim name in the USD stage.
- ``function``: Function to generate the terrain. This function must take as input the terrain difficulty
and the configuration parameters and return a `tuple with the `trimesh`` mesh object and terrain origin.
"""
from __future__ import annotations
import numpy as np
import trimesh
from collections.abc import Callable
from dataclasses import MISSING
from typing import Literal
from omni.isaac.orbit.utils import configclass
@configclass
class FlatPatchSamplingCfg:
"""Configuration for sampling flat patches on the sub-terrain.
For a given sub-terrain, this configuration specifies how to sample flat patches on the terrain.
The sampled flat patches can be used for spawning robots, targets, etc.
Please check the function :meth:`~omni.isaac.orbit.terrains.utils.find_flat_patches` for more details.
"""
num_patches: int = MISSING
"""Number of patches to sample."""
patch_radius: float | list[float] = MISSING
"""Radius of the patches.
A list of radii can be provided to check for patches of different sizes. This is useful to deal with
cases where the terrain may have holes or obstacles in some areas.
"""
x_range: tuple[float, float] = (-1e6, 1e6)
"""The range of x-coordinates to sample from. Defaults to (-1e6, 1e6).
This range is internally clamped to the size of the terrain mesh.
"""
y_range: tuple[float, float] = (-1e6, 1e6)
"""The range of y-coordinates to sample from. Defaults to (-1e6, 1e6).
This range is internally clamped to the size of the terrain mesh.
"""
z_range: tuple[float, float] = (-1e6, 1e6)
"""Allowed range of z-coordinates for the sampled patch. Defaults to (-1e6, 1e6)."""
max_height_diff: float = MISSING
"""Maximum allowed height difference between the highest and lowest points on the patch."""
@configclass
class SubTerrainBaseCfg:
"""Base class for terrain configurations.
All the sub-terrain configurations must inherit from this class.
The :attr:`size` attribute is the size of the generated sub-terrain. Based on this, the terrain must
extend from :math:`(0, 0)` to :math:`(size[0], size[1])`.
"""
function: Callable[[float, SubTerrainBaseCfg], tuple[list[trimesh.Trimesh], np.ndarray]] = MISSING
"""Function to generate the terrain.
This function must take as input the terrain difficulty and the configuration parameters and
return a tuple with a list of ``trimesh`` mesh objects and the terrain origin.
"""
proportion: float = 1.0
"""Proportion of the terrain to generate. Defaults to 1.0.
This is used to generate a mix of terrains. The proportion corresponds to the probability of sampling
the particular terrain. For example, if there are two terrains, A and B, with proportions 0.3 and 0.7,
respectively, then the probability of sampling terrain A is 0.3 and the probability of sampling terrain B
is 0.7.
"""
size: tuple[float, float] = MISSING
"""The width (along x) and length (along y) of the terrain (in m)."""
flat_patch_sampling: dict[str, FlatPatchSamplingCfg] | None = None
"""Dictionary of configurations for sampling flat patches on the sub-terrain. Defaults to None,
in which case no flat patch sampling is performed.
The keys correspond to the name of the flat patch sampling configuration and the values are the
corresponding configurations.
"""
@configclass
class TerrainGeneratorCfg:
"""Configuration for the terrain generator."""
seed: int | None = None
"""The seed for the random number generator. Defaults to None,
in which case the seed is not set."""
curriculum: bool = False
"""Whether to use the curriculum mode. Defaults to False.
If True, the terrains are generated based on their difficulty parameter. Otherwise,
they are randomly generated.
"""
size: tuple[float, float] = MISSING
"""The width (along x) and length (along y) of each sub-terrain (in m).
Note:
This value is passed on to all the sub-terrain configurations.
"""
border_width: float = 0.0
"""The width of the border around the terrain (in m). Defaults to 0.0."""
num_rows: int = 1
"""Number of rows of sub-terrains to generate. Defaults to 1."""
num_cols: int = 1
"""Number of columns of sub-terrains to generate. Defaults to 1."""
color_scheme: Literal["height", "random", "none"] = "none"
"""Color scheme to use for the terrain. Defaults to "none".
The available color schemes are:
- "height": Color based on the height of the terrain.
- "random": Random color scheme.
- "none": No color scheme.
"""
horizontal_scale: float = 0.1
"""The discretization of the terrain along the x and y axes (in m). Defaults to 0.1.
This value is passed on to all the height field sub-terrain configurations.
"""
vertical_scale: float = 0.005
"""The discretization of the terrain along the z axis (in m). Defaults to 0.005.
This value is passed on to all the height field sub-terrain configurations.
"""
slope_threshold: float | None = 0.75
"""The slope threshold above which surfaces are made vertical. Defaults to 0.75.
If None no correction is applied.
This value is passed on to all the height field sub-terrain configurations.
"""
sub_terrains: dict[str, SubTerrainBaseCfg] = MISSING
"""Dictionary of sub-terrain configurations.
The keys correspond to the name of the sub-terrain configuration and the values are the corresponding
configurations.
"""
difficulty_range: tuple[float, float] = (0.0, 1.0)
"""The range of difficulty values for the sub-terrains. Defaults to (0.0, 1.0).
If curriculum is enabled, the terrains will be generated based on this range in ascending order
of difficulty. Otherwise, the terrains will be generated based on this range in a random order.
"""
use_cache: bool = False
"""Whether to load the terrain from cache if it exists. Defaults to True."""
cache_dir: str = "/tmp/orbit/terrains"
"""The directory where the terrain cache is stored. Defaults to "/tmp/orbit/terrains"."""
| 6,616 | Python | 35.15847 | 109 | 0.702086 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/terrain_importer_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from dataclasses import MISSING
from typing import TYPE_CHECKING, Literal
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.utils import configclass
from .terrain_importer import TerrainImporter
if TYPE_CHECKING:
from .terrain_generator_cfg import TerrainGeneratorCfg
@configclass
class TerrainImporterCfg:
"""Configuration for the terrain manager."""
class_type: type = TerrainImporter
"""The class to use for the terrain importer.
Defaults to :class:`omni.isaac.orbit.terrains.terrain_importer.TerrainImporter`.
"""
collision_group: int = -1
"""The collision group of the terrain. Defaults to -1."""
prim_path: str = MISSING
"""The absolute path of the USD terrain prim.
All sub-terrains are imported relative to this prim path.
"""
num_envs: int = MISSING
"""The number of environment origins to consider."""
terrain_type: Literal["generator", "plane", "usd"] = "generator"
"""The type of terrain to generate. Defaults to "generator".
Available options are "plane", "usd", and "generator".
"""
terrain_generator: TerrainGeneratorCfg | None = None
"""The terrain generator configuration.
Only used if ``terrain_type`` is set to "generator".
"""
usd_path: str | None = None
"""The path to the USD file containing the terrain.
Only used if ``terrain_type`` is set to "usd".
"""
env_spacing: float | None = None
"""The spacing between environment origins when defined in a grid. Defaults to None.
Note:
This parameter is used only when the ``terrain_type`` is ``"plane"`` or ``"usd"``.
"""
visual_material: sim_utils.VisualMaterialCfg | None = sim_utils.PreviewSurfaceCfg(
diffuse_color=(0.065, 0.0725, 0.080)
)
"""The visual material of the terrain. Defaults to a dark gray color material.
The material is created at the path: ``{prim_path}/visualMaterial``. If `None`, then no material is created.
.. note::
This parameter is used only when the ``terrain_type`` is ``"generator"``.
"""
physics_material: sim_utils.RigidBodyMaterialCfg = sim_utils.RigidBodyMaterialCfg()
"""The physics material of the terrain. Defaults to a default physics material.
The material is created at the path: ``{prim_path}/physicsMaterial``.
.. note::
This parameter is used only when the ``terrain_type`` is ``"generator"`` or ``"plane"``.
"""
max_init_terrain_level: int | None = None
"""The maximum initial terrain level for defining environment origins. Defaults to None.
The terrain levels are specified by the number of rows in the grid arrangement of
sub-terrains. If None, then the initial terrain level is set to the maximum
terrain level available (``num_rows - 1``).
Note:
This parameter is used only when sub-terrain origins are defined.
"""
debug_vis: bool = False
"""Whether to enable visualization of terrain origins for the terrain. Defaults to False."""
| 3,187 | Python | 30.88 | 112 | 0.685284 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/terrain_generator.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import numpy as np
import os
import torch
import trimesh
import carb
from omni.isaac.orbit.utils.dict import dict_to_md5_hash
from omni.isaac.orbit.utils.io import dump_yaml
from omni.isaac.orbit.utils.timer import Timer
from omni.isaac.orbit.utils.warp import convert_to_warp_mesh
from .height_field import HfTerrainBaseCfg
from .terrain_generator_cfg import FlatPatchSamplingCfg, SubTerrainBaseCfg, TerrainGeneratorCfg
from .trimesh.utils import make_border
from .utils import color_meshes_by_height, find_flat_patches
class TerrainGenerator:
"""Terrain generator to handle different terrain generation functions.
The terrains are represented as meshes. These are obtained either from height fields or by using the
`trimesh <https://trimsh.org/trimesh.html>`__ library. The height field representation is more
flexible, but it is less computationally and memory efficient than the trimesh representation.
All terrain generation functions take in the argument :obj:`difficulty` which determines the complexity
of the terrain. The difficulty is a number between 0 and 1, where 0 is the easiest and 1 is the hardest.
In most cases, the difficulty is used for linear interpolation between different terrain parameters.
For example, in a pyramid stairs terrain the step height is interpolated between the specified minimum
and maximum step height.
Each sub-terrain has a corresponding configuration class that can be used to specify the parameters
of the terrain. The configuration classes are inherited from the :class:`SubTerrainBaseCfg` class
which contains the common parameters for all terrains.
If a curriculum is used, the terrains are generated based on their difficulty parameter.
The difficulty is varied linearly over the number of rows (i.e. along x). If a curriculum
is not used, the terrains are generated randomly.
If the :obj:`cfg.flat_patch_sampling` is specified for a sub-terrain, flat patches are sampled
on the terrain. These can be used for spawning robots, targets, etc. The sampled patches are stored
in the :obj:`flat_patches` dictionary. The key specifies the intention of the flat patches and the
value is a tensor containing the flat patches for each sub-terrain.
If the flag :obj:`cfg.use_cache` is set to True, the terrains are cached based on their
sub-terrain configurations. This means that if the same sub-terrain configuration is used
multiple times, the terrain is only generated once and then reused. This is useful when
generating complex sub-terrains that take a long time to generate.
"""
terrain_mesh: trimesh.Trimesh
"""A single trimesh.Trimesh object for all the generated sub-terrains."""
terrain_meshes: list[trimesh.Trimesh]
"""List of trimesh.Trimesh objects for all the generated sub-terrains."""
terrain_origins: np.ndarray
"""The origin of each sub-terrain. Shape is (num_rows, num_cols, 3)."""
flat_patches: dict[str, torch.Tensor]
"""A dictionary of sampled valid (flat) patches for each sub-terrain.
The dictionary keys are the names of the flat patch sampling configurations. This maps to a
tensor containing the flat patches for each sub-terrain. The shape of the tensor is
(num_rows, num_cols, num_patches, 3).
For instance, the key "root_spawn" maps to a tensor containing the flat patches for spawning an asset.
Similarly, the key "target_spawn" maps to a tensor containing the flat patches for setting targets.
"""
def __init__(self, cfg: TerrainGeneratorCfg, device: str = "cpu"):
"""Initialize the terrain generator.
Args:
cfg: Configuration for the terrain generator.
device: The device to use for the flat patches tensor.
"""
# check inputs
if len(cfg.sub_terrains) == 0:
raise ValueError("No sub-terrains specified! Please add at least one sub-terrain.")
# store inputs
self.cfg = cfg
self.device = device
# -- valid patches
self.flat_patches = {}
# set common values to all sub-terrains config
for sub_cfg in self.cfg.sub_terrains.values():
# size of all terrains
sub_cfg.size = self.cfg.size
# params for height field terrains
if isinstance(sub_cfg, HfTerrainBaseCfg):
sub_cfg.horizontal_scale = self.cfg.horizontal_scale
sub_cfg.vertical_scale = self.cfg.vertical_scale
sub_cfg.slope_threshold = self.cfg.slope_threshold
# set the seed for reproducibility
if self.cfg.seed is not None:
torch.manual_seed(self.cfg.seed)
np.random.seed(self.cfg.seed)
# create a list of all sub-terrains
self.terrain_meshes = list()
self.terrain_origins = np.zeros((self.cfg.num_rows, self.cfg.num_cols, 3))
# parse configuration and add sub-terrains
# create terrains based on curriculum or randomly
if self.cfg.curriculum:
with Timer("[INFO] Generating terrains based on curriculum took"):
self._generate_curriculum_terrains()
else:
with Timer("[INFO] Generating terrains randomly took"):
self._generate_random_terrains()
# add a border around the terrains
self._add_terrain_border()
# combine all the sub-terrains into a single mesh
self.terrain_mesh = trimesh.util.concatenate(self.terrain_meshes)
# color the terrain mesh
if self.cfg.color_scheme == "height":
self.terrain_mesh = color_meshes_by_height(self.terrain_mesh)
elif self.cfg.color_scheme == "random":
self.terrain_mesh.visual.vertex_colors = np.random.choice(
range(256), size=(len(self.terrain_mesh.vertices), 4)
)
elif self.cfg.color_scheme == "none":
pass
else:
raise ValueError(f"Invalid color scheme: {self.cfg.color_scheme}.")
# offset the entire terrain and origins so that it is centered
# -- terrain mesh
transform = np.eye(4)
transform[:2, -1] = -self.cfg.size[0] * self.cfg.num_rows * 0.5, -self.cfg.size[1] * self.cfg.num_cols * 0.5
self.terrain_mesh.apply_transform(transform)
# -- terrain origins
self.terrain_origins += transform[:3, -1]
# -- valid patches
terrain_origins_torch = torch.tensor(self.terrain_origins, dtype=torch.float, device=self.device).unsqueeze(2)
for name, value in self.flat_patches.items():
self.flat_patches[name] = value + terrain_origins_torch
"""
Terrain generator functions.
"""
def _generate_random_terrains(self):
"""Add terrains based on randomly sampled difficulty parameter."""
# normalize the proportions of the sub-terrains
proportions = np.array([sub_cfg.proportion for sub_cfg in self.cfg.sub_terrains.values()])
proportions /= np.sum(proportions)
# create a list of all terrain configs
sub_terrains_cfgs = list(self.cfg.sub_terrains.values())
# randomly sample sub-terrains
for index in range(self.cfg.num_rows * self.cfg.num_cols):
# coordinate index of the sub-terrain
(sub_row, sub_col) = np.unravel_index(index, (self.cfg.num_rows, self.cfg.num_cols))
# randomly sample terrain index
sub_index = np.random.choice(len(proportions), p=proportions)
# randomly sample difficulty parameter
difficulty = np.random.uniform(*self.cfg.difficulty_range)
# generate terrain
mesh, origin = self._get_terrain_mesh(difficulty, sub_terrains_cfgs[sub_index])
# add to sub-terrains
self._add_sub_terrain(mesh, origin, sub_row, sub_col, sub_terrains_cfgs[sub_index])
def _generate_curriculum_terrains(self):
"""Add terrains based on the difficulty parameter."""
# normalize the proportions of the sub-terrains
proportions = np.array([sub_cfg.proportion for sub_cfg in self.cfg.sub_terrains.values()])
proportions /= np.sum(proportions)
# find the sub-terrain index for each column
# we generate the terrains based on their proportion (not randomly sampled)
sub_indices = []
for index in range(self.cfg.num_cols):
sub_index = np.min(np.where(index / self.cfg.num_cols + 0.001 < np.cumsum(proportions))[0])
sub_indices.append(sub_index)
sub_indices = np.array(sub_indices, dtype=np.int32)
# create a list of all terrain configs
sub_terrains_cfgs = list(self.cfg.sub_terrains.values())
# curriculum-based sub-terrains
for sub_col in range(self.cfg.num_cols):
for sub_row in range(self.cfg.num_rows):
# vary the difficulty parameter linearly over the number of rows
lower, upper = self.cfg.difficulty_range
difficulty = (sub_row + np.random.uniform()) / self.cfg.num_rows
difficulty = lower + (upper - lower) * difficulty
# generate terrain
mesh, origin = self._get_terrain_mesh(difficulty, sub_terrains_cfgs[sub_indices[sub_col]])
# add to sub-terrains
self._add_sub_terrain(mesh, origin, sub_row, sub_col, sub_terrains_cfgs[sub_indices[sub_col]])
"""
Internal helper functions.
"""
def _add_terrain_border(self):
"""Add a surrounding border over all the sub-terrains into the terrain meshes."""
# border parameters
border_size = (
self.cfg.num_rows * self.cfg.size[0] + 2 * self.cfg.border_width,
self.cfg.num_cols * self.cfg.size[1] + 2 * self.cfg.border_width,
)
inner_size = (self.cfg.num_rows * self.cfg.size[0], self.cfg.num_cols * self.cfg.size[1])
border_center = (self.cfg.num_rows * self.cfg.size[0] / 2, self.cfg.num_cols * self.cfg.size[1] / 2, -0.5)
# border mesh
border_meshes = make_border(border_size, inner_size, height=1.0, position=border_center)
border = trimesh.util.concatenate(border_meshes)
# update the faces to have minimal triangles
selector = ~(np.asarray(border.triangles)[:, :, 2] < -0.1).any(1)
border.update_faces(selector)
# add the border to the list of meshes
self.terrain_meshes.append(border)
def _add_sub_terrain(
self, mesh: trimesh.Trimesh, origin: np.ndarray, row: int, col: int, sub_terrain_cfg: SubTerrainBaseCfg
):
"""Add input sub-terrain to the list of sub-terrains.
This function adds the input sub-terrain mesh to the list of sub-terrains and updates the origin
of the sub-terrain in the list of origins. It also samples flat patches if specified.
Args:
mesh: The mesh of the sub-terrain.
origin: The origin of the sub-terrain.
row: The row index of the sub-terrain.
col: The column index of the sub-terrain.
"""
# sample flat patches if specified
if sub_terrain_cfg.flat_patch_sampling is not None:
carb.log_info(f"Sampling flat patches for sub-terrain at (row, col): ({row}, {col})")
# convert the mesh to warp mesh
wp_mesh = convert_to_warp_mesh(mesh.vertices, mesh.faces, device=self.device)
# sample flat patches based on each patch configuration for that sub-terrain
for name, patch_cfg in sub_terrain_cfg.flat_patch_sampling.items():
patch_cfg: FlatPatchSamplingCfg
# create the flat patches tensor (if not already created)
if name not in self.flat_patches:
self.flat_patches[name] = torch.zeros(
(self.cfg.num_rows, self.cfg.num_cols, patch_cfg.num_patches, 3), device=self.device
)
# add the flat patches to the tensor
self.flat_patches[name][row, col] = find_flat_patches(
wp_mesh=wp_mesh,
origin=origin,
num_patches=patch_cfg.num_patches,
patch_radius=patch_cfg.patch_radius,
x_range=patch_cfg.x_range,
y_range=patch_cfg.y_range,
z_range=patch_cfg.z_range,
max_height_diff=patch_cfg.max_height_diff,
)
# transform the mesh to the correct position
transform = np.eye(4)
transform[0:2, -1] = (row + 0.5) * self.cfg.size[0], (col + 0.5) * self.cfg.size[1]
mesh.apply_transform(transform)
# add mesh to the list
self.terrain_meshes.append(mesh)
# add origin to the list
self.terrain_origins[row, col] = origin + transform[:3, -1]
def _get_terrain_mesh(self, difficulty: float, cfg: SubTerrainBaseCfg) -> tuple[trimesh.Trimesh, np.ndarray]:
"""Generate a sub-terrain mesh based on the input difficulty parameter.
If caching is enabled, the sub-terrain is cached and loaded from the cache if it exists.
The cache is stored in the cache directory specified in the configuration.
.. Note:
This function centers the 2D center of the mesh and its specified origin such that the
2D center becomes :math:`(0, 0)` instead of :math:`(size[0] / 2, size[1] / 2).
Args:
difficulty: The difficulty parameter.
cfg: The configuration of the sub-terrain.
Returns:
The sub-terrain mesh and origin.
"""
# add other parameters to the sub-terrain configuration
cfg.difficulty = float(difficulty)
cfg.seed = self.cfg.seed
# generate hash for the sub-terrain
sub_terrain_hash = dict_to_md5_hash(cfg.to_dict())
# generate the file name
sub_terrain_cache_dir = os.path.join(self.cfg.cache_dir, sub_terrain_hash)
sub_terrain_stl_filename = os.path.join(sub_terrain_cache_dir, "mesh.stl")
sub_terrain_csv_filename = os.path.join(sub_terrain_cache_dir, "origin.csv")
sub_terrain_meta_filename = os.path.join(sub_terrain_cache_dir, "cfg.yaml")
# check if hash exists - if true, load the mesh and origin and return
if self.cfg.use_cache and os.path.exists(sub_terrain_stl_filename):
# load existing mesh
mesh = trimesh.load_mesh(sub_terrain_stl_filename)
origin = np.loadtxt(sub_terrain_csv_filename, delimiter=",")
# return the generated mesh
return mesh, origin
# generate the terrain
meshes, origin = cfg.function(difficulty, cfg)
mesh = trimesh.util.concatenate(meshes)
# offset mesh such that they are in their center
transform = np.eye(4)
transform[0:2, -1] = -cfg.size[0] * 0.5, -cfg.size[1] * 0.5
mesh.apply_transform(transform)
# change origin to be in the center of the sub-terrain
origin += transform[0:3, -1]
# if caching is enabled, save the mesh and origin
if self.cfg.use_cache:
# create the cache directory
os.makedirs(sub_terrain_cache_dir, exist_ok=True)
# save the data
mesh.export(sub_terrain_stl_filename)
np.savetxt(sub_terrain_csv_filename, origin, delimiter=",", header="x,y,z")
dump_yaml(sub_terrain_meta_filename, cfg)
# return the generated mesh
return mesh, origin
| 15,745 | Python | 47.900621 | 118 | 0.644268 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package with utilities for creating terrains procedurally.
There are two main components in this package:
* :class:`TerrainGenerator`: This class procedurally generates terrains based on the passed
sub-terrain configuration. It creates a ``trimesh`` mesh object and contains the origins of
each generated sub-terrain.
* :class:`TerrainImporter`: This class mainly deals with importing terrains from different
possible sources and adding them to the simulator as a prim object. It also stores the
terrain mesh into a dictionary called :obj:`TerrainImporter.warp_meshes` that later can be used
for ray-casting. The following functions are available for importing terrains:
* :meth:`TerrainImporter.import_ground_plane`: spawn a grid plane which is default in isaacsim/orbit.
* :meth:`TerrainImporter.import_mesh`: spawn a prim from a ``trimesh`` object.
* :meth:`TerrainImporter.import_usd`: spawn a prim as reference to input USD file.
"""
from .height_field import * # noqa: F401, F403
from .terrain_generator import TerrainGenerator
from .terrain_generator_cfg import FlatPatchSamplingCfg, SubTerrainBaseCfg, TerrainGeneratorCfg
from .terrain_importer import TerrainImporter
from .terrain_importer_cfg import TerrainImporterCfg
from .trimesh import * # noqa: F401, F403
from .utils import color_meshes_by_height, create_prim_from_mesh
| 1,489 | Python | 47.064515 | 103 | 0.785091 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/utils.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# needed to import for allowing type-hinting: np.ndarray | torch.Tensor | None
from __future__ import annotations
import numpy as np
import torch
import trimesh
import warp as wp
from omni.isaac.orbit.utils.warp import raycast_mesh
def color_meshes_by_height(meshes: list[trimesh.Trimesh], **kwargs) -> trimesh.Trimesh:
"""
Color the vertices of a trimesh object based on the z-coordinate (height) of each vertex,
using the Turbo colormap. If the z-coordinates are all the same, the vertices will be colored
with a single color.
Args:
meshes: A list of trimesh objects.
Keyword Args:
color: A list of 3 integers in the range [0,255] representing the RGB
color of the mesh. Used when the z-coordinates of all vertices are the same.
color_map: The name of the color map to be used. Defaults to "turbo".
Returns:
A trimesh object with the vertices colored based on the z-coordinate (height) of each vertex.
"""
# Combine all meshes into a single mesh
mesh = trimesh.util.concatenate(meshes)
# Get the z-coordinates of each vertex
heights = mesh.vertices[:, 2]
# Check if the z-coordinates are all the same
if np.max(heights) == np.min(heights):
# Obtain a single color: light blue
color = kwargs.pop("color", [172, 216, 230, 255])
color = np.asarray(color, dtype=np.uint8)
# Set the color for all vertices
mesh.visual.vertex_colors = color
else:
# Normalize the heights to [0,1]
heights_normalized = (heights - np.min(heights)) / (np.max(heights) - np.min(heights))
# clip lower and upper bounds to have better color mapping
heights_normalized = np.clip(heights_normalized, 0.1, 0.9)
# Get the color for each vertex based on the height
color_map = kwargs.pop("color_map", "turbo")
colors = trimesh.visual.color.interpolate(heights_normalized, color_map=color_map)
# Set the vertex colors
mesh.visual.vertex_colors = colors
# Return the mesh
return mesh
def create_prim_from_mesh(prim_path: str, mesh: trimesh.Trimesh, **kwargs):
"""Create a USD prim with mesh defined from vertices and triangles.
The function creates a USD prim with a mesh defined from vertices and triangles. It performs the
following steps:
- Create a USD Xform prim at the path :obj:`prim_path`.
- Create a USD prim with a mesh defined from the input vertices and triangles at the path :obj:`{prim_path}/mesh`.
- Assign a physics material to the mesh at the path :obj:`{prim_path}/physicsMaterial`.
- Assign a visual material to the mesh at the path :obj:`{prim_path}/visualMaterial`.
Args:
prim_path: The path to the primitive to be created.
mesh: The mesh to be used for the primitive.
Keyword Args:
translation: The translation of the terrain. Defaults to None.
orientation: The orientation of the terrain. Defaults to None.
visual_material: The visual material to apply. Defaults to None.
physics_material: The physics material to apply. Defaults to None.
"""
# need to import these here to prevent isaacsim launching when importing this module
import omni.isaac.core.utils.prims as prim_utils
from pxr import UsdGeom
import omni.isaac.orbit.sim as sim_utils
# create parent prim
prim_utils.create_prim(prim_path, "Xform")
# create mesh prim
prim = prim_utils.create_prim(
f"{prim_path}/mesh",
"Mesh",
translation=kwargs.get("translation"),
orientation=kwargs.get("orientation"),
attributes={
"points": mesh.vertices,
"faceVertexIndices": mesh.faces.flatten(),
"faceVertexCounts": np.asarray([3] * len(mesh.faces)),
"subdivisionScheme": "bilinear",
},
)
# apply collider properties
collider_cfg = sim_utils.CollisionPropertiesCfg(collision_enabled=True)
sim_utils.define_collision_properties(prim.GetPrimPath(), collider_cfg)
# add rgba color to the mesh primvars
if mesh.visual.vertex_colors is not None:
# obtain color from the mesh
rgba_colors = np.asarray(mesh.visual.vertex_colors).astype(np.float32) / 255.0
# displayColor is a primvar attribute that is used to color the mesh
color_prim_attr = prim.GetAttribute("primvars:displayColor")
color_prim_var = UsdGeom.Primvar(color_prim_attr)
color_prim_var.SetInterpolation(UsdGeom.Tokens.vertex)
color_prim_attr.Set(rgba_colors[:, :3])
# displayOpacity is a primvar attribute that is used to set the opacity of the mesh
display_prim_attr = prim.GetAttribute("primvars:displayOpacity")
display_prim_var = UsdGeom.Primvar(display_prim_attr)
display_prim_var.SetInterpolation(UsdGeom.Tokens.vertex)
display_prim_var.Set(rgba_colors[:, 3])
# create visual material
if kwargs.get("visual_material") is not None:
visual_material_cfg: sim_utils.VisualMaterialCfg = kwargs.get("visual_material")
# spawn the material
visual_material_cfg.func(f"{prim_path}/visualMaterial", visual_material_cfg)
sim_utils.bind_visual_material(prim.GetPrimPath(), f"{prim_path}/visualMaterial")
# create physics material
if kwargs.get("physics_material") is not None:
physics_material_cfg: sim_utils.RigidBodyMaterialCfg = kwargs.get("physics_material")
# spawn the material
physics_material_cfg.func(f"{prim_path}/physicsMaterial", physics_material_cfg)
sim_utils.bind_physics_material(prim.GetPrimPath(), f"{prim_path}/physicsMaterial")
def find_flat_patches(
wp_mesh: wp.Mesh,
num_patches: int,
patch_radius: float | list[float],
origin: np.ndarray | torch.Tensor | tuple[float, float, float],
x_range: tuple[float, float],
y_range: tuple[float, float],
z_range: tuple[float, float],
max_height_diff: float,
):
"""Finds flat patches of given radius in the input mesh.
The function finds flat patches of given radius based on the search space defined by the input ranges.
The search space is characterized by origin in the mesh frame, and the x, y, and z ranges. The x and y
ranges are used to sample points in the 2D region around the origin, and the z range is used to filter
patches based on the height of the points.
The function performs rejection sampling to find the patches based on the following steps:
1. Sample patch locations in the 2D region around the origin.
2. Define a ring of points around each patch location to query the height of the points using ray-casting.
3. Reject patches that are outside the z range or have a height difference that is too large.
4. Keep sampling until all patches are valid.
Args:
wp_mesh: The warp mesh to find patches in.
num_patches: The desired number of patches to find.
patch_radius: The radii used to form patches. If a list is provided, multiple patch sizes are checked.
This is useful to deal with holes or other artifacts in the mesh.
origin: The origin defining the center of the search space. This is specified in the mesh frame.
x_range: The range of X coordinates to sample from.
y_range: The range of Y coordinates to sample from.
z_range: The range of valid Z coordinates used for filtering patches.
max_height_diff: The maximum allowable distance between the lowest and highest points
on a patch to consider it as valid. If the difference is greater than this value,
the patch is rejected.
Returns:
A tensor of shape (num_patches, 3) containing the flat patches. The patches are defined in the mesh frame.
Raises:
RuntimeError: If the function fails to find valid patches. This can happen if the input parameters
are not suitable for finding valid patches and maximum number of iterations is reached.
"""
# set device to warp mesh device
device = wp.device_to_torch(wp_mesh.device)
# resolve inputs to consistent type
# -- patch radii
if isinstance(patch_radius, float):
patch_radius = [patch_radius]
# -- origin
if isinstance(origin, np.ndarray):
origin = torch.from_numpy(origin).to(torch.float).to(device)
elif isinstance(origin, torch.Tensor):
origin = origin.to(device)
else:
origin = torch.tensor(origin, dtype=torch.float, device=device)
# create ranges for the x and y coordinates around the origin.
# The provided ranges are bounded by the mesh's bounding box.
x_range = (
max(x_range[0] + origin[0].item(), wp_mesh.points.numpy()[:, 0].min()),
min(x_range[1] + origin[0].item(), wp_mesh.points.numpy()[:, 0].max()),
)
y_range = (
max(y_range[0] + origin[1].item(), wp_mesh.points.numpy()[:, 1].min()),
min(y_range[1] + origin[1].item(), wp_mesh.points.numpy()[:, 1].max()),
)
z_range = (
z_range[0] + origin[2].item(),
z_range[1] + origin[2].item(),
)
# create a circle of points around (0, 0) to query validity of the patches
# the ring of points is uniformly distributed around the circle
angle = torch.linspace(0, 2 * np.pi, 10, device=device)
query_x = []
query_y = []
for radius in patch_radius:
query_x.append(radius * torch.cos(angle))
query_y.append(radius * torch.sin(angle))
query_x = torch.cat(query_x).unsqueeze(1) # dim: (num_radii * 10, 1)
query_y = torch.cat(query_y).unsqueeze(1) # dim: (num_radii * 10, 1)
# dim: (num_radii * 10, 3)
query_points = torch.cat([query_x, query_y, torch.zeros_like(query_x)], dim=-1)
# create buffers
# -- a buffer to store indices of points that are not valid
points_ids = torch.arange(num_patches, device=device)
# -- a buffer to store the flat patches locations
flat_patches = torch.zeros(num_patches, 3, device=device)
# sample points and raycast to find the height.
# 1. Reject points that are outside the z_range or have a height difference that is too large.
# 2. Keep sampling until all points are valid.
iter_count = 0
while len(points_ids) > 0 and iter_count < 10000:
# sample points in the 2D region around the origin
pos_x = torch.empty(len(points_ids), device=device).uniform_(*x_range)
pos_y = torch.empty(len(points_ids), device=device).uniform_(*y_range)
flat_patches[points_ids, :2] = torch.stack([pos_x, pos_y], dim=-1)
# define the query points to check validity of the patch
# dim: (num_patches, num_radii * 10, 3)
points = flat_patches[points_ids].unsqueeze(1) + query_points
points[..., 2] = 100.0
# ray-cast direction is downwards
dirs = torch.zeros_like(points)
dirs[..., 2] = -1.0
# ray-cast to find the height of the patches
ray_hits = raycast_mesh(points.view(-1, 3), dirs.view(-1, 3), wp_mesh)[0]
heights = ray_hits.view(points.shape)[..., 2]
# set the height of the patches
# note: for invalid patches, they would be overwritten in the next iteration
# so it's safe to set the height to the last value
flat_patches[points_ids, 2] = heights[..., -1]
# check validity
# -- height is within the z range
not_valid = torch.any(torch.logical_or(heights < z_range[0], heights > z_range[1]), dim=1)
# -- height difference is within the max height difference
not_valid = torch.logical_or(not_valid, (heights.max(dim=1)[0] - heights.min(dim=1)[0]) > max_height_diff)
# remove invalid patches indices
points_ids = points_ids[not_valid]
# increment count
iter_count += 1
# check all patches are valid
if len(points_ids) > 0:
raise RuntimeError(
"Failed to find valid patches! Please check the input parameters."
f"\n\tMaximum number of iterations reached: {iter_count}"
f"\n\tNumber of invalid patches: {len(points_ids)}"
f"\n\tMaximum height difference: {max_height_diff}"
)
# return the flat patches (in the mesh frame)
return flat_patches - origin
| 12,446 | Python | 44.261818 | 118 | 0.663908 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/terrain_importer.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import numpy as np
import torch
import trimesh
from typing import TYPE_CHECKING
import warp
from pxr import UsdGeom
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.markers import VisualizationMarkers
from omni.isaac.orbit.markers.config import FRAME_MARKER_CFG
from omni.isaac.orbit.utils.warp import convert_to_warp_mesh
from .terrain_generator import TerrainGenerator
from .trimesh.utils import make_plane
from .utils import create_prim_from_mesh
if TYPE_CHECKING:
from .terrain_importer_cfg import TerrainImporterCfg
class TerrainImporter:
r"""A class to handle terrain meshes and import them into the simulator.
We assume that a terrain mesh comprises of sub-terrains that are arranged in a grid with
rows ``num_rows`` and columns ``num_cols``. The terrain origins are the positions of the sub-terrains
where the robot should be spawned.
Based on the configuration, the terrain importer handles computing the environment origins from the sub-terrain
origins. In a typical setup, the number of sub-terrains (:math:`num\_rows \times num\_cols`) is smaller than
the number of environments (:math:`num\_envs`). In this case, the environment origins are computed by
sampling the sub-terrain origins.
If a curriculum is used, it is possible to update the environment origins to terrain origins that correspond
to a harder difficulty. This is done by calling :func:`update_terrain_levels`. The idea comes from game-based
curriculum. For example, in a game, the player starts with easy levels and progresses to harder levels.
"""
meshes: dict[str, trimesh.Trimesh]
"""A dictionary containing the names of the meshes and their keys."""
warp_meshes: dict[str, warp.Mesh]
"""A dictionary containing the names of the warp meshes and their keys."""
terrain_origins: torch.Tensor | None
"""The origins of the sub-terrains in the added terrain mesh. Shape is (num_rows, num_cols, 3).
If None, then it is assumed no sub-terrains exist. The environment origins are computed in a grid.
"""
env_origins: torch.Tensor
"""The origins of the environments. Shape is (num_envs, 3)."""
def __init__(self, cfg: TerrainImporterCfg):
"""Initialize the terrain importer.
Args:
cfg: The configuration for the terrain importer.
Raises:
ValueError: If input terrain type is not supported.
ValueError: If terrain type is 'generator' and no configuration provided for ``terrain_generator``.
ValueError: If terrain type is 'usd' and no configuration provided for ``usd_path``.
ValueError: If terrain type is 'usd' or 'plane' and no configuration provided for ``env_spacing``.
"""
# store inputs
self.cfg = cfg
self.device = sim_utils.SimulationContext.instance().device # type: ignore
# create a dict of meshes
self.meshes = dict()
self.warp_meshes = dict()
self.env_origins = None
self.terrain_origins = None
# private variables
self._terrain_flat_patches = dict()
# auto-import the terrain based on the config
if self.cfg.terrain_type == "generator":
# check config is provided
if self.cfg.terrain_generator is None:
raise ValueError("Input terrain type is 'generator' but no value provided for 'terrain_generator'.")
# generate the terrain
terrain_generator = TerrainGenerator(cfg=self.cfg.terrain_generator, device=self.device)
self.import_mesh("terrain", terrain_generator.terrain_mesh)
# configure the terrain origins based on the terrain generator
self.configure_env_origins(terrain_generator.terrain_origins)
# refer to the flat patches
self._terrain_flat_patches = terrain_generator.flat_patches
elif self.cfg.terrain_type == "usd":
# check if config is provided
if self.cfg.usd_path is None:
raise ValueError("Input terrain type is 'usd' but no value provided for 'usd_path'.")
# import the terrain
self.import_usd("terrain", self.cfg.usd_path)
# configure the origins in a grid
self.configure_env_origins()
elif self.cfg.terrain_type == "plane":
# load the plane
self.import_ground_plane("terrain")
# configure the origins in a grid
self.configure_env_origins()
else:
raise ValueError(f"Terrain type '{self.cfg.terrain_type}' not available.")
# set initial state of debug visualization
self.set_debug_vis(self.cfg.debug_vis)
"""
Properties.
"""
@property
def has_debug_vis_implementation(self) -> bool:
"""Whether the terrain importer has a debug visualization implemented.
This always returns True.
"""
return True
@property
def flat_patches(self) -> dict[str, torch.Tensor]:
"""A dictionary containing the sampled valid (flat) patches for the terrain.
This is only available if the terrain type is 'generator'. For other terrain types, this feature
is not available and the function returns an empty dictionary.
Please refer to the :attr:`TerrainGenerator.flat_patches` for more information.
"""
return self._terrain_flat_patches
"""
Operations - Visibility.
"""
def set_debug_vis(self, debug_vis: bool) -> bool:
"""Set the debug visualization of the terrain importer.
Args:
debug_vis: Whether to visualize the terrain origins.
Returns:
Whether the debug visualization was successfully set. False if the terrain
importer does not support debug visualization.
Raises:
RuntimeError: If terrain origins are not configured.
"""
# create a marker if necessary
if debug_vis:
if not hasattr(self, "origin_visualizer"):
self.origin_visualizer = VisualizationMarkers(
cfg=FRAME_MARKER_CFG.replace(prim_path="/Visuals/TerrainOrigin")
)
if self.terrain_origins is not None:
self.origin_visualizer.visualize(self.terrain_origins.reshape(-1, 3))
elif self.env_origins is not None:
self.origin_visualizer.visualize(self.env_origins.reshape(-1, 3))
else:
raise RuntimeError("Terrain origins are not configured.")
# set visibility
self.origin_visualizer.set_visibility(True)
else:
if hasattr(self, "origin_visualizer"):
self.origin_visualizer.set_visibility(False)
# report success
return True
"""
Operations - Import.
"""
def import_ground_plane(self, key: str, size: tuple[float, float] = (2.0e6, 2.0e6)):
"""Add a plane to the terrain importer.
Args:
key: The key to store the mesh.
size: The size of the plane. Defaults to (2.0e6, 2.0e6).
Raises:
ValueError: If a terrain with the same key already exists.
"""
# check if key exists
if key in self.meshes:
raise ValueError(f"Mesh with key {key} already exists. Existing keys: {self.meshes.keys()}.")
# create a plane
mesh = make_plane(size, height=0.0, center_zero=True)
# store the mesh
self.meshes[key] = mesh
# create a warp mesh
device = "cuda" if "cuda" in self.device else "cpu"
self.warp_meshes[key] = convert_to_warp_mesh(mesh.vertices, mesh.faces, device=device)
# get the mesh
ground_plane_cfg = sim_utils.GroundPlaneCfg(physics_material=self.cfg.physics_material, size=size)
ground_plane_cfg.func(self.cfg.prim_path, ground_plane_cfg)
def import_mesh(self, key: str, mesh: trimesh.Trimesh):
"""Import a mesh into the simulator.
The mesh is imported into the simulator under the prim path ``cfg.prim_path/{key}``. The created path
contains the mesh as a :class:`pxr.UsdGeom` instance along with visual or physics material prims.
Args:
key: The key to store the mesh.
mesh: The mesh to import.
Raises:
ValueError: If a terrain with the same key already exists.
"""
# check if key exists
if key in self.meshes:
raise ValueError(f"Mesh with key {key} already exists. Existing keys: {self.meshes.keys()}.")
# store the mesh
self.meshes[key] = mesh
# create a warp mesh
device = "cuda" if "cuda" in self.device else "cpu"
self.warp_meshes[key] = convert_to_warp_mesh(mesh.vertices, mesh.faces, device=device)
# get the mesh
mesh = self.meshes[key]
mesh_prim_path = self.cfg.prim_path + f"/{key}"
# import the mesh
create_prim_from_mesh(
mesh_prim_path,
mesh,
visual_material=self.cfg.visual_material,
physics_material=self.cfg.physics_material,
)
def import_usd(self, key: str, usd_path: str):
"""Import a mesh from a USD file.
We assume that the USD file contains a single mesh. If the USD file contains multiple meshes, then
the first mesh is used. The function mainly helps in registering the mesh into the warp meshes
and the meshes dictionary.
Note:
We do not apply any material properties to the mesh. The material properties should
be defined in the USD file.
Args:
key: The key to store the mesh.
usd_path: The path to the USD file.
Raises:
ValueError: If a terrain with the same key already exists.
"""
# add mesh to the dict
if key in self.meshes:
raise ValueError(f"Mesh with key {key} already exists. Existing keys: {self.meshes.keys()}.")
# add the prim path
cfg = sim_utils.UsdFileCfg(usd_path=usd_path)
cfg.func(self.cfg.prim_path + f"/{key}", cfg)
# traverse the prim and get the collision mesh
# THINK: Should the user specify the collision mesh?
mesh_prim = sim_utils.get_first_matching_child_prim(
self.cfg.prim_path + f"/{key}", lambda prim: prim.GetTypeName() == "Mesh"
)
# check if the mesh is valid
if mesh_prim is None:
raise ValueError(f"Could not find any collision mesh in {usd_path}. Please check asset.")
# cast into UsdGeomMesh
mesh_prim = UsdGeom.Mesh(mesh_prim)
# store the mesh
vertices = np.asarray(mesh_prim.GetPointsAttr().Get())
faces = np.asarray(mesh_prim.GetFaceVertexIndicesAttr().Get()).reshape(-1, 3)
self.meshes[key] = trimesh.Trimesh(vertices=vertices, faces=faces)
# create a warp mesh
device = "cuda" if "cuda" in self.device else "cpu"
self.warp_meshes[key] = convert_to_warp_mesh(vertices, faces, device=device)
"""
Operations - Origins.
"""
def configure_env_origins(self, origins: np.ndarray | None = None):
"""Configure the origins of the environments based on the added terrain.
Args:
origins: The origins of the sub-terrains. Shape is (num_rows, num_cols, 3).
"""
# decide whether to compute origins in a grid or based on curriculum
if origins is not None:
# convert to numpy
if isinstance(origins, np.ndarray):
origins = torch.from_numpy(origins)
# store the origins
self.terrain_origins = origins.to(self.device, dtype=torch.float)
# compute environment origins
self.env_origins = self._compute_env_origins_curriculum(self.cfg.num_envs, self.terrain_origins)
else:
self.terrain_origins = None
# check if env spacing is valid
if self.cfg.env_spacing is None:
raise ValueError("Environment spacing must be specified for configuring grid-like origins.")
# compute environment origins
self.env_origins = self._compute_env_origins_grid(self.cfg.num_envs, self.cfg.env_spacing)
def update_env_origins(self, env_ids: torch.Tensor, move_up: torch.Tensor, move_down: torch.Tensor):
"""Update the environment origins based on the terrain levels."""
# check if grid-like spawning
if self.terrain_origins is None:
return
# update terrain level for the envs
self.terrain_levels[env_ids] += 1 * move_up - 1 * move_down
# robots that solve the last level are sent to a random one
# the minimum level is zero
self.terrain_levels[env_ids] = torch.where(
self.terrain_levels[env_ids] >= self.max_terrain_level,
torch.randint_like(self.terrain_levels[env_ids], self.max_terrain_level),
torch.clip(self.terrain_levels[env_ids], 0),
)
# update the env origins
self.env_origins[env_ids] = self.terrain_origins[self.terrain_levels[env_ids], self.terrain_types[env_ids]]
"""
Internal helpers.
"""
def _compute_env_origins_curriculum(self, num_envs: int, origins: torch.Tensor) -> torch.Tensor:
"""Compute the origins of the environments defined by the sub-terrains origins."""
# extract number of rows and cols
num_rows, num_cols = origins.shape[:2]
# maximum initial level possible for the terrains
if self.cfg.max_init_terrain_level is None:
max_init_level = num_rows - 1
else:
max_init_level = min(self.cfg.max_init_terrain_level, num_rows - 1)
# store maximum terrain level possible
self.max_terrain_level = num_rows
# define all terrain levels and types available
self.terrain_levels = torch.randint(0, max_init_level + 1, (num_envs,), device=self.device)
self.terrain_types = torch.div(
torch.arange(num_envs, device=self.device),
(num_envs / num_cols),
rounding_mode="floor",
).to(torch.long)
# create tensor based on number of environments
env_origins = torch.zeros(num_envs, 3, device=self.device)
env_origins[:] = origins[self.terrain_levels, self.terrain_types]
return env_origins
def _compute_env_origins_grid(self, num_envs: int, env_spacing: float) -> torch.Tensor:
"""Compute the origins of the environments in a grid based on configured spacing."""
# create tensor based on number of environments
env_origins = torch.zeros(num_envs, 3, device=self.device)
# create a grid of origins
num_rows = np.ceil(num_envs / int(np.sqrt(num_envs)))
num_cols = np.ceil(num_envs / num_rows)
ii, jj = torch.meshgrid(
torch.arange(num_rows, device=self.device), torch.arange(num_cols, device=self.device), indexing="ij"
)
env_origins[:, 0] = -(ii.flatten()[:num_envs] - (num_rows - 1) / 2) * env_spacing
env_origins[:, 1] = (jj.flatten()[:num_envs] - (num_cols - 1) / 2) * env_spacing
env_origins[:, 2] = 0.0
return env_origins
| 15,546 | Python | 41.829201 | 116 | 0.632253 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/trimesh/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
This sub-module provides methods to create different terrains using the ``trimesh`` library.
In contrast to the height-field representation, the trimesh representation does not
create arbitrarily small triangles. Instead, the terrain is represented as a single
tri-mesh primitive. Thus, this representation is more computationally and memory
efficient than the height-field representation, but it is not as flexible.
"""
from .mesh_terrains_cfg import (
MeshBoxTerrainCfg,
MeshFloatingRingTerrainCfg,
MeshGapTerrainCfg,
MeshInvertedPyramidStairsTerrainCfg,
MeshPitTerrainCfg,
MeshPlaneTerrainCfg,
MeshPyramidStairsTerrainCfg,
MeshRailsTerrainCfg,
MeshRandomGridTerrainCfg,
MeshRepeatedBoxesTerrainCfg,
MeshRepeatedCylindersTerrainCfg,
MeshRepeatedPyramidsTerrainCfg,
MeshStarTerrainCfg,
)
| 970 | Python | 31.366666 | 92 | 0.791753 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/trimesh/mesh_terrains.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Functions to generate different terrains using the ``trimesh`` library."""
from __future__ import annotations
import numpy as np
import scipy.spatial.transform as tf
import torch
import trimesh
from typing import TYPE_CHECKING
from .utils import * # noqa: F401, F403
from .utils import make_border, make_plane
if TYPE_CHECKING:
from . import mesh_terrains_cfg
def flat_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshPlaneTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a flat terrain as a plane.
.. image:: ../../_static/terrains/trimesh/flat_terrain.jpg
:width: 45%
:align: center
Note:
The :obj:`difficulty` parameter is ignored for this terrain.
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
"""
# compute the position of the terrain
origin = (cfg.size[0] / 2.0, cfg.size[1] / 2.0, 0.0)
# compute the vertices of the terrain
plane_mesh = make_plane(cfg.size, 0.0, center_zero=False)
# return the tri-mesh and the position
return [plane_mesh], np.array(origin)
def pyramid_stairs_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshPyramidStairsTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with a pyramid stair pattern.
The terrain is a pyramid stair pattern which trims to a flat platform at the center of the terrain.
If :obj:`cfg.holes` is True, the terrain will have pyramid stairs of length or width
:obj:`cfg.platform_width` (depending on the direction) with no steps in the remaining area. Additionally,
no border will be added.
.. image:: ../../_static/terrains/trimesh/pyramid_stairs_terrain.jpg
:width: 45%
.. image:: ../../_static/terrains/trimesh/pyramid_stairs_terrain_with_holes.jpg
:width: 45%
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
"""
# resolve the terrain configuration
step_height = cfg.step_height_range[0] + difficulty * (cfg.step_height_range[1] - cfg.step_height_range[0])
# compute number of steps in x and y direction
num_steps_x = (cfg.size[0] - 2 * cfg.border_width - cfg.platform_width) // (2 * cfg.step_width) + 1
num_steps_y = (cfg.size[1] - 2 * cfg.border_width - cfg.platform_width) // (2 * cfg.step_width) + 1
# we take the minimum number of steps in x and y direction
num_steps = int(min(num_steps_x, num_steps_y))
# initialize list of meshes
meshes_list = list()
# generate the border if needed
if cfg.border_width > 0.0 and not cfg.holes:
# obtain a list of meshes for the border
border_center = [0.5 * cfg.size[0], 0.5 * cfg.size[1], -step_height / 2]
border_inner_size = (cfg.size[0] - 2 * cfg.border_width, cfg.size[1] - 2 * cfg.border_width)
make_borders = make_border(cfg.size, border_inner_size, step_height, border_center)
# add the border meshes to the list of meshes
meshes_list += make_borders
# generate the terrain
# -- compute the position of the center of the terrain
terrain_center = [0.5 * cfg.size[0], 0.5 * cfg.size[1], 0.0]
terrain_size = (cfg.size[0] - 2 * cfg.border_width, cfg.size[1] - 2 * cfg.border_width)
# -- generate the stair pattern
for k in range(num_steps):
# check if we need to add holes around the steps
if cfg.holes:
box_size = (cfg.platform_width, cfg.platform_width)
else:
box_size = (terrain_size[0] - 2 * k * cfg.step_width, terrain_size[1] - 2 * k * cfg.step_width)
# compute the quantities of the box
# -- location
box_z = terrain_center[2] + k * step_height / 2.0
box_offset = (k + 0.5) * cfg.step_width
# -- dimensions
box_height = (k + 2) * step_height
# generate the boxes
# top/bottom
box_dims = (box_size[0], cfg.step_width, box_height)
# -- top
box_pos = (terrain_center[0], terrain_center[1] + terrain_size[1] / 2.0 - box_offset, box_z)
box_top = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# -- bottom
box_pos = (terrain_center[0], terrain_center[1] - terrain_size[1] / 2.0 + box_offset, box_z)
box_bottom = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# right/left
if cfg.holes:
box_dims = (cfg.step_width, box_size[1], box_height)
else:
box_dims = (cfg.step_width, box_size[1] - 2 * cfg.step_width, box_height)
# -- right
box_pos = (terrain_center[0] + terrain_size[0] / 2.0 - box_offset, terrain_center[1], box_z)
box_right = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# -- left
box_pos = (terrain_center[0] - terrain_size[0] / 2.0 + box_offset, terrain_center[1], box_z)
box_left = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# add the boxes to the list of meshes
meshes_list += [box_top, box_bottom, box_right, box_left]
# generate final box for the middle of the terrain
box_dims = (
terrain_size[0] - 2 * num_steps * cfg.step_width,
terrain_size[1] - 2 * num_steps * cfg.step_width,
(num_steps + 2) * step_height,
)
box_pos = (terrain_center[0], terrain_center[1], terrain_center[2] + num_steps * step_height / 2)
box_middle = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
meshes_list.append(box_middle)
# origin of the terrain
origin = np.array([terrain_center[0], terrain_center[1], (num_steps + 1) * step_height])
return meshes_list, origin
def inverted_pyramid_stairs_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshInvertedPyramidStairsTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with a inverted pyramid stair pattern.
The terrain is an inverted pyramid stair pattern which trims to a flat platform at the center of the terrain.
If :obj:`cfg.holes` is True, the terrain will have pyramid stairs of length or width
:obj:`cfg.platform_width` (depending on the direction) with no steps in the remaining area. Additionally,
no border will be added.
.. image:: ../../_static/terrains/trimesh/inverted_pyramid_stairs_terrain.jpg
:width: 45%
.. image:: ../../_static/terrains/trimesh/inverted_pyramid_stairs_terrain_with_holes.jpg
:width: 45%
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
"""
# resolve the terrain configuration
step_height = cfg.step_height_range[0] + difficulty * (cfg.step_height_range[1] - cfg.step_height_range[0])
# compute number of steps in x and y direction
num_steps_x = (cfg.size[0] - 2 * cfg.border_width - cfg.platform_width) // (2 * cfg.step_width) + 1
num_steps_y = (cfg.size[1] - 2 * cfg.border_width - cfg.platform_width) // (2 * cfg.step_width) + 1
# we take the minimum number of steps in x and y direction
num_steps = int(min(num_steps_x, num_steps_y))
# total height of the terrain
total_height = (num_steps + 1) * step_height
# initialize list of meshes
meshes_list = list()
# generate the border if needed
if cfg.border_width > 0.0 and not cfg.holes:
# obtain a list of meshes for the border
border_center = [0.5 * cfg.size[0], 0.5 * cfg.size[1], -0.5 * step_height]
border_inner_size = (cfg.size[0] - 2 * cfg.border_width, cfg.size[1] - 2 * cfg.border_width)
make_borders = make_border(cfg.size, border_inner_size, step_height, border_center)
# add the border meshes to the list of meshes
meshes_list += make_borders
# generate the terrain
# -- compute the position of the center of the terrain
terrain_center = [0.5 * cfg.size[0], 0.5 * cfg.size[1], 0.0]
terrain_size = (cfg.size[0] - 2 * cfg.border_width, cfg.size[1] - 2 * cfg.border_width)
# -- generate the stair pattern
for k in range(num_steps):
# check if we need to add holes around the steps
if cfg.holes:
box_size = (cfg.platform_width, cfg.platform_width)
else:
box_size = (terrain_size[0] - 2 * k * cfg.step_width, terrain_size[1] - 2 * k * cfg.step_width)
# compute the quantities of the box
# -- location
box_z = terrain_center[2] - total_height / 2 - (k + 1) * step_height / 2.0
box_offset = (k + 0.5) * cfg.step_width
# -- dimensions
box_height = total_height - (k + 1) * step_height
# generate the boxes
# top/bottom
box_dims = (box_size[0], cfg.step_width, box_height)
# -- top
box_pos = (terrain_center[0], terrain_center[1] + terrain_size[1] / 2.0 - box_offset, box_z)
box_top = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# -- bottom
box_pos = (terrain_center[0], terrain_center[1] - terrain_size[1] / 2.0 + box_offset, box_z)
box_bottom = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# right/left
if cfg.holes:
box_dims = (cfg.step_width, box_size[1], box_height)
else:
box_dims = (cfg.step_width, box_size[1] - 2 * cfg.step_width, box_height)
# -- right
box_pos = (terrain_center[0] + terrain_size[0] / 2.0 - box_offset, terrain_center[1], box_z)
box_right = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# -- left
box_pos = (terrain_center[0] - terrain_size[0] / 2.0 + box_offset, terrain_center[1], box_z)
box_left = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# add the boxes to the list of meshes
meshes_list += [box_top, box_bottom, box_right, box_left]
# generate final box for the middle of the terrain
box_dims = (
terrain_size[0] - 2 * num_steps * cfg.step_width,
terrain_size[1] - 2 * num_steps * cfg.step_width,
step_height,
)
box_pos = (terrain_center[0], terrain_center[1], terrain_center[2] - total_height - step_height / 2)
box_middle = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
meshes_list.append(box_middle)
# origin of the terrain
origin = np.array([terrain_center[0], terrain_center[1], -(num_steps + 1) * step_height])
return meshes_list, origin
def random_grid_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshRandomGridTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with cells of random heights and fixed width.
The terrain is generated in the x-y plane and has a height of 1.0. It is then divided into a grid of the
specified size :obj:`cfg.grid_width`. Each grid cell is then randomly shifted in the z-direction by a value uniformly
sampled between :obj:`cfg.grid_height_range`. At the center of the terrain, a platform of the specified width
:obj:`cfg.platform_width` is generated.
If :obj:`cfg.holes` is True, the terrain will have randomized grid cells only along the plane extending
from the platform (like a plus sign). The remaining area remains empty and no border will be added.
.. image:: ../../_static/terrains/trimesh/random_grid_terrain.jpg
:width: 45%
.. image:: ../../_static/terrains/trimesh/random_grid_terrain_with_holes.jpg
:width: 45%
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
Raises:
ValueError: If the terrain is not square. This method only supports square terrains.
RuntimeError: If the grid width is large such that the border width is negative.
"""
# check to ensure square terrain
if cfg.size[0] != cfg.size[1]:
raise ValueError(f"The terrain must be square. Received size: {cfg.size}.")
# resolve the terrain configuration
grid_height = cfg.grid_height_range[0] + difficulty * (cfg.grid_height_range[1] - cfg.grid_height_range[0])
# initialize list of meshes
meshes_list = list()
# compute the number of boxes in each direction
num_boxes_x = int(cfg.size[0] / cfg.grid_width)
num_boxes_y = int(cfg.size[1] / cfg.grid_width)
# constant parameters
terrain_height = 1.0
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
# generate the border
border_width = cfg.size[0] - min(num_boxes_x, num_boxes_y) * cfg.grid_width
if border_width > 0:
# compute parameters for the border
border_center = (0.5 * cfg.size[0], 0.5 * cfg.size[1], -terrain_height / 2)
border_inner_size = (cfg.size[0] - border_width, cfg.size[1] - border_width)
# create border meshes
make_borders = make_border(cfg.size, border_inner_size, terrain_height, border_center)
meshes_list += make_borders
else:
raise RuntimeError("Border width must be greater than 0! Adjust the parameter 'cfg.grid_width'.")
# create a template grid of terrain height
grid_dim = [cfg.grid_width, cfg.grid_width, terrain_height]
grid_position = [0.5 * cfg.grid_width, 0.5 * cfg.grid_width, -terrain_height / 2]
template_box = trimesh.creation.box(grid_dim, trimesh.transformations.translation_matrix(grid_position))
# extract vertices and faces of the box to create a template
template_vertices = template_box.vertices # (8, 3)
template_faces = template_box.faces
# repeat the template box vertices to span the terrain (num_boxes_x * num_boxes_y, 8, 3)
vertices = torch.tensor(template_vertices, device=device).repeat(num_boxes_x * num_boxes_y, 1, 1)
# create a meshgrid to offset the vertices
x = torch.arange(0, num_boxes_x, device=device)
y = torch.arange(0, num_boxes_y, device=device)
xx, yy = torch.meshgrid(x, y, indexing="ij")
xx = xx.flatten().view(-1, 1)
yy = yy.flatten().view(-1, 1)
xx_yy = torch.cat((xx, yy), dim=1)
# offset the vertices
offsets = cfg.grid_width * xx_yy + border_width / 2
vertices[:, :, :2] += offsets.unsqueeze(1)
# mask the vertices to create holes, s.t. only grids along the x and y axis are present
if cfg.holes:
# -- x-axis
mask_x = torch.logical_and(
(vertices[:, :, 0] > (cfg.size[0] - border_width - cfg.platform_width) / 2).all(dim=1),
(vertices[:, :, 0] < (cfg.size[0] + border_width + cfg.platform_width) / 2).all(dim=1),
)
vertices_x = vertices[mask_x]
# -- y-axis
mask_y = torch.logical_and(
(vertices[:, :, 1] > (cfg.size[1] - border_width - cfg.platform_width) / 2).all(dim=1),
(vertices[:, :, 1] < (cfg.size[1] + border_width + cfg.platform_width) / 2).all(dim=1),
)
vertices_y = vertices[mask_y]
# -- combine these vertices
vertices = torch.cat((vertices_x, vertices_y))
# add noise to the vertices to have a random height over each grid cell
num_boxes = len(vertices)
# create noise for the z-axis
h_noise = torch.zeros((num_boxes, 3), device=device)
h_noise[:, 2].uniform_(-grid_height, grid_height)
# reshape noise to match the vertices (num_boxes, 4, 3)
# only the top vertices of the box are affected
vertices_noise = torch.zeros((num_boxes, 4, 3), device=device)
vertices_noise += h_noise.unsqueeze(1)
# add height only to the top vertices of the box
vertices[vertices[:, :, 2] == 0] += vertices_noise.view(-1, 3)
# move to numpy
vertices = vertices.reshape(-1, 3).cpu().numpy()
# create faces for boxes (num_boxes, 12, 3). Each box has 6 faces, each face has 2 triangles.
faces = torch.tensor(template_faces, device=device).repeat(num_boxes, 1, 1)
face_offsets = torch.arange(0, num_boxes, device=device).unsqueeze(1).repeat(1, 12) * 8
faces += face_offsets.unsqueeze(2)
# move to numpy
faces = faces.view(-1, 3).cpu().numpy()
# convert to trimesh
grid_mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
meshes_list.append(grid_mesh)
# add a platform in the center of the terrain that is accessible from all sides
dim = (cfg.platform_width, cfg.platform_width, terrain_height + grid_height)
pos = (0.5 * cfg.size[0], 0.5 * cfg.size[1], -terrain_height / 2 + grid_height / 2)
box_platform = trimesh.creation.box(dim, trimesh.transformations.translation_matrix(pos))
meshes_list.append(box_platform)
# specify the origin of the terrain
origin = np.array([0.5 * cfg.size[0], 0.5 * cfg.size[1], grid_height])
return meshes_list, origin
def rails_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshRailsTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with box rails as extrusions.
The terrain contains two sets of box rails created as extrusions. The first set (inner rails) is extruded from
the platform at the center of the terrain, and the second set is extruded between the first set of rails
and the terrain border. Each set of rails is extruded to the same height.
.. image:: ../../_static/terrains/trimesh/rails_terrain.jpg
:width: 40%
:align: center
Args:
difficulty: The difficulty of the terrain. this is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
"""
# resolve the terrain configuration
rail_height = cfg.rail_height_range[1] - difficulty * (cfg.rail_height_range[1] - cfg.rail_height_range[0])
# initialize list of meshes
meshes_list = list()
# extract quantities
rail_1_thickness, rail_2_thickness = cfg.rail_thickness_range
rail_center = (0.5 * cfg.size[0], 0.5 * cfg.size[1], rail_height * 0.5)
# constants for terrain generation
terrain_height = 1.0
rail_2_ratio = 0.6
# generate first set of rails
rail_1_inner_size = (cfg.platform_width, cfg.platform_width)
rail_1_outer_size = (cfg.platform_width + 2.0 * rail_1_thickness, cfg.platform_width + 2.0 * rail_1_thickness)
meshes_list += make_border(rail_1_outer_size, rail_1_inner_size, rail_height, rail_center)
# generate second set of rails
rail_2_inner_x = cfg.platform_width + (cfg.size[0] - cfg.platform_width) * rail_2_ratio
rail_2_inner_y = cfg.platform_width + (cfg.size[1] - cfg.platform_width) * rail_2_ratio
rail_2_inner_size = (rail_2_inner_x, rail_2_inner_y)
rail_2_outer_size = (rail_2_inner_x + 2.0 * rail_2_thickness, rail_2_inner_y + 2.0 * rail_2_thickness)
meshes_list += make_border(rail_2_outer_size, rail_2_inner_size, rail_height, rail_center)
# generate the ground
dim = (cfg.size[0], cfg.size[1], terrain_height)
pos = (0.5 * cfg.size[0], 0.5 * cfg.size[1], -terrain_height / 2)
ground_meshes = trimesh.creation.box(dim, trimesh.transformations.translation_matrix(pos))
meshes_list.append(ground_meshes)
# specify the origin of the terrain
origin = np.array([pos[0], pos[1], 0.0])
return meshes_list, origin
def pit_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshPitTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with a pit with levels (stairs) leading out of the pit.
The terrain contains a platform at the center and a staircase leading out of the pit.
The staircase is a series of steps that are aligned along the x- and y- axis. The steps are
created by extruding a ring along the x- and y- axis. If :obj:`is_double_pit` is True, the pit
contains two levels.
.. image:: ../../_static/terrains/trimesh/pit_terrain.jpg
:width: 40%
.. image:: ../../_static/terrains/trimesh/pit_terrain_with_two_levels.jpg
:width: 40%
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
"""
# resolve the terrain configuration
pit_depth = cfg.pit_depth_range[0] + difficulty * (cfg.pit_depth_range[1] - cfg.pit_depth_range[0])
# initialize list of meshes
meshes_list = list()
# extract quantities
inner_pit_size = (cfg.platform_width, cfg.platform_width)
total_depth = pit_depth
# constants for terrain generation
terrain_height = 1.0
ring_2_ratio = 0.6
# if the pit is double, the inner ring is smaller to fit the second level
if cfg.double_pit:
# increase the total height of the pit
total_depth *= 2.0
# reduce the size of the inner ring
inner_pit_x = cfg.platform_width + (cfg.size[0] - cfg.platform_width) * ring_2_ratio
inner_pit_y = cfg.platform_width + (cfg.size[1] - cfg.platform_width) * ring_2_ratio
inner_pit_size = (inner_pit_x, inner_pit_y)
# generate the pit (outer ring)
pit_center = [0.5 * cfg.size[0], 0.5 * cfg.size[1], -total_depth * 0.5]
meshes_list += make_border(cfg.size, inner_pit_size, total_depth, pit_center)
# generate the second level of the pit (inner ring)
if cfg.double_pit:
pit_center[2] = -total_depth
meshes_list += make_border(inner_pit_size, (cfg.platform_width, cfg.platform_width), total_depth, pit_center)
# generate the ground
dim = (cfg.size[0], cfg.size[1], terrain_height)
pos = (0.5 * cfg.size[0], 0.5 * cfg.size[1], -total_depth - terrain_height / 2)
ground_meshes = trimesh.creation.box(dim, trimesh.transformations.translation_matrix(pos))
meshes_list.append(ground_meshes)
# specify the origin of the terrain
origin = np.array([pos[0], pos[1], -total_depth])
return meshes_list, origin
def box_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshBoxTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with boxes (similar to a pyramid).
The terrain has a ground with boxes on top of it that are stacked on top of each other.
The boxes are created by extruding a rectangle along the z-axis. If :obj:`double_box` is True,
then two boxes of height :obj:`box_height` are stacked on top of each other.
.. image:: ../../_static/terrains/trimesh/box_terrain.jpg
:width: 40%
.. image:: ../../_static/terrains/trimesh/box_terrain_with_two_boxes.jpg
:width: 40%
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
"""
# resolve the terrain configuration
box_height = cfg.box_height_range[0] + difficulty * (cfg.box_height_range[1] - cfg.box_height_range[0])
# initialize list of meshes
meshes_list = list()
# extract quantities
total_height = box_height
if cfg.double_box:
total_height *= 2.0
# constants for terrain generation
terrain_height = 1.0
box_2_ratio = 0.6
# Generate the top box
dim = (cfg.platform_width, cfg.platform_width, terrain_height + total_height)
pos = (0.5 * cfg.size[0], 0.5 * cfg.size[1], (total_height - terrain_height) / 2)
box_mesh = trimesh.creation.box(dim, trimesh.transformations.translation_matrix(pos))
meshes_list.append(box_mesh)
# Generate the lower box
if cfg.double_box:
# calculate the size of the lower box
outer_box_x = cfg.platform_width + (cfg.size[0] - cfg.platform_width) * box_2_ratio
outer_box_y = cfg.platform_width + (cfg.size[1] - cfg.platform_width) * box_2_ratio
# create the lower box
dim = (outer_box_x, outer_box_y, terrain_height + total_height / 2)
pos = (0.5 * cfg.size[0], 0.5 * cfg.size[1], (total_height - terrain_height) / 2 - total_height / 4)
box_mesh = trimesh.creation.box(dim, trimesh.transformations.translation_matrix(pos))
meshes_list.append(box_mesh)
# Generate the ground
pos = (0.5 * cfg.size[0], 0.5 * cfg.size[1], -terrain_height / 2)
dim = (cfg.size[0], cfg.size[1], terrain_height)
ground_mesh = trimesh.creation.box(dim, trimesh.transformations.translation_matrix(pos))
meshes_list.append(ground_mesh)
# specify the origin of the terrain
origin = np.array([pos[0], pos[1], total_height])
return meshes_list, origin
def gap_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshGapTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with a gap around the platform.
The terrain has a ground with a platform in the middle. The platform is surrounded by a gap
of width :obj:`gap_width` on all sides.
.. image:: ../../_static/terrains/trimesh/gap_terrain.jpg
:width: 40%
:align: center
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
"""
# resolve the terrain configuration
gap_width = cfg.gap_width_range[0] + difficulty * (cfg.gap_width_range[1] - cfg.gap_width_range[0])
# initialize list of meshes
meshes_list = list()
# constants for terrain generation
terrain_height = 1.0
terrain_center = (0.5 * cfg.size[0], 0.5 * cfg.size[1], -terrain_height / 2)
# Generate the outer ring
inner_size = (cfg.platform_width + 2 * gap_width, cfg.platform_width + 2 * gap_width)
meshes_list += make_border(cfg.size, inner_size, terrain_height, terrain_center)
# Generate the inner box
box_dim = (cfg.platform_width, cfg.platform_width, terrain_height)
box = trimesh.creation.box(box_dim, trimesh.transformations.translation_matrix(terrain_center))
meshes_list.append(box)
# specify the origin of the terrain
origin = np.array([terrain_center[0], terrain_center[1], 0.0])
return meshes_list, origin
def floating_ring_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshFloatingRingTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with a floating square ring.
The terrain has a ground with a floating ring in the middle. The ring extends from the center from
:obj:`platform_width` to :obj:`platform_width` + :obj:`ring_width` in the x and y directions.
The thickness of the ring is :obj:`ring_thickness` and the height of the ring from the terrain
is :obj:`ring_height`.
.. image:: ../../_static/terrains/trimesh/floating_ring_terrain.jpg
:width: 40%
:align: center
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
"""
# resolve the terrain configuration
ring_height = cfg.ring_height_range[1] - difficulty * (cfg.ring_height_range[1] - cfg.ring_height_range[0])
ring_width = cfg.ring_width_range[0] + difficulty * (cfg.ring_width_range[1] - cfg.ring_width_range[0])
# initialize list of meshes
meshes_list = list()
# constants for terrain generation
terrain_height = 1.0
# Generate the floating ring
ring_center = (0.5 * cfg.size[0], 0.5 * cfg.size[1], ring_height + 0.5 * cfg.ring_thickness)
ring_outer_size = (cfg.platform_width + 2 * ring_width, cfg.platform_width + 2 * ring_width)
ring_inner_size = (cfg.platform_width, cfg.platform_width)
meshes_list += make_border(ring_outer_size, ring_inner_size, cfg.ring_thickness, ring_center)
# Generate the ground
dim = (cfg.size[0], cfg.size[1], terrain_height)
pos = (0.5 * cfg.size[0], 0.5 * cfg.size[1], -terrain_height / 2)
ground = trimesh.creation.box(dim, trimesh.transformations.translation_matrix(pos))
meshes_list.append(ground)
# specify the origin of the terrain
origin = np.asarray([pos[0], pos[1], 0.0])
return meshes_list, origin
def star_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshStarTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with a star.
The terrain has a ground with a cylinder in the middle. The star is made of :obj:`num_bars` bars
with a width of :obj:`bar_width` and a height of :obj:`bar_height`. The bars are evenly
spaced around the cylinder and connect to the peripheral of the terrain.
.. image:: ../../_static/terrains/trimesh/star_terrain.jpg
:width: 40%
:align: center
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
Raises:
ValueError: If :obj:`num_bars` is less than 2.
"""
# check the number of bars
if cfg.num_bars < 2:
raise ValueError(f"The number of bars in the star must be greater than 2. Received: {cfg.num_bars}")
# resolve the terrain configuration
bar_height = cfg.bar_height_range[0] + difficulty * (cfg.bar_height_range[1] - cfg.bar_height_range[0])
bar_width = cfg.bar_width_range[1] - difficulty * (cfg.bar_width_range[1] - cfg.bar_width_range[0])
# initialize list of meshes
meshes_list = list()
# Generate a platform in the middle
platform_center = (0.5 * cfg.size[0], 0.5 * cfg.size[1], -bar_height / 2)
platform_transform = trimesh.transformations.translation_matrix(platform_center)
platform = trimesh.creation.cylinder(
cfg.platform_width * 0.5, bar_height, sections=2 * cfg.num_bars, transform=platform_transform
)
meshes_list.append(platform)
# Generate bars to connect the platform to the terrain
transform = np.eye(4)
transform[:3, -1] = np.asarray(platform_center)
yaw = 0.0
for _ in range(cfg.num_bars):
# compute the length of the bar based on the yaw
# length changes since the bar is connected to a square border
bar_length = cfg.size[0]
if yaw < 0.25 * np.pi:
bar_length /= np.math.cos(yaw)
elif yaw < 0.75 * np.pi:
bar_length /= np.math.sin(yaw)
else:
bar_length /= np.math.cos(np.pi - yaw)
# compute the transform of the bar
transform[0:3, 0:3] = tf.Rotation.from_euler("z", yaw).as_matrix()
# add the bar to the mesh
dim = [bar_length - bar_width, bar_width, bar_height]
bar = trimesh.creation.box(dim, transform)
meshes_list.append(bar)
# increment the yaw
yaw += np.pi / cfg.num_bars
# Generate the exterior border
inner_size = (cfg.size[0] - 2 * bar_width, cfg.size[1] - 2 * bar_width)
meshes_list += make_border(cfg.size, inner_size, bar_height, platform_center)
# Generate the ground
ground = make_plane(cfg.size, -bar_height, center_zero=False)
meshes_list.append(ground)
# specify the origin of the terrain
origin = np.asarray([0.5 * cfg.size[0], 0.5 * cfg.size[1], 0.0])
return meshes_list, origin
def repeated_objects_terrain(
difficulty: float, cfg: mesh_terrains_cfg.MeshRepeatedObjectsTerrainCfg
) -> tuple[list[trimesh.Trimesh], np.ndarray]:
"""Generate a terrain with a set of repeated objects.
The terrain has a ground with a platform in the middle. The objects are randomly placed on the
terrain s.t. they do not overlap with the platform.
Depending on the object type, the objects are generated with different parameters. The objects
The types of objects that can be generated are: ``"cylinder"``, ``"box"``, ``"cone"``.
The object parameters are specified in the configuration as curriculum parameters. The difficulty
is used to linearly interpolate between the minimum and maximum values of the parameters.
.. image:: ../../_static/terrains/trimesh/repeated_objects_cylinder_terrain.jpg
:width: 30%
.. image:: ../../_static/terrains/trimesh/repeated_objects_box_terrain.jpg
:width: 30%
.. image:: ../../_static/terrains/trimesh/repeated_objects_pyramid_terrain.jpg
:width: 30%
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
A tuple containing the tri-mesh of the terrain and the origin of the terrain (in m).
Raises:
ValueError: If the object type is not supported. It must be either a string or a callable.
"""
# import the object functions -- this is done here to avoid circular imports
from .mesh_terrains_cfg import (
MeshRepeatedBoxesTerrainCfg,
MeshRepeatedCylindersTerrainCfg,
MeshRepeatedPyramidsTerrainCfg,
)
# if object type is a string, get the function: make_{object_type}
if isinstance(cfg.object_type, str):
object_func = globals().get(f"make_{cfg.object_type}")
else:
object_func = cfg.object_type
if not callable(object_func):
raise ValueError(f"The attribute 'object_type' must be a string or a callable. Received: {object_func}")
# Resolve the terrain configuration
# -- pass parameters to make calling simpler
cp_0 = cfg.object_params_start
cp_1 = cfg.object_params_end
# -- common parameters
num_objects = cp_0.num_objects + int(difficulty * (cp_1.num_objects - cp_0.num_objects))
height = cp_0.height + difficulty * (cp_1.height - cp_0.height)
# -- object specific parameters
# note: SIM114 requires duplicated logical blocks under a single body.
if isinstance(cfg, MeshRepeatedBoxesTerrainCfg):
cp_0: MeshRepeatedBoxesTerrainCfg.ObjectCfg
cp_1: MeshRepeatedBoxesTerrainCfg.ObjectCfg
object_kwargs = {
"length": cp_0.size[0] + difficulty * (cp_1.size[0] - cp_0.size[0]),
"width": cp_0.size[1] + difficulty * (cp_1.size[1] - cp_0.size[1]),
"max_yx_angle": cp_0.max_yx_angle + difficulty * (cp_1.max_yx_angle - cp_0.max_yx_angle),
"degrees": cp_0.degrees,
}
elif isinstance(cfg, MeshRepeatedPyramidsTerrainCfg): # noqa: SIM114
cp_0: MeshRepeatedPyramidsTerrainCfg.ObjectCfg
cp_1: MeshRepeatedPyramidsTerrainCfg.ObjectCfg
object_kwargs = {
"radius": cp_0.radius + difficulty * (cp_1.radius - cp_0.radius),
"max_yx_angle": cp_0.max_yx_angle + difficulty * (cp_1.max_yx_angle - cp_0.max_yx_angle),
"degrees": cp_0.degrees,
}
elif isinstance(cfg, MeshRepeatedCylindersTerrainCfg): # noqa: SIM114
cp_0: MeshRepeatedCylindersTerrainCfg.ObjectCfg
cp_1: MeshRepeatedCylindersTerrainCfg.ObjectCfg
object_kwargs = {
"radius": cp_0.radius + difficulty * (cp_1.radius - cp_0.radius),
"max_yx_angle": cp_0.max_yx_angle + difficulty * (cp_1.max_yx_angle - cp_0.max_yx_angle),
"degrees": cp_0.degrees,
}
else:
raise ValueError(f"Unknown terrain configuration: {cfg}")
# constants for the terrain
platform_clearance = 0.1
# initialize list of meshes
meshes_list = list()
# compute quantities
origin = np.asarray((0.5 * cfg.size[0], 0.5 * cfg.size[1], 0.5 * height))
platform_corners = np.asarray([
[origin[0] - cfg.platform_width / 2, origin[1] - cfg.platform_width / 2],
[origin[0] + cfg.platform_width / 2, origin[1] + cfg.platform_width / 2],
])
platform_corners[0, :] *= 1 - platform_clearance
platform_corners[1, :] *= 1 + platform_clearance
# sample center for objects
while True:
object_centers = np.zeros((num_objects, 3))
object_centers[:, 0] = np.random.uniform(0, cfg.size[0], num_objects)
object_centers[:, 1] = np.random.uniform(0, cfg.size[1], num_objects)
# filter out the centers that are on the platform
is_within_platform_x = np.logical_and(
object_centers[:, 0] >= platform_corners[0, 0], object_centers[:, 0] <= platform_corners[1, 0]
)
is_within_platform_y = np.logical_and(
object_centers[:, 1] >= platform_corners[0, 1], object_centers[:, 1] <= platform_corners[1, 1]
)
masks = np.logical_and(is_within_platform_x, is_within_platform_y)
# if there are no objects on the platform, break
if not np.any(masks):
break
# generate obstacles (but keep platform clean)
for index in range(len(object_centers)):
# randomize the height of the object
ob_height = height + np.random.uniform(-cfg.max_height_noise, cfg.max_height_noise)
if ob_height > 0.0:
object_mesh = object_func(center=object_centers[index], height=ob_height, **object_kwargs)
meshes_list.append(object_mesh)
# generate a ground plane for the terrain
ground_plane = make_plane(cfg.size, height=0.0, center_zero=False)
meshes_list.append(ground_plane)
# generate a platform in the middle
dim = (cfg.platform_width, cfg.platform_width, 0.5 * height)
pos = (0.5 * cfg.size[0], 0.5 * cfg.size[1], 0.25 * height)
platform = trimesh.creation.box(dim, trimesh.transformations.translation_matrix(pos))
meshes_list.append(platform)
return meshes_list, origin
| 38,422 | Python | 44.044549 | 121 | 0.652829 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/trimesh/utils.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import numpy as np
import scipy.spatial.transform as tf
import trimesh
"""
Primitive functions to generate meshes.
"""
def make_plane(size: tuple[float, float], height: float, center_zero: bool = True) -> trimesh.Trimesh:
"""Generate a plane mesh.
If :obj:`center_zero` is True, the origin is at center of the plane mesh i.e. the mesh extends from
:math:`(-size[0] / 2, -size[1] / 2, 0)` to :math:`(size[0] / 2, size[1] / 2, height)`.
Otherwise, the origin is :math:`(size[0] / 2, size[1] / 2)` and the mesh extends from
:math:`(0, 0, 0)` to :math:`(size[0], size[1], height)`.
Args:
size: The length (along x) and width (along y) of the terrain (in m).
height: The height of the plane (in m).
center_zero: Whether the 2D origin of the plane is set to the center of mesh.
Defaults to True.
Returns:
A trimesh.Trimesh objects for the plane.
"""
# compute the vertices of the terrain
x0 = [size[0], size[1], height]
x1 = [size[0], 0.0, height]
x2 = [0.0, size[1], height]
x3 = [0.0, 0.0, height]
# generate the tri-mesh with two triangles
vertices = np.array([x0, x1, x2, x3])
faces = np.array([[1, 0, 2], [2, 3, 1]])
plane_mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
# center the plane at the origin
if center_zero:
plane_mesh.apply_translation(-np.array([size[0] / 2.0, size[1] / 2.0, 0.0]))
# return the tri-mesh and the position
return plane_mesh
def make_border(
size: tuple[float, float], inner_size: tuple[float, float], height: float, position: tuple[float, float, float]
) -> list[trimesh.Trimesh]:
"""Generate meshes for a rectangular border with a hole in the middle.
.. code:: text
+---------------------+
|#####################|
|##+---------------+##|
|##| |##|
|##| |##| length
|##| |##| (y-axis)
|##| |##|
|##+---------------+##|
|#####################|
+---------------------+
width (x-axis)
Args:
size: The length (along x) and width (along y) of the terrain (in m).
inner_size: The inner length (along x) and width (along y) of the hole (in m).
height: The height of the border (in m).
position: The center of the border (in m).
Returns:
A list of trimesh.Trimesh objects that represent the border.
"""
# compute thickness of the border
thickness_x = (size[0] - inner_size[0]) / 2.0
thickness_y = (size[1] - inner_size[1]) / 2.0
# generate tri-meshes for the border
# top/bottom border
box_dims = (size[0], thickness_y, height)
# -- top
box_pos = (position[0], position[1] + inner_size[1] / 2.0 + thickness_y / 2.0, position[2])
box_mesh_top = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# -- bottom
box_pos = (position[0], position[1] - inner_size[1] / 2.0 - thickness_y / 2.0, position[2])
box_mesh_bottom = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# left/right border
box_dims = (thickness_x, inner_size[1], height)
# -- left
box_pos = (position[0] - inner_size[0] / 2.0 - thickness_x / 2.0, position[1], position[2])
box_mesh_left = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# -- right
box_pos = (position[0] + inner_size[0] / 2.0 + thickness_x / 2.0, position[1], position[2])
box_mesh_right = trimesh.creation.box(box_dims, trimesh.transformations.translation_matrix(box_pos))
# return the tri-meshes
return [box_mesh_left, box_mesh_right, box_mesh_top, box_mesh_bottom]
def make_box(
length: float,
width: float,
height: float,
center: tuple[float, float, float],
max_yx_angle: float = 0,
degrees: bool = True,
) -> trimesh.Trimesh:
"""Generate a box mesh with a random orientation.
Args:
length: The length (along x) of the box (in m).
width: The width (along y) of the box (in m).
height: The height of the cylinder (in m).
center: The center of the cylinder (in m).
max_yx_angle: The maximum angle along the y and x axis. Defaults to 0.
degrees: Whether the angle is in degrees. Defaults to True.
Returns:
A trimesh.Trimesh object for the cylinder.
"""
# create a pose for the cylinder
transform = np.eye(4)
transform[0:3, -1] = np.asarray(center)
# -- create a random rotation
euler_zyx = tf.Rotation.random().as_euler("zyx") # returns rotation of shape (3,)
# -- cap the rotation along the y and x axis
if degrees:
max_yx_angle = max_yx_angle / 180.0
euler_zyx[1:] *= max_yx_angle
# -- apply the rotation
transform[0:3, 0:3] = tf.Rotation.from_euler("zyx", euler_zyx).as_matrix()
# create the box
dims = (length, width, height)
return trimesh.creation.box(dims, transform=transform)
def make_cylinder(
radius: float, height: float, center: tuple[float, float, float], max_yx_angle: float = 0, degrees: bool = True
) -> trimesh.Trimesh:
"""Generate a cylinder mesh with a random orientation.
Args:
radius: The radius of the cylinder (in m).
height: The height of the cylinder (in m).
center: The center of the cylinder (in m).
max_yx_angle: The maximum angle along the y and x axis. Defaults to 0.
degrees: Whether the angle is in degrees. Defaults to True.
Returns:
A trimesh.Trimesh object for the cylinder.
"""
# create a pose for the cylinder
transform = np.eye(4)
transform[0:3, -1] = np.asarray(center)
# -- create a random rotation
euler_zyx = tf.Rotation.random().as_euler("zyx") # returns rotation of shape (3,)
# -- cap the rotation along the y and x axis
if degrees:
max_yx_angle = max_yx_angle / 180.0
euler_zyx[1:] *= max_yx_angle
# -- apply the rotation
transform[0:3, 0:3] = tf.Rotation.from_euler("zyx", euler_zyx).as_matrix()
# create the cylinder
return trimesh.creation.cylinder(radius, height, sections=np.random.randint(4, 6), transform=transform)
def make_cone(
radius: float, height: float, center: tuple[float, float, float], max_yx_angle: float = 0, degrees: bool = True
) -> trimesh.Trimesh:
"""Generate a cone mesh with a random orientation.
Args:
radius: The radius of the cone (in m).
height: The height of the cone (in m).
center: The center of the cone (in m).
max_yx_angle: The maximum angle along the y and x axis. Defaults to 0.
degrees: Whether the angle is in degrees. Defaults to True.
Returns:
A trimesh.Trimesh object for the cone.
"""
# create a pose for the cylinder
transform = np.eye(4)
transform[0:3, -1] = np.asarray(center)
# -- create a random rotation
euler_zyx = tf.Rotation.random().as_euler("zyx") # returns rotation of shape (3,)
# -- cap the rotation along the y and x axis
if degrees:
max_yx_angle = max_yx_angle / 180.0
euler_zyx[1:] *= max_yx_angle
# -- apply the rotation
transform[0:3, 0:3] = tf.Rotation.from_euler("zyx", euler_zyx).as_matrix()
# create the cone
return trimesh.creation.cone(radius, height, sections=np.random.randint(4, 6), transform=transform)
| 7,578 | Python | 37.866666 | 115 | 0.608868 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/trimesh/mesh_terrains_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from typing import Literal
import omni.isaac.orbit.terrains.trimesh.mesh_terrains as mesh_terrains
import omni.isaac.orbit.terrains.trimesh.utils as mesh_utils_terrains
from omni.isaac.orbit.utils import configclass
from ..terrain_generator_cfg import SubTerrainBaseCfg
"""
Different trimesh terrain configurations.
"""
@configclass
class MeshPlaneTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a plane mesh terrain."""
function = mesh_terrains.flat_terrain
@configclass
class MeshPyramidStairsTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a pyramid stair mesh terrain."""
function = mesh_terrains.pyramid_stairs_terrain
border_width: float = 0.0
"""The width of the border around the terrain (in m). Defaults to 0.0.
The border is a flat terrain with the same height as the terrain.
"""
step_height_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the steps (in m)."""
step_width: float = MISSING
"""The width of the steps (in m)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
holes: bool = False
"""If True, the terrain will have holes in the steps. Defaults to False.
If :obj:`holes` is True, the terrain will have pyramid stairs of length or width
:obj:`platform_width` (depending on the direction) with no steps in the remaining area. Additionally,
no border will be added.
"""
@configclass
class MeshInvertedPyramidStairsTerrainCfg(MeshPyramidStairsTerrainCfg):
"""Configuration for an inverted pyramid stair mesh terrain.
Note:
This is the same as :class:`MeshPyramidStairsTerrainCfg` except that the steps are inverted.
"""
function = mesh_terrains.inverted_pyramid_stairs_terrain
@configclass
class MeshRandomGridTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a random grid mesh terrain."""
function = mesh_terrains.random_grid_terrain
grid_width: float = MISSING
"""The width of the grid cells (in m)."""
grid_height_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the grid cells (in m)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
holes: bool = False
"""If True, the terrain will have holes in the steps. Defaults to False.
If :obj:`holes` is True, the terrain will have randomized grid cells only along the plane extending
from the platform (like a plus sign). The remaining area remains empty and no border will be added.
"""
@configclass
class MeshRailsTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a terrain with box rails as extrusions."""
function = mesh_terrains.rails_terrain
rail_thickness_range: tuple[float, float] = MISSING
"""The thickness of the inner and outer rails (in m)."""
rail_height_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the rails (in m)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
@configclass
class MeshPitTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a terrain with a pit that leads out of the pit."""
function = mesh_terrains.pit_terrain
pit_depth_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the pit (in m)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
double_pit: bool = False
"""If True, the pit contains two levels of stairs. Defaults to False."""
@configclass
class MeshBoxTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a terrain with boxes (similar to a pyramid)."""
function = mesh_terrains.box_terrain
box_height_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the box (in m)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
double_box: bool = False
"""If True, the pit contains two levels of stairs/boxes. Defaults to False."""
@configclass
class MeshGapTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a terrain with a gap around the platform."""
function = mesh_terrains.gap_terrain
gap_width_range: tuple[float, float] = MISSING
"""The minimum and maximum width of the gap (in m)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
@configclass
class MeshFloatingRingTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a terrain with a floating ring around the center."""
function = mesh_terrains.floating_ring_terrain
ring_width_range: tuple[float, float] = MISSING
"""The minimum and maximum width of the ring (in m)."""
ring_height_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the ring (in m)."""
ring_thickness: float = MISSING
"""The thickness (along z) of the ring (in m)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
@configclass
class MeshStarTerrainCfg(SubTerrainBaseCfg):
"""Configuration for a terrain with a star pattern."""
function = mesh_terrains.star_terrain
num_bars: int = MISSING
"""The number of bars per-side the star. Must be greater than 2."""
bar_width_range: tuple[float, float] = MISSING
"""The minimum and maximum width of the bars in the star (in m)."""
bar_height_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the bars in the star (in m)."""
platform_width: float = 1.0
"""The width of the cylindrical platform at the center of the terrain. Defaults to 1.0."""
@configclass
class MeshRepeatedObjectsTerrainCfg(SubTerrainBaseCfg):
"""Base configuration for a terrain with repeated objects."""
@configclass
class ObjectCfg:
"""Configuration of repeated objects."""
num_objects: int = MISSING
"""The number of objects to add to the terrain."""
height: float = MISSING
"""The height (along z) of the object (in m)."""
function = mesh_terrains.repeated_objects_terrain
object_type: Literal["cylinder", "box", "cone"] | callable = MISSING
"""The type of object to generate.
The type can be a string or a callable. If it is a string, the function will look for a function called
``make_{object_type}`` in the current module scope. If it is a callable, the function will
use the callable to generate the object.
"""
object_params_start: ObjectCfg = MISSING
"""The object curriculum parameters at the start of the curriculum."""
object_params_end: ObjectCfg = MISSING
"""The object curriculum parameters at the end of the curriculum."""
max_height_noise: float = 0.0
"""The maximum amount of noise to add to the height of the objects (in m). Defaults to 0.0."""
platform_width: float = 1.0
"""The width of the cylindrical platform at the center of the terrain. Defaults to 1.0."""
@configclass
class MeshRepeatedPyramidsTerrainCfg(MeshRepeatedObjectsTerrainCfg):
"""Configuration for a terrain with repeated pyramids."""
@configclass
class ObjectCfg(MeshRepeatedObjectsTerrainCfg.ObjectCfg):
"""Configuration for a curriculum of repeated pyramids."""
radius: float = MISSING
"""The radius of the pyramids (in m)."""
max_yx_angle: float = 0.0
"""The maximum angle along the y and x axis. Defaults to 0.0."""
degrees: bool = True
"""Whether the angle is in degrees. Defaults to True."""
object_type = mesh_utils_terrains.make_cone
object_params_start: ObjectCfg = MISSING
"""The object curriculum parameters at the start of the curriculum."""
object_params_end: ObjectCfg = MISSING
"""The object curriculum parameters at the end of the curriculum."""
@configclass
class MeshRepeatedBoxesTerrainCfg(MeshRepeatedObjectsTerrainCfg):
"""Configuration for a terrain with repeated boxes."""
@configclass
class ObjectCfg(MeshRepeatedObjectsTerrainCfg.ObjectCfg):
"""Configuration for repeated boxes."""
size: tuple[float, float] = MISSING
"""The width (along x) and length (along y) of the box (in m)."""
max_yx_angle: float = 0.0
"""The maximum angle along the y and x axis. Defaults to 0.0."""
degrees: bool = True
"""Whether the angle is in degrees. Defaults to True."""
object_type = mesh_utils_terrains.make_box
object_params_start: ObjectCfg = MISSING
"""The box curriculum parameters at the start of the curriculum."""
object_params_end: ObjectCfg = MISSING
"""The box curriculum parameters at the end of the curriculum."""
@configclass
class MeshRepeatedCylindersTerrainCfg(MeshRepeatedObjectsTerrainCfg):
"""Configuration for a terrain with repeated cylinders."""
@configclass
class ObjectCfg(MeshRepeatedObjectsTerrainCfg.ObjectCfg):
"""Configuration for repeated cylinder."""
radius: float = MISSING
"""The radius of the pyramids (in m)."""
max_yx_angle: float = 0.0
"""The maximum angle along the y and x axis. Defaults to 0.0."""
degrees: bool = True
"""Whether the angle is in degrees. Defaults to True."""
object_type = mesh_utils_terrains.make_cylinder
object_params_start: ObjectCfg = MISSING
"""The box curriculum parameters at the start of the curriculum."""
object_params_end: ObjectCfg = MISSING
"""The box curriculum parameters at the end of the curriculum."""
| 9,933 | Python | 35.792592 | 107 | 0.695661 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/height_field/hf_terrains.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Functions to generate height fields for different terrains."""
from __future__ import annotations
import numpy as np
import scipy.interpolate as interpolate
from typing import TYPE_CHECKING
from .utils import height_field_to_mesh
if TYPE_CHECKING:
from . import hf_terrains_cfg
@height_field_to_mesh
def random_uniform_terrain(difficulty: float, cfg: hf_terrains_cfg.HfRandomUniformTerrainCfg) -> np.ndarray:
"""Generate a terrain with height sampled uniformly from a specified range.
.. image:: ../../_static/terrains/height_field/random_uniform_terrain.jpg
:width: 40%
:align: center
Note:
The :obj:`difficulty` parameter is ignored for this terrain.
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
The height field of the terrain as a 2D numpy array with discretized heights.
The shape of the array is (width, length), where width and length are the number of points
along the x and y axis, respectively.
Raises:
ValueError: When the downsampled scale is smaller than the horizontal scale.
"""
# check parameters
# -- horizontal scale
if cfg.downsampled_scale is None:
cfg.downsampled_scale = cfg.horizontal_scale
elif cfg.downsampled_scale < cfg.horizontal_scale:
raise ValueError(
"Downsampled scale must be larger than or equal to the horizontal scale:"
f" {cfg.downsampled_scale} < {cfg.horizontal_scale}."
)
# switch parameters to discrete units
# -- horizontal scale
width_pixels = int(cfg.size[0] / cfg.horizontal_scale)
length_pixels = int(cfg.size[1] / cfg.horizontal_scale)
# -- downsampled scale
width_downsampled = int(cfg.size[0] / cfg.downsampled_scale)
length_downsampled = int(cfg.size[1] / cfg.downsampled_scale)
# -- height
height_min = int(cfg.noise_range[0] / cfg.vertical_scale)
height_max = int(cfg.noise_range[1] / cfg.vertical_scale)
height_step = int(cfg.noise_step / cfg.vertical_scale)
# create range of heights possible
height_range = np.arange(height_min, height_max + height_step, height_step)
# sample heights randomly from the range along a grid
height_field_downsampled = np.random.choice(height_range, size=(width_downsampled, length_downsampled))
# create interpolation function for the sampled heights
x = np.linspace(0, cfg.size[0] * cfg.horizontal_scale, width_downsampled)
y = np.linspace(0, cfg.size[1] * cfg.horizontal_scale, length_downsampled)
func = interpolate.RectBivariateSpline(x, y, height_field_downsampled)
# interpolate the sampled heights to obtain the height field
x_upsampled = np.linspace(0, cfg.size[0] * cfg.horizontal_scale, width_pixels)
y_upsampled = np.linspace(0, cfg.size[1] * cfg.horizontal_scale, length_pixels)
z_upsampled = func(x_upsampled, y_upsampled)
# round off the interpolated heights to the nearest vertical step
return np.rint(z_upsampled).astype(np.int16)
@height_field_to_mesh
def pyramid_sloped_terrain(difficulty: float, cfg: hf_terrains_cfg.HfPyramidSlopedTerrainCfg) -> np.ndarray:
"""Generate a terrain with a truncated pyramid structure.
The terrain is a pyramid-shaped sloped surface with a slope of :obj:`slope` that trims into a flat platform
at the center. The slope is defined as the ratio of the height change along the x axis to the width along the
x axis. For example, a slope of 1.0 means that the height changes by 1 unit for every 1 unit of width.
If the :obj:`cfg.inverted` flag is set to :obj:`True`, the terrain is inverted such that
the platform is at the bottom.
.. image:: ../../_static/terrains/height_field/pyramid_sloped_terrain.jpg
:width: 40%
.. image:: ../../_static/terrains/height_field/inverted_pyramid_sloped_terrain.jpg
:width: 40%
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
The height field of the terrain as a 2D numpy array with discretized heights.
The shape of the array is (width, length), where width and length are the number of points
along the x and y axis, respectively.
"""
# resolve terrain configuration
if cfg.inverted:
slope = -cfg.slope_range[0] - difficulty * (cfg.slope_range[1] - cfg.slope_range[0])
else:
slope = cfg.slope_range[0] + difficulty * (cfg.slope_range[1] - cfg.slope_range[0])
# switch parameters to discrete units
# -- horizontal scale
width_pixels = int(cfg.size[0] / cfg.horizontal_scale)
length_pixels = int(cfg.size[1] / cfg.horizontal_scale)
# -- height
# we want the height to be 1/2 of the width since the terrain is a pyramid
height_max = int(slope * cfg.size[0] / 2 / cfg.vertical_scale)
# -- center of the terrain
center_x = int(width_pixels / 2)
center_y = int(length_pixels / 2)
# create a meshgrid of the terrain
x = np.arange(0, width_pixels)
y = np.arange(0, length_pixels)
xx, yy = np.meshgrid(x, y, sparse=True)
# offset the meshgrid to the center of the terrain
xx = (center_x - np.abs(center_x - xx)) / center_x
yy = (center_y - np.abs(center_y - yy)) / center_y
# reshape the meshgrid to be 2D
xx = xx.reshape(width_pixels, 1)
yy = yy.reshape(1, length_pixels)
# create a sloped surface
hf_raw = np.zeros((width_pixels, length_pixels))
hf_raw = height_max * xx * yy
# create a flat platform at the center of the terrain
platform_width = int(cfg.platform_width / cfg.horizontal_scale / 2)
# get the height of the platform at the corner of the platform
x_pf = width_pixels // 2 - platform_width
y_pf = length_pixels // 2 - platform_width
z_pf = hf_raw[x_pf, y_pf]
hf_raw = np.clip(hf_raw, min(0, z_pf), max(0, z_pf))
# round off the heights to the nearest vertical step
return np.rint(hf_raw).astype(np.int16)
@height_field_to_mesh
def pyramid_stairs_terrain(difficulty: float, cfg: hf_terrains_cfg.HfPyramidStairsTerrainCfg) -> np.ndarray:
"""Generate a terrain with a pyramid stair pattern.
The terrain is a pyramid stair pattern which trims to a flat platform at the center of the terrain.
If the :obj:`cfg.inverted` flag is set to :obj:`True`, the terrain is inverted such that
the platform is at the bottom.
.. image:: ../../_static/terrains/height_field/pyramid_stairs_terrain.jpg
:width: 40%
.. image:: ../../_static/terrains/height_field/inverted_pyramid_stairs_terrain.jpg
:width: 40%
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
The height field of the terrain as a 2D numpy array with discretized heights.
The shape of the array is (width, length), where width and length are the number of points
along the x and y axis, respectively.
"""
# resolve terrain configuration
step_height = cfg.step_height_range[0] + difficulty * (cfg.step_height_range[1] - cfg.step_height_range[0])
if cfg.inverted:
step_height *= -1
# switch parameters to discrete units
# -- terrain
width_pixels = int(cfg.size[0] / cfg.horizontal_scale)
length_pixels = int(cfg.size[1] / cfg.horizontal_scale)
# -- stairs
step_width = int(cfg.step_width / cfg.horizontal_scale)
step_height = int(step_height / cfg.vertical_scale)
# -- platform
platform_width = int(cfg.platform_width / cfg.horizontal_scale)
# create a terrain with a flat platform at the center
hf_raw = np.zeros((width_pixels, length_pixels))
# add the steps
current_step_height = 0
start_x, start_y = 0, 0
stop_x, stop_y = width_pixels, length_pixels
while (stop_x - start_x) > platform_width and (stop_y - start_y) > platform_width:
# increment position
# -- x
start_x += step_width
stop_x -= step_width
# -- y
start_y += step_width
stop_y -= step_width
# increment height
current_step_height += step_height
# add the step
hf_raw[start_x:stop_x, start_y:stop_y] = current_step_height
# round off the heights to the nearest vertical step
return np.rint(hf_raw).astype(np.int16)
@height_field_to_mesh
def discrete_obstacles_terrain(difficulty: float, cfg: hf_terrains_cfg.HfDiscreteObstaclesTerrainCfg) -> np.ndarray:
"""Generate a terrain with randomly generated obstacles as pillars with positive and negative heights.
The terrain is a flat platform at the center of the terrain with randomly generated obstacles as pillars
with positive and negative height. The obstacles are randomly generated cuboids with a random width and
height. They are placed randomly on the terrain with a minimum distance of :obj:`cfg.platform_width`
from the center of the terrain.
.. image:: ../../_static/terrains/height_field/discrete_obstacles_terrain.jpg
:width: 40%
:align: center
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
The height field of the terrain as a 2D numpy array with discretized heights.
The shape of the array is (width, length), where width and length are the number of points
along the x and y axis, respectively.
"""
# resolve terrain configuration
obs_height = cfg.obstacle_height_range[0] + difficulty * (
cfg.obstacle_height_range[1] - cfg.obstacle_height_range[0]
)
# switch parameters to discrete units
# -- terrain
width_pixels = int(cfg.size[0] / cfg.horizontal_scale)
length_pixels = int(cfg.size[1] / cfg.horizontal_scale)
# -- obstacles
obs_height = int(obs_height / cfg.vertical_scale)
obs_width_min = int(cfg.obstacle_width_range[0] / cfg.horizontal_scale)
obs_width_max = int(cfg.obstacle_width_range[1] / cfg.horizontal_scale)
# -- center of the terrain
platform_width = int(cfg.platform_width / cfg.horizontal_scale)
# create discrete ranges for the obstacles
# -- shape
obs_width_range = np.arange(obs_width_min, obs_width_max, 4)
obs_length_range = np.arange(obs_width_min, obs_width_max, 4)
# -- position
obs_x_range = np.arange(0, width_pixels, 4)
obs_y_range = np.arange(0, length_pixels, 4)
# create a terrain with a flat platform at the center
hf_raw = np.zeros((width_pixels, length_pixels))
# generate the obstacles
for _ in range(cfg.num_obstacles):
# sample size
if cfg.obstacle_height_mode == "choice":
height = np.random.choice([-obs_height, -obs_height // 2, obs_height // 2, obs_height])
elif cfg.obstacle_height_mode == "fixed":
height = obs_height
else:
raise ValueError(f"Unknown obstacle height mode '{cfg.obstacle_height_mode}'. Must be 'choice' or 'fixed'.")
width = int(np.random.choice(obs_width_range))
length = int(np.random.choice(obs_length_range))
# sample position
x_start = int(np.random.choice(obs_x_range))
y_start = int(np.random.choice(obs_y_range))
# clip start position to the terrain
if x_start + width > width_pixels:
x_start = width_pixels - width
if y_start + length > length_pixels:
y_start = length_pixels - length
# add to terrain
hf_raw[x_start : x_start + width, y_start : y_start + length] = height
# clip the terrain to the platform
x1 = (width_pixels - platform_width) // 2
x2 = (width_pixels + platform_width) // 2
y1 = (length_pixels - platform_width) // 2
y2 = (length_pixels + platform_width) // 2
hf_raw[x1:x2, y1:y2] = 0
# round off the heights to the nearest vertical step
return np.rint(hf_raw).astype(np.int16)
@height_field_to_mesh
def wave_terrain(difficulty: float, cfg: hf_terrains_cfg.HfWaveTerrainCfg) -> np.ndarray:
r"""Generate a terrain with a wave pattern.
The terrain is a flat platform at the center of the terrain with a wave pattern. The wave pattern
is generated by adding sinusoidal waves based on the number of waves and the amplitude of the waves.
The height of the terrain at a point :math:`(x, y)` is given by:
.. math::
h(x, y) = A \left(\sin\left(\frac{2 \pi x}{\lambda}\right) + \cos\left(\frac{2 \pi y}{\lambda}\right) \right)
where :math:`A` is the amplitude of the waves, :math:`\lambda` is the wavelength of the waves.
.. image:: ../../_static/terrains/height_field/wave_terrain.jpg
:width: 40%
:align: center
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
The height field of the terrain as a 2D numpy array with discretized heights.
The shape of the array is (width, length), where width and length are the number of points
along the x and y axis, respectively.
Raises:
ValueError: When the number of waves is non-positive.
"""
# check number of waves
if cfg.num_waves < 0:
raise ValueError(f"Number of waves must be a positive integer. Got: {cfg.num_waves}.")
# resolve terrain configuration
amplitude = cfg.amplitude_range[0] + difficulty * (cfg.amplitude_range[1] - cfg.amplitude_range[0])
# switch parameters to discrete units
# -- terrain
width_pixels = int(cfg.size[0] / cfg.horizontal_scale)
length_pixels = int(cfg.size[1] / cfg.horizontal_scale)
amplitude_pixels = int(0.5 * amplitude / cfg.vertical_scale)
# compute the wave number: nu = 2 * pi / lambda
wave_length = length_pixels / cfg.num_waves
wave_number = 2 * np.pi / wave_length
# create meshgrid for the terrain
x = np.arange(0, width_pixels)
y = np.arange(0, length_pixels)
xx, yy = np.meshgrid(x, y, sparse=True)
xx = xx.reshape(width_pixels, 1)
yy = yy.reshape(1, length_pixels)
# create a terrain with a flat platform at the center
hf_raw = np.zeros((width_pixels, length_pixels))
# add the waves
hf_raw += amplitude_pixels * (np.cos(yy * wave_number) + np.sin(xx * wave_number))
# round off the heights to the nearest vertical step
return np.rint(hf_raw).astype(np.int16)
@height_field_to_mesh
def stepping_stones_terrain(difficulty: float, cfg: hf_terrains_cfg.HfSteppingStonesTerrainCfg) -> np.ndarray:
"""Generate a terrain with a stepping stones pattern.
The terrain is a stepping stones pattern which trims to a flat platform at the center of the terrain.
.. image:: ../../_static/terrains/height_field/stepping_stones_terrain.jpg
:width: 40%
:align: center
Args:
difficulty: The difficulty of the terrain. This is a value between 0 and 1.
cfg: The configuration for the terrain.
Returns:
The height field of the terrain as a 2D numpy array with discretized heights.
The shape of the array is (width, length), where width and length are the number of points
along the x and y axis, respectively.
"""
# resolve terrain configuration
stone_width = cfg.stone_width_range[1] - difficulty * (cfg.stone_width_range[1] - cfg.stone_width_range[0])
stone_distance = cfg.stone_distance_range[0] + difficulty * (
cfg.stone_distance_range[1] - cfg.stone_distance_range[0]
)
# switch parameters to discrete units
# -- terrain
width_pixels = int(cfg.size[0] / cfg.horizontal_scale)
length_pixels = int(cfg.size[1] / cfg.horizontal_scale)
# -- stones
stone_distance = int(stone_distance / cfg.horizontal_scale)
stone_width = int(stone_width / cfg.horizontal_scale)
stone_height_max = int(cfg.stone_height_max / cfg.vertical_scale)
# -- holes
holes_depth = int(cfg.holes_depth / cfg.vertical_scale)
# -- platform
platform_width = int(cfg.platform_width / cfg.horizontal_scale)
# create range of heights
stone_height_range = np.arange(-stone_height_max - 1, stone_height_max, step=1)
# create a terrain with a flat platform at the center
hf_raw = np.full((width_pixels, length_pixels), holes_depth)
# add the stones
start_x, start_y = 0, 0
# -- if the terrain is longer than it is wide then fill the terrain column by column
if length_pixels >= width_pixels:
while start_y < length_pixels:
# ensure that stone stops along y-axis
stop_y = min(length_pixels, start_y + stone_width)
# randomly sample x-position
start_x = np.random.randint(0, stone_width)
stop_x = max(0, start_x - stone_distance)
# fill first stone
hf_raw[0:stop_x, start_y:stop_y] = np.random.choice(stone_height_range)
# fill row with stones
while start_x < width_pixels:
stop_x = min(width_pixels, start_x + stone_width)
hf_raw[start_x:stop_x, start_y:stop_y] = np.random.choice(stone_height_range)
start_x += stone_width + stone_distance
# update y-position
start_y += stone_width + stone_distance
elif width_pixels > length_pixels:
while start_x < width_pixels:
# ensure that stone stops along x-axis
stop_x = min(width_pixels, start_x + stone_width)
# randomly sample y-position
start_y = np.random.randint(0, stone_width)
stop_y = max(0, start_y - stone_distance)
# fill first stone
hf_raw[start_x:stop_x, 0:stop_y] = np.random.choice(stone_height_range)
# fill column with stones
while start_y < length_pixels:
stop_y = min(length_pixels, start_y + stone_width)
hf_raw[start_x:stop_x, start_y:stop_y] = np.random.choice(stone_height_range)
start_y += stone_width + stone_distance
# update x-position
start_x += stone_width + stone_distance
# add the platform in the center
x1 = (width_pixels - platform_width) // 2
x2 = (width_pixels + platform_width) // 2
y1 = (length_pixels - platform_width) // 2
y2 = (length_pixels + platform_width) // 2
hf_raw[x1:x2, y1:y2] = 0
# round off the heights to the nearest vertical step
return np.rint(hf_raw).astype(np.int16)
| 18,737 | Python | 41.878718 | 120 | 0.660138 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/height_field/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
This sub-module provides utilities to create different terrains as height fields (HF).
Height fields are a 2.5D terrain representation that is used in robotics to obtain the
height of the terrain at a given point. This is useful for controls and planning algorithms.
Each terrain is represented as a 2D numpy array with discretized heights. The shape of the array
is (width, length), where width and length are the number of points along the x and y axis,
respectively. The height of the terrain at a given point is obtained by indexing the array with
the corresponding x and y coordinates.
.. caution::
When working with height field terrains, it is important to remember that the terrain is generated
from a discretized 3D representation. This means that the height of the terrain at a given point
is only an approximation of the real height of the terrain at that point. The discretization
error is proportional to the size of the discretization cells. Therefore, it is important to
choose a discretization size that is small enough for the application. A larger discretization
size will result in a faster simulation, but the terrain will be less accurate.
"""
from .hf_terrains_cfg import (
HfDiscreteObstaclesTerrainCfg,
HfInvertedPyramidSlopedTerrainCfg,
HfInvertedPyramidStairsTerrainCfg,
HfPyramidSlopedTerrainCfg,
HfPyramidStairsTerrainCfg,
HfRandomUniformTerrainCfg,
HfSteppingStonesTerrainCfg,
HfTerrainBaseCfg,
HfWaveTerrainCfg,
)
| 1,637 | Python | 40.999999 | 102 | 0.782529 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/height_field/utils.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import copy
import functools
import numpy as np
import trimesh
from collections.abc import Callable
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .hf_terrains_cfg import HfTerrainBaseCfg
def height_field_to_mesh(func: Callable) -> Callable:
"""Decorator to convert a height field function to a mesh function.
This decorator converts a height field function to a mesh function by sampling the heights
at a specified resolution and performing interpolation to obtain the intermediate heights.
Additionally, it adds a border around the terrain to avoid artifacts at the edges.
Args:
func: The height field function to convert. The function should return a 2D numpy array
with the heights of the terrain.
Returns:
The mesh function. The mesh function returns a tuple containing a list of ``trimesh``
mesh objects and the origin of the terrain.
"""
@functools.wraps(func)
def wrapper(difficulty: float, cfg: HfTerrainBaseCfg):
# check valid border width
if cfg.border_width > 0 and cfg.border_width < cfg.horizontal_scale:
raise ValueError(
f"The border width ({cfg.border_width}) must be greater than or equal to the"
f" horizontal scale ({cfg.horizontal_scale})."
)
# allocate buffer for height field (with border)
width_pixels = int(cfg.size[0] / cfg.horizontal_scale) + 1
length_pixels = int(cfg.size[1] / cfg.horizontal_scale) + 1
border_pixels = int(cfg.border_width / cfg.horizontal_scale) + 1
heights = np.zeros((width_pixels, length_pixels), dtype=np.int16)
# override size of the terrain to account for the border
sub_terrain_size = [width_pixels - 2 * border_pixels, length_pixels - 2 * border_pixels]
sub_terrain_size = [dim * cfg.horizontal_scale for dim in sub_terrain_size]
# update the config
terrain_size = copy.deepcopy(cfg.size)
cfg.size = tuple(sub_terrain_size)
# generate the height field
z_gen = func(difficulty, cfg)
# handle the border for the terrain
heights[border_pixels:-border_pixels, border_pixels:-border_pixels] = z_gen
# set terrain size back to config
cfg.size = terrain_size
# convert to trimesh
vertices, triangles = convert_height_field_to_mesh(
heights, cfg.horizontal_scale, cfg.vertical_scale, cfg.slope_threshold
)
mesh = trimesh.Trimesh(vertices=vertices, faces=triangles)
# compute origin
x1 = int((cfg.size[0] * 0.5 - 1) / cfg.horizontal_scale)
x2 = int((cfg.size[0] * 0.5 + 1) / cfg.horizontal_scale)
y1 = int((cfg.size[1] * 0.5 - 1) / cfg.horizontal_scale)
y2 = int((cfg.size[1] * 0.5 + 1) / cfg.horizontal_scale)
origin_z = np.max(heights[x1:x2, y1:y2]) * cfg.vertical_scale
origin = np.array([0.5 * cfg.size[0], 0.5 * cfg.size[1], origin_z])
# return mesh and origin
return [mesh], origin
return wrapper
def convert_height_field_to_mesh(
height_field: np.ndarray, horizontal_scale: float, vertical_scale: float, slope_threshold: float | None = None
) -> tuple[np.ndarray, np.ndarray]:
"""Convert a height-field array to a triangle mesh represented by vertices and triangles.
This function converts a height-field array to a triangle mesh represented by vertices and triangles.
The height-field array is assumed to be a 2D array of floats, where each element represents the height
of the terrain at that location. The height-field array is assumed to be in the form of a matrix, where
the first dimension represents the x-axis and the second dimension represents the y-axis.
The function can also correct vertical surfaces above the provide slope threshold. This is helpful to
avoid having long vertical surfaces in the mesh. The correction is done by moving the vertices of the
vertical surfaces to minimum of the two neighboring vertices.
The correction is done in the following way:
If :math:`\\frac{y_2 - y_1}{x_2 - x_1} > threshold`, then move A to A' (i.e., set :math:`x_1' = x_2`).
This is repeated along all directions.
.. code-block:: none
B(x_2,y_2)
/|
/ |
/ |
(x_1,y_1)A---A'(x_1',y_1)
Args:
height_field: The input height-field array.
horizontal_scale: The discretization of the terrain along the x and y axis.
vertical_scale: The discretization of the terrain along the z axis.
slope_threshold: The slope threshold above which surfaces are made vertical.
Defaults to None, in which case no correction is applied.
Returns:
The vertices and triangles of the mesh:
- **vertices** (np.ndarray(float)): Array of shape (num_vertices, 3).
Each row represents the location of each vertex (in m).
- **triangles** (np.ndarray(int)): Array of shape (num_triangles, 3).
Each row represents the indices of the 3 vertices connected by this triangle.
"""
# read height field
num_rows, num_cols = height_field.shape
# create a mesh grid of the height field
y = np.linspace(0, (num_cols - 1) * horizontal_scale, num_cols)
x = np.linspace(0, (num_rows - 1) * horizontal_scale, num_rows)
yy, xx = np.meshgrid(y, x)
# copy height field to avoid modifying the original array
hf = height_field.copy()
# correct vertical surfaces above the slope threshold
if slope_threshold is not None:
# scale slope threshold based on the horizontal and vertical scale
slope_threshold *= horizontal_scale / vertical_scale
# allocate arrays to store the movement of the vertices
move_x = np.zeros((num_rows, num_cols))
move_y = np.zeros((num_rows, num_cols))
move_corners = np.zeros((num_rows, num_cols))
# move vertices along the x-axis
move_x[: num_rows - 1, :] += hf[1:num_rows, :] - hf[: num_rows - 1, :] > slope_threshold
move_x[1:num_rows, :] -= hf[: num_rows - 1, :] - hf[1:num_rows, :] > slope_threshold
# move vertices along the y-axis
move_y[:, : num_cols - 1] += hf[:, 1:num_cols] - hf[:, : num_cols - 1] > slope_threshold
move_y[:, 1:num_cols] -= hf[:, : num_cols - 1] - hf[:, 1:num_cols] > slope_threshold
# move vertices along the corners
move_corners[: num_rows - 1, : num_cols - 1] += (
hf[1:num_rows, 1:num_cols] - hf[: num_rows - 1, : num_cols - 1] > slope_threshold
)
move_corners[1:num_rows, 1:num_cols] -= (
hf[: num_rows - 1, : num_cols - 1] - hf[1:num_rows, 1:num_cols] > slope_threshold
)
xx += (move_x + move_corners * (move_x == 0)) * horizontal_scale
yy += (move_y + move_corners * (move_y == 0)) * horizontal_scale
# create vertices for the mesh
vertices = np.zeros((num_rows * num_cols, 3), dtype=np.float32)
vertices[:, 0] = xx.flatten()
vertices[:, 1] = yy.flatten()
vertices[:, 2] = hf.flatten() * vertical_scale
# create triangles for the mesh
triangles = -np.ones((2 * (num_rows - 1) * (num_cols - 1), 3), dtype=np.uint32)
for i in range(num_rows - 1):
ind0 = np.arange(0, num_cols - 1) + i * num_cols
ind1 = ind0 + 1
ind2 = ind0 + num_cols
ind3 = ind2 + 1
start = 2 * i * (num_cols - 1)
stop = start + 2 * (num_cols - 1)
triangles[start:stop:2, 0] = ind0
triangles[start:stop:2, 1] = ind3
triangles[start:stop:2, 2] = ind1
triangles[start + 1 : stop : 2, 0] = ind0
triangles[start + 1 : stop : 2, 1] = ind2
triangles[start + 1 : stop : 2, 2] = ind3
return vertices, triangles
| 8,005 | Python | 45.011494 | 114 | 0.630231 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/height_field/hf_terrains_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from omni.isaac.orbit.utils import configclass
from ..terrain_generator_cfg import SubTerrainBaseCfg
from . import hf_terrains
@configclass
class HfTerrainBaseCfg(SubTerrainBaseCfg):
"""The base configuration for height field terrains."""
border_width: float = 0.0
"""The width of the border/padding around the terrain (in m). Defaults to 0.0.
The border width is subtracted from the :obj:`size` of the terrain. If non-zero, it must be
greater than or equal to the :obj:`horizontal scale`.
"""
horizontal_scale: float = 0.1
"""The discretization of the terrain along the x and y axes (in m). Defaults to 0.1."""
vertical_scale: float = 0.005
"""The discretization of the terrain along the z axis (in m). Defaults to 0.005."""
slope_threshold: float | None = None
"""The slope threshold above which surfaces are made vertical. Defaults to None,
in which case no correction is applied."""
"""
Different height field terrain configurations.
"""
@configclass
class HfRandomUniformTerrainCfg(HfTerrainBaseCfg):
"""Configuration for a random uniform height field terrain."""
function = hf_terrains.random_uniform_terrain
noise_range: tuple[float, float] = MISSING
"""The minimum and maximum height noise (i.e. along z) of the terrain (in m)."""
noise_step: float = MISSING
"""The minimum height (in m) change between two points."""
downsampled_scale: float | None = None
"""The distance between two randomly sampled points on the terrain. Defaults to None,
in which case the :obj:`horizontal scale` is used.
The heights are sampled at this resolution and interpolation is performed for intermediate points.
This must be larger than or equal to the :obj:`horizontal scale`.
"""
@configclass
class HfPyramidSlopedTerrainCfg(HfTerrainBaseCfg):
"""Configuration for a pyramid sloped height field terrain."""
function = hf_terrains.pyramid_sloped_terrain
slope_range: tuple[float, float] = MISSING
"""The slope of the terrain (in radians)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
inverted: bool = False
"""Whether the pyramid is inverted. Defaults to False.
If True, the terrain is inverted such that the platform is at the bottom and the slopes are upwards.
"""
@configclass
class HfInvertedPyramidSlopedTerrainCfg(HfPyramidSlopedTerrainCfg):
"""Configuration for an inverted pyramid sloped height field terrain.
Note:
This is a subclass of :class:`HfPyramidSlopedTerrainCfg` with :obj:`inverted` set to True.
We make it as a separate class to make it easier to distinguish between the two and match
the naming convention of the other terrains.
"""
inverted: bool = True
@configclass
class HfPyramidStairsTerrainCfg(HfTerrainBaseCfg):
"""Configuration for a pyramid stairs height field terrain."""
function = hf_terrains.pyramid_stairs_terrain
step_height_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the steps (in m)."""
step_width: float = MISSING
"""The width of the steps (in m)."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
inverted: bool = False
"""Whether the pyramid stairs is inverted. Defaults to False.
If True, the terrain is inverted such that the platform is at the bottom and the stairs are upwards.
"""
@configclass
class HfInvertedPyramidStairsTerrainCfg(HfPyramidStairsTerrainCfg):
"""Configuration for an inverted pyramid stairs height field terrain.
Note:
This is a subclass of :class:`HfPyramidStairsTerrainCfg` with :obj:`inverted` set to True.
We make it as a separate class to make it easier to distinguish between the two and match
the naming convention of the other terrains.
"""
inverted: bool = True
@configclass
class HfDiscreteObstaclesTerrainCfg(HfTerrainBaseCfg):
"""Configuration for a discrete obstacles height field terrain."""
function = hf_terrains.discrete_obstacles_terrain
obstacle_height_mode: str = "choice"
"""The mode to use for the obstacle height. Defaults to "choice".
The following modes are supported: "choice", "fixed".
"""
obstacle_width_range: tuple[float, float] = MISSING
"""The minimum and maximum width of the obstacles (in m)."""
obstacle_height_range: tuple[float, float] = MISSING
"""The minimum and maximum height of the obstacles (in m)."""
num_obstacles: int = MISSING
"""The number of obstacles to generate."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
@configclass
class HfWaveTerrainCfg(HfTerrainBaseCfg):
"""Configuration for a wave height field terrain."""
function = hf_terrains.wave_terrain
amplitude_range: tuple[float, float] = MISSING
"""The minimum and maximum amplitude of the wave (in m)."""
num_waves: int = 1.0
"""The number of waves to generate. Defaults to 1.0."""
@configclass
class HfSteppingStonesTerrainCfg(HfTerrainBaseCfg):
"""Configuration for a stepping stones height field terrain."""
function = hf_terrains.stepping_stones_terrain
stone_height_max: float = MISSING
"""The maximum height of the stones (in m)."""
stone_width_range: tuple[float, float] = MISSING
"""The minimum and maximum width of the stones (in m)."""
stone_distance_range: tuple[float, float] = MISSING
"""The minimum and maximum distance between stones (in m)."""
holes_depth: float = -10.0
"""The depth of the holes (negative obstacles). Defaults to -10.0."""
platform_width: float = 1.0
"""The width of the square platform at the center of the terrain. Defaults to 1.0."""
| 6,068 | Python | 35.125 | 104 | 0.706658 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/config/rough.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for custom terrains."""
import omni.isaac.orbit.terrains as terrain_gen
from ..terrain_generator_cfg import TerrainGeneratorCfg
ROUGH_TERRAINS_CFG = TerrainGeneratorCfg(
size=(8.0, 8.0),
border_width=20.0,
num_rows=10,
num_cols=20,
horizontal_scale=0.1,
vertical_scale=0.005,
slope_threshold=0.75,
use_cache=False,
sub_terrains={
"pyramid_stairs": terrain_gen.MeshPyramidStairsTerrainCfg(
proportion=0.2,
step_height_range=(0.05, 0.23),
step_width=0.3,
platform_width=3.0,
border_width=1.0,
holes=False,
),
"pyramid_stairs_inv": terrain_gen.MeshInvertedPyramidStairsTerrainCfg(
proportion=0.2,
step_height_range=(0.05, 0.23),
step_width=0.3,
platform_width=3.0,
border_width=1.0,
holes=False,
),
"boxes": terrain_gen.MeshRandomGridTerrainCfg(
proportion=0.2, grid_width=0.45, grid_height_range=(0.05, 0.2), platform_width=2.0
),
"random_rough": terrain_gen.HfRandomUniformTerrainCfg(
proportion=0.2, noise_range=(0.02, 0.10), noise_step=0.02, border_width=0.25
),
"hf_pyramid_slope": terrain_gen.HfPyramidSlopedTerrainCfg(
proportion=0.1, slope_range=(0.0, 0.4), platform_width=2.0, border_width=0.25
),
"hf_pyramid_slope_inv": terrain_gen.HfInvertedPyramidSlopedTerrainCfg(
proportion=0.1, slope_range=(0.0, 0.4), platform_width=2.0, border_width=0.25
),
},
)
"""Rough terrains configuration."""
| 1,768 | Python | 32.377358 | 94 | 0.609163 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/timer.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for a timer class that can be used for performance measurements."""
from __future__ import annotations
import time
from contextlib import ContextDecorator
from typing import Any
class TimerError(Exception):
"""A custom exception used to report errors in use of :class:`Timer` class."""
pass
class Timer(ContextDecorator):
"""A timer for performance measurements.
A class to keep track of time for performance measurement.
It allows timing via context managers and decorators as well.
It uses the `time.perf_counter` function to measure time. This function
returns the number of seconds since the epoch as a float. It has the
highest resolution available on the system.
As a regular object:
.. code-block:: python
import time
from omni.isaac.orbit.utils.timer import Timer
timer = Timer()
timer.start()
time.sleep(1)
print(1 <= timer.time_elapsed <= 2) # Output: True
time.sleep(1)
timer.stop()
print(2 <= stopwatch.total_run_time) # Output: True
As a context manager:
.. code-block:: python
import time
from omni.isaac.orbit.utils.timer import Timer
with Timer() as timer:
time.sleep(1)
print(1 <= timer.time_elapsed <= 2) # Output: True
Reference: https://gist.github.com/sumeet/1123871
"""
def __init__(self, msg: str | None = None):
"""Initializes the timer.
Args:
msg: The message to display when using the timer
class in a context manager. Defaults to None.
"""
self._msg = msg
self._start_time = None
self._stop_time = None
self._elapsed_time = None
def __str__(self) -> str:
"""A string representation of the class object.
Returns:
A string containing the elapsed time.
"""
return f"{self.time_elapsed:0.6f} seconds"
"""
Properties
"""
@property
def time_elapsed(self) -> float:
"""The number of seconds that have elapsed since this timer started timing.
Note:
This is used for checking how much time has elapsed while the timer is still running.
"""
return time.perf_counter() - self._start_time
@property
def total_run_time(self) -> float:
"""The number of seconds that elapsed from when the timer started to when it ended."""
return self._elapsed_time
"""
Operations
"""
def start(self):
"""Start timing."""
if self._start_time is not None:
raise TimerError("Timer is running. Use .stop() to stop it")
self._start_time = time.perf_counter()
def stop(self):
"""Stop timing."""
if self._start_time is None:
raise TimerError("Timer is not running. Use .start() to start it")
self._stop_time = time.perf_counter()
self._elapsed_time = self._stop_time - self._start_time
self._start_time = None
"""
Context managers
"""
def __enter__(self) -> Timer:
"""Start timing and return this `Timer` instance."""
self.start()
return self
def __exit__(self, *exc_info: Any):
"""Stop timing."""
self.stop()
# print message
if self._msg is not None:
print(self._msg, f": {self._elapsed_time:0.6f} seconds")
| 3,572 | Python | 25.272059 | 97 | 0.599944 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/string.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing utilities for transforming strings and regular expressions."""
import ast
import importlib
import inspect
import re
from collections.abc import Callable, Sequence
from typing import Any
"""
String formatting.
"""
def to_camel_case(snake_str: str, to: str = "cC") -> str:
"""Converts a string from snake case to camel case.
Args:
snake_str: A string in snake case (i.e. with '_')
to: Convention to convert string to. Defaults to "cC".
Raises:
ValueError: Invalid input argument `to`, i.e. not "cC" or "CC".
Returns:
A string in camel-case format.
"""
# check input is correct
if to not in ["cC", "CC"]:
msg = "to_camel_case(): Choose a valid `to` argument (CC or cC)"
raise ValueError(msg)
# convert string to lower case and split
components = snake_str.lower().split("_")
if to == "cC":
# We capitalize the first letter of each component except the first one
# with the 'title' method and join them together.
return components[0] + "".join(x.title() for x in components[1:])
else:
# Capitalize first letter in all the components
return "".join(x.title() for x in components)
def to_snake_case(camel_str: str) -> str:
"""Converts a string from camel case to snake case.
Args:
camel_str: A string in camel case.
Returns:
A string in snake case (i.e. with '_')
"""
camel_str = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_str)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", camel_str).lower()
"""
String <-> Callable operations.
"""
def is_lambda_expression(name: str) -> bool:
"""Checks if the input string is a lambda expression.
Args:
name: The input string.
Returns:
Whether the input string is a lambda expression.
"""
try:
ast.parse(name)
return isinstance(ast.parse(name).body[0], ast.Expr) and isinstance(ast.parse(name).body[0].value, ast.Lambda)
except SyntaxError:
return False
def callable_to_string(value: Callable) -> str:
"""Converts a callable object to a string.
Args:
value: A callable object.
Raises:
ValueError: When the input argument is not a callable object.
Returns:
A string representation of the callable object.
"""
# check if callable
if not callable(value):
raise ValueError(f"The input argument is not callable: {value}.")
# check if lambda function
if value.__name__ == "<lambda>":
return f"lambda {inspect.getsourcelines(value)[0][0].strip().split('lambda')[1].strip().split(',')[0]}"
else:
# get the module and function name
module_name = value.__module__
function_name = value.__name__
# return the string
return f"{module_name}:{function_name}"
def string_to_callable(name: str) -> Callable:
"""Resolves the module and function names to return the function.
Args:
name: The function name. The format should be 'module:attribute_name' or a
lambda expression of format: 'lambda x: x'.
Raises:
ValueError: When the resolved attribute is not a function.
ValueError: When the module cannot be found.
Returns:
Callable: The function loaded from the module.
"""
try:
if is_lambda_expression(name):
callable_object = eval(name)
else:
mod_name, attr_name = name.split(":")
mod = importlib.import_module(mod_name)
callable_object = getattr(mod, attr_name)
# check if attribute is callable
if callable(callable_object):
return callable_object
else:
raise AttributeError(f"The imported object is not callable: '{name}'")
except (ValueError, ModuleNotFoundError) as e:
msg = (
f"Could not resolve the input string '{name}' into callable object."
" The format of input should be 'module:attribute_name'.\n"
f"Received the error:\n {e}."
)
raise ValueError(msg)
"""
Regex operations.
"""
def resolve_matching_names(
keys: str | Sequence[str], list_of_strings: Sequence[str], preserve_order: bool = False
) -> tuple[list[int], list[str]]:
"""Match a list of query regular expressions against a list of strings and return the matched indices and names.
When a list of query regular expressions is provided, the function checks each target string against each
query regular expression and returns the indices of the matched strings and the matched strings.
If the :attr:`preserve_order` is True, the ordering of the matched indices and names is the same as the order
of the provided list of strings. This means that the ordering is dictated by the order of the target strings
and not the order of the query regular expressions.
If the :attr:`preserve_order` is False, the ordering of the matched indices and names is the same as the order
of the provided list of query regular expressions.
For example, consider the list of strings is ['a', 'b', 'c', 'd', 'e'] and the regular expressions are ['a|c', 'b'].
If :attr:`preserve_order` is False, then the function will return the indices of the matched strings and the
strings as: ([0, 1, 2], ['a', 'b', 'c']). When :attr:`preserve_order` is True, it will return them as:
([0, 2, 1], ['a', 'c', 'b']).
Note:
The function does not sort the indices. It returns the indices in the order they are found.
Args:
keys: A regular expression or a list of regular expressions to match the strings in the list.
list_of_strings: A list of strings to match.
preserve_order: Whether to preserve the order of the query keys in the returned values. Defaults to False.
Returns:
A tuple of lists containing the matched indices and names.
Raises:
ValueError: When multiple matches are found for a string in the list.
ValueError: When not all regular expressions are matched.
"""
# resolve name keys
if isinstance(keys, str):
keys = [keys]
# find matching patterns
index_list = []
names_list = []
key_idx_list = []
# book-keeping to check that we always have a one-to-one mapping
# i.e. each target string should match only one regular expression
target_strings_match_found = [None for _ in range(len(list_of_strings))]
keys_match_found = [[] for _ in range(len(keys))]
# loop over all target strings
for target_index, potential_match_string in enumerate(list_of_strings):
for key_index, re_key in enumerate(keys):
if re.fullmatch(re_key, potential_match_string):
# check if match already found
if target_strings_match_found[target_index]:
raise ValueError(
f"Multiple matches for '{potential_match_string}':"
f" '{target_strings_match_found[target_index]}' and '{re_key}'!"
)
# add to list
target_strings_match_found[target_index] = re_key
index_list.append(target_index)
names_list.append(potential_match_string)
key_idx_list.append(key_index)
# add for regex key
keys_match_found[key_index].append(potential_match_string)
# reorder keys if they should be returned in order of the query keys
if preserve_order:
reordered_index_list = [None] * len(index_list)
global_index = 0
for key_index in range(len(keys)):
for key_idx_position, key_idx_entry in enumerate(key_idx_list):
if key_idx_entry == key_index:
reordered_index_list[key_idx_position] = global_index
global_index += 1
# reorder index and names list
index_list_reorder = [None] * len(index_list)
names_list_reorder = [None] * len(index_list)
for idx, reorder_idx in enumerate(reordered_index_list):
index_list_reorder[reorder_idx] = index_list[idx]
names_list_reorder[reorder_idx] = names_list[idx]
# update
index_list = index_list_reorder
names_list = names_list_reorder
# check that all regular expressions are matched
if not all(keys_match_found):
# make this print nicely aligned for debugging
msg = "\n"
for key, value in zip(keys, keys_match_found):
msg += f"\t{key}: {value}\n"
msg += f"Available strings: {list_of_strings}\n"
# raise error
raise ValueError(
f"Not all regular expressions are matched! Please check that the regular expressions are correct: {msg}"
)
# return
return index_list, names_list
def resolve_matching_names_values(
data: dict[str, Any], list_of_strings: Sequence[str], preserve_order: bool = False
) -> tuple[list[int], list[str], list[Any]]:
"""Match a list of regular expressions in a dictionary against a list of strings and return
the matched indices, names, and values.
If the :attr:`preserve_order` is True, the ordering of the matched indices and names is the same as the order
of the provided list of strings. This means that the ordering is dictated by the order of the target strings
and not the order of the query regular expressions.
If the :attr:`preserve_order` is False, the ordering of the matched indices and names is the same as the order
of the provided list of query regular expressions.
For example, consider the dictionary is {"a|d|e": 1, "b|c": 2}, the list of strings is ['a', 'b', 'c', 'd', 'e'].
If :attr:`preserve_order` is False, then the function will return the indices of the matched strings, the
matched strings, and the values as: ([0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e'], [1, 2, 2, 1, 1]). When
:attr:`preserve_order` is True, it will return them as: ([0, 3, 4, 1, 2], ['a', 'd', 'e', 'b', 'c'], [1, 1, 1, 2, 2]).
Args:
data: A dictionary of regular expressions and values to match the strings in the list.
list_of_strings: A list of strings to match.
preserve_order: Whether to preserve the order of the query keys in the returned values. Defaults to False.
Returns:
A tuple of lists containing the matched indices, names, and values.
Raises:
TypeError: When the input argument :attr:`data` is not a dictionary.
ValueError: When multiple matches are found for a string in the dictionary.
ValueError: When not all regular expressions in the data keys are matched.
"""
# check valid input
if not isinstance(data, dict):
raise TypeError(f"Input argument `data` should be a dictionary. Received: {data}")
# find matching patterns
index_list = []
names_list = []
values_list = []
key_idx_list = []
# book-keeping to check that we always have a one-to-one mapping
# i.e. each target string should match only one regular expression
target_strings_match_found = [None for _ in range(len(list_of_strings))]
keys_match_found = [[] for _ in range(len(data))]
# loop over all target strings
for target_index, potential_match_string in enumerate(list_of_strings):
for key_index, (re_key, value) in enumerate(data.items()):
if re.fullmatch(re_key, potential_match_string):
# check if match already found
if target_strings_match_found[target_index]:
raise ValueError(
f"Multiple matches for '{potential_match_string}':"
f" '{target_strings_match_found[target_index]}' and '{re_key}'!"
)
# add to list
target_strings_match_found[target_index] = re_key
index_list.append(target_index)
names_list.append(potential_match_string)
values_list.append(value)
key_idx_list.append(key_index)
# add for regex key
keys_match_found[key_index].append(potential_match_string)
# reorder keys if they should be returned in order of the query keys
if preserve_order:
reordered_index_list = [None] * len(index_list)
global_index = 0
for key_index in range(len(data)):
for key_idx_position, key_idx_entry in enumerate(key_idx_list):
if key_idx_entry == key_index:
reordered_index_list[key_idx_position] = global_index
global_index += 1
# reorder index and names list
index_list_reorder = [None] * len(index_list)
names_list_reorder = [None] * len(index_list)
values_list_reorder = [None] * len(index_list)
for idx, reorder_idx in enumerate(reordered_index_list):
index_list_reorder[reorder_idx] = index_list[idx]
names_list_reorder[reorder_idx] = names_list[idx]
values_list_reorder[reorder_idx] = values_list[idx]
# update
index_list = index_list_reorder
names_list = names_list_reorder
values_list = values_list_reorder
# check that all regular expressions are matched
if not all(keys_match_found):
# make this print nicely aligned for debugging
msg = "\n"
for key, value in zip(data.keys(), keys_match_found):
msg += f"\t{key}: {value}\n"
msg += f"Available strings: {list_of_strings}\n"
# raise error
raise ValueError(
f"Not all regular expressions are matched! Please check that the regular expressions are correct: {msg}"
)
# return
return index_list, names_list, values_list
| 13,974 | Python | 40.224189 | 122 | 0.625734 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package containing utilities for common operations and helper functions."""
from .array import *
from .configclass import configclass
from .dict import *
from .string import *
from .timer import Timer
| 332 | Python | 24.615383 | 82 | 0.76506 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/array.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing utilities for working with different array backends."""
# needed to import for allowing type-hinting: torch.device | str | None
from __future__ import annotations
import numpy as np
import torch
from typing import Union
import warp as wp
TensorData = Union[np.ndarray, torch.Tensor, wp.array]
"""Type definition for a tensor data.
Union of numpy, torch, and warp arrays.
"""
TENSOR_TYPES = {
"numpy": np.ndarray,
"torch": torch.Tensor,
"warp": wp.array,
}
"""A dictionary containing the types for each backend.
The keys are the name of the backend ("numpy", "torch", "warp") and the values are the corresponding type
(``np.ndarray``, ``torch.Tensor``, ``wp.array``).
"""
TENSOR_TYPE_CONVERSIONS = {
"numpy": {wp.array: lambda x: x.numpy(), torch.Tensor: lambda x: x.detach().cpu().numpy()},
"torch": {wp.array: lambda x: wp.torch.to_torch(x), np.ndarray: lambda x: torch.from_numpy(x)},
"warp": {np.array: lambda x: wp.array(x), torch.Tensor: lambda x: wp.torch.from_torch(x)},
}
"""A nested dictionary containing the conversion functions for each backend.
The keys of the outer dictionary are the name of target backend ("numpy", "torch", "warp"). The keys of the
inner dictionary are the source backend (``np.ndarray``, ``torch.Tensor``, ``wp.array``).
"""
def convert_to_torch(
array: TensorData,
dtype: torch.dtype = None,
device: torch.device | str | None = None,
) -> torch.Tensor:
"""Converts a given array into a torch tensor.
The function tries to convert the array to a torch tensor. If the array is a numpy/warp arrays, or python
list/tuples, it is converted to a torch tensor. If the array is already a torch tensor, it is returned
directly.
If ``device`` is None, then the function deduces the current device of the data. For numpy arrays,
this defaults to "cpu", for torch tensors it is "cpu" or "cuda", and for warp arrays it is "cuda".
Note:
Since PyTorch does not support unsigned integer types, unsigned integer arrays are converted to
signed integer arrays. This is done by casting the array to the corresponding signed integer type.
Args:
array: The input array. It can be a numpy array, warp array, python list/tuple, or torch tensor.
dtype: Target data-type for the tensor.
device: The target device for the tensor. Defaults to None.
Returns:
The converted array as torch tensor.
"""
# Convert array to tensor
# if the datatype is not currently supported by torch we need to improvise
# supported types are: https://pytorch.org/docs/stable/tensors.html
if isinstance(array, torch.Tensor):
tensor = array
elif isinstance(array, np.ndarray):
if array.dtype == np.uint32:
array = array.astype(np.int32)
# need to deal with object arrays (np.void) separately
tensor = torch.from_numpy(array)
elif isinstance(array, wp.array):
if array.dtype == wp.uint32:
array = array.view(wp.int32)
tensor = wp.to_torch(array)
else:
tensor = torch.Tensor(array)
# Convert tensor to the right device
if device is not None and str(tensor.device) != str(device):
tensor = tensor.to(device)
# Convert dtype of tensor if requested
if dtype is not None and tensor.dtype != dtype:
tensor = tensor.type(dtype)
return tensor
| 3,552 | Python | 36.010416 | 109 | 0.680462 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/math.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing utilities for various math operations."""
# needed to import for allowing type-hinting: torch.Tensor | np.ndarray
from __future__ import annotations
import numpy as np
import torch
import torch.nn.functional
from typing import Literal
"""
General
"""
@torch.jit.script
def scale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor:
"""Normalizes a given input tensor to a range of [-1, 1].
.. note::
It uses pytorch broadcasting functionality to deal with batched input.
Args:
x: Input tensor of shape (N, dims).
lower: The minimum value of the tensor. Shape is (N, dims) or (dims,).
upper: The maximum value of the tensor. Shape is (N, dims) or (dims,).
Returns:
Normalized transform of the tensor. Shape is (N, dims).
"""
# default value of center
offset = (lower + upper) * 0.5
# return normalized tensor
return 2 * (x - offset) / (upper - lower)
@torch.jit.script
def unscale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor:
"""De-normalizes a given input tensor from range of [-1, 1] to (lower, upper).
.. note::
It uses pytorch broadcasting functionality to deal with batched input.
Args:
x: Input tensor of shape (N, dims).
lower: The minimum value of the tensor. Shape is (N, dims) or (dims,).
upper: The maximum value of the tensor. Shape is (N, dims) or (dims,).
Returns:
De-normalized transform of the tensor. Shape is (N, dims).
"""
# default value of center
offset = (lower + upper) * 0.5
# return normalized tensor
return x * (upper - lower) * 0.5 + offset
@torch.jit.script
def saturate(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor:
"""Clamps a given input tensor to (lower, upper).
It uses pytorch broadcasting functionality to deal with batched input.
Args:
x: Input tensor of shape (N, dims).
lower: The minimum value of the tensor. Shape is (N, dims) or (dims,).
upper: The maximum value of the tensor. Shape is (N, dims) or (dims,).
Returns:
Clamped transform of the tensor. Shape is (N, dims).
"""
return torch.max(torch.min(x, upper), lower)
@torch.jit.script
def normalize(x: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
"""Normalizes a given input tensor to unit length.
Args:
x: Input tensor of shape (N, dims).
eps: A small value to avoid division by zero. Defaults to 1e-9.
Returns:
Normalized tensor of shape (N, dims).
"""
return x / x.norm(p=2, dim=-1).clamp(min=eps, max=None).unsqueeze(-1)
@torch.jit.script
def wrap_to_pi(angles: torch.Tensor) -> torch.Tensor:
"""Wraps input angles (in radians) to the range [-pi, pi].
Args:
angles: Input angles of any shape.
Returns:
Angles in the range [-pi, pi].
"""
angles = angles.clone()
angles %= 2 * torch.pi
angles -= 2 * torch.pi * (angles > torch.pi)
return angles
@torch.jit.script
def copysign(mag: float, other: torch.Tensor) -> torch.Tensor:
"""Create a new floating-point tensor with the magnitude of input and the sign of other, element-wise.
Note:
The implementation follows from `torch.copysign`. The function allows a scalar magnitude.
Args:
mag: The magnitude scalar.
other: The tensor containing values whose signbits are applied to magnitude.
Returns:
The output tensor.
"""
mag = torch.tensor(mag, device=other.device, dtype=torch.float).repeat(other.shape[0])
return torch.abs(mag) * torch.sign(other)
"""
Rotation
"""
@torch.jit.script
def matrix_from_quat(quaternions: torch.Tensor) -> torch.Tensor:
"""Convert rotations given as quaternions to rotation matrices.
Args:
quaternions: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
Returns:
Rotation matrices. The shape is (..., 3, 3).
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L41-L70
"""
r, i, j, k = torch.unbind(quaternions, -1)
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
two_s = 2.0 / (quaternions * quaternions).sum(-1)
o = torch.stack(
(
1 - two_s * (j * j + k * k),
two_s * (i * j - k * r),
two_s * (i * k + j * r),
two_s * (i * j + k * r),
1 - two_s * (i * i + k * k),
two_s * (j * k - i * r),
two_s * (i * k - j * r),
two_s * (j * k + i * r),
1 - two_s * (i * i + j * j),
),
-1,
)
return o.reshape(quaternions.shape[:-1] + (3, 3))
def convert_quat(quat: torch.Tensor | np.ndarray, to: Literal["xyzw", "wxyz"] = "xyzw") -> torch.Tensor | np.ndarray:
"""Converts quaternion from one convention to another.
The convention to convert TO is specified as an optional argument. If to == 'xyzw',
then the input is in 'wxyz' format, and vice-versa.
Args:
quat: The quaternion of shape (..., 4).
to: Convention to convert quaternion to.. Defaults to "xyzw".
Returns:
The converted quaternion in specified convention.
Raises:
ValueError: Invalid input argument `to`, i.e. not "xyzw" or "wxyz".
ValueError: Invalid shape of input `quat`, i.e. not (..., 4,).
"""
# check input is correct
if quat.shape[-1] != 4:
msg = f"Expected input quaternion shape mismatch: {quat.shape} != (..., 4)."
raise ValueError(msg)
if to not in ["xyzw", "wxyz"]:
msg = f"Expected input argument `to` to be 'xyzw' or 'wxyz'. Received: {to}."
raise ValueError(msg)
# check if input is numpy array (we support this backend since some classes use numpy)
if isinstance(quat, np.ndarray):
# use numpy functions
if to == "xyzw":
# wxyz -> xyzw
return np.roll(quat, -1, axis=-1)
else:
# xyzw -> wxyz
return np.roll(quat, 1, axis=-1)
else:
# convert to torch (sanity check)
if not isinstance(quat, torch.Tensor):
quat = torch.tensor(quat, dtype=float)
# convert to specified quaternion type
if to == "xyzw":
# wxyz -> xyzw
return quat.roll(-1, dims=-1)
else:
# xyzw -> wxyz
return quat.roll(1, dims=-1)
@torch.jit.script
def quat_conjugate(q: torch.Tensor) -> torch.Tensor:
"""Computes the conjugate of a quaternion.
Args:
q: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
Returns:
The conjugate quaternion in (w, x, y, z). Shape is (..., 4).
"""
shape = q.shape
q = q.reshape(-1, 4)
return torch.cat((q[:, 0:1], -q[:, 1:]), dim=-1).view(shape)
@torch.jit.script
def quat_inv(q: torch.Tensor) -> torch.Tensor:
"""Compute the inverse of a quaternion.
Args:
q: The quaternion orientation in (w, x, y, z). Shape is (N, 4).
Returns:
The inverse quaternion in (w, x, y, z). Shape is (N, 4).
"""
return normalize(quat_conjugate(q))
@torch.jit.script
def quat_from_euler_xyz(roll: torch.Tensor, pitch: torch.Tensor, yaw: torch.Tensor) -> torch.Tensor:
"""Convert rotations given as Euler angles in radians to Quaternions.
Note:
The euler angles are assumed in XYZ convention.
Args:
roll: Rotation around x-axis (in radians). Shape is (N,).
pitch: Rotation around y-axis (in radians). Shape is (N,).
yaw: Rotation around z-axis (in radians). Shape is (N,).
Returns:
The quaternion in (w, x, y, z). Shape is (N, 4).
"""
cy = torch.cos(yaw * 0.5)
sy = torch.sin(yaw * 0.5)
cr = torch.cos(roll * 0.5)
sr = torch.sin(roll * 0.5)
cp = torch.cos(pitch * 0.5)
sp = torch.sin(pitch * 0.5)
# compute quaternion
qw = cy * cr * cp + sy * sr * sp
qx = cy * sr * cp - sy * cr * sp
qy = cy * cr * sp + sy * sr * cp
qz = sy * cr * cp - cy * sr * sp
return torch.stack([qw, qx, qy, qz], dim=-1)
@torch.jit.script
def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor:
"""Returns torch.sqrt(torch.max(0, x)) but with a zero sub-gradient where x is 0.
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L91-L99
"""
ret = torch.zeros_like(x)
positive_mask = x > 0
ret[positive_mask] = torch.sqrt(x[positive_mask])
return ret
@torch.jit.script
def quat_from_matrix(matrix: torch.Tensor) -> torch.Tensor:
"""Convert rotations given as rotation matrices to quaternions.
Args:
matrix: The rotation matrices. Shape is (..., 3, 3).
Returns:
The quaternion in (w, x, y, z). Shape is (..., 4).
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L102-L161
"""
if matrix.size(-1) != 3 or matrix.size(-2) != 3:
raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.")
batch_dim = matrix.shape[:-2]
m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(matrix.reshape(batch_dim + (9,)), dim=-1)
q_abs = _sqrt_positive_part(
torch.stack(
[
1.0 + m00 + m11 + m22,
1.0 + m00 - m11 - m22,
1.0 - m00 + m11 - m22,
1.0 - m00 - m11 + m22,
],
dim=-1,
)
)
# we produce the desired quaternion multiplied by each of r, i, j, k
quat_by_rijk = torch.stack(
[
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1),
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1),
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1),
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1),
],
dim=-2,
)
# We floor here at 0.1 but the exact level is not important; if q_abs is small,
# the candidate won't be picked.
flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device)
quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr))
# if not for numerical problems, quat_candidates[i] should be same (up to a sign),
# forall i; we pick the best-conditioned one (with the largest denominator)
return quat_candidates[torch.nn.functional.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :].reshape(
batch_dim + (4,)
)
def _axis_angle_rotation(axis: Literal["X", "Y", "Z"], angle: torch.Tensor) -> torch.Tensor:
"""Return the rotation matrices for one of the rotations about an axis of which Euler angles describe,
for each value of the angle given.
Args:
axis: Axis label "X" or "Y or "Z".
angle: Euler angles in radians of any shape.
Returns:
Rotation matrices. Shape is (..., 3, 3).
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L164-L191
"""
cos = torch.cos(angle)
sin = torch.sin(angle)
one = torch.ones_like(angle)
zero = torch.zeros_like(angle)
if axis == "X":
R_flat = (one, zero, zero, zero, cos, -sin, zero, sin, cos)
elif axis == "Y":
R_flat = (cos, zero, sin, zero, one, zero, -sin, zero, cos)
elif axis == "Z":
R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one)
else:
raise ValueError("letter must be either X, Y or Z.")
return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3))
def matrix_from_euler(euler_angles: torch.Tensor, convention: str) -> torch.Tensor:
"""
Convert rotations given as Euler angles in radians to rotation matrices.
Args:
euler_angles: Euler angles in radians. Shape is (..., 3).
convention: Convention string of three uppercase letters from {"X", "Y", and "Z"}.
For example, "XYZ" means that the rotations should be applied first about x,
then y, then z.
Returns:
Rotation matrices. Shape is (..., 3, 3).
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L194-L220
"""
if euler_angles.dim() == 0 or euler_angles.shape[-1] != 3:
raise ValueError("Invalid input euler angles.")
if len(convention) != 3:
raise ValueError("Convention must have 3 letters.")
if convention[1] in (convention[0], convention[2]):
raise ValueError(f"Invalid convention {convention}.")
for letter in convention:
if letter not in ("X", "Y", "Z"):
raise ValueError(f"Invalid letter {letter} in convention string.")
matrices = [_axis_angle_rotation(c, e) for c, e in zip(convention, torch.unbind(euler_angles, -1))]
# return functools.reduce(torch.matmul, matrices)
return torch.matmul(torch.matmul(matrices[0], matrices[1]), matrices[2])
@torch.jit.script
def euler_xyz_from_quat(quat: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert rotations given as quaternions to Euler angles in radians.
Note:
The euler angles are assumed in XYZ convention.
Args:
quat: The quaternion orientation in (w, x, y, z). Shape is (N, 4).
Returns:
A tuple containing roll-pitch-yaw. Each element is a tensor of shape (N,).
Reference:
https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
"""
q_w, q_x, q_y, q_z = quat[:, 0], quat[:, 1], quat[:, 2], quat[:, 3]
# roll (x-axis rotation)
sin_roll = 2.0 * (q_w * q_x + q_y * q_z)
cos_roll = 1 - 2 * (q_x * q_x + q_y * q_y)
roll = torch.atan2(sin_roll, cos_roll)
# pitch (y-axis rotation)
sin_pitch = 2.0 * (q_w * q_y - q_z * q_x)
pitch = torch.where(torch.abs(sin_pitch) >= 1, copysign(torch.pi / 2.0, sin_pitch), torch.asin(sin_pitch))
# yaw (z-axis rotation)
sin_yaw = 2.0 * (q_w * q_z + q_x * q_y)
cos_yaw = 1 - 2 * (q_y * q_y + q_z * q_z)
yaw = torch.atan2(sin_yaw, cos_yaw)
return roll % (2 * torch.pi), pitch % (2 * torch.pi), yaw % (2 * torch.pi) # TODO: why not wrap_to_pi here ?
@torch.jit.script
def quat_unique(q: torch.Tensor) -> torch.Tensor:
"""Convert a unit quaternion to a standard form where the real part is non-negative.
Quaternion representations have a singularity since ``q`` and ``-q`` represent the same
rotation. This function ensures the real part of the quaternion is non-negative.
Args:
q: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
Returns:
Standardized quaternions. Shape is (..., 4).
"""
return torch.where(q[..., 0:1] < 0, -q, q)
@torch.jit.script
def quat_mul(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
"""Multiply two quaternions together.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (..., 4).
q2: The second quaternion in (w, x, y, z). Shape is (..., 4).
Returns:
The product of the two quaternions in (w, x, y, z). Shape is (..., 4).
Raises:
ValueError: Input shapes of ``q1`` and ``q2`` are not matching.
"""
# check input is correct
if q1.shape != q2.shape:
msg = f"Expected input quaternion shape mismatch: {q1.shape} != {q2.shape}."
raise ValueError(msg)
# reshape to (N, 4) for multiplication
shape = q1.shape
q1 = q1.reshape(-1, 4)
q2 = q2.reshape(-1, 4)
# extract components from quaternions
w1, x1, y1, z1 = q1[:, 0], q1[:, 1], q1[:, 2], q1[:, 3]
w2, x2, y2, z2 = q2[:, 0], q2[:, 1], q2[:, 2], q2[:, 3]
# perform multiplication
ww = (z1 + x1) * (x2 + y2)
yy = (w1 - y1) * (w2 + z2)
zz = (w1 + y1) * (w2 - z2)
xx = ww + yy + zz
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
w = qq - ww + (z1 - y1) * (y2 - z2)
x = qq - xx + (x1 + w1) * (x2 + w2)
y = qq - yy + (w1 - x1) * (y2 + z2)
z = qq - zz + (z1 + y1) * (w2 - x2)
return torch.stack([w, x, y, z], dim=-1).view(shape)
@torch.jit.script
def quat_box_minus(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
"""The box-minus operator (quaternion difference) between two quaternions.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (N, 4).
q2: The second quaternion in (w, x, y, z). Shape is (N, 4).
Returns:
The difference between the two quaternions. Shape is (N, 3).
Reference:
https://docs.leggedrobotics.com/kindr/cheatsheet_latest.pdf
"""
quat_diff = quat_mul(q1, quat_conjugate(q2)) # q1 * q2^-1
re = quat_diff[:, 0] # real part, q = [w, x, y, z] = [re, im]
im = quat_diff[:, 1:] # imaginary part
norm_im = torch.norm(im, dim=1)
scale = 2.0 * torch.where(norm_im > 1.0e-7, torch.atan2(norm_im, re) / norm_im, torch.sign(re))
return scale.unsqueeze(-1) * im
@torch.jit.script
def yaw_quat(quat: torch.Tensor) -> torch.Tensor:
"""Extract the yaw component of a quaternion.
Args:
quat: The orientation in (w, x, y, z). Shape is (..., 4)
Returns:
A quaternion with only yaw component.
"""
shape = quat.shape
quat_yaw = quat.clone().view(-1, 4)
qw = quat_yaw[:, 0]
qx = quat_yaw[:, 1]
qy = quat_yaw[:, 2]
qz = quat_yaw[:, 3]
yaw = torch.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
quat_yaw[:] = 0.0
quat_yaw[:, 3] = torch.sin(yaw / 2)
quat_yaw[:, 0] = torch.cos(yaw / 2)
quat_yaw = normalize(quat_yaw)
return quat_yaw.view(shape)
@torch.jit.script
def quat_apply(quat: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:
"""Apply a quaternion rotation to a vector.
Args:
quat: The quaternion in (w, x, y, z). Shape is (..., 4).
vec: The vector in (x, y, z). Shape is (..., 3).
Returns:
The rotated vector in (x, y, z). Shape is (..., 3).
"""
# store shape
shape = vec.shape
# reshape to (N, 3) for multiplication
quat = quat.reshape(-1, 4)
vec = vec.reshape(-1, 3)
# extract components from quaternions
xyz = quat[:, 1:]
t = xyz.cross(vec, dim=-1) * 2
return (vec + quat[:, 0:1] * t + xyz.cross(t, dim=-1)).view(shape)
@torch.jit.script
def quat_apply_yaw(quat: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:
"""Rotate a vector only around the yaw-direction.
Args:
quat: The orientation in (w, x, y, z). Shape is (N, 4).
vec: The vector in (x, y, z). Shape is (N, 3).
Returns:
The rotated vector in (x, y, z). Shape is (N, 3).
"""
quat_yaw = yaw_quat(quat)
return quat_apply(quat_yaw, vec)
@torch.jit.script
def quat_rotate(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
"""Rotate a vector by a quaternion.
Args:
q: The quaternion in (w, x, y, z). Shape is (N, 4).
v: The vector in (x, y, z). Shape is (N, 3).
Returns:
The rotated vector in (x, y, z). Shape is (N, 3).
"""
shape = q.shape
q_w = q[:, 0]
q_vec = q[:, 1:]
a = v * (2.0 * q_w**2 - 1.0).unsqueeze(-1)
b = torch.cross(q_vec, v, dim=-1) * q_w.unsqueeze(-1) * 2.0
c = q_vec * torch.bmm(q_vec.view(shape[0], 1, 3), v.view(shape[0], 3, 1)).squeeze(-1) * 2.0
return a + b + c
@torch.jit.script
def quat_rotate_inverse(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
"""Rotate a vector by the inverse of a quaternion.
Args:
q: The quaternion in (w, x, y, z). Shape is (N, 4).
v: The vector in (x, y, z). Shape is (N, 3).
Returns:
The rotated vector in (x, y, z). Shape is (N, 3).
"""
shape = q.shape
q_w = q[:, 0]
q_vec = q[:, 1:]
a = v * (2.0 * q_w**2 - 1.0).unsqueeze(-1)
b = torch.cross(q_vec, v, dim=-1) * q_w.unsqueeze(-1) * 2.0
c = q_vec * torch.bmm(q_vec.view(shape[0], 1, 3), v.view(shape[0], 3, 1)).squeeze(-1) * 2.0
return a - b + c
@torch.jit.script
def quat_from_angle_axis(angle: torch.Tensor, axis: torch.Tensor) -> torch.Tensor:
"""Convert rotations given as angle-axis to quaternions.
Args:
angle: The angle turned anti-clockwise in radians around the vector's direction. Shape is (N,).
axis: The axis of rotation. Shape is (N, 3).
Returns:
The quaternion in (w, x, y, z). Shape is (N, 4).
"""
theta = (angle / 2).unsqueeze(-1)
xyz = normalize(axis) * theta.sin()
w = theta.cos()
return normalize(torch.cat([w, xyz], dim=-1))
@torch.jit.script
def axis_angle_from_quat(quat: torch.Tensor, eps: float = 1.0e-6) -> torch.Tensor:
"""Convert rotations given as quaternions to axis/angle.
Args:
quat: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
eps: The tolerance for Taylor approximation. Defaults to 1.0e-6.
Returns:
Rotations given as a vector in axis angle form. Shape is (..., 3).
The vector's magnitude is the angle turned anti-clockwise in radians around the vector's direction.
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L526-L554
"""
# Modified to take in quat as [q_w, q_x, q_y, q_z]
# Quaternion is [q_w, q_x, q_y, q_z] = [cos(theta/2), n_x * sin(theta/2), n_y * sin(theta/2), n_z * sin(theta/2)]
# Axis-angle is [a_x, a_y, a_z] = [theta * n_x, theta * n_y, theta * n_z]
# Thus, axis-angle is [q_x, q_y, q_z] / (sin(theta/2) / theta)
# When theta = 0, (sin(theta/2) / theta) is undefined
# However, as theta --> 0, we can use the Taylor approximation 1/2 - theta^2 / 48
quat = quat * (1.0 - 2.0 * (quat[..., 0:1] < 0.0))
mag = torch.linalg.norm(quat[..., 1:], dim=-1)
half_angle = torch.atan2(mag, quat[..., 0])
angle = 2.0 * half_angle
# check whether to apply Taylor approximation
sin_half_angles_over_angles = torch.where(
angle.abs() > eps, torch.sin(half_angle) / angle, 0.5 - angle * angle / 48
)
return quat[..., 1:4] / sin_half_angles_over_angles.unsqueeze(-1)
@torch.jit.script
def quat_error_magnitude(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
"""Computes the rotation difference between two quaternions.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (..., 4).
q2: The second quaternion in (w, x, y, z). Shape is (..., 4).
Returns:
Angular error between input quaternions in radians.
"""
quat_diff = quat_mul(q1, quat_conjugate(q2))
return torch.norm(axis_angle_from_quat(quat_diff), dim=-1)
@torch.jit.script
def skew_symmetric_matrix(vec: torch.Tensor) -> torch.Tensor:
"""Computes the skew-symmetric matrix of a vector.
Args:
vec: The input vector. Shape is (3,) or (N, 3).
Returns:
The skew-symmetric matrix. Shape is (1, 3, 3) or (N, 3, 3).
Raises:
ValueError: If input tensor is not of shape (..., 3).
"""
# check input is correct
if vec.shape[-1] != 3:
raise ValueError(f"Expected input vector shape mismatch: {vec.shape} != (..., 3).")
# unsqueeze the last dimension
if vec.ndim == 1:
vec = vec.unsqueeze(0)
# create a skew-symmetric matrix
skew_sym_mat = torch.zeros(vec.shape[0], 3, 3, device=vec.device, dtype=vec.dtype)
skew_sym_mat[:, 0, 1] = -vec[:, 2]
skew_sym_mat[:, 0, 2] = vec[:, 1]
skew_sym_mat[:, 1, 2] = -vec[:, 0]
skew_sym_mat[:, 1, 0] = vec[:, 2]
skew_sym_mat[:, 2, 0] = -vec[:, 1]
skew_sym_mat[:, 2, 1] = vec[:, 0]
return skew_sym_mat
"""
Transformations
"""
def is_identity_pose(pos: torch.tensor, rot: torch.tensor) -> bool:
"""Checks if input poses are identity transforms.
The function checks if the input position and orientation are close to zero and
identity respectively using L2-norm. It does NOT check the error in the orientation.
Args:
pos: The cartesian position. Shape is (N, 3).
rot: The quaternion in (w, x, y, z). Shape is (N, 4).
Returns:
True if all the input poses result in identity transform. Otherwise, False.
"""
# create identity transformations
pos_identity = torch.zeros_like(pos)
rot_identity = torch.zeros_like(rot)
rot_identity[..., 0] = 1
# compare input to identity
return torch.allclose(pos, pos_identity) and torch.allclose(rot, rot_identity)
# @torch.jit.script
def combine_frame_transforms(
t01: torch.Tensor, q01: torch.Tensor, t12: torch.Tensor | None = None, q12: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor]:
r"""Combine transformations between two reference frames into a stationary frame.
It performs the following transformation operation: :math:`T_{02} = T_{01} \times T_{12}`,
where :math:`T_{AB}` is the homogeneous transformation matrix from frame A to B.
Args:
t01: Position of frame 1 w.r.t. frame 0. Shape is (N, 3).
q01: Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
t12: Position of frame 2 w.r.t. frame 1. Shape is (N, 3).
Defaults to None, in which case the position is assumed to be zero.
q12: Quaternion orientation of frame 2 w.r.t. frame 1 in (w, x, y, z). Shape is (N, 4).
Defaults to None, in which case the orientation is assumed to be identity.
Returns:
A tuple containing the position and orientation of frame 2 w.r.t. frame 0.
Shape of the tensors are (N, 3) and (N, 4) respectively.
"""
# compute orientation
if q12 is not None:
q02 = quat_mul(q01, q12)
else:
q02 = q01
# compute translation
if t12 is not None:
t02 = t01 + quat_apply(q01, t12)
else:
t02 = t01
return t02, q02
# @torch.jit.script
def subtract_frame_transforms(
t01: torch.Tensor, q01: torch.Tensor, t02: torch.Tensor | None = None, q02: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor]:
r"""Subtract transformations between two reference frames into a stationary frame.
It performs the following transformation operation: :math:`T_{12} = T_{01}^{-1} \times T_{02}`,
where :math:`T_{AB}` is the homogeneous transformation matrix from frame A to B.
Args:
t01: Position of frame 1 w.r.t. frame 0. Shape is (N, 3).
q01: Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
t02: Position of frame 2 w.r.t. frame 0. Shape is (N, 3).
Defaults to None, in which case the position is assumed to be zero.
q02: Quaternion orientation of frame 2 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
Defaults to None, in which case the orientation is assumed to be identity.
Returns:
A tuple containing the position and orientation of frame 2 w.r.t. frame 1.
Shape of the tensors are (N, 3) and (N, 4) respectively.
"""
# compute orientation
q10 = quat_inv(q01)
if q02 is not None:
q12 = quat_mul(q10, q02)
else:
q12 = q10
# compute translation
if t02 is not None:
t12 = quat_apply(q10, t02 - t01)
else:
t12 = quat_apply(q10, -t01)
return t12, q12
# @torch.jit.script
def compute_pose_error(
t01: torch.Tensor,
q01: torch.Tensor,
t02: torch.Tensor,
q02: torch.Tensor,
rot_error_type: Literal["quat", "axis_angle"] = "axis_angle",
) -> tuple[torch.Tensor, torch.Tensor]:
"""Compute the position and orientation error between source and target frames.
Args:
t01: Position of source frame. Shape is (N, 3).
q01: Quaternion orientation of source frame in (w, x, y, z). Shape is (N, 4).
t02: Position of target frame. Shape is (N, 3).
q02: Quaternion orientation of target frame in (w, x, y, z). Shape is (N, 4).
rot_error_type: The rotation error type to return: "quat", "axis_angle".
Defaults to "axis_angle".
Returns:
A tuple containing position and orientation error. Shape of position error is (N, 3).
Shape of orientation error depends on the value of :attr:`rot_error_type`:
- If :attr:`rot_error_type` is "quat", the orientation error is returned
as a quaternion. Shape is (N, 4).
- If :attr:`rot_error_type` is "axis_angle", the orientation error is
returned as an axis-angle vector. Shape is (N, 3).
Raises:
ValueError: Invalid rotation error type.
"""
# Compute quaternion error (i.e., difference quaternion)
# Reference: https://personal.utdallas.edu/~sxb027100/dock/quaternion.html
# q_current_norm = q_current * q_current_conj
source_quat_norm = quat_mul(q01, quat_conjugate(q01))[:, 0]
# q_current_inv = q_current_conj / q_current_norm
source_quat_inv = quat_conjugate(q01) / source_quat_norm.unsqueeze(-1)
# q_error = q_target * q_current_inv
quat_error = quat_mul(q02, source_quat_inv)
# Compute position error
pos_error = t02 - t01
# return error based on specified type
if rot_error_type == "quat":
return pos_error, quat_error
elif rot_error_type == "axis_angle":
# Convert to axis-angle error
axis_angle_error = axis_angle_from_quat(quat_error)
return pos_error, axis_angle_error
else:
raise ValueError(f"Unsupported orientation error type: {rot_error_type}. Valid: 'quat', 'axis_angle'.")
@torch.jit.script
def apply_delta_pose(
source_pos: torch.Tensor, source_rot: torch.Tensor, delta_pose: torch.Tensor, eps: float = 1.0e-6
) -> tuple[torch.Tensor, torch.Tensor]:
"""Applies delta pose transformation on source pose.
The first three elements of `delta_pose` are interpreted as cartesian position displacement.
The remaining three elements of `delta_pose` are interpreted as orientation displacement
in the angle-axis format.
Args:
source_pos: Position of source frame. Shape is (N, 3).
source_rot: Quaternion orientation of source frame in (w, x, y, z). Shape is (N, 4)..
delta_pose: Position and orientation displacements. Shape is (N, 6).
eps: The tolerance to consider orientation displacement as zero. Defaults to 1.0e-6.
Returns:
A tuple containing the displaced position and orientation frames.
Shape of the tensors are (N, 3) and (N, 4) respectively.
"""
# number of poses given
num_poses = source_pos.shape[0]
device = source_pos.device
# interpret delta_pose[:, 0:3] as target position displacements
target_pos = source_pos + delta_pose[:, 0:3]
# interpret delta_pose[:, 3:6] as target rotation displacements
rot_actions = delta_pose[:, 3:6]
angle = torch.linalg.vector_norm(rot_actions, dim=1)
axis = rot_actions / angle.unsqueeze(-1)
# change from axis-angle to quat convention
identity_quat = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat(num_poses, 1)
rot_delta_quat = torch.where(
angle.unsqueeze(-1).repeat(1, 4) > eps, quat_from_angle_axis(angle, axis), identity_quat
)
# TODO: Check if this is the correct order for this multiplication.
target_rot = quat_mul(rot_delta_quat, source_rot)
return target_pos, target_rot
# @torch.jit.script
def transform_points(
points: torch.Tensor, pos: torch.Tensor | None = None, quat: torch.Tensor | None = None
) -> torch.Tensor:
r"""Transform input points in a given frame to a target frame.
This function transform points from a source frame to a target frame. The transformation is defined by the
position :math:`t` and orientation :math:`R` of the target frame in the source frame.
.. math::
p_{target} = R_{target} \times p_{source} + t_{target}
If the input `points` is a batch of points, the inputs `pos` and `quat` must be either a batch of
positions and quaternions or a single position and quaternion. If the inputs `pos` and `quat` are
a single position and quaternion, the same transformation is applied to all points in the batch.
If either the inputs :attr:`pos` and :attr:`quat` are None, the corresponding transformation is not applied.
Args:
points: Points to transform. Shape is (N, P, 3) or (P, 3).
pos: Position of the target frame. Shape is (N, 3) or (3,).
Defaults to None, in which case the position is assumed to be zero.
quat: Quaternion orientation of the target frame in (w, x, y, z). Shape is (N, 4) or (4,).
Defaults to None, in which case the orientation is assumed to be identity.
Returns:
Transformed points in the target frame. Shape is (N, P, 3) or (P, 3).
Raises:
ValueError: If the inputs `points` is not of shape (N, P, 3) or (P, 3).
ValueError: If the inputs `pos` is not of shape (N, 3) or (3,).
ValueError: If the inputs `quat` is not of shape (N, 4) or (4,).
"""
points_batch = points.clone()
# check if inputs are batched
is_batched = points_batch.dim() == 3
# -- check inputs
if points_batch.dim() == 2:
points_batch = points_batch[None] # (P, 3) -> (1, P, 3)
if points_batch.dim() != 3:
raise ValueError(f"Expected points to have dim = 2 or dim = 3: got shape {points.shape}")
if not (pos is None or pos.dim() == 1 or pos.dim() == 2):
raise ValueError(f"Expected pos to have dim = 1 or dim = 2: got shape {pos.shape}")
if not (quat is None or quat.dim() == 1 or quat.dim() == 2):
raise ValueError(f"Expected quat to have dim = 1 or dim = 2: got shape {quat.shape}")
# -- rotation
if quat is not None:
# convert to batched rotation matrix
rot_mat = matrix_from_quat(quat)
if rot_mat.dim() == 2:
rot_mat = rot_mat[None] # (3, 3) -> (1, 3, 3)
# convert points to matching batch size (N, P, 3) -> (N, 3, P)
# and apply rotation
points_batch = torch.matmul(rot_mat, points_batch.transpose_(1, 2))
# (N, 3, P) -> (N, P, 3)
points_batch = points_batch.transpose_(1, 2)
# -- translation
if pos is not None:
# convert to batched translation vector
if pos.dim() == 1:
pos = pos[None, None, :] # (3,) -> (1, 1, 3)
else:
pos = pos[:, None, :] # (N, 3) -> (N, 1, 3)
# apply translation
points_batch += pos
# -- return points in same shape as input
if not is_batched:
points_batch = points_batch.squeeze(0) # (1, P, 3) -> (P, 3)
return points_batch
"""
Projection operations.
"""
@torch.jit.script
def unproject_depth(depth: torch.Tensor, intrinsics: torch.Tensor) -> torch.Tensor:
r"""Unproject depth image into a pointcloud.
This function converts depth images into points given the calibration matrix of the camera.
.. math::
p_{3D} = K^{-1} \times [u, v, 1]^T \times d
where :math:`p_{3D}` is the 3D point, :math:`d` is the depth value, :math:`u` and :math:`v` are
the pixel coordinates and :math:`K` is the intrinsic matrix.
If `depth` is a batch of depth images and `intrinsics` is a single intrinsic matrix, the same
calibration matrix is applied to all depth images in the batch.
The function assumes that the width and height are both greater than 1. This makes the function
deal with many possible shapes of depth images and intrinsics matrices.
Args:
depth: The depth measurement. Shape is (H, W) or or (H, W, 1) or (N, H, W) or (N, H, W, 1).
intrinsics: A tensor providing camera's calibration matrix. Shape is (3, 3) or (N, 3, 3).
Returns:
The 3D coordinates of points. Shape is (P, 3) or (N, P, 3).
Raises:
ValueError: When depth is not of shape (H, W) or (H, W, 1) or (N, H, W) or (N, H, W, 1).
ValueError: When intrinsics is not of shape (3, 3) or (N, 3, 3).
"""
depth_batch = depth.clone()
intrinsics_batch = intrinsics.clone()
# check if inputs are batched
is_batched = depth_batch.dim() == 4 or (depth_batch.dim() == 3 and depth_batch.shape[-1] != 1)
# make sure inputs are batched
if depth_batch.dim() == 3 and depth_batch.shape[-1] == 1:
depth_batch = depth_batch.squeeze(dim=2) # (H, W, 1) -> (H, W)
if depth_batch.dim() == 2:
depth_batch = depth_batch[None] # (H, W) -> (1, H, W)
if depth_batch.dim() == 4 and depth_batch.shape[-1] == 1:
depth_batch = depth_batch.squeeze(dim=3) # (N, H, W, 1) -> (N, H, W)
if intrinsics_batch.dim() == 2:
intrinsics_batch = intrinsics_batch[None] # (3, 3) -> (1, 3, 3)
# check shape of inputs
if depth_batch.dim() != 3:
raise ValueError(f"Expected depth images to have dim = 2 or 3 or 4: got shape {depth.shape}")
if intrinsics_batch.dim() != 3:
raise ValueError(f"Expected intrinsics to have shape (3, 3) or (N, 3, 3): got shape {intrinsics.shape}")
# get image height and width
im_height, im_width = depth_batch.shape[1:]
# create image points in homogeneous coordinates (3, H x W)
indices_u = torch.arange(im_width, device=depth.device, dtype=depth.dtype)
indices_v = torch.arange(im_height, device=depth.device, dtype=depth.dtype)
img_indices = torch.stack(torch.meshgrid([indices_u, indices_v], indexing="ij"), dim=0).reshape(2, -1)
pixels = torch.nn.functional.pad(img_indices, (0, 0, 0, 1), mode="constant", value=1.0)
pixels = pixels.unsqueeze(0) # (3, H x W) -> (1, 3, H x W)
# unproject points into 3D space
points = torch.matmul(torch.inverse(intrinsics_batch), pixels) # (N, 3, H x W)
points = points / points[:, -1, :].unsqueeze(1) # normalize by last coordinate
# flatten depth image (N, H, W) -> (N, H x W)
depth_batch = depth_batch.transpose_(1, 2).reshape(depth_batch.shape[0], -1).unsqueeze(2)
depth_batch = depth_batch.expand(-1, -1, 3)
# scale points by depth
points_xyz = points.transpose_(1, 2) * depth_batch # (N, H x W, 3)
# return points in same shape as input
if not is_batched:
points_xyz = points_xyz.squeeze(0)
return points_xyz
@torch.jit.script
def project_points(points: torch.Tensor, intrinsics: torch.Tensor) -> torch.Tensor:
r"""Projects 3D points into 2D image plane.
This project 3D points into a 2D image plane. The transformation is defined by the intrinsic
matrix of the camera.
.. math::
\begin{align}
p &= K \times p_{3D} = \\
p_{2D} &= \begin{pmatrix} u \\ v \\ d \end{pmatrix}
= \begin{pmatrix} p[0] / p[2] \\ p[1] / p[2] \\ Z \end{pmatrix}
\end{align}
where :math:`p_{2D} = (u, v, d)` is the projected 3D point, :math:`p_{3D} = (X, Y, Z)` is the
3D point and :math:`K \in \mathbb{R}^{3 \times 3}` is the intrinsic matrix.
If `points` is a batch of 3D points and `intrinsics` is a single intrinsic matrix, the same
calibration matrix is applied to all points in the batch.
Args:
points: The 3D coordinates of points. Shape is (P, 3) or (N, P, 3).
intrinsics: Camera's calibration matrix. Shape is (3, 3) or (N, 3, 3).
Returns:
Projected 3D coordinates of points. Shape is (P, 3) or (N, P, 3).
"""
points_batch = points.clone()
intrinsics_batch = intrinsics.clone()
# check if inputs are batched
is_batched = points_batch.dim() == 2
# make sure inputs are batched
if points_batch.dim() == 2:
points_batch = points_batch[None] # (P, 3) -> (1, P, 3)
if intrinsics_batch.dim() == 2:
intrinsics_batch = intrinsics_batch[None] # (3, 3) -> (1, 3, 3)
# check shape of inputs
if points_batch.dim() != 3:
raise ValueError(f"Expected points to have dim = 3: got shape {points.shape}.")
if intrinsics_batch.dim() != 3:
raise ValueError(f"Expected intrinsics to have shape (3, 3) or (N, 3, 3): got shape {intrinsics.shape}.")
# project points into 2D image plane
points_2d = torch.matmul(intrinsics_batch, points_batch.transpose(1, 2))
points_2d = points_2d / points_2d[:, -1, :].unsqueeze(1) # normalize by last coordinate
points_2d = points_2d.transpose_(1, 2) # (N, 3, P) -> (N, P, 3)
# replace last coordinate with depth
points_2d[:, :, -1] = points_batch[:, :, -1]
# return points in same shape as input
if not is_batched:
points_2d = points_2d.squeeze(0) # (1, 3, P) -> (3, P)
return points_2d
"""
Sampling
"""
@torch.jit.script
def default_orientation(num: int, device: str) -> torch.Tensor:
"""Returns identity rotation transform.
Args:
num: The number of rotations to sample.
device: Device to create tensor on.
Returns:
Identity quaternion in (w, x, y, z). Shape is (num, 4).
"""
quat = torch.zeros((num, 4), dtype=torch.float, device=device)
quat[..., 0] = 1.0
return quat
@torch.jit.script
def random_orientation(num: int, device: str) -> torch.Tensor:
"""Returns sampled rotation in 3D as quaternion.
Args:
num: The number of rotations to sample.
device: Device to create tensor on.
Returns:
Sampled quaternion in (w, x, y, z). Shape is (num, 4).
Reference:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.random.html
"""
# sample random orientation from normal distribution
quat = torch.randn((num, 4), dtype=torch.float, device=device)
# normalize the quaternion
return torch.nn.functional.normalize(quat, p=2.0, dim=-1, eps=1e-12)
@torch.jit.script
def random_yaw_orientation(num: int, device: str) -> torch.Tensor:
"""Returns sampled rotation around z-axis.
Args:
num: The number of rotations to sample.
device: Device to create tensor on.
Returns:
Sampled quaternion in (w, x, y, z). Shape is (num, 4).
"""
roll = torch.zeros(num, dtype=torch.float, device=device)
pitch = torch.zeros(num, dtype=torch.float, device=device)
yaw = 2 * torch.pi * torch.rand(num, dtype=torch.float, device=device)
return quat_from_euler_xyz(roll, pitch, yaw)
def sample_triangle(lower: float, upper: float, size: int | tuple[int, ...], device: str) -> torch.Tensor:
"""Randomly samples tensor from a triangular distribution.
Args:
lower: The lower range of the sampled tensor.
upper: The upper range of the sampled tensor.
size: The shape of the tensor.
device: Device to create tensor on.
Returns:
Sampled tensor. Shape is based on :attr:`size`.
"""
# convert to tuple
if isinstance(size, int):
size = (size,)
# create random tensor in the range [-1, 1]
r = 2 * torch.rand(*size, device=device) - 1
# convert to triangular distribution
r = torch.where(r < 0.0, -torch.sqrt(-r), torch.sqrt(r))
# rescale back to [0, 1]
r = (r + 1.0) / 2.0
# rescale to range [lower, upper]
return (upper - lower) * r + lower
def sample_uniform(
lower: torch.Tensor | float, upper: torch.Tensor | float, size: int | tuple[int, ...], device: str
) -> torch.Tensor:
"""Sample uniformly within a range.
Args:
lower: Lower bound of uniform range.
upper: Upper bound of uniform range.
size: The shape of the tensor.
device: Device to create tensor on.
Returns:
Sampled tensor. Shape is based on :attr:`size`.
"""
# convert to tuple
if isinstance(size, int):
size = (size,)
# return tensor
return torch.rand(*size, device=device) * (upper - lower) + lower
def sample_log_uniform(
lower: torch.Tensor | float, upper: torch.Tensor | float, size: int | tuple[int, ...], device: str
) -> torch.Tensor:
r"""Sample using log-uniform distribution within a range.
The log-uniform distribution is defined as a uniform distribution in the log-space. It
is useful for sampling values that span several orders of magnitude. The sampled values
are uniformly distributed in the log-space and then exponentiated to get the final values.
.. math::
x = \exp(\text{uniform}(\log(\text{lower}), \log(\text{upper})))
Args:
lower: Lower bound of uniform range.
upper: Upper bound of uniform range.
size: The shape of the tensor.
device: Device to create tensor on.
Returns:
Sampled tensor. Shape is based on :attr:`size`.
"""
# cast to tensor if not already
if not isinstance(lower, torch.Tensor):
lower = torch.tensor(lower, dtype=torch.float, device=device)
if not isinstance(upper, torch.Tensor):
upper = torch.tensor(upper, dtype=torch.float, device=device)
# sample in log-space and exponentiate
return torch.exp(sample_uniform(torch.log(lower), torch.log(upper), size, device))
def sample_cylinder(
radius: float, h_range: tuple[float, float], size: int | tuple[int, ...], device: str
) -> torch.Tensor:
"""Sample 3D points uniformly on a cylinder's surface.
The cylinder is centered at the origin and aligned with the z-axis. The height of the cylinder is
sampled uniformly from the range :obj:`h_range`, while the radius is fixed to :obj:`radius`.
The sampled points are returned as a tensor of shape :obj:`(*size, 3)`, i.e. the last dimension
contains the x, y, and z coordinates of the sampled points.
Args:
radius: The radius of the cylinder.
h_range: The minimum and maximum height of the cylinder.
size: The shape of the tensor.
device: Device to create tensor on.
Returns:
Sampled tensor. Shape is :obj:`(*size, 3)`.
"""
# sample angles
angles = (torch.rand(size, device=device) * 2 - 1) * torch.pi
h_min, h_max = h_range
# add shape
if isinstance(size, int):
size = (size, 3)
else:
size += (3,)
# allocate a tensor
xyz = torch.zeros(size, device=device)
xyz[..., 0] = radius * torch.cos(angles)
xyz[..., 1] = radius * torch.sin(angles)
xyz[..., 2].uniform_(h_min, h_max)
# return positions
return xyz
| 46,817 | Python | 35.66249 | 118 | 0.608881 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/dict.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for utilities for working with dictionaries."""
import collections.abc
import hashlib
import json
from collections.abc import Iterable, Mapping
from typing import Any
from .array import TENSOR_TYPE_CONVERSIONS, TENSOR_TYPES
from .string import callable_to_string, string_to_callable
"""
Dictionary <-> Class operations.
"""
def class_to_dict(obj: object) -> dict[str, Any]:
"""Convert an object into dictionary recursively.
Note:
Ignores all names starting with "__" (i.e. built-in methods).
Args:
obj: An instance of a class to convert.
Raises:
ValueError: When input argument is not an object.
Returns:
Converted dictionary mapping.
"""
# check that input data is class instance
if not hasattr(obj, "__class__"):
raise ValueError(f"Expected a class instance. Received: {type(obj)}.")
# convert object to dictionary
if isinstance(obj, dict):
obj_dict = obj
else:
obj_dict = obj.__dict__
# convert to dictionary
data = dict()
for key, value in obj_dict.items():
# disregard builtin attributes
if key.startswith("__"):
continue
# check if attribute is callable -- function
if callable(value):
data[key] = callable_to_string(value)
# check if attribute is a dictionary
elif hasattr(value, "__dict__") or isinstance(value, dict):
data[key] = class_to_dict(value)
else:
data[key] = value
return data
def update_class_from_dict(obj, data: dict[str, Any], _ns: str = "") -> None:
"""Reads a dictionary and sets object variables recursively.
This function performs in-place update of the class member attributes.
Args:
obj: An instance of a class to update.
data: Input dictionary to update from.
_ns: Namespace of the current object. This is useful for nested configuration
classes or dictionaries. Defaults to "".
Raises:
TypeError: When input is not a dictionary.
ValueError: When dictionary has a value that does not match default config type.
KeyError: When dictionary has a key that does not exist in the default config type.
"""
for key, value in data.items():
# key_ns is the full namespace of the key
key_ns = _ns + "/" + key
# check if key is present in the object
if hasattr(obj, key):
obj_mem = getattr(obj, key)
if isinstance(obj_mem, Mapping):
# Note: We don't handle two-level nested dictionaries. Just use configclass if this is needed.
# iterate over the dictionary to look for callable values
for k, v in obj_mem.items():
if callable(v):
value[k] = string_to_callable(value[k])
setattr(obj, key, value)
elif isinstance(value, Mapping):
# recursively call if it is a dictionary
update_class_from_dict(obj_mem, value, _ns=key_ns)
elif isinstance(value, Iterable) and not isinstance(value, str):
# check length of value to be safe
if len(obj_mem) != len(value) and obj_mem is not None:
raise ValueError(
f"[Config]: Incorrect length under namespace: {key_ns}."
f" Expected: {len(obj_mem)}, Received: {len(value)}."
)
# set value
setattr(obj, key, value)
elif callable(obj_mem):
# update function name
value = string_to_callable(value)
setattr(obj, key, value)
elif isinstance(value, type(obj_mem)):
# check that they are type-safe
setattr(obj, key, value)
else:
raise ValueError(
f"[Config]: Incorrect type under namespace: {key_ns}."
f" Expected: {type(obj_mem)}, Received: {type(value)}."
)
else:
raise KeyError(f"[Config]: Key not found under namespace: {key_ns}.")
"""
Dictionary <-> Hashable operations.
"""
def dict_to_md5_hash(data: object) -> str:
"""Convert a dictionary into a hashable key using MD5 hash.
Args:
data: Input dictionary or configuration object to convert.
Returns:
A string object of double length containing only hexadecimal digits.
"""
# convert to dictionary
if isinstance(data, dict):
encoded_buffer = json.dumps(data, sort_keys=True).encode()
else:
encoded_buffer = json.dumps(class_to_dict(data), sort_keys=True).encode()
# compute hash using MD5
data_hash = hashlib.md5()
data_hash.update(encoded_buffer)
# return the hash key
return data_hash.hexdigest()
"""
Dictionary operations.
"""
def convert_dict_to_backend(
data: dict, backend: str = "numpy", array_types: Iterable[str] = ("numpy", "torch", "warp")
) -> dict:
"""Convert all arrays or tensors in a dictionary to a given backend.
This function iterates over the dictionary, converts all arrays or tensors with the given types to
the desired backend, and stores them in a new dictionary. It also works with nested dictionaries.
Currently supported backends are "numpy", "torch", and "warp".
Note:
This function only converts arrays or tensors. Other types of data are left unchanged. Mutable types
(e.g. lists) are referenced by the new dictionary, so they are not copied.
Args:
data: An input dict containing array or tensor data as values.
backend: The backend ("numpy", "torch", "warp") to which arrays in this dict should be converted.
Defaults to "numpy".
array_types: A list containing the types of arrays that should be converted to
the desired backend. Defaults to ("numpy", "torch", "warp").
Raises:
ValueError: If the specified ``backend`` or ``array_types`` are unknown, i.e. not in the list of supported
backends ("numpy", "torch", "warp").
Returns:
The updated dict with the data converted to the desired backend.
"""
# THINK: Should we also support converting to a specific device, e.g. "cuda:0"?
# Check the backend is valid.
if backend not in TENSOR_TYPE_CONVERSIONS:
raise ValueError(f"Unknown backend '{backend}'. Supported backends are 'numpy', 'torch', and 'warp'.")
# Define the conversion functions for each backend.
tensor_type_conversions = TENSOR_TYPE_CONVERSIONS[backend]
# Parse the array types and convert them to the corresponding types: "numpy" -> np.ndarray, etc.
parsed_types = list()
for t in array_types:
# Check type is valid.
if t not in TENSOR_TYPES:
raise ValueError(f"Unknown array type: '{t}'. Supported array types are 'numpy', 'torch', and 'warp'.")
# Exclude types that match the backend, since we do not need to convert these.
if t == backend:
continue
# Convert the string types to the corresponding types.
parsed_types.append(TENSOR_TYPES[t])
# Convert the data to the desired backend.
output_dict = dict()
for key, value in data.items():
# Obtain the data type of the current value.
data_type = type(value)
# -- arrays
if data_type in parsed_types:
# check if we have a known conversion.
if data_type not in tensor_type_conversions:
raise ValueError(f"No registered conversion for data type: {data_type} to {backend}!")
# convert the data to the desired backend.
output_dict[key] = tensor_type_conversions[data_type](value)
# -- nested dictionaries
elif isinstance(data[key], dict):
output_dict[key] = convert_dict_to_backend(value)
# -- everything else
else:
output_dict[key] = value
return output_dict
def update_dict(orig_dict: dict, new_dict: collections.abc.Mapping) -> dict:
"""Updates existing dictionary with values from a new dictionary.
This function mimics the dict.update() function. However, it works for
nested dictionaries as well.
Reference:
https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
Args:
orig_dict: The original dictionary to insert items to.
new_dict: The new dictionary to insert items from.
Returns:
The updated dictionary.
"""
for keyname, value in new_dict.items():
if isinstance(value, collections.abc.Mapping):
orig_dict[keyname] = update_dict(orig_dict.get(keyname, {}), value)
else:
orig_dict[keyname] = value
return orig_dict
def print_dict(val, nesting: int = -4, start: bool = True):
"""Outputs a nested dictionary."""
if isinstance(val, dict):
if not start:
print("")
nesting += 4
for k in val:
print(nesting * " ", end="")
print(k, end=": ")
print_dict(val[k], nesting, start=False)
else:
# deal with functions in print statements
if callable(val):
print(callable_to_string(val))
else:
print(val)
| 9,522 | Python | 35.76834 | 115 | 0.614262 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/configclass.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module that provides a wrapper around the Python 3.7 onwards ``dataclasses`` module."""
import inspect
from collections.abc import Callable
from copy import deepcopy
from dataclasses import MISSING, Field, dataclass, field, replace
from typing import Any, ClassVar
from .dict import class_to_dict, update_class_from_dict
_CONFIGCLASS_METHODS = ["to_dict", "from_dict", "replace", "copy"]
"""List of class methods added at runtime to dataclass."""
"""
Wrapper around dataclass.
"""
def __dataclass_transform__():
"""Add annotations decorator for PyLance."""
return lambda a: a
@__dataclass_transform__()
def configclass(cls, **kwargs):
"""Wrapper around `dataclass` functionality to add extra checks and utilities.
As of Python 3.7, the standard dataclasses have two main issues which makes them non-generic for
configuration use-cases. These include:
1. Requiring a type annotation for all its members.
2. Requiring explicit usage of :meth:`field(default_factory=...)` to reinitialize mutable variables.
This function provides a decorator that wraps around Python's `dataclass`_ utility to deal with
the above two issues. It also provides additional helper functions for dictionary <-> class
conversion and easily copying class instances.
Usage:
.. code-block:: python
from dataclasses import MISSING
from omni.isaac.orbit.utils.configclass import configclass
@configclass
class ViewerCfg:
eye: list = [7.5, 7.5, 7.5] # field missing on purpose
lookat: list = field(default_factory=[0.0, 0.0, 0.0])
@configclass
class EnvCfg:
num_envs: int = MISSING
episode_length: int = 2000
viewer: ViewerCfg = ViewerCfg()
# create configuration instance
env_cfg = EnvCfg(num_envs=24)
# print information as a dictionary
print(env_cfg.to_dict())
# create a copy of the configuration
env_cfg_copy = env_cfg.copy()
# replace arbitrary fields using keyword arguments
env_cfg_copy = env_cfg_copy.replace(num_envs=32)
Args:
cls: The class to wrap around.
**kwargs: Additional arguments to pass to :func:`dataclass`.
Returns:
The wrapped class.
.. _dataclass: https://docs.python.org/3/library/dataclasses.html
"""
# add type annotations
_add_annotation_types(cls)
# add field factory
_process_mutable_types(cls)
# copy mutable members
# note: we check if user defined __post_init__ function exists and augment it with our own
if hasattr(cls, "__post_init__"):
setattr(cls, "__post_init__", _combined_function(cls.__post_init__, _custom_post_init))
else:
setattr(cls, "__post_init__", _custom_post_init)
# add helper functions for dictionary conversion
setattr(cls, "to_dict", _class_to_dict)
setattr(cls, "from_dict", _update_class_from_dict)
setattr(cls, "replace", _replace_class_with_kwargs)
setattr(cls, "copy", _copy_class)
# wrap around dataclass
cls = dataclass(cls, **kwargs)
# return wrapped class
return cls
"""
Dictionary <-> Class operations.
These are redefined here to add new docstrings.
"""
def _class_to_dict(obj: object) -> dict[str, Any]:
"""Convert an object into dictionary recursively.
Returns:
Converted dictionary mapping.
"""
return class_to_dict(obj)
def _update_class_from_dict(obj, data: dict[str, Any]) -> None:
"""Reads a dictionary and sets object variables recursively.
This function performs in-place update of the class member attributes.
Args:
data: Input (nested) dictionary to update from.
Raises:
TypeError: When input is not a dictionary.
ValueError: When dictionary has a value that does not match default config type.
KeyError: When dictionary has a key that does not exist in the default config type.
"""
return update_class_from_dict(obj, data, _ns="")
def _replace_class_with_kwargs(obj: object, **kwargs) -> object:
"""Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
.. code-block:: python
@configclass(frozen=True)
class C:
x: int
y: int
c = C(1, 2)
c1 = c.replace(x=3)
assert c1.x == 3 and c1.y == 2
Args:
obj: The object to replace.
**kwargs: The fields to replace and their new values.
Returns:
The new object.
"""
return replace(obj, **kwargs)
def _copy_class(obj: object) -> object:
"""Return a new object with the same fields as the original."""
return replace(obj)
"""
Private helper functions.
"""
def _add_annotation_types(cls):
"""Add annotations to all elements in the dataclass.
By definition in Python, a field is defined as a class variable that has a type annotation.
In case type annotations are not provided, dataclass ignores those members when :func:`__dict__()` is called.
This function adds these annotations to the class variable to prevent any issues in case the user forgets to
specify the type annotation.
This makes the following a feasible operation:
@dataclass
class State:
pos = (0.0, 0.0, 0.0)
^^
If the function is NOT used, the following type-error is returned:
TypeError: 'pos' is a field but has no type annotation
"""
# get type hints
hints = {}
# iterate over class inheritance
# we add annotations from base classes first
for base in reversed(cls.__mro__):
# check if base is object
if base is object:
continue
# get base class annotations
ann = base.__dict__.get("__annotations__", {})
# directly add all annotations from base class
hints.update(ann)
# iterate over base class members
# Note: Do not change this to dir(base) since it orders the members alphabetically.
# This is not desirable since the order of the members is important in some cases.
for key in base.__dict__:
# get class member
value = getattr(base, key)
# skip members
if _skippable_class_member(key, value, hints):
continue
# add type annotations for members that don't have explicit type annotations
# for these, we deduce the type from the default value
if not isinstance(value, type):
if key not in hints:
# check if var type is not MISSING
# we cannot deduce type from MISSING!
if value is MISSING:
raise TypeError(
f"Missing type annotation for '{key}' in class '{cls.__name__}'."
" Please add a type annotation or set a default value."
)
# add type annotation
hints[key] = type(value)
elif key != value.__name__:
# note: we don't want to add type annotations for nested configclass. Thus, we check if
# the name of the type matches the name of the variable.
# since Python 3.10, type hints are stored as strings
hints[key] = f"type[{value.__name__}]"
# Note: Do not change this line. `cls.__dict__.get("__annotations__", {})` is different from
# `cls.__annotations__` because of inheritance.
cls.__annotations__ = cls.__dict__.get("__annotations__", {})
cls.__annotations__ = hints
def _process_mutable_types(cls):
"""Initialize all mutable elements through :obj:`dataclasses.Field` to avoid unnecessary complaints.
By default, dataclass requires usage of :obj:`field(default_factory=...)` to reinitialize mutable objects every time a new
class instance is created. If a member has a mutable type and it is created without specifying the `field(default_factory=...)`,
then Python throws an error requiring the usage of `default_factory`.
Additionally, Python only explicitly checks for field specification when the type is a list, set or dict. This misses the
use-case where the type is class itself. Thus, the code silently carries a bug with it which can lead to undesirable effects.
This function deals with this issue
This makes the following a feasible operation:
@dataclass
class State:
pos: list = [0.0, 0.0, 0.0]
^^
If the function is NOT used, the following value-error is returned:
ValueError: mutable default <class 'list'> for field pos is not allowed: use default_factory
"""
# note: Need to set this up in the same order as annotations. Otherwise, it
# complains about missing positional arguments.
ann = cls.__dict__.get("__annotations__", {})
# iterate over all class members and store them in a dictionary
class_members = {}
for base in reversed(cls.__mro__):
# check if base is object
if base is object:
continue
# iterate over base class members
for key in base.__dict__:
# get class member
f = getattr(base, key)
# skip members
if _skippable_class_member(key, f):
continue
# store class member if it is not a type or if it is already present in annotations
if not isinstance(f, type) or key in ann:
class_members[key] = f
# iterate over base class data fields
# in previous call, things that became a dataclass field were removed from class members
# so we need to add them back here as a dataclass field directly
for key, f in base.__dict__.get("__dataclass_fields__", {}).items():
# store class member
if not isinstance(f, type):
class_members[key] = f
# check that all annotations are present in class members
# note: mainly for debugging purposes
if len(class_members) != len(ann):
raise ValueError(
f"In class '{cls.__name__}', number of annotations ({len(ann)}) does not match number of class members"
f" ({len(class_members)}). Please check that all class members have type annotations and/or a default"
" value. If you don't want to specify a default value, please use the literal `dataclasses.MISSING`."
)
# iterate over annotations and add field factory for mutable types
for key in ann:
# find matching field in class
value = class_members.get(key, MISSING)
# check if key belongs to ClassVar
# in that case, we cannot use default_factory!
origin = getattr(ann[key], "__origin__", None)
if origin is ClassVar:
continue
# check if f is MISSING
# note: commented out for now since it causes issue with inheritance
# of dataclasses when parent have some positional and some keyword arguments.
# Ref: https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses
# TODO: check if this is fixed in Python 3.10
# if f is MISSING:
# continue
if isinstance(value, Field):
setattr(cls, key, value)
elif not isinstance(value, type):
# create field factory for mutable types
value = field(default_factory=_return_f(value))
setattr(cls, key, value)
def _custom_post_init(obj):
"""Deepcopy all elements to avoid shared memory issues for mutable objects in dataclasses initialization.
This function is called explicitly instead of as a part of :func:`_process_mutable_types()` to prevent mapping
proxy type i.e. a read only proxy for mapping objects. The error is thrown when using hierarchical data-classes
for configuration.
"""
for key in dir(obj):
# skip dunder members
if key.startswith("__"):
continue
# get data member
value = getattr(obj, key)
# duplicate data members
if not callable(value):
setattr(obj, key, deepcopy(value))
def _combined_function(f1: Callable, f2: Callable) -> Callable:
"""Combine two functions into one.
Args:
f1: The first function.
f2: The second function.
Returns:
The combined function.
"""
def _combined(*args, **kwargs):
# call both functions
f1(*args, **kwargs)
f2(*args, **kwargs)
return _combined
"""
Helper functions
"""
def _skippable_class_member(key: str, value: Any, hints: dict | None = None) -> bool:
"""Check if the class member should be skipped in configclass processing.
The following members are skipped:
* Dunder members: ``__name__``, ``__module__``, ``__qualname__``, ``__annotations__``, ``__dict__``.
* Manually-added special class functions: From :obj:`_CONFIGCLASS_METHODS`.
* Members that are already present in the type annotations.
* Functions bounded to class object or class.
Args:
key: The class member name.
value: The class member value.
hints: The type hints for the class. Defaults to None, in which case, the
members existence in type hints are not checked.
Returns:
True if the class member should be skipped, False otherwise.
"""
# skip dunder members
if key.startswith("__"):
return True
# skip manually-added special class functions
if key in _CONFIGCLASS_METHODS:
return True
# check if key is already present
if hints is not None and key in hints:
return True
# skip functions bounded to class
if callable(value):
signature = inspect.signature(value)
if "self" in signature.parameters or "cls" in signature.parameters:
return True
# Otherwise, don't skip
return False
def _return_f(f: Any) -> Callable[[], Any]:
"""Returns default factory function for creating mutable/immutable variables.
This function should be used to create default factory functions for variables.
Example:
.. code-block:: python
value = field(default_factory=_return_f(value))
setattr(cls, key, value)
"""
def _wrap():
if isinstance(f, Field):
if f.default_factory is MISSING:
return deepcopy(f.default)
else:
return f.default_factory
else:
return deepcopy(f)
return _wrap
| 14,831 | Python | 34.230404 | 132 | 0.630841 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/assets.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module that defines the host-server where assets and resources are stored.
By default, we use the Isaac Sim Nucleus Server for hosting assets and resources. This makes
distribution of the assets easier and makes the repository smaller in size code-wise.
For more information, please check information on `Omniverse Nucleus`_.
.. _Omniverse Nucleus: https://docs.omniverse.nvidia.com/nucleus/latest/overview/overview.html
"""
import io
import os
import tempfile
from typing import Literal
import carb
import omni.client
import omni.isaac.core.utils.nucleus as nucleus_utils
# get assets root path
# note: we check only once at the start of the module to prevent multiple checks on the Nucleus Server
NUCLEUS_ASSET_ROOT_DIR = nucleus_utils.get_assets_root_path()
"""Path to the root directory on the Nucleus Server.
This is resolved using Isaac Sim's Nucleus API. If the Nucleus Server is not running, then this
will be set to None. The path is resolved using the following steps:
1. Based on simulation parameter: ``/persistent/isaac/asset_root/default``.
2. Iterating over all the connected Nucleus Servers and checking for the first server that has the
the connected status.
3. Based on simulation parameter: ``/persistent/isaac/asset_root/cloud``.
"""
# check nucleus connection
if NUCLEUS_ASSET_ROOT_DIR is None:
msg = (
"Unable to perform Nucleus login on Omniverse. Assets root path is not set.\n"
"\tPlease check: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html#omniverse-nucleus"
)
carb.log_error(msg)
raise RuntimeError(msg)
NVIDIA_NUCLEUS_DIR = f"{NUCLEUS_ASSET_ROOT_DIR}/NVIDIA"
"""Path to the root directory on the NVIDIA Nucleus Server."""
ISAAC_NUCLEUS_DIR = f"{NUCLEUS_ASSET_ROOT_DIR}/Isaac"
"""Path to the ``Isaac`` directory on the NVIDIA Nucleus Server."""
ISAAC_ORBIT_NUCLEUS_DIR = f"{ISAAC_NUCLEUS_DIR}/Samples/Orbit"
"""Path to the ``Isaac/Samples/Orbit`` directory on the NVIDIA Nucleus Server."""
def check_file_path(path: str) -> Literal[0, 1, 2]:
"""Checks if a file exists on the Nucleus Server or locally.
Args:
path: The path to the file.
Returns:
The status of the file. Possible values are listed below.
* :obj:`0` if the file does not exist
* :obj:`1` if the file exists locally
* :obj:`2` if the file exists on the Nucleus Server
"""
if os.path.isfile(path):
return 1
elif omni.client.stat(path)[0] == omni.client.Result.OK:
return 2
else:
return 0
def retrieve_file_path(path: str, download_dir: str | None = None, force_download: bool = True) -> str:
"""Retrieves the path to a file on the Nucleus Server or locally.
If the file exists locally, then the absolute path to the file is returned.
If the file exists on the Nucleus Server, then the file is downloaded to the local machine
and the absolute path to the file is returned.
Args:
path: The path to the file.
download_dir: The directory where the file should be downloaded. Defaults to None, in which
case the file is downloaded to the system's temporary directory.
force_download: Whether to force download the file from the Nucleus Server. This will overwrite
the local file if it exists. Defaults to True.
Returns:
The path to the file on the local machine.
Raises:
FileNotFoundError: When the file not found locally or on Nucleus Server.
RuntimeError: When the file cannot be copied from the Nucleus Server to the local machine. This
can happen when the file already exists locally and :attr:`force_download` is set to False.
"""
# check file status
file_status = check_file_path(path)
if file_status == 1:
return os.path.abspath(path)
elif file_status == 2:
# resolve download directory
if download_dir is None:
download_dir = tempfile.gettempdir()
else:
download_dir = os.path.abspath(download_dir)
# create download directory if it does not exist
if not os.path.exists(download_dir):
os.makedirs(download_dir)
# download file in temp directory using os
file_name = os.path.basename(omni.client.break_url(path).path)
target_path = os.path.join(download_dir, file_name)
# check if file already exists locally
if not os.path.isfile(target_path) or force_download:
# copy file to local machine
result = omni.client.copy(path, target_path)
if result != omni.client.Result.OK and force_download:
raise RuntimeError(f"Unable to copy file: '{path}'. Is the Nucleus Server running?")
return os.path.abspath(target_path)
else:
raise FileNotFoundError(f"Unable to find the file: {path}")
def read_file(path: str) -> io.BytesIO:
"""Reads a file from the Nucleus Server or locally.
Args:
path: The path to the file.
Raises:
FileNotFoundError: When the file not found locally or on Nucleus Server.
Returns:
The content of the file.
"""
# check file status
file_status = check_file_path(path)
if file_status == 1:
with open(path, "rb") as f:
return io.BytesIO(f.read())
elif file_status == 2:
file_content = omni.client.read_file(path)[2]
return io.BytesIO(memoryview(file_content).tobytes())
else:
raise FileNotFoundError(f"Unable to find the file: {path}")
| 5,687 | Python | 36.92 | 117 | 0.684368 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/io/yaml.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Utilities for file I/O with yaml."""
import os
import yaml
from omni.isaac.orbit.utils import class_to_dict
def load_yaml(filename: str) -> dict:
"""Loads an input PKL file safely.
Args:
filename: The path to pickled file.
Raises:
FileNotFoundError: When the specified file does not exist.
Returns:
The data read from the input file.
"""
if not os.path.exists(filename):
raise FileNotFoundError(f"File not found: {filename}")
with open(filename) as f:
data = yaml.full_load(f)
return data
def dump_yaml(filename: str, data: dict | object, sort_keys: bool = False):
"""Saves data into a YAML file safely.
Note:
The function creates any missing directory along the file's path.
Args:
filename: The path to save the file at.
data: The data to save either a dictionary or class object.
sort_keys: Whether to sort the keys in the output file. Defaults to False.
"""
# check ending
if not filename.endswith("yaml"):
filename += ".yaml"
# create directory
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename), exist_ok=True)
# convert data into dictionary
if not isinstance(data, dict):
data = class_to_dict(data)
# save data
with open(filename, "w") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=sort_keys)
| 1,572 | Python | 27.089285 | 82 | 0.653308 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/io/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Submodules for files IO operations.
"""
from .pkl import dump_pickle, load_pickle
from .yaml import dump_yaml, load_yaml
| 249 | Python | 19.833332 | 56 | 0.738956 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/io/pkl.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Utilities for file I/O with pickle."""
import os
import pickle
from typing import Any
def load_pickle(filename: str) -> Any:
"""Loads an input PKL file safely.
Args:
filename: The path to pickled file.
Raises:
FileNotFoundError: When the specified file does not exist.
Returns:
The data read from the input file.
"""
if not os.path.exists(filename):
raise FileNotFoundError(f"File not found: {filename}")
with open(filename, "rb") as f:
data = pickle.load(f)
return data
def dump_pickle(filename: str, data: Any):
"""Saves data into a pickle file safely.
Note:
The function creates any missing directory along the file's path.
Args:
filename: The path to save the file at.
data: The data to save.
"""
# check ending
if not filename.endswith("pkl"):
filename += ".pkl"
# create directory
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename), exist_ok=True)
# save data
with open(filename, "wb") as f:
pickle.dump(data, f)
| 1,252 | Python | 23.568627 | 73 | 0.638978 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/warp/kernels.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Custom kernels for warp."""
import warp as wp
@wp.kernel
def raycast_mesh_kernel(
mesh: wp.uint64,
ray_starts: wp.array(dtype=wp.vec3),
ray_directions: wp.array(dtype=wp.vec3),
ray_hits: wp.array(dtype=wp.vec3),
ray_distance: wp.array(dtype=wp.float32),
ray_normal: wp.array(dtype=wp.vec3),
ray_face_id: wp.array(dtype=wp.int32),
max_dist: float = 1e6,
return_distance: int = False,
return_normal: int = False,
return_face_id: int = False,
):
"""Performs ray-casting against a mesh.
This function performs ray-casting against the given mesh using the provided ray start positions
and directions. The resulting ray hit positions are stored in the :obj:`ray_hits` array.
Note that the `ray_starts`, `ray_directions`, and `ray_hits` arrays should have compatible shapes
and data types to ensure proper execution. Additionally, they all must be in the same frame.
The function utilizes the `mesh_query_ray` method from the `wp` module to perform the actual ray-casting
operation. The maximum ray-cast distance is set to `1e6` units.
Args:
mesh: The input mesh. The ray-casting is performed against this mesh on the device specified by the
`mesh`'s `device` attribute.
ray_starts: The input ray start positions. Shape is (N, 3).
ray_directions: The input ray directions. Shape is (N, 3).
ray_hits: The output ray hit positions. Shape is (N, 3).
ray_distance: The output ray hit distances. Shape is (N,), if `return_distance` is True. Otherwise,
this array is not used.
ray_normal: The output ray hit normals. Shape is (N, 3), if `return_normal` is True. Otherwise,
this array is not used.
ray_face_id: The output ray hit face ids. Shape is (N,), if `return_face_id` is True. Otherwise,
this array is not used.
max_dist: The maximum ray-cast distance. Defaults to 1e6.
return_distance: Whether to return the ray hit distances. Defaults to False.
return_normal: Whether to return the ray hit normals. Defaults to False`.
return_face_id: Whether to return the ray hit face ids. Defaults to False.
"""
# get the thread id
tid = wp.tid()
t = float(0.0) # hit distance along ray
u = float(0.0) # hit face barycentric u
v = float(0.0) # hit face barycentric v
sign = float(0.0) # hit face sign
n = wp.vec3() # hit face normal
f = int(0) # hit face index
# ray cast against the mesh and store the hit position
hit_success = wp.mesh_query_ray(mesh, ray_starts[tid], ray_directions[tid], max_dist, t, u, v, sign, n, f)
# if the ray hit, store the hit data
if hit_success:
ray_hits[tid] = ray_starts[tid] + t * ray_directions[tid]
if return_distance == 1:
ray_distance[tid] = t
if return_normal == 1:
ray_normal[tid] = n
if return_face_id == 1:
ray_face_id[tid] = f
| 3,123 | Python | 41.216216 | 110 | 0.651297 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/warp/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing operations based on warp."""
from .ops import convert_to_warp_mesh, raycast_mesh
| 230 | Python | 24.666664 | 56 | 0.747826 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/warp/ops.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Wrapping around warp kernels for compatibility with torch tensors."""
# needed to import for allowing type-hinting: torch.Tensor | None
from __future__ import annotations
import numpy as np
import torch
import warp as wp
from . import kernels
def raycast_mesh(
ray_starts: torch.Tensor,
ray_directions: torch.Tensor,
mesh: wp.Mesh,
max_dist: float = 1e6,
return_distance: bool = False,
return_normal: bool = False,
return_face_id: bool = False,
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]:
"""Performs ray-casting against a mesh.
Note that the `ray_starts` and `ray_directions`, and `ray_hits` should have compatible shapes
and data types to ensure proper execution. Additionally, they all must be in the same frame.
Args:
ray_starts: The starting position of the rays. Shape (N, 3).
ray_directions: The ray directions for each ray. Shape (N, 3).
mesh: The warp mesh to ray-cast against.
max_dist: The maximum distance to ray-cast. Defaults to 1e6.
return_distance: Whether to return the distance of the ray until it hits the mesh. Defaults to False.
return_normal: Whether to return the normal of the mesh face the ray hits. Defaults to False.
return_face_id: Whether to return the face id of the mesh face the ray hits. Defaults to False.
Returns:
The ray hit position. Shape (N, 3).
The returned tensor contains :obj:`float('inf')` for missed hits.
The ray hit distance. Shape (N,).
Will only return if :attr:`return_distance` is True, else returns None.
The returned tensor contains :obj:`float('inf')` for missed hits.
The ray hit normal. Shape (N, 3).
Will only return if :attr:`return_normal` is True else returns None.
The returned tensor contains :obj:`float('inf')` for missed hits.
The ray hit face id. Shape (N,).
Will only return if :attr:`return_face_id` is True else returns None.
The returned tensor contains :obj:`int(-1)` for missed hits.
"""
# extract device and shape information
shape = ray_starts.shape
device = ray_starts.device
# device of the mesh
torch_device = wp.device_to_torch(mesh.device)
# reshape the tensors
ray_starts = ray_starts.to(torch_device).view(-1, 3).contiguous()
ray_directions = ray_directions.to(torch_device).view(-1, 3).contiguous()
num_rays = ray_starts.shape[0]
# create output tensor for the ray hits
ray_hits = torch.full((num_rays, 3), float("inf"), device=torch_device).contiguous()
# map the memory to warp arrays
ray_starts_wp = wp.from_torch(ray_starts, dtype=wp.vec3)
ray_directions_wp = wp.from_torch(ray_directions, dtype=wp.vec3)
ray_hits_wp = wp.from_torch(ray_hits, dtype=wp.vec3)
if return_distance:
ray_distance = torch.full((num_rays,), float("inf"), device=torch_device).contiguous()
ray_distance_wp = wp.from_torch(ray_distance, dtype=wp.float32)
else:
ray_distance = None
ray_distance_wp = wp.empty((1,), dtype=wp.float32, device=torch_device)
if return_normal:
ray_normal = torch.full((num_rays, 3), float("inf"), device=torch_device).contiguous()
ray_normal_wp = wp.from_torch(ray_normal, dtype=wp.vec3)
else:
ray_normal = None
ray_normal_wp = wp.empty((1,), dtype=wp.vec3, device=torch_device)
if return_face_id:
ray_face_id = torch.ones((num_rays,), dtype=torch.int32, device=torch_device).contiguous() * (-1)
ray_face_id_wp = wp.from_torch(ray_face_id, dtype=wp.int32)
else:
ray_face_id = None
ray_face_id_wp = wp.empty((1,), dtype=wp.int32, device=torch_device)
# launch the warp kernel
wp.launch(
kernel=kernels.raycast_mesh_kernel,
dim=num_rays,
inputs=[
mesh.id,
ray_starts_wp,
ray_directions_wp,
ray_hits_wp,
ray_distance_wp,
ray_normal_wp,
ray_face_id_wp,
float(max_dist),
int(return_distance),
int(return_normal),
int(return_face_id),
],
device=mesh.device,
)
# NOTE: Synchronize is not needed anymore, but we keep it for now. Check with @dhoeller.
wp.synchronize()
if return_distance:
ray_distance = ray_distance.to(device).view(shape[0], shape[1])
if return_normal:
ray_normal = ray_normal.to(device).view(shape)
if return_face_id:
ray_face_id = ray_face_id.to(device).view(shape[0], shape[1])
return ray_hits.to(device).view(shape), ray_distance, ray_normal, ray_face_id
def convert_to_warp_mesh(points: np.ndarray, indices: np.ndarray, device: str) -> wp.Mesh:
"""Create a warp mesh object with a mesh defined from vertices and triangles.
Args:
points: The vertices of the mesh. Shape is (N, 3), where N is the number of vertices.
indices: The triangles of the mesh as references to vertices for each triangle.
Shape is (M, 3), where M is the number of triangles / faces.
device: The device to use for the mesh.
Returns:
The warp mesh object.
"""
return wp.Mesh(
points=wp.array(points.astype(np.float32), dtype=wp.vec3, device=device),
indices=wp.array(indices.astype(np.int32).flatten(), dtype=wp.int32, device=device),
)
| 5,620 | Python | 38.865248 | 109 | 0.64306 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/noise/noise_model.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from . import noise_cfg
def constant_bias_noise(data: torch.Tensor, cfg: noise_cfg.ConstantBiasNoiseCfg) -> torch.Tensor:
"""Add a constant noise."""
return data + cfg.bias
def additive_uniform_noise(data: torch.Tensor, cfg: noise_cfg.UniformNoiseCfg) -> torch.Tensor:
"""Adds a noise sampled from a uniform distribution."""
return data + torch.rand_like(data) * (cfg.n_max - cfg.n_min) + cfg.n_min
def additive_gaussian_noise(data: torch.Tensor, cfg: noise_cfg.GaussianNoiseCfg) -> torch.Tensor:
"""Adds a noise sampled from a gaussian distribution."""
return data + cfg.mean + cfg.std * torch.randn_like(data)
| 870 | Python | 30.107142 | 97 | 0.717241 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/noise/noise_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from collections.abc import Callable
from dataclasses import MISSING
from omni.isaac.orbit.utils import configclass
from . import noise_model
@configclass
class NoiseCfg:
"""Base configuration for a noise term."""
func: Callable[[torch.Tensor, NoiseCfg], torch.Tensor] = MISSING
"""The function to be called for applying the noise.
Note:
The shape of the input and output tensors must be the same.
"""
@configclass
class AdditiveUniformNoiseCfg(NoiseCfg):
"""Configuration for a additive uniform noise term."""
func = noise_model.additive_uniform_noise
n_min: float = -1.0
"""The minimum value of the noise. Defaults to -1.0."""
n_max: float = 1.0
"""The maximum value of the noise. Defaults to 1.0."""
@configclass
class AdditiveGaussianNoiseCfg(NoiseCfg):
"""Configuration for a additive gaussian noise term."""
func = noise_model.additive_gaussian_noise
mean: float = 0.0
"""The mean of the noise. Defaults to 0.0."""
std: float = 1.0
"""The standard deviation of the noise. Defaults to 1.0."""
@configclass
class ConstantBiasNoiseCfg(NoiseCfg):
"""Configuration for a constant bias noise term."""
func = noise_model.constant_bias_noise
bias: float = 0.0
"""The bias to add. Defaults to 0.0."""
| 1,480 | Python | 23.278688 | 68 | 0.693243 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/noise/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing different noise models implementations.
The noise models are implemented as functions that take in a tensor and a configuration and return a tensor
with the noise applied. These functions are then used in the :class:`NoiseCfg` configuration class.
Usage:
.. code-block:: python
import torch
from omni.isaac.orbit.utils.noise import AdditiveGaussianNoiseCfg
# create a random tensor
my_tensor = torch.rand(128, 128, device="cuda")
# create a noise configuration
cfg = AdditiveGaussianNoiseCfg(mean=0.0, std=1.0)
# apply the noise
my_noisified_tensor = cfg.func(my_tensor, cfg)
"""
from .noise_cfg import NoiseCfg # noqa: F401
from .noise_cfg import AdditiveGaussianNoiseCfg, AdditiveUniformNoiseCfg, ConstantBiasNoiseCfg
| 909 | Python | 29.333332 | 107 | 0.753575 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/asset_base_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from typing import Literal
from omni.isaac.orbit.sim import SpawnerCfg
from omni.isaac.orbit.utils import configclass
from .asset_base import AssetBase
@configclass
class AssetBaseCfg:
"""The base configuration class for an asset's parameters.
Please see the :class:`AssetBase` class for more information on the asset class.
"""
@configclass
class InitialStateCfg:
"""Initial state of the asset.
This defines the default initial state of the asset when it is spawned into the simulation, as
well as the default state when the simulation is reset.
After parsing the initial state, the asset class stores this information in the :attr:`data`
attribute of the asset class. This can then be accessed by the user to modify the state of the asset
during the simulation, for example, at resets.
"""
# root position
pos: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Position of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0)."""
rot: tuple[float, float, float, float] = (1.0, 0.0, 0.0, 0.0)
"""Quaternion rotation (w, x, y, z) of the root in simulation world frame.
Defaults to (1.0, 0.0, 0.0, 0.0).
"""
class_type: type[AssetBase] = MISSING
"""The associated asset class.
The class should inherit from :class:`omni.isaac.orbit.assets.asset_base.AssetBase`.
"""
prim_path: str = MISSING
"""Prim path (or expression) to the asset.
.. note::
The expression can contain the environment namespace regex ``{ENV_REGEX_NS}`` which
will be replaced with the environment namespace.
Example: ``{ENV_REGEX_NS}/Robot`` will be replaced with ``/World/envs/env_.*/Robot``.
"""
spawn: SpawnerCfg | None = None
"""Spawn configuration for the asset. Defaults to None.
If None, then no prims are spawned by the asset class. Instead, it is assumed that the
asset is already present in the scene.
"""
init_state: InitialStateCfg = InitialStateCfg()
"""Initial state of the rigid object. Defaults to identity pose."""
collision_group: Literal[0, -1] = 0
"""Collision group of the asset. Defaults to ``0``.
* ``-1``: global collision group (collides with all assets in the scene).
* ``0``: local collision group (collides with other assets in the same environment).
"""
debug_vis: bool = False
"""Whether to enable debug visualization for the asset. Defaults to ``False``."""
| 2,685 | Python | 33.883116 | 108 | 0.667784 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package for different assets, such as rigid objects and articulations.
An asset is a physical object that can be spawned in the simulation. The class handles both
the spawning of the asset into the USD stage as well as initialization of necessary physics
handles to interact with the asset.
Upon construction of the asset instance, the prim corresponding to the asset is spawned into the
USD stage if the spawn configuration is not None. The spawn configuration is defined in the
:attr:`AssetBaseCfg.spawn` attribute. In case the configured :attr:`AssetBaseCfg.prim_path` is
an expression, then the prim is spawned at all the matching paths. Otherwise, a single prim is
spawned at the configured path. For more information on the spawn configuration, see the
:mod:`omni.isaac.orbit.sim.spawners` module.
The asset class also registers callbacks for the stage play/stop events. These are used to
construct the physics handles for the asset as the physics engine is only available when the
stage is playing. Additionally, the class registers a callback for debug visualization of the
asset. This can be enabled by setting the :attr:`AssetBaseCfg.debug_vis` attribute to True.
The asset class follows the following naming convention for its methods:
* **set_xxx()**: These are used to only set the buffers into the :attr:`data` instance. However, they
do not write the data into the simulator. The writing of data only happens when the
:meth:`write_data_to_sim` method is called.
* **write_xxx_to_sim()**: These are used to set the buffers into the :attr:`data` instance and write
the corresponding data into the simulator as well.
* **update(dt)**: These are used to update the buffers in the :attr:`data` instance. This should
be called after a simulation step is performed.
The main reason to separate the ``set`` and ``write`` operations is to provide flexibility to the
user when they need to perform a post-processing operation of the buffers before applying them
into the simulator. A common example for this is dealing with explicit actuator models where the
specified joint targets are not directly applied to the simulator but are instead used to compute
the corresponding actuator torques.
"""
from .articulation import Articulation, ArticulationCfg, ArticulationData
from .asset_base import AssetBase
from .asset_base_cfg import AssetBaseCfg
from .rigid_object import RigidObject, RigidObjectCfg, RigidObjectData
| 2,567 | Python | 56.066665 | 101 | 0.791196 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/asset_base.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import inspect
import re
import weakref
from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any
import omni.kit.app
import omni.timeline
import omni.isaac.orbit.sim as sim_utils
if TYPE_CHECKING:
from .asset_base_cfg import AssetBaseCfg
class AssetBase(ABC):
"""The base interface class for assets.
An asset corresponds to any physics-enabled object that can be spawned in the simulation. These include
rigid objects, articulated objects, deformable objects etc. The core functionality of an asset is to
provide a set of buffers that can be used to interact with the simulator. The buffers are updated
by the asset class and can be written into the simulator using the their respective ``write`` methods.
This allows a convenient way to perform post-processing operations on the buffers before writing them
into the simulator and obtaining the corresponding simulation results.
The class handles both the spawning of the asset into the USD stage as well as initialization of necessary
physics handles to interact with the asset. Upon construction of the asset instance, the prim corresponding
to the asset is spawned into the USD stage if the spawn configuration is not None. The spawn configuration
is defined in the :attr:`AssetBaseCfg.spawn` attribute. In case the configured :attr:`AssetBaseCfg.prim_path`
is an expression, then the prim is spawned at all the matching paths. Otherwise, a single prim is spawned
at the configured path. For more information on the spawn configuration, see the
:mod:`omni.isaac.orbit.sim.spawners` module.
Unlike Isaac Sim interface, where one usually needs to call the
:meth:`omni.isaac.core.prims.XFormPrimView.initialize` method to initialize the PhysX handles, the asset
class automatically initializes and invalidates the PhysX handles when the stage is played/stopped. This
is done by registering callbacks for the stage play/stop events.
Additionally, the class registers a callback for debug visualization of the asset if a debug visualization
is implemented in the asset class. This can be enabled by setting the :attr:`AssetBaseCfg.debug_vis` attribute
to True. The debug visualization is implemented through the :meth:`_set_debug_vis_impl` and
:meth:`_debug_vis_callback` methods.
"""
def __init__(self, cfg: AssetBaseCfg):
"""Initialize the asset base.
Args:
cfg: The configuration class for the asset.
Raises:
RuntimeError: If no prims found at input prim path or prim path expression.
"""
# store inputs
self.cfg = cfg
# flag for whether the asset is initialized
self._is_initialized = False
# check if base asset path is valid
# note: currently the spawner does not work if there is a regex pattern in the leaf
# For example, if the prim path is "/World/Robot_[1,2]" since the spawner will not
# know which prim to spawn. This is a limitation of the spawner and not the asset.
asset_path = self.cfg.prim_path.split("/")[-1]
asset_path_is_regex = re.match(r"^[a-zA-Z0-9/_]+$", asset_path) is None
# spawn the asset
if self.cfg.spawn is not None and not asset_path_is_regex:
self.cfg.spawn.func(
self.cfg.prim_path,
self.cfg.spawn,
translation=self.cfg.init_state.pos,
orientation=self.cfg.init_state.rot,
)
# check that spawn was successful
matching_prims = sim_utils.find_matching_prims(self.cfg.prim_path)
if len(matching_prims) == 0:
raise RuntimeError(f"Could not find prim with path {self.cfg.prim_path}.")
# note: Use weakref on all callbacks to ensure that this object can be deleted when its destructor is called.
# add callbacks for stage play/stop
# The order is set to 10 which is arbitrary but should be lower priority than the default order of 0
timeline_event_stream = omni.timeline.get_timeline_interface().get_timeline_event_stream()
self._initialize_handle = timeline_event_stream.create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.PLAY),
lambda event, obj=weakref.proxy(self): obj._initialize_callback(event),
order=10,
)
self._invalidate_initialize_handle = timeline_event_stream.create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.STOP),
lambda event, obj=weakref.proxy(self): obj._invalidate_initialize_callback(event),
order=10,
)
# add handle for debug visualization (this is set to a valid handle inside set_debug_vis)
self._debug_vis_handle = None
# set initial state of debug visualization
self.set_debug_vis(self.cfg.debug_vis)
def __del__(self):
"""Unsubscribe from the callbacks."""
# clear physics events handles
if self._initialize_handle:
self._initialize_handle.unsubscribe()
self._initialize_handle = None
if self._invalidate_initialize_handle:
self._invalidate_initialize_handle.unsubscribe()
self._invalidate_initialize_handle = None
# clear debug visualization
if self._debug_vis_handle:
self._debug_vis_handle.unsubscribe()
self._debug_vis_handle = None
"""
Properties
"""
@property
@abstractmethod
def num_instances(self) -> int:
"""Number of instances of the asset.
This is equal to the number of asset instances per environment multiplied by the number of environments.
"""
return NotImplementedError
@property
def device(self) -> str:
"""Memory device for computation."""
return self._device
@property
@abstractmethod
def data(self) -> Any:
"""Data related to the asset."""
return NotImplementedError
@property
def has_debug_vis_implementation(self) -> bool:
"""Whether the asset has a debug visualization implemented."""
# check if function raises NotImplementedError
source_code = inspect.getsource(self._set_debug_vis_impl)
return "NotImplementedError" not in source_code
"""
Operations.
"""
def set_debug_vis(self, debug_vis: bool) -> bool:
"""Sets whether to visualize the asset data.
Args:
debug_vis: Whether to visualize the asset data.
Returns:
Whether the debug visualization was successfully set. False if the asset
does not support debug visualization.
"""
# check if debug visualization is supported
if not self.has_debug_vis_implementation:
return False
# toggle debug visualization objects
self._set_debug_vis_impl(debug_vis)
# toggle debug visualization handles
if debug_vis:
# create a subscriber for the post update event if it doesn't exist
if self._debug_vis_handle is None:
app_interface = omni.kit.app.get_app_interface()
self._debug_vis_handle = app_interface.get_post_update_event_stream().create_subscription_to_pop(
lambda event, obj=weakref.proxy(self): obj._debug_vis_callback(event)
)
else:
# remove the subscriber if it exists
if self._debug_vis_handle is not None:
self._debug_vis_handle.unsubscribe()
self._debug_vis_handle = None
# return success
return True
@abstractmethod
def reset(self, env_ids: Sequence[int] | None = None):
"""Resets all internal buffers of selected environments.
Args:
env_ids: The indices of the object to reset. Defaults to None (all instances).
"""
raise NotImplementedError
@abstractmethod
def write_data_to_sim(self):
"""Writes data to the simulator."""
raise NotImplementedError
@abstractmethod
def update(self, dt: float):
"""Update the internal buffers.
The time step ``dt`` is used to compute numerical derivatives of quantities such as joint
accelerations which are not provided by the simulator.
Args:
dt: The amount of time passed from last ``update`` call.
"""
raise NotImplementedError
"""
Implementation specific.
"""
@abstractmethod
def _initialize_impl(self):
"""Initializes the PhysX handles and internal buffers."""
raise NotImplementedError
def _set_debug_vis_impl(self, debug_vis: bool):
"""Set debug visualization into visualization objects.
This function is responsible for creating the visualization objects if they don't exist
and input ``debug_vis`` is True. If the visualization objects exist, the function should
set their visibility into the stage.
"""
raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.")
def _debug_vis_callback(self, event):
"""Callback for debug visualization.
This function calls the visualization objects and sets the data to visualize into them.
"""
raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.")
"""
Internal simulation callbacks.
"""
def _initialize_callback(self, event):
"""Initializes the scene elements.
Note:
PhysX handles are only enabled once the simulator starts playing. Hence, this function needs to be
called whenever the simulator "plays" from a "stop" state.
"""
if not self._is_initialized:
# obtain simulation related information
sim = sim_utils.SimulationContext.instance()
if sim is None:
raise RuntimeError("SimulationContext is not initialized! Please initialize SimulationContext first.")
self._backend = sim.backend
self._device = sim.device
# initialize the asset
self._initialize_impl()
# set flag
self._is_initialized = True
def _invalidate_initialize_callback(self, event):
"""Invalidates the scene elements."""
self._is_initialized = False
| 10,684 | Python | 39.782443 | 118 | 0.659023 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/rigid_object/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for rigid object assets."""
from .rigid_object import RigidObject
from .rigid_object_cfg import RigidObjectCfg
from .rigid_object_data import RigidObjectData
| 296 | Python | 25.999998 | 56 | 0.777027 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/rigid_object/rigid_object_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from ..asset_base_cfg import AssetBaseCfg
from .rigid_object import RigidObject
@configclass
class RigidObjectCfg(AssetBaseCfg):
"""Configuration parameters for a rigid object."""
@configclass
class InitialStateCfg(AssetBaseCfg.InitialStateCfg):
"""Initial state of the rigid body."""
lin_vel: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Linear velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0)."""
ang_vel: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Angular velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0)."""
##
# Initialize configurations.
##
class_type: type = RigidObject
init_state: InitialStateCfg = InitialStateCfg()
"""Initial state of the rigid object. Defaults to identity pose with zero velocity."""
| 1,029 | Python | 30.21212 | 98 | 0.681244 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/rigid_object/rigid_object_data.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import torch
from dataclasses import dataclass
@dataclass
class RigidObjectData:
"""Data container for a rigid object."""
##
# Properties.
##
body_names: list[str] = None
"""Body names in the order parsed by the simulation view."""
##
# Default states.
##
default_root_state: torch.Tensor = None
"""Default root state ``[pos, quat, lin_vel, ang_vel]`` in local environment frame. Shape is (num_instances, 13)."""
##
# Frame states.
##
root_state_w: torch.Tensor = None
"""Root state ``[pos, quat, lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 13)."""
root_vel_b: torch.Tensor = None
"""Root velocity `[lin_vel, ang_vel]` in base frame. Shape is (num_instances, 6)."""
projected_gravity_b: torch.Tensor = None
"""Projection of the gravity direction on base frame. Shape is (num_instances, 3)."""
heading_w: torch.Tensor = None
"""Yaw heading of the base frame (in radians). Shape is (num_instances,).
Note:
This quantity is computed by assuming that the forward-direction of the base
frame is along x-direction, i.e. :math:`(1, 0, 0)`.
"""
body_state_w: torch.Tensor = None
"""State of all bodies `[pos, quat, lin_vel, ang_vel]` in simulation world frame.
Shape is (num_instances, num_bodies, 13)."""
body_acc_w: torch.Tensor = None
"""Acceleration of all bodies. Shape is (num_instances, num_bodies, 6).
Note:
This quantity is computed based on the rigid body state from the last step.
"""
"""
Properties
"""
@property
def root_pos_w(self) -> torch.Tensor:
"""Root position in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, :3]
@property
def root_quat_w(self) -> torch.Tensor:
"""Root orientation (w, x, y, z) in simulation world frame. Shape is (num_instances, 4)."""
return self.root_state_w[:, 3:7]
@property
def root_vel_w(self) -> torch.Tensor:
"""Root velocity in simulation world frame. Shape is (num_instances, 6)."""
return self.root_state_w[:, 7:13]
@property
def root_lin_vel_w(self) -> torch.Tensor:
"""Root linear velocity in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, 7:10]
@property
def root_ang_vel_w(self) -> torch.Tensor:
"""Root angular velocity in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, 10:13]
@property
def root_lin_vel_b(self) -> torch.Tensor:
"""Root linear velocity in base frame. Shape is (num_instances, 3)."""
return self.root_vel_b[:, 0:3]
@property
def root_ang_vel_b(self) -> torch.Tensor:
"""Root angular velocity in base world frame. Shape is (num_instances, 3)."""
return self.root_vel_b[:, 3:6]
@property
def body_pos_w(self) -> torch.Tensor:
"""Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., :3]
@property
def body_quat_w(self) -> torch.Tensor:
"""Orientation (w, x, y, z) of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 4)."""
return self.body_state_w[..., 3:7]
@property
def body_vel_w(self) -> torch.Tensor:
"""Velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 6)."""
return self.body_state_w[..., 7:13]
@property
def body_lin_vel_w(self) -> torch.Tensor:
"""Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., 7:10]
@property
def body_ang_vel_w(self) -> torch.Tensor:
"""Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., 10:13]
@property
def body_lin_acc_w(self) -> torch.Tensor:
"""Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_acc_w[..., 0:3]
@property
def body_ang_acc_w(self) -> torch.Tensor:
"""Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_acc_w[..., 3:6]
| 4,558 | Python | 33.278195 | 120 | 0.621983 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/rigid_object/rigid_object.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
import warnings
from collections.abc import Sequence
from typing import TYPE_CHECKING
import carb
import omni.physics.tensors.impl.api as physx
from pxr import UsdPhysics
import omni.isaac.orbit.sim as sim_utils
import omni.isaac.orbit.utils.math as math_utils
import omni.isaac.orbit.utils.string as string_utils
from ..asset_base import AssetBase
from .rigid_object_data import RigidObjectData
if TYPE_CHECKING:
from .rigid_object_cfg import RigidObjectCfg
class RigidObject(AssetBase):
"""A rigid object asset class.
Rigid objects are assets comprising of rigid bodies. They can be used to represent dynamic objects
such as boxes, spheres, etc. A rigid body is described by its pose, velocity and mass distribution.
For an asset to be considered a rigid object, the root prim of the asset must have the `USD RigidBodyAPI`_
applied to it. This API is used to define the simulation properties of the rigid body. On playing the
simulation, the physics engine will automatically register the rigid body and create a corresponding
rigid body handle. This handle can be accessed using the :attr:`root_physx_view` attribute.
.. note::
For users familiar with Isaac Sim, the PhysX view class API is not the exactly same as Isaac Sim view
class API. Similar to Orbit, Isaac Sim wraps around the PhysX view API. However, as of now (2023.1 release),
we see a large difference in initializing the view classes in Isaac Sim. This is because the view classes
in Isaac Sim perform additional USD-related operations which are slow and also not required.
.. _`USD RigidBodyAPI`: https://openusd.org/dev/api/class_usd_physics_rigid_body_a_p_i.html
"""
cfg: RigidObjectCfg
"""Configuration instance for the rigid object."""
def __init__(self, cfg: RigidObjectCfg):
"""Initialize the rigid object.
Args:
cfg: A configuration instance.
"""
super().__init__(cfg)
# container for data access
self._data = RigidObjectData()
"""
Properties
"""
@property
def data(self) -> RigidObjectData:
return self._data
@property
def num_instances(self) -> int:
return self.root_physx_view.count
@property
def num_bodies(self) -> int:
"""Number of bodies in the asset."""
return 1
@property
def body_names(self) -> list[str]:
"""Ordered names of bodies in articulation."""
prim_paths = self.root_physx_view.prim_paths[: self.num_bodies]
return [path.split("/")[-1] for path in prim_paths]
@property
def root_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
Note:
Use this view with caution. It requires handling of tensors in a specific way.
"""
return self._root_physx_view
@property
def body_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
.. deprecated:: v0.3.0
The attribute 'body_physx_view' will be removed in v0.4.0. Please use :attr:`root_physx_view` instead.
"""
dep_msg = "The attribute 'body_physx_view' will be removed in v0.4.0. Please use 'root_physx_view' instead."
warnings.warn(dep_msg, DeprecationWarning)
carb.log_error(dep_msg)
return self.root_physx_view
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None):
# resolve all indices
if env_ids is None:
env_ids = slice(None)
# reset external wrench
self._external_force_b[env_ids] = 0.0
self._external_torque_b[env_ids] = 0.0
# reset last body vel
self._last_body_vel_w[env_ids] = 0.0
def write_data_to_sim(self):
"""Write external wrench to the simulation.
Note:
We write external wrench to the simulation here since this function is called before the simulation step.
This ensures that the external wrench is applied at every simulation step.
"""
# write external wrench
if self.has_external_wrench:
self.root_physx_view.apply_forces_and_torques_at_position(
force_data=self._external_force_b.view(-1, 3),
torque_data=self._external_torque_b.view(-1, 3),
position_data=None,
indices=self._ALL_BODY_INDICES,
is_global=False,
)
def update(self, dt: float):
# -- root-state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.root_state_w[:, :7] = self.root_physx_view.get_transforms()
self._data.root_state_w[:, 3:7] = math_utils.convert_quat(self._data.root_state_w[:, 3:7], to="wxyz")
self._data.root_state_w[:, 7:] = self.root_physx_view.get_velocities()
# -- body-state (note: for rigid objects, we only have one body so we just copy the root state)
self._data.body_state_w[:] = self._data.root_state_w.view(-1, self.num_bodies, 13)
# -- update common data
self._update_common_data(dt)
def find_bodies(self, name_keys: str | Sequence[str], preserve_order: bool = False) -> tuple[list[int], list[str]]:
"""Find bodies in the articulation based on the name keys.
Please check the :meth:`omni.isaac.orbit.utils.string_utils.resolve_matching_names` function for more
information on the name matching.
Args:
name_keys: A regular expression or a list of regular expressions to match the body names.
preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False.
Returns:
A tuple of lists containing the body indices and names.
"""
return string_utils.resolve_matching_names(name_keys, self.body_names, preserve_order)
"""
Operations - Write to simulation.
"""
def write_root_state_to_sim(self, root_state: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root state over selected environment indices into the simulation.
The root state comprises of the cartesian position, quaternion orientation in (w, x, y, z), and linear
and angular velocity. All the quantities are in the simulation frame.
Args:
root_state: Root state in simulation frame. Shape is (len(env_ids), 13).
env_ids: Environment indices. If None, then all indices are used.
"""
# set into simulation
self.write_root_pose_to_sim(root_state[:, :7], env_ids=env_ids)
self.write_root_velocity_to_sim(root_state[:, 7:], env_ids=env_ids)
def write_root_pose_to_sim(self, root_pose: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root pose over selected environment indices into the simulation.
The root pose comprises of the cartesian position and quaternion orientation in (w, x, y, z).
Args:
root_pose: Root poses in simulation frame. Shape is (len(env_ids), 7).
env_ids: Environment indices. If None, then all indices are used.
"""
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, :7] = root_pose.clone()
# convert root quaternion from wxyz to xyzw
root_poses_xyzw = self._data.root_state_w[:, :7].clone()
root_poses_xyzw[:, 3:] = math_utils.convert_quat(root_poses_xyzw[:, 3:], to="xyzw")
# set into simulation
self.root_physx_view.set_transforms(root_poses_xyzw, indices=physx_env_ids)
def write_root_velocity_to_sim(self, root_velocity: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root velocity over selected environment indices into the simulation.
Args:
root_velocity: Root velocities in simulation frame. Shape is (len(env_ids), 6).
env_ids: Environment indices. If None, then all indices are used.
"""
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, 7:] = root_velocity.clone()
# set into simulation
self.root_physx_view.set_velocities(self._data.root_state_w[:, 7:], indices=physx_env_ids)
"""
Operations - Setters.
"""
def set_external_force_and_torque(
self,
forces: torch.Tensor,
torques: torch.Tensor,
body_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set external force and torque to apply on the asset's bodies in their local frame.
For many applications, we want to keep the applied external force on rigid bodies constant over a period of
time (for instance, during the policy control). This function allows us to store the external force and torque
into buffers which are then applied to the simulation at every step.
.. caution::
If the function is called with empty forces and torques, then this function disables the application
of external wrench to the simulation.
.. code-block:: python
# example of disabling external wrench
asset.set_external_force_and_torque(forces=torch.zeros(0, 3), torques=torch.zeros(0, 3))
.. note::
This function does not apply the external wrench to the simulation. It only fills the buffers with
the desired values. To apply the external wrench, call the :meth:`write_data_to_sim` function
right before the simulation step.
Args:
forces: External forces in bodies' local frame. Shape is (len(env_ids), len(body_ids), 3).
torques: External torques in bodies' local frame. Shape is (len(env_ids), len(body_ids), 3).
body_ids: Body indices to apply external wrench to. Defaults to None (all bodies).
env_ids: Environment indices to apply external wrench to. Defaults to None (all instances).
"""
if forces.any() or torques.any():
self.has_external_wrench = True
# resolve all indices
# -- env_ids
if env_ids is None:
env_ids = self._ALL_INDICES
elif not isinstance(env_ids, torch.Tensor):
env_ids = torch.tensor(env_ids, dtype=torch.long, device=self.device)
# -- body_ids
if body_ids is None:
body_ids = torch.arange(self.num_bodies, dtype=torch.long, device=self.device)
elif isinstance(body_ids, slice):
body_ids = torch.arange(self.num_bodies, dtype=torch.long, device=self.device)[body_ids]
elif not isinstance(body_ids, torch.Tensor):
body_ids = torch.tensor(body_ids, dtype=torch.long, device=self.device)
# note: we need to do this complicated indexing since torch doesn't support multi-indexing
# create global body indices from env_ids and env_body_ids
# (env_id * total_bodies_per_env) + body_id
indices = body_ids.repeat(len(env_ids), 1) + env_ids.unsqueeze(1) * self.num_bodies
indices = indices.view(-1)
# set into internal buffers
# note: these are applied in the write_to_sim function
self._external_force_b.flatten(0, 1)[indices] = forces.flatten(0, 1)
self._external_torque_b.flatten(0, 1)[indices] = torques.flatten(0, 1)
else:
self.has_external_wrench = False
"""
Internal helper.
"""
def _initialize_impl(self):
# create simulation view
self._physics_sim_view = physx.create_simulation_view(self._backend)
self._physics_sim_view.set_subspace_roots("/")
# obtain the first prim in the regex expression (all others are assumed to be a copy of this)
template_prim = sim_utils.find_first_matching_prim(self.cfg.prim_path)
if template_prim is None:
raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.")
template_prim_path = template_prim.GetPath().pathString
# find rigid root prims
root_prims = sim_utils.get_all_matching_child_prims(
template_prim_path, predicate=lambda prim: prim.HasAPI(UsdPhysics.RigidBodyAPI)
)
if len(root_prims) == 0:
raise RuntimeError(
f"Failed to find a rigid body when resolving '{self.cfg.prim_path}'."
" Please ensure that the prim has 'USD RigidBodyAPI' applied."
)
if len(root_prims) > 1:
raise RuntimeError(
f"Failed to find a single rigid body when resolving '{self.cfg.prim_path}'."
f" Found multiple '{root_prims}' under '{template_prim_path}'."
" Please ensure that there is only one rigid body in the prim path tree."
)
# resolve root prim back into regex expression
root_prim_path = root_prims[0].GetPath().pathString
root_prim_path_expr = self.cfg.prim_path + root_prim_path[len(template_prim_path) :]
# -- object view
self._root_physx_view = self._physics_sim_view.create_rigid_body_view(root_prim_path_expr.replace(".*", "*"))
# log information about the articulation
carb.log_info(f"Rigid body initialized at: {self.cfg.prim_path} with root '{root_prim_path_expr}'.")
carb.log_info(f"Number of instances: {self.num_instances}")
carb.log_info(f"Number of bodies: {self.num_bodies}")
carb.log_info(f"Body names: {self.body_names}")
# create buffers
self._create_buffers()
# process configuration
self._process_cfg()
def _create_buffers(self):
"""Create buffers for storing data."""
# constants
self._ALL_INDICES = torch.arange(self.num_instances, dtype=torch.long, device=self.device)
self._ALL_BODY_INDICES = torch.arange(
self.root_physx_view.count * self.num_bodies, dtype=torch.long, device=self.device
)
self.GRAVITY_VEC_W = torch.tensor((0.0, 0.0, -1.0), device=self.device).repeat(self.num_instances, 1)
self.FORWARD_VEC_B = torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self.num_instances, 1)
# external forces and torques
self.has_external_wrench = False
self._external_force_b = torch.zeros((self.num_instances, self.num_bodies, 3), device=self.device)
self._external_torque_b = torch.zeros_like(self._external_force_b)
# asset data
# -- properties
self._data.body_names = self.body_names
# -- root states
self._data.root_state_w = torch.zeros(self.num_instances, 13, device=self.device)
self._data.root_state_w[:, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
self._data.default_root_state = torch.zeros_like(self._data.root_state_w)
self._data.default_root_state[:, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
# -- body states
self._data.body_state_w = torch.zeros(self.num_instances, self.num_bodies, 13, device=self.device)
self._data.body_state_w[:, :, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
# -- post-computed
self._data.root_vel_b = torch.zeros(self.num_instances, 6, device=self.device)
self._data.projected_gravity_b = torch.zeros(self.num_instances, 3, device=self.device)
self._data.heading_w = torch.zeros(self.num_instances, device=self.device)
self._data.body_acc_w = torch.zeros(self.num_instances, self.num_bodies, 6, device=self.device)
# history buffers for quantities
# -- used to compute body accelerations numerically
self._last_body_vel_w = torch.zeros(self.num_instances, self.num_bodies, 6, device=self.device)
def _process_cfg(self):
"""Post processing of configuration parameters."""
# default state
# -- root state
# note: we cast to tuple to avoid torch/numpy type mismatch.
default_root_state = (
tuple(self.cfg.init_state.pos)
+ tuple(self.cfg.init_state.rot)
+ tuple(self.cfg.init_state.lin_vel)
+ tuple(self.cfg.init_state.ang_vel)
)
default_root_state = torch.tensor(default_root_state, dtype=torch.float, device=self.device)
self._data.default_root_state = default_root_state.repeat(self.num_instances, 1)
def _update_common_data(self, dt: float):
"""Update common quantities related to rigid objects.
Note:
This has been separated from the update function to allow for the child classes to
override the update function without having to worry about updating the common data.
"""
# -- body acceleration
self._data.body_acc_w[:] = (self._data.body_state_w[..., 7:] - self._last_body_vel_w) / dt
self._last_body_vel_w[:] = self._data.body_state_w[..., 7:]
# -- root state in body frame
self._data.root_vel_b[:, 0:3] = math_utils.quat_rotate_inverse(
self._data.root_quat_w, self._data.root_lin_vel_w
)
self._data.root_vel_b[:, 3:6] = math_utils.quat_rotate_inverse(
self._data.root_quat_w, self._data.root_ang_vel_w
)
self._data.projected_gravity_b[:] = math_utils.quat_rotate_inverse(self._data.root_quat_w, self.GRAVITY_VEC_W)
# -- heading direction of root
forward_w = math_utils.quat_apply(self._data.root_quat_w, self.FORWARD_VEC_B)
self._data.heading_w[:] = torch.atan2(forward_w[:, 1], forward_w[:, 0])
"""
Internal simulation callbacks.
"""
def _invalidate_initialize_callback(self, event):
"""Invalidates the scene elements."""
# call parent
super()._invalidate_initialize_callback(event)
# set all existing views to None to invalidate them
self._physics_sim_view = None
self._root_physx_view = None
| 18,749 | Python | 43.749403 | 119 | 0.630914 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/articulation/articulation_data.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import torch
from dataclasses import dataclass
from ..rigid_object import RigidObjectData
@dataclass
class ArticulationData(RigidObjectData):
"""Data container for an articulation."""
##
# Properties.
##
joint_names: list[str] = None
"""Joint names in the order parsed by the simulation view."""
##
# Default states.
##
default_joint_pos: torch.Tensor = None
"""Default joint positions of all joints. Shape is (num_instances, num_joints)."""
default_joint_vel: torch.Tensor = None
"""Default joint velocities of all joints. Shape is (num_instances, num_joints)."""
##
# Joint states <- From simulation.
##
joint_pos: torch.Tensor = None
"""Joint positions of all joints. Shape is (num_instances, num_joints)."""
joint_vel: torch.Tensor = None
"""Joint velocities of all joints. Shape is (num_instances, num_joints)."""
joint_acc: torch.Tensor = None
"""Joint acceleration of all joints. Shape is (num_instances, num_joints)."""
##
# Joint commands -- Set into simulation.
##
joint_pos_target: torch.Tensor = None
"""Joint position targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
joint_vel_target: torch.Tensor = None
"""Joint velocity targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
joint_effort_target: torch.Tensor = None
"""Joint effort targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
joint_stiffness: torch.Tensor = None
"""Joint stiffness provided to simulation. Shape is (num_instances, num_joints)."""
joint_damping: torch.Tensor = None
"""Joint damping provided to simulation. Shape is (num_instances, num_joints)."""
joint_armature: torch.Tensor = None
"""Joint armature provided to simulation. Shape is (num_instances, num_joints)."""
joint_friction: torch.Tensor = None
"""Joint friction provided to simulation. Shape is (num_instances, num_joints)."""
##
# Joint commands -- Explicit actuators.
##
computed_torque: torch.Tensor = None
"""Joint torques computed from the actuator model (before clipping). Shape is (num_instances, num_joints).
This quantity is the raw torque output from the actuator mode, before any clipping is applied.
It is exposed for users who want to inspect the computations inside the actuator model.
For instance, to penalize the learning agent for a difference between the computed and applied torques.
Note: The torques are zero for implicit actuator models.
"""
applied_torque: torch.Tensor = None
"""Joint torques applied from the actuator model (after clipping). Shape is (num_instances, num_joints).
These torques are set into the simulation, after clipping the :attr:`computed_torque` based on the
actuator model.
Note: The torques are zero for implicit actuator models.
"""
##
# Other Data.
##
soft_joint_pos_limits: torch.Tensor = None
"""Joint positions limits for all joints. Shape is (num_instances, num_joints, 2)."""
soft_joint_vel_limits: torch.Tensor = None
"""Joint velocity limits for all joints. Shape is (num_instances, num_joints)."""
gear_ratio: torch.Tensor = None
"""Gear ratio for relating motor torques to applied Joint torques. Shape is (num_instances, num_joints)."""
| 4,271 | Python | 34.305785 | 115 | 0.694919 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/articulation/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for rigid articulated assets."""
from .articulation import Articulation
from .articulation_cfg import ArticulationCfg
from .articulation_data import ArticulationData
| 304 | Python | 26.72727 | 56 | 0.792763 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/articulation/articulation.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# Flag for pyright to ignore type errors in this file.
# pyright: reportPrivateUsage=false
from __future__ import annotations
import torch
import warnings
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
import carb
import omni.physics.tensors.impl.api as physx
from omni.isaac.core.utils.types import ArticulationActions
from pxr import UsdPhysics
import omni.isaac.orbit.sim as sim_utils
import omni.isaac.orbit.utils.math as math_utils
import omni.isaac.orbit.utils.string as string_utils
from omni.isaac.orbit.actuators import ActuatorBase, ActuatorBaseCfg, ImplicitActuator
from ..rigid_object import RigidObject
from .articulation_data import ArticulationData
if TYPE_CHECKING:
from .articulation_cfg import ArticulationCfg
class Articulation(RigidObject):
"""An articulation asset class.
An articulation is a collection of rigid bodies connected by joints. The joints can be either
fixed or actuated. The joints can be of different types, such as revolute, prismatic, D-6, etc.
However, the articulation class has currently been tested with revolute and prismatic joints.
The class supports both floating-base and fixed-base articulations. The type of articulation
is determined based on the root joint of the articulation. If the root joint is fixed, then
the articulation is considered a fixed-base system. Otherwise, it is considered a floating-base
system. This can be checked using the :attr:`Articulation.is_fixed_base` attribute.
For an asset to be considered an articulation, the root prim of the asset must have the
`USD ArticulationRootAPI`_. This API is used to define the sub-tree of the articulation using
the reduced coordinate formulation. On playing the simulation, the physics engine parses the
articulation root prim and creates the corresponding articulation in the physics engine. The
articulation root prim can be specified using the :attr:`AssetBaseCfg.prim_path` attribute.
The articulation class is a subclass of the :class:`RigidObject` class. Therefore, it inherits
all the functionality of the rigid object class. In case of an articulation, the :attr:`root_physx_view`
attribute corresponds to the articulation root view and can be used to access the articulation
related data.
The articulation class also provides the functionality to augment the simulation of an articulated
system with custom actuator models. These models can either be explicit or implicit, as detailed in
the :mod:`omni.isaac.orbit.actuators` module. The actuator models are specified using the
:attr:`ArticulationCfg.actuators` attribute. These are then parsed and used to initialize the
corresponding actuator models, when the simulation is played.
During the simulation step, the articulation class first applies the actuator models to compute
the joint commands based on the user-specified targets. These joint commands are then applied
into the simulation. The joint commands can be either position, velocity, or effort commands.
As an example, the following snippet shows how this can be used for position commands:
.. code-block:: python
# an example instance of the articulation class
my_articulation = Articulation(cfg)
# set joint position targets
my_articulation.set_joint_position_target(position)
# propagate the actuator models and apply the computed commands into the simulation
my_articulation.write_data_to_sim()
# step the simulation using the simulation context
sim_context.step()
# update the articulation state, where dt is the simulation time step
my_articulation.update(dt)
.. _`USD ArticulationRootAPI`: https://openusd.org/dev/api/class_usd_physics_articulation_root_a_p_i.html
"""
cfg: ArticulationCfg
"""Configuration instance for the articulations."""
def __init__(self, cfg: ArticulationCfg):
"""Initialize the articulation.
Args:
cfg: A configuration instance.
"""
super().__init__(cfg)
# container for data access
self._data = ArticulationData()
# data for storing actuator group
self.actuators: dict[str, ActuatorBase] = dict.fromkeys(self.cfg.actuators.keys())
"""
Properties
"""
@property
def data(self) -> ArticulationData:
return self._data
@property
def is_fixed_base(self) -> bool:
"""Whether the articulation is a fixed-base or floating-base system."""
return self.root_physx_view.shared_metatype.fixed_base
@property
def num_joints(self) -> int:
"""Number of joints in articulation."""
return self.root_physx_view.shared_metatype.dof_count
@property
def num_fixed_tendons(self) -> int:
"""Number of fixed tendons in articulation."""
return self.root_physx_view.max_fixed_tendons
@property
def num_bodies(self) -> int:
"""Number of bodies in articulation."""
return self.root_physx_view.shared_metatype.link_count
@property
def joint_names(self) -> list[str]:
"""Ordered names of joints in articulation."""
return self.root_physx_view.shared_metatype.dof_names
@property
def body_names(self) -> list[str]:
"""Ordered names of bodies in articulation."""
return self.root_physx_view.shared_metatype.link_names
@property
def root_physx_view(self) -> physx.ArticulationView:
"""Articulation view for the asset (PhysX).
Note:
Use this view with caution. It requires handling of tensors in a specific way.
"""
return self._root_physx_view
@property
def body_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
.. deprecated:: v0.3.0
In previous versions, this attribute returned the rigid body view over all the links of the articulation.
However, this led to confusion with the link ordering as they were not ordered in the same way as the
articulation view.
Therefore, this attribute will be removed in v0.4.0. Please use the :attr:`root_physx_view` attribute
instead.
"""
dep_msg = "The attribute 'body_physx_view' will be removed in v0.4.0. Please use 'root_physx_view' instead."
warnings.warn(dep_msg, DeprecationWarning)
carb.log_error(dep_msg)
return self._body_physx_view
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None):
super().reset(env_ids)
# use ellipses object to skip initial indices.
if env_ids is None:
env_ids = slice(None)
# reset actuators
for actuator in self.actuators.values():
actuator.reset(env_ids)
def write_data_to_sim(self):
"""Write external wrenches and joint commands to the simulation.
If any explicit actuators are present, then the actuator models are used to compute the
joint commands. Otherwise, the joint commands are directly set into the simulation.
"""
# write external wrench
if self.has_external_wrench:
# apply external forces and torques
self._body_physx_view.apply_forces_and_torques_at_position(
force_data=self._external_force_body_view_b.view(-1, 3),
torque_data=self._external_torque_body_view_b.view(-1, 3),
position_data=None,
indices=self._ALL_BODY_INDICES,
is_global=False,
)
# apply actuator models
self._apply_actuator_model()
# write actions into simulation
self.root_physx_view.set_dof_actuation_forces(self._joint_effort_target_sim, self._ALL_INDICES)
# position and velocity targets only for implicit actuators
if self._has_implicit_actuators:
self.root_physx_view.set_dof_position_targets(self._joint_pos_target_sim, self._ALL_INDICES)
self.root_physx_view.set_dof_velocity_targets(self._joint_vel_target_sim, self._ALL_INDICES)
def update(self, dt: float):
# -- root state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.root_state_w[:, :7] = self.root_physx_view.get_root_transforms()
self._data.root_state_w[:, 3:7] = math_utils.convert_quat(self._data.root_state_w[:, 3:7], to="wxyz")
self._data.root_state_w[:, 7:] = self.root_physx_view.get_root_velocities()
# -- body-state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.body_state_w[..., :7] = self.root_physx_view.get_link_transforms()
self._data.body_state_w[..., 3:7] = math_utils.convert_quat(self._data.body_state_w[..., 3:7], to="wxyz")
self._data.body_state_w[..., 7:] = self.root_physx_view.get_link_velocities()
# -- joint states
self._data.joint_pos[:] = self.root_physx_view.get_dof_positions()
self._data.joint_vel[:] = self.root_physx_view.get_dof_velocities()
self._data.joint_acc[:] = (self._data.joint_vel - self._previous_joint_vel) / dt
# -- update common data
# note: these are computed in the base class
self._update_common_data(dt)
# -- update history buffers
self._previous_joint_vel[:] = self._data.joint_vel[:]
def find_joints(
self, name_keys: str | Sequence[str], joint_subset: list[str] | None = None, preserve_order: bool = False
) -> tuple[list[int], list[str]]:
"""Find joints in the articulation based on the name keys.
Please see the :func:`omni.isaac.orbit.utils.string.resolve_matching_names` function for more information
on the name matching.
Args:
name_keys: A regular expression or a list of regular expressions to match the joint names.
joint_subset: A subset of joints to search for. Defaults to None, which means all joints
in the articulation are searched.
preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False.
Returns:
A tuple of lists containing the joint indices and names.
"""
if joint_subset is None:
joint_subset = self.joint_names
# find joints
return string_utils.resolve_matching_names(name_keys, joint_subset, preserve_order)
"""
Operations - Setters.
"""
def set_external_force_and_torque(
self,
forces: torch.Tensor,
torques: torch.Tensor,
body_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
# call parent to set the external forces and torques into buffers
super().set_external_force_and_torque(forces, torques, body_ids, env_ids)
# reordering of the external forces and torques to match the body view ordering
if self.has_external_wrench:
self._external_force_body_view_b = self._external_force_b[:, self._body_view_ordering]
self._external_torque_body_view_b = self._external_torque_b[:, self._body_view_ordering]
"""
Operations - Writers.
"""
def write_root_pose_to_sim(self, root_pose: torch.Tensor, env_ids: Sequence[int] | None = None):
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, :7] = root_pose.clone()
# convert root quaternion from wxyz to xyzw
root_poses_xyzw = self._data.root_state_w[:, :7].clone()
root_poses_xyzw[:, 3:] = math_utils.convert_quat(root_poses_xyzw[:, 3:], to="xyzw")
# set into simulation
self.root_physx_view.set_root_transforms(root_poses_xyzw, indices=physx_env_ids)
def write_root_velocity_to_sim(self, root_velocity: torch.Tensor, env_ids: Sequence[int] | None = None):
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, 7:] = root_velocity.clone()
# set into simulation
self.root_physx_view.set_root_velocities(self._data.root_state_w[:, 7:], indices=physx_env_ids)
def write_joint_state_to_sim(
self,
position: torch.Tensor,
velocity: torch.Tensor,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | slice | None = None,
):
"""Write joint positions and velocities to the simulation.
Args:
position: Joint positions. Shape is (len(env_ids), len(joint_ids)).
velocity: Joint velocities. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_pos[env_ids, joint_ids] = position
self._data.joint_vel[env_ids, joint_ids] = velocity
self._previous_joint_vel[env_ids, joint_ids] = velocity
self._data.joint_acc[env_ids, joint_ids] = 0.0
# set into simulation
self.root_physx_view.set_dof_positions(self._data.joint_pos, indices=physx_env_ids)
self.root_physx_view.set_dof_velocities(self._data.joint_vel, indices=physx_env_ids)
def write_joint_stiffness_to_sim(
self,
stiffness: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint stiffness into the simulation.
Args:
stiffness: Joint stiffness. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the stiffness for. Defaults to None (all joints).
env_ids: The environment indices to set the stiffness for. Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_stiffness[env_ids, joint_ids] = stiffness
# set into simulation
self.root_physx_view.set_dof_stiffnesses(self._data.joint_stiffness.cpu(), indices=physx_env_ids.cpu())
def write_joint_damping_to_sim(
self,
damping: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint damping into the simulation.
Args:
damping: Joint damping. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the damping for.
Defaults to None (all joints).
env_ids: The environment indices to set the damping for.
Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_damping[env_ids, joint_ids] = damping
# set into simulation
self.root_physx_view.set_dof_dampings(self._data.joint_damping.cpu(), indices=physx_env_ids.cpu())
def write_joint_effort_limit_to_sim(
self,
limits: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint effort limits into the simulation.
Args:
limits: Joint torque limits. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# move tensor to cpu if needed
if isinstance(limits, torch.Tensor):
limits = limits.cpu()
# set into internal buffers
torque_limit_all = self.root_physx_view.get_dof_max_forces()
torque_limit_all[env_ids, joint_ids] = limits
# set into simulation
self.root_physx_view.set_dof_max_forces(torque_limit_all.cpu(), indices=physx_env_ids.cpu())
def write_joint_armature_to_sim(
self,
armature: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint armature into the simulation.
Args:
armature: Joint armature. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_armature[env_ids, joint_ids] = armature
# set into simulation
self.root_physx_view.set_dof_armatures(self._data.joint_armature.cpu(), indices=physx_env_ids.cpu())
def write_joint_friction_to_sim(
self,
joint_friction: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint friction into the simulation.
Args:
joint_friction: Joint friction. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_friction[env_ids, joint_ids] = joint_friction
# set into simulation
self.root_physx_view.set_dof_friction_coefficients(self._data.joint_friction.cpu(), indices=physx_env_ids.cpu())
"""
Operations - State.
"""
def set_joint_position_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint position targets into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint position targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
# set targets
self._data.joint_pos_target[env_ids, joint_ids] = target
def set_joint_velocity_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint velocity targets into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint velocity targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
# set targets
self._data.joint_vel_target[env_ids, joint_ids] = target
def set_joint_effort_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint efforts into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint effort targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
# set targets
self._data.joint_effort_target[env_ids, joint_ids] = target
"""
Internal helper.
"""
def _initialize_impl(self):
# create simulation view
self._physics_sim_view = physx.create_simulation_view(self._backend)
self._physics_sim_view.set_subspace_roots("/")
# obtain the first prim in the regex expression (all others are assumed to be a copy of this)
template_prim = sim_utils.find_first_matching_prim(self.cfg.prim_path)
if template_prim is None:
raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.")
template_prim_path = template_prim.GetPath().pathString
# find articulation root prims
root_prims = sim_utils.get_all_matching_child_prims(
template_prim_path, predicate=lambda prim: prim.HasAPI(UsdPhysics.ArticulationRootAPI)
)
if len(root_prims) == 0:
raise RuntimeError(
f"Failed to find an articulation when resolving '{self.cfg.prim_path}'."
" Please ensure that the prim has 'USD ArticulationRootAPI' applied."
)
if len(root_prims) > 1:
raise RuntimeError(
f"Failed to find a single articulation when resolving '{self.cfg.prim_path}'."
f" Found multiple '{root_prims}' under '{template_prim_path}'."
" Please ensure that there is only one articulation in the prim path tree."
)
# resolve articulation root prim back into regex expression
root_prim_path = root_prims[0].GetPath().pathString
root_prim_path_expr = self.cfg.prim_path + root_prim_path[len(template_prim_path) :]
# -- articulation
self._root_physx_view = self._physics_sim_view.create_articulation_view(root_prim_path_expr.replace(".*", "*"))
# -- link views
# note: we use the root view to get the body names, but we use the body view to get the
# actual data. This is mainly needed to apply external forces to the bodies.
physx_body_names = self.root_physx_view.shared_metatype.link_names
body_names_regex = r"(" + "|".join(physx_body_names) + r")"
body_names_regex = f"{self.cfg.prim_path}/{body_names_regex}"
self._body_physx_view = self._physics_sim_view.create_rigid_body_view(body_names_regex.replace(".*", "*"))
# create ordering from articulation view to body view for body names
# note: we need to do this since the body view is not ordered in the same way as the articulation view
# -- root view
root_view_body_names = self.body_names
# -- body view
prim_paths = self._body_physx_view.prim_paths[: self.num_bodies]
body_view_body_names = [path.split("/")[-1] for path in prim_paths]
# -- mapping from articulation view to body view
self._body_view_ordering = [body_view_body_names.index(name) for name in root_view_body_names]
self._body_view_ordering = torch.tensor(self._body_view_ordering, dtype=torch.long, device=self.device)
# log information about the articulation
carb.log_info(f"Articulation initialized at: {self.cfg.prim_path} with root '{root_prim_path_expr}'.")
carb.log_info(f"Is fixed root: {self.is_fixed_base}")
carb.log_info(f"Number of bodies: {self.num_bodies}")
carb.log_info(f"Body names: {self.body_names}")
carb.log_info(f"Number of joints: {self.num_joints}")
carb.log_info(f"Joint names: {self.joint_names}")
carb.log_info(f"Number of fixed tendons: {self.num_fixed_tendons}")
# -- assert that parsing was successful
if set(physx_body_names) != set(self.body_names):
raise RuntimeError("Failed to parse all bodies properly in the articulation.")
# create buffers
self._create_buffers()
# process configuration
self._process_cfg()
self._process_actuators_cfg()
# validate configuration
self._validate_cfg()
# log joint information
self._log_articulation_joint_info()
def _create_buffers(self):
# allocate buffers
super()._create_buffers()
# history buffers
self._previous_joint_vel = torch.zeros(self.num_instances, self.num_joints, device=self.device)
# asset data
# -- properties
self._data.joint_names = self.joint_names
# -- joint states
self._data.joint_pos = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.joint_vel = torch.zeros_like(self._data.joint_pos)
self._data.joint_acc = torch.zeros_like(self._data.joint_pos)
self._data.default_joint_pos = torch.zeros_like(self._data.joint_pos)
self._data.default_joint_vel = torch.zeros_like(self._data.joint_pos)
# -- joint commands
self._data.joint_pos_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_vel_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_effort_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_stiffness = torch.zeros_like(self._data.joint_pos)
self._data.joint_damping = torch.zeros_like(self._data.joint_pos)
self._data.joint_armature = torch.zeros_like(self._data.joint_pos)
self._data.joint_friction = torch.zeros_like(self._data.joint_pos)
# -- joint commands (explicit)
self._data.computed_torque = torch.zeros_like(self._data.joint_pos)
self._data.applied_torque = torch.zeros_like(self._data.joint_pos)
# -- other data
self._data.soft_joint_pos_limits = torch.zeros(self.num_instances, self.num_joints, 2, device=self.device)
self._data.soft_joint_vel_limits = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.gear_ratio = torch.ones(self.num_instances, self.num_joints, device=self.device)
# soft joint position limits (recommended not to be too close to limits).
joint_pos_limits = self.root_physx_view.get_dof_limits()
joint_pos_mean = (joint_pos_limits[..., 0] + joint_pos_limits[..., 1]) / 2
joint_pos_range = joint_pos_limits[..., 1] - joint_pos_limits[..., 0]
soft_limit_factor = self.cfg.soft_joint_pos_limit_factor
# add to data
self._data.soft_joint_pos_limits[..., 0] = joint_pos_mean - 0.5 * joint_pos_range * soft_limit_factor
self._data.soft_joint_pos_limits[..., 1] = joint_pos_mean + 0.5 * joint_pos_range * soft_limit_factor
# create buffers to store processed actions from actuator models
self._joint_pos_target_sim = torch.zeros_like(self._data.joint_pos_target)
self._joint_vel_target_sim = torch.zeros_like(self._data.joint_pos_target)
self._joint_effort_target_sim = torch.zeros_like(self._data.joint_pos_target)
def _process_cfg(self):
"""Post processing of configuration parameters."""
# default state
super()._process_cfg()
# -- joint state
# joint pos
indices_list, _, values_list = string_utils.resolve_matching_names_values(
self.cfg.init_state.joint_pos, self.joint_names
)
self._data.default_joint_pos[:, indices_list] = torch.tensor(values_list, device=self.device)
# joint vel
indices_list, _, values_list = string_utils.resolve_matching_names_values(
self.cfg.init_state.joint_vel, self.joint_names
)
self._data.default_joint_vel[:, indices_list] = torch.tensor(values_list, device=self.device)
"""
Internal helpers -- Actuators.
"""
def _process_actuators_cfg(self):
"""Process and apply articulation joint properties."""
# flag for implicit actuators
# if this is false, we by-pass certain checks when doing actuator-related operations
self._has_implicit_actuators = False
# cache the values coming from the usd
usd_stiffness = self.root_physx_view.get_dof_stiffnesses().clone()
usd_damping = self.root_physx_view.get_dof_dampings().clone()
usd_armature = self.root_physx_view.get_dof_armatures().clone()
usd_friction = self.root_physx_view.get_dof_friction_coefficients().clone()
usd_effort_limit = self.root_physx_view.get_dof_max_forces().clone()
usd_velocity_limit = self.root_physx_view.get_dof_max_velocities().clone()
# iterate over all actuator configurations
for actuator_name, actuator_cfg in self.cfg.actuators.items():
# type annotation for type checkers
actuator_cfg: ActuatorBaseCfg
# create actuator group
joint_ids, joint_names = self.find_joints(actuator_cfg.joint_names_expr)
# check if any joints are found
if len(joint_names) == 0:
raise ValueError(
f"No joints found for actuator group: {actuator_name} with joint name expression:"
f" {actuator_cfg.joint_names_expr}."
)
# create actuator collection
# note: for efficiency avoid indexing when over all indices
actuator: ActuatorBase = actuator_cfg.class_type(
cfg=actuator_cfg,
joint_names=joint_names,
joint_ids=slice(None) if len(joint_names) == self.num_joints else joint_ids,
num_envs=self.num_instances,
device=self.device,
stiffness=usd_stiffness[:, joint_ids],
damping=usd_damping[:, joint_ids],
armature=usd_armature[:, joint_ids],
friction=usd_friction[:, joint_ids],
effort_limit=usd_effort_limit[:, joint_ids],
velocity_limit=usd_velocity_limit[:, joint_ids],
)
# log information on actuator groups
carb.log_info(
f"Actuator collection: {actuator_name} with model '{actuator_cfg.class_type.__name__}' and"
f" joint names: {joint_names} [{joint_ids}]."
)
# store actuator group
self.actuators[actuator_name] = actuator
# set the passed gains and limits into the simulation
if isinstance(actuator, ImplicitActuator):
self._has_implicit_actuators = True
# the gains and limits are set into the simulation since actuator model is implicit
self.write_joint_stiffness_to_sim(actuator.stiffness, joint_ids=actuator.joint_indices)
self.write_joint_damping_to_sim(actuator.damping, joint_ids=actuator.joint_indices)
self.write_joint_effort_limit_to_sim(actuator.effort_limit, joint_ids=actuator.joint_indices)
self.write_joint_armature_to_sim(actuator.armature, joint_ids=actuator.joint_indices)
self.write_joint_friction_to_sim(actuator.friction, joint_ids=actuator.joint_indices)
else:
# the gains and limits are processed by the actuator model
# we set gains to zero, and torque limit to a high value in simulation to avoid any interference
self.write_joint_stiffness_to_sim(0.0, joint_ids=actuator.joint_indices)
self.write_joint_damping_to_sim(0.0, joint_ids=actuator.joint_indices)
self.write_joint_effort_limit_to_sim(1.0e9, joint_ids=actuator.joint_indices)
self.write_joint_armature_to_sim(actuator.armature, joint_ids=actuator.joint_indices)
self.write_joint_friction_to_sim(actuator.friction, joint_ids=actuator.joint_indices)
# perform some sanity checks to ensure actuators are prepared correctly
total_act_joints = sum(actuator.num_joints for actuator in self.actuators.values())
if total_act_joints != (self.num_joints - self.num_fixed_tendons):
carb.log_warn(
"Not all actuators are configured! Total number of actuated joints not equal to number of"
f" joints available: {total_act_joints} != {self.num_joints}."
)
def _apply_actuator_model(self):
"""Processes joint commands for the articulation by forwarding them to the actuators.
The actions are first processed using actuator models. Depending on the robot configuration,
the actuator models compute the joint level simulation commands and sets them into the PhysX buffers.
"""
# process actions per group
for actuator in self.actuators.values():
# prepare input for actuator model based on cached data
# TODO : A tensor dict would be nice to do the indexing of all tensors together
control_action = ArticulationActions(
joint_positions=self._data.joint_pos_target[:, actuator.joint_indices],
joint_velocities=self._data.joint_vel_target[:, actuator.joint_indices],
joint_efforts=self._data.joint_effort_target[:, actuator.joint_indices],
joint_indices=actuator.joint_indices,
)
# compute joint command from the actuator model
control_action = actuator.compute(
control_action,
joint_pos=self._data.joint_pos[:, actuator.joint_indices],
joint_vel=self._data.joint_vel[:, actuator.joint_indices],
)
# update targets (these are set into the simulation)
if control_action.joint_positions is not None:
self._joint_pos_target_sim[:, actuator.joint_indices] = control_action.joint_positions
if control_action.joint_velocities is not None:
self._joint_vel_target_sim[:, actuator.joint_indices] = control_action.joint_velocities
if control_action.joint_efforts is not None:
self._joint_effort_target_sim[:, actuator.joint_indices] = control_action.joint_efforts
# update state of the actuator model
# -- torques
self._data.computed_torque[:, actuator.joint_indices] = actuator.computed_effort
self._data.applied_torque[:, actuator.joint_indices] = actuator.applied_effort
# -- actuator data
self._data.soft_joint_vel_limits[:, actuator.joint_indices] = actuator.velocity_limit
# TODO: find a cleaner way to handle gear ratio. Only needed for variable gear ratio actuators.
if hasattr(actuator, "gear_ratio"):
self._data.gear_ratio[:, actuator.joint_indices] = actuator.gear_ratio
"""
Internal helpers -- Debugging.
"""
def _validate_cfg(self):
"""Validate the configuration after processing.
Note:
This function should be called only after the configuration has been processed and the buffers have been
created. Otherwise, some settings that are altered during processing may not be validated.
For instance, the actuator models may change the joint max velocity limits.
"""
# check that the default values are within the limits
joint_pos_limits = self.root_physx_view.get_dof_limits()[0].to(self.device)
out_of_range = self._data.default_joint_pos[0] < joint_pos_limits[:, 0]
out_of_range |= self._data.default_joint_pos[0] > joint_pos_limits[:, 1]
violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1)
# throw error if any of the default joint positions are out of the limits
if len(violated_indices) > 0:
# prepare message for violated joints
msg = "The following joints have default positions out of the limits: \n"
for idx in violated_indices:
joint_name = self.data.joint_names[idx]
joint_limits = joint_pos_limits[idx]
joint_pos = self.data.default_joint_pos[0, idx]
# add to message
msg += f"\t- '{joint_name}': {joint_pos:.3f} not in [{joint_limits[0]:.3f}, {joint_limits[1]:.3f}]\n"
raise ValueError(msg)
# check that the default joint velocities are within the limits
joint_max_vel = self.root_physx_view.get_dof_max_velocities()[0].to(self.device)
out_of_range = torch.abs(self._data.default_joint_vel[0]) > joint_max_vel
violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1)
if len(violated_indices) > 0:
# prepare message for violated joints
msg = "The following joints have default velocities out of the limits: \n"
for idx in violated_indices:
joint_name = self.data.joint_names[idx]
joint_limits = [-joint_max_vel[idx], joint_max_vel[idx]]
joint_vel = self.data.default_joint_vel[0, idx]
# add to message
msg += f"\t- '{joint_name}': {joint_vel:.3f} not in [{joint_limits[0]:.3f}, {joint_limits[1]:.3f}]\n"
raise ValueError(msg)
def _log_articulation_joint_info(self):
"""Log information about the articulation's simulated joints."""
# read out all joint parameters from simulation
# -- gains
stiffnesses = self.root_physx_view.get_dof_stiffnesses()[0].tolist()
dampings = self.root_physx_view.get_dof_dampings()[0].tolist()
# -- properties
armatures = self.root_physx_view.get_dof_armatures()[0].tolist()
frictions = self.root_physx_view.get_dof_friction_coefficients()[0].tolist()
# -- limits
position_limits = self.root_physx_view.get_dof_limits()[0].tolist()
velocity_limits = self.root_physx_view.get_dof_max_velocities()[0].tolist()
effort_limits = self.root_physx_view.get_dof_max_forces()[0].tolist()
# create table for term information
table = PrettyTable(float_format=".3f")
table.title = f"Simulation Joint Information (Prim path: {self.cfg.prim_path})"
table.field_names = [
"Index",
"Name",
"Stiffness",
"Damping",
"Armature",
"Friction",
"Position Limits",
"Velocity Limits",
"Effort Limits",
]
# set alignment of table columns
table.align["Name"] = "l"
# add info on each term
for index, name in enumerate(self.joint_names):
table.add_row([
index,
name,
stiffnesses[index],
dampings[index],
armatures[index],
frictions[index],
position_limits[index],
velocity_limits[index],
effort_limits[index],
])
# convert table to string
carb.log_info(f"Simulation parameters for joints in {self.cfg.prim_path}:\n" + table.get_string())
# read out all tendon parameters from simulation
if self.num_fixed_tendons > 0:
# -- gains
ft_stiffnesses = self.root_physx_view.get_fixed_tendon_stiffnesses()[0].tolist()
ft_dampings = self.root_physx_view.get_fixed_tendon_dampings()[0].tolist()
# -- limits
ft_limit_stiffnesses = self.root_physx_view.get_fixed_tendon_limit_stiffnesses()[0].tolist()
ft_limits = self.root_physx_view.get_fixed_tendon_limits()[0].tolist()
ft_rest_lengths = self.root_physx_view.get_fixed_tendon_rest_lengths()[0].tolist()
ft_offsets = self.root_physx_view.get_fixed_tendon_offsets()[0].tolist()
# create table for term information
tendon_table = PrettyTable(float_format=".3f")
tendon_table.title = f"Simulation Tendon Information (Prim path: {self.cfg.prim_path})"
tendon_table.field_names = [
"Index",
"Stiffness",
"Damping",
"Limit Stiffness",
"Limit",
"Rest Length",
"Offset",
]
# add info on each term
for index in range(self.num_fixed_tendons):
tendon_table.add_row([
index,
ft_stiffnesses[index],
ft_dampings[index],
ft_limit_stiffnesses[index],
ft_limits[index],
ft_rest_lengths[index],
ft_offsets[index],
])
# convert table to string
carb.log_info(f"Simulation parameters for tendons in {self.cfg.prim_path}:\n" + tendon_table.get_string())
| 43,750 | Python | 46.972588 | 120 | 0.627429 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/articulation/articulation_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from omni.isaac.orbit.actuators import ActuatorBaseCfg
from omni.isaac.orbit.utils import configclass
from ..rigid_object import RigidObjectCfg
from .articulation import Articulation
@configclass
class ArticulationCfg(RigidObjectCfg):
"""Configuration parameters for an articulation."""
class_type: type = Articulation
@configclass
class InitialStateCfg(RigidObjectCfg.InitialStateCfg):
"""Initial state of the articulation."""
# root position
joint_pos: dict[str, float] = {".*": 0.0}
"""Joint positions of the joints. Defaults to 0.0 for all joints."""
joint_vel: dict[str, float] = {".*": 0.0}
"""Joint velocities of the joints. Defaults to 0.0 for all joints."""
##
# Initialize configurations.
##
init_state: InitialStateCfg = InitialStateCfg()
"""Initial state of the articulated object. Defaults to identity pose with zero velocity and zero joint state."""
soft_joint_pos_limit_factor: float = 1.0
"""Fraction specifying the range of DOF position limits (parsed from the asset) to use.
Defaults to 1.0."""
actuators: dict[str, ActuatorBaseCfg] = MISSING
"""Actuators for the robot with corresponding joint names."""
| 1,391 | Python | 32.142856 | 117 | 0.702372 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/markers/visualization_markers.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""A class to coordinate groups of visual markers (such as spheres, frames or arrows)
using `UsdGeom.PointInstancer`_ class.
The class :class:`VisualizationMarkers` is used to create a group of visual markers and
visualize them in the viewport. The markers are represented as :class:`UsdGeom.PointInstancer` prims
in the USD stage. The markers are created as prototypes in the :class:`UsdGeom.PointInstancer` prim
and are instanced in the :class:`UsdGeom.PointInstancer` prim. The markers can be visualized by
passing the indices of the marker prototypes and their translations, orientations and scales.
The marker prototypes can be configured with the :class:`VisualizationMarkersCfg` class.
.. _UsdGeom.PointInstancer: https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html
"""
# needed to import for allowing type-hinting: np.ndarray | torch.Tensor | None
from __future__ import annotations
import numpy as np
import torch
from dataclasses import MISSING
import omni.isaac.core.utils.stage as stage_utils
import omni.kit.commands
import omni.physx.scripts.utils as physx_utils
from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics, Vt
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.sim.spawners import SpawnerCfg
from omni.isaac.orbit.utils.configclass import configclass
from omni.isaac.orbit.utils.math import convert_quat
@configclass
class VisualizationMarkersCfg:
"""A class to configure a :class:`VisualizationMarkers`."""
prim_path: str = MISSING
"""The prim path where the :class:`UsdGeom.PointInstancer` will be created."""
markers: dict[str, SpawnerCfg] = MISSING
"""The dictionary of marker configurations.
The key is the name of the marker, and the value is the configuration of the marker.
The key is used to identify the marker in the class.
"""
class VisualizationMarkers:
"""A class to coordinate groups of visual markers (loaded from USD).
This class allows visualization of different UI markers in the scene, such as points and frames.
The class wraps around the `UsdGeom.PointInstancer`_ for efficient handling of objects
in the stage via instancing the created marker prototype prims.
A marker prototype prim is a reusable template prim used for defining variations of objects
in the scene. For example, a sphere prim can be used as a marker prototype prim to create
multiple sphere prims in the scene at different locations. Thus, prototype prims are useful
for creating multiple instances of the same prim in the scene.
The class parses the configuration to create different the marker prototypes into the stage. Each marker
prototype prim is created as a child of the :class:`UsdGeom.PointInstancer` prim. The prim path for the
the marker prim is resolved using the key of the marker in the :attr:`VisualizationMarkersCfg.markers`
dictionary. The marker prototypes are created using the :meth:`omni.isaac.core.utils.create_prim`
function, and then then instanced using :class:`UsdGeom.PointInstancer` prim to allow creating multiple
instances of the marker prims.
Switching between different marker prototypes is possible by calling the :meth:`visualize` method with
the prototype indices corresponding to the marker prototype. The prototype indices are based on the order
in the :attr:`VisualizationMarkersCfg.markers` dictionary. For example, if the dictionary has two markers,
"marker1" and "marker2", then their prototype indices are 0 and 1 respectively. The prototype indices
can be passed as a list or array of integers.
Usage:
The following snippet shows how to create 24 sphere markers with a radius of 1.0 at random translations
within the range [-1.0, 1.0]. The first 12 markers will be colored red and the rest will be colored green.
.. code-block:: python
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.markers import VisualizationMarkersCfg, VisualizationMarkers
# Create the markers configuration
# This creates two marker prototypes, "marker1" and "marker2" which are spheres with a radius of 1.0.
# The color of "marker1" is red and the color of "marker2" is green.
cfg = VisualizationMarkersCfg(
prim_path="/World/Visuals/testMarkers",
markers={
"marker1": sim_utils.SphereCfg(
radius=1.0,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"marker2": VisualizationMarkersCfg.SphereCfg(
radius=1.0,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
),
}
)
# Create the markers instance
# This will create a UsdGeom.PointInstancer prim at the given path along with the marker prototypes.
marker = VisualizationMarkers(cfg)
# Set position of the marker
# -- randomly sample translations between -1.0 and 1.0
marker_translations = np.random.uniform(-1.0, 1.0, (24, 3))
# -- this will create 24 markers at the given translations
# note: the markers will all be `marker1` since the marker indices are not given
marker.visualize(translations=marker_translations)
# alter the markers based on their prototypes indices
# first 12 markers will be marker1 and the rest will be marker2
# 0 -> marker1, 1 -> marker2
marker_indices = [0] * 12 + [1] * 12
# this will change the marker prototypes at the given indices
# note: the translations of the markers will not be changed from the previous call
# since the translations are not given.
marker.visualize(marker_indices=marker_indices)
# alter the markers based on their prototypes indices and translations
marker.visualize(marker_indices=marker_indices, translations=marker_translations)
.. _UsdGeom.PointInstancer: https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html
"""
def __init__(self, cfg: VisualizationMarkersCfg):
"""Initialize the class.
When the class is initialized, the :class:`UsdGeom.PointInstancer` is created into the stage
and the marker prims are registered into it.
.. note::
If a prim already exists at the given path, the function will find the next free path
and create the :class:`UsdGeom.PointInstancer` prim there.
Args:
cfg: The configuration for the markers.
Raises:
ValueError: When no markers are provided in the :obj:`cfg`.
"""
# get next free path for the prim
prim_path = stage_utils.get_next_free_path(cfg.prim_path)
# create a new prim
stage = stage_utils.get_current_stage()
self._instancer_manager = UsdGeom.PointInstancer.Define(stage, prim_path)
# store inputs
self.prim_path = prim_path
self.cfg = cfg
# check if any markers is provided
if len(self.cfg.markers) == 0:
raise ValueError(f"The `cfg.markers` cannot be empty. Received: {self.cfg.markers}")
# create a child prim for the marker
self._add_markers_prototypes(self.cfg.markers)
# Note: We need to do this the first time to initialize the instancer.
# Otherwise, the instancer will not be "created" and the function `GetInstanceIndices()` will fail.
self._instancer_manager.GetProtoIndicesAttr().Set(list(range(self.num_prototypes)))
self._instancer_manager.GetPositionsAttr().Set([Gf.Vec3f(0.0)] * self.num_prototypes)
self._count = self.num_prototypes
def __str__(self) -> str:
"""Return: A string representation of the class."""
msg = f"VisualizationMarkers(prim_path={self.prim_path})"
msg += f"\n\tCount: {self.count}"
msg += f"\n\tNumber of prototypes: {self.num_prototypes}"
msg += "\n\tMarkers Prototypes:"
for index, (name, marker) in enumerate(self.cfg.markers.items()):
msg += f"\n\t\t[Index: {index}]: {name}: {marker.to_dict()}"
return msg
"""
Properties.
"""
@property
def num_prototypes(self) -> int:
"""The number of marker prototypes available."""
return len(self.cfg.markers)
@property
def count(self) -> int:
"""The total number of marker instances."""
# TODO: Update this when the USD API is available (Isaac Sim 2023.1)
# return self._instancer_manager.GetInstanceCount()
return self._count
"""
Operations.
"""
def set_visibility(self, visible: bool):
"""Sets the visibility of the markers.
The method does this through the USD API.
Args:
visible: flag to set the visibility.
"""
imageable = UsdGeom.Imageable(self._instancer_manager)
if visible:
imageable.MakeVisible()
else:
imageable.MakeInvisible()
def is_visible(self) -> bool:
"""Checks the visibility of the markers.
Returns:
True if the markers are visible, False otherwise.
"""
return self._instancer_manager.GetVisibilityAttr().Get() != UsdGeom.Tokens.invisible
def visualize(
self,
translations: np.ndarray | torch.Tensor | None = None,
orientations: np.ndarray | torch.Tensor | None = None,
scales: np.ndarray | torch.Tensor | None = None,
marker_indices: list[int] | np.ndarray | torch.Tensor | None = None,
):
"""Update markers in the viewport.
.. note::
If the prim `PointInstancer` is hidden in the stage, the function will simply return
without updating the markers. This helps in unnecessary computation when the markers
are not visible.
Whenever updating the markers, the input arrays must have the same number of elements
in the first dimension. If the number of elements is different, the `UsdGeom.PointInstancer`
will raise an error complaining about the mismatch.
Additionally, the function supports dynamic update of the markers. This means that the
number of markers can change between calls. For example, if you have 24 points that you
want to visualize, you can pass 24 translations, orientations, and scales. If you want to
visualize only 12 points, you can pass 12 translations, orientations, and scales. The
function will automatically update the number of markers in the scene.
The function will also update the marker prototypes based on their prototype indices. For instance,
if you have two marker prototypes, and you pass the following marker indices: [0, 1, 0, 1], the function
will update the first and third markers with the first prototype, and the second and fourth markers
with the second prototype. This is useful when you want to visualize different markers in the same
scene. The list of marker indices must have the same number of elements as the translations, orientations,
or scales. If the number of elements is different, the function will raise an error.
.. caution::
This function will update all the markers instanced from the prototypes. That means
if you have 24 markers, you will need to pass 24 translations, orientations, and scales.
If you want to update only a subset of the markers, you will need to handle the indices
yourself and pass the complete arrays to this function.
Args:
translations: Translations w.r.t. parent prim frame. Shape is (M, 3).
Defaults to None, which means left unchanged.
orientations: Quaternion orientations (w, x, y, z) w.r.t. parent prim frame. Shape is (M, 4).
Defaults to None, which means left unchanged.
scales: Scale applied before any rotation is applied. Shape is (M, 3).
Defaults to None, which means left unchanged.
marker_indices: Decides which marker prototype to visualize. Shape is (M).
Defaults to None, which means left unchanged provided that the total number of markers
is the same as the previous call. If the number of markers is different, the function
will update the number of markers in the scene.
Raises:
ValueError: When input arrays do not follow the expected shapes.
ValueError: When the function is called with all None arguments.
"""
# check if it is visible (if not then let's not waste time)
if not self.is_visible():
return
# check if we have any markers to visualize
num_markers = 0
# resolve inputs
# -- position
if translations is not None:
if isinstance(translations, torch.Tensor):
translations = translations.detach().cpu().numpy()
# check that shape is correct
if translations.shape[1] != 3 or len(translations.shape) != 2:
raise ValueError(f"Expected `translations` to have shape (M, 3). Received: {translations.shape}.")
# apply translations
self._instancer_manager.GetPositionsAttr().Set(Vt.Vec3fArray.FromNumpy(translations))
# update number of markers
num_markers = translations.shape[0]
# -- orientation
if orientations is not None:
if isinstance(orientations, torch.Tensor):
orientations = orientations.detach().cpu().numpy()
# check that shape is correct
if orientations.shape[1] != 4 or len(orientations.shape) != 2:
raise ValueError(f"Expected `orientations` to have shape (M, 4). Received: {orientations.shape}.")
# roll orientations from (w, x, y, z) to (x, y, z, w)
# internally USD expects (x, y, z, w)
orientations = convert_quat(orientations, to="xyzw")
# apply orientations
self._instancer_manager.GetOrientationsAttr().Set(Vt.QuathArray.FromNumpy(orientations))
# update number of markers
num_markers = orientations.shape[0]
# -- scales
if scales is not None:
if isinstance(scales, torch.Tensor):
scales = scales.detach().cpu().numpy()
# check that shape is correct
if scales.shape[1] != 3 or len(scales.shape) != 2:
raise ValueError(f"Expected `scales` to have shape (M, 3). Received: {scales.shape}.")
# apply scales
self._instancer_manager.GetScalesAttr().Set(Vt.Vec3fArray.FromNumpy(scales))
# update number of markers
num_markers = scales.shape[0]
# -- status
if marker_indices is not None or num_markers != self._count:
# apply marker indices
if marker_indices is not None:
if isinstance(marker_indices, torch.Tensor):
marker_indices = marker_indices.detach().cpu().numpy()
elif isinstance(marker_indices, list):
marker_indices = np.array(marker_indices)
# check that shape is correct
if len(marker_indices.shape) != 1:
raise ValueError(f"Expected `marker_indices` to have shape (M,). Received: {marker_indices.shape}.")
# apply proto indices
self._instancer_manager.GetProtoIndicesAttr().Set(Vt.IntArray.FromNumpy(marker_indices))
# update number of markers
num_markers = marker_indices.shape[0]
else:
# check that number of markers is not zero
if num_markers == 0:
raise ValueError("Number of markers cannot be zero! Hint: The function was called with no inputs?")
# set all markers to be the first prototype
self._instancer_manager.GetProtoIndicesAttr().Set([0] * num_markers)
# set number of markers
self._count = num_markers
"""
Helper functions.
"""
def _add_markers_prototypes(self, markers_cfg: dict[str, sim_utils.SpawnerCfg]):
"""Adds markers prototypes to the scene and sets the markers instancer to use them."""
# add markers based on config
for name, cfg in markers_cfg.items():
# resolve prim path
marker_prim_path = f"{self.prim_path}/{name}"
# create a child prim for the marker
prim = cfg.func(prim_path=marker_prim_path, cfg=cfg)
# make the asset uninstanceable (in case it is)
# point instancer defines its own prototypes so if an asset is already instanced, this doesn't work.
self._process_prototype_prim(prim)
# remove any physics on the markers because they are only for visualization!
physx_utils.removeRigidBodySubtree(prim)
# add child reference to point instancer
self._instancer_manager.GetPrototypesRel().AddTarget(marker_prim_path)
# check that we loaded all the prototypes
prototypes = self._instancer_manager.GetPrototypesRel().GetTargets()
if len(prototypes) != len(markers_cfg):
raise RuntimeError(
f"Failed to load all the prototypes. Expected: {len(markers_cfg)}. Received: {len(prototypes)}."
)
def _process_prototype_prim(self, prim: Usd.Prim):
"""Process a prim and its descendants to make them suitable for defining prototypes.
Point instancer defines its own prototypes so if an asset is already instanced, this doesn't work.
This function checks if the prim at the specified prim path and its descendants are instanced.
If so, it makes the respective prim uninstanceable by disabling instancing on the prim.
Additionally, it makes the prim invisible to secondary rays. This is useful when we do not want
to see the marker prims on camera images.
Args:
prim_path: The prim path to check.
stage: The stage where the prim exists.
Defaults to None, in which case the current stage is used.
"""
# check if prim is valid
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim.GetPrimAtPath()}' is not valid.")
# iterate over all prims under prim-path
all_prims = [prim]
while len(all_prims) > 0:
# get current prim
child_prim = all_prims.pop(0)
# check if it is physics body -> if so, remove it
if child_prim.HasAPI(UsdPhysics.ArticulationRootAPI):
child_prim.RemoveAPI(UsdPhysics.ArticulationRootAPI)
child_prim.RemoveAPI(PhysxSchema.PhysxArticulationAPI)
if child_prim.HasAPI(UsdPhysics.RigidBodyAPI):
child_prim.RemoveAPI(UsdPhysics.RigidBodyAPI)
child_prim.RemoveAPI(PhysxSchema.PhysxRigidBodyAPI)
if child_prim.IsA(UsdPhysics.Joint):
child_prim.GetAttribute("physics:jointEnabled").Set(False)
# check if prim is instanced -> if so, make it uninstanceable
if child_prim.IsInstance():
child_prim.SetInstanceable(False)
# check if prim is a mesh -> if so, make it invisible to secondary rays
if child_prim.IsA(UsdGeom.Gprim):
# invisible to secondary rays such as depth images
omni.kit.commands.execute(
"ChangePropertyCommand",
prop_path=Sdf.Path(f"{child_prim.GetPrimPath().pathString}.primvars:invisibleToSecondaryRays"),
value=True,
prev=None,
type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool,
)
# add children to list
all_prims += child_prim.GetChildren()
| 20,441 | Python | 48.858536 | 120 | 0.647082 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/markers/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package for marker utilities to simplify creation of UI elements in the GUI.
Currently, the sub-package provides the following classes:
* :class:`VisualizationMarkers` for creating a group of markers using `UsdGeom.PointInstancer
<https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html>`_.
.. note::
For some simple use-cases, it may be sufficient to use the debug drawing utilities from Isaac Sim.
The debug drawing API is available in the `omni.isaac.debug_drawing`_ module. It allows drawing of
points and splines efficiently on the UI.
.. _omni.isaac.debug_drawing: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_debug_drawing.html
"""
from .config import * # noqa: F401, F403
from .visualization_markers import VisualizationMarkers, VisualizationMarkersCfg
| 967 | Python | 36.230768 | 127 | 0.762151 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/markers/config/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.markers.visualization_markers import VisualizationMarkersCfg
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
##
# Sensors.
##
RAY_CASTER_MARKER_CFG = VisualizationMarkersCfg(
markers={
"hit": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
},
)
"""Configuration for the ray-caster marker."""
CONTACT_SENSOR_MARKER_CFG = VisualizationMarkersCfg(
markers={
"contact": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"no_contact": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
visible=False,
),
},
)
"""Configuration for the contact sensor marker."""
##
# Frames.
##
FRAME_MARKER_CFG = VisualizationMarkersCfg(
markers={
"frame": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/frame_prim.usd",
scale=(0.5, 0.5, 0.5),
)
}
)
"""Configuration for the frame marker."""
RED_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
)
}
)
"""Configuration for the red arrow marker (along x-direction)."""
BLUE_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)),
)
}
)
"""Configuration for the blue arrow marker (along x-direction)."""
GREEN_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
)
}
)
"""Configuration for the green arrow marker (along x-direction)."""
##
# Goals.
##
CUBOID_MARKER_CFG = VisualizationMarkersCfg(
markers={
"cuboid": sim_utils.CuboidCfg(
size=(0.1, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
}
)
"""Configuration for the cuboid marker."""
POSITION_GOAL_MARKER_CFG = VisualizationMarkersCfg(
markers={
"target_far": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"target_near": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
),
"target_invisible": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)),
visible=False,
),
}
)
"""Configuration for the end-effector tracking marker."""
| 3,511 | Python | 27.552845 | 87 | 0.609513 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/docs/CHANGELOG.rst | Changelog
---------
0.16.5 (2024-05-22)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed :class:`omni.isaac.orbit.sensor.ContactSensor` not loading correctly in extension mode.
Earlier, the :attr:`omni.isaac.orbit.sensor.ContactSensor.body_physx_view` was not initialized when
:meth:`omni.isaac.orbit.sensor.ContactSensor._debug_vis_callback` is called which references it.
0.16.4 (2024-05-15)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed compound classes being directly assigned in ``default_factory`` generator method
:meth:`omni.isaac.orbit.utils.configclass._return_f`, which resulted in shared references such that modifications to
compound objects were reflected across all instances generated from the same ``default_factory`` method.
0.16.3 (2024-05-13)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added ``variants`` attribute to the :class:`omni.isaac.orbit.sim.from_files.UsdFileCfg` class to select USD
variants when loading assets from USD files.
0.16.2 (2024-04-26)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed parsing of filter prim path expressions in the :class:`omni.isaac.orbit.sensors.ContactSensor` class.
Earlier, the filter prim paths given to the physics view was not being parsed since they were specified as
regex expressions instead of glob expressions.
0.16.1 (2024-04-20)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added attribute :attr:`omni.isaac.orbit.sim.ArticulationRootPropertiesCfg.fix_root_link` to fix the root link
of an articulation to the world frame.
0.16.0 (2024-04-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the function :meth:`omni.isaac.orbit.utils.math.quat_unique` to standardize quaternion representations,
i.e. always have a non-negative real part.
* Added events terms for randomizing mass by scale, simulation joint properties (stiffness, damping, armature,
and friction)
Fixed
^^^^^
* Added clamping of joint positions and velocities in event terms for resetting joints. The simulation does not
throw an error if the set values are out of their range. Hence, users are expected to clamp them before setting.
* Fixed :class:`omni.isaac.orbit.envs.mdp.EMAJointPositionToLimitsActionCfg` to smoothen the actions
at environment frequency instead of simulation frequency.
* Renamed the following functions in :meth:`omni.isaac.orbit.envs.mdp` to avoid confusions:
* Observation: :meth:`joint_pos_norm` -> :meth:`joint_pos_limit_normalized`
* Action: :class:`ExponentialMovingAverageJointPositionAction` -> :class:`EMAJointPositionToLimitsAction`
* Termination: :meth:`base_height` -> :meth:`root_height_below_minimum`
* Termination: :meth:`joint_pos_limit` -> :meth:`joint_pos_out_of_limit`
* Termination: :meth:`joint_pos_manual_limit` -> :meth:`joint_pos_out_of_manual_limit`
* Termination: :meth:`joint_vel_limit` -> :meth:`joint_vel_out_of_limit`
* Termination: :meth:`joint_vel_manual_limit` -> :meth:`joint_vel_out_of_manual_limit`
* Termination: :meth:`joint_torque_limit` -> :meth:`joint_effort_out_of_limit`
Deprecated
^^^^^^^^^^
* Deprecated the function :meth:`omni.isaac.orbit.envs.mdp.add_body_mass` in favor of
:meth:`omni.isaac.orbit.envs.mdp.randomize_rigid_body_mass`. This supports randomizing the mass based on different
operations (add, scale, or set) and sampling distributions.
0.15.12 (2024-04-16)
~~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Replaced calls to the ``check_file_path`` function in the :mod:`omni.isaac.orbit.sim.spawners.from_files`
with the USD stage resolve identifier function. This helps speed up the loading of assets from file paths
by avoiding Nucleus server calls.
0.15.11 (2024-04-15)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :meth:`omni.isaac.orbit.sim.SimulationContext.has_rtx_sensors` method to check if any
RTX-related sensors such as cameras have been created in the simulation. This is useful to determine
if simulation requires RTX rendering during step or not.
Fixed
^^^^^
* Fixed the rendering of RTX-related sensors such as cameras inside the :class:`omni.isaac.orbit.envs.RLTaskEnv` class.
Earlier the rendering did not happen inside the step function, which caused the sensor data to be empty.
0.15.10 (2024-04-11)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed sharing of the same memory address between returned tensors from observation terms
in the :class:`omni.isaac.orbit.managers.ObservationManager` class. Earlier, the returned
tensors could map to the same memory address, causing issues when the tensors were modified
during scaling, clipping or other operations.
0.15.9 (2024-04-04)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed assignment of individual termination terms inside the :class:`omni.isaac.orbit.managers.TerminationManager`
class. Earlier, the terms were being assigned their values through an OR operation which resulted in incorrect
values. This regression was introduced in version 0.15.1.
0.15.8 (2024-04-02)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added option to define ordering of points for the mesh-grid generation in the
:func:`omni.isaac.orbit.sensors.ray_caster.patterns.grid_pattern`. This parameter defaults to 'xy'
for backward compatibility.
0.15.7 (2024-03-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds option to return indices/data in the specified query keys order in
:class:`omni.isaac.orbit.managers.SceneEntityCfg` class, and the respective
:func:`omni.isaac.orbit.utils.string.resolve_matching_names_values` and
:func:`omni.isaac.orbit.utils.string.resolve_matching_names` functions.
0.15.6 (2024-03-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Extended the :class:`omni.isaac.orbit.app.AppLauncher` class to support the loading of experience files
from the command line. This allows users to load a specific experience file when running the application
(such as for multi-camera rendering or headless mode).
Changed
^^^^^^^
* Changed default loading of experience files in the :class:`omni.isaac.orbit.app.AppLauncher` class from the ones
provided by Isaac Sim to the ones provided in Orbit's ``source/apps`` directory.
0.15.5 (2024-03-23)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the env origins in :meth:`_compute_env_origins_grid` of :class:`omni.isaac.orbit.terrain.TerrainImporter`
to match that obtained from the Isaac Sim :class:`omni.isaac.cloner.GridCloner` class.
Added
^^^^^
* Added unit test to ensure consistency between environment origins generated by IsaacSim's Grid Cloner and those
produced by the TerrainImporter.
0.15.4 (2024-03-22)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.envs.mdp.actions.NonHolonomicActionCfg` class to use
the correct variable when applying actions.
0.15.3 (2024-03-21)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added unit test to check that :class:`omni.isaac.orbit.scene.InteractiveScene` entity data is not shared between separate instances.
Fixed
^^^^^
* Moved class variables in :class:`omni.isaac.orbit.scene.InteractiveScene` to correctly be assigned as
instance variables.
* Removed custom ``__del__`` magic method from :class:`omni.isaac.orbit.scene.InteractiveScene`.
0.15.2 (2024-03-21)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added resolving of relative paths for the main asset USD file when using the
:class:`omni.isaac.orbit.sim.converters.UrdfConverter` class. This is to ensure that the material paths are
resolved correctly when the main asset file is moved to a different location.
0.15.1 (2024-03-19)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the imitation learning workflow example script, updating Orbit and Robomimic API calls.
* Removed the resetting of :attr:`_term_dones` in the :meth:`omni.isaac.orbit.managers.TerminationManager.reset`.
Previously, the environment cleared out all the terms. However, it impaired reading the specific term's values externally.
0.15.0 (2024-03-17)
~~~~~~~~~~~~~~~~~~~
Deprecated
^^^^^^^^^^
* Renamed :class:`omni.isaac.orbit.managers.RandomizationManager` to :class:`omni.isaac.orbit.managers.EventManager`
class for clarification as the manager takes care of events such as reset in addition to pure randomizations.
* Renamed :class:`omni.isaac.orbit.managers.RandomizationTermCfg` to :class:`omni.isaac.orbit.managers.EventTermCfg`
for consistency with the class name change.
0.14.1 (2024-03-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added simulation schemas for joint drive and fixed tendons. These can be configured for assets imported
from file formats.
* Added logging of tendon properties to the articulation class (if they are present in the USD prim).
0.14.0 (2024-03-15)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the ordering of body names used in the :class:`omni.isaac.orbit.assets.Articulation` class. Earlier,
the body names were not following the same ordering as the bodies in the articulation. This led
to issues when using the body names to access data related to the links from the articulation view
(such as Jacobians, mass matrices, etc.).
Removed
^^^^^^^
* Removed the attribute :attr:`body_physx_view` from the :class:`omni.isaac.orbit.assets.RigidObject`
and :class:`omni.isaac.orbit.assets.Articulation` classes. These were causing confusions when used
with articulation view since the body names were not following the same ordering.
0.13.1 (2024-03-14)
~~~~~~~~~~~~~~~~~~~
Removed
^^^^^^^
* Removed the :mod:`omni.isaac.orbit.compat` module. This module was used to provide compatibility
with older versions of Isaac Sim. It is no longer needed since we have most of the functionality
absorbed into the main classes.
0.13.0 (2024-03-12)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for the following data types inside the :class:`omni.isaac.orbit.sensors.Camera` class:
``instance_segmentation_fast`` and ``instance_id_segmentation_fast``. These are GPU-supported annotations
and are faster than the regular annotations.
Fixed
^^^^^
* Fixed handling of semantic filtering inside the :class:`omni.isaac.orbit.sensors.Camera` class. Earlier,
the annotator was given ``semanticTypes`` as an argument. However, with Isaac Sim 2023.1, the annotator
does not accept this argument. Instead the mapping needs to be set to the synthetic data interface directly.
* Fixed the return shape of colored images for segmentation data types inside the
:class:`omni.isaac.orbit.sensors.Camera` class. Earlier, the images were always returned as ``int32``. Now,
they are casted to ``uint8`` 4-channel array before returning if colorization is enabled for the annotation type.
Removed
^^^^^^^
* Dropped support for ``instance_segmentation`` and ``instance_id_segmentation`` annotations in the
:class:`omni.isaac.orbit.sensors.Camera` class. Their "fast" counterparts should be used instead.
* Renamed the argument :attr:`omni.isaac.orbit.sensors.CameraCfg.semantic_types` to
:attr:`omni.isaac.orbit.sensors.CameraCfg.semantic_filter`. This is more aligned with Replicator's terminology
for semantic filter predicates.
* Replaced the argument :attr:`omni.isaac.orbit.sensors.CameraCfg.colorize` with separate colorized
arguments for each annotation type (:attr:`~omni.isaac.orbit.sensors.CameraCfg.colorize_instance_segmentation`,
:attr:`~omni.isaac.orbit.sensors.CameraCfg.colorize_instance_id_segmentation`, and
:attr:`~omni.isaac.orbit.sensors.CameraCfg.colorize_semantic_segmentation`).
0.12.4 (2024-03-11)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Adapted randomization terms to deal with ``slice`` for the body indices. Earlier, the terms were not
able to handle the slice object and were throwing an error.
* Added ``slice`` type-hinting to all body and joint related methods in the rigid body and articulation
classes. This is to make it clear that the methods can handle both list of indices and slices.
0.12.3 (2024-03-11)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added signal handler to the :class:`omni.isaac.orbit.app.AppLauncher` class to catch the ``SIGINT`` signal
and close the application gracefully. This is to prevent the application from crashing when the user
presses ``Ctrl+C`` to close the application.
0.12.2 (2024-03-10)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added observation terms for states of a rigid object in world frame.
* Added randomization terms to set root state with randomized orientation and joint state within user-specified limits.
* Added reward term for penalizing specific termination terms.
Fixed
^^^^^
* Improved sampling of states inside randomization terms. Earlier, the code did multiple torch calls
for sampling different components of the vector. Now, it uses a single call to sample the entire vector.
0.12.1 (2024-03-09)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added an option to the last actions observation term to get a specific term by name from the action manager.
If None, the behavior remains the same as before (the entire action is returned).
0.12.0 (2024-03-08)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added functionality to sample flat patches on a generated terrain. This can be configured using
:attr:`omni.isaac.orbit.terrains.SubTerrainBaseCfg.flat_patch_sampling` attribute.
* Added a randomization function for setting terrain-aware root state. Through this, an asset can be
reset to a randomly sampled flat patches.
Fixed
^^^^^
* Separated normal and terrain-base position commands. The terrain based commands rely on the
terrain to sample flat patches for setting the target position.
* Fixed command resample termination function.
Changed
^^^^^^^
* Added the attribute :attr:`omni.isaac.orbit.envs.mdp.commands.UniformVelocityCommandCfg.heading_control_stiffness`
to control the stiffness of the heading control term in the velocity command term. Earlier, this was
hard-coded to 0.5 inside the term.
Removed
^^^^^^^
* Removed the function :meth:`sample_new_targets` in the terrain importer. Instead the attribute
:attr:`omni.isaac.orbit.terrains.TerrainImporter.flat_patches` should be used to sample new targets.
0.11.3 (2024-03-04)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Corrects the functions :func:`omni.isaac.orbit.utils.math.axis_angle_from_quat` and :func:`omni.isaac.orbit.utils.math.quat_error_magnitude`
to accept tensors of the form (..., 4) instead of (N, 4). This brings us in line with our documentation and also upgrades one of our functions
to handle higher dimensions.
0.11.2 (2024-03-04)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added checks for default joint position and joint velocity in the articulation class. This is to prevent
users from configuring values for these quantities that might be outside the valid range from the simulation.
0.11.1 (2024-02-29)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Replaced the default values for ``joint_ids`` and ``body_ids`` from ``None`` to ``slice(None)``
in the :class:`omni.isaac.orbit.managers.SceneEntityCfg`.
* Adapted rewards and observations terms so that the users can query a subset of joints and bodies.
0.11.0 (2024-02-27)
~~~~~~~~~~~~~~~~~~~
Removed
^^^^^^^
* Dropped support for Isaac Sim<=2022.2. As part of this, removed the components of :class:`omni.isaac.orbit.app.AppLauncher`
which handled ROS extension loading. We no longer need them in Isaac Sim>=2023.1 to control the load order to avoid crashes.
* Upgraded Dockerfile to use ISAACSIM_VERSION=2023.1.1 by default.
0.10.28 (2024-02-29)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Implemented relative and moving average joint position action terms. These allow the user to specify
the target joint positions as relative to the current joint positions or as a moving average of the
joint positions over a window of time.
0.10.27 (2024-02-28)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added UI feature to start and stop animation recording in the stage when running an environment.
To enable this feature, please pass the argument ``--disable_fabric`` to the environment script to allow
USD read/write operations. Be aware that this will slow down the simulation.
0.10.26 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a viewport camera controller class to the :class:`omni.isaac.orbit.envs.BaseEnv`. This is useful
for applications where the user wants to render the viewport from different perspectives even when the
simulation is running in headless mode.
0.10.25 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Ensures that all path arguments in :mod:`omni.isaac.orbit.sim.utils` are cast to ``str``. Previously,
we had handled path types as strings without casting.
0.10.24 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added tracking of contact time in the :class:`omni.isaac.orbit.sensors.ContactSensor` class. Previously,
only the air time was being tracked.
* Added contact force threshold, :attr:`omni.isaac.orbit.sensors.ContactSensorCfg.force_threshold`, to detect
when the contact sensor is in contact. Previously, this was set to hard-coded 1.0 in the sensor class.
0.10.23 (2024-02-21)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixes the order of size arguments in :meth:`omni.isaac.orbit.terrains.height_field.random_uniform_terrain`. Previously, the function would crash if the size along x and y were not the same.
0.10.22 (2024-02-14)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed "divide by zero" bug in :class:`~omni.isaac.orbit.sim.SimulationContext` when setting gravity vector.
Now, it is correctly disabled when the gravity vector is set to zero.
0.10.21 (2024-02-12)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the printing of articulation joint information when the articulation has only one joint.
Earlier, the function was performing a squeeze operation on the tensor, which caused an error when
trying to index the tensor of shape (1,).
0.10.20 (2024-02-12)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds :attr:`omni.isaac.orbit.sim.PhysxCfg.enable_enhanced_determinism` to enable improved
determinism from PhysX. Please note this comes at the expense of performance.
0.10.19 (2024-02-08)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed environment closing so that articulations, objects, and sensors are cleared properly.
0.10.18 (2024-02-05)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Pinned :mod:`torch` version to 2.0.1 in the setup.py to keep parity version of :mod:`torch` supplied by
Isaac 2023.1.1, and prevent version incompatibility between :mod:`torch` ==2.2 and
:mod:`typing-extensions` ==3.7.4.3
0.10.17 (2024-02-02)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^^
* Fixed carb setting ``/app/livestream/enabled`` to be set as False unless live-streaming is specified
by :class:`omni.isaac.orbit.app.AppLauncher` settings. This fixes the logic of :meth:`SimulationContext.render`,
which depended on the config in previous versions of Isaac defaulting to false for this setting.
0.10.16 (2024-01-29)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^^
* Added an offset parameter to the height scan observation term. This allows the user to specify the
height offset of the scan from the tracked body. Previously it was hard-coded to be 0.5.
0.10.15 (2024-01-29)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed joint torque computation for implicit actuators. Earlier, the torque was always zero for implicit
actuators. Now, it is computed approximately by applying the PD law.
0.10.14 (2024-01-22)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the tensor shape of :attr:`omni.isaac.orbit.sensors.ContactSensorData.force_matrix_w`. Earlier, the reshaping
led to a mismatch with the data obtained from PhysX.
0.10.13 (2024-01-15)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed running of environments with a single instance even if the :attr:`replicate_physics`` flag is set to True.
0.10.12 (2024-01-10)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed indexing of source and target frames in the :class:`omni.isaac.orbit.sensors.FrameTransformer` class.
Earlier, it always assumed that the source frame body is at index 0. Now, it uses the body index of the
source frame to compute the transformation.
Deprecated
^^^^^^^^^^
* Renamed quantities in the :class:`omni.isaac.orbit.sensors.FrameTransformerData` class to be more
consistent with the terminology used in the asset classes. The following quantities are deprecated:
* ``target_rot_w`` -> ``target_quat_w``
* ``source_rot_w`` -> ``source_quat_w``
* ``target_rot_source`` -> ``target_quat_source``
0.10.11 (2024-01-08)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed attribute error raised when calling the :class:`omni.isaac.orbit.envs.mdp.TerrainBasedPositionCommand`
command term.
* Added a dummy function in :class:`omni.isaac.orbit.terrain.TerrainImporter` that returns environment
origins as terrain-aware sampled targets. This function should be implemented by child classes based on
the terrain type.
0.10.10 (2023-12-21)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed reliance on non-existent ``Viewport`` in :class:`omni.isaac.orbit.sim.SimulationContext` when loading livestreaming
by ensuring that the extension ``omni.kit.viewport.window`` is enabled in :class:`omni.isaac.orbit.app.AppLauncher` when
livestreaming is enabled
0.10.9 (2023-12-21)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed invalidation of physics views inside the asset and sensor classes. Earlier, they were left initialized
even when the simulation was stopped. This caused issues when closing the application.
0.10.8 (2023-12-20)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.envs.mdp.actions.DifferentialInverseKinematicsAction` class
to account for the offset pose of the end-effector.
0.10.7 (2023-12-19)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a check to ray-cast and camera sensor classes to ensure that the sensor prim path does not
have a regex expression at its leaf. For instance, ``/World/Robot/camera_.*`` is not supported
for these sensor types. This behavior needs to be fixed in the future.
0.10.6 (2023-12-19)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for using articulations as visualization markers. This disables all physics APIs from
the articulation and allows the user to use it as a visualization marker. It is useful for creating
visualization markers for the end-effectors or base of the robot.
Fixed
^^^^^
* Fixed hiding of debug markers from secondary images when using the
:class:`omni.isaac.orbit.markers.VisualizationMarkers` class. Earlier, the properties were applied on
the XForm prim instead of the Mesh prim.
0.10.5 (2023-12-18)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed test ``check_base_env_anymal_locomotion.py``, which
previously called :func:`torch.jit.load` with the path to a policy (which would work
for a local file), rather than calling
:func:`omni.isaac.orbit.utils.assets.read_file` on the path to get the file itself.
0.10.4 (2023-12-14)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed potentially breaking import of omni.kit.widget.toolbar by ensuring that
if live-stream is enabled, then the :mod:`omni.kit.widget.toolbar`
extension is loaded.
0.10.3 (2023-12-12)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the attribute :attr:`omni.isaac.orbit.actuators.ActuatorNetMLPCfg.input_order`
to specify the order of the input tensors to the MLP network.
Fixed
^^^^^
* Fixed computation of metrics for the velocity command term. Earlier, the norm was being computed
over the entire batch instead of the last dimension.
* Fixed the clipping inside the :class:`omni.isaac.orbit.actuators.DCMotor` class. Earlier, it was
not able to handle the case when configured saturation limit was set to None.
0.10.2 (2023-12-12)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a check in the simulation stop callback in the :class:`omni.isaac.orbit.sim.SimulationContext` class
to not render when an exception is raised. The while loop in the callback was preventing the application
from closing when an exception was raised.
0.10.1 (2023-12-06)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added command manager class with terms defined by :class:`omni.isaac.orbit.managers.CommandTerm`. This
allow for multiple types of command generators to be used in the same environment.
0.10.0 (2023-12-04)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Modified the sensor and asset base classes to use the underlying PhysX views instead of Isaac Sim views.
Using Isaac Sim classes led to a very high load time (of the order of minutes) when using a scene with
many assets. This is because Isaac Sim supports USD paths which are slow and not required.
Added
^^^^^
* Added faster implementation of USD stage traversal methods inside the :class:`omni.isaac.orbit.sim.utils` module.
* Added properties :attr:`omni.isaac.orbit.assets.AssetBase.num_instances` and
:attr:`omni.isaac.orbit.sensor.SensorBase.num_instances` to obtain the number of instances of the asset
or sensor in the simulation respectively.
Removed
^^^^^^^
* Removed dependencies on Isaac Sim view classes. It is no longer possible to use :attr:`root_view` and
:attr:`body_view`. Instead use :attr:`root_physx_view` and :attr:`body_physx_view` to access the underlying
PhysX views.
0.9.55 (2023-12-03)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the Nucleus directory path in the :attr:`omni.isaac.orbit.utils.assets.NVIDIA_NUCLEUS_DIR`.
Earlier, it was referring to the ``NVIDIA/Assets`` directory instead of ``NVIDIA``.
0.9.54 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed pose computation in the :class:`omni.isaac.orbit.sensors.Camera` class to obtain them from XFormPrimView
instead of using ``UsdGeomCamera.ComputeLocalToWorldTransform`` method. The latter is not updated correctly
during GPU simulation.
* Fixed initialization of the annotator info in the class :class:`omni.isaac.orbit.sensors.Camera`. Previously
all dicts had the same memory address which caused all annotators to have the same info.
* Fixed the conversion of ``uint32`` warp arrays inside the :meth:`omni.isaac.orbit.utils.array.convert_to_torch`
method. PyTorch does not support this type, so it is converted to ``int32`` before converting to PyTorch tensor.
* Added render call inside :meth:`omni.isaac.orbit.sim.SimulationContext.reset` to initialize Replicator
buffers when the simulation is reset.
0.9.53 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of passing :obj:`None` to the :class:`omni.isaac.orbit.actuators.ActuatorBaseCfg`
class. Earlier, they were resolved to fixed default values. Now, they imply that the values are loaded
from the USD joint drive configuration.
Added
^^^^^
* Added setting of joint armature and friction quantities to the articulation class.
0.9.52 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the warning print in :meth:`omni.isaac.orbit.sim.utils.apply_nested` method
to be more descriptive. Earlier, it was printing a warning for every instanced prim.
Now, it only prints a warning if it could not apply the attribute to any of the prims.
Added
^^^^^
* Added the method :meth:`omni.isaac.orbit.utils.assets.retrieve_file_path` to
obtain the absolute path of a file on the Nucleus server or locally.
Fixed
^^^^^
* Fixed hiding of STOP button in the :class:`AppLauncher` class when running the
simulation in headless mode.
* Fixed a bug with :meth:`omni.isaac.orbit.sim.utils.clone` failing when the input prim path
had no parent (example: "/Table").
0.9.51 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the :meth:`omni.isaac.orbit.sensor.SensorBase.update` method to always recompute the buffers if
the sensor is in visualization mode.
Added
^^^^^
* Added available entities to the error message when accessing a non-existent entity in the
:class:`InteractiveScene` class.
* Added a warning message when the user tries to reference an invalid prim in the :class:`FrameTransformer` sensor.
0.9.50 (2023-11-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Hid the ``STOP`` button in the UI when running standalone Python scripts. This is to prevent
users from accidentally clicking the button and stopping the simulation. They should only be able to
play and pause the simulation from the UI.
Removed
^^^^^^^
* Removed :attr:`omni.isaac.orbit.sim.SimulationCfg.shutdown_app_on_stop`. The simulation is always rendering
if it is stopped from the UI. The user needs to close the window or press ``Ctrl+C`` to close the simulation.
0.9.49 (2023-11-27)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added an interface class, :class:`omni.isaac.orbit.managers.ManagerTermBase`, to serve as the parent class
for term implementations that are functional classes.
* Adapted all managers to support terms that are classes and not just functions clearer. This allows the user to
create more complex terms that require additional state information.
0.9.48 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed initialization of drift in the :class:`omni.isaac.orbit.sensors.RayCasterCamera` class.
0.9.47 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Automated identification of the root prim in the :class:`omni.isaac.orbit.assets.RigidObject` and
:class:`omni.isaac.orbit.assets.Articulation` classes. Earlier, the root prim was hard-coded to
the spawn prim path. Now, the class searches for the root prim under the spawn prim path.
0.9.46 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed a critical issue in the asset classes with writing states into physics handles.
Earlier, the states were written over all the indices instead of the indices of the
asset that were being updated. This caused the physics handles to refresh the states
of all the assets in the scene, which is not desirable.
0.9.45 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :class:`omni.isaac.orbit.command_generators.UniformPoseCommandGenerator` to generate
poses in the asset's root frame by uniformly sampling from a given range.
0.9.44 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added methods :meth:`reset` and :meth:`step` to the :class:`omni.isaac.orbit.envs.BaseEnv`. This unifies
the environment interface for simple standalone applications with the class.
0.9.43 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Replaced subscription of physics play and stop events in the :class:`omni.isaac.orbit.assets.AssetBase` and
:class:`omni.isaac.orbit.sensors.SensorBase` classes with subscription to time-line play and stop events.
This is to prevent issues in cases where physics first needs to perform mesh cooking and handles are not
available immediately. For instance, with deformable meshes.
0.9.42 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed setting of damping values from the configuration for :class:`ActuatorBase` class. Earlier,
the stiffness values were being set into damping when a dictionary configuration was passed to the
actuator model.
* Added dealing with :class:`int` and :class:`float` values in the configurations of :class:`ActuatorBase`.
Earlier, a type-error was thrown when integer values were passed to the actuator model.
0.9.41 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the naming and shaping issues in the binary joint action term.
0.9.40 (2023-11-09)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Simplified the manual initialization of Isaac Sim :class:`ArticulationView` class. Earlier, we basically
copied the code from the Isaac Sim source code. Now, we just call their initialize method.
Changed
^^^^^^^
* Changed the name of attribute :attr:`default_root_state_w` to :attr:`default_root_state`. The latter is
more correct since the data is actually in the local environment frame and not the simulation world frame.
0.9.39 (2023-11-08)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed the reference of private ``_body_view`` variable inside the :class:`RigidObject` class
to the public ``body_view`` property. For a rigid object, the private variable is not defined.
0.9.38 (2023-11-07)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Upgraded the :class:`omni.isaac.orbit.envs.RLTaskEnv` class to support Gym 0.29.0 environment definition.
Added
^^^^^
* Added computation of ``time_outs`` and ``terminated`` signals inside the termination manager. These follow the
definition mentioned in `Gym 0.29.0 <https://gymnasium.farama.org/tutorials/gymnasium_basics/handling_time_limits/>`_.
* Added proper handling of observation and action spaces in the :class:`omni.isaac.orbit.envs.RLTaskEnv` class.
These now follow closely to how Gym VecEnv handles the spaces.
0.9.37 (2023-11-06)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed broken visualization in :mod:`omni.isaac.orbit.sensors.FrameTramsformer` class by overwriting the
correct ``_debug_vis_callback`` function.
* Moved the visualization marker configurations of sensors to their respective sensor configuration classes.
This allows users to set these configurations from the configuration object itself.
0.9.36 (2023-11-03)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added explicit deleting of different managers in the :class:`omni.isaac.orbit.envs.BaseEnv` and
:class:`omni.isaac.orbit.envs.RLTaskEnv` classes. This is required since deleting the managers
is order-sensitive (many managers need to be deleted before the scene is deleted).
0.9.35 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the error: ``'str' object has no attribute '__module__'`` introduced by adding the future import inside the
:mod:`omni.isaac.orbit.utils.warp.kernels` module. Warp language does not support the ``__future__`` imports.
0.9.34 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added missing import of ``from __future__ import annotations`` in the :mod:`omni.isaac.orbit.utils.warp`
module. This is needed to have a consistent behavior across Python versions.
0.9.33 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.command_generators.NullCommandGenerator` class. Earlier,
it was having a runtime error due to infinity in the resampling time range. Now, the class just
overrides the parent methods to perform no operations.
0.9.32 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Renamed the :class:`omni.isaac.orbit.envs.RLEnv` class to :class:`omni.isaac.orbit.envs.RLTaskEnv` to
avoid confusions in terminologies between environments and tasks.
0.9.31 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.orbit.sensors.RayCasterCamera` class, as a ray-casting based camera for
"distance_to_camera", "distance_to_image_plane" and "normals" annotations. It has the same interface and
functionalities as the USD Camera while it is on average 30% faster.
0.9.30 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added skipping of None values in the :class:`InteractiveScene` class when creating the scene from configuration
objects. Earlier, it was throwing an error when the user passed a None value for a scene element.
* Added ``kwargs`` to the :class:`RLEnv` class to allow passing additional arguments from gym registry function.
This is now needed since the registry function passes args beyond the ones specified in the constructor.
0.9.29 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the material path resolution inside the :class:`omni.isaac.orbit.sim.converters.UrdfConverter` class.
With Isaac Sim 2023.1, the material paths from the importer are always saved as absolute paths. This caused
issues when the generated USD file was moved to a different location. The fix now resolves the material paths
relative to the USD file location.
0.9.28 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the way the :func:`omni.isaac.orbit.sim.spawners.from_files.spawn_ground_plane` function sets the
height of the ground. Earlier, it was reading the height from the configuration object. Now, it expects the
desired transformation as inputs to the function. This makes it consistent with the other spawner functions.
0.9.27 (2023-10-31)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Removed the default value of the argument ``camel_case`` in setters of USD attributes. This is to avoid
confusion with the naming of the attributes in the USD file.
Fixed
^^^^^
* Fixed the selection of material prim in the :class:`omni.isaac.orbit.sim.spawners.materials.spawn_preview_surface`
method. Earlier, the created prim was being selected in the viewport which interfered with the selection of
prims by the user.
* Updated :class:`omni.isaac.orbit.sim.converters.MeshConverter` to use a different stage than the default stage
for the conversion. This is to avoid the issue of the stage being closed when the conversion is done.
0.9.26 (2023-10-31)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the sensor implementation for :class:`omni.isaac.orbit.sensors.FrameTransformer` class. Currently,
it handles obtaining the transformation between two frames in the same articulation.
0.9.25 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :mod:`omni.isaac.orbit.envs.ui` module to put all the UI-related classes in one place. This currently
implements the :class:`omni.isaac.orbit.envs.ui.BaseEnvWindow` and :class:`omni.isaac.orbit.envs.ui.RLEnvWindow`
classes. Users can inherit from these classes to create their own UI windows.
* Added the attribute :attr:`omni.isaac.orbit.envs.BaseEnvCfg.ui_window_class_type` to specify the UI window class
to be used for the environment. This allows the user to specify their own UI window class to be used for the
environment.
0.9.24 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of setting up debug visualization for assets, sensors and command generators.
Earlier it was raising an error if debug visualization was not enabled in the configuration object.
Now it checks whether debug visualization is implemented and only sets up the callback if it is
implemented.
0.9.23 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed a typo in the :class:`AssetBase` and :class:`SensorBase` that effected the class destructor.
Earlier, a tuple was being created in the constructor instead of the actual object.
0.9.22 (2023-10-26)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a :class:`omni.isaac.orbit.command_generators.NullCommandGenerator` class for no command environments.
This is easier to work with than having checks for :obj:`None` in the command generator.
Fixed
^^^^^
* Moved the randomization manager to the :class:`omni.isaac.orbit.envs.BaseEnv` class with the default
settings to reset the scene to the defaults specified in the configurations of assets.
* Moved command generator to the :class:`omni.isaac.orbit.envs.RlEnv` class to have all task-specification
related classes in the same place.
0.9.21 (2023-10-26)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Decreased the priority of callbacks in asset and sensor base classes. This may help in preventing
crashes when warm starting the simulation.
* Fixed no rendering mode when running the environment from the GUI. Earlier the function
:meth:`SimulationContext.set_render_mode` was erroring out.
0.9.20 (2023-10-25)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed naming in :class:`omni.isaac.orbit.sim.SimulationContext.RenderMode` to use ``NO_GUI_OR_RENDERING``
and ``NO_RENDERING`` instead of ``HEADLESS`` for clarity.
* Changed :class:`omni.isaac.orbit.sim.SimulationContext` to be capable of handling livestreaming and
offscreen rendering.
* Changed :class:`omni.isaac.orbit.app.AppLauncher` envvar ``VIEWPORT_RECORD`` to the more descriptive
``OFFSCREEN_RENDER``.
0.9.19 (2023-10-25)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added Gym observation and action spaces for the :class:`omni.isaac.orbit.envs.RLEnv` class.
0.9.18 (2023-10-23)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Created :class:`omni.issac.orbit.sim.converters.asset_converter.AssetConverter` to serve as a base
class for all asset converters.
* Added :class:`omni.issac.orbit.sim.converters.mesh_converter.MeshConverter` to handle loading and conversion
of mesh files (OBJ, STL and FBX) into USD format.
* Added script ``convert_mesh.py`` to ``source/tools`` to allow users to convert a mesh to USD via command line arguments.
Changed
^^^^^^^
* Renamed the submodule :mod:`omni.isaac.orbit.sim.loaders` to :mod:`omni.isaac.orbit.sim.converters` to be more
general with the functionality of the module.
* Updated ``check_instanceable.py`` script to convert relative paths to absolute paths.
0.9.17 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added setters and getters for term configurations in the :class:`RandomizationManager`, :class:`RewardManager`
and :class:`TerminationManager` classes. This allows the user to modify the term configurations after the
manager has been created.
* Added the method :meth:`compute_group` to the :class:`omni.isaac.orbit.managers.ObservationManager` class to
compute the observations for only a given group.
* Added the curriculum term for modifying reward weights after certain environment steps.
0.9.16 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for keyword arguments for terms in the :class:`omni.isaac.orbit.managers.ManagerBase`.
Fixed
^^^^^
* Fixed resetting of buffers in the :class:`TerminationManager` class. Earlier, the values were being set
to ``0.0`` instead of ``False``.
0.9.15 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added base yaw heading and body acceleration into :class:`omni.isaac.orbit.assets.RigidObjectData` class.
These quantities are computed inside the :class:`RigidObject` class.
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.orbit.assets.RigidObject.set_external_force_and_torque` method to correctly
deal with the body indices.
* Fixed a bug in the :meth:`omni.isaac.orbit.utils.math.wrap_to_pi` method to prevent self-assignment of
the input tensor.
0.9.14 (2023-10-21)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added 2-D drift (i.e. along x and y) to the :class:`omni.isaac.orbit.sensors.RayCaster` class.
* Added flags to the :class:`omni.isaac.orbit.sensors.ContactSensorCfg` to optionally obtain the
sensor origin and air time information. Since these are not required by default, they are
disabled by default.
Fixed
^^^^^
* Fixed the handling of contact sensor history buffer in the :class:`omni.isaac.orbit.sensors.ContactSensor` class.
Earlier, the buffer was not being updated correctly.
0.9.13 (2023-10-20)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the issue with double :obj:`Ellipsis` when indexing tensors with multiple dimensions.
The fix now uses :obj:`slice(None)` instead of :obj:`Ellipsis` to index the tensors.
0.9.12 (2023-10-18)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed bugs in actuator model implementation for actuator nets. Earlier the DC motor clipping was not working.
* Fixed bug in applying actuator model in the :class:`omni.isaac.orbit.asset.Articulation` class. The new
implementation caches the outputs from explicit actuator model into the ``joint_pos_*_sim`` buffer to
avoid feedback loops in the tensor operation.
0.9.11 (2023-10-17)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the support for semantic tags into the :class:`omni.isaac.orbit.sim.spawner.SpawnerCfg` class. This allows
the user to specify the semantic tags for a prim when spawning it into the scene. It follows the same format as
Omniverse Replicator.
0.9.10 (2023-10-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added ``--livestream`` and ``--ros`` CLI args to :class:`omni.isaac.orbit.app.AppLauncher` class.
* Added a static function :meth:`omni.isaac.orbit.app.AppLauncher.add_app_launcher_args`, which
appends the arguments needed for :class:`omni.isaac.orbit.app.AppLauncher` to the argument parser.
Changed
^^^^^^^
* Within :class:`omni.isaac.orbit.app.AppLauncher`, removed ``REMOTE_DEPLOYMENT`` env-var processing
in the favor of ``HEADLESS`` and ``LIVESTREAM`` env-vars. These have clearer uses and better parity
with the CLI args.
0.9.9 (2023-10-12)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the property :attr:`omni.isaac.orbit.assets.Articulation.is_fixed_base` to the articulation class to
check if the base of the articulation is fixed or floating.
* Added the task-space action term corresponding to the differential inverse-kinematics controller.
Fixed
^^^^^
* Simplified the :class:`omni.isaac.orbit.controllers.DifferentialIKController` to assume that user provides the
correct end-effector poses and Jacobians. Earlier it was doing internal frame transformations which made the
code more complicated and error-prone.
0.9.8 (2023-09-30)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the boundedness of class objects that register callbacks into the simulator.
These include devices, :class:`AssetBase`, :class:`SensorBase` and :class:`CommandGenerator`.
The fix ensures that object gets deleted when the user deletes the object.
0.9.7 (2023-09-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Modified the :class:`omni.isaac.orbit.markers.VisualizationMarkers` to use the
:class:`omni.isaac.orbit.sim.spawner.SpawnerCfg` class instead of their
own configuration objects. This makes it consistent with the other ways to spawn assets in the scene.
Added
^^^^^
* Added the method :meth:`copy` to configclass to allow copying of configuration objects.
0.9.6 (2023-09-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed class-level configuration classes to refer to class types using ``class_type`` attribute instead
of ``cls`` or ``cls_name``.
0.9.5 (2023-09-25)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Added future import of ``annotations`` to have a consistent behavior across Python versions.
* Removed the type-hinting from docstrings to simplify maintenance of the documentation. All type-hints are
now in the code itself.
0.9.4 (2023-08-29)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :class:`omni.isaac.orbit.scene.InteractiveScene`, as the central scene unit that contains all entities
that are part of the simulation. These include the terrain, sensors, articulations, rigid objects etc.
The scene groups the common operations of these entities and allows to access them via their unique names.
* Added :mod:`omni.isaac.orbit.envs` module that contains environment definitions that encapsulate the different
general (scene, action manager, observation manager) and RL-specific (reward and termination manager) managers.
* Added :class:`omni.isaac.orbit.managers.SceneEntityCfg` to handle which scene elements are required by the
manager's terms. This allows the manager to parse useful information from the scene elements, such as the
joint and body indices, and pass them to the term.
* Added :class:`omni.isaac.orbit.sim.SimulationContext.RenderMode` to handle different rendering modes based on
what the user wants to update (viewport, cameras, or UI elements).
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.command_generators.CommandGeneratorBase` to register a debug visualization
callback similar to how sensors and robots handle visualization.
0.9.3 (2023-08-23)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Enabled the `faulthander <https://docs.python.org/3/library/faulthandler.html>`_ to catch segfaults and print
the stack trace. This is enabled by default in the :class:`omni.isaac.orbit.app.AppLauncher` class.
Fixed
^^^^^
* Re-added the :mod:`omni.isaac.orbit.utils.kit` to the ``compat`` directory and fixed all the references to it.
* Fixed the deletion of Replicator nodes for the :class:`omni.isaac.orbit.sensors.Camera` class. Earlier, the
Replicator nodes were not being deleted when the camera was deleted. However, this does not prevent the random
crashes that happen when the camera is deleted.
* Fixed the :meth:`omni.isaac.orbit.utils.math.convert_quat` to support both numpy and torch tensors.
Changed
^^^^^^^
* Renamed all the scripts inside the ``test`` directory to follow the convention:
* ``test_<module_name>.py``: Tests for the module ``<module_name>`` using unittest.
* ``check_<module_name>``: Check for the module ``<module_name>`` using python main function.
0.9.2 (2023-08-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the ability to color meshes in the :class:`omni.isaac.orbit.terrain.TerrainGenerator` class. Currently,
it only supports coloring the mesh randomly (``"random"``), based on the terrain height (``"height"``), and
no coloring (``"none"``).
Fixed
^^^^^
* Modified the :class:`omni.isaac.orbit.terrain.TerrainImporter` class to configure visual and physics materials
based on the configuration object.
0.9.1 (2023-08-18)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Introduced three different rotation conventions in the :class:`omni.isaac.orbit.sensors.Camera` class. These
conventions are:
* ``opengl``: the camera is looking down the -Z axis with the +Y axis pointing up
* ``ros``: the camera is looking down the +Z axis with the +Y axis pointing down
* ``world``: the camera is looking along the +X axis with the -Z axis pointing down
These can be used to declare the camera offset in :class:`omni.isaac.orbit.sensors.CameraCfg.OffsetCfg` class
and in :meth:`omni.isaac.orbit.sensors.Camera.set_world_pose` method. Additionally, all conventions are
saved to :class:`omni.isaac.orbit.sensors.CameraData` class for easy access.
Changed
^^^^^^^
* Adapted all the sensor classes to follow a structure similar to the :class:`omni.issac.orbit.assets.AssetBase`.
Hence, the spawning and initialization of sensors manually by the users is avoided.
* Removed the :meth:`debug_vis` function since that this functionality is handled by a render callback automatically
(based on the passed configuration for the :class:`omni.isaac.orbit.sensors.SensorBaseCfg.debug_vis` flag).
0.9.0 (2023-08-18)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Introduces a new set of asset interfaces. These interfaces simplify the spawning of assets into the scene
and initializing the physics handle by putting that inside post-startup physics callbacks. With this, users
no longer need to worry about the :meth:`spawn` and :meth:`initialize` calls.
* Added utility methods to :mod:`omni.isaac.orbit.utils.string` module that resolve regex expressions based
on passed list of target keys.
Changed
^^^^^^^
* Renamed all references of joints in an articulation from "dof" to "joint". This makes it consistent with the
terminology used in robotics.
Deprecated
^^^^^^^^^^
* Removed the previous modules for objects and robots. Instead the :class:`Articulation` and :class:`RigidObject`
should be used.
0.8.12 (2023-08-18)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added other properties provided by ``PhysicsScene`` to the :class:`omni.isaac.orbit.sim.SimulationContext`
class to allow setting CCD, solver iterations, etc.
* Added commonly used functions to the :class:`SimulationContext` class itself to avoid having additional
imports from Isaac Sim when doing simple tasks such as setting camera view or retrieving the simulation settings.
Fixed
^^^^^
* Switched the notations of default buffer values in :class:`omni.isaac.orbit.sim.PhysxCfg` from multiplication
to scientific notation to avoid confusion with the values.
0.8.11 (2023-08-18)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds utility functions and configuration objects in the :mod:`omni.isaac.orbit.sim.spawners`
to create the following prims in the scene:
* :mod:`omni.isaac.orbit.sim.spawners.from_file`: Create a prim from a USD/URDF file.
* :mod:`omni.isaac.orbit.sim.spawners.shapes`: Create USDGeom prims for shapes (box, sphere, cylinder, capsule, etc.).
* :mod:`omni.isaac.orbit.sim.spawners.materials`: Create a visual or physics material prim.
* :mod:`omni.isaac.orbit.sim.spawners.lights`: Create a USDLux prim for different types of lights.
* :mod:`omni.isaac.orbit.sim.spawners.sensors`: Create a USD prim for supported sensors.
Changed
^^^^^^^
* Modified the :class:`SimulationContext` class to take the default physics material using the material spawn
configuration object.
0.8.10 (2023-08-17)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added methods for defining different physics-based schemas in the :mod:`omni.isaac.orbit.sim.schemas` module.
These methods allow creating the schema if it doesn't exist at the specified prim path and modify
its properties based on the configuration object.
0.8.9 (2023-08-09)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Moved the :class:`omni.isaac.orbit.asset_loader.UrdfLoader` class to the :mod:`omni.isaac.orbit.sim.loaders`
module to make it more accessible to the user.
0.8.8 (2023-08-09)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added configuration classes and functions for setting different physics-based schemas in the
:mod:`omni.isaac.orbit.sim.schemas` module. These allow modifying properties of the physics solver
on the asset using configuration objects.
0.8.7 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added support for `__post_init__ <https://docs.python.org/3/library/dataclasses.html#post-init-processing>`_ in
the :class:`omni.isaac.orbit.utils.configclass` decorator.
0.8.6 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for callable classes in the :class:`omni.isaac.orbit.managers.ManagerBase`.
0.8.5 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.markers.Visualizationmarkers` class so that the markers are not visible in camera rendering mode.
Changed
^^^^^^^
* Simplified the creation of the point instancer in the :class:`omni.isaac.orbit.markers.Visualizationmarkers` class. It now creates a new
prim at the next available prim path if a prim already exists at the given path.
0.8.4 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.orbit.sim.SimulationContext` class to the :mod:`omni.isaac.orbit.sim` module.
This class inherits from the :class:`omni.isaac.core.simulation_context.SimulationContext` class and adds
the ability to create a simulation context from a configuration object.
0.8.3 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Moved the :class:`ActuatorBase` class to the :mod:`omni.isaac.orbit.actuators.actuator_base` module.
* Renamed the :mod:`omni.isaac.orbit.actuators.actuator` module to :mod:`omni.isaac.orbit.actuators.actuator_pd`
to make it more explicit that it contains the PD actuator models.
0.8.2 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Cleaned up the :class:`omni.isaac.orbit.terrain.TerrainImporter` class to take all the parameters from the configuration
object. This makes it consistent with the other classes in the package.
* Moved the configuration classes for terrain generator and terrain importer into separate files to resolve circular
dependency issues.
0.8.1 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a hack into :class:`omni.isaac.orbit.app.AppLauncher` class to remove orbit packages from the path before launching
the simulation application. This prevents the warning messages that appears when the user launches the ``SimulationApp``.
Added
^^^^^
* Enabled necessary viewport extensions in the :class:`omni.isaac.orbit.app.AppLauncher` class itself if ``VIEWPORT_ENABLED``
flag is true.
0.8.0 (2023-07-26)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`ActionManager` class to the :mod:`omni.isaac.orbit.managers` module to handle actions in the
environment through action terms.
* Added contact force history to the :class:`omni.isaac.orbit.sensors.ContactSensor` class. The history is stored
in the ``net_forces_w_history`` attribute of the sensor data.
Changed
^^^^^^^
* Implemented lazy update of buffers in the :class:`omni.isaac.orbit.sensors.SensorBase` class. This allows the user
to update the sensor data only when required, i.e. when the data is requested by the user. This helps avoid double
computation of sensor data when a reset is called in the environment.
Deprecated
^^^^^^^^^^
* Removed the support for different backends in the sensor class. We only use Pytorch as the backend now.
* Removed the concept of actuator groups. They are now handled by the :class:`omni.isaac.orbit.managers.ActionManager`
class. The actuator models are now directly handled by the robot class itself.
0.7.4 (2023-07-26)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of the :class:`omni.isaac.orbit.terrains.TerrainImporter` class. It now expects the terrain
type to be specified in the configuration object. This allows the user to specify everything in the configuration
object and not have to do an explicit call to import a terrain.
Fixed
^^^^^
* Fixed setting of quaternion orientations inside the :class:`omni.isaac.orbit.markers.Visualizationmarkers` class.
Earlier, the orientation was being set into the point instancer in the wrong order (``wxyz`` instead of ``xyzw``).
0.7.3 (2023-07-25)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the issue with multiple inheritance in the :class:`omni.isaac.orbit.utils.configclass` decorator.
Earlier, if the inheritance tree was more than one level deep and the lowest level configuration class was
not updating its values from the middle level classes.
0.7.2 (2023-07-24)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the method :meth:`replace` to the :class:`omni.isaac.orbit.utils.configclass` decorator to allow
creating a new configuration object with values replaced from keyword arguments. This function internally
calls the `dataclasses.replace <https://docs.python.org/3/library/dataclasses.html#dataclasses.replace>`_.
Fixed
^^^^^
* Fixed the handling of class types as member values in the :meth:`omni.isaac.orbit.utils.configclass`. Earlier it was
throwing an error since class types were skipped in the if-else block.
0.7.1 (2023-07-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`TerminationManager`, :class:`CurriculumManager`, and :class:`RandomizationManager` classes
to the :mod:`omni.isaac.orbit.managers` module to handle termination, curriculum, and randomization respectively.
0.7.0 (2023-07-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Created a new :mod:`omni.isaac.orbit.managers` module for all the managers related to the environment / scene.
This includes the :class:`omni.isaac.orbit.managers.ObservationManager` and :class:`omni.isaac.orbit.managers.RewardManager`
classes that were previously in the :mod:`omni.isaac.orbit.utils.mdp` module.
* Added the :class:`omni.isaac.orbit.managers.ManagerBase` class to handle the creation of managers.
* Added configuration classes for :class:`ObservationTermCfg` and :class:`RewardTermCfg` to allow easy creation of
observation and reward terms.
Changed
^^^^^^^
* Changed the behavior of :class:`ObservationManager` and :class:`RewardManager` classes to accept the key ``func``
in each configuration term to be a callable. This removes the need to inherit from the base class
and allows more reusability of the functions across different environments.
* Moved the old managers to the :mod:`omni.isaac.orbit.compat.utils.mdp` module.
* Modified the necessary scripts to use the :mod:`omni.isaac.orbit.compat.utils.mdp` module.
0.6.2 (2023-07-21)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :mod:`omni.isaac.orbit.command_generators` to generate different commands based on the desired task.
It allows the user to generate commands for different tasks in the same environment without having to write
custom code for each task.
0.6.1 (2023-07-16)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.orbit.utils.math.quat_apply_yaw` to compute the yaw quaternion correctly.
Added
^^^^^
* Added functions to convert string and callable objects in :mod:`omni.isaac.orbit.utils.string`.
0.6.0 (2023-07-16)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the argument :attr:`sort_keys` to the :meth:`omni.isaac.orbit.utils.io.yaml.dump_yaml` method to allow
enabling/disabling of sorting of keys in the output yaml file.
Fixed
^^^^^
* Fixed the ordering of terms in :mod:`omni.isaac.orbit.utils.configclass` to be consistent in the order in which
they are defined. Previously, the ordering was done alphabetically which made it inconsistent with the order in which
the parameters were defined.
Changed
^^^^^^^
* Changed the default value of the argument :attr:`sort_keys` in the :meth:`omni.isaac.orbit.utils.io.yaml.dump_yaml`
method to ``False``.
* Moved the old config classes in :mod:`omni.isaac.orbit.utils.configclass` to
:mod:`omni.isaac.orbit.compat.utils.configclass` so that users can still run their old code where alphabetical
ordering was used.
0.5.0 (2023-07-04)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a generalized :class:`omni.isaac.orbit.sensors.SensorBase` class that leverages the ideas of views to
handle multiple sensors in a single class.
* Added the classes :class:`omni.isaac.orbit.sensors.RayCaster`, :class:`omni.isaac.orbit.sensors.ContactSensor`,
and :class:`omni.isaac.orbit.sensors.Camera` that output a batched tensor of sensor data.
Changed
^^^^^^^
* Renamed the parameter ``sensor_tick`` to ``update_freq`` to make it more intuitive.
* Moved the old sensors in :mod:`omni.isaac.orbit.sensors` to :mod:`omni.isaac.orbit.compat.sensors`.
* Modified the standalone scripts to use the :mod:`omni.isaac.orbit.compat.sensors` module.
0.4.4 (2023-07-05)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.orbit.terrains.trimesh.utils.make_plane` method to handle the case when the
plane origin does not need to be centered.
* Added the :attr:`omni.isaac.orbit.terrains.TerrainGeneratorCfg.seed` to make generation of terrains reproducible.
The default value is ``None`` which means that the seed is not set.
Changed
^^^^^^^
* Changed the saving of ``origins`` in :class:`omni.isaac.orbit.terrains.TerrainGenerator` class to be in CSV format
instead of NPY format.
0.4.3 (2023-06-28)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.orbit.markers.PointInstancerMarker` class that wraps around
`UsdGeom.PointInstancer <https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html>`_
to directly work with torch and numpy arrays.
Changed
^^^^^^^
* Moved the old markers in :mod:`omni.isaac.orbit.markers` to :mod:`omni.isaac.orbit.compat.markers`.
* Modified the standalone scripts to use the :mod:`omni.isaac.orbit.compat.markers` module.
0.4.2 (2023-06-28)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the sub-module :mod:`omni.isaac.orbit.terrains` to allow procedural generation of terrains and supporting
importing of terrains from different sources (meshes, usd files or default ground plane).
0.4.1 (2023-06-27)
~~~~~~~~~~~~~~~~~~
* Added the :class:`omni.isaac.orbit.app.AppLauncher` class to allow controlled instantiation of
the `SimulationApp <https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.kit/docs/index.html>`_
and extension loading for remote deployment and ROS bridges.
Changed
^^^^^^^
* Modified all standalone scripts to use the :class:`omni.isaac.orbit.app.AppLauncher` class.
0.4.0 (2023-05-27)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a helper class :class:`omni.isaac.orbit.asset_loader.UrdfLoader` that converts a URDF file to instanceable USD
file based on the input configuration object.
0.3.2 (2023-04-27)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added safe-printing of functions while using the :meth:`omni.isaac.orbit.utils.dict.print_dict` function.
0.3.1 (2023-04-23)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a modified version of ``lula_franka_gen.urdf`` which includes an end-effector frame.
* Added a standalone script ``play_rmpflow.py`` to show RMPFlow controller.
Fixed
^^^^^
* Fixed the splitting of commands in the :meth:`ActuatorGroup.compute` method. Earlier it was reshaping the
commands to the shape ``(num_actuators, num_commands)`` which was causing the commands to be split incorrectly.
* Fixed the processing of actuator command in the :meth:`RobotBase._process_actuators_cfg` to deal with multiple
command types when using "implicit" actuator group.
0.3.0 (2023-04-20)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added the destructor to the keyboard devices to unsubscribe from carb.
Added
^^^^^
* Added the :class:`Se2Gamepad` and :class:`Se3Gamepad` for gamepad teleoperation support.
0.2.8 (2023-04-10)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed bugs in :meth:`axis_angle_from_quat` in the ``omni.isaac.orbit.utils.math`` to handle quaternion with negative w component.
* Fixed bugs in :meth:`subtract_frame_transforms` in the ``omni.isaac.orbit.utils.math`` by adding the missing final rotation.
0.2.7 (2023-04-07)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed repetition in applying mimic multiplier for "p_abs" in the :class:`GripperActuatorGroup` class.
* Fixed bugs in :meth:`reset_buffers` in the :class:`RobotBase` and :class:`LeggedRobot` classes.
0.2.6 (2023-03-16)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`CollisionPropertiesCfg` to rigid/articulated object and robot base classes.
* Added the :class:`PhysicsMaterialCfg` to the :class:`SingleArm` class for tool sites.
Changed
^^^^^^^
* Changed the default control mode of the :obj:`PANDA_HAND_MIMIC_GROUP_CFG` to be from ``"v_abs"`` to ``"p_abs"``.
Using velocity control for the mimic group can cause the hand to move in a jerky manner.
0.2.5 (2023-03-08)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the indices used for the Jacobian and dynamics quantities in the :class:`MobileManipulator` class.
0.2.4 (2023-03-04)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :meth:`apply_nested_physics_material` to the ``omni.isaac.orbit.utils.kit``.
* Added the :meth:`sample_cylinder` to sample points from a cylinder's surface.
* Added documentation about the issue in using instanceable asset as markers.
Fixed
^^^^^
* Simplified the physics material application in the rigid object and legged robot classes.
Removed
^^^^^^^
* Removed the ``geom_prim_rel_path`` argument in the :class:`RigidObjectCfg.MetaInfoCfg` class.
0.2.3 (2023-02-24)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the end-effector body index used for getting the Jacobian in the :class:`SingleArm` and :class:`MobileManipulator` classes.
0.2.2 (2023-01-27)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`set_world_pose_ros` and :meth:`set_world_pose_from_view` in the :class:`Camera` class.
Deprecated
^^^^^^^^^^
* Removed the :meth:`set_world_pose_from_ypr` method from the :class:`Camera` class.
0.2.1 (2023-01-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`Camera` class to support different fisheye projection types.
0.2.0 (2023-01-25)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for warp backend in camera utilities.
* Extended the ``play_camera.py`` with ``--gpu`` flag to use GPU replicator backend.
0.1.1 (2023-01-24)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed setting of physics material on the ground plane when using :meth:`omni.isaac.orbit.utils.kit.create_ground_plane` function.
0.1.0 (2023-01-17)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Initial release of the extension with experimental API.
* Available robot configurations:
* **Quadrupeds:** Unitree A1, ANYmal B, ANYmal C
* **Single-arm manipulators:** Franka Emika arm, UR5
* **Mobile manipulators:** Clearpath Ridgeback with Franka Emika arm or UR5
| 67,221 | reStructuredText | 30.035088 | 191 | 0.71378 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit/docs/README.md | # Orbit: Framework
Orbit includes its own set of interfaces and wrappers around Isaac Sim classes. One of the main goals behind this
decision is to have a unified description for different systems. While isaac Sim tries to be general for a wider
variety of simulation requires, our goal has been to specialize these for learning requirements. These include
features such as augmenting simulators with non-ideal actuator models, managing different observation and reward
settings, integrate different sensors, as well as provide interfaces to features that are currently not available in
Isaac Sim but are available from the physics side (such as deformable bodies).
We recommend the users to try out the demo scripts present in `standalone/demos` that display how different parts
of the framework can be integrated together.
| 827 | Markdown | 67.999994 | 116 | 0.822249 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit_assets/setup.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Installation script for the 'omni.isaac.orbit_assets' python package."""
import os
import toml
from setuptools import setup
# Obtain the extension data from the extension.toml file
EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__))
# Read the extension.toml file
EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml"))
# Installation operation
setup(
name="omni-isaac-orbit_assets",
author="ORBIT Project Developers",
maintainer="Mayank Mittal",
maintainer_email="[email protected]",
url=EXTENSION_TOML_DATA["package"]["repository"],
version=EXTENSION_TOML_DATA["package"]["version"],
description=EXTENSION_TOML_DATA["package"]["description"],
keywords=EXTENSION_TOML_DATA["package"]["keywords"],
include_package_data=True,
python_requires=">=3.10",
packages=["omni.isaac.orbit_assets"],
classifiers=[
"Natural Language :: English",
"Programming Language :: Python :: 3.10",
"Isaac Sim :: 2023.1.0-hotfix.1",
"Isaac Sim :: 2023.1.1",
],
zip_safe=False,
)
| 1,216 | Python | 30.205127 | 89 | 0.688322 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit_assets/test/test_valid_configs.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# ignore private usage of variables warning
# pyright: reportPrivateUsage=none
"""Launch Isaac Sim Simulator first."""
from omni.isaac.orbit.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import unittest
import omni.isaac.orbit_assets as orbit_assets # noqa: F401
from omni.isaac.orbit.assets import AssetBase, AssetBaseCfg
from omni.isaac.orbit.sensors import SensorBase, SensorBaseCfg
from omni.isaac.orbit.sim import build_simulation_context
class TestValidEntitiesConfigs(unittest.TestCase):
"""Test cases for all registered entities configurations."""
@classmethod
def setUpClass(cls):
# load all registered entities configurations from the module
cls.registered_entities: dict[str, AssetBaseCfg | SensorBaseCfg] = {}
# inspect all classes from the module
for obj_name in dir(orbit_assets):
obj = getattr(orbit_assets, obj_name)
# store all registered entities configurations
if isinstance(obj, (AssetBaseCfg, SensorBaseCfg)):
cls.registered_entities[obj_name] = obj
# print all existing entities names
print(">>> All registered entities:", list(cls.registered_entities.keys()))
"""
Test fixtures.
"""
def test_asset_configs(self):
"""Check all registered asset configurations."""
# iterate over all registered assets
for asset_name, entity_cfg in self.registered_entities.items():
for device in ("cuda:0", "cpu"):
with self.subTest(asset_name=asset_name, device=device):
with build_simulation_context(device=device, auto_add_lighting=True) as sim:
# print the asset name
print(">>> Testing entities:", asset_name)
# name the prim path
entity_cfg.prim_path = "/World/asset"
# create the asset / sensors
entity: AssetBase | SensorBase = entity_cfg.class_type(entity_cfg) # type: ignore
# play the sim
sim.reset()
# check asset is initialized successfully
self.assertTrue(entity._is_initialized)
if __name__ == "__main__":
run_tests()
| 2,541 | Python | 34.305555 | 106 | 0.630067 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit_assets/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "0.1.2"
# Description
title = "ORBIT Assets"
description="Extension containing configuration instances of different assets and sensors"
readme = "docs/README.md"
repository = "https://github.com/NVIDIA-Omniverse/Orbit"
category = "robotics"
keywords = ["kit", "robotics", "assets", "orbit"]
[dependencies]
"omni.isaac.orbit" = {}
# Main python module this extension provides.
[[python.module]]
name = "omni.isaac.orbit_assets"
| 503 | TOML | 25.526314 | 90 | 0.73161 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/unitree.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for Unitree robots.
The following configurations are available:
* :obj:`UNITREE_A1_CFG`: Unitree A1 robot with DC motor model for the legs
* :obj:`UNITREE_GO1_CFG`: Unitree Go1 robot with actuator net model for the legs
* :obj:`UNITREE_GO2_CFG`: Unitree Go2 robot with DC motor model for the legs
Reference: https://github.com/unitreerobotics/unitree_ros
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ActuatorNetMLPCfg, DCMotorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
##
# Configuration - Actuators.
##
GO1_ACTUATOR_CFG = ActuatorNetMLPCfg(
joint_names_expr=[".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"],
network_file=f"{ISAAC_ORBIT_NUCLEUS_DIR}/ActuatorNets/Unitree/unitree_go1.pt",
pos_scale=-1.0,
vel_scale=1.0,
torque_scale=1.0,
input_order="pos_vel",
input_idx=[0, 1, 2],
effort_limit=23.7, # taken from spec sheet
velocity_limit=30.0, # taken from spec sheet
saturation_effort=23.7, # same as effort limit
)
"""Configuration of Go1 actuators using MLP model.
Actuator specifications: https://shop.unitree.com/products/go1-motor
This model is taken from: https://github.com/Improbable-AI/walk-these-ways
"""
##
# Configuration
##
UNITREE_A1_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Unitree/A1/a1.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.42),
joint_pos={
".*L_hip_joint": 0.1,
".*R_hip_joint": -0.1,
"F[L,R]_thigh_joint": 0.8,
"R[L,R]_thigh_joint": 1.0,
".*_calf_joint": -1.5,
},
joint_vel={".*": 0.0},
),
soft_joint_pos_limit_factor=0.9,
actuators={
"base_legs": DCMotorCfg(
joint_names_expr=[".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"],
effort_limit=33.5,
saturation_effort=33.5,
velocity_limit=21.0,
stiffness=25.0,
damping=0.5,
friction=0.0,
),
},
)
"""Configuration of Unitree A1 using DC motor.
Note: Specifications taken from: https://www.trossenrobotics.com/a1-quadruped#specifications
"""
UNITREE_GO1_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Unitree/Go1/go1.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.4),
joint_pos={
".*L_hip_joint": 0.1,
".*R_hip_joint": -0.1,
"F[L,R]_thigh_joint": 0.8,
"R[L,R]_thigh_joint": 1.0,
".*_calf_joint": -1.5,
},
joint_vel={".*": 0.0},
),
soft_joint_pos_limit_factor=0.9,
actuators={
"base_legs": GO1_ACTUATOR_CFG,
},
)
"""Configuration of Unitree Go1 using MLP-based actuator model."""
UNITREE_GO2_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Unitree/Go2/go2.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.4),
joint_pos={
".*L_hip_joint": 0.1,
".*R_hip_joint": -0.1,
"F[L,R]_thigh_joint": 0.8,
"R[L,R]_thigh_joint": 1.0,
".*_calf_joint": -1.5,
},
joint_vel={".*": 0.0},
),
soft_joint_pos_limit_factor=0.9,
actuators={
"base_legs": DCMotorCfg(
joint_names_expr=[".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"],
effort_limit=23.5,
saturation_effort=23.5,
velocity_limit=30.0,
stiffness=25.0,
damping=0.5,
friction=0.0,
),
},
)
"""Configuration of Unitree Go2 using DC-Motor actuator model."""
| 5,691 | Python | 31.340909 | 111 | 0.601652 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/monaV2.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the ANYbotics robots.
The following configuration parameters are available:
* :obj:`ANYMAL_B_CFG`: The ANYmal-B robot with ANYdrives 3.0
* :obj:`ANYMAL_C_CFG`: The ANYmal-C robot with ANYdrives 3.0
* :obj:`ANYMAL_D_CFG`: The ANYmal-D robot with ANYdrives 3.0
Reference:
* https://github.com/ANYbotics/anymal_b_simple_description
* https://github.com/ANYbotics/anymal_c_simple_description
* https://github.com/ANYbotics/anymal_d_simple_description
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ActuatorNetLSTMCfg, DCMotorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
##
# Configuration - Actuators.
##
MONAV2_LEG_SIMPLE_ACTUATOR_CFG = DCMotorCfg(
joint_names_expr=["HpR","HpL",
"HrR","HrL",
"HwR","HwL",
"ApR","ApL",
"ArR","ArL",
"KpR","KpL",],
saturation_effort=120.0,
effort_limit=80.0,
velocity_limit=7.5,
stiffness={".*": 40.0},
damping={".*": 5.0},
)
MONAV2_ARM_SIMPLE_ACTUATOR_CFG = DCMotorCfg(
joint_names_expr=["SpR","SpL",
"SrR","SrL",
"SwR","SwL",
"WpR","WpL",
"WrR","WrL",
"WwR","WwL"],
saturation_effort=120.0,
effort_limit=80.0,
velocity_limit=7.5,
stiffness={".*": 40.0},
damping={".*": 5.0},
)
MONAV2_TORSO_SIMPLE_ACTUATOR_CFG = DCMotorCfg(
joint_names_expr=["FpC", "FrC", "FwC"],
saturation_effort=120.0,
effort_limit=80.0,
velocity_limit=7.5,
stiffness={".*": 40.0},
damping={".*": 5.0},
)
"""Configuration for ANYdrive 3.x with DC actuator model."""
##
# Configuration - Articulation.
##
MONAV2_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path="/home/fnuabhimanyu/WholeBodyMotion/assets/hoa_full_body1/full_body1/URDF_description/meshes/mona_v2_simple/mona_v2_simple.usd",
activate_contact_sensors=False,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=10.0,
max_angular_velocity=10.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
# collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.02, rest_offset=0.0),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.923),
joint_pos={
"SpR": -0.5,
"SpL": 0.5 # all motors
},
),
actuators={"legs": MONAV2_LEG_SIMPLE_ACTUATOR_CFG,
"arms": MONAV2_ARM_SIMPLE_ACTUATOR_CFG,
"torso": MONAV2_TORSO_SIMPLE_ACTUATOR_CFG,},
soft_joint_pos_limit_factor=0.95,
)
| 3,243 | Python | 30.192307 | 145 | 0.608696 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.