file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/rl_task_env.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import gymnasium as gym
import math
import numpy as np
import torch
from collections.abc import Sequence
from typing import Any, ClassVar
from omni.isaac.version import get_version
from omni.isaac.orbit.managers import CommandManager, CurriculumManager, RewardManager, TerminationManager
from .base_env import BaseEnv, VecEnvObs
from .rl_task_env_cfg import RLTaskEnvCfg
VecEnvStepReturn = tuple[VecEnvObs, torch.Tensor, torch.Tensor, torch.Tensor, dict]
"""The environment signals processed at the end of each step.
The tuple contains batched information for each sub-environment. The information is stored in the following order:
1. **Observations**: The observations from the environment.
2. **Rewards**: The rewards from the environment.
3. **Terminated Dones**: Whether the environment reached a terminal state, such as task success or robot falling etc.
4. **Timeout Dones**: Whether the environment reached a timeout state, such as end of max episode length.
5. **Extras**: A dictionary containing additional information from the environment.
"""
class RLTaskEnv(BaseEnv, gym.Env):
"""The superclass for reinforcement learning-based environments.
This class inherits from :class:`BaseEnv` and implements the core functionality for
reinforcement learning-based environments. It is designed to be used with any RL
library. The class is designed to be used with vectorized environments, i.e., the
environment is expected to be run in parallel with multiple sub-environments. The
number of sub-environments is specified using the ``num_envs``.
Each observation from the environment is a batch of observations for each sub-
environments. The method :meth:`step` is also expected to receive a batch of actions
for each sub-environment.
While the environment itself is implemented as a vectorized environment, we do not
inherit from :class:`gym.vector.VectorEnv`. This is mainly because the class adds
various methods (for wait and asynchronous updates) which are not required.
Additionally, each RL library typically has its own definition for a vectorized
environment. Thus, to reduce complexity, we directly use the :class:`gym.Env` over
here and leave it up to library-defined wrappers to take care of wrapping this
environment for their agents.
Note:
For vectorized environments, it is recommended to **only** call the :meth:`reset`
method once before the first call to :meth:`step`, i.e. after the environment is created.
After that, the :meth:`step` function handles the reset of terminated sub-environments.
This is because the simulator does not support resetting individual sub-environments
in a vectorized environment.
"""
is_vector_env: ClassVar[bool] = True
"""Whether the environment is a vectorized environment."""
metadata: ClassVar[dict[str, Any]] = {
"render_modes": [None, "human", "rgb_array"],
"isaac_sim_version": get_version(),
}
"""Metadata for the environment."""
cfg: RLTaskEnvCfg
"""Configuration for the environment."""
def __init__(self, cfg: RLTaskEnvCfg, render_mode: str | None = None, **kwargs):
"""Initialize the environment.
Args:
cfg: The configuration for the environment.
render_mode: The render mode for the environment. Defaults to None, which
is similar to ``"human"``.
"""
# initialize the base class to setup the scene.
super().__init__(cfg=cfg)
# store the render mode
self.render_mode = render_mode
# initialize data and constants
# -- counter for curriculum
self.common_step_counter = 0
# -- init buffers
self.episode_length_buf = torch.zeros(self.num_envs, device=self.device, dtype=torch.long)
# setup the action and observation spaces for Gym
self._configure_gym_env_spaces()
# perform events at the start of the simulation
if "startup" in self.event_manager.available_modes:
self.event_manager.apply(mode="startup")
# print the environment information
print("[INFO]: Completed setting up the environment...")
"""
Properties.
"""
@property
def max_episode_length_s(self) -> float:
"""Maximum episode length in seconds."""
return self.cfg.episode_length_s
@property
def max_episode_length(self) -> int:
"""Maximum episode length in environment steps."""
return math.ceil(self.max_episode_length_s / self.step_dt)
"""
Operations - Setup.
"""
def load_managers(self):
# note: this order is important since observation manager needs to know the command and action managers
# and the reward manager needs to know the termination manager
# -- command manager
self.command_manager: CommandManager = CommandManager(self.cfg.commands, self)
print("[INFO] Command Manager: ", self.command_manager)
# call the parent class to load the managers for observations and actions.
super().load_managers()
# prepare the managers
# -- termination manager
self.termination_manager = TerminationManager(self.cfg.terminations, self)
print("[INFO] Termination Manager: ", self.termination_manager)
# -- reward manager
self.reward_manager = RewardManager(self.cfg.rewards, self)
print("[INFO] Reward Manager: ", self.reward_manager)
# -- curriculum manager
self.curriculum_manager = CurriculumManager(self.cfg.curriculum, self)
print("[INFO] Curriculum Manager: ", self.curriculum_manager)
"""
Operations - MDP
"""
def step(self, action: torch.Tensor) -> VecEnvStepReturn:
"""Execute one time-step of the environment's dynamics and reset terminated environments.
Unlike the :class:`BaseEnv.step` class, the function performs the following operations:
1. Process the actions.
2. Perform physics stepping.
3. Perform rendering if gui is enabled.
4. Update the environment counters and compute the rewards and terminations.
5. Reset the environments that terminated.
6. Compute the observations.
7. Return the observations, rewards, resets and extras.
Args:
action: The actions to apply on the environment. Shape is (num_envs, action_dim).
Returns:
A tuple containing the observations, rewards, resets (terminated and truncated) and extras.
"""
# process actions
self.action_manager.process_action(action)
# perform physics stepping
for _ in range(self.cfg.decimation):
# set actions into buffers
self.action_manager.apply_action()
# set actions into simulator
self.scene.write_data_to_sim()
# simulate
self.sim.step(render=False)
# update buffers at sim dt
self.scene.update(dt=self.physics_dt)
# perform rendering if gui is enabled
if self.sim.has_gui():
self.sim.render()
# post-step:
# -- update env counters (used for curriculum generation)
self.episode_length_buf += 1 # step in current episode (per env)
self.common_step_counter += 1 # total step (common for all envs)
# -- check terminations
self.reset_buf = self.termination_manager.compute()
self.reset_terminated = self.termination_manager.terminated
self.reset_time_outs = self.termination_manager.time_outs
# -- reward computation
self.reward_buf = self.reward_manager.compute(dt=self.step_dt)
# -- reset envs that terminated/timed-out and log the episode information
reset_env_ids = self.reset_buf.nonzero(as_tuple=False).squeeze(-1)
if len(reset_env_ids) > 0:
self._reset_idx(reset_env_ids)
# -- update command
self.command_manager.compute(dt=self.step_dt)
# -- step interval events
if "interval" in self.event_manager.available_modes:
self.event_manager.apply(mode="interval", dt=self.step_dt)
# -- compute observations
# note: done after reset to get the correct observations for reset envs
self.obs_buf = self.observation_manager.compute()
# return observations, rewards, resets and extras
return self.obs_buf, self.reward_buf, self.reset_terminated, self.reset_time_outs, self.extras
def render(self) -> np.ndarray | None:
"""Run rendering without stepping through the physics.
By convention, if mode is:
- **human**: Render to the current display and return nothing. Usually for human consumption.
- **rgb_array**: Return an numpy.ndarray with shape (x, y, 3), representing RGB values for an
x-by-y pixel image, suitable for turning into a video.
Returns:
The rendered image as a numpy array if mode is "rgb_array". Otherwise, returns None.
Raises:
RuntimeError: If mode is set to "rgb_data" and simulation render mode does not support it.
In this case, the simulation render mode must be set to ``RenderMode.PARTIAL_RENDERING``
or ``RenderMode.FULL_RENDERING``.
NotImplementedError: If an unsupported rendering mode is specified.
"""
# run a rendering step of the simulator
self.sim.render()
# decide the rendering mode
if self.render_mode == "human" or self.render_mode is None:
return None
elif self.render_mode == "rgb_array":
# check that if any render could have happened
if self.sim.render_mode.value < self.sim.RenderMode.PARTIAL_RENDERING.value:
raise RuntimeError(
f"Cannot render '{self.render_mode}' when the simulation render mode is"
f" '{self.sim.render_mode.name}'. Please set the simulation render mode to:"
f"'{self.sim.RenderMode.PARTIAL_RENDERING.name}' or '{self.sim.RenderMode.FULL_RENDERING.name}'."
)
# create the annotator if it does not exist
if not hasattr(self, "_rgb_annotator"):
import omni.replicator.core as rep
# create render product
self._render_product = rep.create.render_product(
self.cfg.viewer.cam_prim_path, self.cfg.viewer.resolution
)
# create rgb annotator -- used to read data from the render product
self._rgb_annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu")
self._rgb_annotator.attach([self._render_product])
# obtain the rgb data
rgb_data = self._rgb_annotator.get_data()
# convert to numpy array
rgb_data = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape)
# return the rgb data
# note: initially the renerer is warming up and returns empty data
if rgb_data.size == 0:
return np.zeros((self.cfg.viewer.resolution[1], self.cfg.viewer.resolution[0], 3), dtype=np.uint8)
else:
return rgb_data[:, :, :3]
else:
raise NotImplementedError(
f"Render mode '{self.render_mode}' is not supported. Please use: {self.metadata['render_modes']}."
)
def close(self):
if not self._is_closed:
# destructor is order-sensitive
del self.command_manager
del self.reward_manager
del self.termination_manager
del self.curriculum_manager
# call the parent class to close the environment
super().close()
"""
Helper functions.
"""
def _configure_gym_env_spaces(self):
"""Configure the action and observation spaces for the Gym environment."""
# observation space (unbounded since we don't impose any limits)
self.single_observation_space = gym.spaces.Dict()
for group_name, group_term_names in self.observation_manager.active_terms.items():
# extract quantities about the group
has_concatenated_obs = self.observation_manager.group_obs_concatenate[group_name]
group_dim = self.observation_manager.group_obs_dim[group_name]
group_term_dim = self.observation_manager.group_obs_term_dim[group_name]
# check if group is concatenated or not
# if not concatenated, then we need to add each term separately as a dictionary
if has_concatenated_obs:
self.single_observation_space[group_name] = gym.spaces.Box(low=-np.inf, high=np.inf, shape=group_dim)
else:
self.single_observation_space[group_name] = gym.spaces.Dict({
term_name: gym.spaces.Box(low=-np.inf, high=np.inf, shape=term_dim)
for term_name, term_dim in zip(group_term_names, group_term_dim)
})
# action space (unbounded since we don't impose any limits)
action_dim = sum(self.action_manager.action_term_dim)
self.single_action_space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=(action_dim,))
# batch the spaces for vectorized environments
self.observation_space = gym.vector.utils.batch_space(self.single_observation_space, self.num_envs)
self.action_space = gym.vector.utils.batch_space(self.single_action_space, self.num_envs)
def _reset_idx(self, env_ids: Sequence[int]):
"""Reset environments based on specified indices.
Args:
env_ids: List of environment ids which must be reset
"""
# update the curriculum for environments that need a reset
self.curriculum_manager.compute(env_ids=env_ids)
# reset the internal buffers of the scene elements
self.scene.reset(env_ids)
# apply events such as randomizations for environments that need a reset
if "reset" in self.event_manager.available_modes:
self.event_manager.apply(env_ids=env_ids, mode="reset")
# iterate over all managers and reset them
# this returns a dictionary of information which is stored in the extras
# note: This is order-sensitive! Certain things need be reset before others.
self.extras["log"] = dict()
# -- observation manager
info = self.observation_manager.reset(env_ids)
self.extras["log"].update(info)
# -- action manager
info = self.action_manager.reset(env_ids)
self.extras["log"].update(info)
# -- rewards manager
info = self.reward_manager.reset(env_ids)
self.extras["log"].update(info)
# -- curriculum manager
info = self.curriculum_manager.reset(env_ids)
self.extras["log"].update(info)
# -- command manager
info = self.command_manager.reset(env_ids)
self.extras["log"].update(info)
# -- event manager
info = self.event_manager.reset(env_ids)
self.extras["log"].update(info)
# -- termination manager
info = self.termination_manager.reset(env_ids)
self.extras["log"].update(info)
# reset the episode length buffer
self.episode_length_buf[env_ids] = 0
| 15,635 | Python | 44.321739 | 117 | 0.649376 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/base_env.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import builtins
import torch
import warnings
from collections.abc import Sequence
from typing import Any, Dict
import carb
import omni.isaac.core.utils.torch as torch_utils
from omni.isaac.orbit.managers import ActionManager, EventManager, ObservationManager
from omni.isaac.orbit.scene import InteractiveScene
from omni.isaac.orbit.sim import SimulationContext
from omni.isaac.orbit.utils.timer import Timer
from .base_env_cfg import BaseEnvCfg
from .ui import ViewportCameraController
VecEnvObs = Dict[str, torch.Tensor | Dict[str, torch.Tensor]]
"""Observation returned by the environment.
The observations are stored in a dictionary. The keys are the group to which the observations belong.
This is useful for various setups such as reinforcement learning with asymmetric actor-critic or
multi-agent learning. For non-learning paradigms, this may include observations for different components
of a system.
Within each group, the observations can be stored either as a dictionary with keys as the names of each
observation term in the group, or a single tensor obtained from concatenating all the observation terms.
For example, for asymmetric actor-critic, the observation for the actor and the critic can be accessed
using the keys ``"policy"`` and ``"critic"`` respectively.
Note:
By default, most learning frameworks deal with default and privileged observations in different ways.
This handling must be taken care of by the wrapper around the :class:`RLTaskEnv` instance.
For included frameworks (RSL-RL, RL-Games, skrl), the observations must have the key "policy". In case,
the key "critic" is also present, then the critic observations are taken from the "critic" group.
Otherwise, they are the same as the "policy" group.
"""
class BaseEnv:
"""The base environment encapsulates the simulation scene and the environment managers.
While a simulation scene or world comprises of different components such as the robots, objects,
and sensors (cameras, lidars, etc.), the environment is a higher level abstraction
that provides an interface for interacting with the simulation. The environment is comprised of
the following components:
* **Scene**: The scene manager that creates and manages the virtual world in which the robot operates.
This includes defining the robot, static and dynamic objects, sensors, etc.
* **Observation Manager**: The observation manager that generates observations from the current simulation
state and the data gathered from the sensors. These observations may include privileged information
that is not available to the robot in the real world. Additionally, user-defined terms can be added
to process the observations and generate custom observations. For example, using a network to embed
high-dimensional observations into a lower-dimensional space.
* **Action Manager**: The action manager that processes the raw actions sent to the environment and
converts them to low-level commands that are sent to the simulation. It can be configured to accept
raw actions at different levels of abstraction. For example, in case of a robotic arm, the raw actions
can be joint torques, joint positions, or end-effector poses. Similarly for a mobile base, it can be
the joint torques, or the desired velocity of the floating base.
* **Event Manager**: The event manager orchestrates operations triggered based on simulation events.
This includes resetting the scene to a default state, applying random pushes to the robot at different intervals
of time, or randomizing properties such as mass and friction coefficients. This is useful for training
and evaluating the robot in a variety of scenarios.
The environment provides a unified interface for interacting with the simulation. However, it does not
include task-specific quantities such as the reward function, or the termination conditions. These
quantities are often specific to defining Markov Decision Processes (MDPs) while the base environment
is agnostic to the MDP definition.
The environment steps forward in time at a fixed time-step. The physics simulation is decimated at a
lower time-step. This is to ensure that the simulation is stable. These two time-steps can be configured
independently using the :attr:`BaseEnvCfg.decimation` (number of simulation steps per environment step)
and the :attr:`BaseEnvCfg.sim.dt` (physics time-step) parameters. Based on these parameters, the
environment time-step is computed as the product of the two. The two time-steps can be obtained by
querying the :attr:`physics_dt` and the :attr:`step_dt` properties respectively.
"""
def __init__(self, cfg: BaseEnvCfg):
"""Initialize the environment.
Args:
cfg: The configuration object for the environment.
Raises:
RuntimeError: If a simulation context already exists. The environment must always create one
since it configures the simulation context and controls the simulation.
"""
# store inputs to class
self.cfg = cfg
# initialize internal variables
self._is_closed = False
# create a simulation context to control the simulator
if SimulationContext.instance() is None:
self.sim = SimulationContext(self.cfg.sim)
else:
raise RuntimeError("Simulation context already exists. Cannot create a new one.")
# print useful information
print("[INFO]: Base environment:")
print(f"\tEnvironment device : {self.device}")
print(f"\tPhysics step-size : {self.physics_dt}")
print(f"\tRendering step-size : {self.physics_dt * self.cfg.sim.substeps}")
print(f"\tEnvironment step-size : {self.step_dt}")
print(f"\tPhysics GPU pipeline : {self.cfg.sim.use_gpu_pipeline}")
print(f"\tPhysics GPU simulation: {self.cfg.sim.physx.use_gpu}")
# generate scene
with Timer("[INFO]: Time taken for scene creation"):
self.scene = InteractiveScene(self.cfg.scene)
print("[INFO]: Scene manager: ", self.scene)
# set up camera viewport controller
# viewport is not available in other rendering modes so the function will throw a warning
# FIXME: This needs to be fixed in the future when we unify the UI functionalities even for
# non-rendering modes.
if self.sim.render_mode >= self.sim.RenderMode.PARTIAL_RENDERING:
self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer)
else:
self.viewport_camera_controller = None
# play the simulator to activate physics handles
# note: this activates the physics simulation view that exposes TensorAPIs
# note: when started in extension mode, first call sim.reset_async() and then initialize the managers
if builtins.ISAAC_LAUNCHED_FROM_TERMINAL is False:
print("[INFO]: Starting the simulation. This may take a few seconds. Please wait...")
with Timer("[INFO]: Time taken for simulation start"):
self.sim.reset()
# add timeline event to load managers
self.load_managers()
# extend UI elements
# we need to do this here after all the managers are initialized
# this is because they dictate the sensors and commands right now
if self.sim.has_gui() and self.cfg.ui_window_class_type is not None:
self._window = self.cfg.ui_window_class_type(self, window_name="Orbit")
else:
# if no window, then we don't need to store the window
self._window = None
# allocate dictionary to store metrics
self.extras = {}
def __del__(self):
"""Cleanup for the environment."""
self.close()
"""
Properties.
"""
@property
def num_envs(self) -> int:
"""The number of instances of the environment that are running."""
return self.scene.num_envs
@property
def physics_dt(self) -> float:
"""The physics time-step (in s).
This is the lowest time-decimation at which the simulation is happening.
"""
return self.cfg.sim.dt
@property
def step_dt(self) -> float:
"""The environment stepping time-step (in s).
This is the time-step at which the environment steps forward.
"""
return self.cfg.sim.dt * self.cfg.decimation
@property
def device(self):
"""The device on which the environment is running."""
return self.sim.device
"""
Operations - Setup.
"""
def load_managers(self):
"""Load the managers for the environment.
This function is responsible for creating the various managers (action, observation,
events, etc.) for the environment. Since the managers require access to physics handles,
they can only be created after the simulator is reset (i.e. played for the first time).
.. note::
In case of standalone application (when running simulator from Python), the function is called
automatically when the class is initialized.
However, in case of extension mode, the user must call this function manually after the simulator
is reset. This is because the simulator is only reset when the user calls
:meth:`SimulationContext.reset_async` and it isn't possible to call async functions in the constructor.
"""
# check the configs
if self.cfg.randomization is not None:
msg = (
"The 'randomization' attribute is deprecated and will be removed in a future release. "
"Please use the 'events' attribute to configure the randomization settings."
)
warnings.warn(msg, category=DeprecationWarning)
carb.log_warn(msg)
# set the randomization as events (for backward compatibility)
self.cfg.events = self.cfg.randomization
# prepare the managers
# -- action manager
self.action_manager = ActionManager(self.cfg.actions, self)
print("[INFO] Action Manager: ", self.action_manager)
# -- observation manager
self.observation_manager = ObservationManager(self.cfg.observations, self)
print("[INFO] Observation Manager:", self.observation_manager)
# -- event manager
self.event_manager = EventManager(self.cfg.events, self)
print("[INFO] Event Manager: ", self.event_manager)
"""
Operations - MDP.
"""
def reset(self, seed: int | None = None, options: dict[str, Any] | None = None) -> tuple[VecEnvObs, dict]:
"""Resets all the environments and returns observations.
Args:
seed: The seed to use for randomization. Defaults to None, in which case the seed is not set.
options: Additional information to specify how the environment is reset. Defaults to None.
Note:
This argument is used for compatibility with Gymnasium environment definition.
Returns:
A tuple containing the observations and extras.
"""
# set the seed
if seed is not None:
self.seed(seed)
# reset state of scene
indices = torch.arange(self.num_envs, dtype=torch.int64, device=self.device)
self._reset_idx(indices)
# return observations
return self.observation_manager.compute(), self.extras
def step(self, action: torch.Tensor) -> VecEnvObs:
"""Execute one time-step of the environment's dynamics.
The environment steps forward at a fixed time-step, while the physics simulation is
decimated at a lower time-step. This is to ensure that the simulation is stable. These two
time-steps can be configured independently using the :attr:`BaseEnvCfg.decimation` (number of
simulation steps per environment step) and the :attr:`BaseEnvCfg.physics_dt` (physics time-step).
Based on these parameters, the environment time-step is computed as the product of the two.
Args:
action: The actions to apply on the environment. Shape is (num_envs, action_dim).
Returns:
A tuple containing the observations and extras.
"""
# process actions
self.action_manager.process_action(action)
# perform physics stepping
for _ in range(self.cfg.decimation):
# set actions into buffers
self.action_manager.apply_action()
# set actions into simulator
self.scene.write_data_to_sim()
# simulate
self.sim.step(render=False)
# update buffers at sim dt
self.scene.update(dt=self.physics_dt)
# perform rendering if gui is enabled
if self.sim.has_gui():
self.sim.render()
# post-step: step interval event
if "interval" in self.event_manager.available_modes:
self.event_manager.apply(mode="interval", dt=self.step_dt)
# return observations and extras
return self.observation_manager.compute(), self.extras
@staticmethod
def seed(seed: int = -1) -> int:
"""Set the seed for the environment.
Args:
seed: The seed for random generator. Defaults to -1.
Returns:
The seed used for random generator.
"""
# set seed for replicator
try:
import omni.replicator.core as rep
rep.set_global_seed(seed)
except ModuleNotFoundError:
pass
# set seed for torch and other libraries
return torch_utils.set_seed(seed)
def close(self):
"""Cleanup for the environment."""
if not self._is_closed:
# destructor is order-sensitive
del self.action_manager
del self.observation_manager
del self.event_manager
del self.scene
del self.viewport_camera_controller
# clear callbacks and instance
self.sim.clear_all_callbacks()
self.sim.clear_instance()
# destroy the window
if self._window is not None:
self._window = None
# update closing status
self._is_closed = True
"""
Helper functions.
"""
def _reset_idx(self, env_ids: Sequence[int]):
"""Reset environments based on specified indices.
Args:
env_ids: List of environment ids which must be reset
"""
# reset the internal buffers of the scene elements
self.scene.reset(env_ids)
# apply events such as randomizations for environments that need a reset
if "reset" in self.event_manager.available_modes:
self.event_manager.apply(env_ids=env_ids, mode="reset")
# iterate over all managers and reset them
# this returns a dictionary of information which is stored in the extras
# note: This is order-sensitive! Certain things need be reset before others.
self.extras["log"] = dict()
# -- observation manager
info = self.observation_manager.reset(env_ids)
self.extras["log"].update(info)
# -- action manager
info = self.action_manager.reset(env_ids)
self.extras["log"].update(info)
# -- event manager
info = self.event_manager.reset(env_ids)
self.extras["log"].update(info)
| 15,816 | Python | 42.936111 | 118 | 0.669512 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/ui/rl_task_env_window.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
from .base_env_window import BaseEnvWindow
if TYPE_CHECKING:
from ..rl_task_env import RLTaskEnv
class RLTaskEnvWindow(BaseEnvWindow):
"""Window manager for the RL environment.
On top of the basic environment window, this class adds controls for the RL environment.
This includes visualization of the command manager.
"""
def __init__(self, env: RLTaskEnv, window_name: str = "Orbit"):
"""Initialize the window.
Args:
env: The environment object.
window_name: The name of the window. Defaults to "Orbit".
"""
# initialize base window
super().__init__(env, window_name)
# add custom UI elements
with self.ui_window_elements["main_vstack"]:
with self.ui_window_elements["debug_frame"]:
with self.ui_window_elements["debug_vstack"]:
# add command manager visualization
self._create_debug_vis_ui_element("commands", self.env.command_manager)
| 1,210 | Python | 30.051281 | 92 | 0.64876 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/ui/viewport_camera_controller.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 numpy as np
import torch
import weakref
from collections.abc import Sequence
from typing import TYPE_CHECKING
import omni.kit.app
import omni.timeline
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv, ViewerCfg
class ViewportCameraController:
"""This class handles controlling the camera associated with a viewport in the simulator.
It can be used to set the viewpoint camera to track different origin types:
- **world**: the center of the world (static)
- **env**: the center of an environment (static)
- **asset_root**: the root of an asset in the scene (e.g. tracking a robot moving in the scene)
On creation, the camera is set to track the origin type specified in the configuration.
For the :attr:`asset_root` origin type, the camera is updated at each rendering step to track the asset's
root position. For this, it registers a callback to the post update event stream from the simulation app.
"""
def __init__(self, env: BaseEnv, cfg: ViewerCfg):
"""Initialize the ViewportCameraController.
Args:
env: The environment.
cfg: The configuration for the viewport camera controller.
Raises:
ValueError: If origin type is configured to be "env" but :attr:`cfg.env_index` is out of bounds.
ValueError: If origin type is configured to be "asset_root" but :attr:`cfg.asset_name` is unset.
"""
# store inputs
self._env = env
self._cfg = copy.deepcopy(cfg)
# cast viewer eye and look-at to numpy arrays
self.default_cam_eye = np.array(self._cfg.eye)
self.default_cam_lookat = np.array(self._cfg.lookat)
# set the camera origins
if self.cfg.origin_type == "env":
# check that the env_index is within bounds
self.set_view_env_index(self.cfg.env_index)
# set the camera origin to the center of the environment
self.update_view_to_env()
elif self.cfg.origin_type == "asset_root":
# note: we do not yet update camera for tracking an asset origin, as the asset may not yet be
# in the scene when this is called. Instead, we subscribe to the post update event to update the camera
# at each rendering step.
if self.cfg.asset_name is None:
raise ValueError(f"No asset name provided for viewer with origin type: '{self.cfg.origin_type}'.")
else:
# set the camera origin to the center of the world
self.update_view_to_world()
# subscribe to post update event so that camera view can be updated at each rendering step
app_interface = omni.kit.app.get_app_interface()
app_event_stream = app_interface.get_post_update_event_stream()
self._viewport_camera_update_handle = app_event_stream.create_subscription_to_pop(
lambda event, obj=weakref.proxy(self): obj._update_tracking_callback(event)
)
def __del__(self):
"""Unsubscribe from the callback."""
# use hasattr to handle case where __init__ has not completed before __del__ is called
if hasattr(self, "_viewport_camera_update_handle") and self._viewport_camera_update_handle is not None:
self._viewport_camera_update_handle.unsubscribe()
self._viewport_camera_update_handle = None
"""
Properties
"""
@property
def cfg(self) -> ViewerCfg:
"""The configuration for the viewer."""
return self._cfg
"""
Public Functions
"""
def set_view_env_index(self, env_index: int):
"""Sets the environment index for the camera view.
Args:
env_index: The index of the environment to set the camera view to.
Raises:
ValueError: If the environment index is out of bounds. It should be between 0 and num_envs - 1.
"""
# check that the env_index is within bounds
if env_index < 0 or env_index >= self._env.num_envs:
raise ValueError(
f"Out of range value for attribute 'env_index': {env_index}."
f" Expected a value between 0 and {self._env.num_envs - 1} for the current environment."
)
# update the environment index
self.cfg.env_index = env_index
# update the camera view if the origin is set to env type (since, the camera view is static)
# note: for assets, the camera view is updated at each rendering step
if self.cfg.origin_type == "env":
self.update_view_to_env()
def update_view_to_world(self):
"""Updates the viewer's origin to the origin of the world which is (0, 0, 0)."""
# set origin type to world
self.cfg.origin_type = "world"
# update the camera origins
self.viewer_origin = torch.zeros(3)
# update the camera view
self.update_view_location()
def update_view_to_env(self):
"""Updates the viewer's origin to the origin of the selected environment."""
# set origin type to world
self.cfg.origin_type = "env"
# update the camera origins
self.viewer_origin = self._env.scene.env_origins[self.cfg.env_index]
# update the camera view
self.update_view_location()
def update_view_to_asset_root(self, asset_name: str):
"""Updates the viewer's origin based upon the root of an asset in the scene.
Args:
asset_name: The name of the asset in the scene. The name should match the name of the
asset in the scene.
Raises:
ValueError: If the asset is not in the scene.
"""
# check if the asset is in the scene
if self.cfg.asset_name != asset_name:
asset_entities = [*self._env.scene.rigid_objects.keys(), *self._env.scene.articulations.keys()]
if asset_name not in asset_entities:
raise ValueError(f"Asset '{asset_name}' is not in the scene. Available entities: {asset_entities}.")
# update the asset name
self.cfg.asset_name = asset_name
# set origin type to asset_root
self.cfg.origin_type = "asset_root"
# update the camera origins
self.viewer_origin = self._env.scene[self.cfg.asset_name].data.root_pos_w[self.cfg.env_index]
# update the camera view
self.update_view_location()
def update_view_location(self, eye: Sequence[float] | None = None, lookat: Sequence[float] | None = None):
"""Updates the camera view pose based on the current viewer origin and the eye and lookat positions.
Args:
eye: The eye position of the camera. If None, the current eye position is used.
lookat: The lookat position of the camera. If None, the current lookat position is used.
"""
# store the camera view pose for later use
if eye is not None:
self.default_cam_eye = np.asarray(eye)
if lookat is not None:
self.default_cam_lookat = np.asarray(lookat)
# set the camera locations
viewer_origin = self.viewer_origin.detach().cpu().numpy()
cam_eye = viewer_origin + self.default_cam_eye
cam_target = viewer_origin + self.default_cam_lookat
# set the camera view
self._env.sim.set_camera_view(eye=cam_eye, target=cam_target)
"""
Private Functions
"""
def _update_tracking_callback(self, event):
"""Updates the camera view at each rendering step."""
# update the camera view if the origin is set to asset_root
# in other cases, the camera view is static and does not need to be updated continuously
if self.cfg.origin_type == "asset_root" and self.cfg.asset_name is not None:
self.update_view_to_asset_root(self.cfg.asset_name)
| 8,046 | Python | 40.6943 | 116 | 0.637087 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/ui/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module providing UI window implementation for environments.
The UI elements are used to control the environment and visualize the state of the environment.
This includes functionalities such as tracking a robot in the simulation,
toggling different debug visualization tools, and other user-defined functionalities.
"""
from .base_env_window import BaseEnvWindow
from .rl_task_env_window import RLTaskEnvWindow
from .viewport_camera_controller import ViewportCameraController
| 608 | Python | 37.062498 | 95 | 0.814145 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/ui/base_env_window.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import asyncio
import os
import weakref
from datetime import datetime
from typing import TYPE_CHECKING
import omni.isaac.ui.ui_utils as ui_utils
import omni.kit.app
import omni.kit.commands
import omni.ui
import omni.usd
from omni.kit.window.extensions import SimpleCheckBox
from pxr import PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics
if TYPE_CHECKING:
from ..base_env import BaseEnv
class BaseEnvWindow:
"""Window manager for the basic environment.
This class creates a window that is used to control the environment. The window
contains controls for rendering, debug visualization, and other environment-specific
UI elements.
Users can add their own UI elements to the window by using the `with` context manager.
This can be done either be inheriting the class or by using the `env.window` object
directly from the standalone execution script.
Example for adding a UI element from the standalone execution script:
>>> with env.window.ui_window_elements["main_vstack"]:
>>> ui.Label("My UI element")
"""
def __init__(self, env: BaseEnv, window_name: str = "Orbit"):
"""Initialize the window.
Args:
env: The environment object.
window_name: The name of the window. Defaults to "Orbit".
"""
# store inputs
self.env = env
# prepare the list of assets that can be followed by the viewport camera
# note that the first two options are "World" and "Env" which are special cases
self._viewer_assets_options = [
"World",
"Env",
*self.env.scene.rigid_objects.keys(),
*self.env.scene.articulations.keys(),
]
print("Creating window for environment.")
# create window for UI
self.ui_window = omni.ui.Window(
window_name, width=400, height=500, visible=True, dock_preference=omni.ui.DockPreference.RIGHT_TOP
)
# dock next to properties window
asyncio.ensure_future(self._dock_window(window_title=self.ui_window.title))
# keep a dictionary of stacks so that child environments can add their own UI elements
# this can be done by using the `with` context manager
self.ui_window_elements = dict()
# create main frame
self.ui_window_elements["main_frame"] = self.ui_window.frame
with self.ui_window_elements["main_frame"]:
# create main stack
self.ui_window_elements["main_vstack"] = omni.ui.VStack(spacing=5, height=0)
with self.ui_window_elements["main_vstack"]:
# create collapsable frame for simulation
self._build_sim_frame()
# create collapsable frame for viewer
self._build_viewer_frame()
# create collapsable frame for debug visualization
self._build_debug_vis_frame()
def __del__(self):
"""Destructor for the window."""
# destroy the window
if self.ui_window is not None:
self.ui_window.visible = False
self.ui_window.destroy()
self.ui_window = None
"""
Build sub-sections of the UI.
"""
def _build_sim_frame(self):
"""Builds the sim-related controls frame for the UI."""
# create collapsable frame for controls
self.ui_window_elements["sim_frame"] = omni.ui.CollapsableFrame(
title="Simulation Settings",
width=omni.ui.Fraction(1),
height=0,
collapsed=False,
style=ui_utils.get_style(),
horizontal_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with self.ui_window_elements["sim_frame"]:
# create stack for controls
self.ui_window_elements["sim_vstack"] = omni.ui.VStack(spacing=5, height=0)
with self.ui_window_elements["sim_vstack"]:
# create rendering mode dropdown
render_mode_cfg = {
"label": "Rendering Mode",
"type": "dropdown",
"default_val": self.env.sim.render_mode.value,
"items": [member.name for member in self.env.sim.RenderMode if member.value >= 0],
"tooltip": "Select a rendering mode\n" + self.env.sim.RenderMode.__doc__,
"on_clicked_fn": lambda value: self.env.sim.set_render_mode(self.env.sim.RenderMode[value]),
}
self.ui_window_elements["render_dropdown"] = ui_utils.dropdown_builder(**render_mode_cfg)
# create animation recording box
record_animate_cfg = {
"label": "Record Animation",
"type": "state_button",
"a_text": "START",
"b_text": "STOP",
"tooltip": "Record the animation of the scene. Only effective if fabric is disabled.",
"on_clicked_fn": lambda value: self._toggle_recording_animation_fn(value),
}
self.ui_window_elements["record_animation"] = ui_utils.state_btn_builder(**record_animate_cfg)
# disable the button if fabric is not enabled
self.ui_window_elements["record_animation"].enabled = not self.env.sim.is_fabric_enabled()
def _build_viewer_frame(self):
"""Build the viewer-related control frame for the UI."""
# create collapsable frame for viewer
self.ui_window_elements["viewer_frame"] = omni.ui.CollapsableFrame(
title="Viewer Settings",
width=omni.ui.Fraction(1),
height=0,
collapsed=False,
style=ui_utils.get_style(),
horizontal_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with self.ui_window_elements["viewer_frame"]:
# create stack for controls
self.ui_window_elements["viewer_vstack"] = omni.ui.VStack(spacing=5, height=0)
with self.ui_window_elements["viewer_vstack"]:
# create a number slider to move to environment origin
# NOTE: slider is 1-indexed, whereas the env index is 0-indexed
viewport_origin_cfg = {
"label": "Environment Index",
"type": "button",
"default_val": self.env.cfg.viewer.env_index + 1,
"min": 1,
"max": self.env.num_envs,
"tooltip": "The environment index to follow. Only effective if follow mode is not 'World'.",
}
self.ui_window_elements["viewer_env_index"] = ui_utils.int_builder(**viewport_origin_cfg)
# create a number slider to move to environment origin
self.ui_window_elements["viewer_env_index"].add_value_changed_fn(self._set_viewer_env_index_fn)
# create a tracker for the camera location
viewer_follow_cfg = {
"label": "Follow Mode",
"type": "dropdown",
"default_val": 0,
"items": [name.replace("_", " ").title() for name in self._viewer_assets_options],
"tooltip": "Select the viewport camera following mode.",
"on_clicked_fn": self._set_viewer_origin_type_fn,
}
self.ui_window_elements["viewer_follow"] = ui_utils.dropdown_builder(**viewer_follow_cfg)
# add viewer default eye and lookat locations
self.ui_window_elements["viewer_eye"] = ui_utils.xyz_builder(
label="Camera Eye",
tooltip="Modify the XYZ location of the viewer eye.",
default_val=self.env.cfg.viewer.eye,
step=0.1,
on_value_changed_fn=[self._set_viewer_location_fn] * 3,
)
self.ui_window_elements["viewer_lookat"] = ui_utils.xyz_builder(
label="Camera Target",
tooltip="Modify the XYZ location of the viewer target.",
default_val=self.env.cfg.viewer.lookat,
step=0.1,
on_value_changed_fn=[self._set_viewer_location_fn] * 3,
)
def _build_debug_vis_frame(self):
"""Builds the debug visualization frame for various scene elements.
This function inquires the scene for all elements that have a debug visualization
implemented and creates a checkbox to toggle the debug visualization for each element
that has it implemented. If the element does not have a debug visualization implemented,
a label is created instead.
"""
# create collapsable frame for debug visualization
self.ui_window_elements["debug_frame"] = omni.ui.CollapsableFrame(
title="Scene Debug Visualization",
width=omni.ui.Fraction(1),
height=0,
collapsed=False,
style=ui_utils.get_style(),
horizontal_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with self.ui_window_elements["debug_frame"]:
# create stack for debug visualization
self.ui_window_elements["debug_vstack"] = omni.ui.VStack(spacing=5, height=0)
with self.ui_window_elements["debug_vstack"]:
elements = [
self.env.scene.terrain,
*self.env.scene.rigid_objects.values(),
*self.env.scene.articulations.values(),
*self.env.scene.sensors.values(),
]
names = [
"terrain",
*self.env.scene.rigid_objects.keys(),
*self.env.scene.articulations.keys(),
*self.env.scene.sensors.keys(),
]
# create one for the terrain
for elem, name in zip(elements, names):
if elem is not None:
self._create_debug_vis_ui_element(name, elem)
"""
Custom callbacks for UI elements.
"""
def _toggle_recording_animation_fn(self, value: bool):
"""Toggles the animation recording."""
if value:
# log directory to save the recording
if not hasattr(self, "animation_log_dir"):
# create a new log directory
log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
self.animation_log_dir = os.path.join(os.getcwd(), "recordings", log_dir)
# start the recording
_ = omni.kit.commands.execute(
"StartRecording",
target_paths=[("/World", True)],
live_mode=True,
use_frame_range=False,
start_frame=0,
end_frame=0,
use_preroll=False,
preroll_frame=0,
record_to="FILE",
fps=0,
apply_root_anim=False,
increment_name=True,
record_folder=self.animation_log_dir,
take_name="TimeSample",
)
else:
# stop the recording
_ = omni.kit.commands.execute("StopRecording")
# save the current stage
stage = omni.usd.get_context().get_stage()
source_layer = stage.GetRootLayer()
# output the stage to a file
stage_usd_path = os.path.join(self.animation_log_dir, "Stage.usd")
source_prim_path = "/"
# creates empty anon layer
temp_layer = Sdf.Find(stage_usd_path)
if temp_layer is None:
temp_layer = Sdf.Layer.CreateNew(stage_usd_path)
temp_stage = Usd.Stage.Open(temp_layer)
# update stage data
UsdGeom.SetStageUpAxis(temp_stage, UsdGeom.GetStageUpAxis(stage))
UsdGeom.SetStageMetersPerUnit(temp_stage, UsdGeom.GetStageMetersPerUnit(stage))
# copy the prim
Sdf.CreatePrimInLayer(temp_layer, source_prim_path)
Sdf.CopySpec(source_layer, source_prim_path, temp_layer, source_prim_path)
# set the default prim
temp_layer.defaultPrim = Sdf.Path(source_prim_path).name
# remove all physics from the stage
for prim in temp_stage.TraverseAll():
# skip if the prim is an instance
if prim.IsInstanceable():
continue
# if prim has articulation then disable it
if prim.HasAPI(UsdPhysics.ArticulationRootAPI):
prim.RemoveAPI(UsdPhysics.ArticulationRootAPI)
prim.RemoveAPI(PhysxSchema.PhysxArticulationAPI)
# if prim has rigid body then disable it
if prim.HasAPI(UsdPhysics.RigidBodyAPI):
prim.RemoveAPI(UsdPhysics.RigidBodyAPI)
prim.RemoveAPI(PhysxSchema.PhysxRigidBodyAPI)
# if prim is a joint type then disable it
if prim.IsA(UsdPhysics.Joint):
prim.GetAttribute("physics:jointEnabled").Set(False)
# resolve all paths relative to layer path
omni.usd.resolve_paths(source_layer.identifier, temp_layer.identifier)
# save the stage
temp_layer.Save()
# print the path to the saved stage
print("Recording completed.")
print(f"\tSaved recorded stage to : {stage_usd_path}")
print(f"\tSaved recorded animation to: {os.path.join(self.animation_log_dir, 'TimeSample_tk001.usd')}")
print("\nTo play the animation, check the instructions in the following link:")
print(
"\thttps://docs.omniverse.nvidia.com/extensions/latest/ext_animation_stage-recorder.html#using-the-captured-timesamples"
)
print("\n")
# reset the log directory
self.animation_log_dir = None
def _set_viewer_origin_type_fn(self, value: str):
"""Sets the origin of the viewport's camera. This is based on the drop-down menu in the UI."""
# Extract the viewport camera controller from environment
vcc = self.env.viewport_camera_controller
if vcc is None:
raise ValueError("Viewport camera controller is not initialized! Please check the rendering mode.")
# Based on origin type, update the camera view
if value == "World":
vcc.update_view_to_world()
elif value == "Env":
vcc.update_view_to_env()
else:
# find which index the asset is
fancy_names = [name.replace("_", " ").title() for name in self._viewer_assets_options]
# store the desired env index
viewer_asset_name = self._viewer_assets_options[fancy_names.index(value)]
# update the camera view
vcc.update_view_to_asset_root(viewer_asset_name)
def _set_viewer_location_fn(self, model: omni.ui.SimpleFloatModel):
"""Sets the viewport camera location based on the UI."""
# access the viewport camera controller (for brevity)
vcc = self.env.viewport_camera_controller
if vcc is None:
raise ValueError("Viewport camera controller is not initialized! Please check the rendering mode.")
# obtain the camera locations and set them in the viewpoint camera controller
eye = [self.ui_window_elements["viewer_eye"][i].get_value_as_float() for i in range(3)]
lookat = [self.ui_window_elements["viewer_lookat"][i].get_value_as_float() for i in range(3)]
# update the camera view
vcc.update_view_location(eye, lookat)
def _set_viewer_env_index_fn(self, model: omni.ui.SimpleIntModel):
"""Sets the environment index and updates the camera if in 'env' origin mode."""
# access the viewport camera controller (for brevity)
vcc = self.env.viewport_camera_controller
if vcc is None:
raise ValueError("Viewport camera controller is not initialized! Please check the rendering mode.")
# store the desired env index, UI is 1-indexed
vcc.set_view_env_index(model.as_int - 1)
"""
Helper functions - UI building.
"""
def _create_debug_vis_ui_element(self, name: str, elem: object):
"""Create a checkbox for toggling debug visualization for the given element."""
with omni.ui.HStack():
# create the UI element
text = (
"Toggle debug visualization."
if elem.has_debug_vis_implementation
else "Debug visualization not implemented."
)
omni.ui.Label(
name.replace("_", " ").title(),
width=ui_utils.LABEL_WIDTH - 12,
alignment=omni.ui.Alignment.LEFT_CENTER,
tooltip=text,
)
self.ui_window_elements[f"{name}_cb"] = SimpleCheckBox(
model=omni.ui.SimpleBoolModel(),
enabled=elem.has_debug_vis_implementation,
checked=elem.cfg.debug_vis,
on_checked_fn=lambda value, e=weakref.proxy(elem): e.set_debug_vis(value),
)
ui_utils.add_line_rect_flourish()
async def _dock_window(self, window_title: str):
"""Docks the custom UI window to the property window."""
# wait for the window to be created
for _ in range(5):
if omni.ui.Workspace.get_window(window_title):
break
await self.env.sim.app.next_update_async()
# dock next to properties window
custom_window = omni.ui.Workspace.get_window(window_title)
property_window = omni.ui.Workspace.get_window("Property")
if custom_window and property_window:
custom_window.dock_in(property_window, omni.ui.DockPosition.SAME, 1.0)
custom_window.focus()
| 18,520 | Python | 45.535176 | 136 | 0.582397 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module with implementation of manager terms.
The functions can be provided to different managers that are responsible for the
different aspects of the MDP. These include the observation, reward, termination,
actions, events and curriculum managers.
The terms are defined under the ``envs`` module because they are used to define
the environment. However, they are not part of the environment directly, but
are used to define the environment through their managers.
"""
from .actions import * # noqa: F401, F403
from .commands import * # noqa: F401, F403
from .curriculums import * # noqa: F401, F403
from .events import * # noqa: F401, F403
from .observations import * # noqa: F401, F403
from .rewards import * # noqa: F401, F403
from .terminations import * # noqa: F401, F403
| 918 | Python | 35.759999 | 81 | 0.752723 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/curriculums.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Common functions that can be used to create curriculum for the learning environment.
The functions can be passed to the :class:`omni.isaac.orbit.managers.CurriculumTermCfg` object to enable
the curriculum introduced by the function.
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def modify_reward_weight(env: RLTaskEnv, env_ids: Sequence[int], term_name: str, weight: float, num_steps: int):
"""Curriculum that modifies a reward weight a given number of steps.
Args:
env: The learning environment.
env_ids: Not used since all environments are affected.
term_name: The name of the reward term.
weight: The weight of the reward term.
num_steps: The number of steps after which the change should be applied.
"""
if env.common_step_counter > num_steps:
# obtain term settings
term_cfg = env.reward_manager.get_term_cfg(term_name)
# update term settings
term_cfg.weight = weight
env.reward_manager.set_term_cfg(term_name, term_cfg)
| 1,285 | Python | 33.756756 | 112 | 0.713619 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/rewards.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Common functions that can be used to enable reward functions.
The functions can be passed to the :class:`omni.isaac.orbit.managers.RewardTermCfg` object to include
the reward introduced by the function.
"""
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import Articulation, RigidObject
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers.manager_base import ManagerTermBase
from omni.isaac.orbit.managers.manager_term_cfg import RewardTermCfg
from omni.isaac.orbit.sensors import ContactSensor
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
"""
General.
"""
def is_alive(env: RLTaskEnv) -> torch.Tensor:
"""Reward for being alive."""
return (~env.termination_manager.terminated).float()
def is_terminated(env: RLTaskEnv) -> torch.Tensor:
"""Penalize terminated episodes that don't correspond to episodic timeouts."""
return env.termination_manager.terminated.float()
class is_terminated_term(ManagerTermBase):
"""Penalize termination for specific terms that don't correspond to episodic timeouts.
The parameters are as follows:
* attr:`term_keys`: The termination terms to penalize. This can be a string, a list of strings
or regular expressions. Default is ".*" which penalizes all terminations.
The reward is computed as the sum of the termination terms that are not episodic timeouts.
This means that the reward is 0 if the episode is terminated due to an episodic timeout. Otherwise,
if two termination terms are active, the reward is 2.
"""
def __init__(self, cfg: RewardTermCfg, env: RLTaskEnv):
# initialize the base class
super().__init__(cfg, env)
# find and store the termination terms
term_keys = cfg.params.get("term_keys", ".*")
self._term_names = env.termination_manager.find_terms(term_keys)
def __call__(self, env: RLTaskEnv, term_keys: str | list[str] = ".*") -> torch.Tensor:
# Return the unweighted reward for the termination terms
reset_buf = torch.zeros(env.num_envs, device=env.device)
for term in self._term_names:
# Sums over terminations term values to account for multiple terminations in the same step
reset_buf += env.termination_manager.get_term(term)
return (reset_buf * (~env.termination_manager.time_outs)).float()
"""
Root penalties.
"""
def lin_vel_z_l2(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize z-axis base linear velocity using L2-kernel."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return torch.square(asset.data.root_lin_vel_b[:, 2])
def ang_vel_xy_l2(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize xy-axis base angular velocity using L2-kernel."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return torch.sum(torch.square(asset.data.root_ang_vel_b[:, :2]), dim=1)
def flat_orientation_l2(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize non-flat base orientation using L2-kernel.
This is computed by penalizing the xy-components of the projected gravity vector.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return torch.sum(torch.square(asset.data.projected_gravity_b[:, :2]), dim=1)
def base_height_l2(
env: RLTaskEnv, target_height: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Penalize asset height from its target using L2-kernel.
Note:
Currently, it assumes a flat terrain, i.e. the target height is in the world frame.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
# TODO: Fix this for rough-terrain.
return torch.square(asset.data.root_pos_w[:, 2] - target_height)
def body_lin_acc_l2(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize the linear acceleration of bodies using L2-kernel."""
asset: Articulation = env.scene[asset_cfg.name]
return torch.sum(torch.norm(asset.data.body_lin_acc_w[:, asset_cfg.body_ids, :], dim=-1), dim=1)
"""
Joint penalties.
"""
def joint_torques_l2(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize joint torques applied on the articulation using L2-kernel.
NOTE: Only the joints configured in :attr:`asset_cfg.joint_ids` will have their joint torques contribute to the L2 norm.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return torch.sum(torch.square(asset.data.applied_torque[:, asset_cfg.joint_ids]), dim=1)
def joint_vel_l1(env: RLTaskEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Penalize joint velocities on the articulation using an L1-kernel."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return torch.sum(torch.abs(asset.data.joint_vel[:, asset_cfg.joint_ids]), dim=1)
def joint_vel_l2(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize joint velocities on the articulation using L1-kernel.
NOTE: Only the joints configured in :attr:`asset_cfg.joint_ids` will have their joint velocities contribute to the L1 norm.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return torch.sum(torch.square(asset.data.joint_vel[:, asset_cfg.joint_ids]), dim=1)
def joint_acc_l2(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize joint accelerations on the articulation using L2-kernel.
NOTE: Only the joints configured in :attr:`asset_cfg.joint_ids` will have their joint accelerations contribute to the L2 norm.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return torch.sum(torch.square(asset.data.joint_acc[:, asset_cfg.joint_ids]), dim=1)
def joint_deviation_l1(env, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize joint positions that deviate from the default one."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute out of limits constraints
angle = asset.data.joint_pos[:, asset_cfg.joint_ids] - asset.data.default_joint_pos[:, asset_cfg.joint_ids]
return torch.sum(torch.abs(angle), dim=1)
def joint_pos_limits(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize joint positions if they cross the soft limits.
This is computed as a sum of the absolute value of the difference between the joint position and the soft limits.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute out of limits constraints
out_of_limits = -(
asset.data.joint_pos[:, asset_cfg.joint_ids] - asset.data.soft_joint_pos_limits[:, asset_cfg.joint_ids, 0]
).clip(max=0.0)
out_of_limits += (
asset.data.joint_pos[:, asset_cfg.joint_ids] - asset.data.soft_joint_pos_limits[:, asset_cfg.joint_ids, 1]
).clip(min=0.0)
return torch.sum(out_of_limits, dim=1)
def joint_vel_limits(
env: RLTaskEnv, soft_ratio: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Penalize joint velocities if they cross the soft limits.
This is computed as a sum of the absolute value of the difference between the joint velocity and the soft limits.
Args:
soft_ratio: The ratio of the soft limits to be used.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute out of limits constraints
out_of_limits = (
torch.abs(asset.data.joint_vel[:, asset_cfg.joint_ids])
- asset.data.soft_joint_vel_limits[:, asset_cfg.joint_ids] * soft_ratio
)
# clip to max error = 1 rad/s per joint to avoid huge penalties
out_of_limits = out_of_limits.clip_(min=0.0, max=1.0)
return torch.sum(out_of_limits, dim=1)
"""
Action penalties.
"""
def applied_torque_limits(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Penalize applied torques if they cross the limits.
This is computed as a sum of the absolute value of the difference between the applied torques and the limits.
.. caution::
Currently, this only works for explicit actuators since we manually compute the applied torques.
For implicit actuators, we currently cannot retrieve the applied torques from the physics engine.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute out of limits constraints
# TODO: We need to fix this to support implicit joints.
out_of_limits = torch.abs(
asset.data.applied_torque[:, asset_cfg.joint_ids] - asset.data.computed_torque[:, asset_cfg.joint_ids]
)
return torch.sum(out_of_limits, dim=1)
def action_rate_l2(env: RLTaskEnv) -> torch.Tensor:
"""Penalize the rate of change of the actions using L2-kernel."""
return torch.sum(torch.square(env.action_manager.action - env.action_manager.prev_action), dim=1)
def action_l2(env: RLTaskEnv) -> torch.Tensor:
"""Penalize the actions using L2-kernel."""
return torch.sum(torch.square(env.action_manager.action), dim=1)
"""
Contact sensor.
"""
def undesired_contacts(env: RLTaskEnv, threshold: float, sensor_cfg: SceneEntityCfg) -> torch.Tensor:
"""Penalize undesired contacts as the number of violations that are above a threshold."""
# extract the used quantities (to enable type-hinting)
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
# check if contact force is above threshold
net_contact_forces = contact_sensor.data.net_forces_w_history
is_contact = torch.max(torch.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] > threshold
# sum over contacts for each environment
return torch.sum(is_contact, dim=1)
def contact_forces(env: RLTaskEnv, threshold: float, sensor_cfg: SceneEntityCfg) -> torch.Tensor:
"""Penalize contact forces as the amount of violations of the net contact force."""
# extract the used quantities (to enable type-hinting)
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
net_contact_forces = contact_sensor.data.net_forces_w_history
# compute the violation
violation = torch.max(torch.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] - threshold
# compute the penalty
return torch.sum(violation.clip(min=0.0), dim=1)
"""
Velocity-tracking rewards.
"""
def track_lin_vel_xy_exp(
env: RLTaskEnv, std: float, command_name: str, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Reward tracking of linear velocity commands (xy axes) using exponential kernel."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
# compute the error
lin_vel_error = torch.sum(
torch.square(env.command_manager.get_command(command_name)[:, :2] - asset.data.root_lin_vel_b[:, :2]),
dim=1,
)
return torch.exp(-lin_vel_error / std**2)
def track_ang_vel_z_exp(
env: RLTaskEnv, std: float, command_name: str, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Reward tracking of angular velocity commands (yaw) using exponential kernel."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
# compute the error
ang_vel_error = torch.square(env.command_manager.get_command(command_name)[:, 2] - asset.data.root_ang_vel_b[:, 2])
return torch.exp(-ang_vel_error / std**2)
| 12,477 | Python | 40.732441 | 130 | 0.70666 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/events.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Common functions that can be used to enable different events.
Events include anything related to altering the simulation state. This includes changing the physics
materials, applying external forces, and resetting the state of the asset.
The functions can be passed to the :class:`omni.isaac.orbit.managers.EventTermCfg` object to enable
the event introduced by the function.
"""
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import Articulation, RigidObject
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers.manager_base import ManagerTermBase
from omni.isaac.orbit.managers.manager_term_cfg import EventTermCfg
from omni.isaac.orbit.terrains import TerrainImporter
from omni.isaac.orbit.utils.math import quat_from_euler_xyz, random_orientation, sample_uniform
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
def randomize_rigid_body_material(
env: BaseEnv,
env_ids: torch.Tensor | None,
static_friction_range: tuple[float, float],
dynamic_friction_range: tuple[float, float],
restitution_range: tuple[float, float],
num_buckets: int,
asset_cfg: SceneEntityCfg,
):
"""Randomize the physics materials on all geometries of the asset.
This function creates a set of physics materials with random static friction, dynamic friction, and restitution
values. The number of materials is specified by ``num_buckets``. The materials are generated by sampling
uniform random values from the given ranges.
The material properties are then assigned to the geometries of the asset. The assignment is done by
creating a random integer tensor of shape (num_instances, max_num_shapes) where ``num_instances``
is the number of assets spawned and ``max_num_shapes`` is the maximum number of shapes in the asset (over
all bodies). The integer values are used as indices to select the material properties from the
material buckets.
.. attention::
This function uses CPU tensors to assign the material properties. It is recommended to use this function
only during the initialization of the environment. Otherwise, it may lead to a significant performance
overhead.
.. note::
PhysX only allows 64000 unique physics materials in the scene. If the number of materials exceeds this
limit, the simulation will crash.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject | Articulation = env.scene[asset_cfg.name]
num_envs = env.scene.num_envs
# resolve environment ids
if env_ids is None:
env_ids = torch.arange(num_envs, device="cpu")
# sample material properties from the given ranges
material_buckets = torch.zeros(num_buckets, 3)
material_buckets[:, 0].uniform_(*static_friction_range)
material_buckets[:, 1].uniform_(*dynamic_friction_range)
material_buckets[:, 2].uniform_(*restitution_range)
# create random material assignments based on the total number of shapes: num_assets x num_shapes
# note: not optimal since it creates assignments for all the shapes but only a subset is used in the body indices case.
material_ids = torch.randint(0, num_buckets, (len(env_ids), asset.root_physx_view.max_shapes))
if asset_cfg.body_ids == slice(None):
# get the current materials of the bodies
materials = asset.root_physx_view.get_material_properties()
# assign the new materials
# material ids are of shape: num_env_ids x num_shapes
# material_buckets are of shape: num_buckets x 3
materials[env_ids] = material_buckets[material_ids]
# set the material properties into the physics simulation
asset.root_physx_view.set_material_properties(materials, env_ids)
elif isinstance(asset, Articulation):
# obtain number of shapes per body (needed for indexing the material properties correctly)
# note: this is a workaround since the Articulation does not provide a direct way to obtain the number of shapes
# per body. We use the physics simulation view to obtain the number of shapes per body.
num_shapes_per_body = []
for link_path in asset.root_physx_view.link_paths[0]:
link_physx_view = asset._physics_sim_view.create_rigid_body_view(link_path) # type: ignore
num_shapes_per_body.append(link_physx_view.max_shapes)
# get the current materials of the bodies
materials = asset.root_physx_view.get_material_properties()
# sample material properties from the given ranges
for body_id in asset_cfg.body_ids:
# start index of shape
start_idx = sum(num_shapes_per_body[:body_id])
# end index of shape
end_idx = start_idx + num_shapes_per_body[body_id]
# assign the new materials
# material ids are of shape: num_env_ids x num_shapes
# material_buckets are of shape: num_buckets x 3
materials[env_ids, start_idx:end_idx] = material_buckets[material_ids[:, start_idx:end_idx]]
# set the material properties into the physics simulation
asset.root_physx_view.set_material_properties(materials, env_ids)
else:
raise ValueError(
f"Randomization term 'randomize_rigid_body_material' not supported for asset: '{asset_cfg.name}'"
f" with type: '{type(asset)}' and body_ids: '{asset_cfg.body_ids}'."
)
def add_body_mass(
env: BaseEnv, env_ids: torch.Tensor | None, mass_range: tuple[float, float], asset_cfg: SceneEntityCfg
):
"""Randomize the mass of the bodies by adding a random value sampled from the given range.
.. tip::
This function uses CPU tensors to assign the material properties. It is recommended to use this function
only during the initialization of the environment.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject | Articulation = env.scene[asset_cfg.name]
num_envs = env.scene.num_envs
# resolve environment ids
if env_ids is None:
env_ids = torch.arange(num_envs, device="cpu")
# resolve body indices
if asset_cfg.body_ids == slice(None):
body_ids = torch.arange(asset.num_bodies, dtype=torch.int, device="cpu")
else:
body_ids = torch.tensor(asset_cfg.body_ids, dtype=torch.int, device="cpu")
# get the current masses of the bodies (num_assets, num_bodies)
masses = asset.root_physx_view.get_masses()
# note: we modify the masses in-place for all environments
# however, the setter takes care that only the masses of the specified environments are modified
masses[:, body_ids] += sample_uniform(*mass_range, (masses.shape[0], len(body_ids)), device=masses.device)
# set the mass into the physics simulation
asset.root_physx_view.set_masses(masses, env_ids)
def apply_external_force_torque(
env: BaseEnv,
env_ids: torch.Tensor,
force_range: tuple[float, float],
torque_range: tuple[float, float],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
"""Randomize the external forces and torques applied to the bodies.
This function creates a set of random forces and torques sampled from the given ranges. The number of forces
and torques is equal to the number of bodies times the number of environments. The forces and torques are
applied to the bodies by calling ``asset.set_external_force_and_torque``. The forces and torques are only
applied when ``asset.write_data_to_sim()`` is called in the environment.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject | Articulation = env.scene[asset_cfg.name]
num_envs = env.scene.num_envs
# resolve environment ids
if env_ids is None:
env_ids = torch.arange(num_envs)
# resolve number of bodies
num_bodies = len(asset_cfg.body_ids) if isinstance(asset_cfg.body_ids, list) else asset.num_bodies
# sample random forces and torques
size = (len(env_ids), num_bodies, 3)
forces = sample_uniform(*force_range, size, asset.device)
torques = sample_uniform(*torque_range, size, asset.device)
# set the forces and torques into the buffers
# note: these are only applied when you call: `asset.write_data_to_sim()`
asset.set_external_force_and_torque(forces, torques, env_ids=env_ids, body_ids=asset_cfg.body_ids)
def push_by_setting_velocity(
env: BaseEnv,
env_ids: torch.Tensor,
velocity_range: dict[str, tuple[float, float]],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
"""Push the asset by setting the root velocity to a random value within the given ranges.
This creates an effect similar to pushing the asset with a random impulse that changes the asset's velocity.
It samples the root velocity from the given ranges and sets the velocity into the physics simulation.
The function takes a dictionary of velocity ranges for each axis and rotation. The keys of the dictionary
are ``x``, ``y``, ``z``, ``roll``, ``pitch``, and ``yaw``. The values are tuples of the form ``(min, max)``.
If the dictionary does not contain a key, the velocity is set to zero for that axis.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject | Articulation = env.scene[asset_cfg.name]
# velocities
vel_w = asset.data.root_vel_w[env_ids]
# sample random velocities
range_list = [velocity_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]]
ranges = torch.tensor(range_list, device=asset.device)
vel_w[:] = sample_uniform(ranges[:, 0], ranges[:, 1], vel_w.shape, device=asset.device)
# set the velocities into the physics simulation
asset.write_root_velocity_to_sim(vel_w, env_ids=env_ids)
def reset_root_state_uniform(
env: BaseEnv,
env_ids: torch.Tensor,
pose_range: dict[str, tuple[float, float]],
velocity_range: dict[str, tuple[float, float]],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
"""Reset the asset root state to a random position and velocity uniformly within the given ranges.
This function randomizes the root position and velocity of the asset.
* It samples the root position from the given ranges and adds them to the default root position, before setting
them into the physics simulation.
* It samples the root orientation from the given ranges and sets them into the physics simulation.
* It samples the root velocity from the given ranges and sets them into the physics simulation.
The function takes a dictionary of position and velocity ranges for each axis and rotation. The keys of the
dictionary are ``x``, ``y``, ``z``, ``roll``, ``pitch``, and ``yaw``. The values are tuples of the form
``(min, max)``. If the dictionary does not contain a key, the position or velocity is set to zero for that axis.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject | Articulation = env.scene[asset_cfg.name]
# get default root state
root_states = asset.data.default_root_state[env_ids].clone()
# poses
range_list = [pose_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]]
ranges = torch.tensor(range_list, device=asset.device)
rand_samples = sample_uniform(ranges[:, 0], ranges[:, 1], (len(env_ids), 6), device=asset.device)
positions = root_states[:, 0:3] + env.scene.env_origins[env_ids] + rand_samples[:, 0:3]
orientations = quat_from_euler_xyz(rand_samples[:, 3], rand_samples[:, 4], rand_samples[:, 5])
# velocities
range_list = [velocity_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]]
ranges = torch.tensor(range_list, device=asset.device)
rand_samples = sample_uniform(ranges[:, 0], ranges[:, 1], (len(env_ids), 6), device=asset.device)
velocities = root_states[:, 7:13] + rand_samples
# set into the physics simulation
asset.write_root_pose_to_sim(torch.cat([positions, orientations], dim=-1), env_ids=env_ids)
asset.write_root_velocity_to_sim(velocities, env_ids=env_ids)
def reset_root_state_with_random_orientation(
env: BaseEnv,
env_ids: torch.Tensor,
pose_range: dict[str, tuple[float, float]],
velocity_range: dict[str, tuple[float, float]],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
"""Reset the asset root position and velocities sampled randomly within the given ranges
and the asset root orientation sampled randomly from the SO(3).
This function randomizes the root position and velocity of the asset.
* It samples the root position from the given ranges and adds them to the default root position, before setting
them into the physics simulation.
* It samples the root orientation uniformly from the SO(3) and sets them into the physics simulation.
* It samples the root velocity from the given ranges and sets them into the physics simulation.
The function takes a dictionary of position and velocity ranges for each axis and rotation:
* :attr:`pose_range` - a dictionary of position ranges for each axis. The keys of the dictionary are ``x``,
``y``, and ``z``.
* :attr:`velocity_range` - a dictionary of velocity ranges for each axis and rotation. The keys of the dictionary
are ``x``, ``y``, ``z``, ``roll``, ``pitch``, and ``yaw``.
The values are tuples of the form ``(min, max)``. If the dictionary does not contain a particular key,
the position is set to zero for that axis.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject | Articulation = env.scene[asset_cfg.name]
# get default root state
root_states = asset.data.default_root_state[env_ids].clone()
# poses
range_list = [pose_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z"]]
ranges = torch.tensor(range_list, device=asset.device)
rand_samples = sample_uniform(ranges[:, 0], ranges[:, 1], (len(env_ids), 3), device=asset.device)
positions = root_states[:, 0:3] + env.scene.env_origins[env_ids] + rand_samples
orientations = random_orientation(len(env_ids), device=asset.device)
# velocities
range_list = [velocity_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]]
ranges = torch.tensor(range_list, device=asset.device)
rand_samples = sample_uniform(ranges[:, 0], ranges[:, 1], (len(env_ids), 6), device=asset.device)
velocities = root_states[:, 7:13] + rand_samples
# set into the physics simulation
asset.write_root_pose_to_sim(torch.cat([positions, orientations], dim=-1), env_ids=env_ids)
asset.write_root_velocity_to_sim(velocities, env_ids=env_ids)
def reset_robot_root_from_terrain(
env: BaseEnv,
env_ids: torch.Tensor,
pose_range: dict[str, tuple[float, float]],
velocity_range: dict[str, tuple[float, float]],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
"""Reset the robot root state by sampling a random valid pose from the terrain.
This function samples a random valid pose(based on flat patches) from the terrain and sets the root state
of the robot to this pose. The function also samples random velocities from the given ranges and sets them
into the physics simulation.
Note:
The function expects the terrain to have valid flat patches under the key "init_pos". The flat patches
are used to sample the random pose for the robot.
Raises:
ValueError: If the terrain does not have valid flat patches under the key "init_pos".
"""
# access the used quantities (to enable type-hinting)
asset: RigidObject | Articulation = env.scene[asset_cfg.name]
terrain: TerrainImporter = env.scene.terrain
# obtain all flat patches corresponding to the valid poses
valid_poses: torch.Tensor = terrain.flat_patches.get("init_pos")
if valid_poses is None:
raise ValueError(
"The event term 'reset_robot_root_from_terrain' requires valid flat patches under 'init_pos'."
f" Found: {list(terrain.flat_patches.keys())}"
)
# sample random valid poses
ids = torch.randint(0, valid_poses.shape[2], size=(len(env_ids),), device=env.device)
positions = valid_poses[terrain.terrain_levels[env_ids], terrain.terrain_types[env_ids], ids]
positions += asset.data.default_root_state[env_ids, :3]
# sample random orientations
range_list = [pose_range.get(key, (0.0, 0.0)) for key in ["roll", "pitch", "yaw"]]
ranges = torch.tensor(range_list, device=asset.device)
rand_samples = sample_uniform(ranges[:, 0], ranges[:, 1], (len(env_ids), 3), device=asset.device)
# convert to quaternions
orientations = quat_from_euler_xyz(rand_samples[:, 0], rand_samples[:, 1], rand_samples[:, 2])
# sample random velocities
range_list = [velocity_range.get(key, (0.0, 0.0)) for key in ["x", "y", "z", "roll", "pitch", "yaw"]]
ranges = torch.tensor(range_list, device=asset.device)
rand_samples = sample_uniform(ranges[:, 0], ranges[:, 1], (len(env_ids), 6), device=asset.device)
velocities = asset.data.default_root_state[:, 7:13] + rand_samples
# set into the physics simulation
asset.write_root_pose_to_sim(torch.cat([positions, orientations], dim=-1), env_ids=env_ids)
asset.write_root_velocity_to_sim(velocities, env_ids=env_ids)
def reset_joints_by_scale(
env: BaseEnv,
env_ids: torch.Tensor,
position_range: tuple[float, float],
velocity_range: tuple[float, float],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
"""Reset the robot joints by scaling the default position and velocity by the given ranges.
This function samples random values from the given ranges and scales the default joint positions and velocities
by these values. The scaled values are then set into the physics simulation.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# get default joint state
joint_pos = asset.data.default_joint_pos[env_ids].clone()
joint_vel = asset.data.default_joint_vel[env_ids].clone()
# scale these values randomly
joint_pos *= sample_uniform(*position_range, joint_pos.shape, joint_pos.device)
joint_vel *= sample_uniform(*velocity_range, joint_vel.shape, joint_vel.device)
# clamp joint pos to limits
joint_pos_limits = asset.data.soft_joint_pos_limits[env_ids]
joint_pos = joint_pos.clamp_(joint_pos_limits[..., 0], joint_pos_limits[..., 1])
# set into the physics simulation
asset.write_joint_state_to_sim(joint_pos, joint_vel, env_ids=env_ids)
def reset_joints_by_offset(
env: BaseEnv,
env_ids: torch.Tensor,
position_range: tuple[float, float],
velocity_range: tuple[float, float],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
"""Reset the robot joints with offsets around the default position and velocity by the given ranges.
This function samples random values from the given ranges and biases the default joint positions and velocities
by these values. The biased values are then set into the physics simulation.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# get default joint state
joint_pos = asset.data.default_joint_pos[env_ids].clone()
joint_vel = asset.data.default_joint_vel[env_ids].clone()
# bias these values randomly
joint_pos += sample_uniform(*position_range, joint_pos.shape, joint_pos.device)
joint_vel += sample_uniform(*velocity_range, joint_vel.shape, joint_vel.device)
# clamp joint pos to limits
joint_pos_limits = asset.data.soft_joint_pos_limits[env_ids]
joint_pos = joint_pos.clamp_(joint_pos_limits[..., 0], joint_pos_limits[..., 1])
# set into the physics simulation
asset.write_joint_state_to_sim(joint_pos, joint_vel, env_ids=env_ids)
class reset_joints_within_range(ManagerTermBase):
"""Reset an articulation's joints to a random position in the given ranges.
This function samples random values for the joint position and velocities from the given ranges.
The values are then set into the physics simulation.
The parameters to the function are:
* :attr:`position_range` - a dictionary of position ranges for each joint. The keys of the dictionary are the
joint names (or regular expressions) of the asset.
* :attr:`velocity_range` - a dictionary of velocity ranges for each joint. The keys of the dictionary are the
joint names (or regular expressions) of the asset.
* :attr:`use_default_offset` - a boolean flag to indicate if the ranges are offset by the default joint state.
Defaults to False.
* :attr:`asset_cfg` - the configuration of the asset to reset. Defaults to the entity named "robot" in the scene.
The dictionary values are a tuple of the form ``(min, max)``, where ``min`` and ``max`` are the minimum and
maximum values. If the dictionary does not contain a key, the joint position or joint velocity is set to
the default value for that joint. If the ``min`` or the ``max`` value is ``None``, the joint limits are used
instead.
"""
def __init__(self, cfg: EventTermCfg, env: BaseEnv):
# initialize the base class
super().__init__(cfg, env)
# check if the cfg has the required parameters
if "position_range" not in cfg.params or "velocity_range" not in cfg.params:
raise ValueError(
"The term 'reset_joints_within_range' requires parameters: 'position_range' and 'velocity_range'."
f" Received: {list(cfg.params.keys())}."
)
# parse the parameters
asset_cfg: SceneEntityCfg = cfg.params.get("asset_cfg", SceneEntityCfg("robot"))
use_default_offset = cfg.params.get("use_default_offset", False)
# extract the used quantities (to enable type-hinting)
self._asset: Articulation = env.scene[asset_cfg.name]
default_joint_pos = self._asset.data.default_joint_pos[0]
default_joint_vel = self._asset.data.default_joint_vel[0]
# create buffers to store the joint position and velocity ranges
self._pos_ranges = self._asset.data.soft_joint_pos_limits[0].clone()
self._vel_ranges = torch.stack(
[-self._asset.data.soft_joint_vel_limits[0], self._asset.data.soft_joint_vel_limits[0]], dim=1
)
# parse joint position ranges
pos_joint_ids = []
for joint_name, joint_range in cfg.params["position_range"].items():
# find the joint ids
joint_ids = self._asset.find_joints(joint_name)[0]
pos_joint_ids.extend(joint_ids)
# set the joint position ranges based on the given values
if joint_range[0] is not None:
self._pos_ranges[joint_ids, 0] = joint_range[0] + use_default_offset * default_joint_pos[joint_ids]
if joint_range[1] is not None:
self._pos_ranges[joint_ids, 1] = joint_range[1] + use_default_offset * default_joint_pos[joint_ids]
# store the joint pos ids (used later to sample the joint positions)
self._pos_joint_ids = torch.tensor(pos_joint_ids, device=self._pos_ranges.device)
# clamp sampling range to the joint position limits
joint_pos_limits = self._asset.data.soft_joint_pos_limits[0]
self._pos_ranges = self._pos_ranges.clamp(min=joint_pos_limits[:, 0], max=joint_pos_limits[:, 1])
self._pos_ranges = self._pos_ranges[self._pos_joint_ids]
# parse joint velocity ranges
vel_joint_ids = []
for joint_name, joint_range in cfg.params["velocity_range"].items():
# find the joint ids
joint_ids = self._asset.find_joints(joint_name)[0]
vel_joint_ids.extend(joint_ids)
# set the joint position ranges based on the given values
if joint_range[0] is not None:
self._vel_ranges[joint_ids, 0] = joint_range[0] + use_default_offset * default_joint_vel[joint_ids]
if joint_range[1] is not None:
self._vel_ranges[joint_ids, 1] = joint_range[1] + use_default_offset * default_joint_vel[joint_ids]
# store the joint vel ids (used later to sample the joint positions)
self._vel_joint_ids = torch.tensor(vel_joint_ids, device=self._vel_ranges.device)
# clamp sampling range to the joint velocity limits
joint_vel_limits = self._asset.data.soft_joint_vel_limits[0]
self._vel_ranges = self._vel_ranges.clamp(min=-joint_vel_limits[:, None], max=joint_vel_limits[:, None])
self._vel_ranges = self._vel_ranges[self._vel_joint_ids]
def __call__(
self,
env: BaseEnv,
env_ids: torch.Tensor,
position_range: dict[str, tuple[float | None, float | None]],
velocity_range: dict[str, tuple[float | None, float | None]],
use_default_offset: bool = False,
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
):
# get default joint state
joint_pos = self._asset.data.default_joint_pos[env_ids].clone()
joint_vel = self._asset.data.default_joint_vel[env_ids].clone()
# sample random joint positions for each joint
if len(self._pos_joint_ids) > 0:
joint_pos_shape = (len(env_ids), len(self._pos_joint_ids))
joint_pos[:, self._pos_joint_ids] = sample_uniform(
self._pos_ranges[:, 0], self._pos_ranges[:, 1], joint_pos_shape, device=joint_pos.device
)
# sample random joint velocities for each joint
if len(self._vel_joint_ids) > 0:
joint_vel_shape = (len(env_ids), len(self._vel_joint_ids))
joint_vel[:, self._vel_joint_ids] = sample_uniform(
self._vel_ranges[:, 0], self._vel_ranges[:, 1], joint_vel_shape, device=joint_vel.device
)
# set into the physics simulation
self._asset.write_joint_state_to_sim(joint_pos, joint_vel, env_ids=env_ids)
def reset_scene_to_default(env: BaseEnv, env_ids: torch.Tensor):
"""Reset the scene to the default state specified in the scene configuration."""
# rigid bodies
for rigid_object in env.scene.rigid_objects.values():
# obtain default and deal with the offset for env origins
default_root_state = rigid_object.data.default_root_state[env_ids].clone()
default_root_state[:, 0:3] += env.scene.env_origins[env_ids]
# set into the physics simulation
rigid_object.write_root_state_to_sim(default_root_state, env_ids=env_ids)
# articulations
for articulation_asset in env.scene.articulations.values():
# obtain default and deal with the offset for env origins
default_root_state = articulation_asset.data.default_root_state[env_ids].clone()
default_root_state[:, 0:3] += env.scene.env_origins[env_ids]
# set into the physics simulation
articulation_asset.write_root_state_to_sim(default_root_state, env_ids=env_ids)
# obtain default joint positions
default_joint_pos = articulation_asset.data.default_joint_pos[env_ids].clone()
default_joint_vel = articulation_asset.data.default_joint_vel[env_ids].clone()
# set into the physics simulation
articulation_asset.write_joint_state_to_sim(default_joint_pos, default_joint_vel, env_ids=env_ids)
| 27,752 | Python | 48.470588 | 123 | 0.682077 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/terminations.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Common functions that can be used to activate certain terminations.
The functions can be passed to the :class:`omni.isaac.orbit.managers.TerminationTermCfg` object to enable
the termination introduced by the function.
"""
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import Articulation, RigidObject
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.sensors import ContactSensor
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
from omni.isaac.orbit.managers.command_manager import CommandTerm
"""
MDP terminations.
"""
def time_out(env: RLTaskEnv) -> torch.Tensor:
"""Terminate the episode when the episode length exceeds the maximum episode length."""
return env.episode_length_buf >= env.max_episode_length
def command_resample(env: RLTaskEnv, command_name: str, num_resamples: int = 1) -> torch.Tensor:
"""Terminate the episode based on the total number of times commands have been re-sampled.
This makes the maximum episode length fluid in nature as it depends on how the commands are
sampled. It is useful in situations where delayed rewards are used :cite:`rudin2022advanced`.
"""
command: CommandTerm = env.command_manager.get_term(command_name)
return torch.logical_and((command.time_left <= env.step_dt), (command.command_counter == num_resamples))
"""
Root terminations.
"""
def bad_orientation(
env: RLTaskEnv, limit_angle: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Terminate when the asset's orientation is too far from the desired orientation limits.
This is computed by checking the angle between the projected gravity vector and the z-axis.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return torch.acos(-asset.data.projected_gravity_b[:, 2]).abs() > limit_angle
def base_height(
env: RLTaskEnv, minimum_height: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Terminate when the asset's height is below the minimum height.
Note:
This is currently only supported for flat terrains, i.e. the minimum height is in the world frame.
"""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return asset.data.root_pos_w[:, 2] < minimum_height
"""
Joint terminations.
"""
def joint_pos_limit(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Terminate when the asset's joint positions are outside of the soft joint limits."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute any violations
out_of_upper_limits = torch.any(asset.data.joint_pos > asset.data.soft_joint_pos_limits[..., 1], dim=1)
out_of_lower_limits = torch.any(asset.data.joint_pos < asset.data.soft_joint_pos_limits[..., 0], dim=1)
return torch.logical_or(out_of_upper_limits, out_of_lower_limits)
def joint_pos_manual_limit(
env: RLTaskEnv, bounds: tuple[float, float], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Terminate when the asset's joint positions are outside of the configured bounds.
Note:
This function is similar to :func:`joint_pos_limit` but allows the user to specify the bounds manually.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
if asset_cfg.joint_ids is None:
asset_cfg.joint_ids = slice(None)
# compute any violations
out_of_upper_limits = torch.any(asset.data.joint_pos[:, asset_cfg.joint_ids] > bounds[1], dim=1)
out_of_lower_limits = torch.any(asset.data.joint_pos[:, asset_cfg.joint_ids] < bounds[0], dim=1)
return torch.logical_or(out_of_upper_limits, out_of_lower_limits)
def joint_vel_limit(env: RLTaskEnv, max_velocity, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Terminate when the asset's joint velocities are outside of the soft joint limits."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# TODO read max velocities per joint from robot
return torch.any(torch.abs(asset.data.joint_vel) > max_velocity, dim=1)
def joint_torque_limit(env: RLTaskEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Terminate when torque applied on the asset's joints are are outside of the soft joint limits."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return torch.any(
torch.isclose(asset.data.computed_torques, asset.data.applied_torque),
dim=1,
)
"""
Contact sensor.
"""
def illegal_contact(env: RLTaskEnv, threshold: float, sensor_cfg: SceneEntityCfg) -> torch.Tensor:
"""Terminate when the contact force on the sensor exceeds the force threshold."""
# extract the used quantities (to enable type-hinting)
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
net_contact_forces = contact_sensor.data.net_forces_w_history
# check if any contact force exceeds the threshold
return torch.any(
torch.max(torch.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] > threshold, dim=1
)
| 5,608 | Python | 39.064285 | 119 | 0.720578 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/observations.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Common functions that can be used to create observation terms.
The functions can be passed to the :class:`omni.isaac.orbit.managers.ObservationTermCfg` object to enable
the observation introduced by the function.
"""
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
import omni.isaac.orbit.utils.math as math_utils
from omni.isaac.orbit.assets import Articulation, RigidObject
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.sensors import RayCaster
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv, RLTaskEnv
"""
Root state.
"""
def base_pos_z(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Root height in the simulation world frame."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return asset.data.root_pos_w[:, 2].unsqueeze(-1)
def base_lin_vel(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Root linear velocity in the asset's root frame."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return asset.data.root_lin_vel_b
def base_ang_vel(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Root angular velocity in the asset's root frame."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return asset.data.root_ang_vel_b
def projected_gravity(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Gravity projection on the asset's root frame."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return asset.data.projected_gravity_b
def root_pos_w(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Asset root position in the environment frame."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return asset.data.root_pos_w - env.scene.env_origins
def root_quat_w(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Asset root orientation in the environment frame."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return asset.data.root_quat_w
def root_lin_vel_w(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Asset root linear velocity in the environment frame."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return asset.data.root_lin_vel_w
def root_ang_vel_w(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Asset root angular velocity in the environment frame."""
# extract the used quantities (to enable type-hinting)
asset: RigidObject = env.scene[asset_cfg.name]
return asset.data.root_ang_vel_w
"""
Joint state.
"""
def joint_pos_rel(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""The joint positions of the asset w.r.t. the default joint positions.
NOTE: Only the joints configured in :attr:`asset_cfg.joint_ids` will have their positions returned.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return asset.data.joint_pos[:, asset_cfg.joint_ids] - asset.data.default_joint_pos[:, asset_cfg.joint_ids]
def joint_pos_norm(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""The joint positions of the asset normalized with the asset's joint limits.
NOTE: Only the joints configured in :attr:`asset_cfg.joint_ids` will have their normalized positions returned.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return math_utils.scale_transform(
asset.data.joint_pos[:, asset_cfg.joint_ids],
asset.data.soft_joint_pos_limits[:, asset_cfg.joint_ids, 0],
asset.data.soft_joint_pos_limits[:, asset_cfg.joint_ids, 1],
)
def joint_vel_rel(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")):
"""The joint velocities of the asset w.r.t. the default joint velocities.
NOTE: Only the joints configured in :attr:`asset_cfg.joint_ids` will have their velocities returned.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
return asset.data.joint_vel[:, asset_cfg.joint_ids] - asset.data.default_joint_vel[:, asset_cfg.joint_ids]
"""
Sensors.
"""
def height_scan(env: BaseEnv, sensor_cfg: SceneEntityCfg, offset: float = 0.5) -> torch.Tensor:
"""Height scan from the given sensor w.r.t. the sensor's frame.
The provided offset (Defaults to 0.5) is subtracted from the returned values.
"""
# extract the used quantities (to enable type-hinting)
sensor: RayCaster = env.scene.sensors[sensor_cfg.name]
# height scan: height = sensor_height - hit_point_z - offset
return sensor.data.pos_w[:, 2].unsqueeze(1) - sensor.data.ray_hits_w[..., 2] - offset
def body_incoming_wrench(env: BaseEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Incoming spatial wrench on bodies of an articulation in the simulation world frame.
This is the 6-D wrench (force and torque) applied to the body link by the incoming joint force.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# obtain the link incoming forces in world frame
link_incoming_forces = asset.root_physx_view.get_link_incoming_joint_force()[:, asset_cfg.body_ids]
return link_incoming_forces.view(env.num_envs, -1)
"""
Actions.
"""
def last_action(env: BaseEnv, action_name: str | None = None) -> torch.Tensor:
"""The last input action to the environment.
The name of the action term for which the action is required. If None, the
entire action tensor is returned.
"""
if action_name is None:
return env.action_manager.action
else:
return env.action_manager.get_term(action_name).raw_actions
"""
Commands.
"""
def generated_commands(env: RLTaskEnv, command_name: str) -> torch.Tensor:
"""The generated command from command term in the command manager with the given name."""
return env.command_manager.get_command(command_name)
| 6,773 | Python | 37.05618 | 114 | 0.713569 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/actions/task_space_actions.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
import carb
import omni.isaac.orbit.utils.math as math_utils
from omni.isaac.orbit.assets.articulation import Articulation
from omni.isaac.orbit.controllers.differential_ik import DifferentialIKController
from omni.isaac.orbit.managers.action_manager import ActionTerm
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
from . import actions_cfg
class DifferentialInverseKinematicsAction(ActionTerm):
r"""Inverse Kinematics action term.
This action term performs pre-processing of the raw actions using scaling transformation.
.. math::
\text{action} = \text{scaling} \times \text{input action}
\text{joint position} = J^{-} \times \text{action}
where :math:`\text{scaling}` is the scaling applied to the input action, and :math:`\text{input action}`
is the input action from the user, :math:`J` is the Jacobian over the articulation's actuated joints,
and \text{joint position} is the desired joint position command for the articulation's joints.
"""
cfg: actions_cfg.DifferentialInverseKinematicsActionCfg
"""The configuration of the action term."""
_asset: Articulation
"""The articulation asset on which the action term is applied."""
_scale: torch.Tensor
"""The scaling factor applied to the input action. Shape is (1, action_dim)."""
def __init__(self, cfg: actions_cfg.DifferentialInverseKinematicsActionCfg, env: BaseEnv):
# initialize the action term
super().__init__(cfg, env)
# resolve the joints over which the action term is applied
self._joint_ids, self._joint_names = self._asset.find_joints(self.cfg.joint_names)
self._num_joints = len(self._joint_ids)
# parse the body index
body_ids, body_names = self._asset.find_bodies(self.cfg.body_name)
if len(body_ids) != 1:
raise ValueError(
f"Expected one match for the body name: {self.cfg.body_name}. Found {len(body_ids)}: {body_names}."
)
# save only the first body index
self._body_idx = body_ids[0]
self._body_name = body_names[0]
# check if articulation is fixed-base
# if fixed-base then the jacobian for the base is not computed
# this means that number of bodies is one less than the articulation's number of bodies
if self._asset.is_fixed_base:
self._jacobi_body_idx = self._body_idx - 1
else:
self._jacobi_body_idx = self._body_idx
# log info for debugging
carb.log_info(
f"Resolved joint names for the action term {self.__class__.__name__}:"
f" {self._joint_names} [{self._joint_ids}]"
)
carb.log_info(
f"Resolved body name for the action term {self.__class__.__name__}: {self._body_name} [{self._body_idx}]"
)
# Avoid indexing across all joints for efficiency
if self._num_joints == self._asset.num_joints:
self._joint_ids = slice(None)
# create the differential IK controller
self._ik_controller = DifferentialIKController(
cfg=self.cfg.controller, num_envs=self.num_envs, device=self.device
)
# create tensors for raw and processed actions
self._raw_actions = torch.zeros(self.num_envs, self.action_dim, device=self.device)
self._processed_actions = torch.zeros_like(self.raw_actions)
# save the scale as tensors
self._scale = torch.zeros((self.num_envs, self.action_dim), device=self.device)
self._scale[:] = torch.tensor(self.cfg.scale, device=self.device)
# convert the fixed offsets to torch tensors of batched shape
if self.cfg.body_offset is not None:
self._offset_pos = torch.tensor(self.cfg.body_offset.pos, device=self.device).repeat(self.num_envs, 1)
self._offset_rot = torch.tensor(self.cfg.body_offset.rot, device=self.device).repeat(self.num_envs, 1)
else:
self._offset_pos, self._offset_rot = None, None
"""
Properties.
"""
@property
def action_dim(self) -> int:
return self._ik_controller.action_dim
@property
def raw_actions(self) -> torch.Tensor:
return self._raw_actions
@property
def processed_actions(self) -> torch.Tensor:
return self._processed_actions
"""
Operations.
"""
def process_actions(self, actions: torch.Tensor):
# store the raw actions
self._raw_actions[:] = actions
self._processed_actions[:] = self.raw_actions * self._scale
# obtain quantities from simulation
ee_pos_curr, ee_quat_curr = self._compute_frame_pose()
# set command into controller
self._ik_controller.set_command(self._processed_actions, ee_pos_curr, ee_quat_curr)
def apply_actions(self):
# obtain quantities from simulation
ee_pos_curr, ee_quat_curr = self._compute_frame_pose()
joint_pos = self._asset.data.joint_pos[:, self._joint_ids]
# compute the delta in joint-space
if ee_quat_curr.norm() != 0:
jacobian = self._compute_frame_jacobian()
joint_pos_des = self._ik_controller.compute(ee_pos_curr, ee_quat_curr, jacobian, joint_pos)
else:
joint_pos_des = joint_pos.clone()
# set the joint position command
self._asset.set_joint_position_target(joint_pos_des, self._joint_ids)
"""
Helper functions.
"""
def _compute_frame_pose(self) -> tuple[torch.Tensor, torch.Tensor]:
"""Computes the pose of the target frame in the root frame.
Returns:
A tuple of the body's position and orientation in the root frame.
"""
# obtain quantities from simulation
ee_pose_w = self._asset.data.body_state_w[:, self._body_idx, :7]
root_pose_w = self._asset.data.root_state_w[:, :7]
# compute the pose of the body in the root frame
ee_pose_b, ee_quat_b = math_utils.subtract_frame_transforms(
root_pose_w[:, 0:3], root_pose_w[:, 3:7], ee_pose_w[:, 0:3], ee_pose_w[:, 3:7]
)
# account for the offset
if self.cfg.body_offset is not None:
ee_pose_b, ee_quat_b = math_utils.combine_frame_transforms(
ee_pose_b, ee_quat_b, self._offset_pos, self._offset_rot
)
return ee_pose_b, ee_quat_b
def _compute_frame_jacobian(self):
"""Computes the geometric Jacobian of the target frame in the root frame.
This function accounts for the target frame offset and applies the necessary transformations to obtain
the right Jacobian from the parent body Jacobian.
"""
# read the parent jacobian
jacobian = self._asset.root_physx_view.get_jacobians()[:, self._jacobi_body_idx, :, self._joint_ids]
# account for the offset
if self.cfg.body_offset is not None:
# Modify the jacobian to account for the offset
# -- translational part
# v_link = v_ee + w_ee x r_link_ee = v_J_ee * q + w_J_ee * q x r_link_ee
# = (v_J_ee + w_J_ee x r_link_ee ) * q
# = (v_J_ee - r_link_ee_[x] @ w_J_ee) * q
jacobian[:, 0:3, :] += torch.bmm(-math_utils.skew_symmetric_matrix(self._offset_pos), jacobian[:, 3:, :])
# -- rotational part
# w_link = R_link_ee @ w_ee
jacobian[:, 3:, :] = torch.bmm(math_utils.matrix_from_quat(self._offset_rot), jacobian[:, 3:, :])
return jacobian
| 7,767 | Python | 40.100529 | 117 | 0.627527 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/actions/non_holonomic_actions.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
import carb
from omni.isaac.orbit.assets.articulation import Articulation
from omni.isaac.orbit.managers.action_manager import ActionTerm
from omni.isaac.orbit.utils.math import euler_xyz_from_quat
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
from . import actions_cfg
class NonHolonomicAction(ActionTerm):
r"""Non-holonomic action that maps a two dimensional action to the velocity of the robot in
the x, y and yaw directions.
This action term helps model a skid-steer robot base. The action is a 2D vector which comprises of the
forward velocity :math:`v_{B,x}` and the turning rate :\omega_{B,z}: in the base frame. Using the current
base orientation, the commands are transformed into dummy joint velocity targets as:
.. math::
\dot{q}_{0, des} &= v_{B,x} \cos(\theta) \\
\dot{q}_{1, des} &= v_{B,x} \sin(\theta) \\
\dot{q}_{2, des} &= \omega_{B,z}
where :math:`\theta` is the yaw of the 2-D base. Since the base is simulated as a dummy joint, the yaw is directly
the value of the revolute joint along z, i.e., :math:`q_2 = \theta`.
.. note::
The current implementation assumes that the base is simulated with three dummy joints (prismatic joints along x
and y, and revolute joint along z). This is because it is easier to consider the mobile base as a floating link
controlled by three dummy joints, in comparison to simulating wheels which is at times is tricky because of
friction settings.
However, the action term can be extended to support other base configurations as well.
.. tip::
For velocity control of the base with dummy mechanism, we recommend setting high damping gains to the joints.
This ensures that the base remains unperturbed from external disturbances, such as an arm mounted on the base.
"""
cfg: actions_cfg.NonHolonomicActionCfg
"""The configuration of the action term."""
_asset: Articulation
"""The articulation asset on which the action term is applied."""
_scale: torch.Tensor
"""The scaling factor applied to the input action. Shape is (1, 2)."""
_offset: torch.Tensor
"""The offset applied to the input action. Shape is (1, 2)."""
def __init__(self, cfg: actions_cfg.NonHolonomicActionCfg, env: BaseEnv):
# initialize the action term
super().__init__(cfg, env)
# parse the joint information
# -- x joint
x_joint_id, x_joint_name = self._asset.find_joints(self.cfg.x_joint_name)
if len(x_joint_id) != 1:
raise ValueError(
f"Expected a single joint match for the x joint name: {self.cfg.x_joint_name}, got {len(x_joint_id)}"
)
# -- y joint
y_joint_id, y_joint_name = self._asset.find_joints(self.cfg.y_joint_name)
if len(y_joint_id) != 1:
raise ValueError(f"Found more than one joint match for the y joint name: {self.cfg.y_joint_name}")
# -- yaw joint
yaw_joint_id, yaw_joint_name = self._asset.find_joints(self.cfg.yaw_joint_name)
if len(yaw_joint_id) != 1:
raise ValueError(f"Found more than one joint match for the yaw joint name: {self.cfg.yaw_joint_name}")
# parse the body index
self._body_idx, self._body_name = self._asset.find_bodies(self.cfg.body_name)
if len(self._body_idx) != 1:
raise ValueError(f"Found more than one body match for the body name: {self.cfg.body_name}")
# process into a list of joint ids
self._joint_ids = [x_joint_id[0], y_joint_id[0], yaw_joint_id[0]]
self._joint_names = [x_joint_name[0], y_joint_name[0], yaw_joint_name[0]]
# log info for debugging
carb.log_info(
f"Resolved joint names for the action term {self.__class__.__name__}:"
f" {self._joint_names} [{self._joint_ids}]"
)
carb.log_info(
f"Resolved body name for the action term {self.__class__.__name__}: {self._body_name} [{self._body_idx}]"
)
# create tensors for raw and processed actions
self._raw_actions = torch.zeros(self.num_envs, self.action_dim, device=self.device)
self._processed_actions = torch.zeros_like(self.raw_actions)
self._joint_vel_command = torch.zeros(self.num_envs, 3, device=self.device)
# save the scale and offset as tensors
self._scale = torch.tensor(self.cfg.scale, device=self.device).unsqueeze(0)
self._offset = torch.tensor(self.cfg.offset, device=self.device).unsqueeze(0)
"""
Properties.
"""
@property
def action_dim(self) -> int:
return 2
@property
def raw_actions(self) -> torch.Tensor:
return self._raw_actions
@property
def processed_actions(self) -> torch.Tensor:
return self._processed_actions
"""
Operations.
"""
def process_actions(self, actions):
# store the raw actions
self._raw_actions[:] = actions
self._processed_actions = self.raw_actions * self._scale + self._offset
def apply_actions(self):
# obtain current heading
quat_w = self._asset.data.body_quat_w[:, self._body_idx]
yaw_w = euler_xyz_from_quat(quat_w)[2]
# compute joint velocities targets
self._joint_vel_command[:, 0] = torch.cos(yaw_w) * self.processed_actions[:, 0] # x
self._joint_vel_command[:, 1] = torch.sin(yaw_w) * self.processed_actions[:, 0] # y
self._joint_vel_command[:, 2] = self.processed_actions[:, 1] # yaw
# set the joint velocity targets
self._asset.set_joint_velocity_target(self._joint_vel_command, joint_ids=self._joint_ids)
| 5,929 | Python | 40.760563 | 119 | 0.644291 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/actions/joint_actions.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
import carb
import omni.isaac.orbit.utils.string as string_utils
from omni.isaac.orbit.assets.articulation import Articulation
from omni.isaac.orbit.managers.action_manager import ActionTerm
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
from . import actions_cfg
class JointAction(ActionTerm):
r"""Base class for joint actions.
This action term performs pre-processing of the raw actions using affine transformations (scale and offset).
These transformations can be configured to be applied to a subset of the articulation's joints.
Mathematically, the action term is defined as:
.. math::
\text{action} = \text{offset} + \text{scaling} \times \text{input action}
where :math:`\text{action}` is the action that is sent to the articulation's actuated joints, :math:`\text{offset}`
is the offset applied to the input action, :math:`\text{scaling}` is the scaling applied to the input
action, and :math:`\text{input action}` is the input action from the user.
Based on above, this kind of action transformation ensures that the input and output actions are in the same
units and dimensions. The child classes of this action term can then map the output action to a specific
desired command of the articulation's joints (e.g. position, velocity, etc.).
"""
cfg: actions_cfg.JointActionCfg
"""The configuration of the action term."""
_asset: Articulation
"""The articulation asset on which the action term is applied."""
_scale: torch.Tensor | float
"""The scaling factor applied to the input action."""
_offset: torch.Tensor | float
"""The offset applied to the input action."""
def __init__(self, cfg: actions_cfg.JointActionCfg, env: BaseEnv) -> None:
# initialize the action term
super().__init__(cfg, env)
# resolve the joints over which the action term is applied
self._joint_ids, self._joint_names = self._asset.find_joints(self.cfg.joint_names)
self._num_joints = len(self._joint_ids)
# log the resolved joint names for debugging
carb.log_info(
f"Resolved joint names for the action term {self.__class__.__name__}:"
f" {self._joint_names} [{self._joint_ids}]"
)
# Avoid indexing across all joints for efficiency
if self._num_joints == self._asset.num_joints:
self._joint_ids = slice(None)
# create tensors for raw and processed actions
self._raw_actions = torch.zeros(self.num_envs, self.action_dim, device=self.device)
self._processed_actions = torch.zeros_like(self.raw_actions)
# parse scale
if isinstance(cfg.scale, (float, int)):
self._scale = float(cfg.scale)
elif isinstance(cfg.scale, dict):
self._scale = torch.ones(self.num_envs, self.action_dim, device=self.device)
# resolve the dictionary config
index_list, _, value_list = string_utils.resolve_matching_names_values(self.cfg.scale, self._joint_names)
self._scale[:, index_list] = torch.tensor(value_list, device=self.device)
else:
raise ValueError(f"Unsupported scale type: {type(cfg.scale)}. Supported types are float and dict.")
# parse offset
if isinstance(cfg.offset, (float, int)):
self._offset = float(cfg.offset)
elif isinstance(cfg.offset, dict):
self._offset = torch.zeros_like(self._raw_actions)
# resolve the dictionary config
index_list, _, value_list = string_utils.resolve_matching_names_values(self.cfg.offset, self._joint_names)
self._offset[:, index_list] = torch.tensor(value_list, device=self.device)
else:
raise ValueError(f"Unsupported offset type: {type(cfg.offset)}. Supported types are float and dict.")
"""
Properties.
"""
@property
def action_dim(self) -> int:
return self._num_joints
@property
def raw_actions(self) -> torch.Tensor:
return self._raw_actions
@property
def processed_actions(self) -> torch.Tensor:
return self._processed_actions
"""
Operations.
"""
def process_actions(self, actions: torch.Tensor):
# store the raw actions
self._raw_actions[:] = actions
# apply the affine transformations
self._processed_actions = self._raw_actions * self._scale + self._offset
class JointPositionAction(JointAction):
"""Joint action term that applies the processed actions to the articulation's joints as position commands."""
cfg: actions_cfg.JointPositionActionCfg
"""The configuration of the action term."""
def __init__(self, cfg: actions_cfg.JointPositionActionCfg, env: BaseEnv):
# initialize the action term
super().__init__(cfg, env)
# use default joint positions as offset
if cfg.use_default_offset:
self._offset = self._asset.data.default_joint_pos[:, self._joint_ids].clone()
def apply_actions(self):
# set position targets
self._asset.set_joint_position_target(self.processed_actions, joint_ids=self._joint_ids)
class RelativeJointPositionAction(JointAction):
r"""Joint action term that applies the processed actions to the articulation's joints as relative position commands.
Unlike :class:`JointPositionAction`, this action term applies the processed actions as relative position commands.
This means that the processed actions are added to the current joint positions of the articulation's joints
before being sent as position commands.
This means that the action applied at every step is:
.. math::
\text{applied action} = \text{current joint positions} + \text{processed actions}
where :math:`\text{current joint positions}` are the current joint positions of the articulation's joints.
"""
cfg: actions_cfg.RelativeJointPositionActionCfg
"""The configuration of the action term."""
def __init__(self, cfg: actions_cfg.RelativeJointPositionActionCfg, env: BaseEnv):
# initialize the action term
super().__init__(cfg, env)
# use zero offset for relative position
if cfg.use_zero_offset:
self._offset = 0.0
def apply_actions(self):
# add current joint positions to the processed actions
current_actions = self.processed_actions + self._asset.data.joint_pos[:, self._joint_ids]
# set position targets
self._asset.set_joint_position_target(current_actions, joint_ids=self._joint_ids)
class ExponentialMovingAverageJointPositionAction(JointPositionAction):
r"""Joint action term that applies the processed actions to the articulation's joints as exponential
moving average position commands.
Exponential moving average is a type of moving average that gives more weight to the most recent data points.
This action term applies the processed actions as moving average position action commands.
The moving average is computed as:
.. math::
\text{applied action} = \text{weight} \times \text{processed actions} + (1 - \text{weight}) \times \text{previous applied action}
where :math:`\text{weight}` is the weight for the moving average, :math:`\text{processed actions}` are the
processed actions, and :math:`\text{previous action}` is the previous action that was applied to the articulation's
joints.
In the trivial case where the weight is 1.0, the action term behaves exactly like :class:`JointPositionAction`.
On reset, the previous action is initialized to the current joint positions of the articulation's joints.
"""
cfg: actions_cfg.ExponentialMovingAverageJointPositionActionCfg
"""The configuration of the action term."""
def __init__(self, cfg: actions_cfg.ExponentialMovingAverageJointPositionActionCfg, env: BaseEnv):
# initialize the action term
super().__init__(cfg, env)
# parse and save the moving average weight
if isinstance(cfg.weight, float):
# check that the weight is in the valid range
if not 0.0 <= cfg.weight <= 1.0:
raise ValueError(f"Moving average weight must be in the range [0, 1]. Got {cfg.weight}.")
self._weight = cfg.weight
elif isinstance(cfg.weight, dict):
self._weight = torch.ones((env.num_envs, self.action_dim), device=self.device)
# resolve the dictionary config
index_list, names_list, value_list = string_utils.resolve_matching_names_values(
cfg.weight, self._joint_names
)
# check that the weights are in the valid range
for name, value in zip(names_list, value_list):
if not 0.0 <= value <= 1.0:
raise ValueError(
f"Moving average weight must be in the range [0, 1]. Got {value} for joint {name}."
)
self._weight[:, index_list] = torch.tensor(value_list, device=self.device)
else:
raise ValueError(
f"Unsupported moving average weight type: {type(cfg.weight)}. Supported types are float and dict."
)
# initialize the previous targets
self._prev_applied_actions = torch.zeros_like(self.processed_actions)
def reset(self, env_ids: Sequence[int] | None = None) -> None:
# check if specific environment ids are provided
if env_ids is None:
env_ids = slice(None)
# reset history to current joint positions
self._prev_applied_actions[env_ids, :] = self._asset.data.joint_pos[env_ids, self._joint_ids]
def apply_actions(self):
# set position targets as moving average
current_actions = self._weight * self.processed_actions
current_actions += (1.0 - self._weight) * self._prev_applied_actions
# set position targets
self._asset.set_joint_position_target(current_actions, joint_ids=self._joint_ids)
# update previous targets
self._prev_applied_actions[:] = current_actions[:]
class JointVelocityAction(JointAction):
"""Joint action term that applies the processed actions to the articulation's joints as velocity commands."""
cfg: actions_cfg.JointVelocityActionCfg
"""The configuration of the action term."""
def __init__(self, cfg: actions_cfg.JointVelocityActionCfg, env: BaseEnv):
# initialize the action term
super().__init__(cfg, env)
# use default joint velocity as offset
if cfg.use_default_offset:
self._offset = self._asset.data.default_joint_vel[:, self._joint_ids].clone()
def apply_actions(self):
# set joint velocity targets
self._asset.set_joint_velocity_target(self.processed_actions, joint_ids=self._joint_ids)
class JointEffortAction(JointAction):
"""Joint action term that applies the processed actions to the articulation's joints as effort commands."""
cfg: actions_cfg.JointEffortActionCfg
"""The configuration of the action term."""
def __init__(self, cfg: actions_cfg.JointEffortActionCfg, env: BaseEnv):
super().__init__(cfg, env)
def apply_actions(self):
# set joint effort targets
self._asset.set_joint_effort_target(self.processed_actions, joint_ids=self._joint_ids)
| 11,659 | Python | 41.246377 | 137 | 0.669783 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/actions/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Various action terms that can be used in the environment."""
from .actions_cfg import *
from .binary_joint_actions import *
from .joint_actions import *
from .non_holonomic_actions import *
| 317 | Python | 25.499998 | 63 | 0.747634 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/actions/actions_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 omni.isaac.orbit.controllers import DifferentialIKControllerCfg
from omni.isaac.orbit.managers.action_manager import ActionTerm, ActionTermCfg
from omni.isaac.orbit.utils import configclass
from . import binary_joint_actions, joint_actions, non_holonomic_actions, task_space_actions
##
# Joint actions.
##
@configclass
class JointActionCfg(ActionTermCfg):
"""Configuration for the base joint action term.
See :class:`JointAction` for more details.
"""
joint_names: list[str] = MISSING
"""List of joint names or regex expressions that the action will be mapped to."""
scale: float | dict[str, float] = 1.0
"""Scale factor for the action (float or dict of regex expressions). Defaults to 1.0."""
offset: float | dict[str, float] = 0.0
"""Offset factor for the action (float or dict of regex expressions). Defaults to 0.0."""
@configclass
class JointPositionActionCfg(JointActionCfg):
"""Configuration for the joint position action term.
See :class:`JointPositionAction` for more details.
"""
class_type: type[ActionTerm] = joint_actions.JointPositionAction
use_default_offset: bool = True
"""Whether to use default joint positions configured in the articulation asset as offset.
Defaults to True.
If True, this flag results in overwriting the values of :attr:`offset` to the default joint positions
from the articulation asset.
"""
@configclass
class RelativeJointPositionActionCfg(JointActionCfg):
"""Configuration for the relative joint position action term.
See :class:`RelativeJointPositionAction` for more details.
"""
class_type: type[ActionTerm] = joint_actions.RelativeJointPositionAction
use_zero_offset: bool = True
"""Whether to ignore the offset defined in articulation asset. Defaults to True.
If True, this flag results in overwriting the values of :attr:`offset` to zero.
"""
@configclass
class ExponentialMovingAverageJointPositionActionCfg(JointPositionActionCfg):
"""Configuration for the exponential moving average joint position action term.
See :class:`ExponentialMovingAverageJointPositionAction` for more details.
"""
class_type: type[ActionTerm] = joint_actions.ExponentialMovingAverageJointPositionAction
weight: float | dict[str, float] = 1.0
"""The weight for the moving average (float or dict of regex expressions). Defaults to 1.0.
If set to 1.0, the processed action is applied directly without any moving average window.
"""
@configclass
class JointVelocityActionCfg(JointActionCfg):
"""Configuration for the joint velocity action term.
See :class:`JointVelocityAction` for more details.
"""
class_type: type[ActionTerm] = joint_actions.JointVelocityAction
use_default_offset: bool = True
"""Whether to use default joint velocities configured in the articulation asset as offset.
Defaults to True.
This overrides the settings from :attr:`offset` if set to True.
"""
@configclass
class JointEffortActionCfg(JointActionCfg):
"""Configuration for the joint effort action term.
See :class:`JointEffortAction` for more details.
"""
class_type: type[ActionTerm] = joint_actions.JointEffortAction
##
# Gripper actions.
##
@configclass
class BinaryJointActionCfg(ActionTermCfg):
"""Configuration for the base binary joint action term.
See :class:`BinaryJointAction` for more details.
"""
joint_names: list[str] = MISSING
"""List of joint names or regex expressions that the action will be mapped to."""
open_command_expr: dict[str, float] = MISSING
"""The joint command to move to *open* configuration."""
close_command_expr: dict[str, float] = MISSING
"""The joint command to move to *close* configuration."""
@configclass
class BinaryJointPositionActionCfg(BinaryJointActionCfg):
"""Configuration for the binary joint position action term.
See :class:`BinaryJointPositionAction` for more details.
"""
class_type: type[ActionTerm] = binary_joint_actions.BinaryJointPositionAction
@configclass
class BinaryJointVelocityActionCfg(BinaryJointActionCfg):
"""Configuration for the binary joint velocity action term.
See :class:`BinaryJointVelocityAction` for more details.
"""
class_type: type[ActionTerm] = binary_joint_actions.BinaryJointVelocityAction
##
# Non-holonomic actions.
##
@configclass
class NonHolonomicActionCfg(ActionTermCfg):
"""Configuration for the non-holonomic action term with dummy joints at the base.
See :class:`NonHolonomicAction` for more details.
"""
class_type: type[ActionTerm] = non_holonomic_actions.NonHolonomicAction
body_name: str = MISSING
"""Name of the body which has the dummy mechanism connected to."""
x_joint_name: str = MISSING
"""The dummy joint name in the x direction."""
y_joint_name: str = MISSING
"""The dummy joint name in the y direction."""
yaw_joint_name: str = MISSING
"""The dummy joint name in the yaw direction."""
scale: tuple[float, float] = (1.0, 1.0)
"""Scale factor for the action. Defaults to (1.0, 1.0)."""
offset: tuple[float, float] = (0.0, 0.0)
"""Offset factor for the action. Defaults to (0.0, 0.0)."""
##
# Task-space Actions.
##
@configclass
class DifferentialInverseKinematicsActionCfg(ActionTermCfg):
"""Configuration for inverse differential kinematics action term.
See :class:`DifferentialInverseKinematicsAction` for more details.
"""
@configclass
class OffsetCfg:
"""The offset pose from parent frame to child frame.
On many robots, end-effector frames are fictitious frames that do not have a corresponding
rigid body. In such cases, it is easier to define this transform w.r.t. their parent rigid body.
For instance, for the Franka Emika arm, the end-effector is defined at an offset to the the
"panda_hand" frame.
"""
pos: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Translation w.r.t. the parent 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)`` w.r.t. the parent frame. Defaults to (1.0, 0.0, 0.0, 0.0)."""
class_type: type[ActionTerm] = task_space_actions.DifferentialInverseKinematicsAction
joint_names: list[str] = MISSING
"""List of joint names or regex expressions that the action will be mapped to."""
body_name: str = MISSING
"""Name of the body or frame for which IK is performed."""
body_offset: OffsetCfg | None = None
"""Offset of target frame w.r.t. to the body frame. Defaults to None, in which case no offset is applied."""
scale: float | tuple[float, ...] = 1.0
"""Scale factor for the action. Defaults to 1.0."""
controller: DifferentialIKControllerCfg = MISSING
"""The configuration for the differential IK controller."""
| 7,163 | Python | 31.563636 | 112 | 0.710596 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/actions/binary_joint_actions.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
import carb
import omni.isaac.orbit.utils.string as string_utils
from omni.isaac.orbit.assets.articulation import Articulation
from omni.isaac.orbit.managers.action_manager import ActionTerm
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
from . import actions_cfg
class BinaryJointAction(ActionTerm):
"""Base class for binary joint actions.
This action term maps a binary action to the *open* or *close* joint configurations. These configurations are
specified through the :class:`BinaryJointActionCfg` object. If the input action is a float vector, the action
is considered binary based on the sign of the action values.
Based on above, we follow the following convention for the binary action:
1. Open action: 1 (bool) or positive values (float).
2. Close action: 0 (bool) or negative values (float).
The action term can mostly be used for gripper actions, where the gripper is either open or closed. This
helps in devising a mimicking mechanism for the gripper, since in simulation it is often not possible to
add such constraints to the gripper.
"""
cfg: actions_cfg.BinaryJointActionCfg
"""The configuration of the action term."""
_asset: Articulation
"""The articulation asset on which the action term is applied."""
def __init__(self, cfg: actions_cfg.BinaryJointActionCfg, env: BaseEnv) -> None:
# initialize the action term
super().__init__(cfg, env)
# resolve the joints over which the action term is applied
self._joint_ids, self._joint_names = self._asset.find_joints(self.cfg.joint_names)
self._num_joints = len(self._joint_ids)
# log the resolved joint names for debugging
carb.log_info(
f"Resolved joint names for the action term {self.__class__.__name__}:"
f" {self._joint_names} [{self._joint_ids}]"
)
# create tensors for raw and processed actions
self._raw_actions = torch.zeros(self.num_envs, 1, device=self.device)
self._processed_actions = torch.zeros(self.num_envs, self._num_joints, device=self.device)
# parse open command
self._open_command = torch.zeros(self._num_joints, device=self.device)
index_list, name_list, value_list = string_utils.resolve_matching_names_values(
self.cfg.open_command_expr, self._joint_names
)
if len(index_list) != self._num_joints:
raise ValueError(
f"Could not resolve all joints for the action term. Missing: {set(self._joint_names) - set(name_list)}"
)
self._open_command[index_list] = torch.tensor(value_list, device=self.device)
# parse close command
self._close_command = torch.zeros_like(self._open_command)
index_list, name_list, value_list = string_utils.resolve_matching_names_values(
self.cfg.close_command_expr, self._joint_names
)
if len(index_list) != self._num_joints:
raise ValueError(
f"Could not resolve all joints for the action term. Missing: {set(self._joint_names) - set(name_list)}"
)
self._close_command[index_list] = torch.tensor(value_list, device=self.device)
"""
Properties.
"""
@property
def action_dim(self) -> int:
return 1
@property
def raw_actions(self) -> torch.Tensor:
return self._raw_actions
@property
def processed_actions(self) -> torch.Tensor:
return self._processed_actions
"""
Operations.
"""
def process_actions(self, actions: torch.Tensor):
# store the raw actions
self._raw_actions[:] = actions
# compute the binary mask
if actions.dtype == torch.bool:
# true: close, false: open
binary_mask = actions == 0
else:
# true: close, false: open
binary_mask = actions < 0
# compute the command
self._processed_actions = torch.where(binary_mask, self._close_command, self._open_command)
class BinaryJointPositionAction(BinaryJointAction):
"""Binary joint action that sets the binary action into joint position targets."""
cfg: actions_cfg.BinaryJointPositionActionCfg
"""The configuration of the action term."""
def apply_actions(self):
self._asset.set_joint_position_target(self._processed_actions, joint_ids=self._joint_ids)
class BinaryJointVelocityAction(BinaryJointAction):
"""Binary joint action that sets the binary action into joint velocity targets."""
cfg: actions_cfg.BinaryJointVelocityActionCfg
"""The configuration of the action term."""
def apply_actions(self):
self._asset.set_joint_velocity_target(self._processed_actions, joint_ids=self._joint_ids)
| 5,021 | Python | 35.656934 | 119 | 0.667994 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/commands/commands_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import math
from dataclasses import MISSING
from omni.isaac.orbit.managers import CommandTermCfg
from omni.isaac.orbit.utils import configclass
from .null_command import NullCommand
from .pose_2d_command import TerrainBasedPose2dCommand, UniformPose2dCommand
from .pose_command import UniformPoseCommand
from .velocity_command import NormalVelocityCommand, UniformVelocityCommand
@configclass
class NullCommandCfg(CommandTermCfg):
"""Configuration for the null command generator."""
class_type: type = NullCommand
def __post_init__(self):
"""Post initialization."""
# set the resampling time range to infinity to avoid resampling
self.resampling_time_range = (math.inf, math.inf)
@configclass
class UniformVelocityCommandCfg(CommandTermCfg):
"""Configuration for the uniform velocity command generator."""
class_type: type = UniformVelocityCommand
asset_name: str = MISSING
"""Name of the asset in the environment for which the commands are generated."""
heading_command: bool = MISSING
"""Whether to use heading command or angular velocity command.
If True, the angular velocity command is computed from the heading error, where the
target heading is sampled uniformly from provided range. Otherwise, the angular velocity
command is sampled uniformly from provided range.
"""
heading_control_stiffness: float = MISSING
"""Scale factor to convert the heading error to angular velocity command."""
rel_standing_envs: float = MISSING
"""Probability threshold for environments where the robots that are standing still."""
rel_heading_envs: float = MISSING
"""Probability threshold for environments where the robots follow the heading-based angular velocity command
(the others follow the sampled angular velocity command)."""
@configclass
class Ranges:
"""Uniform distribution ranges for the velocity commands."""
lin_vel_x: tuple[float, float] = MISSING # min max [m/s]
lin_vel_y: tuple[float, float] = MISSING # min max [m/s]
ang_vel_z: tuple[float, float] = MISSING # min max [rad/s]
heading: tuple[float, float] = MISSING # min max [rad]
ranges: Ranges = MISSING
"""Distribution ranges for the velocity commands."""
@configclass
class NormalVelocityCommandCfg(UniformVelocityCommandCfg):
"""Configuration for the normal velocity command generator."""
class_type: type = NormalVelocityCommand
heading_command: bool = False # --> we don't use heading command for normal velocity command.
@configclass
class Ranges:
"""Normal distribution ranges for the velocity commands."""
mean_vel: tuple[float, float, float] = MISSING
"""Mean velocity for the normal distribution.
The tuple contains the mean linear-x, linear-y, and angular-z velocity.
"""
std_vel: tuple[float, float, float] = MISSING
"""Standard deviation for the normal distribution.
The tuple contains the standard deviation linear-x, linear-y, and angular-z velocity.
"""
zero_prob: tuple[float, float, float] = MISSING
"""Probability of zero velocity for the normal distribution.
The tuple contains the probability of zero linear-x, linear-y, and angular-z velocity.
"""
ranges: Ranges = MISSING
"""Distribution ranges for the velocity commands."""
@configclass
class UniformPoseCommandCfg(CommandTermCfg):
"""Configuration for uniform pose command generator."""
class_type: type = UniformPoseCommand
asset_name: str = MISSING
"""Name of the asset in the environment for which the commands are generated."""
body_name: str = MISSING
"""Name of the body in the asset for which the commands are generated."""
@configclass
class Ranges:
"""Uniform distribution ranges for the pose commands."""
pos_x: tuple[float, float] = MISSING # min max [m]
pos_y: tuple[float, float] = MISSING # min max [m]
pos_z: tuple[float, float] = MISSING # min max [m]
roll: tuple[float, float] = MISSING # min max [rad]
pitch: tuple[float, float] = MISSING # min max [rad]
yaw: tuple[float, float] = MISSING # min max [rad]
ranges: Ranges = MISSING
"""Ranges for the commands."""
@configclass
class UniformPose2dCommandCfg(CommandTermCfg):
"""Configuration for the uniform 2D-pose command generator."""
class_type: type = UniformPose2dCommand
asset_name: str = MISSING
"""Name of the asset in the environment for which the commands are generated."""
simple_heading: bool = MISSING
"""Whether to use simple heading or not.
If True, the heading is in the direction of the target position.
"""
@configclass
class Ranges:
"""Uniform distribution ranges for the position commands."""
pos_x: tuple[float, float] = MISSING
"""Range for the x position (in m)."""
pos_y: tuple[float, float] = MISSING
"""Range for the y position (in m)."""
heading: tuple[float, float] = MISSING
"""Heading range for the position commands (in rad).
Used only if :attr:`simple_heading` is False.
"""
ranges: Ranges = MISSING
"""Distribution ranges for the position commands."""
@configclass
class TerrainBasedPose2dCommandCfg(UniformPose2dCommandCfg):
"""Configuration for the terrain-based position command generator."""
class_type = TerrainBasedPose2dCommand
@configclass
class Ranges:
"""Uniform distribution ranges for the position commands."""
heading: tuple[float, float] = MISSING
"""Heading range for the position commands (in rad).
Used only if :attr:`simple_heading` is False.
"""
ranges: Ranges = MISSING
"""Distribution ranges for the sampled commands."""
| 6,065 | Python | 33.465909 | 112 | 0.688541 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/commands/pose_2d_command.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing command generators for the 2D-pose for locomotion tasks."""
from __future__ import annotations
import torch
from collections.abc import Sequence
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import CommandTerm
from omni.isaac.orbit.markers import VisualizationMarkers
from omni.isaac.orbit.markers.config import GREEN_ARROW_X_MARKER_CFG
from omni.isaac.orbit.terrains import TerrainImporter
from omni.isaac.orbit.utils.math import quat_from_euler_xyz, quat_rotate_inverse, wrap_to_pi, yaw_quat
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
from .commands_cfg import TerrainBasedPose2dCommandCfg, UniformPose2dCommandCfg
class UniformPose2dCommand(CommandTerm):
"""Command generator that generates pose commands containing a 3-D position and heading.
The command generator samples uniform 2D positions around the environment origin. It sets
the height of the position command to the default root height of the robot. The heading
command is either set to point towards the target or is sampled uniformly.
This can be configured through the :attr:`Pose2dCommandCfg.simple_heading` parameter in
the configuration.
"""
cfg: UniformPose2dCommandCfg
"""Configuration for the command generator."""
def __init__(self, cfg: UniformPose2dCommandCfg, env: BaseEnv):
"""Initialize the command generator class.
Args:
cfg: The configuration parameters for the command generator.
env: The environment object.
"""
# initialize the base class
super().__init__(cfg, env)
# obtain the robot and terrain assets
# -- robot
self.robot: Articulation = env.scene[cfg.asset_name]
# crete buffers to store the command
# -- commands: (x, y, z, heading)
self.pos_command_w = torch.zeros(self.num_envs, 3, device=self.device)
self.heading_command_w = torch.zeros(self.num_envs, device=self.device)
self.pos_command_b = torch.zeros_like(self.pos_command_w)
self.heading_command_b = torch.zeros_like(self.heading_command_w)
# -- metrics
self.metrics["error_pos"] = torch.zeros(self.num_envs, device=self.device)
self.metrics["error_heading"] = torch.zeros(self.num_envs, device=self.device)
def __str__(self) -> str:
msg = "PositionCommand:\n"
msg += f"\tCommand dimension: {tuple(self.command.shape[1:])}\n"
msg += f"\tResampling time range: {self.cfg.resampling_time_range}"
return msg
"""
Properties
"""
@property
def command(self) -> torch.Tensor:
"""The desired 2D-pose in base frame. Shape is (num_envs, 4)."""
return torch.cat([self.pos_command_b, self.heading_command_b.unsqueeze(1)], dim=1)
"""
Implementation specific functions.
"""
def _update_metrics(self):
# logs data
self.metrics["error_pos_2d"] = torch.norm(self.pos_command_w[:, :2] - self.robot.data.root_pos_w[:, :2], dim=1)
self.metrics["error_heading"] = torch.abs(wrap_to_pi(self.heading_command_w - self.robot.data.heading_w))
def _resample_command(self, env_ids: Sequence[int]):
# obtain env origins for the environments
self.pos_command_w[env_ids] = self._env.scene.env_origins[env_ids]
# offset the position command by the current root position
r = torch.empty(len(env_ids), device=self.device)
self.pos_command_w[env_ids, 0] += r.uniform_(*self.cfg.ranges.pos_x)
self.pos_command_w[env_ids, 1] += r.uniform_(*self.cfg.ranges.pos_y)
self.pos_command_w[env_ids, 2] += self.robot.data.default_root_state[env_ids, 2]
if self.cfg.simple_heading:
# set heading command to point towards target
target_vec = self.pos_command_w[env_ids] - self.robot.data.root_pos_w[env_ids]
target_direction = torch.atan2(target_vec[:, 1], target_vec[:, 0])
flipped_target_direction = wrap_to_pi(target_direction + torch.pi)
# compute errors to find the closest direction to the current heading
# this is done to avoid the discontinuity at the -pi/pi boundary
curr_to_target = wrap_to_pi(target_direction - self.robot.data.heading_w[env_ids]).abs()
curr_to_flipped_target = wrap_to_pi(flipped_target_direction - self.robot.data.heading_w[env_ids]).abs()
# set the heading command to the closest direction
self.heading_command_w[env_ids] = torch.where(
curr_to_target < curr_to_flipped_target,
target_direction,
flipped_target_direction,
)
else:
# random heading command
self.heading_command_w[env_ids] = r.uniform_(*self.cfg.ranges.heading)
def _update_command(self):
"""Re-target the position command to the current root state."""
target_vec = self.pos_command_w - self.robot.data.root_pos_w[:, :3]
self.pos_command_b[:] = quat_rotate_inverse(yaw_quat(self.robot.data.root_quat_w), target_vec)
self.heading_command_b[:] = wrap_to_pi(self.heading_command_w - self.robot.data.heading_w)
def _set_debug_vis_impl(self, debug_vis: bool):
# create markers if necessary for the first tome
if debug_vis:
if not hasattr(self, "arrow_goal_visualizer"):
marker_cfg = GREEN_ARROW_X_MARKER_CFG.copy()
marker_cfg.markers["arrow"].scale = (0.2, 0.2, 0.8)
marker_cfg.prim_path = "/Visuals/Command/pose_goal"
self.arrow_goal_visualizer = VisualizationMarkers(marker_cfg)
# set their visibility to true
self.arrow_goal_visualizer.set_visibility(True)
else:
if hasattr(self, "arrow_goal_visualizer"):
self.arrow_goal_visualizer.set_visibility(False)
def _debug_vis_callback(self, event):
# update the box marker
self.arrow_goal_visualizer.visualize(
translations=self.pos_command_w,
orientations=quat_from_euler_xyz(
torch.zeros_like(self.heading_command_w),
torch.zeros_like(self.heading_command_w),
self.heading_command_w,
),
)
class TerrainBasedPose2dCommand(UniformPose2dCommand):
"""Command generator that generates pose commands based on the terrain.
This command generator samples the position commands from the valid patches of the terrain.
The heading commands are either set to point towards the target or are sampled uniformly.
It expects the terrain to have a valid flat patches under the key 'target'.
"""
cfg: TerrainBasedPose2dCommandCfg
"""Configuration for the command generator."""
def __init__(self, cfg: TerrainBasedPose2dCommandCfg, env: BaseEnv):
# initialize the base class
super().__init__(cfg, env)
# obtain the terrain asset
self.terrain: TerrainImporter = env.scene["terrain"]
# obtain the valid targets from the terrain
if "target" not in self.terrain.flat_patches:
raise RuntimeError(
"The terrain-based command generator requires a valid flat patch under 'target' in the terrain."
f" Found: {list(self.terrain.flat_patches.keys())}"
)
# valid targets: (terrain_level, terrain_type, num_patches, 3)
self.valid_targets: torch.Tensor = self.terrain.flat_patches["target"]
def _resample_command(self, env_ids: Sequence[int]):
# sample new position targets from the terrain
ids = torch.randint(0, self.valid_targets.shape[2], size=(len(env_ids),), device=self.device)
self.pos_command_w[env_ids] = self.valid_targets[
self.terrain.terrain_levels[env_ids], self.terrain.terrain_types[env_ids], ids
]
# offset the position command by the current root height
self.pos_command_w[env_ids, 2] += self.robot.data.default_root_state[env_ids, 2]
if self.cfg.simple_heading:
# set heading command to point towards target
target_vec = self.pos_command_w[env_ids] - self.robot.data.root_pos_w[env_ids]
target_direction = torch.atan2(target_vec[:, 1], target_vec[:, 0])
flipped_target_direction = wrap_to_pi(target_direction + torch.pi)
# compute errors to find the closest direction to the current heading
# this is done to avoid the discontinuity at the -pi/pi boundary
curr_to_target = wrap_to_pi(target_direction - self.robot.data.heading_w[env_ids]).abs()
curr_to_flipped_target = wrap_to_pi(flipped_target_direction - self.robot.data.heading_w[env_ids]).abs()
# set the heading command to the closest direction
self.heading_command_w[env_ids] = torch.where(
curr_to_target < curr_to_flipped_target,
target_direction,
flipped_target_direction,
)
else:
# random heading command
r = torch.empty(len(env_ids), device=self.device)
self.heading_command_w[env_ids] = r.uniform_(*self.cfg.ranges.heading)
| 9,435 | Python | 44.365384 | 119 | 0.649921 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/commands/velocity_command.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing command generators for the velocity-based locomotion task."""
from __future__ import annotations
import torch
from collections.abc import Sequence
from typing import TYPE_CHECKING
import omni.isaac.orbit.utils.math as math_utils
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import CommandTerm
from omni.isaac.orbit.markers import VisualizationMarkers
from omni.isaac.orbit.markers.config import BLUE_ARROW_X_MARKER_CFG, GREEN_ARROW_X_MARKER_CFG
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
from .commands_cfg import NormalVelocityCommandCfg, UniformVelocityCommandCfg
class UniformVelocityCommand(CommandTerm):
r"""Command generator that generates a velocity command in SE(2) from uniform distribution.
The command comprises of a linear velocity in x and y direction and an angular velocity around
the z-axis. It is given in the robot's base frame.
If the :attr:`cfg.heading_command` flag is set to True, the angular velocity is computed from the heading
error similar to doing a proportional control on the heading error. The target heading is sampled uniformly
from the provided range. Otherwise, the angular velocity is sampled uniformly from the provided range.
Mathematically, the angular velocity is computed as follows from the heading command:
.. math::
\omega_z = \frac{1}{2} \text{wrap_to_pi}(\theta_{\text{target}} - \theta_{\text{current}})
"""
cfg: UniformVelocityCommandCfg
"""The configuration of the command generator."""
def __init__(self, cfg: UniformVelocityCommandCfg, env: BaseEnv):
"""Initialize the command generator.
Args:
cfg: The configuration of the command generator.
env: The environment.
"""
# initialize the base class
super().__init__(cfg, env)
# obtain the robot asset
# -- robot
self.robot: Articulation = env.scene[cfg.asset_name]
# crete buffers to store the command
# -- command: x vel, y vel, yaw vel, heading
self.vel_command_b = torch.zeros(self.num_envs, 3, device=self.device)
self.heading_target = torch.zeros(self.num_envs, device=self.device)
self.is_heading_env = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device)
self.is_standing_env = torch.zeros_like(self.is_heading_env)
# -- metrics
self.metrics["error_vel_xy"] = torch.zeros(self.num_envs, device=self.device)
self.metrics["error_vel_yaw"] = torch.zeros(self.num_envs, device=self.device)
def __str__(self) -> str:
"""Return a string representation of the command generator."""
msg = "UniformVelocityCommand:\n"
msg += f"\tCommand dimension: {tuple(self.command.shape[1:])}\n"
msg += f"\tResampling time range: {self.cfg.resampling_time_range}\n"
msg += f"\tHeading command: {self.cfg.heading_command}\n"
if self.cfg.heading_command:
msg += f"\tHeading probability: {self.cfg.rel_heading_envs}\n"
msg += f"\tStanding probability: {self.cfg.rel_standing_envs}"
return msg
"""
Properties
"""
@property
def command(self) -> torch.Tensor:
"""The desired base velocity command in the base frame. Shape is (num_envs, 3)."""
return self.vel_command_b
"""
Implementation specific functions.
"""
def _update_metrics(self):
# time for which the command was executed
max_command_time = self.cfg.resampling_time_range[1]
max_command_step = max_command_time / self._env.step_dt
# logs data
self.metrics["error_vel_xy"] += (
torch.norm(self.vel_command_b[:, :2] - self.robot.data.root_lin_vel_b[:, :2], dim=-1) / max_command_step
)
self.metrics["error_vel_yaw"] += (
torch.abs(self.vel_command_b[:, 2] - self.robot.data.root_ang_vel_b[:, 2]) / max_command_step
)
def _resample_command(self, env_ids: Sequence[int]):
# sample velocity commands
r = torch.empty(len(env_ids), device=self.device)
# -- linear velocity - x direction
self.vel_command_b[env_ids, 0] = r.uniform_(*self.cfg.ranges.lin_vel_x)
# -- linear velocity - y direction
self.vel_command_b[env_ids, 1] = r.uniform_(*self.cfg.ranges.lin_vel_y)
# -- ang vel yaw - rotation around z
self.vel_command_b[env_ids, 2] = r.uniform_(*self.cfg.ranges.ang_vel_z)
# heading target
if self.cfg.heading_command:
self.heading_target[env_ids] = r.uniform_(*self.cfg.ranges.heading)
# update heading envs
self.is_heading_env[env_ids] = r.uniform_(0.0, 1.0) <= self.cfg.rel_heading_envs
# update standing envs
self.is_standing_env[env_ids] = r.uniform_(0.0, 1.0) <= self.cfg.rel_standing_envs
def _update_command(self):
"""Post-processes the velocity command.
This function sets velocity command to zero for standing environments and computes angular
velocity from heading direction if the heading_command flag is set.
"""
# Compute angular velocity from heading direction
if self.cfg.heading_command:
# resolve indices of heading envs
env_ids = self.is_heading_env.nonzero(as_tuple=False).flatten()
# compute angular velocity
heading_error = math_utils.wrap_to_pi(self.heading_target[env_ids] - self.robot.data.heading_w[env_ids])
self.vel_command_b[env_ids, 2] = torch.clip(
self.cfg.heading_control_stiffness * heading_error,
min=self.cfg.ranges.ang_vel_z[0],
max=self.cfg.ranges.ang_vel_z[1],
)
# Enforce standing (i.e., zero velocity command) for standing envs
# TODO: check if conversion is needed
standing_env_ids = self.is_standing_env.nonzero(as_tuple=False).flatten()
self.vel_command_b[standing_env_ids, :] = 0.0
def _set_debug_vis_impl(self, debug_vis: bool):
# set visibility of markers
# note: parent only deals with callbacks. not their visibility
if debug_vis:
# create markers if necessary for the first tome
if not hasattr(self, "base_vel_goal_visualizer"):
# -- goal
marker_cfg = GREEN_ARROW_X_MARKER_CFG.copy()
marker_cfg.prim_path = "/Visuals/Command/velocity_goal"
marker_cfg.markers["arrow"].scale = (0.5, 0.5, 0.5)
self.base_vel_goal_visualizer = VisualizationMarkers(marker_cfg)
# -- current
marker_cfg = BLUE_ARROW_X_MARKER_CFG.copy()
marker_cfg.prim_path = "/Visuals/Command/velocity_current"
marker_cfg.markers["arrow"].scale = (0.5, 0.5, 0.5)
self.base_vel_visualizer = VisualizationMarkers(marker_cfg)
# set their visibility to true
self.base_vel_goal_visualizer.set_visibility(True)
self.base_vel_visualizer.set_visibility(True)
else:
if hasattr(self, "base_vel_goal_visualizer"):
self.base_vel_goal_visualizer.set_visibility(False)
self.base_vel_visualizer.set_visibility(False)
def _debug_vis_callback(self, event):
# get marker location
# -- base state
base_pos_w = self.robot.data.root_pos_w.clone()
base_pos_w[:, 2] += 0.5
# -- resolve the scales and quaternions
vel_des_arrow_scale, vel_des_arrow_quat = self._resolve_xy_velocity_to_arrow(self.command[:, :2])
vel_arrow_scale, vel_arrow_quat = self._resolve_xy_velocity_to_arrow(self.robot.data.root_lin_vel_b[:, :2])
# display markers
self.base_vel_goal_visualizer.visualize(base_pos_w, vel_des_arrow_quat, vel_des_arrow_scale)
self.base_vel_visualizer.visualize(base_pos_w, vel_arrow_quat, vel_arrow_scale)
"""
Internal helpers.
"""
def _resolve_xy_velocity_to_arrow(self, xy_velocity: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Converts the XY base velocity command to arrow direction rotation."""
# obtain default scale of the marker
default_scale = self.base_vel_goal_visualizer.cfg.markers["arrow"].scale
# arrow-scale
arrow_scale = torch.tensor(default_scale, device=self.device).repeat(xy_velocity.shape[0], 1)
arrow_scale[:, 0] *= torch.linalg.norm(xy_velocity, dim=1) * 3.0
# arrow-direction
heading_angle = torch.atan2(xy_velocity[:, 1], xy_velocity[:, 0])
zeros = torch.zeros_like(heading_angle)
arrow_quat = math_utils.quat_from_euler_xyz(zeros, zeros, heading_angle)
# convert everything back from base to world frame
base_quat_w = self.robot.data.root_quat_w
arrow_quat = math_utils.quat_mul(base_quat_w, arrow_quat)
return arrow_scale, arrow_quat
class NormalVelocityCommand(UniformVelocityCommand):
"""Command generator that generates a velocity command in SE(2) from a normal distribution.
The command comprises of a linear velocity in x and y direction and an angular velocity around
the z-axis. It is given in the robot's base frame.
The command is sampled from a normal distribution with mean and standard deviation specified in
the configuration. With equal probability, the sign of the individual components is flipped.
"""
cfg: NormalVelocityCommandCfg
"""The command generator configuration."""
def __init__(self, cfg: NormalVelocityCommandCfg, env: object):
"""Initializes the command generator.
Args:
cfg: The command generator configuration.
env: The environment.
"""
super().__init__(self, cfg, env)
# create buffers for zero commands envs
self.is_zero_vel_x_env = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device)
self.is_zero_vel_y_env = torch.zeros_like(self.is_zero_vel_x_env)
self.is_zero_vel_yaw_env = torch.zeros_like(self.is_zero_vel_x_env)
def __str__(self) -> str:
"""Return a string representation of the command generator."""
msg = "NormalVelocityCommand:\n"
msg += f"\tCommand dimension: {tuple(self.command.shape[1:])}\n"
msg += f"\tResampling time range: {self.cfg.resampling_time_range}\n"
msg += f"\tStanding probability: {self.cfg.rel_standing_envs}"
return msg
def _resample_command(self, env_ids):
# sample velocity commands
r = torch.empty(len(env_ids), device=self.device)
# -- linear velocity - x direction
self.vel_command_b[env_ids, 0] = r.normal_(mean=self.cfg.ranges.mean_vel[0], std=self.cfg.ranges.std_vel[0])
self.vel_command_b[env_ids, 0] *= torch.where(r.uniform_(0.0, 1.0) <= 0.5, 1.0, -1.0)
# -- linear velocity - y direction
self.vel_command_b[env_ids, 1] = r.normal_(mean=self.cfg.ranges.mean_vel[1], std=self.cfg.ranges.std_vel[1])
self.vel_command_b[env_ids, 1] *= torch.where(r.uniform_(0.0, 1.0) <= 0.5, 1.0, -1.0)
# -- angular velocity - yaw direction
self.vel_command_b[env_ids, 2] = r.normal_(mean=self.cfg.ranges.mean_vel[2], std=self.cfg.ranges.std_vel[2])
self.vel_command_b[env_ids, 2] *= torch.where(r.uniform_(0.0, 1.0) <= 0.5, 1.0, -1.0)
# update element wise zero velocity command
# TODO what is zero prob ?
self.is_zero_vel_x_env[env_ids] = r.uniform_(0.0, 1.0) <= self.cfg.ranges.zero_prob[0]
self.is_zero_vel_y_env[env_ids] = r.uniform_(0.0, 1.0) <= self.cfg.ranges.zero_prob[1]
self.is_zero_vel_yaw_env[env_ids] = r.uniform_(0.0, 1.0) <= self.cfg.ranges.zero_prob[2]
# update standing envs
self.is_standing_env[env_ids] = r.uniform_(0.0, 1.0) <= self.cfg.rel_standing_envs
def _update_command(self):
"""Sets velocity command to zero for standing envs."""
# Enforce standing (i.e., zero velocity command) for standing envs
standing_env_ids = self.is_standing_env.nonzero(as_tuple=False).flatten() # TODO check if conversion is needed
self.vel_command_b[standing_env_ids, :] = 0.0
# Enforce zero velocity for individual elements
# TODO: check if conversion is needed
zero_vel_x_env_ids = self.is_zero_vel_x_env.nonzero(as_tuple=False).flatten()
zero_vel_y_env_ids = self.is_zero_vel_y_env.nonzero(as_tuple=False).flatten()
zero_vel_yaw_env_ids = self.is_zero_vel_yaw_env.nonzero(as_tuple=False).flatten()
self.vel_command_b[zero_vel_x_env_ids, 0] = 0.0
self.vel_command_b[zero_vel_y_env_ids, 1] = 0.0
self.vel_command_b[zero_vel_yaw_env_ids, 2] = 0.0
| 12,959 | Python | 46.29927 | 119 | 0.641408 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/commands/pose_command.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing command generators for pose tracking."""
from __future__ import annotations
import torch
from collections.abc import Sequence
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import CommandTerm
from omni.isaac.orbit.markers import VisualizationMarkers
from omni.isaac.orbit.markers.config import FRAME_MARKER_CFG
from omni.isaac.orbit.utils.math import combine_frame_transforms, compute_pose_error, quat_from_euler_xyz
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
from .commands_cfg import UniformPoseCommandCfg
class UniformPoseCommand(CommandTerm):
"""Command generator for generating pose commands uniformly.
The command generator generates poses by sampling positions uniformly within specified
regions in cartesian space. For orientation, it samples uniformly the euler angles
(roll-pitch-yaw) and converts them into quaternion representation (w, x, y, z).
The position and orientation commands are generated in the base frame of the robot, and not the
simulation world frame. This means that users need to handle the transformation from the
base frame to the simulation world frame themselves.
.. caution::
Sampling orientations uniformly is not strictly the same as sampling euler angles uniformly.
This is because rotations are defined by 3D non-Euclidean space, and the mapping
from euler angles to rotations is not one-to-one.
"""
cfg: UniformPoseCommandCfg
"""Configuration for the command generator."""
def __init__(self, cfg: UniformPoseCommandCfg, env: BaseEnv):
"""Initialize the command generator class.
Args:
cfg: The configuration parameters for the command generator.
env: The environment object.
"""
# initialize the base class
super().__init__(cfg, env)
# extract the robot and body index for which the command is generated
self.robot: Articulation = env.scene[cfg.asset_name]
self.body_idx = self.robot.find_bodies(cfg.body_name)[0][0]
# create buffers
# -- commands: (x, y, z, qw, qx, qy, qz) in root frame
self.pose_command_b = torch.zeros(self.num_envs, 7, device=self.device)
self.pose_command_b[:, 3] = 1.0
self.pose_command_w = torch.zeros_like(self.pose_command_b)
# -- metrics
self.metrics["position_error"] = torch.zeros(self.num_envs, device=self.device)
self.metrics["orientation_error"] = torch.zeros(self.num_envs, device=self.device)
def __str__(self) -> str:
msg = "UniformPoseCommand:\n"
msg += f"\tCommand dimension: {tuple(self.command.shape[1:])}\n"
msg += f"\tResampling time range: {self.cfg.resampling_time_range}\n"
return msg
"""
Properties
"""
@property
def command(self) -> torch.Tensor:
"""The desired pose command. Shape is (num_envs, 7).
The first three elements correspond to the position, followed by the quaternion orientation in (w, x, y, z).
"""
return self.pose_command_b
"""
Implementation specific functions.
"""
def _update_metrics(self):
# transform command from base frame to simulation world frame
self.pose_command_w[:, :3], self.pose_command_w[:, 3:] = combine_frame_transforms(
self.robot.data.root_pos_w,
self.robot.data.root_quat_w,
self.pose_command_b[:, :3],
self.pose_command_b[:, 3:],
)
# compute the error
pos_error, rot_error = compute_pose_error(
self.pose_command_w[:, :3],
self.pose_command_w[:, 3:],
self.robot.data.body_state_w[:, self.body_idx, :3],
self.robot.data.body_state_w[:, self.body_idx, 3:7],
)
self.metrics["position_error"] = torch.norm(pos_error, dim=-1)
self.metrics["orientation_error"] = torch.norm(rot_error, dim=-1)
def _resample_command(self, env_ids: Sequence[int]):
# sample new pose targets
# -- position
r = torch.empty(len(env_ids), device=self.device)
self.pose_command_b[env_ids, 0] = r.uniform_(*self.cfg.ranges.pos_x)
self.pose_command_b[env_ids, 1] = r.uniform_(*self.cfg.ranges.pos_y)
self.pose_command_b[env_ids, 2] = r.uniform_(*self.cfg.ranges.pos_z)
# -- orientation
euler_angles = torch.zeros_like(self.pose_command_b[env_ids, :3])
euler_angles[:, 0].uniform_(*self.cfg.ranges.roll)
euler_angles[:, 1].uniform_(*self.cfg.ranges.pitch)
euler_angles[:, 2].uniform_(*self.cfg.ranges.yaw)
self.pose_command_b[env_ids, 3:] = quat_from_euler_xyz(
euler_angles[:, 0], euler_angles[:, 1], euler_angles[:, 2]
)
def _update_command(self):
pass
def _set_debug_vis_impl(self, debug_vis: bool):
# create markers if necessary for the first tome
if debug_vis:
if not hasattr(self, "goal_pose_visualizer"):
marker_cfg = FRAME_MARKER_CFG.copy()
marker_cfg.markers["frame"].scale = (0.1, 0.1, 0.1)
# -- goal pose
marker_cfg.prim_path = "/Visuals/Command/goal_pose"
self.goal_pose_visualizer = VisualizationMarkers(marker_cfg)
# -- current body pose
marker_cfg.prim_path = "/Visuals/Command/body_pose"
self.body_pose_visualizer = VisualizationMarkers(marker_cfg)
# set their visibility to true
self.goal_pose_visualizer.set_visibility(True)
self.body_pose_visualizer.set_visibility(True)
else:
if hasattr(self, "goal_pose_visualizer"):
self.goal_pose_visualizer.set_visibility(False)
self.body_pose_visualizer.set_visibility(False)
def _debug_vis_callback(self, event):
# update the markers
# -- goal pose
self.goal_pose_visualizer.visualize(self.pose_command_w[:, :3], self.pose_command_w[:, 3:])
# -- current body pose
body_pose_w = self.robot.data.body_state_w[:, self.body_idx]
self.body_pose_visualizer.visualize(body_pose_w[:, :3], body_pose_w[:, 3:7])
| 6,437 | Python | 40.006369 | 116 | 0.63803 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/commands/null_command.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing command generator that does nothing."""
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING
from omni.isaac.orbit.managers import CommandTerm
if TYPE_CHECKING:
from .commands_cfg import NullCommandCfg
class NullCommand(CommandTerm):
"""Command generator that does nothing.
This command generator does not generate any commands. It is used for environments that do not
require any commands.
"""
cfg: NullCommandCfg
"""Configuration for the command generator."""
def __str__(self) -> str:
msg = "NullCommand:\n"
msg += "\tCommand dimension: N/A\n"
msg += f"\tResampling time range: {self.cfg.resampling_time_range}"
return msg
"""
Properties
"""
@property
def command(self):
"""Null command.
Raises:
RuntimeError: No command is generated. Always raises this error.
"""
raise RuntimeError("NullCommandTerm does not generate any commands.")
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]:
return {}
def compute(self, dt: float):
pass
"""
Implementation specific functions.
"""
def _update_metrics(self):
pass
def _resample_command(self, env_ids: Sequence[int]):
pass
def _update_command(self):
pass
| 1,574 | Python | 21.5 | 98 | 0.640407 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/envs/mdp/commands/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Various command terms that can be used in the environment."""
from .commands_cfg import (
NormalVelocityCommandCfg,
NullCommandCfg,
TerrainBasedPose2dCommandCfg,
UniformPose2dCommandCfg,
UniformPoseCommandCfg,
UniformVelocityCommandCfg,
)
from .null_command import NullCommand
from .pose_2d_command import TerrainBasedPose2dCommand, UniformPose2dCommand
from .pose_command import UniformPoseCommand
from .velocity_command import NormalVelocityCommand, UniformVelocityCommand
| 626 | Python | 30.349998 | 76 | 0.801917 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/observation_manager.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Observation manager for computing observation signals for a given world."""
from __future__ import annotations
import torch
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
from .manager_base import ManagerBase, ManagerTermBase
from .manager_term_cfg import ObservationGroupCfg, ObservationTermCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
class ObservationManager(ManagerBase):
"""Manager for computing observation signals for a given world.
Observations are organized into groups based on their intended usage. This allows having different observation
groups for different types of learning such as asymmetric actor-critic and student-teacher training. Each
group contains observation terms which contain information about the observation function to call, the noise
corruption model to use, and the sensor to retrieve data from.
Each observation group should inherit from the :class:`ObservationGroupCfg` class. Within each group, each
observation term should instantiate the :class:`ObservationTermCfg` class.
"""
def __init__(self, cfg: object, env: BaseEnv):
"""Initialize observation manager.
Args:
cfg: The configuration object or dictionary (``dict[str, ObservationGroupCfg]``).
env: The environment instance.
"""
super().__init__(cfg, env)
# compute combined vector for obs group
self._group_obs_dim: dict[str, tuple[int, ...]] = dict()
for group_name, group_term_dims in self._group_obs_term_dim.items():
term_dims = [torch.tensor(dims, device="cpu") for dims in group_term_dims]
self._group_obs_dim[group_name] = tuple(torch.sum(torch.stack(term_dims, dim=0), dim=0).tolist())
def __str__(self) -> str:
"""Returns: A string representation for the observation manager."""
msg = f"<ObservationManager> contains {len(self._group_obs_term_names)} groups.\n"
# add info for each group
for group_name, group_dim in self._group_obs_dim.items():
# create table for term information
table = PrettyTable()
table.title = f"Active Observation Terms in Group: '{group_name}' (shape: {group_dim})"
table.field_names = ["Index", "Name", "Shape"]
# set alignment of table columns
table.align["Name"] = "l"
# add info for each term
obs_terms = zip(
self._group_obs_term_names[group_name],
self._group_obs_term_dim[group_name],
)
for index, (name, dims) in enumerate(obs_terms):
# resolve inputs to simplify prints
tab_dims = tuple(dims)
# add row
table.add_row([index, name, tab_dims])
# convert table to string
msg += table.get_string()
msg += "\n"
return msg
"""
Properties.
"""
@property
def active_terms(self) -> dict[str, list[str]]:
"""Name of active observation terms in each group."""
return self._group_obs_term_names
@property
def group_obs_dim(self) -> dict[str, tuple[int, ...]]:
"""Shape of observation tensor in each group."""
return self._group_obs_dim
@property
def group_obs_term_dim(self) -> dict[str, list[tuple[int, ...]]]:
"""Shape of observation tensor for each term in each group."""
return self._group_obs_term_dim
@property
def group_obs_concatenate(self) -> dict[str, bool]:
"""Whether the observation terms are concatenated in each group."""
return self._group_obs_concatenate
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]:
# call all terms that are classes
for group_cfg in self._group_obs_class_term_cfgs.values():
for term_cfg in group_cfg:
term_cfg.func.reset(env_ids=env_ids)
# nothing to log here
return {}
def compute(self) -> dict[str, torch.Tensor | dict[str, torch.Tensor]]:
"""Compute the observations per group for all groups.
The method computes the observations for all the groups handled by the observation manager.
Please check the :meth:`compute_group` on the processing of observations per group.
Returns:
A dictionary with keys as the group names and values as the computed observations.
"""
# create a buffer for storing obs from all the groups
obs_buffer = dict()
# iterate over all the terms in each group
for group_name in self._group_obs_term_names:
obs_buffer[group_name] = self.compute_group(group_name)
# otherwise return a dict with observations of all groups
return obs_buffer
def compute_group(self, group_name: str) -> torch.Tensor | dict[str, torch.Tensor]:
"""Computes the observations for a given group.
The observations for a given group are computed by calling the registered functions for each
term in the group. The functions are called in the order of the terms in the group. The functions
are expected to return a tensor with shape (num_envs, ...).
If a corruption/noise model is registered for a term, the function is called to corrupt
the observation. The corruption function is expected to return a tensor with the same
shape as the observation. The observations are clipped and scaled as per the configuration
settings.
The operations are performed in the order: compute, add corruption/noise, clip, scale.
By default, no scaling or clipping is applied.
Args:
group_name: The name of the group for which to compute the observations. Defaults to None,
in which case observations for all the groups are computed and returned.
Returns:
Depending on the group's configuration, the tensors for individual observation terms are
concatenated along the last dimension into a single tensor. Otherwise, they are returned as
a dictionary with keys corresponding to the term's name.
Raises:
ValueError: If input ``group_name`` is not a valid group handled by the manager.
"""
# check ig group name is valid
if group_name not in self._group_obs_term_names:
raise ValueError(
f"Unable to find the group '{group_name}' in the observation manager."
f" Available groups are: {list(self._group_obs_term_names.keys())}"
)
# iterate over all the terms in each group
group_term_names = self._group_obs_term_names[group_name]
# buffer to store obs per group
group_obs = dict.fromkeys(group_term_names, None)
# read attributes for each term
obs_terms = zip(group_term_names, self._group_obs_term_cfgs[group_name])
# evaluate terms: compute, add noise, clip, scale.
for name, term_cfg in obs_terms:
# compute term's value
obs: torch.Tensor = term_cfg.func(self._env, **term_cfg.params).clone()
# apply post-processing
if term_cfg.noise:
obs = term_cfg.noise.func(obs, term_cfg.noise)
if term_cfg.clip:
obs = obs.clip_(min=term_cfg.clip[0], max=term_cfg.clip[1])
if term_cfg.scale:
obs = obs.mul_(term_cfg.scale)
# TODO: Introduce delay and filtering models.
# Ref: https://robosuite.ai/docs/modules/sensors.html#observables
# add value to list
group_obs[name] = obs
# concatenate all observations in the group together
if self._group_obs_concatenate[group_name]:
return torch.cat(list(group_obs.values()), dim=-1)
else:
return group_obs
"""
Helper functions.
"""
def _prepare_terms(self):
"""Prepares a list of observation terms functions."""
# create buffers to store information for each observation group
# TODO: Make this more convenient by using data structures.
self._group_obs_term_names: dict[str, list[str]] = dict()
self._group_obs_term_dim: dict[str, list[int]] = dict()
self._group_obs_term_cfgs: dict[str, list[ObservationTermCfg]] = dict()
self._group_obs_class_term_cfgs: dict[str, list[ObservationTermCfg]] = dict()
self._group_obs_concatenate: dict[str, bool] = dict()
# check if config is dict already
if isinstance(self.cfg, dict):
group_cfg_items = self.cfg.items()
else:
group_cfg_items = self.cfg.__dict__.items()
# iterate over all the groups
for group_name, group_cfg in group_cfg_items:
# check for non config
if group_cfg is None:
continue
# check if the term is a curriculum term
if not isinstance(group_cfg, ObservationGroupCfg):
raise TypeError(
f"Observation group '{group_name}' is not of type 'ObservationGroupCfg'."
f" Received: '{type(group_cfg)}'."
)
# initialize list for the group settings
self._group_obs_term_names[group_name] = list()
self._group_obs_term_dim[group_name] = list()
self._group_obs_term_cfgs[group_name] = list()
self._group_obs_class_term_cfgs[group_name] = list()
# read common config for the group
self._group_obs_concatenate[group_name] = group_cfg.concatenate_terms
# check if config is dict already
if isinstance(group_cfg, dict):
group_cfg_items = group_cfg.items()
else:
group_cfg_items = group_cfg.__dict__.items()
# iterate over all the terms in each group
for term_name, term_cfg in group_cfg.__dict__.items():
# skip non-obs settings
if term_name in ["enable_corruption", "concatenate_terms"]:
continue
# check for non config
if term_cfg is None:
continue
if not isinstance(term_cfg, ObservationTermCfg):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type ObservationTermCfg."
f" Received: '{type(term_cfg)}'."
)
# resolve common terms in the config
self._resolve_common_term_cfg(f"{group_name}/{term_name}", term_cfg, min_argc=1)
# check noise settings
if not group_cfg.enable_corruption:
term_cfg.noise = None
# add term config to list to list
self._group_obs_term_names[group_name].append(term_name)
self._group_obs_term_cfgs[group_name].append(term_cfg)
# call function the first time to fill up dimensions
obs_dims = tuple(term_cfg.func(self._env, **term_cfg.params).shape[1:])
self._group_obs_term_dim[group_name].append(obs_dims)
# add term in a separate list if term is a class
if isinstance(term_cfg.func, ManagerTermBase):
self._group_obs_class_term_cfgs[group_name].append(term_cfg)
# call reset (in-case above call to get obs dims changed the state)
term_cfg.func.reset()
| 11,820 | Python | 44.291188 | 114 | 0.609645 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/manager_base.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 inspect
from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any
import carb
import omni.isaac.orbit.utils.string as string_utils
from omni.isaac.orbit.utils import string_to_callable
from .manager_term_cfg import ManagerTermBaseCfg
from .scene_entity_cfg import SceneEntityCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
class ManagerTermBase(ABC):
"""Base class for manager terms.
Manager term implementations can be functions or classes. If the term is a class, it should
inherit from this base class and implement the required methods.
Each manager is implemented as a class that inherits from the :class:`ManagerBase` class. Each manager
class should also have a corresponding configuration class that defines the configuration terms for the
manager. Each term should the :class:`ManagerTermBaseCfg` class or its subclass.
Example pseudo-code for creating a manager:
.. code-block:: python
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.mdp import ManagerBase, ManagerTermBaseCfg
@configclass
class MyManagerCfg:
my_term_1: ManagerTermBaseCfg = ManagerTermBaseCfg(...)
my_term_2: ManagerTermBaseCfg = ManagerTermBaseCfg(...)
my_term_3: ManagerTermBaseCfg = ManagerTermBaseCfg(...)
# define manager instance
my_manager = ManagerBase(cfg=ManagerCfg(), env=env)
"""
def __init__(self, cfg: ManagerTermBaseCfg, env: BaseEnv):
"""Initialize the manager term.
Args:
cfg: The configuration object.
env: The environment instance.
"""
# store the inputs
self.cfg = cfg
self._env = env
"""
Properties.
"""
@property
def num_envs(self) -> int:
"""Number of environments."""
return self._env.num_envs
@property
def device(self) -> str:
"""Device on which to perform computations."""
return self._env.device
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> None:
"""Resets the manager term.
Args:
env_ids: The environment ids. Defaults to None, in which case
all environments are considered.
"""
pass
def __call__(self, *args) -> Any:
"""Returns the value of the term required by the manager.
In case of a class implementation, this function is called by the manager
to get the value of the term. The arguments passed to this function are
the ones specified in the term configuration (see :attr:`ManagerTermBaseCfg.params`).
.. attention::
To be consistent with memory-less implementation of terms with functions, it is
recommended to ensure that the returned mutable quantities are cloned before
returning them. For instance, if the term returns a tensor, it is recommended
to ensure that the returned tensor is a clone of the original tensor. This prevents
the manager from storing references to the tensors and altering the original tensors.
Args:
*args: Variable length argument list.
Returns:
The value of the term.
"""
raise NotImplementedError
class ManagerBase(ABC):
"""Base class for all managers."""
def __init__(self, cfg: object, env: BaseEnv):
"""Initialize the manager.
Args:
cfg: The configuration object.
env: The environment instance.
"""
# store the inputs
self.cfg = copy.deepcopy(cfg)
self._env = env
# parse config to create terms information
self._prepare_terms()
"""
Properties.
"""
@property
def num_envs(self) -> int:
"""Number of environments."""
return self._env.num_envs
@property
def device(self) -> str:
"""Device on which to perform computations."""
return self._env.device
@property
@abstractmethod
def active_terms(self) -> list[str] | dict[str, list[str]]:
"""Name of active terms."""
raise NotImplementedError
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]:
"""Resets the manager and returns logging information for the current time-step.
Args:
env_ids: The environment ids for which to log data.
Defaults None, which logs data for all environments.
Returns:
Dictionary containing the logging information.
"""
return {}
def find_terms(self, name_keys: str | Sequence[str]) -> list[str]:
"""Find terms in the manager based on the names.
This function searches the manager for terms based on the names. The names can be
specified as regular expressions or a list of regular expressions. The search is
performed on the active terms in the manager.
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 term names.
Returns:
A list of term names that match the input keys.
"""
# resolve search keys
if isinstance(self.active_terms, dict):
list_of_strings = []
for names in self.active_terms.values():
list_of_strings.extend(names)
else:
list_of_strings = self.active_terms
# return the matching names
return string_utils.resolve_matching_names(name_keys, list_of_strings)[1]
"""
Implementation specific.
"""
@abstractmethod
def _prepare_terms(self):
"""Prepare terms information from the configuration object."""
raise NotImplementedError
"""
Helper functions.
"""
def _resolve_common_term_cfg(self, term_name: str, term_cfg: ManagerTermBaseCfg, min_argc: int = 1):
"""Resolve common term configuration.
Usually, called by the :meth:`_prepare_terms` method to resolve common term configuration.
Note:
By default, all term functions are expected to have at least one argument, which is the
environment object. Some other managers may expect functions to take more arguments, for
instance, the environment indices as the second argument. In such cases, the
``min_argc`` argument can be used to specify the minimum number of arguments
required by the term function to be called correctly by the manager.
Args:
term_name: The name of the term.
term_cfg: The term configuration.
min_argc: The minimum number of arguments required by the term function to be called correctly
by the manager.
Raises:
TypeError: If the term configuration is not of type :class:`ManagerTermBaseCfg`.
ValueError: If the scene entity defined in the term configuration does not exist.
AttributeError: If the term function is not callable.
ValueError: If the term function's arguments are not matched by the parameters.
"""
# check if the term is a valid term config
if not isinstance(term_cfg, ManagerTermBaseCfg):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type ManagerTermBaseCfg."
f" Received: '{type(term_cfg)}'."
)
# iterate over all the entities and parse the joint and body names
for key, value in term_cfg.params.items():
# deal with string
if isinstance(value, SceneEntityCfg):
# load the entity
try:
value.resolve(self._env.scene)
except ValueError as e:
raise ValueError(f"Error while parsing '{term_name}:{key}'. {e}")
# log the entity for checking later
msg = f"[{term_cfg.__class__.__name__}:{term_name}] Found entity '{value.name}'."
if value.joint_ids is not None:
msg += f"\n\tJoint names: {value.joint_names} [{value.joint_ids}]"
if value.body_ids is not None:
msg += f"\n\tBody names: {value.body_names} [{value.body_ids}]"
# print the information
carb.log_info(msg)
# store the entity
term_cfg.params[key] = value
# get the corresponding function or functional class
if isinstance(term_cfg.func, str):
term_cfg.func = string_to_callable(term_cfg.func)
# initialize the term if it is a class
if inspect.isclass(term_cfg.func):
if not issubclass(term_cfg.func, ManagerTermBase):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type ManagerTermBase."
f" Received: '{type(term_cfg.func)}'."
)
term_cfg.func = term_cfg.func(cfg=term_cfg, env=self._env)
# check if function is callable
if not callable(term_cfg.func):
raise AttributeError(f"The term '{term_name}' is not callable. Received: {term_cfg.func}")
# check if term's arguments are matched by params
term_params = list(term_cfg.params.keys())
args = inspect.signature(term_cfg.func).parameters
args_with_defaults = [arg for arg in args if args[arg].default is not inspect.Parameter.empty]
args_without_defaults = [arg for arg in args if args[arg].default is inspect.Parameter.empty]
args = args_without_defaults + args_with_defaults
# ignore first two arguments for env and env_ids
# Think: Check for cases when kwargs are set inside the function?
if len(args) > min_argc:
if set(args[min_argc:]) != set(term_params + args_with_defaults):
raise ValueError(
f"The term '{term_name}' expects mandatory parameters: {args_without_defaults[min_argc:]}"
f" and optional parameters: {args_with_defaults}, but received: {term_params}."
)
| 10,629 | Python | 36.167832 | 110 | 0.621884 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for environment managers.
The managers are used to handle various aspects of the environment such as randomization events, curriculum,
and observations. Each manager implements a specific functionality for the environment. The managers are
designed to be modular and can be easily extended to support new functionality.
"""
from .action_manager import ActionManager, ActionTerm
from .command_manager import CommandManager, CommandTerm
from .curriculum_manager import CurriculumManager
from .event_manager import EventManager, RandomizationManager
from .manager_base import ManagerBase, ManagerTermBase
from .manager_term_cfg import (
ActionTermCfg,
CommandTermCfg,
CurriculumTermCfg,
EventTermCfg,
ManagerTermBaseCfg,
ObservationGroupCfg,
ObservationTermCfg,
RandomizationTermCfg,
RewardTermCfg,
TerminationTermCfg,
)
from .observation_manager import ObservationManager
from .reward_manager import RewardManager
from .scene_entity_cfg import SceneEntityCfg
from .termination_manager import TerminationManager
| 1,188 | Python | 33.970587 | 108 | 0.808081 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/event_manager.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Event manager for orchestrating operations based on different simulation events."""
from __future__ import annotations
import torch
import warnings
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
import carb
from .manager_base import ManagerBase, ManagerTermBase
from .manager_term_cfg import EventTermCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
class EventManager(ManagerBase):
"""Manager for orchestrating operations based on different simulation events.
The event manager applies operations to the environment based on different simulation events. For example,
changing the masses of objects or their friction coefficients during initialization/ reset, or applying random
pushes to the robot at a fixed interval of steps. The user can specify several modes of events to fine-tune the
behavior based on when to apply the event.
The event terms are parsed from a config class containing the manager's settings and each term's
parameters. Each event term should instantiate the :class:`EventTermCfg` class.
Event terms can be grouped by their mode. The mode is a user-defined string that specifies when
the event term should be applied. This provides the user complete control over when event
terms should be applied.
For a typical training process, you may want to apply events in the following modes:
- "startup": Event is applied once at the beginning of the training.
- "reset": Event is applied at every reset.
- "interval": Event is applied at pre-specified intervals of time.
However, you can also define your own modes and use them in the training process as you see fit.
For this you will need to add the triggering of that mode in the environment implementation as well.
.. note::
The triggering of operations corresponding to the mode ``"interval"`` are the only mode that are
directly handled by the manager itself. The other modes are handled by the environment implementation.
"""
_env: RLTaskEnv
"""The environment instance."""
def __init__(self, cfg: object, env: RLTaskEnv):
"""Initialize the event manager.
Args:
cfg: A configuration object or dictionary (``dict[str, EventTermCfg]``).
env: An environment object.
"""
super().__init__(cfg, env)
def __str__(self) -> str:
"""Returns: A string representation for event manager."""
msg = f"<EventManager> contains {len(self._mode_term_names)} active terms.\n"
# add info on each mode
for mode in self._mode_term_names:
# create table for term information
table = PrettyTable()
table.title = f"Active Event Terms in Mode: '{mode}'"
# add table headers based on mode
if mode == "interval":
table.field_names = ["Index", "Name", "Interval time range (s)"]
table.align["Name"] = "l"
for index, (name, cfg) in enumerate(zip(self._mode_term_names[mode], self._mode_term_cfgs[mode])):
table.add_row([index, name, cfg.interval_range_s])
else:
table.field_names = ["Index", "Name"]
table.align["Name"] = "l"
for index, name in enumerate(self._mode_term_names[mode]):
table.add_row([index, name])
# convert table to string
msg += table.get_string()
msg += "\n"
return msg
"""
Properties.
"""
@property
def active_terms(self) -> dict[str, list[str]]:
"""Name of active event terms.
The keys are the modes of event and the values are the names of the event terms.
"""
return self._mode_term_names
@property
def available_modes(self) -> list[str]:
"""Modes of events."""
return list(self._mode_term_names.keys())
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]:
# call all terms that are classes
for mode_cfg in self._mode_class_term_cfgs.values():
for term_cfg in mode_cfg:
term_cfg.func.reset(env_ids=env_ids)
# nothing to log here
return {}
def apply(self, mode: str, env_ids: Sequence[int] | None = None, dt: float | None = None):
"""Calls each event term in the specified mode.
Note:
For interval mode, the time step of the environment is used to determine if the event
should be applied.
Args:
mode: The mode of event.
env_ids: The indices of the environments to apply the event to.
Defaults to None, in which case the event is applied to all environments.
dt: The time step of the environment. This is only used for the "interval" mode.
Defaults to None to simplify the call for other modes.
Raises:
ValueError: If the mode is ``"interval"`` and the time step is not provided.
"""
# check if mode is valid
if mode not in self._mode_term_names:
carb.log_warn(f"Event mode '{mode}' is not defined. Skipping event.")
return
# iterate over all the event terms
for index, term_cfg in enumerate(self._mode_term_cfgs[mode]):
# resample interval if needed
if mode == "interval":
if dt is None:
raise ValueError(
f"Event mode '{mode}' requires the time step of the environment"
" to be passed to the event manager."
)
# extract time left for this term
time_left = self._interval_mode_time_left[index]
# update the time left for each environment
time_left -= dt
# check if the interval has passed
env_ids = (time_left <= 0.0).nonzero().flatten()
if len(env_ids) > 0:
lower, upper = term_cfg.interval_range_s
time_left[env_ids] = torch.rand(len(env_ids), device=self.device) * (upper - lower) + lower
# call the event term
term_cfg.func(self._env, env_ids, **term_cfg.params)
"""
Operations - Term settings.
"""
def set_term_cfg(self, term_name: str, cfg: EventTermCfg):
"""Sets the configuration of the specified term into the manager.
The method finds the term by name by searching through all the modes.
It then updates the configuration of the term with the first matching name.
Args:
term_name: The name of the event term.
cfg: The configuration for the event term.
Raises:
ValueError: If the term name is not found.
"""
term_found = False
for mode, terms in self._mode_term_names.items():
if term_name in terms:
self._mode_term_cfgs[mode][terms.index(term_name)] = cfg
term_found = True
break
if not term_found:
raise ValueError(f"Event term '{term_name}' not found.")
def get_term_cfg(self, term_name: str) -> EventTermCfg:
"""Gets the configuration for the specified term.
The method finds the term by name by searching through all the modes.
It then returns the configuration of the term with the first matching name.
Args:
term_name: The name of the event term.
Returns:
The configuration of the event term.
Raises:
ValueError: If the term name is not found.
"""
for mode, terms in self._mode_term_names.items():
if term_name in terms:
return self._mode_term_cfgs[mode][terms.index(term_name)]
raise ValueError(f"Event term '{term_name}' not found.")
"""
Helper functions.
"""
def _prepare_terms(self):
"""Prepares a list of event functions."""
# parse remaining event terms and decimate their information
self._mode_term_names: dict[str, list[str]] = dict()
self._mode_term_cfgs: dict[str, list[EventTermCfg]] = dict()
self._mode_class_term_cfgs: dict[str, list[EventTermCfg]] = dict()
# buffer to store the time left for each environment for "interval" mode
self._interval_mode_time_left: list[torch.Tensor] = list()
# check if config is dict already
if isinstance(self.cfg, dict):
cfg_items = self.cfg.items()
else:
cfg_items = self.cfg.__dict__.items()
# iterate over all the terms
for term_name, term_cfg in cfg_items:
# check for non config
if term_cfg is None:
continue
# check for valid config type
if not isinstance(term_cfg, EventTermCfg):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type EventTermCfg."
f" Received: '{type(term_cfg)}'."
)
# resolve common parameters
self._resolve_common_term_cfg(term_name, term_cfg, min_argc=2)
# check if mode is a new mode
if term_cfg.mode not in self._mode_term_names:
# add new mode
self._mode_term_names[term_cfg.mode] = list()
self._mode_term_cfgs[term_cfg.mode] = list()
self._mode_class_term_cfgs[term_cfg.mode] = list()
# add term name and parameters
self._mode_term_names[term_cfg.mode].append(term_name)
self._mode_term_cfgs[term_cfg.mode].append(term_cfg)
# check if the term is a class
if isinstance(term_cfg.func, ManagerTermBase):
self._mode_class_term_cfgs[term_cfg.mode].append(term_cfg)
# resolve the mode of the events
if term_cfg.mode == "interval":
if term_cfg.interval_range_s is None:
raise ValueError(
f"Event term '{term_name}' has mode 'interval' but 'interval_range_s' is not specified."
)
# sample the time left for each environment
lower, upper = term_cfg.interval_range_s
time_left = torch.rand(self.num_envs, device=self.device) * (upper - lower) + lower
self._interval_mode_time_left.append(time_left)
class RandomizationManager(EventManager):
"""Manager for applying event specific operations to different elements in the scene.
.. deprecated:: v0.4.0
As the RandomizationManager also handles events such as resetting the environment, the class has been
renamed to EventManager as it is more general purpose. The RandomizationManager will be removed in v0.4.0.
"""
def __init__(self, cfg: object, env: RLTaskEnv):
"""Initialize the randomization manager.
Args:
cfg: A configuration object or dictionary (``dict[str, EventTermCfg]``).
env: An environment object.
"""
dep_msg = "The class 'RandomizationManager' will be removed in v0.4.0. Please use 'EventManager' instead."
warnings.warn(dep_msg, DeprecationWarning)
carb.log_error(dep_msg)
super().__init__(cfg, env)
def randomize(self, mode: str, env_ids: Sequence[int] | None = None, dt: float | None = None):
"""Randomize the environment.
.. deprecated:: v0.4.0
This method will be removed in v0.4.0. Please use the method :meth:`EventManager.apply`
instead.
"""
dep_msg = (
"The class 'RandomizationManager' including its method 'randomize' will be removed in v0.4.0. Please use "
"the class 'EventManager' with the method 'apply' instead."
)
warnings.warn(dep_msg, DeprecationWarning)
carb.log_error(dep_msg)
self.apply(mode, env_ids, dt)
| 12,265 | Python | 39.481848 | 118 | 0.603261 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/command_manager.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Command manager for generating and updating commands."""
from __future__ import annotations
import inspect
import torch
import weakref
from abc import abstractmethod
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
import omni.kit.app
from .manager_base import ManagerBase, ManagerTermBase
from .manager_term_cfg import CommandTermCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
class CommandTerm(ManagerTermBase):
"""The base class for implementing a command term.
A command term is used to generate commands for goal-conditioned tasks. For example,
in the case of a goal-conditioned navigation task, the command term can be used to
generate a target position for the robot to navigate to.
It implements a resampling mechanism that allows the command to be resampled at a fixed
frequency. The resampling frequency can be specified in the configuration object.
Additionally, it is possible to assign a visualization function to the command term
that can be used to visualize the command in the simulator.
"""
def __init__(self, cfg: CommandTermCfg, env: RLTaskEnv):
"""Initialize the command generator class.
Args:
cfg: The configuration parameters for the command generator.
env: The environment object.
"""
super().__init__(cfg, env)
# create buffers to store the command
# -- metrics that can be used for logging
self.metrics = dict()
# -- time left before resampling
self.time_left = torch.zeros(self.num_envs, device=self.device)
# -- counter for the number of times the command has been resampled within the current episode
self.command_counter = torch.zeros(self.num_envs, device=self.device, dtype=torch.long)
# 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."""
if self._debug_vis_handle:
self._debug_vis_handle.unsubscribe()
self._debug_vis_handle = None
"""
Properties
"""
@property
@abstractmethod
def command(self) -> torch.Tensor:
"""The command tensor. Shape is (num_envs, command_dim)."""
raise NotImplementedError
@property
def has_debug_vis_implementation(self) -> bool:
"""Whether the command generator 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 command data.
Args:
debug_vis: Whether to visualize the command data.
Returns:
Whether the debug visualization was successfully set. False if the command
generator 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
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]:
"""Reset the command generator and log metrics.
This function resets the command counter and resamples the command. It should be called
at the beginning of each episode.
Args:
env_ids: The list of environment IDs to reset. Defaults to None.
Returns:
A dictionary containing the information to log under the "{name}" key.
"""
# resolve the environment IDs
if env_ids is None:
env_ids = slice(None)
# set the command counter to zero
self.command_counter[env_ids] = 0
# resample the command
self._resample(env_ids)
# add logging metrics
extras = {}
for metric_name, metric_value in self.metrics.items():
# compute the mean metric value
extras[metric_name] = torch.mean(metric_value[env_ids]).item()
# reset the metric value
metric_value[env_ids] = 0.0
return extras
def compute(self, dt: float):
"""Compute the command.
Args:
dt: The time step passed since the last call to compute.
"""
# update the metrics based on current state
self._update_metrics()
# reduce the time left before resampling
self.time_left -= dt
# resample the command if necessary
resample_env_ids = (self.time_left <= 0.0).nonzero().flatten()
if len(resample_env_ids) > 0:
self._resample(resample_env_ids)
# update the command
self._update_command()
"""
Helper functions.
"""
def _resample(self, env_ids: Sequence[int]):
"""Resample the command.
This function resamples the command and time for which the command is applied for the
specified environment indices.
Args:
env_ids: The list of environment IDs to resample.
"""
# resample the time left before resampling
self.time_left[env_ids] = self.time_left[env_ids].uniform_(*self.cfg.resampling_time_range)
# increment the command counter
self.command_counter[env_ids] += 1
# resample the command
self._resample_command(env_ids)
"""
Implementation specific functions.
"""
@abstractmethod
def _update_metrics(self):
"""Update the metrics based on the current state."""
raise NotImplementedError
@abstractmethod
def _resample_command(self, env_ids: Sequence[int]):
"""Resample the command for the specified environments."""
raise NotImplementedError
@abstractmethod
def _update_command(self):
"""Update the command based on the current state."""
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__}.")
class CommandManager(ManagerBase):
"""Manager for generating commands.
The command manager is used to generate commands for an agent to execute. It makes it convenient to switch
between different command generation strategies within the same environment. For instance, in an environment
consisting of a quadrupedal robot, the command to it could be a velocity command or position command.
By keeping the command generation logic separate from the environment, it is easy to switch between different
command generation strategies.
The command terms are implemented as classes that inherit from the :class:`CommandTerm` class.
Each command generator term should also have a corresponding configuration class that inherits from the
:class:`CommandTermCfg` class.
"""
_env: RLTaskEnv
"""The environment instance."""
def __init__(self, cfg: object, env: RLTaskEnv):
"""Initialize the command manager.
Args:
cfg: The configuration object or dictionary (``dict[str, CommandTermCfg]``).
env: The environment instance.
"""
super().__init__(cfg, env)
# store the commands
self._commands = dict()
self.cfg.debug_vis = False
for term in self._terms.values():
self.cfg.debug_vis |= term.cfg.debug_vis
def __str__(self) -> str:
"""Returns: A string representation for the command manager."""
msg = f"<CommandManager> contains {len(self._terms.values())} active terms.\n"
# create table for term information
table = PrettyTable()
table.title = "Active Command Terms"
table.field_names = ["Index", "Name", "Type"]
# set alignment of table columns
table.align["Name"] = "l"
# add info on each term
for index, (name, term) in enumerate(self._terms.items()):
table.add_row([index, name, term.__class__.__name__])
# convert table to string
msg += table.get_string()
msg += "\n"
return msg
"""
Properties.
"""
@property
def active_terms(self) -> list[str]:
"""Name of active command terms."""
return list(self._terms.keys())
@property
def has_debug_vis_implementation(self) -> bool:
"""Whether the command terms have debug visualization implemented."""
# check if function raises NotImplementedError
has_debug_vis = False
for term in self._terms.values():
has_debug_vis |= term.has_debug_vis_implementation
return has_debug_vis
"""
Operations.
"""
def set_debug_vis(self, debug_vis: bool) -> bool:
"""Sets whether to visualize the command data.
Args:
debug_vis: Whether to visualize the command data.
Returns:
Whether the debug visualization was successfully set. False if the command
generator does not support debug visualization.
"""
for term in self._terms.values():
term.set_debug_vis(debug_vis)
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, torch.Tensor]:
"""Reset the command terms and log their metrics.
This function resets the command counter and resamples the command for each term. It should be called
at the beginning of each episode.
Args:
env_ids: The list of environment IDs to reset. Defaults to None.
Returns:
A dictionary containing the information to log under the "Metrics/{term_name}/{metric_name}" key.
"""
# resolve environment ids
if env_ids is None:
env_ids = slice(None)
# store information
extras = {}
for name, term in self._terms.items():
# reset the command term
metrics = term.reset(env_ids=env_ids)
# compute the mean metric value
for metric_name, metric_value in metrics.items():
extras[f"Metrics/{name}/{metric_name}"] = metric_value
# return logged information
return extras
def compute(self, dt: float):
"""Updates the commands.
This function calls each command term managed by the class.
Args:
dt: The time-step interval of the environment.
"""
# iterate over all the command terms
for term in self._terms.values():
# compute term's value
term.compute(dt)
def get_command(self, name: str) -> torch.Tensor:
"""Returns the command for the specified command term.
Args:
name: The name of the command term.
Returns:
The command tensor of the specified command term.
"""
return self._terms[name].command
def get_term(self, name: str) -> CommandTerm:
"""Returns the command term with the specified name.
Args:
name: The name of the command term.
Returns:
The command term with the specified name.
"""
return self._terms[name]
"""
Helper functions.
"""
def _prepare_terms(self):
"""Prepares a list of command terms."""
# parse command terms from the config
self._terms: dict[str, CommandTerm] = dict()
# check if config is dict already
if isinstance(self.cfg, dict):
cfg_items = self.cfg.items()
else:
cfg_items = self.cfg.__dict__.items()
# iterate over all the terms
for term_name, term_cfg in cfg_items:
# check for non config
if term_cfg is None:
continue
# check for valid config type
if not isinstance(term_cfg, CommandTermCfg):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type CommandTermCfg."
f" Received: '{type(term_cfg)}'."
)
# create the action term
term = term_cfg.class_type(term_cfg, self._env)
# add class to dict
self._terms[term_name] = term
| 14,055 | Python | 34.405541 | 113 | 0.623764 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/scene_entity_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration terms for different managers."""
from __future__ import annotations
from dataclasses import MISSING
from omni.isaac.orbit.assets import Articulation, RigidObject
from omni.isaac.orbit.scene import InteractiveScene
from omni.isaac.orbit.utils import configclass
@configclass
class SceneEntityCfg:
"""Configuration for a scene entity that is used by the manager's term.
This class is used to specify the name of the scene entity that is queried from the
:class:`InteractiveScene` and passed to the manager's term function.
"""
name: str = MISSING
"""The name of the scene entity.
This is the name defined in the scene configuration file. See the :class:`InteractiveSceneCfg`
class for more details.
"""
joint_names: str | list[str] | None = None
"""The names of the joints from the scene entity. Defaults to None.
The names can be either joint names or a regular expression matching the joint names.
These are converted to joint indices on initialization of the manager and passed to the term
function as a list of joint indices under :attr:`joint_ids`.
"""
joint_ids: list[int] | slice = slice(None)
"""The indices of the joints from the asset required by the term. Defaults to slice(None), which means
all the joints in the asset (if present).
If :attr:`joint_names` is specified, this is filled in automatically on initialization of the
manager.
"""
body_names: str | list[str] | None = None
"""The names of the bodies from the asset required by the term. Defaults to None.
The names can be either body names or a regular expression matching the body names.
These are converted to body indices on initialization of the manager and passed to the term
function as a list of body indices under :attr:`body_ids`.
"""
body_ids: list[int] | slice = slice(None)
"""The indices of the bodies from the asset required by the term. Defaults to slice(None), which means
all the bodies in the asset.
If :attr:`body_names` is specified, this is filled in automatically on initialization of the
manager.
"""
preserve_order: bool = False
"""Whether to preserve indices ordering to match with that in the specified joint or body names. Defaults to False.
If False, the ordering of the indices are sorted in ascending order (i.e. the ordering in the entity's joints
or bodies). Otherwise, the indices are preserved in the order of the specified joint and body names.
For more details, see the :meth:`omni.isaac.orbit.utils.string.resolve_matching_names` function.
.. note::
This attribute is only used when :attr:`joint_names` or :attr:`body_names` are specified.
"""
def resolve(self, scene: InteractiveScene):
"""Resolves the scene entity and converts the joint and body names to indices.
This function examines the scene entity from the :class:`InteractiveScene` and resolves the indices
and names of the joints and bodies. It is an expensive operation as it resolves regular expressions
and should be called only once.
Args:
scene: The interactive scene instance.
Raises:
ValueError: If the scene entity is not found.
ValueError: If both ``joint_names`` and ``joint_ids`` are specified and are not consistent.
ValueError: If both ``body_names`` and ``body_ids`` are specified and are not consistent.
"""
# check if the entity is valid
if self.name not in scene.keys():
raise ValueError(f"The scene entity '{self.name}' does not exist. Available entities: {scene.keys()}.")
# convert joint names to indices based on regex
if self.joint_names is not None or self.joint_ids != slice(None):
entity: Articulation = scene[self.name]
# -- if both are not their default values, check if they are valid
if self.joint_names is not None and self.joint_ids != slice(None):
if isinstance(self.joint_names, str):
self.joint_names = [self.joint_names]
if isinstance(self.joint_ids, int):
self.joint_ids = [self.joint_ids]
joint_ids, _ = entity.find_joints(self.joint_names, preserve_order=self.preserve_order)
joint_names = [entity.joint_names[i] for i in self.joint_ids]
if joint_ids != self.joint_ids or joint_names != self.joint_names:
raise ValueError(
"Both 'joint_names' and 'joint_ids' are specified, and are not consistent."
f"\n\tfrom joint names: {self.joint_names} [{joint_ids}]"
f"\n\tfrom joint ids: {joint_names} [{self.joint_ids}]"
"\nHint: Use either 'joint_names' or 'joint_ids' to avoid confusion."
)
# -- from joint names to joint indices
elif self.joint_names is not None:
if isinstance(self.joint_names, str):
self.joint_names = [self.joint_names]
self.joint_ids, _ = entity.find_joints(self.joint_names, preserve_order=self.preserve_order)
# performance optimization (slice offers faster indexing than list of indices)
# only all joint in the entity order are selected
if len(self.joint_ids) == entity.num_joints and self.joint_names == entity.joint_names:
self.joint_ids = slice(None)
# -- from joint indices to joint names
elif self.joint_ids != slice(None):
if isinstance(self.joint_ids, int):
self.joint_ids = [self.joint_ids]
self.joint_names = [entity.joint_names[i] for i in self.joint_ids]
# convert body names to indices based on regex
if self.body_names is not None or self.body_ids != slice(None):
entity: RigidObject = scene[self.name]
# -- if both are not their default values, check if they are valid
if self.body_names is not None and self.body_ids != slice(None):
if isinstance(self.body_names, str):
self.body_names = [self.body_names]
if isinstance(self.body_ids, int):
self.body_ids = [self.body_ids]
body_ids, _ = entity.find_bodies(self.body_names, preserve_order=self.preserve_order)
body_names = [entity.body_names[i] for i in self.body_ids]
if body_ids != self.body_ids or body_names != self.body_names:
raise ValueError(
"Both 'body_names' and 'body_ids' are specified, and are not consistent."
f"\n\tfrom body names: {self.body_names} [{body_ids}]"
f"\n\tfrom body ids: {body_names} [{self.body_ids}]"
"\nHint: Use either 'body_names' or 'body_ids' to avoid confusion."
)
# -- from body names to body indices
elif self.body_names is not None:
if isinstance(self.body_names, str):
self.body_names = [self.body_names]
self.body_ids, _ = entity.find_bodies(self.body_names, preserve_order=self.preserve_order)
# performance optimization (slice offers faster indexing than list of indices)
# only all bodies in the entity order are selected
if len(self.body_ids) == entity.num_bodies and self.body_names == entity.body_names:
self.body_ids = slice(None)
# -- from body indices to body names
elif self.body_ids != slice(None):
if isinstance(self.body_ids, int):
self.body_ids = [self.body_ids]
self.body_names = [entity.body_names[i] for i in self.body_ids]
| 8,102 | Python | 48.711656 | 119 | 0.62429 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/curriculum_manager.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Curriculum manager for updating environment quantities subject to a training curriculum."""
from __future__ import annotations
import torch
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
from .manager_base import ManagerBase, ManagerTermBase
from .manager_term_cfg import CurriculumTermCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
class CurriculumManager(ManagerBase):
"""Manager to implement and execute specific curricula.
The curriculum manager updates various quantities of the environment subject to a training curriculum by
calling a list of terms. These help stabilize learning by progressively making the learning tasks harder
as the agent improves.
The curriculum terms are parsed from a config class containing the manager's settings and each term's
parameters. Each curriculum term should instantiate the :class:`CurriculumTermCfg` class.
"""
_env: RLTaskEnv
"""The environment instance."""
def __init__(self, cfg: object, env: RLTaskEnv):
"""Initialize the manager.
Args:
cfg: The configuration object or dictionary (``dict[str, CurriculumTermCfg]``)
env: An environment object.
Raises:
TypeError: If curriculum term is not of type :class:`CurriculumTermCfg`.
ValueError: If curriculum term configuration does not satisfy its function signature.
"""
super().__init__(cfg, env)
# prepare logging
self._curriculum_state = dict()
for term_name in self._term_names:
self._curriculum_state[term_name] = None
def __str__(self) -> str:
"""Returns: A string representation for curriculum manager."""
msg = f"<CurriculumManager> contains {len(self._term_names)} active terms.\n"
# create table for term information
table = PrettyTable()
table.title = "Active Curriculum Terms"
table.field_names = ["Index", "Name"]
# set alignment of table columns
table.align["Name"] = "l"
# add info on each term
for index, name in enumerate(self._term_names):
table.add_row([index, name])
# convert table to string
msg += table.get_string()
msg += "\n"
return msg
"""
Properties.
"""
@property
def active_terms(self) -> list[str]:
"""Name of active curriculum terms."""
return self._term_names
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]:
"""Returns the current state of individual curriculum terms.
Note:
This function does not use the environment indices :attr:`env_ids`
and logs the state of all the terms. The argument is only present
to maintain consistency with other classes.
Returns:
Dictionary of curriculum terms and their states.
"""
extras = {}
for term_name, term_state in self._curriculum_state.items():
if term_state is not None:
# deal with dict
if isinstance(term_state, dict):
# each key is a separate state to log
for key, value in term_state.items():
if isinstance(value, torch.Tensor):
value = value.item()
extras[f"Curriculum/{term_name}/{key}"] = value
else:
# log directly if not a dict
if isinstance(term_state, torch.Tensor):
term_state = term_state.item()
extras[f"Curriculum/{term_name}"] = term_state
# reset all the curriculum terms
for term_cfg in self._class_term_cfgs:
term_cfg.func.reset(env_ids=env_ids)
# return logged information
return extras
def compute(self, env_ids: Sequence[int] | None = None):
"""Update the curriculum terms.
This function calls each curriculum term managed by the class.
Args:
env_ids: The list of environment IDs to update.
If None, all the environments are updated. Defaults to None.
"""
# resolve environment indices
if env_ids is None:
env_ids = slice(None)
# iterate over all the curriculum terms
for name, term_cfg in zip(self._term_names, self._term_cfgs):
state = term_cfg.func(self._env, env_ids, **term_cfg.params)
self._curriculum_state[name] = state
"""
Helper functions.
"""
def _prepare_terms(self):
# parse remaining curriculum terms and decimate their information
self._term_names: list[str] = list()
self._term_cfgs: list[CurriculumTermCfg] = list()
self._class_term_cfgs: list[CurriculumTermCfg] = list()
# check if config is dict already
if isinstance(self.cfg, dict):
cfg_items = self.cfg.items()
else:
cfg_items = self.cfg.__dict__.items()
# iterate over all the terms
for term_name, term_cfg in cfg_items:
# check for non config
if term_cfg is None:
continue
# check if the term is a valid term config
if not isinstance(term_cfg, CurriculumTermCfg):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type CurriculumTermCfg."
f" Received: '{type(term_cfg)}'."
)
# resolve common parameters
self._resolve_common_term_cfg(term_name, term_cfg, min_argc=2)
# add name and config to list
self._term_names.append(term_name)
self._term_cfgs.append(term_cfg)
# check if the term is a class
if isinstance(term_cfg.func, ManagerTermBase):
self._class_term_cfgs.append(term_cfg)
| 6,171 | Python | 35.738095 | 108 | 0.602009 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/manager_term_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration terms for different managers."""
from __future__ import annotations
import torch
import warnings
from collections.abc import Callable
from dataclasses import MISSING
from typing import TYPE_CHECKING, Any
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.noise import NoiseCfg
from .scene_entity_cfg import SceneEntityCfg
if TYPE_CHECKING:
from .action_manager import ActionTerm
from .command_manager import CommandTerm
from .manager_base import ManagerTermBase
@configclass
class ManagerTermBaseCfg:
"""Configuration for a manager term."""
func: Callable | ManagerTermBase = MISSING
"""The function or class to be called for the term.
The function must take the environment object as the first argument.
The remaining arguments are specified in the :attr:`params` attribute.
It also supports `callable classes`_, i.e. classes that implement the :meth:`__call__`
method. In this case, the class should inherit from the :class:`ManagerTermBase` class
and implement the required methods.
.. _`callable classes`: https://docs.python.org/3/reference/datamodel.html#object.__call__
"""
params: dict[str, Any | SceneEntityCfg] = dict()
"""The parameters to be passed to the function as keyword arguments. Defaults to an empty dict.
.. note::
If the value is a :class:`SceneEntityCfg` object, the manager will query the scene entity
from the :class:`InteractiveScene` and process the entity's joints and bodies as specified
in the :class:`SceneEntityCfg` object.
"""
##
# Action manager.
##
@configclass
class ActionTermCfg:
"""Configuration for an action term."""
class_type: type[ActionTerm] = MISSING
"""The associated action term class.
The class should inherit from :class:`omni.isaac.orbit.managers.action_manager.ActionTerm`.
"""
asset_name: str = MISSING
"""The name of the scene entity.
This is the name defined in the scene configuration file. See the :class:`InteractiveSceneCfg`
class for more details.
"""
##
# Command manager.
##
@configclass
class CommandTermCfg:
"""Configuration for a command generator term."""
class_type: type[CommandTerm] = MISSING
"""The associated command term class to use.
The class should inherit from :class:`omni.isaac.orbit.managers.command_manager.CommandTerm`.
"""
resampling_time_range: tuple[float, float] = MISSING
"""Time before commands are changed [s]."""
debug_vis: bool = False
"""Whether to visualize debug information. Defaults to False."""
##
# Curriculum manager.
##
@configclass
class CurriculumTermCfg(ManagerTermBaseCfg):
"""Configuration for a curriculum term."""
func: Callable[..., float | dict[str, float] | None] = MISSING
"""The name of the function to be called.
This function should take the environment object, environment indices
and any other parameters as input and return the curriculum state for
logging purposes. If the function returns None, the curriculum state
is not logged.
"""
##
# Observation manager.
##
@configclass
class ObservationTermCfg(ManagerTermBaseCfg):
"""Configuration for an observation term."""
func: Callable[..., torch.Tensor] = MISSING
"""The name of the function to be called.
This function should take the environment object and any other parameters
as input and return the observation signal as torch float tensors of
shape (num_envs, obs_term_dim).
"""
noise: NoiseCfg | None = None
"""The noise to add to the observation. Defaults to None, in which case no noise is added."""
clip: tuple[float, float] | None = None
"""The clipping range for the observation after adding noise. Defaults to None,
in which case no clipping is applied."""
scale: float | None = None
"""The scale to apply to the observation after clipping. Defaults to None,
in which case no scaling is applied (same as setting scale to :obj:`1`)."""
@configclass
class ObservationGroupCfg:
"""Configuration for an observation group."""
concatenate_terms: bool = True
"""Whether to concatenate the observation terms in the group. Defaults to True.
If true, the observation terms in the group are concatenated along the last dimension.
Otherwise, they are kept separate and returned as a dictionary.
"""
enable_corruption: bool = False
"""Whether to enable corruption for the observation group. Defaults to False.
If true, the observation terms in the group are corrupted by adding noise (if specified).
Otherwise, no corruption is applied.
"""
##
# Event manager
##
@configclass
class EventTermCfg(ManagerTermBaseCfg):
"""Configuration for a event term."""
func: Callable[..., None] = MISSING
"""The name of the function to be called.
This function should take the environment object, environment indices
and any other parameters as input.
"""
mode: str = MISSING
"""The mode in which the event term is applied.
Note:
The mode name ``"interval"`` is a special mode that is handled by the
manager Hence, its name is reserved and cannot be used for other modes.
"""
interval_range_s: tuple[float, float] | None = None
"""The range of time in seconds at which the term is applied.
Based on this, the interval is sampled uniformly between the specified
range for each environment instance. The term is applied on the environment
instances where the current time hits the interval time.
Note:
This is only used if the mode is ``"interval"``.
"""
@configclass
class RandomizationTermCfg(EventTermCfg):
"""Configuration for a randomization term.
.. deprecated:: v0.3.0
This class is deprecated and will be removed in v0.4.0. Please use :class:`EventTermCfg` instead.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Deprecation warning.
warnings.warn(
"The RandomizationTermCfg has been renamed to EventTermCfg and will be removed in v0.4.0. Please use"
" EventTermCfg instead.",
DeprecationWarning,
)
##
# Reward manager.
##
@configclass
class RewardTermCfg(ManagerTermBaseCfg):
"""Configuration for a reward term."""
func: Callable[..., torch.Tensor] = MISSING
"""The name of the function to be called.
This function should take the environment object and any other parameters
as input and return the reward signals as torch float tensors of
shape (num_envs,).
"""
weight: float = MISSING
"""The weight of the reward term.
This is multiplied with the reward term's value to compute the final
reward.
Note:
If the weight is zero, the reward term is ignored.
"""
##
# Termination manager.
##
@configclass
class TerminationTermCfg(ManagerTermBaseCfg):
"""Configuration for a termination term."""
func: Callable[..., torch.Tensor] = MISSING
"""The name of the function to be called.
This function should take the environment object and any other parameters
as input and return the termination signals as torch boolean tensors of
shape (num_envs,).
"""
time_out: bool = False
"""Whether the termination term contributes towards episodic timeouts. Defaults to False.
Note:
These usually correspond to tasks that have a fixed time limit.
"""
| 7,667 | Python | 27.295203 | 113 | 0.696361 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/reward_manager.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Reward manager for computing reward signals for a given world."""
from __future__ import annotations
import torch
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
from .manager_base import ManagerBase, ManagerTermBase
from .manager_term_cfg import RewardTermCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
class RewardManager(ManagerBase):
"""Manager for computing reward signals for a given world.
The reward manager computes the total reward as a sum of the weighted reward terms. The reward
terms are parsed from a nested config class containing the reward manger's settings and reward
terms configuration.
The reward terms are parsed from a config class containing the manager's settings and each term's
parameters. Each reward term should instantiate the :class:`RewardTermCfg` class.
.. note::
The reward manager multiplies the reward term's ``weight`` with the time-step interval ``dt``
of the environment. This is done to ensure that the computed reward terms are balanced with
respect to the chosen time-step interval in the environment.
"""
_env: RLTaskEnv
"""The environment instance."""
def __init__(self, cfg: object, env: RLTaskEnv):
"""Initialize the reward manager.
Args:
cfg: The configuration object or dictionary (``dict[str, RewardTermCfg]``).
env: The environment instance.
"""
super().__init__(cfg, env)
# prepare extra info to store individual reward term information
self._episode_sums = dict()
for term_name in self._term_names:
self._episode_sums[term_name] = torch.zeros(self.num_envs, dtype=torch.float, device=self.device)
# create buffer for managing reward per environment
self._reward_buf = torch.zeros(self.num_envs, dtype=torch.float, device=self.device)
def __str__(self) -> str:
"""Returns: A string representation for reward manager."""
msg = f"<RewardManager> contains {len(self._term_names)} active terms.\n"
# create table for term information
table = PrettyTable()
table.title = "Active Reward Terms"
table.field_names = ["Index", "Name", "Weight"]
# set alignment of table columns
table.align["Name"] = "l"
table.align["Weight"] = "r"
# add info on each term
for index, (name, term_cfg) in enumerate(zip(self._term_names, self._term_cfgs)):
table.add_row([index, name, term_cfg.weight])
# convert table to string
msg += table.get_string()
msg += "\n"
return msg
"""
Properties.
"""
@property
def active_terms(self) -> list[str]:
"""Name of active reward terms."""
return self._term_names
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, torch.Tensor]:
"""Returns the episodic sum of individual reward terms.
Args:
env_ids: The environment ids for which the episodic sum of
individual reward terms is to be returned. Defaults to all the environment ids.
Returns:
Dictionary of episodic sum of individual reward terms.
"""
# resolve environment ids
if env_ids is None:
env_ids = slice(None)
# store information
extras = {}
for key in self._episode_sums.keys():
# store information
# r_1 + r_2 + ... + r_n
episodic_sum_avg = torch.mean(self._episode_sums[key][env_ids])
extras["Episode Reward/" + key] = episodic_sum_avg / self._env.max_episode_length_s
# reset episodic sum
self._episode_sums[key][env_ids] = 0.0
# reset all the reward terms
for term_cfg in self._class_term_cfgs:
term_cfg.func.reset(env_ids=env_ids)
# return logged information
return extras
def compute(self, dt: float) -> torch.Tensor:
"""Computes the reward signal as a weighted sum of individual terms.
This function calls each reward term managed by the class and adds them to compute the net
reward signal. It also updates the episodic sums corresponding to individual reward terms.
Args:
dt: The time-step interval of the environment.
Returns:
The net reward signal of shape (num_envs,).
"""
# reset computation
self._reward_buf[:] = 0.0
# iterate over all the reward terms
for name, term_cfg in zip(self._term_names, self._term_cfgs):
# skip if weight is zero (kind of a micro-optimization)
if term_cfg.weight == 0.0:
continue
# compute term's value
value = term_cfg.func(self._env, **term_cfg.params) * term_cfg.weight * dt
# update total reward
self._reward_buf += value
# update episodic sum
self._episode_sums[name] += value
return self._reward_buf
"""
Operations - Term settings.
"""
def set_term_cfg(self, term_name: str, cfg: RewardTermCfg):
"""Sets the configuration of the specified term into the manager.
Args:
term_name: The name of the reward term.
cfg: The configuration for the reward term.
Raises:
ValueError: If the term name is not found.
"""
if term_name not in self._term_names:
raise ValueError(f"Reward term '{term_name}' not found.")
# set the configuration
self._term_cfgs[self._term_names.index(term_name)] = cfg
def get_term_cfg(self, term_name: str) -> RewardTermCfg:
"""Gets the configuration for the specified term.
Args:
term_name: The name of the reward term.
Returns:
The configuration of the reward term.
Raises:
ValueError: If the term name is not found.
"""
if term_name not in self._term_names:
raise ValueError(f"Reward term '{term_name}' not found.")
# return the configuration
return self._term_cfgs[self._term_names.index(term_name)]
"""
Helper functions.
"""
def _prepare_terms(self):
"""Prepares a list of reward functions."""
# parse remaining reward terms and decimate their information
self._term_names: list[str] = list()
self._term_cfgs: list[RewardTermCfg] = list()
self._class_term_cfgs: list[RewardTermCfg] = list()
# check if config is dict already
if isinstance(self.cfg, dict):
cfg_items = self.cfg.items()
else:
cfg_items = self.cfg.__dict__.items()
# iterate over all the terms
for term_name, term_cfg in cfg_items:
# check for non config
if term_cfg is None:
continue
# check for valid config type
if not isinstance(term_cfg, RewardTermCfg):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type RewardTermCfg."
f" Received: '{type(term_cfg)}'."
)
# check for valid weight type
if not isinstance(term_cfg.weight, (float, int)):
raise TypeError(
f"Weight for the term '{term_name}' is not of type float or int."
f" Received: '{type(term_cfg.weight)}'."
)
# resolve common parameters
self._resolve_common_term_cfg(term_name, term_cfg, min_argc=1)
# add function to list
self._term_names.append(term_name)
self._term_cfgs.append(term_cfg)
# check if the term is a class
if isinstance(term_cfg.func, ManagerTermBase):
self._class_term_cfgs.append(term_cfg)
| 8,148 | Python | 35.379464 | 109 | 0.602111 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/action_manager.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Action manager for processing actions sent to the environment."""
from __future__ import annotations
import torch
from abc import abstractmethod
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import AssetBase
from .manager_base import ManagerBase, ManagerTermBase
from .manager_term_cfg import ActionTermCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
class ActionTerm(ManagerTermBase):
"""Base class for action terms.
The action term is responsible for processing the raw actions sent to the environment
and applying them to the asset managed by the term. The action term is comprised of two
operations:
* Processing of actions: This operation is performed once per **environment step** and
is responsible for pre-processing the raw actions sent to the environment.
* Applying actions: This operation is performed once per **simulation step** and is
responsible for applying the processed actions to the asset managed by the term.
"""
def __init__(self, cfg: ActionTermCfg, env: BaseEnv):
"""Initialize the action term.
Args:
cfg: The configuration object.
env: The environment instance.
"""
# call the base class constructor
super().__init__(cfg, env)
# parse config to obtain asset to which the term is applied
self._asset: AssetBase = self._env.scene[self.cfg.asset_name]
"""
Properties.
"""
@property
@abstractmethod
def action_dim(self) -> int:
"""Dimension of the action term."""
raise NotImplementedError
@property
@abstractmethod
def raw_actions(self) -> torch.Tensor:
"""The input/raw actions sent to the term."""
raise NotImplementedError
@property
@abstractmethod
def processed_actions(self) -> torch.Tensor:
"""The actions computed by the term after applying any processing."""
raise NotImplementedError
"""
Operations.
"""
@abstractmethod
def process_actions(self, actions: torch.Tensor):
"""Processes the actions sent to the environment.
Note:
This function is called once per environment step by the manager.
Args:
actions: The actions to process.
"""
raise NotImplementedError
@abstractmethod
def apply_actions(self):
"""Applies the actions to the asset managed by the term.
Note:
This is called at every simulation step by the manager.
"""
raise NotImplementedError
class ActionManager(ManagerBase):
"""Manager for processing and applying actions for a given world.
The action manager handles the interpretation and application of user-defined
actions on a given world. It is comprised of different action terms that decide
the dimension of the expected actions.
The action manager performs operations at two stages:
* processing of actions: It splits the input actions to each term and performs any
pre-processing needed. This should be called once at every environment step.
* apply actions: This operation typically sets the processed actions into the assets in the
scene (such as robots). It should be called before every simulation step.
"""
def __init__(self, cfg: object, env: BaseEnv):
"""Initialize the action manager.
Args:
cfg: The configuration object or dictionary (``dict[str, ActionTermCfg]``).
env: The environment instance.
"""
super().__init__(cfg, env)
# create buffers to store actions
self._action = torch.zeros((self.num_envs, self.total_action_dim), device=self.device)
self._prev_action = torch.zeros_like(self._action)
def __str__(self) -> str:
"""Returns: A string representation for action manager."""
msg = f"<ActionManager> contains {len(self._term_names)} active terms.\n"
# create table for term information
table = PrettyTable()
table.title = f"Active Action Terms (shape: {self.total_action_dim})"
table.field_names = ["Index", "Name", "Dimension"]
# set alignment of table columns
table.align["Name"] = "l"
table.align["Dimension"] = "r"
# add info on each term
for index, (name, term) in enumerate(self._terms.items()):
table.add_row([index, name, term.action_dim])
# convert table to string
msg += table.get_string()
msg += "\n"
return msg
"""
Properties.
"""
@property
def total_action_dim(self) -> int:
"""Total dimension of actions."""
return sum(self.action_term_dim)
@property
def active_terms(self) -> list[str]:
"""Name of active action terms."""
return self._term_names
@property
def action_term_dim(self) -> list[int]:
"""Shape of each action term."""
return [term.action_dim for term in self._terms.values()]
@property
def action(self) -> torch.Tensor:
"""The actions sent to the environment. Shape is (num_envs, total_action_dim)."""
return self._action
@property
def prev_action(self) -> torch.Tensor:
"""The previous actions sent to the environment. Shape is (num_envs, total_action_dim)."""
return self._prev_action
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, torch.Tensor]:
"""Resets the action history.
Args:
env_ids: The environment ids. Defaults to None, in which case
all environments are considered.
Returns:
An empty dictionary.
"""
# resolve environment ids
if env_ids is None:
env_ids = slice(None)
# reset the action history
self._prev_action[env_ids] = 0.0
self._action[env_ids] = 0.0
# reset all action terms
for term in self._terms.values():
term.reset(env_ids=env_ids)
# nothing to log here
return {}
def process_action(self, action: torch.Tensor):
"""Processes the actions sent to the environment.
Note:
This function should be called once per environment step.
Args:
action: The actions to process.
"""
# check if action dimension is valid
if self.total_action_dim != action.shape[1]:
raise ValueError(f"Invalid action shape, expected: {self.total_action_dim}, received: {action.shape[1]}.")
# store the input actions
self._prev_action[:] = self._action
self._action[:] = action.to(self.device)
# split the actions and apply to each tensor
idx = 0
for term in self._terms.values():
term_actions = action[:, idx : idx + term.action_dim]
term.process_actions(term_actions)
idx += term.action_dim
def apply_action(self) -> None:
"""Applies the actions to the environment/simulation.
Note:
This should be called at every simulation step.
"""
for term in self._terms.values():
term.apply_actions()
def get_term(self, name: str) -> ActionTerm:
"""Returns the action term with the specified name.
Args:
name: The name of the action term.
Returns:
The action term with the specified name.
"""
return self._terms[name]
"""
Helper functions.
"""
def _prepare_terms(self):
"""Prepares a list of action terms."""
# parse action terms from the config
self._term_names: list[str] = list()
self._terms: dict[str, ActionTerm] = dict()
# check if config is dict already
if isinstance(self.cfg, dict):
cfg_items = self.cfg.items()
else:
cfg_items = self.cfg.__dict__.items()
for term_name, term_cfg in cfg_items:
# check if term config is None
if term_cfg is None:
continue
# check valid type
if not isinstance(term_cfg, ActionTermCfg):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type ActionTermCfg."
f" Received: '{type(term_cfg)}'."
)
# create the action term
term = term_cfg.class_type(term_cfg, self._env)
# sanity check if term is valid type
if not isinstance(term, ActionTerm):
raise TypeError(f"Returned object for the term '{term_name}' is not of type ActionType.")
# add term name and parameters
self._term_names.append(term_name)
self._terms[term_name] = term
| 9,069 | Python | 31.862319 | 118 | 0.614732 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/managers/termination_manager.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Termination manager for computing done signals for a given world."""
from __future__ import annotations
import torch
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
from .manager_base import ManagerBase, ManagerTermBase
from .manager_term_cfg import TerminationTermCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
class TerminationManager(ManagerBase):
"""Manager for computing done signals for a given world.
The termination manager computes the termination signal (also called dones) as a combination
of termination terms. Each termination term is a function which takes the environment as an
argument and returns a boolean tensor of shape (num_envs,). The termination manager
computes the termination signal as the union (logical or) of all the termination terms.
Following the `Gymnasium API <https://gymnasium.farama.org/tutorials/gymnasium_basics/handling_time_limits/>`_,
the termination signal is computed as the logical OR of the following signals:
* **Time-out**: This signal is set to true if the environment has ended after an externally defined condition
(that is outside the scope of a MDP). For example, the environment may be terminated if the episode has
timed out (i.e. reached max episode length).
* **Terminated**: This signal is set to true if the environment has reached a terminal state defined by the
environment. This state may correspond to task success, task failure, robot falling, etc.
These signals can be individually accessed using the :attr:`time_outs` and :attr:`terminated` properties.
The termination terms are parsed from a config class containing the manager's settings and each term's
parameters. Each termination term should instantiate the :class:`TerminationTermCfg` class. The term's
configuration :attr:`TerminationTermCfg.time_out` decides whether the term is a timeout or a termination term.
"""
_env: RLTaskEnv
"""The environment instance."""
def __init__(self, cfg: object, env: RLTaskEnv):
"""Initializes the termination manager.
Args:
cfg: The configuration object or dictionary (``dict[str, TerminationTermCfg]``).
env: An environment object.
"""
super().__init__(cfg, env)
# prepare extra info to store individual termination term information
self._term_dones = dict()
for term_name in self._term_names:
self._term_dones[term_name] = torch.zeros(self.num_envs, device=self.device, dtype=torch.bool)
# create buffer for managing termination per environment
self._truncated_buf = torch.zeros(self.num_envs, device=self.device, dtype=torch.bool)
self._terminated_buf = torch.zeros_like(self._truncated_buf)
def __str__(self) -> str:
"""Returns: A string representation for termination manager."""
msg = f"<TerminationManager> contains {len(self._term_names)} active terms.\n"
# create table for term information
table = PrettyTable()
table.title = "Active Termination Terms"
table.field_names = ["Index", "Name", "Time Out"]
# set alignment of table columns
table.align["Name"] = "l"
# add info on each term
for index, (name, term_cfg) in enumerate(zip(self._term_names, self._term_cfgs)):
table.add_row([index, name, term_cfg.time_out])
# convert table to string
msg += table.get_string()
msg += "\n"
return msg
"""
Properties.
"""
@property
def active_terms(self) -> list[str]:
"""Name of active termination terms."""
return self._term_names
@property
def dones(self) -> torch.Tensor:
"""The net termination signal. Shape is (num_envs,)."""
return self._truncated_buf | self._terminated_buf
@property
def time_outs(self) -> torch.Tensor:
"""The timeout signal (reaching max episode length). Shape is (num_envs,).
This signal is set to true if the environment has ended after an externally defined condition
(that is outside the scope of a MDP). For example, the environment may be terminated if the episode has
timed out (i.e. reached max episode length).
"""
return self._truncated_buf
@property
def terminated(self) -> torch.Tensor:
"""The terminated signal (reaching a terminal state). Shape is (num_envs,).
This signal is set to true if the environment has reached a terminal state defined by the environment.
This state may correspond to task success, task failure, robot falling, etc.
"""
return self._terminated_buf
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, torch.Tensor]:
"""Returns the episodic counts of individual termination terms.
Args:
env_ids: The environment ids. Defaults to None, in which case
all environments are considered.
Returns:
Dictionary of episodic sum of individual reward terms.
"""
# resolve environment ids
if env_ids is None:
env_ids = slice(None)
# add to episode dict
extras = {}
for key in self._term_dones.keys():
# store information
extras["Episode Termination/" + key] = torch.count_nonzero(self._term_dones[key][env_ids]).item()
# reset all the reward terms
for term_cfg in self._class_term_cfgs:
term_cfg.func.reset(env_ids=env_ids)
# return logged information
return extras
def compute(self) -> torch.Tensor:
"""Computes the termination signal as union of individual terms.
This function calls each termination term managed by the class and performs a logical OR operation
to compute the net termination signal.
Returns:
The combined termination signal of shape (num_envs,).
"""
# reset computation
self._truncated_buf[:] = False
self._terminated_buf[:] = False
# iterate over all the termination terms
for name, term_cfg in zip(self._term_names, self._term_cfgs):
value = term_cfg.func(self._env, **term_cfg.params)
# store timeout signal separately
if term_cfg.time_out:
self._truncated_buf |= value
else:
self._terminated_buf |= value
# add to episode dones
self._term_dones[name][:] = value
# return combined termination signal
return self._truncated_buf | self._terminated_buf
def get_term(self, name: str) -> torch.Tensor:
"""Returns the termination term with the specified name.
Args:
name: The name of the termination term.
Returns:
The corresponding termination term value. Shape is (num_envs,).
"""
return self._term_dones[name]
"""
Operations - Term settings.
"""
def set_term_cfg(self, term_name: str, cfg: TerminationTermCfg):
"""Sets the configuration of the specified term into the manager.
Args:
term_name: The name of the termination term.
cfg: The configuration for the termination term.
Raises:
ValueError: If the term name is not found.
"""
if term_name not in self._term_names:
raise ValueError(f"Termination term '{term_name}' not found.")
# set the configuration
self._term_cfgs[self._term_names.index(term_name)] = cfg
def get_term_cfg(self, term_name: str) -> TerminationTermCfg:
"""Gets the configuration for the specified term.
Args:
term_name: The name of the termination term.
Returns:
The configuration of the termination term.
Raises:
ValueError: If the term name is not found.
"""
if term_name not in self._term_names:
raise ValueError(f"Termination term '{term_name}' not found.")
# return the configuration
return self._term_cfgs[self._term_names.index(term_name)]
"""
Helper functions.
"""
def _prepare_terms(self):
"""Prepares a list of termination functions."""
# parse remaining termination terms and decimate their information
self._term_names: list[str] = list()
self._term_cfgs: list[TerminationTermCfg] = list()
self._class_term_cfgs: list[TerminationTermCfg] = list()
# check if config is dict already
if isinstance(self.cfg, dict):
cfg_items = self.cfg.items()
else:
cfg_items = self.cfg.__dict__.items()
# iterate over all the terms
for term_name, term_cfg in cfg_items:
# check for non config
if term_cfg is None:
continue
# check for valid config type
if not isinstance(term_cfg, TerminationTermCfg):
raise TypeError(
f"Configuration for the term '{term_name}' is not of type TerminationTermCfg."
f" Received: '{type(term_cfg)}'."
)
# resolve common parameters
self._resolve_common_term_cfg(term_name, term_cfg, min_argc=1)
# add function to list
self._term_names.append(term_name)
self._term_cfgs.append(term_cfg)
# check if the term is a class
if isinstance(term_cfg.func, ManagerTermBase):
self._class_term_cfgs.append(term_cfg)
| 9,845 | Python | 38.071428 | 115 | 0.634027 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/controllers/rmp_flow.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 dataclasses import MISSING
import omni.isaac.core.utils.prims as prim_utils
from omni.isaac.core.articulations import Articulation
from omni.isaac.core.simulation_context import SimulationContext
from omni.isaac.motion_generation import ArticulationMotionPolicy
from omni.isaac.motion_generation.lula.motion_policies import RmpFlow, RmpFlowSmoothed
from omni.isaac.orbit.utils import configclass
@configclass
class RmpFlowControllerCfg:
"""Configuration for RMP-Flow controller (provided through LULA library)."""
name: str = "rmp_flow"
"""Name of the controller. Supported: "rmp_flow", "rmp_flow_smoothed". Defaults to "rmp_flow"."""
config_file: str = MISSING
"""Path to the configuration file for the controller."""
urdf_file: str = MISSING
"""Path to the URDF model of the robot."""
collision_file: str = MISSING
"""Path to collision model description of the robot."""
frame_name: str = MISSING
"""Name of the robot frame for task space (must be present in the URDF)."""
evaluations_per_frame: float = MISSING
"""Number of substeps during Euler integration inside LULA world model."""
ignore_robot_state_updates: bool = False
"""If true, then state of the world model inside controller is rolled out. Defaults to False."""
class RmpFlowController:
"""Wraps around RMPFlow from IsaacSim for batched environments."""
def __init__(self, cfg: RmpFlowControllerCfg, device: str):
"""Initialize the controller.
Args:
cfg: The configuration for the controller.
device: The device to use for computation.
"""
# store input
self.cfg = cfg
self._device = device
# display info
print(f"[INFO]: Loading RMPFlow controller URDF from: {self.cfg.urdf_file}")
"""
Properties.
"""
@property
def num_actions(self) -> int:
"""Dimension of the action space of controller."""
return 7
"""
Operations.
"""
def initialize(self, prim_paths_expr: str):
"""Initialize the controller.
Args:
prim_paths_expr: The expression to find the articulation prim paths.
"""
# obtain the simulation time
physics_dt = SimulationContext.instance().get_physics_dt()
# find all prims
self._prim_paths = prim_utils.find_matching_prim_paths(prim_paths_expr)
self.num_robots = len(self._prim_paths)
# resolve controller
if self.cfg.name == "rmp_flow":
controller_cls = RmpFlow
elif self.cfg.name == "rmp_flow_smoothed":
controller_cls = RmpFlowSmoothed
else:
raise ValueError(f"Unsupported controller in Lula library: {self.cfg.name}")
# create all franka robots references and their controllers
self.articulation_policies = list()
for prim_path in self._prim_paths:
# add robot reference
robot = Articulation(prim_path)
robot.initialize()
# add controller
rmpflow = controller_cls(
robot_description_path=self.cfg.collision_file,
urdf_path=self.cfg.urdf_file,
rmpflow_config_path=self.cfg.config_file,
end_effector_frame_name=self.cfg.frame_name,
maximum_substep_size=physics_dt / self.cfg.evaluations_per_frame,
ignore_robot_state_updates=self.cfg.ignore_robot_state_updates,
)
# wrap rmpflow to connect to the Franka robot articulation
articulation_policy = ArticulationMotionPolicy(robot, rmpflow, physics_dt)
self.articulation_policies.append(articulation_policy)
# get number of active joints
self.active_dof_names = self.articulation_policies[0].get_motion_policy().get_active_joints()
self.num_dof = len(self.active_dof_names)
# create buffers
# -- for storing command
self._command = torch.zeros(self.num_robots, self.num_actions, device=self._device)
# -- for policy output
self.dof_pos_target = torch.zeros((self.num_robots, self.num_dof), device=self._device)
self.dof_vel_target = torch.zeros((self.num_robots, self.num_dof), device=self._device)
def reset_idx(self, robot_ids: torch.Tensor = None):
"""Reset the internals."""
# if no robot ids are provided, then reset all robots
if robot_ids is None:
robot_ids = torch.arange(self.num_robots, device=self._device)
# reset policies for specified robots
for index in robot_ids:
self.articulation_policies[index].motion_policy.reset()
def set_command(self, command: torch.Tensor):
"""Set target end-effector pose command."""
# store command
self._command[:] = command
def compute(self) -> tuple[torch.Tensor, torch.Tensor]:
"""Performs inference with the controller.
Returns:
The target joint positions and velocity commands.
"""
# convert command to numpy
command = self._command.cpu().numpy()
# compute control actions
for i, policy in enumerate(self.articulation_policies):
# enable type-hinting
policy: ArticulationMotionPolicy
# set rmpflow target to be the current position of the target cube.
policy.get_motion_policy().set_end_effector_target(
target_position=command[i, 0:3], target_orientation=command[i, 3:7]
)
# apply action on the robot
action = policy.get_next_articulation_action()
# copy actions into buffer
self.dof_pos_target[i, :] = torch.from_numpy(action.joint_positions[:]).to(self.dof_pos_target)
self.dof_vel_target[i, :] = torch.from_numpy(action.joint_velocities[:]).to(self.dof_vel_target)
return self.dof_pos_target, self.dof_vel_target
| 6,146 | Python | 39.440789 | 108 | 0.643345 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/controllers/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package for different controllers and motion-generators.
Controllers or motion generators are responsible for closed-loop tracking of a given command. The
controller can be a simple PID controller or a more complex controller such as impedance control
or inverse kinematics control. The controller is responsible for generating the desired joint-level
commands to be sent to the robot.
"""
from .differential_ik import DifferentialIKController
from .differential_ik_cfg import DifferentialIKControllerCfg
| 637 | Python | 38.874998 | 99 | 0.814757 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/controllers/operational_space.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 dataclasses import MISSING
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.math import apply_delta_pose, compute_pose_error
@configclass
class OperationSpaceControllerCfg:
"""Configuration for operation-space controller."""
command_types: Sequence[str] = MISSING
"""Type of command.
It has two sub-strings joined by underscore:
- type of command mode: "position", "pose", "force"
- type of command resolving: "abs" (absolute), "rel" (relative)
"""
impedance_mode: str = MISSING
"""Type of gains for motion control: "fixed", "variable", "variable_kp"."""
uncouple_motion_wrench: bool = False
"""Whether to decouple the wrench computation from task-space pose (motion) error."""
motion_control_axes: Sequence[int] = (1, 1, 1, 1, 1, 1)
"""Motion direction to control. Mark as 0/1 for each axis."""
force_control_axes: Sequence[int] = (0, 0, 0, 0, 0, 0)
"""Force direction to control. Mark as 0/1 for each axis."""
inertial_compensation: bool = False
"""Whether to perform inertial compensation for motion control (inverse dynamics)."""
gravity_compensation: bool = False
"""Whether to perform gravity compensation."""
stiffness: float | Sequence[float] = MISSING
"""The positional gain for determining wrenches based on task-space pose error."""
damping_ratio: float | Sequence[float] | None = None
"""The damping ratio is used in-conjunction with positional gain to compute wrenches
based on task-space 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".
"""
force_stiffness: float | Sequence[float] = None
"""The positional gain for determining wrenches for closed-loop force control.
If obj:`None`, then open-loop control of desired forces is performed.
"""
position_command_scale: tuple[float, float, float] = (1.0, 1.0, 1.0)
"""Scaling of the position command received. Used only in relative mode."""
rotation_command_scale: tuple[float, float, float] = (1.0, 1.0, 1.0)
"""Scaling of the rotation command received. Used only in relative mode."""
class OperationSpaceController:
"""Operation-space controller.
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: OperationSpaceControllerCfg, num_robots: int, num_dof: int, device: str):
"""Initialize operation-space controller.
Args:
cfg: The configuration for operation-space controller.
num_robots: The number of robots to control.
num_dof: The number of degrees of freedom of the robot.
device: The device to use for computations.
Raises:
ValueError: When invalid control command is provided.
"""
# store inputs
self.cfg = cfg
self.num_robots = num_robots
self.num_dof = num_dof
self._device = device
# resolve tasks-pace target dimensions
self.target_list = list()
for command_type in self.cfg.command_types:
if "position" in command_type:
self.target_list.append(3)
elif command_type == "pose_rel":
self.target_list.append(6)
elif command_type == "pose_abs":
self.target_list.append(7)
elif command_type == "force_abs":
self.target_list.append(6)
else:
raise ValueError(f"Invalid control command: {command_type}.")
self.target_dim = sum(self.target_list)
# create buffers
# -- selection matrices
self._selection_matrix_motion = torch.diag(
torch.tensor(self.cfg.motion_control_axes, dtype=torch.float, device=self._device)
)
self._selection_matrix_force = torch.diag(
torch.tensor(self.cfg.force_control_axes, dtype=torch.float, device=self._device)
)
# -- commands
self._task_space_target = torch.zeros(self.num_robots, self.target_dim, device=self._device)
# -- scaling of command
self._position_command_scale = torch.diag(torch.tensor(self.cfg.position_command_scale, device=self._device))
self._rotation_command_scale = torch.diag(torch.tensor(self.cfg.rotation_command_scale, device=self._device))
# -- motion control gains
self._p_gains = torch.zeros(self.num_robots, 6, device=self._device)
self._p_gains[:] = torch.tensor(self.cfg.stiffness, device=self._device)
self._d_gains = 2 * torch.sqrt(self._p_gains) * torch.tensor(self.cfg.damping_ratio, device=self._device)
# -- force control gains
if self.cfg.force_stiffness is not None:
self._p_wrench_gains = torch.zeros(self.num_robots, 6, device=self._device)
self._p_wrench_gains[:] = torch.tensor(self.cfg.force_stiffness, device=self._device)
else:
self._p_wrench_gains = None
# -- position gain limits
self._p_gains_limits = torch.zeros(self.num_robots, 6, device=self._device)
self._p_gains_limits[..., 0], self._p_gains_limits[..., 1] = (
self.cfg.stiffness_limits[0],
self.cfg.stiffness_limits[1],
)
# -- damping ratio limits
self._damping_ratio_limits = torch.zeros_like(self._p_gains_limits)
self._damping_ratio_limits[..., 0], self._damping_ratio_limits[..., 1] = (
self.cfg.damping_ratio_limits[0],
self.cfg.damping_ratio_limits[1],
)
# -- storing outputs
self._desired_torques = torch.zeros(self.num_robots, self.num_dof, self.num_dof, device=self._device)
"""
Properties.
"""
@property
def num_actions(self) -> int:
"""Dimension of the action space of controller."""
# impedance mode
if self.cfg.impedance_mode == "fixed":
# task-space pose
return self.target_dim
elif self.cfg.impedance_mode == "variable_kp":
# task-space pose + stiffness
return self.target_dim + 6
elif self.cfg.impedance_mode == "variable":
# task-space pose + stiffness + damping
return self.target_dim + 6 + 6
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 or force command.
Args:
command: The target end-effector pose or force command.
"""
# 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._task_space_target[:] = command
elif self.cfg.impedance_mode == "variable_kp":
# split input command
task_space_command, stiffness = torch.tensor_split(command, (self.target_dim, 6), dim=-1)
# format command
stiffness = stiffness.clip_(min=self._p_gains_limits[0], max=self._p_gains_limits[1])
# joint positions + stiffness
self._task_space_target[:] = task_space_command.squeeze(dim=-1)
self._p_gains[:] = stiffness
self._d_gains[:] = 2 * torch.sqrt(self._p_gains) # critically damped
elif self.cfg.impedance_mode == "variable":
# split input command
task_space_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._task_space_target[:] = task_space_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,
jacobian: torch.Tensor,
ee_pose: torch.Tensor | None = None,
ee_vel: torch.Tensor | None = None,
ee_force: torch.Tensor | None = None,
mass_matrix: torch.Tensor | None = None,
gravity: torch.Tensor | None = None,
) -> torch.Tensor:
"""Performs inference with the controller.
Args:
jacobian: The Jacobian matrix of the end-effector.
ee_pose: The current end-effector pose. It is a tensor of shape
(num_robots, 7), which contains the position and quaternion (w, x, y, z). Defaults to None.
ee_vel: The current end-effector velocity. It is a tensor of shape
(num_robots, 6), which contains the linear and angular velocities. Defaults to None.
ee_force: The current external force on the end-effector.
It is a tensor of shape (num_robots, 3), which contains the linear force. Defaults to None.
mass_matrix: The joint-space inertial matrix. Defaults to None.
gravity: The joint-space gravity vector. Defaults to None.
Raises:
ValueError: When the end-effector pose is not provided for the 'position_rel' command.
ValueError: When the end-effector pose is not provided for the 'position_abs' command.
ValueError: When the end-effector pose is not provided for the 'pose_rel' command.
ValueError: When an invalid command type is provided.
ValueError: When motion-control is enabled but the end-effector pose or velocity is not provided.
ValueError: When force-control is enabled but the end-effector force is not provided.
ValueError: When inertial compensation is enabled but the mass matrix is not provided.
ValueError: When gravity compensation is enabled but the gravity vector is not provided.
Returns:
The target joint torques commands.
"""
# buffers for motion/force control
desired_ee_pos = None
desired_ee_rot = None
desired_ee_force = None
# resolve the commands
target_groups = torch.split(self._task_space_target, self.target_list)
for command_type, target in zip(self.cfg.command_types, target_groups):
if command_type == "position_rel":
# check input is provided
if ee_pose is None:
raise ValueError("End-effector pose is required for 'position_rel' command.")
# scale command
target @= self._position_command_scale
# compute targets
desired_ee_pos = ee_pose[:, :3] + target
desired_ee_rot = ee_pose[:, 3:]
elif command_type == "position_abs":
# check input is provided
if ee_pose is None:
raise ValueError("End-effector pose is required for 'position_abs' command.")
# compute targets
desired_ee_pos = target
desired_ee_rot = ee_pose[:, 3:]
elif command_type == "pose_rel":
# check input is provided
if ee_pose is None:
raise ValueError("End-effector pose is required for 'pose_rel' command.")
# scale command
target[:, 0:3] @= self._position_command_scale
target[:, 3:6] @= self._rotation_command_scale
# compute targets
desired_ee_pos, desired_ee_rot = apply_delta_pose(ee_pose[:, :3], ee_pose[:, 3:], target)
elif command_type == "pose_abs":
# compute targets
desired_ee_pos = target[:, 0:3]
desired_ee_rot = target[:, 3:7]
elif command_type == "force_abs":
# compute targets
desired_ee_force = target
else:
raise ValueError(f"Invalid control command: {self.cfg.command_type}.")
# reset desired joint torques
self._desired_torques[:] = 0
# compute for motion-control
if desired_ee_pos is not None:
# check input is provided
if ee_pose is None or ee_vel is None:
raise ValueError("End-effector pose and velocity are required for motion control.")
# -- end-effector tracking error
pose_error = compute_pose_error(
ee_pose[:, :3], ee_pose[:, 3:], desired_ee_pos, desired_ee_rot, rot_error_type="axis_angle"
)
velocity_error = -ee_vel # zero target velocity
# -- desired end-effector acceleration (spring damped system)
des_ee_acc = self._p_gains * pose_error + self._d_gains * velocity_error
# -- inertial compensation
if self.cfg.inertial_compensation:
# check input is provided
if mass_matrix is None:
raise ValueError("Mass matrix is required for inertial compensation.")
# compute task-space dynamics quantities
# wrench = (J M^(-1) J^T)^(-1) * \ddot(x_des)
mass_matrix_inv = torch.inverse(mass_matrix)
if self.cfg.uncouple_motion_wrench:
# decoupled-mass matrices
lambda_pos = torch.inverse(jacobian[:, 0:3] @ mass_matrix_inv * jacobian[:, 0:3].T)
lambda_ori = torch.inverse(jacobian[:, 3:6] @ mass_matrix_inv * jacobian[:, 3:6].T)
# desired end-effector wrench (from pseudo-dynamics)
decoupled_force = lambda_pos @ des_ee_acc[:, 0:3]
decoupled_torque = lambda_ori @ des_ee_acc[:, 3:6]
des_motion_wrench = torch.cat(decoupled_force, decoupled_torque)
else:
# coupled dynamics
lambda_full = torch.inverse(jacobian @ mass_matrix_inv * jacobian.T)
# desired end-effector wrench (from pseudo-dynamics)
des_motion_wrench = lambda_full @ des_ee_acc
else:
# task-space impedance control
# wrench = \ddot(x_des)
des_motion_wrench = des_ee_acc
# -- joint-space wrench
self._desired_torques += jacobian.T @ self._selection_matrix_motion @ des_motion_wrench
# compute for force control
if desired_ee_force is not None:
# -- task-space wrench
if self.cfg.stiffness is not None:
# check input is provided
if ee_force is None:
raise ValueError("End-effector force is required for closed-loop force control.")
# closed-loop control
des_force_wrench = desired_ee_force + self._p_wrench_gains * (desired_ee_force - ee_force)
else:
# open-loop control
des_force_wrench = desired_ee_force
# -- joint-space wrench
self._desired_torques += jacobian.T @ self._selection_matrix_force @ des_force_wrench
# add gravity compensation (bias correction)
if self.cfg.gravity_compensation:
# check input is provided
if gravity is None:
raise ValueError("Gravity vector is required for gravity compensation.")
# add gravity compensation
self._desired_torques += gravity
return self._desired_torques
| 16,820 | Python | 44.462162 | 153 | 0.597265 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/controllers/differential_ik.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
from omni.isaac.orbit.utils.math import apply_delta_pose, compute_pose_error
if TYPE_CHECKING:
from .differential_ik_cfg import DifferentialIKControllerCfg
class DifferentialIKController:
r"""Differential inverse kinematics (IK) controller.
This controller is based on the concept of differential inverse kinematics [1, 2] which is a method for computing
the change in joint positions that yields the desired change in pose.
.. math::
\Delta \mathbf{q} = \mathbf{J}^{\dagger} \Delta \mathbf{x}
\mathbf{q}_{\text{desired}} = \mathbf{q}_{\text{current}} + \Delta \mathbf{q}
where :math:`\mathbf{J}^{\dagger}` is the pseudo-inverse of the Jacobian matrix :math:`\mathbf{J}`,
:math:`\Delta \mathbf{x}` is the desired change in pose, and :math:`\mathbf{q}_{\text{current}}`
is the current joint positions.
To deal with singularity in Jacobian, the following methods are supported for computing inverse of the Jacobian:
- "pinv": Moore-Penrose pseudo-inverse
- "svd": Adaptive singular-value decomposition (SVD)
- "trans": Transpose of matrix
- "dls": Damped version of Moore-Penrose pseudo-inverse (also called Levenberg-Marquardt)
.. caution::
The controller does not assume anything about the frames of the current and desired end-effector pose,
or the joint-space velocities. It is up to the user to ensure that these quantities are given
in the correct format.
Reference:
[1] https://ethz.ch/content/dam/ethz/special-interest/mavt/robotics-n-intelligent-systems/rsl-dam/documents/RobotDynamics2017/RD_HS2017script.pdf
[2] https://www.cs.cmu.edu/~15464-s13/lectures/lecture6/iksurvey.pdf
"""
def __init__(self, cfg: DifferentialIKControllerCfg, num_envs: int, device: str):
"""Initialize the controller.
Args:
cfg: The configuration for the controller.
num_envs: The number of environments.
device: The device to use for computations.
"""
# store inputs
self.cfg = cfg
self.num_envs = num_envs
self._device = device
# create buffers
self.ee_pos_des = torch.zeros(self.num_envs, 3, device=self._device)
self.ee_quat_des = torch.zeros(self.num_envs, 4, device=self._device)
# -- input command
self._command = torch.zeros(self.num_envs, self.action_dim, device=self._device)
"""
Properties.
"""
@property
def action_dim(self) -> int:
"""Dimension of the controller's input command."""
if self.cfg.command_type == "position":
return 3 # (x, y, z)
elif self.cfg.command_type == "pose" and self.cfg.use_relative_mode:
return 6 # (dx, dy, dz, droll, dpitch, dyaw)
else:
return 7 # (x, y, z, qw, qx, qy, qz)
"""
Operations.
"""
def reset(self, env_ids: torch.Tensor = None):
"""Reset the internals.
Args:
env_ids: The environment indices to reset. If None, then all environments are reset.
"""
pass
def set_command(
self, command: torch.Tensor, ee_pos: torch.Tensor | None = None, ee_quat: torch.Tensor | None = None
):
"""Set target end-effector pose command.
Based on the configured command type and relative mode, the method computes the desired end-effector pose.
It is up to the user to ensure that the command is given in the correct frame. The method only
applies the relative mode if the command type is ``position_rel`` or ``pose_rel``.
Args:
command: The input command in shape (N, 3) or (N, 6) or (N, 7).
ee_pos: The current end-effector position in shape (N, 3).
This is only needed if the command type is ``position_rel`` or ``pose_rel``.
ee_quat: The current end-effector orientation (w, x, y, z) in shape (N, 4).
This is only needed if the command type is ``position_*`` or ``pose_rel``.
Raises:
ValueError: If the command type is ``position_*`` and :attr:`ee_quat` is None.
ValueError: If the command type is ``position_rel`` and :attr:`ee_pos` is None.
ValueError: If the command type is ``pose_rel`` and either :attr:`ee_pos` or :attr:`ee_quat` is None.
"""
# store command
self._command[:] = command
# compute the desired end-effector pose
if self.cfg.command_type == "position":
# we need end-effector orientation even though we are in position mode
# this is only needed for display purposes
if ee_quat is None:
raise ValueError("End-effector orientation can not be None for `position_*` command type!")
# compute targets
if self.cfg.use_relative_mode:
if ee_pos is None:
raise ValueError("End-effector position can not be None for `position_rel` command type!")
self.ee_pos_des[:] = ee_pos + self._command
self.ee_quat_des[:] = ee_quat
else:
self.ee_pos_des[:] = self._command
self.ee_quat_des[:] = ee_quat
else:
# compute targets
if self.cfg.use_relative_mode:
if ee_pos is None or ee_quat is None:
raise ValueError(
"Neither end-effector position nor orientation can be None for `pose_rel` command type!"
)
self.ee_pos_des, self.ee_quat_des = apply_delta_pose(ee_pos, ee_quat, self._command)
else:
self.ee_pos_des = self._command[:, 0:3]
self.ee_quat_des = self._command[:, 3:7]
def compute(
self, ee_pos: torch.Tensor, ee_quat: torch.Tensor, jacobian: torch.Tensor, joint_pos: torch.Tensor
) -> torch.Tensor:
"""Computes the target joint positions that will yield the desired end effector pose.
Args:
ee_pos: The current end-effector position in shape (N, 3).
ee_quat: The current end-effector orientation in shape (N, 4).
jacobian: The geometric jacobian matrix in shape (N, 6, num_joints).
joint_pos: The current joint positions in shape (N, num_joints).
Returns:
The target joint positions commands in shape (N, num_joints).
"""
# compute the delta in joint-space
if "position" in self.cfg.command_type:
position_error = self.ee_pos_des - ee_pos
jacobian_pos = jacobian[:, 0:3]
delta_joint_pos = self._compute_delta_joint_pos(delta_pose=position_error, jacobian=jacobian_pos)
else:
position_error, axis_angle_error = compute_pose_error(
ee_pos, ee_quat, self.ee_pos_des, self.ee_quat_des, rot_error_type="axis_angle"
)
pose_error = torch.cat((position_error, axis_angle_error), dim=1)
delta_joint_pos = self._compute_delta_joint_pos(delta_pose=pose_error, jacobian=jacobian)
# return the desired joint positions
return joint_pos + delta_joint_pos
"""
Helper functions.
"""
def _compute_delta_joint_pos(self, delta_pose: torch.Tensor, jacobian: torch.Tensor) -> torch.Tensor:
"""Computes the change in joint position that yields the desired change in pose.
The method uses the Jacobian mapping from joint-space velocities to end-effector velocities
to compute the delta-change in the joint-space that moves the robot closer to a desired
end-effector position.
Args:
delta_pose: The desired delta pose in shape (N, 3) or (N, 6).
jacobian: The geometric jacobian matrix in shape (N, 3, num_joints) or (N, 6, num_joints).
Returns:
The desired delta in joint space. Shape is (N, num-jointsß).
"""
if self.cfg.ik_params is None:
raise RuntimeError(f"Inverse-kinematics parameters for method '{self.cfg.ik_method}' is not defined!")
# compute the delta in joint-space
if self.cfg.ik_method == "pinv": # Jacobian pseudo-inverse
# parameters
k_val = self.cfg.ik_params["k_val"]
# computation
jacobian_pinv = torch.linalg.pinv(jacobian)
delta_joint_pos = k_val * jacobian_pinv @ delta_pose.unsqueeze(-1)
delta_joint_pos = delta_joint_pos.squeeze(-1)
elif self.cfg.ik_method == "svd": # adaptive SVD
# parameters
k_val = self.cfg.ik_params["k_val"]
min_singular_value = self.cfg.ik_params["min_singular_value"]
# computation
# U: 6xd, S: dxd, V: d x num-joint
U, S, Vh = torch.linalg.svd(jacobian)
S_inv = 1.0 / S
S_inv = torch.where(S > min_singular_value, S_inv, torch.zeros_like(S_inv))
jacobian_pinv = (
torch.transpose(Vh, dim0=1, dim1=2)[:, :, :6]
@ torch.diag_embed(S_inv)
@ torch.transpose(U, dim0=1, dim1=2)
)
delta_joint_pos = k_val * jacobian_pinv @ delta_pose.unsqueeze(-1)
delta_joint_pos = delta_joint_pos.squeeze(-1)
elif self.cfg.ik_method == "trans": # Jacobian transpose
# parameters
k_val = self.cfg.ik_params["k_val"]
# computation
jacobian_T = torch.transpose(jacobian, dim0=1, dim1=2)
delta_joint_pos = k_val * jacobian_T @ delta_pose.unsqueeze(-1)
delta_joint_pos = delta_joint_pos.squeeze(-1)
elif self.cfg.ik_method == "dls": # damped least squares
# parameters
lambda_val = self.cfg.ik_params["lambda_val"]
# computation
jacobian_T = torch.transpose(jacobian, dim0=1, dim1=2)
lambda_matrix = (lambda_val**2) * torch.eye(n=jacobian.shape[1], device=self._device)
delta_joint_pos = (
jacobian_T @ torch.inverse(jacobian @ jacobian_T + lambda_matrix) @ delta_pose.unsqueeze(-1)
)
delta_joint_pos = delta_joint_pos.squeeze(-1)
else:
raise ValueError(f"Unsupported inverse-kinematics method: {self.cfg.ik_method}")
return delta_joint_pos
| 10,589 | Python | 44.06383 | 153 | 0.602134 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/controllers/differential_ik_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 Literal
from omni.isaac.orbit.utils import configclass
from .differential_ik import DifferentialIKController
@configclass
class DifferentialIKControllerCfg:
"""Configuration for differential inverse kinematics controller."""
class_type: type = DifferentialIKController
"""The associated controller class."""
command_type: Literal["position", "pose"] = MISSING
"""Type of task-space command to control the articulation's body.
If "position", then the controller only controls the position of the articulation's body.
Otherwise, the controller controls the pose of the articulation's body.
"""
use_relative_mode: bool = False
"""Whether to use relative mode for the controller. Defaults to False.
If True, then the controller treats the input command as a delta change in the position/pose.
Otherwise, the controller treats the input command as the absolute position/pose.
"""
ik_method: Literal["pinv", "svd", "trans", "dls"] = MISSING
"""Method for computing inverse of Jacobian."""
ik_params: dict[str, float] | None = None
"""Parameters for the inverse-kinematics method. Defaults to None, in which case the default
parameters for the method are used.
- Moore-Penrose pseudo-inverse ("pinv"):
- "k_val": Scaling of computed delta-joint positions (default: 1.0).
- Adaptive Singular Value Decomposition ("svd"):
- "k_val": Scaling of computed delta-joint positions (default: 1.0).
- "min_singular_value": Single values less than this are suppressed to zero (default: 1e-5).
- Jacobian transpose ("trans"):
- "k_val": Scaling of computed delta-joint positions (default: 1.0).
- Damped Moore-Penrose pseudo-inverse ("dls"):
- "lambda_val": Damping coefficient (default: 0.01).
"""
def __post_init__(self):
# check valid input
if self.command_type not in ["position", "pose"]:
raise ValueError(f"Unsupported inverse-kinematics command: {self.command_type}.")
if self.ik_method not in ["pinv", "svd", "trans", "dls"]:
raise ValueError(f"Unsupported inverse-kinematics method: {self.ik_method}.")
# default parameters for different inverse kinematics approaches.
default_ik_params = {
"pinv": {"k_val": 1.0},
"svd": {"k_val": 1.0, "min_singular_value": 1e-5},
"trans": {"k_val": 1.0},
"dls": {"lambda_val": 0.01},
}
# update parameters for IK-method if not provided
ik_params = default_ik_params[self.ik_method].copy()
if self.ik_params is not None:
ik_params.update(self.ik_params)
self.ik_params = ik_params
| 2,929 | Python | 39.136986 | 100 | 0.665073 |
NVIDIA-Omniverse/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
from __future__ import annotations
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,320 | Python | 39.176724 | 153 | 0.615558 |
NVIDIA-Omniverse/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
from __future__ import annotations
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,542 | Python | 39.605262 | 117 | 0.730869 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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
| 29,548 | Python | 39.983356 | 148 | 0.659266 |
NVIDIA-Omniverse/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 __future__ import annotations
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.
References:
* PhysX 5 documentation: https://nvidia-omniverse.github.io/PhysX/
"""
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,098 | Python | 40.389344 | 116 | 0.710537 |
NVIDIA-Omniverse/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
from __future__ import annotations
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, Usd
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 `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.
.. _omni.isaac.core.simulation_context.SimulationContext: https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.core/docs/index.html#module-omni.isaac.core.simulation_context
"""
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/offscreen_render/enabled"))
# 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 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 = self._physics_context._physics_scene # pyright: ignore [reportPrivateUsage]
physx_scene_api = self._physics_context._physx_scene_api # pyright: ignore [reportPrivateUsage]
# 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()
| 33,577 | Python | 47.106017 | 199 | 0.653751 |
NVIDIA-Omniverse/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 __future__ import annotations
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."""
@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 rad/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."""
| 7,830 | Python | 39.158974 | 157 | 0.698595 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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
from __future__ import annotations
import carb
import omni.isaac.core.utils.stage as stage_utils
from pxr import PhysxSchema, Usd, UsdPhysics
from ..utils import apply_nested, 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.
.. 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.
"""
# 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()
# 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)
# 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
| 23,529 | Python | 39.222222 | 157 | 0.69085 |
NVIDIA-Omniverse/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."""
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.
"""
| 3,807 | Python | 38.666666 | 148 | 0.720252 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 __future__ import annotations
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,559 | Python | 42.4375 | 211 | 0.706602 |
NVIDIA-Omniverse/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 __future__ import annotations
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,801 | Python | 35.767567 | 147 | 0.708278 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 __future__ import annotations
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,258 | Python | 25.072 | 80 | 0.668201 |
NVIDIA-Omniverse/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.GeometryCfg,
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,873 | Python | 41.629139 | 164 | 0.678552 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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.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
from omni.isaac.orbit.utils.assets import check_file_path
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.
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
if not check_file_path(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 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,293 | Python | 40.98513 | 115 | 0.679625 |
NVIDIA-Omniverse/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.ArticulationPropertiesCfg | 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."""
@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."""
| 3,786 | Python | 31.646551 | 107 | 0.710512 |
NVIDIA-Omniverse/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 __future__ import annotations
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,200 | Python | 36.176991 | 139 | 0.703571 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 __future__ import annotations
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,409 | Python | 37.314606 | 130 | 0.723379 |
NVIDIA-Omniverse/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
| 957 | Python | 35.846152 | 101 | 0.798328 |
NVIDIA-Omniverse/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 __future__ import annotations
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,756 | Python | 32.788461 | 105 | 0.694761 |
NVIDIA-Omniverse/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
from __future__ import annotations
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,541 | Python | 36.899497 | 121 | 0.626044 |
NVIDIA-Omniverse/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 __future__ import annotations
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,408 | Python | 28.978723 | 90 | 0.71946 |
NVIDIA-Omniverse/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
from __future__ import annotations
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,085 | Python | 43.929368 | 164 | 0.647 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 __future__ import annotations
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,235 | Python | 34.492063 | 117 | 0.699329 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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.
"""
from __future__ import annotations
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/offscreen_render/enabled", self._offscreen_render)
# 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,560 | Python | 50.909539 | 121 | 0.639449 |
NVIDIA-Omniverse/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."""
from __future__ import annotations
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)
| 573 | Python | 25.090908 | 79 | 0.692845 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 __future__ import annotations
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,456 | Python | 27.208861 | 85 | 0.688959 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 __future__ import annotations
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,447 | Python | 36.890109 | 115 | 0.64839 |
NVIDIA-Omniverse/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
from __future__ import annotations
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 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
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,551 | Python | 40.69437 | 158 | 0.626262 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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
from __future__ import annotations
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,781 | Python | 47.709876 | 118 | 0.644509 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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
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,367 | Python | 44.138686 | 118 | 0.663297 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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
from __future__ import annotations
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,614 | Python | 37.654822 | 115 | 0.609535 |
NVIDIA-Omniverse/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 __future__ import annotations
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,969 | Python | 35.654412 | 107 | 0.695857 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 |
NVIDIA-Omniverse/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 __future__ import annotations
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,104 | Python | 34.911765 | 104 | 0.706913 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.