file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
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 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/terrains/config/rough.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for custom terrains."""
from __future__ import annotations
import omni.isaac.orbit.terrains as terrain_gen
from ..terrain_generator_cfg import TerrainGeneratorCfg
ROUGH_TERRAINS_CFG = TerrainGeneratorCfg(
size=(8.0, 8.0),
border_width=20.0,
num_rows=10,
num_cols=20,
horizontal_scale=0.1,
vertical_scale=0.005,
slope_threshold=0.75,
use_cache=False,
sub_terrains={
"pyramid_stairs": terrain_gen.MeshPyramidStairsTerrainCfg(
proportion=0.2,
step_height_range=(0.05, 0.23),
step_width=0.3,
platform_width=3.0,
border_width=1.0,
holes=False,
),
"pyramid_stairs_inv": terrain_gen.MeshInvertedPyramidStairsTerrainCfg(
proportion=0.2,
step_height_range=(0.05, 0.23),
step_width=0.3,
platform_width=3.0,
border_width=1.0,
holes=False,
),
"boxes": terrain_gen.MeshRandomGridTerrainCfg(
proportion=0.2, grid_width=0.45, grid_height_range=(0.05, 0.2), platform_width=2.0
),
"random_rough": terrain_gen.HfRandomUniformTerrainCfg(
proportion=0.2, noise_range=(0.02, 0.10), noise_step=0.02, border_width=0.25
),
"hf_pyramid_slope": terrain_gen.HfPyramidSlopedTerrainCfg(
proportion=0.1, slope_range=(0.0, 0.4), platform_width=2.0, border_width=0.25
),
"hf_pyramid_slope_inv": terrain_gen.HfInvertedPyramidSlopedTerrainCfg(
proportion=0.1, slope_range=(0.0, 0.4), platform_width=2.0, border_width=0.25
),
},
)
"""Rough terrains configuration."""
| 1,804 | Python | 31.818181 | 94 | 0.611973 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/timer.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for a timer class that can be used for performance measurements."""
from __future__ import annotations
import time
from contextlib import ContextDecorator
from typing import Any
class TimerError(Exception):
"""A custom exception used to report errors in use of :class:`Timer` class."""
pass
class Timer(ContextDecorator):
"""A timer for performance measurements.
A class to keep track of time for performance measurement.
It allows timing via context managers and decorators as well.
It uses the `time.perf_counter` function to measure time. This function
returns the number of seconds since the epoch as a float. It has the
highest resolution available on the system.
As a regular object:
.. code-block:: python
import time
from omni.isaac.orbit.utils.timer import Timer
timer = Timer()
timer.start()
time.sleep(1)
print(1 <= timer.time_elapsed <= 2) # Output: True
time.sleep(1)
timer.stop()
print(2 <= stopwatch.total_run_time) # Output: True
As a context manager:
.. code-block:: python
import time
from omni.isaac.orbit.utils.timer import Timer
with Timer() as timer:
time.sleep(1)
print(1 <= timer.time_elapsed <= 2) # Output: True
Reference: https://gist.github.com/sumeet/1123871
"""
def __init__(self, msg: str | None = None):
"""Initializes the timer.
Args:
msg: The message to display when using the timer
class in a context manager. Defaults to None.
"""
self._msg = msg
self._start_time = None
self._stop_time = None
self._elapsed_time = None
def __str__(self) -> str:
"""A string representation of the class object.
Returns:
A string containing the elapsed time.
"""
return f"{self.time_elapsed:0.6f} seconds"
"""
Properties
"""
@property
def time_elapsed(self) -> float:
"""The number of seconds that have elapsed since this timer started timing.
Note:
This is used for checking how much time has elapsed while the timer is still running.
"""
return time.perf_counter() - self._start_time
@property
def total_run_time(self) -> float:
"""The number of seconds that elapsed from when the timer started to when it ended."""
return self._elapsed_time
"""
Operations
"""
def start(self):
"""Start timing."""
if self._start_time is not None:
raise TimerError("Timer is running. Use .stop() to stop it")
self._start_time = time.perf_counter()
def stop(self):
"""Stop timing."""
if self._start_time is None:
raise TimerError("Timer is not running. Use .start() to start it")
self._stop_time = time.perf_counter()
self._elapsed_time = self._stop_time - self._start_time
self._start_time = None
"""
Context managers
"""
def __enter__(self) -> Timer:
"""Start timing and return this `Timer` instance."""
self.start()
return self
def __exit__(self, *exc_info: Any):
"""Stop timing."""
self.stop()
# print message
if self._msg is not None:
print(self._msg, f": {self._elapsed_time:0.6f} seconds")
| 3,572 | Python | 25.272059 | 97 | 0.599944 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/string.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing utilities for transforming strings and regular expressions."""
from __future__ import annotations
import ast
import importlib
import inspect
import re
from collections.abc import Callable, Sequence
from typing import Any
"""
String formatting.
"""
def to_camel_case(snake_str: str, to: str = "cC") -> str:
"""Converts a string from snake case to camel case.
Args:
snake_str: A string in snake case (i.e. with '_')
to: Convention to convert string to. Defaults to "cC".
Raises:
ValueError: Invalid input argument `to`, i.e. not "cC" or "CC".
Returns:
A string in camel-case format.
"""
# check input is correct
if to not in ["cC", "CC"]:
msg = "to_camel_case(): Choose a valid `to` argument (CC or cC)"
raise ValueError(msg)
# convert string to lower case and split
components = snake_str.lower().split("_")
if to == "cC":
# We capitalize the first letter of each component except the first one
# with the 'title' method and join them together.
return components[0] + "".join(x.title() for x in components[1:])
else:
# Capitalize first letter in all the components
return "".join(x.title() for x in components)
def to_snake_case(camel_str: str) -> str:
"""Converts a string from camel case to snake case.
Args:
camel_str: A string in camel case.
Returns:
A string in snake case (i.e. with '_')
"""
camel_str = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_str)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", camel_str).lower()
"""
String <-> Callable operations.
"""
def is_lambda_expression(name: str) -> bool:
"""Checks if the input string is a lambda expression.
Args:
name: The input string.
Returns:
Whether the input string is a lambda expression.
"""
try:
ast.parse(name)
return isinstance(ast.parse(name).body[0], ast.Expr) and isinstance(ast.parse(name).body[0].value, ast.Lambda)
except SyntaxError:
return False
def callable_to_string(value: Callable) -> str:
"""Converts a callable object to a string.
Args:
value: A callable object.
Raises:
ValueError: When the input argument is not a callable object.
Returns:
A string representation of the callable object.
"""
# check if callable
if not callable(value):
raise ValueError(f"The input argument is not callable: {value}.")
# check if lambda function
if value.__name__ == "<lambda>":
return f"lambda {inspect.getsourcelines(value)[0][0].strip().split('lambda')[1].strip().split(',')[0]}"
else:
# get the module and function name
module_name = value.__module__
function_name = value.__name__
# return the string
return f"{module_name}:{function_name}"
def string_to_callable(name: str) -> Callable:
"""Resolves the module and function names to return the function.
Args:
name: The function name. The format should be 'module:attribute_name' or a
lambda expression of format: 'lambda x: x'.
Raises:
ValueError: When the resolved attribute is not a function.
ValueError: When the module cannot be found.
Returns:
Callable: The function loaded from the module.
"""
try:
if is_lambda_expression(name):
callable_object = eval(name)
else:
mod_name, attr_name = name.split(":")
mod = importlib.import_module(mod_name)
callable_object = getattr(mod, attr_name)
# check if attribute is callable
if callable(callable_object):
return callable_object
else:
raise AttributeError(f"The imported object is not callable: '{name}'")
except (ValueError, ModuleNotFoundError) as e:
msg = (
f"Could not resolve the input string '{name}' into callable object."
" The format of input should be 'module:attribute_name'.\n"
f"Received the error:\n {e}."
)
raise ValueError(msg)
"""
Regex operations.
"""
def resolve_matching_names(
keys: str | Sequence[str], list_of_strings: Sequence[str], preserve_order: bool = False
) -> tuple[list[int], list[str]]:
"""Match a list of query regular expressions against a list of strings and return the matched indices and names.
When a list of query regular expressions is provided, the function checks each target string against each
query regular expression and returns the indices of the matched strings and the matched strings.
If the :attr:`preserve_order` is True, the ordering of the matched indices and names is the same as the order
of the provided list of strings. This means that the ordering is dictated by the order of the target strings
and not the order of the query regular expressions.
If the :attr:`preserve_order` is False, the ordering of the matched indices and names is the same as the order
of the provided list of query regular expressions.
For example, consider the list of strings is ['a', 'b', 'c', 'd', 'e'] and the regular expressions are ['a|c', 'b'].
If :attr:`preserve_order` is False, then the function will return the indices of the matched strings and the
strings as: ([0, 1, 2], ['a', 'b', 'c']). When :attr:`preserve_order` is True, it will return them as:
([0, 2, 1], ['a', 'c', 'b']).
Note:
The function does not sort the indices. It returns the indices in the order they are found.
Args:
keys: A regular expression or a list of regular expressions to match the strings in the list.
list_of_strings: A list of strings to match.
preserve_order: Whether to preserve the order of the query keys in the returned values. Defaults to False.
Returns:
A tuple of lists containing the matched indices and names.
Raises:
ValueError: When multiple matches are found for a string in the list.
ValueError: When not all regular expressions are matched.
"""
# resolve name keys
if isinstance(keys, str):
keys = [keys]
# find matching patterns
index_list = []
names_list = []
key_idx_list = []
# book-keeping to check that we always have a one-to-one mapping
# i.e. each target string should match only one regular expression
target_strings_match_found = [None for _ in range(len(list_of_strings))]
keys_match_found = [[] for _ in range(len(keys))]
# loop over all target strings
for target_index, potential_match_string in enumerate(list_of_strings):
for key_index, re_key in enumerate(keys):
if re.fullmatch(re_key, potential_match_string):
# check if match already found
if target_strings_match_found[target_index]:
raise ValueError(
f"Multiple matches for '{potential_match_string}':"
f" '{target_strings_match_found[target_index]}' and '{re_key}'!"
)
# add to list
target_strings_match_found[target_index] = re_key
index_list.append(target_index)
names_list.append(potential_match_string)
key_idx_list.append(key_index)
# add for regex key
keys_match_found[key_index].append(potential_match_string)
# reorder keys if they should be returned in order of the query keys
if preserve_order:
reordered_index_list = [None] * len(index_list)
global_index = 0
for key_index in range(len(keys)):
for key_idx_position, key_idx_entry in enumerate(key_idx_list):
if key_idx_entry == key_index:
reordered_index_list[key_idx_position] = global_index
global_index += 1
# reorder index and names list
index_list_reorder = [None] * len(index_list)
names_list_reorder = [None] * len(index_list)
for idx, reorder_idx in enumerate(reordered_index_list):
index_list_reorder[reorder_idx] = index_list[idx]
names_list_reorder[reorder_idx] = names_list[idx]
# update
index_list = index_list_reorder
names_list = names_list_reorder
# check that all regular expressions are matched
if not all(keys_match_found):
# make this print nicely aligned for debugging
msg = "\n"
for key, value in zip(keys, keys_match_found):
msg += f"\t{key}: {value}\n"
msg += f"Available strings: {list_of_strings}\n"
# raise error
raise ValueError(
f"Not all regular expressions are matched! Please check that the regular expressions are correct: {msg}"
)
# return
return index_list, names_list
def resolve_matching_names_values(
data: dict[str, Any], list_of_strings: Sequence[str], preserve_order: bool = False
) -> tuple[list[int], list[str], list[Any]]:
"""Match a list of regular expressions in a dictionary against a list of strings and return
the matched indices, names, and values.
If the :attr:`preserve_order` is True, the ordering of the matched indices and names is the same as the order
of the provided list of strings. This means that the ordering is dictated by the order of the target strings
and not the order of the query regular expressions.
If the :attr:`preserve_order` is False, the ordering of the matched indices and names is the same as the order
of the provided list of query regular expressions.
For example, consider the dictionary is {"a|d|e": 1, "b|c": 2}, the list of strings is ['a', 'b', 'c', 'd', 'e'].
If :attr:`preserve_order` is False, then the function will return the indices of the matched strings, the
matched strings, and the values as: ([0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e'], [1, 2, 2, 1, 1]). When
:attr:`preserve_order` is True, it will return them as: ([0, 3, 4, 1, 2], ['a', 'd', 'e', 'b', 'c'], [1, 1, 1, 2, 2]).
Args:
data: A dictionary of regular expressions and values to match the strings in the list.
list_of_strings: A list of strings to match.
preserve_order: Whether to preserve the order of the query keys in the returned values. Defaults to False.
Returns:
A tuple of lists containing the matched indices, names, and values.
Raises:
TypeError: When the input argument :attr:`data` is not a dictionary.
ValueError: When multiple matches are found for a string in the dictionary.
ValueError: When not all regular expressions in the data keys are matched.
"""
# check valid input
if not isinstance(data, dict):
raise TypeError(f"Input argument `data` should be a dictionary. Received: {data}")
# find matching patterns
index_list = []
names_list = []
values_list = []
key_idx_list = []
# book-keeping to check that we always have a one-to-one mapping
# i.e. each target string should match only one regular expression
target_strings_match_found = [None for _ in range(len(list_of_strings))]
keys_match_found = [[] for _ in range(len(data))]
# loop over all target strings
for target_index, potential_match_string in enumerate(list_of_strings):
for key_index, (re_key, value) in enumerate(data.items()):
if re.fullmatch(re_key, potential_match_string):
# check if match already found
if target_strings_match_found[target_index]:
raise ValueError(
f"Multiple matches for '{potential_match_string}':"
f" '{target_strings_match_found[target_index]}' and '{re_key}'!"
)
# add to list
target_strings_match_found[target_index] = re_key
index_list.append(target_index)
names_list.append(potential_match_string)
values_list.append(value)
key_idx_list.append(key_index)
# add for regex key
keys_match_found[key_index].append(potential_match_string)
# reorder keys if they should be returned in order of the query keys
if preserve_order:
reordered_index_list = [None] * len(index_list)
global_index = 0
for key_index in range(len(data)):
for key_idx_position, key_idx_entry in enumerate(key_idx_list):
if key_idx_entry == key_index:
reordered_index_list[key_idx_position] = global_index
global_index += 1
# reorder index and names list
index_list_reorder = [None] * len(index_list)
names_list_reorder = [None] * len(index_list)
values_list_reorder = [None] * len(index_list)
for idx, reorder_idx in enumerate(reordered_index_list):
index_list_reorder[reorder_idx] = index_list[idx]
names_list_reorder[reorder_idx] = names_list[idx]
values_list_reorder[reorder_idx] = values_list[idx]
# update
index_list = index_list_reorder
names_list = names_list_reorder
values_list = values_list_reorder
# check that all regular expressions are matched
if not all(keys_match_found):
# make this print nicely aligned for debugging
msg = "\n"
for key, value in zip(data.keys(), keys_match_found):
msg += f"\t{key}: {value}\n"
msg += f"Available strings: {list_of_strings}\n"
# raise error
raise ValueError(
f"Not all regular expressions are matched! Please check that the regular expressions are correct: {msg}"
)
# return
return index_list, names_list, values_list
| 14,010 | Python | 40.087976 | 122 | 0.626053 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package containing utilities for common operations and helper functions."""
from .array import *
from .configclass import configclass
from .dict import *
from .string import *
from .timer import Timer
| 332 | Python | 24.615383 | 82 | 0.76506 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/array.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing utilities for working with different array backends."""
from __future__ import annotations
import numpy as np
import torch
from typing import Union
import warp as wp
TensorData = Union[np.ndarray, torch.Tensor, wp.array]
"""Type definition for a tensor data.
Union of numpy, torch, and warp arrays.
"""
TENSOR_TYPES = {
"numpy": np.ndarray,
"torch": torch.Tensor,
"warp": wp.array,
}
"""A dictionary containing the types for each backend.
The keys are the name of the backend ("numpy", "torch", "warp") and the values are the corresponding type
(``np.ndarray``, ``torch.Tensor``, ``wp.array``).
"""
TENSOR_TYPE_CONVERSIONS = {
"numpy": {wp.array: lambda x: x.numpy(), torch.Tensor: lambda x: x.detach().cpu().numpy()},
"torch": {wp.array: lambda x: wp.torch.to_torch(x), np.ndarray: lambda x: torch.from_numpy(x)},
"warp": {np.array: lambda x: wp.array(x), torch.Tensor: lambda x: wp.torch.from_torch(x)},
}
"""A nested dictionary containing the conversion functions for each backend.
The keys of the outer dictionary are the name of target backend ("numpy", "torch", "warp"). The keys of the
inner dictionary are the source backend (``np.ndarray``, ``torch.Tensor``, ``wp.array``).
"""
def convert_to_torch(
array: TensorData,
dtype: torch.dtype = None,
device: torch.device | str | None = None,
) -> torch.Tensor:
"""Converts a given array into a torch tensor.
The function tries to convert the array to a torch tensor. If the array is a numpy/warp arrays, or python
list/tuples, it is converted to a torch tensor. If the array is already a torch tensor, it is returned
directly.
If ``device`` is None, then the function deduces the current device of the data. For numpy arrays,
this defaults to "cpu", for torch tensors it is "cpu" or "cuda", and for warp arrays it is "cuda".
Note:
Since PyTorch does not support unsigned integer types, unsigned integer arrays are converted to
signed integer arrays. This is done by casting the array to the corresponding signed integer type.
Args:
array: The input array. It can be a numpy array, warp array, python list/tuple, or torch tensor.
dtype: Target data-type for the tensor.
device: The target device for the tensor. Defaults to None.
Returns:
The converted array as torch tensor.
"""
# Convert array to tensor
# if the datatype is not currently supported by torch we need to improvise
# supported types are: https://pytorch.org/docs/stable/tensors.html
if isinstance(array, torch.Tensor):
tensor = array
elif isinstance(array, np.ndarray):
if array.dtype == np.uint32:
array = array.astype(np.int64)
# need to deal with object arrays (np.void) separately
tensor = torch.from_numpy(array)
elif isinstance(array, wp.array):
if array.dtype == wp.uint32:
array = array.view(wp.int32)
tensor = wp.to_torch(array)
else:
tensor = torch.Tensor(array)
# Convert tensor to the right device
if device is not None and str(tensor.device) != str(device):
tensor = tensor.to(device)
# Convert dtype of tensor if requested
if dtype is not None and tensor.dtype != dtype:
tensor = tensor.type(dtype)
return tensor
| 3,480 | Python | 35.642105 | 109 | 0.679023 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/math.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing utilities for various math operations."""
from __future__ import annotations
import numpy as np
import torch
import torch.nn.functional
from typing import Literal
"""
General
"""
@torch.jit.script
def scale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor:
"""Normalizes a given input tensor to a range of [-1, 1].
.. note::
It uses pytorch broadcasting functionality to deal with batched input.
Args:
x: Input tensor of shape (N, dims).
lower: The minimum value of the tensor. Shape is (N, dims) or (dims,).
upper: The maximum value of the tensor. Shape is (N, dims) or (dims,).
Returns:
Normalized transform of the tensor. Shape is (N, dims).
"""
# default value of center
offset = (lower + upper) * 0.5
# return normalized tensor
return 2 * (x - offset) / (upper - lower)
@torch.jit.script
def unscale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor:
"""De-normalizes a given input tensor from range of [-1, 1] to (lower, upper).
.. note::
It uses pytorch broadcasting functionality to deal with batched input.
Args:
x: Input tensor of shape (N, dims).
lower: The minimum value of the tensor. Shape is (N, dims) or (dims,).
upper: The maximum value of the tensor. Shape is (N, dims) or (dims,).
Returns:
De-normalized transform of the tensor. Shape is (N, dims).
"""
# default value of center
offset = (lower + upper) * 0.5
# return normalized tensor
return x * (upper - lower) * 0.5 + offset
@torch.jit.script
def saturate(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor:
"""Clamps a given input tensor to (lower, upper).
It uses pytorch broadcasting functionality to deal with batched input.
Args:
x: Input tensor of shape (N, dims).
lower: The minimum value of the tensor. Shape is (N, dims) or (dims,).
upper: The maximum value of the tensor. Shape is (N, dims) or (dims,).
Returns:
Clamped transform of the tensor. Shape is (N, dims).
"""
return torch.max(torch.min(x, upper), lower)
@torch.jit.script
def normalize(x: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
"""Normalizes a given input tensor to unit length.
Args:
x: Input tensor of shape (N, dims).
eps: A small value to avoid division by zero. Defaults to 1e-9.
Returns:
Normalized tensor of shape (N, dims).
"""
return x / x.norm(p=2, dim=-1).clamp(min=eps, max=None).unsqueeze(-1)
@torch.jit.script
def wrap_to_pi(angles: torch.Tensor) -> torch.Tensor:
"""Wraps input angles (in radians) to the range [-pi, pi].
Args:
angles: Input angles of any shape.
Returns:
Angles in the range [-pi, pi].
"""
angles = angles.clone()
angles %= 2 * torch.pi
angles -= 2 * torch.pi * (angles > torch.pi)
return angles
@torch.jit.script
def copysign(mag: float, other: torch.Tensor) -> torch.Tensor:
"""Create a new floating-point tensor with the magnitude of input and the sign of other, element-wise.
Note:
The implementation follows from `torch.copysign`. The function allows a scalar magnitude.
Args:
mag: The magnitude scalar.
other: The tensor containing values whose signbits are applied to magnitude.
Returns:
The output tensor.
"""
mag = torch.tensor(mag, device=other.device, dtype=torch.float).repeat(other.shape[0])
return torch.abs(mag) * torch.sign(other)
"""
Rotation
"""
@torch.jit.script
def matrix_from_quat(quaternions: torch.Tensor) -> torch.Tensor:
"""Convert rotations given as quaternions to rotation matrices.
Args:
quaternions: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
Returns:
Rotation matrices. The shape is (..., 3, 3).
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L41-L70
"""
r, i, j, k = torch.unbind(quaternions, -1)
# pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
two_s = 2.0 / (quaternions * quaternions).sum(-1)
o = torch.stack(
(
1 - two_s * (j * j + k * k),
two_s * (i * j - k * r),
two_s * (i * k + j * r),
two_s * (i * j + k * r),
1 - two_s * (i * i + k * k),
two_s * (j * k - i * r),
two_s * (i * k - j * r),
two_s * (j * k + i * r),
1 - two_s * (i * i + j * j),
),
-1,
)
return o.reshape(quaternions.shape[:-1] + (3, 3))
def convert_quat(quat: torch.Tensor | np.ndarray, to: Literal["xyzw", "wxyz"] = "xyzw") -> torch.Tensor | np.ndarray:
"""Converts quaternion from one convention to another.
The convention to convert TO is specified as an optional argument. If to == 'xyzw',
then the input is in 'wxyz' format, and vice-versa.
Args:
quat: The quaternion of shape (..., 4).
to: Convention to convert quaternion to.. Defaults to "xyzw".
Returns:
The converted quaternion in specified convention.
Raises:
ValueError: Invalid input argument `to`, i.e. not "xyzw" or "wxyz".
ValueError: Invalid shape of input `quat`, i.e. not (..., 4,).
"""
# check input is correct
if quat.shape[-1] != 4:
msg = f"Expected input quaternion shape mismatch: {quat.shape} != (..., 4)."
raise ValueError(msg)
if to not in ["xyzw", "wxyz"]:
msg = f"Expected input argument `to` to be 'xyzw' or 'wxyz'. Received: {to}."
raise ValueError(msg)
# check if input is numpy array (we support this backend since some classes use numpy)
if isinstance(quat, np.ndarray):
# use numpy functions
if to == "xyzw":
# wxyz -> xyzw
return np.roll(quat, -1, axis=-1)
else:
# xyzw -> wxyz
return np.roll(quat, 1, axis=-1)
else:
# convert to torch (sanity check)
if not isinstance(quat, torch.Tensor):
quat = torch.tensor(quat, dtype=float)
# convert to specified quaternion type
if to == "xyzw":
# wxyz -> xyzw
return quat.roll(-1, dims=-1)
else:
# xyzw -> wxyz
return quat.roll(1, dims=-1)
@torch.jit.script
def quat_conjugate(q: torch.Tensor) -> torch.Tensor:
"""Computes the conjugate of a quaternion.
Args:
q: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
Returns:
The conjugate quaternion in (w, x, y, z). Shape is (..., 4).
"""
shape = q.shape
q = q.reshape(-1, 4)
return torch.cat((q[:, 0:1], -q[:, 1:]), dim=-1).view(shape)
@torch.jit.script
def quat_inv(q: torch.Tensor) -> torch.Tensor:
"""Compute the inverse of a quaternion.
Args:
q: The quaternion orientation in (w, x, y, z). Shape is (N, 4).
Returns:
The inverse quaternion in (w, x, y, z). Shape is (N, 4).
"""
return normalize(quat_conjugate(q))
@torch.jit.script
def quat_from_euler_xyz(roll: torch.Tensor, pitch: torch.Tensor, yaw: torch.Tensor) -> torch.Tensor:
"""Convert rotations given as Euler angles in radians to Quaternions.
Note:
The euler angles are assumed in XYZ convention.
Args:
roll: Rotation around x-axis (in radians). Shape is (N,).
pitch: Rotation around y-axis (in radians). Shape is (N,).
yaw: Rotation around z-axis (in radians). Shape is (N,).
Returns:
The quaternion in (w, x, y, z). Shape is (N, 4).
"""
cy = torch.cos(yaw * 0.5)
sy = torch.sin(yaw * 0.5)
cr = torch.cos(roll * 0.5)
sr = torch.sin(roll * 0.5)
cp = torch.cos(pitch * 0.5)
sp = torch.sin(pitch * 0.5)
# compute quaternion
qw = cy * cr * cp + sy * sr * sp
qx = cy * sr * cp - sy * cr * sp
qy = cy * cr * sp + sy * sr * cp
qz = sy * cr * cp - cy * sr * sp
return torch.stack([qw, qx, qy, qz], dim=-1)
@torch.jit.script
def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor:
"""Returns torch.sqrt(torch.max(0, x)) but with a zero sub-gradient where x is 0.
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L91-L99
"""
ret = torch.zeros_like(x)
positive_mask = x > 0
ret[positive_mask] = torch.sqrt(x[positive_mask])
return ret
@torch.jit.script
def quat_from_matrix(matrix: torch.Tensor) -> torch.Tensor:
"""Convert rotations given as rotation matrices to quaternions.
Args:
matrix: The rotation matrices. Shape is (..., 3, 3).
Returns:
The quaternion in (w, x, y, z). Shape is (..., 4).
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L102-L161
"""
if matrix.size(-1) != 3 or matrix.size(-2) != 3:
raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.")
batch_dim = matrix.shape[:-2]
m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(matrix.reshape(batch_dim + (9,)), dim=-1)
q_abs = _sqrt_positive_part(
torch.stack(
[
1.0 + m00 + m11 + m22,
1.0 + m00 - m11 - m22,
1.0 - m00 + m11 - m22,
1.0 - m00 - m11 + m22,
],
dim=-1,
)
)
# we produce the desired quaternion multiplied by each of r, i, j, k
quat_by_rijk = torch.stack(
[
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1),
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1),
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1),
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and `int`.
torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1),
],
dim=-2,
)
# We floor here at 0.1 but the exact level is not important; if q_abs is small,
# the candidate won't be picked.
flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device)
quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr))
# if not for numerical problems, quat_candidates[i] should be same (up to a sign),
# forall i; we pick the best-conditioned one (with the largest denominator)
return quat_candidates[torch.nn.functional.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :].reshape(
batch_dim + (4,)
)
def _axis_angle_rotation(axis: Literal["X", "Y", "Z"], angle: torch.Tensor) -> torch.Tensor:
"""Return the rotation matrices for one of the rotations about an axis of which Euler angles describe,
for each value of the angle given.
Args:
axis: Axis label "X" or "Y or "Z".
angle: Euler angles in radians of any shape.
Returns:
Rotation matrices. Shape is (..., 3, 3).
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L164-L191
"""
cos = torch.cos(angle)
sin = torch.sin(angle)
one = torch.ones_like(angle)
zero = torch.zeros_like(angle)
if axis == "X":
R_flat = (one, zero, zero, zero, cos, -sin, zero, sin, cos)
elif axis == "Y":
R_flat = (cos, zero, sin, zero, one, zero, -sin, zero, cos)
elif axis == "Z":
R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one)
else:
raise ValueError("letter must be either X, Y or Z.")
return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3))
def matrix_from_euler(euler_angles: torch.Tensor, convention: str) -> torch.Tensor:
"""
Convert rotations given as Euler angles in radians to rotation matrices.
Args:
euler_angles: Euler angles in radians. Shape is (..., 3).
convention: Convention string of three uppercase letters from {"X", "Y", and "Z"}.
For example, "XYZ" means that the rotations should be applied first about x,
then y, then z.
Returns:
Rotation matrices. Shape is (..., 3, 3).
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L194-L220
"""
if euler_angles.dim() == 0 or euler_angles.shape[-1] != 3:
raise ValueError("Invalid input euler angles.")
if len(convention) != 3:
raise ValueError("Convention must have 3 letters.")
if convention[1] in (convention[0], convention[2]):
raise ValueError(f"Invalid convention {convention}.")
for letter in convention:
if letter not in ("X", "Y", "Z"):
raise ValueError(f"Invalid letter {letter} in convention string.")
matrices = [_axis_angle_rotation(c, e) for c, e in zip(convention, torch.unbind(euler_angles, -1))]
# return functools.reduce(torch.matmul, matrices)
return torch.matmul(torch.matmul(matrices[0], matrices[1]), matrices[2])
@torch.jit.script
def euler_xyz_from_quat(quat: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert rotations given as quaternions to Euler angles in radians.
Note:
The euler angles are assumed in XYZ convention.
Args:
quat: The quaternion orientation in (w, x, y, z). Shape is (N, 4).
Returns:
A tuple containing roll-pitch-yaw. Each element is a tensor of shape (N,).
Reference:
https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
"""
q_w, q_x, q_y, q_z = quat[:, 0], quat[:, 1], quat[:, 2], quat[:, 3]
# roll (x-axis rotation)
sin_roll = 2.0 * (q_w * q_x + q_y * q_z)
cos_roll = 1 - 2 * (q_x * q_x + q_y * q_y)
roll = torch.atan2(sin_roll, cos_roll)
# pitch (y-axis rotation)
sin_pitch = 2.0 * (q_w * q_y - q_z * q_x)
pitch = torch.where(torch.abs(sin_pitch) >= 1, copysign(torch.pi / 2.0, sin_pitch), torch.asin(sin_pitch))
# yaw (z-axis rotation)
sin_yaw = 2.0 * (q_w * q_z + q_x * q_y)
cos_yaw = 1 - 2 * (q_y * q_y + q_z * q_z)
yaw = torch.atan2(sin_yaw, cos_yaw)
return roll % (2 * torch.pi), pitch % (2 * torch.pi), yaw % (2 * torch.pi) # TODO: why not wrap_to_pi here ?
@torch.jit.script
def quat_mul(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
"""Multiply two quaternions together.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (..., 4).
q2: The second quaternion in (w, x, y, z). Shape is (..., 4).
Returns:
The product of the two quaternions in (w, x, y, z). Shape is (..., 4).
Raises:
ValueError: Input shapes of ``q1`` and ``q2`` are not matching.
"""
# check input is correct
if q1.shape != q2.shape:
msg = f"Expected input quaternion shape mismatch: {q1.shape} != {q2.shape}."
raise ValueError(msg)
# reshape to (N, 4) for multiplication
shape = q1.shape
q1 = q1.reshape(-1, 4)
q2 = q2.reshape(-1, 4)
# extract components from quaternions
w1, x1, y1, z1 = q1[:, 0], q1[:, 1], q1[:, 2], q1[:, 3]
w2, x2, y2, z2 = q2[:, 0], q2[:, 1], q2[:, 2], q2[:, 3]
# perform multiplication
ww = (z1 + x1) * (x2 + y2)
yy = (w1 - y1) * (w2 + z2)
zz = (w1 + y1) * (w2 - z2)
xx = ww + yy + zz
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
w = qq - ww + (z1 - y1) * (y2 - z2)
x = qq - xx + (x1 + w1) * (x2 + w2)
y = qq - yy + (w1 - x1) * (y2 + z2)
z = qq - zz + (z1 + y1) * (w2 - x2)
return torch.stack([w, x, y, z], dim=-1).view(shape)
@torch.jit.script
def quat_box_minus(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
"""The box-minus operator (quaternion difference) between two quaternions.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (N, 4).
q2: The second quaternion in (w, x, y, z). Shape is (N, 4).
Returns:
The difference between the two quaternions. Shape is (N, 3).
Reference:
https://docs.leggedrobotics.com/kindr/cheatsheet_latest.pdf
"""
quat_diff = quat_mul(q1, quat_conjugate(q2)) # q1 * q2^-1
re = quat_diff[:, 0] # real part, q = [w, x, y, z] = [re, im]
im = quat_diff[:, 1:] # imaginary part
norm_im = torch.norm(im, dim=1)
scale = 2.0 * torch.where(norm_im > 1.0e-7, torch.atan(norm_im / re) / norm_im, torch.sign(re))
return scale.unsqueeze(-1) * im
@torch.jit.script
def yaw_quat(quat: torch.Tensor) -> torch.Tensor:
"""Extract the yaw component of a quaternion.
Args:
quat: The orientation in (w, x, y, z). Shape is (..., 4)
Returns:
A quaternion with only yaw component.
"""
shape = quat.shape
quat_yaw = quat.clone().view(-1, 4)
qw = quat_yaw[:, 0]
qx = quat_yaw[:, 1]
qy = quat_yaw[:, 2]
qz = quat_yaw[:, 3]
yaw = torch.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
quat_yaw[:] = 0.0
quat_yaw[:, 3] = torch.sin(yaw / 2)
quat_yaw[:, 0] = torch.cos(yaw / 2)
quat_yaw = normalize(quat_yaw)
return quat_yaw.view(shape)
@torch.jit.script
def quat_apply(quat: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:
"""Apply a quaternion rotation to a vector.
Args:
quat: The quaternion in (w, x, y, z). Shape is (..., 4).
vec: The vector in (x, y, z). Shape is (..., 3).
Returns:
The rotated vector in (x, y, z). Shape is (..., 3).
"""
# store shape
shape = vec.shape
# reshape to (N, 3) for multiplication
quat = quat.reshape(-1, 4)
vec = vec.reshape(-1, 3)
# extract components from quaternions
xyz = quat[:, 1:]
t = xyz.cross(vec, dim=-1) * 2
return (vec + quat[:, 0:1] * t + xyz.cross(t, dim=-1)).view(shape)
@torch.jit.script
def quat_apply_yaw(quat: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:
"""Rotate a vector only around the yaw-direction.
Args:
quat: The orientation in (w, x, y, z). Shape is (N, 4).
vec: The vector in (x, y, z). Shape is (N, 3).
Returns:
The rotated vector in (x, y, z). Shape is (N, 3).
"""
quat_yaw = yaw_quat(quat)
return quat_apply(quat_yaw, vec)
@torch.jit.script
def quat_rotate(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
"""Rotate a vector by a quaternion.
Args:
q: The quaternion in (w, x, y, z). Shape is (N, 4).
v: The vector in (x, y, z). Shape is (N, 3).
Returns:
The rotated vector in (x, y, z). Shape is (N, 3).
"""
shape = q.shape
q_w = q[:, 0]
q_vec = q[:, 1:]
a = v * (2.0 * q_w**2 - 1.0).unsqueeze(-1)
b = torch.cross(q_vec, v, dim=-1) * q_w.unsqueeze(-1) * 2.0
c = q_vec * torch.bmm(q_vec.view(shape[0], 1, 3), v.view(shape[0], 3, 1)).squeeze(-1) * 2.0
return a + b + c
@torch.jit.script
def quat_rotate_inverse(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
"""Rotate a vector by the inverse of a quaternion.
Args:
q: The quaternion in (w, x, y, z). Shape is (N, 4).
v: The vector in (x, y, z). Shape is (N, 3).
Returns:
The rotated vector in (x, y, z). Shape is (N, 3).
"""
shape = q.shape
q_w = q[:, 0]
q_vec = q[:, 1:]
a = v * (2.0 * q_w**2 - 1.0).unsqueeze(-1)
b = torch.cross(q_vec, v, dim=-1) * q_w.unsqueeze(-1) * 2.0
c = q_vec * torch.bmm(q_vec.view(shape[0], 1, 3), v.view(shape[0], 3, 1)).squeeze(-1) * 2.0
return a - b + c
@torch.jit.script
def quat_from_angle_axis(angle: torch.Tensor, axis: torch.Tensor) -> torch.Tensor:
"""Convert rotations given as angle-axis to quaternions.
Args:
angle: The angle turned anti-clockwise in radians around the vector's direction. Shape is (N,).
axis: The axis of rotation. Shape is (N, 3).
Returns:
The quaternion in (w, x, y, z). Shape is (N, 4).
"""
theta = (angle / 2).unsqueeze(-1)
xyz = normalize(axis) * theta.sin()
w = theta.cos()
return normalize(torch.cat([w, xyz], dim=-1))
@torch.jit.script
def axis_angle_from_quat(quat: torch.Tensor, eps: float = 1.0e-6) -> torch.Tensor:
"""Convert rotations given as quaternions to axis/angle.
Args:
quat: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
eps: The tolerance for Taylor approximation. Defaults to 1.0e-6.
Returns:
Rotations given as a vector in axis angle form. Shape is (..., 3).
The vector's magnitude is the angle turned anti-clockwise in radians around the vector's direction.
Reference:
https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py#L526-L554
"""
# Modified to take in quat as [q_w, q_x, q_y, q_z]
# Quaternion is [q_w, q_x, q_y, q_z] = [cos(theta/2), n_x * sin(theta/2), n_y * sin(theta/2), n_z * sin(theta/2)]
# Axis-angle is [a_x, a_y, a_z] = [theta * n_x, theta * n_y, theta * n_z]
# Thus, axis-angle is [q_x, q_y, q_z] / (sin(theta/2) / theta)
# When theta = 0, (sin(theta/2) / theta) is undefined
# However, as theta --> 0, we can use the Taylor approximation 1/2 - theta^2 / 48
quat = quat * (1.0 - 2.0 * (quat[..., 0:1] < 0.0))
mag = torch.linalg.norm(quat[..., 1:], dim=-1)
half_angle = torch.atan2(mag, quat[..., 0])
angle = 2.0 * half_angle
# check whether to apply Taylor approximation
sin_half_angles_over_angles = torch.where(
torch.abs(angle.abs()) > eps, torch.sin(half_angle) / angle, 0.5 - angle * angle / 48
)
return quat[..., 1:4] / sin_half_angles_over_angles.unsqueeze(-1)
@torch.jit.script
def quat_error_magnitude(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor:
"""Computes the rotation difference between two quaternions.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (..., 4).
q2: The second quaternion in (w, x, y, z). Shape is (..., 4).
Returns:
Angular error between input quaternions in radians.
"""
quat_diff = quat_mul(q1, quat_conjugate(q2))
return torch.norm(axis_angle_from_quat(quat_diff), dim=-1)
@torch.jit.script
def skew_symmetric_matrix(vec: torch.Tensor) -> torch.Tensor:
"""Computes the skew-symmetric matrix of a vector.
Args:
vec: The input vector. Shape is (3,) or (N, 3).
Returns:
The skew-symmetric matrix. Shape is (1, 3, 3) or (N, 3, 3).
Raises:
ValueError: If input tensor is not of shape (..., 3).
"""
# check input is correct
if vec.shape[-1] != 3:
raise ValueError(f"Expected input vector shape mismatch: {vec.shape} != (..., 3).")
# unsqueeze the last dimension
if vec.ndim == 1:
vec = vec.unsqueeze(0)
# create a skew-symmetric matrix
skew_sym_mat = torch.zeros(vec.shape[0], 3, 3, device=vec.device, dtype=vec.dtype)
skew_sym_mat[:, 0, 1] = -vec[:, 2]
skew_sym_mat[:, 0, 2] = vec[:, 1]
skew_sym_mat[:, 1, 2] = -vec[:, 0]
skew_sym_mat[:, 1, 0] = vec[:, 2]
skew_sym_mat[:, 2, 0] = -vec[:, 1]
skew_sym_mat[:, 2, 1] = vec[:, 0]
return skew_sym_mat
"""
Transformations
"""
def is_identity_pose(pos: torch.tensor, rot: torch.tensor) -> bool:
"""Checks if input poses are identity transforms.
The function checks if the input position and orientation are close to zero and
identity respectively using L2-norm. It does NOT check the error in the orientation.
Args:
pos: The cartesian position. Shape is (N, 3).
rot: The quaternion in (w, x, y, z). Shape is (N, 4).
Returns:
True if all the input poses result in identity transform. Otherwise, False.
"""
# create identity transformations
pos_identity = torch.zeros_like(pos)
rot_identity = torch.zeros_like(rot)
rot_identity[..., 0] = 1
# compare input to identity
return torch.allclose(pos, pos_identity) and torch.allclose(rot, rot_identity)
# @torch.jit.script
def combine_frame_transforms(
t01: torch.Tensor, q01: torch.Tensor, t12: torch.Tensor | None = None, q12: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor]:
r"""Combine transformations between two reference frames into a stationary frame.
It performs the following transformation operation: :math:`T_{02} = T_{01} \times T_{12}`,
where :math:`T_{AB}` is the homogeneous transformation matrix from frame A to B.
Args:
t01: Position of frame 1 w.r.t. frame 0. Shape is (N, 3).
q01: Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
t12: Position of frame 2 w.r.t. frame 1. Shape is (N, 3).
Defaults to None, in which case the position is assumed to be zero.
q12: Quaternion orientation of frame 2 w.r.t. frame 1 in (w, x, y, z). Shape is (N, 4).
Defaults to None, in which case the orientation is assumed to be identity.
Returns:
A tuple containing the position and orientation of frame 2 w.r.t. frame 0.
Shape of the tensors are (N, 3) and (N, 4) respectively.
"""
# compute orientation
if q12 is not None:
q02 = quat_mul(q01, q12)
else:
q02 = q01
# compute translation
if t12 is not None:
t02 = t01 + quat_apply(q01, t12)
else:
t02 = t01
return t02, q02
# @torch.jit.script
def subtract_frame_transforms(
t01: torch.Tensor, q01: torch.Tensor, t02: torch.Tensor | None = None, q02: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor]:
r"""Subtract transformations between two reference frames into a stationary frame.
It performs the following transformation operation: :math:`T_{12} = T_{01}^{-1} \times T_{02}`,
where :math:`T_{AB}` is the homogeneous transformation matrix from frame A to B.
Args:
t01: Position of frame 1 w.r.t. frame 0. Shape is (N, 3).
q01: Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
t02: Position of frame 2 w.r.t. frame 0. Shape is (N, 3).
Defaults to None, in which case the position is assumed to be zero.
q02: Quaternion orientation of frame 2 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
Defaults to None, in which case the orientation is assumed to be identity.
Returns:
A tuple containing the position and orientation of frame 2 w.r.t. frame 1.
Shape of the tensors are (N, 3) and (N, 4) respectively.
"""
# compute orientation
q10 = quat_inv(q01)
if q02 is not None:
q12 = quat_mul(q10, q02)
else:
q12 = q10
# compute translation
if t02 is not None:
t12 = quat_apply(q10, t02 - t01)
else:
t12 = quat_apply(q10, -t01)
return t12, q12
# @torch.jit.script
def compute_pose_error(
t01: torch.Tensor,
q01: torch.Tensor,
t02: torch.Tensor,
q02: torch.Tensor,
rot_error_type: Literal["quat", "axis_angle"] = "axis_angle",
) -> tuple[torch.Tensor, torch.Tensor]:
"""Compute the position and orientation error between source and target frames.
Args:
t01: Position of source frame. Shape is (N, 3).
q01: Quaternion orientation of source frame in (w, x, y, z). Shape is (N, 4).
t02: Position of target frame. Shape is (N, 3).
q02: Quaternion orientation of target frame in (w, x, y, z). Shape is (N, 4).
rot_error_type: The rotation error type to return: "quat", "axis_angle".
Defaults to "axis_angle".
Returns:
A tuple containing position and orientation error. Shape of position error is (N, 3).
Shape of orientation error depends on the value of :attr:`rot_error_type`:
- If :attr:`rot_error_type` is "quat", the orientation error is returned
as a quaternion. Shape is (N, 4).
- If :attr:`rot_error_type` is "axis_angle", the orientation error is
returned as an axis-angle vector. Shape is (N, 3).
Raises:
ValueError: Invalid rotation error type.
"""
# Compute quaternion error (i.e., difference quaternion)
# Reference: https://personal.utdallas.edu/~sxb027100/dock/quaternion.html
# q_current_norm = q_current * q_current_conj
source_quat_norm = quat_mul(q01, quat_conjugate(q01))[:, 0]
# q_current_inv = q_current_conj / q_current_norm
source_quat_inv = quat_conjugate(q01) / source_quat_norm.unsqueeze(-1)
# q_error = q_target * q_current_inv
quat_error = quat_mul(q02, source_quat_inv)
# Compute position error
pos_error = t02 - t01
# return error based on specified type
if rot_error_type == "quat":
return pos_error, quat_error
elif rot_error_type == "axis_angle":
# Convert to axis-angle error
axis_angle_error = axis_angle_from_quat(quat_error)
return pos_error, axis_angle_error
else:
raise ValueError(f"Unsupported orientation error type: {rot_error_type}. Valid: 'quat', 'axis_angle'.")
@torch.jit.script
def apply_delta_pose(
source_pos: torch.Tensor, source_rot: torch.Tensor, delta_pose: torch.Tensor, eps: float = 1.0e-6
) -> tuple[torch.Tensor, torch.Tensor]:
"""Applies delta pose transformation on source pose.
The first three elements of `delta_pose` are interpreted as cartesian position displacement.
The remaining three elements of `delta_pose` are interpreted as orientation displacement
in the angle-axis format.
Args:
source_pos: Position of source frame. Shape is (N, 3).
source_rot: Quaternion orientation of source frame in (w, x, y, z). Shape is (N, 4)..
delta_pose: Position and orientation displacements. Shape is (N, 6).
eps: The tolerance to consider orientation displacement as zero. Defaults to 1.0e-6.
Returns:
A tuple containing the displaced position and orientation frames.
Shape of the tensors are (N, 3) and (N, 4) respectively.
"""
# number of poses given
num_poses = source_pos.shape[0]
device = source_pos.device
# interpret delta_pose[:, 0:3] as target position displacements
target_pos = source_pos + delta_pose[:, 0:3]
# interpret delta_pose[:, 3:6] as target rotation displacements
rot_actions = delta_pose[:, 3:6]
angle = torch.linalg.vector_norm(rot_actions, dim=1)
axis = rot_actions / angle.unsqueeze(-1)
# change from axis-angle to quat convention
identity_quat = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat(num_poses, 1)
rot_delta_quat = torch.where(
angle.unsqueeze(-1).repeat(1, 4) > eps, quat_from_angle_axis(angle, axis), identity_quat
)
# TODO: Check if this is the correct order for this multiplication.
target_rot = quat_mul(rot_delta_quat, source_rot)
return target_pos, target_rot
# @torch.jit.script
def transform_points(
points: torch.Tensor, pos: torch.Tensor | None = None, quat: torch.Tensor | None = None
) -> torch.Tensor:
r"""Transform input points in a given frame to a target frame.
This function transform points from a source frame to a target frame. The transformation is defined by the
position :math:`t` and orientation :math:`R` of the target frame in the source frame.
.. math::
p_{target} = R_{target} \times p_{source} + t_{target}
If the input `points` is a batch of points, the inputs `pos` and `quat` must be either a batch of
positions and quaternions or a single position and quaternion. If the inputs `pos` and `quat` are
a single position and quaternion, the same transformation is applied to all points in the batch.
If either the inputs :attr:`pos` and :attr:`quat` are None, the corresponding transformation is not applied.
Args:
points: Points to transform. Shape is (N, P, 3) or (P, 3).
pos: Position of the target frame. Shape is (N, 3) or (3,).
Defaults to None, in which case the position is assumed to be zero.
quat: Quaternion orientation of the target frame in (w, x, y, z). Shape is (N, 4) or (4,).
Defaults to None, in which case the orientation is assumed to be identity.
Returns:
Transformed points in the target frame. Shape is (N, P, 3) or (P, 3).
Raises:
ValueError: If the inputs `points` is not of shape (N, P, 3) or (P, 3).
ValueError: If the inputs `pos` is not of shape (N, 3) or (3,).
ValueError: If the inputs `quat` is not of shape (N, 4) or (4,).
"""
points_batch = points.clone()
# check if inputs are batched
is_batched = points_batch.dim() == 3
# -- check inputs
if points_batch.dim() == 2:
points_batch = points_batch[None] # (P, 3) -> (1, P, 3)
if points_batch.dim() != 3:
raise ValueError(f"Expected points to have dim = 2 or dim = 3: got shape {points.shape}")
if not (pos is None or pos.dim() == 1 or pos.dim() == 2):
raise ValueError(f"Expected pos to have dim = 1 or dim = 2: got shape {pos.shape}")
if not (quat is None or quat.dim() == 1 or quat.dim() == 2):
raise ValueError(f"Expected quat to have dim = 1 or dim = 2: got shape {quat.shape}")
# -- rotation
if quat is not None:
# convert to batched rotation matrix
rot_mat = matrix_from_quat(quat)
if rot_mat.dim() == 2:
rot_mat = rot_mat[None] # (3, 3) -> (1, 3, 3)
# convert points to matching batch size (N, P, 3) -> (N, 3, P)
# and apply rotation
points_batch = torch.matmul(rot_mat, points_batch.transpose_(1, 2))
# (N, 3, P) -> (N, P, 3)
points_batch = points_batch.transpose_(1, 2)
# -- translation
if pos is not None:
# convert to batched translation vector
if pos.dim() == 1:
pos = pos[None, None, :] # (3,) -> (1, 1, 3)
else:
pos = pos[:, None, :] # (N, 3) -> (N, 1, 3)
# apply translation
points_batch += pos
# -- return points in same shape as input
if not is_batched:
points_batch = points_batch.squeeze(0) # (1, P, 3) -> (P, 3)
return points_batch
"""
Projection operations.
"""
@torch.jit.script
def unproject_depth(depth: torch.Tensor, intrinsics: torch.Tensor) -> torch.Tensor:
r"""Unproject depth image into a pointcloud.
This function converts depth images into points given the calibration matrix of the camera.
.. math::
p_{3D} = K^{-1} \times [u, v, 1]^T \times d
where :math:`p_{3D}` is the 3D point, :math:`d` is the depth value, :math:`u` and :math:`v` are
the pixel coordinates and :math:`K` is the intrinsic matrix.
If `depth` is a batch of depth images and `intrinsics` is a single intrinsic matrix, the same
calibration matrix is applied to all depth images in the batch.
The function assumes that the width and height are both greater than 1. This makes the function
deal with many possible shapes of depth images and intrinsics matrices.
Args:
depth: The depth measurement. Shape is (H, W) or or (H, W, 1) or (N, H, W) or (N, H, W, 1).
intrinsics: A tensor providing camera's calibration matrix. Shape is (3, 3) or (N, 3, 3).
Returns:
The 3D coordinates of points. Shape is (P, 3) or (N, P, 3).
Raises:
ValueError: When depth is not of shape (H, W) or (H, W, 1) or (N, H, W) or (N, H, W, 1).
ValueError: When intrinsics is not of shape (3, 3) or (N, 3, 3).
"""
depth_batch = depth.clone()
intrinsics_batch = intrinsics.clone()
# check if inputs are batched
is_batched = depth_batch.dim() == 4 or (depth_batch.dim() == 3 and depth_batch.shape[-1] != 1)
# make sure inputs are batched
if depth_batch.dim() == 3 and depth_batch.shape[-1] == 1:
depth_batch = depth_batch.squeeze(dim=2) # (H, W, 1) -> (H, W)
if depth_batch.dim() == 2:
depth_batch = depth_batch[None] # (H, W) -> (1, H, W)
if depth_batch.dim() == 4 and depth_batch.shape[-1] == 1:
depth_batch = depth_batch.squeeze(dim=3) # (N, H, W, 1) -> (N, H, W)
if intrinsics_batch.dim() == 2:
intrinsics_batch = intrinsics_batch[None] # (3, 3) -> (1, 3, 3)
# check shape of inputs
if depth_batch.dim() != 3:
raise ValueError(f"Expected depth images to have dim = 2 or 3 or 4: got shape {depth.shape}")
if intrinsics_batch.dim() != 3:
raise ValueError(f"Expected intrinsics to have shape (3, 3) or (N, 3, 3): got shape {intrinsics.shape}")
# get image height and width
im_height, im_width = depth_batch.shape[1:]
# create image points in homogeneous coordinates (3, H x W)
indices_u = torch.arange(im_width, device=depth.device, dtype=depth.dtype)
indices_v = torch.arange(im_height, device=depth.device, dtype=depth.dtype)
img_indices = torch.stack(torch.meshgrid([indices_u, indices_v], indexing="ij"), dim=0).reshape(2, -1)
pixels = torch.nn.functional.pad(img_indices, (0, 0, 0, 1), mode="constant", value=1.0)
pixels = pixels.unsqueeze(0) # (3, H x W) -> (1, 3, H x W)
# unproject points into 3D space
points = torch.matmul(torch.inverse(intrinsics_batch), pixels) # (N, 3, H x W)
points = points / points[:, -1, :].unsqueeze(1) # normalize by last coordinate
# flatten depth image (N, H, W) -> (N, H x W)
depth_batch = depth_batch.transpose_(1, 2).reshape(depth_batch.shape[0], -1).unsqueeze(2)
depth_batch = depth_batch.expand(-1, -1, 3)
# scale points by depth
points_xyz = points.transpose_(1, 2) * depth_batch # (N, H x W, 3)
# return points in same shape as input
if not is_batched:
points_xyz = points_xyz.squeeze(0)
return points_xyz
@torch.jit.script
def project_points(points: torch.Tensor, intrinsics: torch.Tensor) -> torch.Tensor:
r"""Projects 3D points into 2D image plane.
This project 3D points into a 2D image plane. The transformation is defined by the intrinsic
matrix of the camera.
.. math::
\begin{align}
p &= K \times p_{3D} = \\
p_{2D} &= \begin{pmatrix} u \\ v \\ d \end{pmatrix}
= \begin{pmatrix} p[0] / p[2] \\ p[1] / p[2] \\ Z \end{pmatrix}
\end{align}
where :math:`p_{2D} = (u, v, d)` is the projected 3D point, :math:`p_{3D} = (X, Y, Z)` is the
3D point and :math:`K \in \mathbb{R}^{3 \times 3}` is the intrinsic matrix.
If `points` is a batch of 3D points and `intrinsics` is a single intrinsic matrix, the same
calibration matrix is applied to all points in the batch.
Args:
points: The 3D coordinates of points. Shape is (P, 3) or (N, P, 3).
intrinsics: Camera's calibration matrix. Shape is (3, 3) or (N, 3, 3).
Returns:
Projected 3D coordinates of points. Shape is (P, 3) or (N, P, 3).
"""
points_batch = points.clone()
intrinsics_batch = intrinsics.clone()
# check if inputs are batched
is_batched = points_batch.dim() == 2
# make sure inputs are batched
if points_batch.dim() == 2:
points_batch = points_batch[None] # (P, 3) -> (1, P, 3)
if intrinsics_batch.dim() == 2:
intrinsics_batch = intrinsics_batch[None] # (3, 3) -> (1, 3, 3)
# check shape of inputs
if points_batch.dim() != 3:
raise ValueError(f"Expected points to have dim = 3: got shape {points.shape}.")
if intrinsics_batch.dim() != 3:
raise ValueError(f"Expected intrinsics to have shape (3, 3) or (N, 3, 3): got shape {intrinsics.shape}.")
# project points into 2D image plane
points_2d = torch.matmul(intrinsics_batch, points_batch.transpose(1, 2))
points_2d = points_2d / points_2d[:, -1, :].unsqueeze(1) # normalize by last coordinate
points_2d = points_2d.transpose_(1, 2) # (N, 3, P) -> (N, P, 3)
# replace last coordinate with depth
points_2d[:, :, -1] = points_batch[:, :, -1]
# return points in same shape as input
if not is_batched:
points_2d = points_2d.squeeze(0) # (1, 3, P) -> (3, P)
return points_2d
"""
Sampling
"""
@torch.jit.script
def default_orientation(num: int, device: str) -> torch.Tensor:
"""Returns identity rotation transform.
Args:
num: The number of rotations to sample.
device: Device to create tensor on.
Returns:
Identity quaternion in (w, x, y, z). Shape is (num, 4).
"""
quat = torch.zeros((num, 4), dtype=torch.float, device=device)
quat[..., 0] = 1.0
return quat
@torch.jit.script
def random_orientation(num: int, device: str) -> torch.Tensor:
"""Returns sampled rotation in 3D as quaternion.
Args:
num: The number of rotations to sample.
device: Device to create tensor on.
Returns:
Sampled quaternion in (w, x, y, z). Shape is (num, 4).
Reference:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.random.html
"""
# sample random orientation from normal distribution
quat = torch.randn((num, 4), dtype=torch.float, device=device)
# normalize the quaternion
return torch.nn.functional.normalize(quat, p=2.0, dim=-1, eps=1e-12)
@torch.jit.script
def random_yaw_orientation(num: int, device: str) -> torch.Tensor:
"""Returns sampled rotation around z-axis.
Args:
num: The number of rotations to sample.
device: Device to create tensor on.
Returns:
Sampled quaternion in (w, x, y, z). Shape is (num, 4).
"""
roll = torch.zeros(num, dtype=torch.float, device=device)
pitch = torch.zeros(num, dtype=torch.float, device=device)
yaw = 2 * torch.pi * torch.rand(num, dtype=torch.float, device=device)
return quat_from_euler_xyz(roll, pitch, yaw)
def sample_triangle(lower: float, upper: float, size: int | tuple[int, ...], device: str) -> torch.Tensor:
"""Randomly samples tensor from a triangular distribution.
Args:
lower: The lower range of the sampled tensor.
upper: The upper range of the sampled tensor.
size: The shape of the tensor.
device: Device to create tensor on.
Returns:
Sampled tensor. Shape is based on :attr:`size`.
"""
# convert to tuple
if isinstance(size, int):
size = (size,)
# create random tensor in the range [-1, 1]
r = 2 * torch.rand(*size, device=device) - 1
# convert to triangular distribution
r = torch.where(r < 0.0, -torch.sqrt(-r), torch.sqrt(r))
# rescale back to [0, 1]
r = (r + 1.0) / 2.0
# rescale to range [lower, upper]
return (upper - lower) * r + lower
def sample_uniform(
lower: torch.Tensor | float, upper: torch.Tensor | float, size: int | tuple[int, ...], device: str
) -> torch.Tensor:
"""Sample uniformly within a range.
Args:
lower: Lower bound of uniform range.
upper: Upper bound of uniform range.
size: The shape of the tensor.
device: Device to create tensor on.
Returns:
Sampled tensor. Shape is based on :attr:`size`.
"""
# convert to tuple
if isinstance(size, int):
size = (size,)
# return tensor
return torch.rand(*size, device=device) * (upper - lower) + lower
def sample_cylinder(
radius: float, h_range: tuple[float, float], size: int | tuple[int, ...], device: str
) -> torch.Tensor:
"""Sample 3D points uniformly on a cylinder's surface.
The cylinder is centered at the origin and aligned with the z-axis. The height of the cylinder is
sampled uniformly from the range :obj:`h_range`, while the radius is fixed to :obj:`radius`.
The sampled points are returned as a tensor of shape :obj:`(*size, 3)`, i.e. the last dimension
contains the x, y, and z coordinates of the sampled points.
Args:
radius: The radius of the cylinder.
h_range: The minimum and maximum height of the cylinder.
size: The shape of the tensor.
device: Device to create tensor on.
Returns:
Sampled tensor. Shape is :obj:`(*size, 3)`.
"""
# sample angles
angles = (torch.rand(size, device=device) * 2 - 1) * torch.pi
h_min, h_max = h_range
# add shape
if isinstance(size, int):
size = (size, 3)
else:
size += (3,)
# allocate a tensor
xyz = torch.zeros(size, device=device)
xyz[..., 0] = radius * torch.cos(angles)
xyz[..., 1] = radius * torch.sin(angles)
xyz[..., 2].uniform_(h_min, h_max)
# return positions
return xyz
| 44,978 | Python | 35.598047 | 118 | 0.606296 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/dict.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for utilities for working with dictionaries."""
from __future__ import annotations
import collections.abc
import hashlib
import json
from collections.abc import Iterable, Mapping
from typing import Any
from .array import TENSOR_TYPE_CONVERSIONS, TENSOR_TYPES
from .string import callable_to_string, string_to_callable
"""
Dictionary <-> Class operations.
"""
def class_to_dict(obj: object) -> dict[str, Any]:
"""Convert an object into dictionary recursively.
Note:
Ignores all names starting with "__" (i.e. built-in methods).
Args:
obj: An instance of a class to convert.
Raises:
ValueError: When input argument is not an object.
Returns:
Converted dictionary mapping.
"""
# check that input data is class instance
if not hasattr(obj, "__class__"):
raise ValueError(f"Expected a class instance. Received: {type(obj)}.")
# convert object to dictionary
if isinstance(obj, dict):
obj_dict = obj
else:
obj_dict = obj.__dict__
# convert to dictionary
data = dict()
for key, value in obj_dict.items():
# disregard builtin attributes
if key.startswith("__"):
continue
# check if attribute is callable -- function
if callable(value):
data[key] = callable_to_string(value)
# check if attribute is a dictionary
elif hasattr(value, "__dict__") or isinstance(value, dict):
data[key] = class_to_dict(value)
else:
data[key] = value
return data
def update_class_from_dict(obj, data: dict[str, Any], _ns: str = "") -> None:
"""Reads a dictionary and sets object variables recursively.
This function performs in-place update of the class member attributes.
Args:
obj: An instance of a class to update.
data: Input dictionary to update from.
_ns: Namespace of the current object. This is useful for nested configuration
classes or dictionaries. Defaults to "".
Raises:
TypeError: When input is not a dictionary.
ValueError: When dictionary has a value that does not match default config type.
KeyError: When dictionary has a key that does not exist in the default config type.
"""
for key, value in data.items():
# key_ns is the full namespace of the key
key_ns = _ns + "/" + key
# check if key is present in the object
if hasattr(obj, key):
obj_mem = getattr(obj, key)
if isinstance(obj_mem, Mapping):
# Note: We don't handle two-level nested dictionaries. Just use configclass if this is needed.
# iterate over the dictionary to look for callable values
for k, v in obj_mem.items():
if callable(v):
value[k] = string_to_callable(value[k])
setattr(obj, key, value)
elif isinstance(value, Mapping):
# recursively call if it is a dictionary
update_class_from_dict(obj_mem, value, _ns=key_ns)
elif isinstance(value, Iterable) and not isinstance(value, str):
# check length of value to be safe
if len(obj_mem) != len(value) and obj_mem is not None:
raise ValueError(
f"[Config]: Incorrect length under namespace: {key_ns}."
f" Expected: {len(obj_mem)}, Received: {len(value)}."
)
# set value
setattr(obj, key, value)
elif callable(obj_mem):
# update function name
value = string_to_callable(value)
setattr(obj, key, value)
elif isinstance(value, type(obj_mem)):
# check that they are type-safe
setattr(obj, key, value)
else:
raise ValueError(
f"[Config]: Incorrect type under namespace: {key_ns}."
f" Expected: {type(obj_mem)}, Received: {type(value)}."
)
else:
raise KeyError(f"[Config]: Key not found under namespace: {key_ns}.")
"""
Dictionary <-> Hashable operations.
"""
def dict_to_md5_hash(data: object) -> str:
"""Convert a dictionary into a hashable key using MD5 hash.
Args:
data: Input dictionary or configuration object to convert.
Returns:
A string object of double length containing only hexadecimal digits.
"""
# convert to dictionary
if isinstance(data, dict):
encoded_buffer = json.dumps(data, sort_keys=True).encode()
else:
encoded_buffer = json.dumps(class_to_dict(data), sort_keys=True).encode()
# compute hash using MD5
data_hash = hashlib.md5()
data_hash.update(encoded_buffer)
# return the hash key
return data_hash.hexdigest()
"""
Dictionary operations.
"""
def convert_dict_to_backend(
data: dict, backend: str = "numpy", array_types: Iterable[str] = ("numpy", "torch", "warp")
) -> dict:
"""Convert all arrays or tensors in a dictionary to a given backend.
This function iterates over the dictionary, converts all arrays or tensors with the given types to
the desired backend, and stores them in a new dictionary. It also works with nested dictionaries.
Currently supported backends are "numpy", "torch", and "warp".
Note:
This function only converts arrays or tensors. Other types of data are left unchanged. Mutable types
(e.g. lists) are referenced by the new dictionary, so they are not copied.
Args:
data: An input dict containing array or tensor data as values.
backend: The backend ("numpy", "torch", "warp") to which arrays in this dict should be converted.
Defaults to "numpy".
array_types: A list containing the types of arrays that should be converted to
the desired backend. Defaults to ("numpy", "torch", "warp").
Raises:
ValueError: If the specified ``backend`` or ``array_types`` are unknown, i.e. not in the list of supported
backends ("numpy", "torch", "warp").
Returns:
The updated dict with the data converted to the desired backend.
"""
# THINK: Should we also support converting to a specific device, e.g. "cuda:0"?
# Check the backend is valid.
if backend not in TENSOR_TYPE_CONVERSIONS:
raise ValueError(f"Unknown backend '{backend}'. Supported backends are 'numpy', 'torch', and 'warp'.")
# Define the conversion functions for each backend.
tensor_type_conversions = TENSOR_TYPE_CONVERSIONS[backend]
# Parse the array types and convert them to the corresponding types: "numpy" -> np.ndarray, etc.
parsed_types = list()
for t in array_types:
# Check type is valid.
if t not in TENSOR_TYPES:
raise ValueError(f"Unknown array type: '{t}'. Supported array types are 'numpy', 'torch', and 'warp'.")
# Exclude types that match the backend, since we do not need to convert these.
if t == backend:
continue
# Convert the string types to the corresponding types.
parsed_types.append(TENSOR_TYPES[t])
# Convert the data to the desired backend.
output_dict = dict()
for key, value in data.items():
# Obtain the data type of the current value.
data_type = type(value)
# -- arrays
if data_type in parsed_types:
# check if we have a known conversion.
if data_type not in tensor_type_conversions:
raise ValueError(f"No registered conversion for data type: {data_type} to {backend}!")
# convert the data to the desired backend.
output_dict[key] = tensor_type_conversions[data_type](value)
# -- nested dictionaries
elif isinstance(data[key], dict):
output_dict[key] = convert_dict_to_backend(value)
# -- everything else
else:
output_dict[key] = value
return output_dict
def update_dict(orig_dict: dict, new_dict: collections.abc.Mapping) -> dict:
"""Updates existing dictionary with values from a new dictionary.
This function mimics the dict.update() function. However, it works for
nested dictionaries as well.
Reference:
https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
Args:
orig_dict: The original dictionary to insert items to.
new_dict: The new dictionary to insert items from.
Returns:
The updated dictionary.
"""
for keyname, value in new_dict.items():
if isinstance(value, collections.abc.Mapping):
orig_dict[keyname] = update_dict(orig_dict.get(keyname, {}), value)
else:
orig_dict[keyname] = value
return orig_dict
def print_dict(val, nesting: int = -4, start: bool = True):
"""Outputs a nested dictionary."""
if isinstance(val, dict):
if not start:
print("")
nesting += 4
for k in val:
print(nesting * " ", end="")
print(k, end=": ")
print_dict(val[k], nesting, start=False)
else:
# deal with functions in print statements
if callable(val):
print(callable_to_string(val))
else:
print(val)
| 9,558 | Python | 35.624521 | 115 | 0.614773 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/configclass.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Sub-module that provides a wrapper around the Python 3.7 onwards ``dataclasses`` module."""
import inspect
from collections.abc import Callable
from copy import deepcopy
from dataclasses import MISSING, Field, dataclass, field, replace
from typing import Any, ClassVar
from .dict import class_to_dict, update_class_from_dict
_CONFIGCLASS_METHODS = ["to_dict", "from_dict", "replace", "copy"]
"""List of class methods added at runtime to dataclass."""
"""
Wrapper around dataclass.
"""
def __dataclass_transform__():
"""Add annotations decorator for PyLance."""
return lambda a: a
@__dataclass_transform__()
def configclass(cls, **kwargs):
"""Wrapper around `dataclass` functionality to add extra checks and utilities.
As of Python 3.7, the standard dataclasses have two main issues which makes them non-generic for
configuration use-cases. These include:
1. Requiring a type annotation for all its members.
2. Requiring explicit usage of :meth:`field(default_factory=...)` to reinitialize mutable variables.
This function provides a decorator that wraps around Python's `dataclass`_ utility to deal with
the above two issues. It also provides additional helper functions for dictionary <-> class
conversion and easily copying class instances.
Usage:
.. code-block:: python
from dataclasses import MISSING
from omni.isaac.orbit.utils.configclass import configclass
@configclass
class ViewerCfg:
eye: list = [7.5, 7.5, 7.5] # field missing on purpose
lookat: list = field(default_factory=[0.0, 0.0, 0.0])
@configclass
class EnvCfg:
num_envs: int = MISSING
episode_length: int = 2000
viewer: ViewerCfg = ViewerCfg()
# create configuration instance
env_cfg = EnvCfg(num_envs=24)
# print information as a dictionary
print(env_cfg.to_dict())
# create a copy of the configuration
env_cfg_copy = env_cfg.copy()
# replace arbitrary fields using keyword arguments
env_cfg_copy = env_cfg_copy.replace(num_envs=32)
Args:
cls: The class to wrap around.
**kwargs: Additional arguments to pass to :func:`dataclass`.
Returns:
The wrapped class.
.. _dataclass: https://docs.python.org/3/library/dataclasses.html
"""
# add type annotations
_add_annotation_types(cls)
# add field factory
_process_mutable_types(cls)
# copy mutable members
# note: we check if user defined __post_init__ function exists and augment it with our own
if hasattr(cls, "__post_init__"):
setattr(cls, "__post_init__", _combined_function(cls.__post_init__, _custom_post_init))
else:
setattr(cls, "__post_init__", _custom_post_init)
# add helper functions for dictionary conversion
setattr(cls, "to_dict", _class_to_dict)
setattr(cls, "from_dict", _update_class_from_dict)
setattr(cls, "replace", _replace_class_with_kwargs)
setattr(cls, "copy", _copy_class)
# wrap around dataclass
cls = dataclass(cls, **kwargs)
# return wrapped class
return cls
"""
Dictionary <-> Class operations.
These are redefined here to add new docstrings.
"""
def _class_to_dict(obj: object) -> dict[str, Any]:
"""Convert an object into dictionary recursively.
Returns:
Converted dictionary mapping.
"""
return class_to_dict(obj)
def _update_class_from_dict(obj, data: dict[str, Any]) -> None:
"""Reads a dictionary and sets object variables recursively.
This function performs in-place update of the class member attributes.
Args:
data: Input (nested) dictionary to update from.
Raises:
TypeError: When input is not a dictionary.
ValueError: When dictionary has a value that does not match default config type.
KeyError: When dictionary has a key that does not exist in the default config type.
"""
return update_class_from_dict(obj, data, _ns="")
def _replace_class_with_kwargs(obj: object, **kwargs) -> object:
"""Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
.. code-block:: python
@configclass(frozen=True)
class C:
x: int
y: int
c = C(1, 2)
c1 = c.replace(x=3)
assert c1.x == 3 and c1.y == 2
Args:
obj: The object to replace.
**kwargs: The fields to replace and their new values.
Returns:
The new object.
"""
return replace(obj, **kwargs)
def _copy_class(obj: object) -> object:
"""Return a new object with the same fields as the original."""
return replace(obj)
"""
Private helper functions.
"""
def _add_annotation_types(cls):
"""Add annotations to all elements in the dataclass.
By definition in Python, a field is defined as a class variable that has a type annotation.
In case type annotations are not provided, dataclass ignores those members when :func:`__dict__()` is called.
This function adds these annotations to the class variable to prevent any issues in case the user forgets to
specify the type annotation.
This makes the following a feasible operation:
@dataclass
class State:
pos = (0.0, 0.0, 0.0)
^^
If the function is NOT used, the following type-error is returned:
TypeError: 'pos' is a field but has no type annotation
"""
# get type hints
hints = {}
# iterate over class inheritance
# we add annotations from base classes first
for base in reversed(cls.__mro__):
# check if base is object
if base is object:
continue
# get base class annotations
ann = base.__dict__.get("__annotations__", {})
# directly add all annotations from base class
hints.update(ann)
# iterate over base class members
# Note: Do not change this to dir(base) since it orders the members alphabetically.
# This is not desirable since the order of the members is important in some cases.
for key in base.__dict__:
# get class member
value = getattr(base, key)
# skip members
if _skippable_class_member(key, value, hints):
continue
# add type annotations for members that don't have explicit type annotations
# for these, we deduce the type from the default value
if not isinstance(value, type):
if key not in hints:
# check if var type is not MISSING
# we cannot deduce type from MISSING!
if value is MISSING:
raise TypeError(
f"Missing type annotation for '{key}' in class '{cls.__name__}'."
" Please add a type annotation or set a default value."
)
# add type annotation
hints[key] = type(value)
elif key != value.__name__:
# note: we don't want to add type annotations for nested configclass. Thus, we check if
# the name of the type matches the name of the variable.
# since Python 3.10, type hints are stored as strings
hints[key] = f"type[{value.__name__}]"
# Note: Do not change this line. `cls.__dict__.get("__annotations__", {})` is different from
# `cls.__annotations__` because of inheritance.
cls.__annotations__ = cls.__dict__.get("__annotations__", {})
cls.__annotations__ = hints
def _process_mutable_types(cls):
"""Initialize all mutable elements through :obj:`dataclasses.Field` to avoid unnecessary complaints.
By default, dataclass requires usage of :obj:`field(default_factory=...)` to reinitialize mutable objects every time a new
class instance is created. If a member has a mutable type and it is created without specifying the `field(default_factory=...)`,
then Python throws an error requiring the usage of `default_factory`.
Additionally, Python only explicitly checks for field specification when the type is a list, set or dict. This misses the
use-case where the type is class itself. Thus, the code silently carries a bug with it which can lead to undesirable effects.
This function deals with this issue
This makes the following a feasible operation:
@dataclass
class State:
pos: list = [0.0, 0.0, 0.0]
^^
If the function is NOT used, the following value-error is returned:
ValueError: mutable default <class 'list'> for field pos is not allowed: use default_factory
"""
# note: Need to set this up in the same order as annotations. Otherwise, it
# complains about missing positional arguments.
ann = cls.__dict__.get("__annotations__", {})
# iterate over all class members and store them in a dictionary
class_members = {}
for base in reversed(cls.__mro__):
# check if base is object
if base is object:
continue
# iterate over base class members
for key in base.__dict__:
# get class member
f = getattr(base, key)
# skip members
if _skippable_class_member(key, f):
continue
# store class member if it is not a type or if it is already present in annotations
if not isinstance(f, type) or key in ann:
class_members[key] = f
# iterate over base class data fields
# in previous call, things that became a dataclass field were removed from class members
# so we need to add them back here as a dataclass field directly
for key, f in base.__dict__.get("__dataclass_fields__", {}).items():
# store class member
if not isinstance(f, type):
class_members[key] = f
# check that all annotations are present in class members
# note: mainly for debugging purposes
if len(class_members) != len(ann):
raise ValueError(
f"In class '{cls.__name__}', number of annotations ({len(ann)}) does not match number of class members"
f" ({len(class_members)}). Please check that all class members have type annotations and/or a default"
" value. If you don't want to specify a default value, please use the literal `dataclasses.MISSING`."
)
# iterate over annotations and add field factory for mutable types
for key in ann:
# find matching field in class
value = class_members.get(key, MISSING)
# check if key belongs to ClassVar
# in that case, we cannot use default_factory!
origin = getattr(ann[key], "__origin__", None)
if origin is ClassVar:
continue
# check if f is MISSING
# note: commented out for now since it causes issue with inheritance
# of dataclasses when parent have some positional and some keyword arguments.
# Ref: https://stackoverflow.com/questions/51575931/class-inheritance-in-python-3-7-dataclasses
# TODO: check if this is fixed in Python 3.10
# if f is MISSING:
# continue
if isinstance(value, Field):
setattr(cls, key, value)
elif not isinstance(value, type):
# create field factory for mutable types
value = field(default_factory=_return_f(value))
setattr(cls, key, value)
def _custom_post_init(obj):
"""Deepcopy all elements to avoid shared memory issues for mutable objects in dataclasses initialization.
This function is called explicitly instead of as a part of :func:`_process_mutable_types()` to prevent mapping
proxy type i.e. a read only proxy for mapping objects. The error is thrown when using hierarchical data-classes
for configuration.
"""
for key in dir(obj):
# skip dunder members
if key.startswith("__"):
continue
# get data member
value = getattr(obj, key)
# duplicate data members
if not callable(value):
setattr(obj, key, deepcopy(value))
def _combined_function(f1: Callable, f2: Callable) -> Callable:
"""Combine two functions into one.
Args:
f1: The first function.
f2: The second function.
Returns:
The combined function.
"""
def _combined(*args, **kwargs):
# call both functions
f1(*args, **kwargs)
f2(*args, **kwargs)
return _combined
"""
Helper functions
"""
def _skippable_class_member(key: str, value: Any, hints: dict | None = None) -> bool:
"""Check if the class member should be skipped in configclass processing.
The following members are skipped:
* Dunder members: ``__name__``, ``__module__``, ``__qualname__``, ``__annotations__``, ``__dict__``.
* Manually-added special class functions: From :obj:`_CONFIGCLASS_METHODS`.
* Members that are already present in the type annotations.
* Functions bounded to class object or class.
Args:
key: The class member name.
value: The class member value.
hints: The type hints for the class. Defaults to None, in which case, the
members existence in type hints are not checked.
Returns:
True if the class member should be skipped, False otherwise.
"""
# skip dunder members
if key.startswith("__"):
return True
# skip manually-added special class functions
if key in _CONFIGCLASS_METHODS:
return True
# check if key is already present
if hints is not None and key in hints:
return True
# skip functions bounded to class
if callable(value):
signature = inspect.signature(value)
if "self" in signature.parameters or "cls" in signature.parameters:
return True
# Otherwise, don't skip
return False
def _return_f(f: Any) -> Callable[[], Any]:
"""Returns default factory function for creating mutable/immutable variables.
This function should be used to create default factory functions for variables.
Example:
.. code-block:: python
value = field(default_factory=_return_f(value))
setattr(cls, key, value)
"""
def _wrap():
if isinstance(f, Field):
if f.default_factory is MISSING:
return deepcopy(f.default)
else:
return f.default_factory
else:
return f
return _wrap
| 14,857 | Python | 34.125295 | 132 | 0.631016 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/assets.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module that defines the host-server where assets and resources are stored.
By default, we use the Isaac Sim Nucleus Server for hosting assets and resources. This makes
distribution of the assets easier and makes the repository smaller in size code-wise.
For more information on Omniverse Nucleus:
https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html#omniverse-nucleus
"""
from __future__ import annotations
import io
import os
import tempfile
from typing import Literal
import carb
import omni.client
import omni.isaac.core.utils.nucleus as nucleus_utils
# check nucleus connection
if nucleus_utils.get_assets_root_path() is None:
msg = (
"Unable to perform Nucleus login on Omniverse. Assets root path is not set.\n"
"\tPlease check: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html#omniverse-nucleus"
)
carb.log_error(msg)
raise RuntimeError(msg)
NVIDIA_NUCLEUS_DIR = f"{nucleus_utils.get_assets_root_path()}/NVIDIA"
"""Path to the root directory on the NVIDIA Nucleus Server."""
ISAAC_NUCLEUS_DIR = f"{nucleus_utils.get_assets_root_path()}/Isaac"
"""Path to the `Isaac` directory on the NVIDIA Nucleus Server."""
ISAAC_ORBIT_NUCLEUS_DIR = f"{ISAAC_NUCLEUS_DIR}/Samples/Orbit"
"""Path to the `Isaac/Samples/Orbit` directory on the NVIDIA Nucleus Server."""
def check_file_path(path: str) -> Literal[0, 1, 2]:
"""Checks if a file exists on the Nucleus Server or locally.
Args:
path: The path to the file.
Returns:
The status of the file. Possible values are:
* :obj:`0` if the file does not exist
* :obj:`1` if the file exists locally
* :obj:`2` if the file exists on the Nucleus Server
"""
if os.path.isfile(path):
return 1
elif omni.client.stat(path)[0] == omni.client.Result.OK:
return 2
else:
return 0
def retrieve_file_path(path: str, download_dir: str | None = None, force_download: bool = True) -> str:
"""Retrieves the path to a file on the Nucleus Server or locally.
If the file exists locally, then the absolute path to the file is returned.
If the file exists on the Nucleus Server, then the file is downloaded to the local machine
and the absolute path to the file is returned.
Args:
path: The path to the file.
download_dir: The directory where the file should be downloaded. Defaults to None, in which
case the file is downloaded to the system's temporary directory.
force_download: Whether to force download the file from the Nucleus Server. This will overwrite
the local file if it exists. Defaults to True.
Returns:
The path to the file on the local machine.
Raises:
FileNotFoundError: When the file not found locally or on Nucleus Server.
RuntimeError: When the file cannot be copied from the Nucleus Server to the local machine. This
can happen when the file already exists locally and :attr:`force_download` is set to False.
"""
# check file status
file_status = check_file_path(path)
if file_status == 1:
return os.path.abspath(path)
elif file_status == 2:
# resolve download directory
if download_dir is None:
download_dir = tempfile.gettempdir()
else:
download_dir = os.path.abspath(download_dir)
# create download directory if it does not exist
if not os.path.exists(download_dir):
os.makedirs(download_dir)
# download file in temp directory using os
file_name = os.path.basename(omni.client.break_url(path).path)
target_path = os.path.join(download_dir, file_name)
# check if file already exists locally
if not os.path.isfile(target_path) or force_download:
# copy file to local machine
result = omni.client.copy(path, target_path)
if result != omni.client.Result.OK and force_download:
raise RuntimeError(f"Unable to copy file: '{path}'. Is the Nucleus Server running?")
return os.path.abspath(target_path)
else:
raise FileNotFoundError(f"Unable to find the file: {path}")
def read_file(path: str) -> io.BytesIO:
"""Reads a file from the Nucleus Server or locally.
Args:
path: The path to the file.
Raises:
FileNotFoundError: When the file not found locally or on Nucleus Server.
Returns:
The content of the file.
"""
# check file status
file_status = check_file_path(path)
if file_status == 1:
with open(path, "rb") as f:
return io.BytesIO(f.read())
elif file_status == 2:
file_content = omni.client.read_file(path)[2]
return io.BytesIO(memoryview(file_content).tobytes())
else:
raise FileNotFoundError(f"Unable to find the file: {path}")
| 5,040 | Python | 35.79562 | 117 | 0.672222 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/io/yaml.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Utilities for file I/O with yaml."""
import os
import yaml
from omni.isaac.orbit.utils import class_to_dict
def load_yaml(filename: str) -> dict:
"""Loads an input PKL file safely.
Args:
filename: The path to pickled file.
Raises:
FileNotFoundError: When the specified file does not exist.
Returns:
The data read from the input file.
"""
if not os.path.exists(filename):
raise FileNotFoundError(f"File not found: {filename}")
with open(filename) as f:
data = yaml.full_load(f)
return data
def dump_yaml(filename: str, data: dict | object, sort_keys: bool = False):
"""Saves data into a YAML file safely.
Note:
The function creates any missing directory along the file's path.
Args:
filename: The path to save the file at.
data: The data to save either a dictionary or class object.
sort_keys: Whether to sort the keys in the output file. Defaults to False.
"""
# check ending
if not filename.endswith("yaml"):
filename += ".yaml"
# create directory
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename), exist_ok=True)
# convert data into dictionary
if not isinstance(data, dict):
data = class_to_dict(data)
# save data
with open(filename, "w") as f:
yaml.dump(data, f, default_flow_style=False, sort_keys=sort_keys)
| 1,572 | Python | 27.089285 | 82 | 0.653308 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/io/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Submodules for files IO operations.
"""
from .pkl import dump_pickle, load_pickle
from .yaml import dump_yaml, load_yaml
| 249 | Python | 19.833332 | 56 | 0.738956 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/io/pkl.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Utilities for file I/O with pickle."""
import os
import pickle
from typing import Any
def load_pickle(filename: str) -> Any:
"""Loads an input PKL file safely.
Args:
filename: The path to pickled file.
Raises:
FileNotFoundError: When the specified file does not exist.
Returns:
The data read from the input file.
"""
if not os.path.exists(filename):
raise FileNotFoundError(f"File not found: {filename}")
with open(filename, "rb") as f:
data = pickle.load(f)
return data
def dump_pickle(filename: str, data: Any):
"""Saves data into a pickle file safely.
Note:
The function creates any missing directory along the file's path.
Args:
filename: The path to save the file at.
data: The data to save.
"""
# check ending
if not filename.endswith("pkl"):
filename += ".pkl"
# create directory
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename), exist_ok=True)
# save data
with open(filename, "wb") as f:
pickle.dump(data, f)
| 1,252 | Python | 23.568627 | 73 | 0.638978 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/warp/kernels.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Custom kernels for warp."""
import warp as wp
@wp.kernel
def raycast_mesh_kernel(
mesh: wp.uint64,
ray_starts: wp.array(dtype=wp.vec3),
ray_directions: wp.array(dtype=wp.vec3),
ray_hits: wp.array(dtype=wp.vec3),
ray_distance: wp.array(dtype=wp.float32),
ray_normal: wp.array(dtype=wp.vec3),
ray_face_id: wp.array(dtype=wp.int32),
max_dist: float = 1e6,
return_distance: int = False,
return_normal: int = False,
return_face_id: int = False,
):
"""Performs ray-casting against a mesh.
This function performs ray-casting against the given mesh using the provided ray start positions
and directions. The resulting ray hit positions are stored in the :obj:`ray_hits` array.
Note that the `ray_starts`, `ray_directions`, and `ray_hits` arrays should have compatible shapes
and data types to ensure proper execution. Additionally, they all must be in the same frame.
The function utilizes the `mesh_query_ray` method from the `wp` module to perform the actual ray-casting
operation. The maximum ray-cast distance is set to `1e6` units.
Args:
mesh: The input mesh. The ray-casting is performed against this mesh on the device specified by the
`mesh`'s `device` attribute.
ray_starts: The input ray start positions. Shape is (N, 3).
ray_directions: The input ray directions. Shape is (N, 3).
ray_hits: The output ray hit positions. Shape is (N, 3).
ray_distance: The output ray hit distances. Shape is (N,), if `return_distance` is True. Otherwise,
this array is not used.
ray_normal: The output ray hit normals. Shape is (N, 3), if `return_normal` is True. Otherwise,
this array is not used.
ray_face_id: The output ray hit face ids. Shape is (N,), if `return_face_id` is True. Otherwise,
this array is not used.
max_dist: The maximum ray-cast distance. Defaults to 1e6.
return_distance: Whether to return the ray hit distances. Defaults to False.
return_normal: Whether to return the ray hit normals. Defaults to False`.
return_face_id: Whether to return the ray hit face ids. Defaults to False.
"""
# get the thread id
tid = wp.tid()
t = float(0.0) # hit distance along ray
u = float(0.0) # hit face barycentric u
v = float(0.0) # hit face barycentric v
sign = float(0.0) # hit face sign
n = wp.vec3() # hit face normal
f = int(0) # hit face index
# ray cast against the mesh and store the hit position
hit_success = wp.mesh_query_ray(mesh, ray_starts[tid], ray_directions[tid], max_dist, t, u, v, sign, n, f)
# if the ray hit, store the hit data
if hit_success:
ray_hits[tid] = ray_starts[tid] + t * ray_directions[tid]
if return_distance == 1:
ray_distance[tid] = t
if return_normal == 1:
ray_normal[tid] = n
if return_face_id == 1:
ray_face_id[tid] = f
| 3,123 | Python | 41.216216 | 110 | 0.651297 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/warp/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing operations based on warp."""
from .ops import convert_to_warp_mesh, raycast_mesh
| 230 | Python | 24.666664 | 56 | 0.747826 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/warp/ops.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Wrapping around warp kernels for compatibility with torch tensors."""
from __future__ import annotations
import numpy as np
import torch
import warp as wp
from . import kernels
def raycast_mesh(
ray_starts: torch.Tensor,
ray_directions: torch.Tensor,
mesh: wp.Mesh,
max_dist: float = 1e6,
return_distance: bool = False,
return_normal: bool = False,
return_face_id: bool = False,
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]:
"""Performs ray-casting against a mesh.
Note that the `ray_starts` and `ray_directions`, and `ray_hits` should have compatible shapes
and data types to ensure proper execution. Additionally, they all must be in the same frame.
Args:
ray_starts: The starting position of the rays. Shape (N, 3).
ray_directions: The ray directions for each ray. Shape (N, 3).
mesh: The warp mesh to ray-cast against.
max_dist: The maximum distance to ray-cast. Defaults to 1e6.
return_distance: Whether to return the distance of the ray until it hits the mesh. Defaults to False.
return_normal: Whether to return the normal of the mesh face the ray hits. Defaults to False.
return_face_id: Whether to return the face id of the mesh face the ray hits. Defaults to False.
Returns:
The ray hit position. Shape (N, 3).
The returned tensor contains :obj:`float('inf')` for missed hits.
The ray hit distance. Shape (N,).
Will only return if :attr:`return_distance` is True, else returns None.
The returned tensor contains :obj:`float('inf')` for missed hits.
The ray hit normal. Shape (N, 3).
Will only return if :attr:`return_normal` is True else returns None.
The returned tensor contains :obj:`float('inf')` for missed hits.
The ray hit face id. Shape (N,).
Will only return if :attr:`return_face_id` is True else returns None.
The returned tensor contains :obj:`int(-1)` for missed hits.
"""
# extract device and shape information
shape = ray_starts.shape
device = ray_starts.device
# device of the mesh
torch_device = wp.device_to_torch(mesh.device)
# reshape the tensors
ray_starts = ray_starts.to(torch_device).view(-1, 3).contiguous()
ray_directions = ray_directions.to(torch_device).view(-1, 3).contiguous()
num_rays = ray_starts.shape[0]
# create output tensor for the ray hits
ray_hits = torch.full((num_rays, 3), float("inf"), device=torch_device).contiguous()
# map the memory to warp arrays
ray_starts_wp = wp.from_torch(ray_starts, dtype=wp.vec3)
ray_directions_wp = wp.from_torch(ray_directions, dtype=wp.vec3)
ray_hits_wp = wp.from_torch(ray_hits, dtype=wp.vec3)
if return_distance:
ray_distance = torch.full((num_rays,), float("inf"), device=torch_device).contiguous()
ray_distance_wp = wp.from_torch(ray_distance, dtype=wp.float32)
else:
ray_distance = None
ray_distance_wp = wp.empty((1,), dtype=wp.float32, device=torch_device)
if return_normal:
ray_normal = torch.full((num_rays, 3), float("inf"), device=torch_device).contiguous()
ray_normal_wp = wp.from_torch(ray_normal, dtype=wp.vec3)
else:
ray_normal = None
ray_normal_wp = wp.empty((1,), dtype=wp.vec3, device=torch_device)
if return_face_id:
ray_face_id = torch.ones((num_rays,), dtype=torch.int32, device=torch_device).contiguous() * (-1)
ray_face_id_wp = wp.from_torch(ray_face_id, dtype=wp.int32)
else:
ray_face_id = None
ray_face_id_wp = wp.empty((1,), dtype=wp.int32, device=torch_device)
# launch the warp kernel
wp.launch(
kernel=kernels.raycast_mesh_kernel,
dim=num_rays,
inputs=[
mesh.id,
ray_starts_wp,
ray_directions_wp,
ray_hits_wp,
ray_distance_wp,
ray_normal_wp,
ray_face_id_wp,
float(max_dist),
int(return_distance),
int(return_normal),
int(return_face_id),
],
device=mesh.device,
)
# NOTE: Synchronize is not needed anymore, but we keep it for now. Check with @dhoeller.
wp.synchronize()
if return_distance:
ray_distance = ray_distance.to(device).view(shape[0], shape[1])
if return_normal:
ray_normal = ray_normal.to(device).view(shape)
if return_face_id:
ray_face_id = ray_face_id.to(device).view(shape[0], shape[1])
return ray_hits.to(device).view(shape), ray_distance, ray_normal, ray_face_id
def convert_to_warp_mesh(points: np.ndarray, indices: np.ndarray, device: str) -> wp.Mesh:
"""Create a warp mesh object with a mesh defined from vertices and triangles.
Args:
points: The vertices of the mesh. Shape is (N, 3), where N is the number of vertices.
indices: The triangles of the mesh as references to vertices for each triangle.
Shape is (M, 3), where M is the number of triangles / faces.
device: The device to use for the mesh.
Returns:
The warp mesh object.
"""
return wp.Mesh(
points=wp.array(points.astype(np.float32), dtype=wp.vec3, device=device),
indices=wp.array(indices.astype(np.int32).flatten(), dtype=wp.int32, device=device),
)
| 5,554 | Python | 38.678571 | 109 | 0.64152 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/noise/noise_model.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from . import noise_cfg
def constant_bias_noise(data: torch.Tensor, cfg: noise_cfg.ConstantBiasNoiseCfg) -> torch.Tensor:
"""Add a constant noise."""
return data + cfg.bias
def additive_uniform_noise(data: torch.Tensor, cfg: noise_cfg.UniformNoiseCfg) -> torch.Tensor:
"""Adds a noise sampled from a uniform distribution."""
return data + torch.rand_like(data) * (cfg.n_max - cfg.n_min) + cfg.n_min
def additive_gaussian_noise(data: torch.Tensor, cfg: noise_cfg.GaussianNoiseCfg) -> torch.Tensor:
"""Adds a noise sampled from a gaussian distribution."""
return data + cfg.mean + cfg.std * torch.randn_like(data)
| 870 | Python | 30.107142 | 97 | 0.717241 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/noise/noise_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from collections.abc import Callable
from dataclasses import MISSING
from omni.isaac.orbit.utils import configclass
from . import noise_model
@configclass
class NoiseCfg:
"""Base configuration for a noise term."""
func: Callable[[torch.Tensor, NoiseCfg], torch.Tensor] = MISSING
"""The function to be called for applying the noise.
Note:
The shape of the input and output tensors must be the same.
"""
@configclass
class AdditiveUniformNoiseCfg(NoiseCfg):
"""Configuration for a additive uniform noise term."""
func = noise_model.additive_uniform_noise
n_min: float = -1.0
"""The minimum value of the noise. Defaults to -1.0."""
n_max: float = 1.0
"""The maximum value of the noise. Defaults to 1.0."""
@configclass
class AdditiveGaussianNoiseCfg(NoiseCfg):
"""Configuration for a additive gaussian noise term."""
func = noise_model.additive_gaussian_noise
mean: float = 0.0
"""The mean of the noise. Defaults to 0.0."""
std: float = 1.0
"""The standard deviation of the noise. Defaults to 1.0."""
@configclass
class ConstantBiasNoiseCfg(NoiseCfg):
"""Configuration for a constant bias noise term."""
func = noise_model.constant_bias_noise
bias: float = 0.0
"""The bias to add. Defaults to 0.0."""
| 1,480 | Python | 23.278688 | 68 | 0.693243 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/utils/noise/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module containing different noise models implementations.
The noise models are implemented as functions that take in a tensor and a configuration and return a tensor
with the noise applied. These functions are then used in the :class:`NoiseCfg` configuration class.
Usage:
.. code-block:: python
import torch
from omni.isaac.orbit.utils.noise import AdditiveGaussianNoiseCfg
# create a random tensor
my_tensor = torch.rand(128, 128, device="cuda")
# create a noise configuration
cfg = AdditiveGaussianNoiseCfg(mean=0.0, std=1.0)
# apply the noise
my_noisified_tensor = cfg.func(my_tensor, cfg)
"""
from .noise_cfg import NoiseCfg # noqa: F401
from .noise_cfg import AdditiveGaussianNoiseCfg, AdditiveUniformNoiseCfg, ConstantBiasNoiseCfg
| 909 | Python | 29.333332 | 107 | 0.753575 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/asset_base_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from dataclasses import MISSING
from typing import Literal
from omni.isaac.orbit.sim import SpawnerCfg
from omni.isaac.orbit.utils import configclass
from .asset_base import AssetBase
@configclass
class AssetBaseCfg:
"""The base configuration class for an asset's parameters.
Please see the :class:`AssetBase` class for more information on the asset class.
"""
@configclass
class InitialStateCfg:
"""Initial state of the asset.
This defines the default initial state of the asset when it is spawned into the simulation, as
well as the default state when the simulation is reset.
After parsing the initial state, the asset class stores this information in the :attr:`data`
attribute of the asset class. This can then be accessed by the user to modify the state of the asset
during the simulation, for example, at resets.
"""
# root position
pos: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Position of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0)."""
rot: tuple[float, float, float, float] = (1.0, 0.0, 0.0, 0.0)
"""Quaternion rotation (w, x, y, z) of the root in simulation world frame.
Defaults to (1.0, 0.0, 0.0, 0.0).
"""
class_type: type[AssetBase] = MISSING
"""The associated asset class.
The class should inherit from :class:`omni.isaac.orbit.assets.asset_base.AssetBase`.
"""
prim_path: str = MISSING
"""Prim path (or expression) to the asset.
.. note::
The expression can contain the environment namespace regex ``{ENV_REGEX_NS}`` which
will be replaced with the environment namespace.
Example: ``{ENV_REGEX_NS}/Robot`` will be replaced with ``/World/envs/env_.*/Robot``.
"""
spawn: SpawnerCfg | None = None
"""Spawn configuration for the asset. Defaults to None.
If None, then no prims are spawned by the asset class. Instead, it is assumed that the
asset is already present in the scene.
"""
init_state: InitialStateCfg = InitialStateCfg()
"""Initial state of the rigid object. Defaults to identity pose."""
collision_group: Literal[0, -1] = 0
"""Collision group of the asset. Defaults to ``0``.
* ``-1``: global collision group (collides with all assets in the scene).
* ``0``: local collision group (collides with other assets in the same environment).
"""
debug_vis: bool = False
"""Whether to enable debug visualization for the asset. Defaults to ``False``."""
| 2,721 | Python | 33.455696 | 108 | 0.668872 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package for different assets, such as rigid objects and articulations.
An asset is a physical object that can be spawned in the simulation. The class handles both
the spawning of the asset into the USD stage as well as initialization of necessary physics
handles to interact with the asset.
Upon construction of the asset instance, the prim corresponding to the asset is spawned into the
USD stage if the spawn configuration is not None. The spawn configuration is defined in the
:attr:`AssetBaseCfg.spawn` attribute. In case the configured :attr:`AssetBaseCfg.prim_path` is
an expression, then the prim is spawned at all the matching paths. Otherwise, a single prim is
spawned at the configured path. For more information on the spawn configuration, see the
:mod:`omni.isaac.orbit.sim.spawners` module.
The asset class also registers callbacks for the stage play/stop events. These are used to
construct the physics handles for the asset as the physics engine is only available when the
stage is playing. Additionally, the class registers a callback for debug visualization of the
asset. This can be enabled by setting the :attr:`AssetBaseCfg.debug_vis` attribute to True.
The asset class follows the following naming convention for its methods:
* **set_xxx()**: These are used to only set the buffers into the :attr:`data` instance. However, they
do not write the data into the simulator. The writing of data only happens when the
:meth:`write_data_to_sim` method is called.
* **write_xxx_to_sim()**: These are used to set the buffers into the :attr:`data` instance and write
the corresponding data into the simulator as well.
* **update(dt)**: These are used to update the buffers in the :attr:`data` instance. This should
be called after a simulation step is performed.
The main reason to separate the ``set`` and ``write`` operations is to provide flexibility to the
user when they need to perform a post-processing operation of the buffers before applying them
into the simulator. A common example for this is dealing with explicit actuator models where the
specified joint targets are not directly applied to the simulator but are instead used to compute
the corresponding actuator torques.
"""
from .articulation import Articulation, ArticulationCfg, ArticulationData
from .asset_base import AssetBase
from .asset_base_cfg import AssetBaseCfg
from .rigid_object import RigidObject, RigidObjectCfg, RigidObjectData
| 2,567 | Python | 56.066665 | 101 | 0.791196 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/asset_base.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import inspect
import re
import weakref
from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any
import omni.kit.app
import omni.timeline
import omni.isaac.orbit.sim as sim_utils
if TYPE_CHECKING:
from .asset_base_cfg import AssetBaseCfg
class AssetBase(ABC):
"""The base interface class for assets.
An asset corresponds to any physics-enabled object that can be spawned in the simulation. These include
rigid objects, articulated objects, deformable objects etc. The core functionality of an asset is to
provide a set of buffers that can be used to interact with the simulator. The buffers are updated
by the asset class and can be written into the simulator using the their respective ``write`` methods.
This allows a convenient way to perform post-processing operations on the buffers before writing them
into the simulator and obtaining the corresponding simulation results.
The class handles both the spawning of the asset into the USD stage as well as initialization of necessary
physics handles to interact with the asset. Upon construction of the asset instance, the prim corresponding
to the asset is spawned into the USD stage if the spawn configuration is not None. The spawn configuration
is defined in the :attr:`AssetBaseCfg.spawn` attribute. In case the configured :attr:`AssetBaseCfg.prim_path`
is an expression, then the prim is spawned at all the matching paths. Otherwise, a single prim is spawned
at the configured path. For more information on the spawn configuration, see the
:mod:`omni.isaac.orbit.sim.spawners` module.
Unlike Isaac Sim interface, where one usually needs to call the
:meth:`omni.isaac.core.prims.XFormPrimView.initialize` method to initialize the PhysX handles, the asset
class automatically initializes and invalidates the PhysX handles when the stage is played/stopped. This
is done by registering callbacks for the stage play/stop events.
Additionally, the class registers a callback for debug visualization of the asset if a debug visualization
is implemented in the asset class. This can be enabled by setting the :attr:`AssetBaseCfg.debug_vis` attribute
to True. The debug visualization is implemented through the :meth:`_set_debug_vis_impl` and
:meth:`_debug_vis_callback` methods.
"""
def __init__(self, cfg: AssetBaseCfg):
"""Initialize the asset base.
Args:
cfg: The configuration class for the asset.
Raises:
RuntimeError: If no prims found at input prim path or prim path expression.
"""
# store inputs
self.cfg = cfg
# flag for whether the asset is initialized
self._is_initialized = False
# check if base asset path is valid
# note: currently the spawner does not work if there is a regex pattern in the leaf
# For example, if the prim path is "/World/Robot_[1,2]" since the spawner will not
# know which prim to spawn. This is a limitation of the spawner and not the asset.
asset_path = self.cfg.prim_path.split("/")[-1]
asset_path_is_regex = re.match(r"^[a-zA-Z0-9/_]+$", asset_path) is None
# spawn the asset
if self.cfg.spawn is not None and not asset_path_is_regex:
self.cfg.spawn.func(
self.cfg.prim_path,
self.cfg.spawn,
translation=self.cfg.init_state.pos,
orientation=self.cfg.init_state.rot,
)
# check that spawn was successful
matching_prims = sim_utils.find_matching_prims(self.cfg.prim_path)
if len(matching_prims) == 0:
raise RuntimeError(f"Could not find prim with path {self.cfg.prim_path}.")
# note: Use weakref on all callbacks to ensure that this object can be deleted when its destructor is called.
# add callbacks for stage play/stop
# The order is set to 10 which is arbitrary but should be lower priority than the default order of 0
timeline_event_stream = omni.timeline.get_timeline_interface().get_timeline_event_stream()
self._initialize_handle = timeline_event_stream.create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.PLAY),
lambda event, obj=weakref.proxy(self): obj._initialize_callback(event),
order=10,
)
self._invalidate_initialize_handle = timeline_event_stream.create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.STOP),
lambda event, obj=weakref.proxy(self): obj._invalidate_initialize_callback(event),
order=10,
)
# add handle for debug visualization (this is set to a valid handle inside set_debug_vis)
self._debug_vis_handle = None
# set initial state of debug visualization
self.set_debug_vis(self.cfg.debug_vis)
def __del__(self):
"""Unsubscribe from the callbacks."""
# clear physics events handles
if self._initialize_handle:
self._initialize_handle.unsubscribe()
self._initialize_handle = None
if self._invalidate_initialize_handle:
self._invalidate_initialize_handle.unsubscribe()
self._invalidate_initialize_handle = None
# clear debug visualization
if self._debug_vis_handle:
self._debug_vis_handle.unsubscribe()
self._debug_vis_handle = None
"""
Properties
"""
@property
@abstractmethod
def num_instances(self) -> int:
"""Number of instances of the asset.
This is equal to the number of asset instances per environment multiplied by the number of environments.
"""
return NotImplementedError
@property
def device(self) -> str:
"""Memory device for computation."""
return self._device
@property
@abstractmethod
def data(self) -> Any:
"""Data related to the asset."""
return NotImplementedError
@property
def has_debug_vis_implementation(self) -> bool:
"""Whether the asset has a debug visualization implemented."""
# check if function raises NotImplementedError
source_code = inspect.getsource(self._set_debug_vis_impl)
return "NotImplementedError" not in source_code
"""
Operations.
"""
def set_debug_vis(self, debug_vis: bool) -> bool:
"""Sets whether to visualize the asset data.
Args:
debug_vis: Whether to visualize the asset data.
Returns:
Whether the debug visualization was successfully set. False if the asset
does not support debug visualization.
"""
# check if debug visualization is supported
if not self.has_debug_vis_implementation:
return False
# toggle debug visualization objects
self._set_debug_vis_impl(debug_vis)
# toggle debug visualization handles
if debug_vis:
# create a subscriber for the post update event if it doesn't exist
if self._debug_vis_handle is None:
app_interface = omni.kit.app.get_app_interface()
self._debug_vis_handle = app_interface.get_post_update_event_stream().create_subscription_to_pop(
lambda event, obj=weakref.proxy(self): obj._debug_vis_callback(event)
)
else:
# remove the subscriber if it exists
if self._debug_vis_handle is not None:
self._debug_vis_handle.unsubscribe()
self._debug_vis_handle = None
# return success
return True
@abstractmethod
def reset(self, env_ids: Sequence[int] | None = None):
"""Resets all internal buffers of selected environments.
Args:
env_ids: The indices of the object to reset. Defaults to None (all instances).
"""
raise NotImplementedError
@abstractmethod
def write_data_to_sim(self):
"""Writes data to the simulator."""
raise NotImplementedError
@abstractmethod
def update(self, dt: float):
"""Update the internal buffers.
The time step ``dt`` is used to compute numerical derivatives of quantities such as joint
accelerations which are not provided by the simulator.
Args:
dt: The amount of time passed from last ``update`` call.
"""
raise NotImplementedError
"""
Implementation specific.
"""
@abstractmethod
def _initialize_impl(self):
"""Initializes the PhysX handles and internal buffers."""
raise NotImplementedError
def _set_debug_vis_impl(self, debug_vis: bool):
"""Set debug visualization into visualization objects.
This function is responsible for creating the visualization objects if they don't exist
and input ``debug_vis`` is True. If the visualization objects exist, the function should
set their visibility into the stage.
"""
raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.")
def _debug_vis_callback(self, event):
"""Callback for debug visualization.
This function calls the visualization objects and sets the data to visualize into them.
"""
raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.")
"""
Internal simulation callbacks.
"""
def _initialize_callback(self, event):
"""Initializes the scene elements.
Note:
PhysX handles are only enabled once the simulator starts playing. Hence, this function needs to be
called whenever the simulator "plays" from a "stop" state.
"""
if not self._is_initialized:
# obtain simulation related information
sim = sim_utils.SimulationContext.instance()
if sim is None:
raise RuntimeError("SimulationContext is not initialized! Please initialize SimulationContext first.")
self._backend = sim.backend
self._device = sim.device
# initialize the asset
self._initialize_impl()
# set flag
self._is_initialized = True
def _invalidate_initialize_callback(self, event):
"""Invalidates the scene elements."""
self._is_initialized = False
| 10,684 | Python | 39.782443 | 118 | 0.659023 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/rigid_object/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for rigid object assets."""
from .rigid_object import RigidObject
from .rigid_object_cfg import RigidObjectCfg
from .rigid_object_data import RigidObjectData
| 296 | Python | 25.999998 | 56 | 0.777027 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/rigid_object/rigid_object_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from omni.isaac.orbit.utils import configclass
from ..asset_base_cfg import AssetBaseCfg
from .rigid_object import RigidObject
@configclass
class RigidObjectCfg(AssetBaseCfg):
"""Configuration parameters for a rigid object."""
@configclass
class InitialStateCfg(AssetBaseCfg.InitialStateCfg):
"""Initial state of the rigid body."""
lin_vel: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Linear velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0)."""
ang_vel: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Angular velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0)."""
##
# Initialize configurations.
##
class_type: type = RigidObject
init_state: InitialStateCfg = InitialStateCfg()
"""Initial state of the rigid object. Defaults to identity pose with zero velocity."""
| 1,065 | Python | 29.457142 | 98 | 0.683568 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/rigid_object/rigid_object_data.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from dataclasses import dataclass
@dataclass
class RigidObjectData:
"""Data container for a rigid object."""
##
# Properties.
##
body_names: list[str] = None
"""Body names in the order parsed by the simulation view."""
##
# Default states.
##
default_root_state: torch.Tensor = None
"""Default root state ``[pos, quat, lin_vel, ang_vel]`` in local environment frame. Shape is (num_instances, 13)."""
##
# Frame states.
##
root_state_w: torch.Tensor = None
"""Root state ``[pos, quat, lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 13)."""
root_vel_b: torch.Tensor = None
"""Root velocity `[lin_vel, ang_vel]` in base frame. Shape is (num_instances, 6)."""
projected_gravity_b: torch.Tensor = None
"""Projection of the gravity direction on base frame. Shape is (num_instances, 3)."""
heading_w: torch.Tensor = None
"""Yaw heading of the base frame (in radians). Shape is (num_instances,).
Note:
This quantity is computed by assuming that the forward-direction of the base
frame is along x-direction, i.e. :math:`(1, 0, 0)`.
"""
body_state_w: torch.Tensor = None
"""State of all bodies `[pos, quat, lin_vel, ang_vel]` in simulation world frame.
Shape is (num_instances, num_bodies, 13)."""
body_acc_w: torch.Tensor = None
"""Acceleration of all bodies. Shape is (num_instances, num_bodies, 6).
Note:
This quantity is computed based on the rigid body state from the last step.
"""
"""
Properties
"""
@property
def root_pos_w(self) -> torch.Tensor:
"""Root position in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, :3]
@property
def root_quat_w(self) -> torch.Tensor:
"""Root orientation (w, x, y, z) in simulation world frame. Shape is (num_instances, 4)."""
return self.root_state_w[:, 3:7]
@property
def root_vel_w(self) -> torch.Tensor:
"""Root velocity in simulation world frame. Shape is (num_instances, 6)."""
return self.root_state_w[:, 7:13]
@property
def root_lin_vel_w(self) -> torch.Tensor:
"""Root linear velocity in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, 7:10]
@property
def root_ang_vel_w(self) -> torch.Tensor:
"""Root angular velocity in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, 10:13]
@property
def root_lin_vel_b(self) -> torch.Tensor:
"""Root linear velocity in base frame. Shape is (num_instances, 3)."""
return self.root_vel_b[:, 0:3]
@property
def root_ang_vel_b(self) -> torch.Tensor:
"""Root angular velocity in base world frame. Shape is (num_instances, 3)."""
return self.root_vel_b[:, 3:6]
@property
def body_pos_w(self) -> torch.Tensor:
"""Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., :3]
@property
def body_quat_w(self) -> torch.Tensor:
"""Orientation (w, x, y, z) of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 4)."""
return self.body_state_w[..., 3:7]
@property
def body_vel_w(self) -> torch.Tensor:
"""Velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 6)."""
return self.body_state_w[..., 7:13]
@property
def body_lin_vel_w(self) -> torch.Tensor:
"""Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., 7:10]
@property
def body_ang_vel_w(self) -> torch.Tensor:
"""Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., 10:13]
@property
def body_lin_acc_w(self) -> torch.Tensor:
"""Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_acc_w[..., 0:3]
@property
def body_ang_acc_w(self) -> torch.Tensor:
"""Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_acc_w[..., 3:6]
| 4,594 | Python | 33.037037 | 120 | 0.622987 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/rigid_object/rigid_object.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
import warnings
from collections.abc import Sequence
from typing import TYPE_CHECKING
import carb
import omni.physics.tensors.impl.api as physx
from pxr import UsdPhysics
import omni.isaac.orbit.sim as sim_utils
import omni.isaac.orbit.utils.math as math_utils
import omni.isaac.orbit.utils.string as string_utils
from ..asset_base import AssetBase
from .rigid_object_data import RigidObjectData
if TYPE_CHECKING:
from .rigid_object_cfg import RigidObjectCfg
class RigidObject(AssetBase):
"""A rigid object asset class.
Rigid objects are assets comprising of rigid bodies. They can be used to represent dynamic objects
such as boxes, spheres, etc. A rigid body is described by its pose, velocity and mass distribution.
For an asset to be considered a rigid object, the root prim of the asset must have the `USD RigidBodyAPI`_
applied to it. This API is used to define the simulation properties of the rigid body. On playing the
simulation, the physics engine will automatically register the rigid body and create a corresponding
rigid body handle. This handle can be accessed using the :attr:`root_physx_view` attribute.
.. note::
For users familiar with Isaac Sim, the PhysX view class API is not the exactly same as Isaac Sim view
class API. Similar to Orbit, Isaac Sim wraps around the PhysX view API. However, as of now (2023.1 release),
we see a large difference in initializing the view classes in Isaac Sim. This is because the view classes
in Isaac Sim perform additional USD-related operations which are slow and also not required.
.. _`USD RigidBodyAPI`: https://openusd.org/dev/api/class_usd_physics_rigid_body_a_p_i.html
"""
cfg: RigidObjectCfg
"""Configuration instance for the rigid object."""
def __init__(self, cfg: RigidObjectCfg):
"""Initialize the rigid object.
Args:
cfg: A configuration instance.
"""
super().__init__(cfg)
# container for data access
self._data = RigidObjectData()
"""
Properties
"""
@property
def data(self) -> RigidObjectData:
return self._data
@property
def num_instances(self) -> int:
return self.root_physx_view.count
@property
def num_bodies(self) -> int:
"""Number of bodies in the asset."""
return 1
@property
def body_names(self) -> list[str]:
"""Ordered names of bodies in articulation."""
prim_paths = self.root_physx_view.prim_paths[: self.num_bodies]
return [path.split("/")[-1] for path in prim_paths]
@property
def root_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
Note:
Use this view with caution. It requires handling of tensors in a specific way.
"""
return self._root_physx_view
@property
def body_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
.. deprecated:: v0.3.0
The attribute 'body_physx_view' will be removed in v0.4.0. Please use :attr:`root_physx_view` instead.
"""
dep_msg = "The attribute 'body_physx_view' will be removed in v0.4.0. Please use 'root_physx_view' instead."
warnings.warn(dep_msg, DeprecationWarning)
carb.log_error(dep_msg)
return self.root_physx_view
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None):
# resolve all indices
if env_ids is None:
env_ids = slice(None)
# reset external wrench
self._external_force_b[env_ids] = 0.0
self._external_torque_b[env_ids] = 0.0
# reset last body vel
self._last_body_vel_w[env_ids] = 0.0
def write_data_to_sim(self):
"""Write external wrench to the simulation.
Note:
We write external wrench to the simulation here since this function is called before the simulation step.
This ensures that the external wrench is applied at every simulation step.
"""
# write external wrench
if self.has_external_wrench:
self.root_physx_view.apply_forces_and_torques_at_position(
force_data=self._external_force_b.view(-1, 3),
torque_data=self._external_torque_b.view(-1, 3),
position_data=None,
indices=self._ALL_BODY_INDICES,
is_global=False,
)
def update(self, dt: float):
# -- root-state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.root_state_w[:, :7] = self.root_physx_view.get_transforms()
self._data.root_state_w[:, 3:7] = math_utils.convert_quat(self._data.root_state_w[:, 3:7], to="wxyz")
self._data.root_state_w[:, 7:] = self.root_physx_view.get_velocities()
# -- body-state (note: for rigid objects, we only have one body so we just copy the root state)
self._data.body_state_w[:] = self._data.root_state_w.view(-1, self.num_bodies, 13)
# -- update common data
self._update_common_data(dt)
def find_bodies(self, name_keys: str | Sequence[str], preserve_order: bool = False) -> tuple[list[int], list[str]]:
"""Find bodies in the articulation based on the name keys.
Please check the :meth:`omni.isaac.orbit.utils.string_utils.resolve_matching_names` function for more
information on the name matching.
Args:
name_keys: A regular expression or a list of regular expressions to match the body names.
preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False.
Returns:
A tuple of lists containing the body indices and names.
"""
return string_utils.resolve_matching_names(name_keys, self.body_names, preserve_order)
"""
Operations - Write to simulation.
"""
def write_root_state_to_sim(self, root_state: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root state over selected environment indices into the simulation.
The root state comprises of the cartesian position, quaternion orientation in (w, x, y, z), and linear
and angular velocity. All the quantities are in the simulation frame.
Args:
root_state: Root state in simulation frame. Shape is (len(env_ids), 13).
env_ids: Environment indices. If None, then all indices are used.
"""
# set into simulation
self.write_root_pose_to_sim(root_state[:, :7], env_ids=env_ids)
self.write_root_velocity_to_sim(root_state[:, 7:], env_ids=env_ids)
def write_root_pose_to_sim(self, root_pose: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root pose over selected environment indices into the simulation.
The root pose comprises of the cartesian position and quaternion orientation in (w, x, y, z).
Args:
root_pose: Root poses in simulation frame. Shape is (len(env_ids), 7).
env_ids: Environment indices. If None, then all indices are used.
"""
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, :7] = root_pose.clone()
# convert root quaternion from wxyz to xyzw
root_poses_xyzw = self._data.root_state_w[:, :7].clone()
root_poses_xyzw[:, 3:] = math_utils.convert_quat(root_poses_xyzw[:, 3:], to="xyzw")
# set into simulation
self.root_physx_view.set_transforms(root_poses_xyzw, indices=physx_env_ids)
def write_root_velocity_to_sim(self, root_velocity: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root velocity over selected environment indices into the simulation.
Args:
root_velocity: Root velocities in simulation frame. Shape is (len(env_ids), 6).
env_ids: Environment indices. If None, then all indices are used.
"""
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, 7:] = root_velocity.clone()
# set into simulation
self.root_physx_view.set_velocities(self._data.root_state_w[:, 7:], indices=physx_env_ids)
"""
Operations - Setters.
"""
def set_external_force_and_torque(
self,
forces: torch.Tensor,
torques: torch.Tensor,
body_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set external force and torque to apply on the asset's bodies in their local frame.
For many applications, we want to keep the applied external force on rigid bodies constant over a period of
time (for instance, during the policy control). This function allows us to store the external force and torque
into buffers which are then applied to the simulation at every step.
.. caution::
If the function is called with empty forces and torques, then this function disables the application
of external wrench to the simulation.
.. code-block:: python
# example of disabling external wrench
asset.set_external_force_and_torque(forces=torch.zeros(0, 3), torques=torch.zeros(0, 3))
.. note::
This function does not apply the external wrench to the simulation. It only fills the buffers with
the desired values. To apply the external wrench, call the :meth:`write_data_to_sim` function
right before the simulation step.
Args:
forces: External forces in bodies' local frame. Shape is (len(env_ids), len(body_ids), 3).
torques: External torques in bodies' local frame. Shape is (len(env_ids), len(body_ids), 3).
body_ids: Body indices to apply external wrench to. Defaults to None (all bodies).
env_ids: Environment indices to apply external wrench to. Defaults to None (all instances).
"""
if forces.any() or torques.any():
self.has_external_wrench = True
# resolve all indices
# -- env_ids
if env_ids is None:
env_ids = self._ALL_INDICES
elif not isinstance(env_ids, torch.Tensor):
env_ids = torch.tensor(env_ids, dtype=torch.long, device=self.device)
# -- body_ids
if body_ids is None:
body_ids = torch.arange(self.num_bodies, dtype=torch.long, device=self.device)
elif isinstance(body_ids, slice):
body_ids = torch.arange(self.num_bodies, dtype=torch.long, device=self.device)[body_ids]
elif not isinstance(body_ids, torch.Tensor):
body_ids = torch.tensor(body_ids, dtype=torch.long, device=self.device)
# note: we need to do this complicated indexing since torch doesn't support multi-indexing
# create global body indices from env_ids and env_body_ids
# (env_id * total_bodies_per_env) + body_id
indices = body_ids.repeat(len(env_ids), 1) + env_ids.unsqueeze(1) * self.num_bodies
indices = indices.view(-1)
# set into internal buffers
# note: these are applied in the write_to_sim function
self._external_force_b.flatten(0, 1)[indices] = forces.flatten(0, 1)
self._external_torque_b.flatten(0, 1)[indices] = torques.flatten(0, 1)
else:
self.has_external_wrench = False
"""
Internal helper.
"""
def _initialize_impl(self):
# create simulation view
self._physics_sim_view = physx.create_simulation_view(self._backend)
self._physics_sim_view.set_subspace_roots("/")
# obtain the first prim in the regex expression (all others are assumed to be a copy of this)
template_prim = sim_utils.find_first_matching_prim(self.cfg.prim_path)
if template_prim is None:
raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.")
template_prim_path = template_prim.GetPath().pathString
# find rigid root prims
root_prims = sim_utils.get_all_matching_child_prims(
template_prim_path, predicate=lambda prim: prim.HasAPI(UsdPhysics.RigidBodyAPI)
)
if len(root_prims) != 1:
raise RuntimeError(
f"Failed to find a single rigid body when resolving '{self.cfg.prim_path}'."
f" Found multiple '{root_prims}' under '{template_prim_path}'."
)
# resolve root prim back into regex expression
root_prim_path = root_prims[0].GetPath().pathString
root_prim_path_expr = self.cfg.prim_path + root_prim_path[len(template_prim_path) :]
# -- object view
self._root_physx_view = self._physics_sim_view.create_rigid_body_view(root_prim_path_expr.replace(".*", "*"))
# log information about the articulation
carb.log_info(f"Rigid body initialized at: {self.cfg.prim_path} with root '{root_prim_path_expr}'.")
carb.log_info(f"Number of instances: {self.num_instances}")
carb.log_info(f"Number of bodies: {self.num_bodies}")
carb.log_info(f"Body names: {self.body_names}")
# create buffers
self._create_buffers()
# process configuration
self._process_cfg()
def _create_buffers(self):
"""Create buffers for storing data."""
# constants
self._ALL_INDICES = torch.arange(self.num_instances, dtype=torch.long, device=self.device)
self._ALL_BODY_INDICES = torch.arange(
self.root_physx_view.count * self.num_bodies, dtype=torch.long, device=self.device
)
self.GRAVITY_VEC_W = torch.tensor((0.0, 0.0, -1.0), device=self.device).repeat(self.num_instances, 1)
self.FORWARD_VEC_B = torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self.num_instances, 1)
# external forces and torques
self.has_external_wrench = False
self._external_force_b = torch.zeros((self.num_instances, self.num_bodies, 3), device=self.device)
self._external_torque_b = torch.zeros_like(self._external_force_b)
# asset data
# -- properties
self._data.body_names = self.body_names
# -- root states
self._data.root_state_w = torch.zeros(self.num_instances, 13, device=self.device)
self._data.root_state_w[:, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
self._data.default_root_state = torch.zeros_like(self._data.root_state_w)
self._data.default_root_state[:, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
# -- body states
self._data.body_state_w = torch.zeros(self.num_instances, self.num_bodies, 13, device=self.device)
self._data.body_state_w[:, :, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
# -- post-computed
self._data.root_vel_b = torch.zeros(self.num_instances, 6, device=self.device)
self._data.projected_gravity_b = torch.zeros(self.num_instances, 3, device=self.device)
self._data.heading_w = torch.zeros(self.num_instances, device=self.device)
self._data.body_acc_w = torch.zeros(self.num_instances, self.num_bodies, 6, device=self.device)
# history buffers for quantities
# -- used to compute body accelerations numerically
self._last_body_vel_w = torch.zeros(self.num_instances, self.num_bodies, 6, device=self.device)
def _process_cfg(self):
"""Post processing of configuration parameters."""
# default state
# -- root state
# note: we cast to tuple to avoid torch/numpy type mismatch.
default_root_state = (
tuple(self.cfg.init_state.pos)
+ tuple(self.cfg.init_state.rot)
+ tuple(self.cfg.init_state.lin_vel)
+ tuple(self.cfg.init_state.ang_vel)
)
default_root_state = torch.tensor(default_root_state, dtype=torch.float, device=self.device)
self._data.default_root_state = default_root_state.repeat(self.num_instances, 1)
def _update_common_data(self, dt: float):
"""Update common quantities related to rigid objects.
Note:
This has been separated from the update function to allow for the child classes to
override the update function without having to worry about updating the common data.
"""
# -- body acceleration
self._data.body_acc_w[:] = (self._data.body_state_w[..., 7:] - self._last_body_vel_w) / dt
self._last_body_vel_w[:] = self._data.body_state_w[..., 7:]
# -- root state in body frame
self._data.root_vel_b[:, 0:3] = math_utils.quat_rotate_inverse(
self._data.root_quat_w, self._data.root_lin_vel_w
)
self._data.root_vel_b[:, 3:6] = math_utils.quat_rotate_inverse(
self._data.root_quat_w, self._data.root_ang_vel_w
)
self._data.projected_gravity_b[:] = math_utils.quat_rotate_inverse(self._data.root_quat_w, self.GRAVITY_VEC_W)
# -- heading direction of root
forward_w = math_utils.quat_apply(self._data.root_quat_w, self.FORWARD_VEC_B)
self._data.heading_w[:] = torch.atan2(forward_w[:, 1], forward_w[:, 0])
"""
Internal simulation callbacks.
"""
def _invalidate_initialize_callback(self, event):
"""Invalidates the scene elements."""
# call parent
super()._invalidate_initialize_callback(event)
# set all existing views to None to invalidate them
self._physics_sim_view = None
self._root_physx_view = None
| 18,412 | Python | 44.01956 | 119 | 0.632305 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/config/cassie.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for Agility robots.
The following configurations are available:
* :obj:`CASSIE_CFG`: Agility Cassie robot with simple PD controller for the legs
Reference: https://github.com/UMich-BipedLab/Cassie_Model/blob/master/urdf/cassie.urdf
"""
from __future__ import annotations
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
from ..articulation import ArticulationCfg
##
# Configuration
##
CASSIE_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Agility/Cassie/cassie.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.9),
joint_pos={
"hip_abduction_left": 0.1,
"hip_rotation_left": 0.0,
"hip_flexion_left": 1.0,
"thigh_joint_left": -1.8,
"ankle_joint_left": 1.57,
"toe_joint_left": -1.57,
"hip_abduction_right": -0.1,
"hip_rotation_right": 0.0,
"hip_flexion_right": 1.0,
"thigh_joint_right": -1.8,
"ankle_joint_right": 1.57,
"toe_joint_right": -1.57,
},
joint_vel={".*": 0.0},
),
soft_joint_pos_limit_factor=0.9,
actuators={
"legs": ImplicitActuatorCfg(
joint_names_expr=["hip_.*", "thigh_.*", "ankle_.*"],
effort_limit=200.0,
velocity_limit=10.0,
stiffness={
"hip_abduction.*": 100.0,
"hip_rotation.*": 100.0,
"hip_flexion.*": 200.0,
"thigh_joint.*": 200.0,
"ankle_joint.*": 200.0,
},
damping={
"hip_abduction.*": 3.0,
"hip_rotation.*": 3.0,
"hip_flexion.*": 6.0,
"thigh_joint.*": 6.0,
"ankle_joint.*": 6.0,
},
),
"toes": ImplicitActuatorCfg(
joint_names_expr=["toe_.*"],
effort_limit=20.0,
velocity_limit=10.0,
stiffness={
"toe_joint.*": 20.0,
},
damping={
"toe_joint.*": 1.0,
},
),
},
)
| 2,980 | Python | 29.731958 | 110 | 0.537919 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/articulation/articulation_data.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import torch
from dataclasses import dataclass
from ..rigid_object import RigidObjectData
@dataclass
class ArticulationData(RigidObjectData):
"""Data container for an articulation."""
##
# Properties.
##
joint_names: list[str] = None
"""Joint names in the order parsed by the simulation view."""
##
# Default states.
##
default_joint_pos: torch.Tensor = None
"""Default joint positions of all joints. Shape is (num_instances, num_joints)."""
default_joint_vel: torch.Tensor = None
"""Default joint velocities of all joints. Shape is (num_instances, num_joints)."""
##
# Joint states <- From simulation.
##
joint_pos: torch.Tensor = None
"""Joint positions of all joints. Shape is (num_instances, num_joints)."""
joint_vel: torch.Tensor = None
"""Joint velocities of all joints. Shape is (num_instances, num_joints)."""
joint_acc: torch.Tensor = None
"""Joint acceleration of all joints. Shape is (num_instances, num_joints)."""
##
# Joint commands -- Set into simulation.
##
joint_pos_target: torch.Tensor = None
"""Joint position targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
joint_vel_target: torch.Tensor = None
"""Joint velocity targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
joint_effort_target: torch.Tensor = None
"""Joint effort targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
joint_stiffness: torch.Tensor = None
"""Joint stiffness provided to simulation. Shape is (num_instances, num_joints)."""
joint_damping: torch.Tensor = None
"""Joint damping provided to simulation. Shape is (num_instances, num_joints)."""
joint_armature: torch.Tensor = None
"""Joint armature provided to simulation. Shape is (num_instances, num_joints)."""
joint_friction: torch.Tensor = None
"""Joint friction provided to simulation. Shape is (num_instances, num_joints)."""
##
# Joint commands -- Explicit actuators.
##
computed_torque: torch.Tensor = None
"""Joint torques computed from the actuator model (before clipping). Shape is (num_instances, num_joints).
This quantity is the raw torque output from the actuator mode, before any clipping is applied.
It is exposed for users who want to inspect the computations inside the actuator model.
For instance, to penalize the learning agent for a difference between the computed and applied torques.
Note: The torques are zero for implicit actuator models.
"""
applied_torque: torch.Tensor = None
"""Joint torques applied from the actuator model (after clipping). Shape is (num_instances, num_joints).
These torques are set into the simulation, after clipping the :attr:`computed_torque` based on the
actuator model.
Note: The torques are zero for implicit actuator models.
"""
##
# Other Data.
##
soft_joint_pos_limits: torch.Tensor = None
"""Joint positions limits for all joints. Shape is (num_instances, num_joints, 2)."""
soft_joint_vel_limits: torch.Tensor = None
"""Joint velocity limits for all joints. Shape is (num_instances, num_joints)."""
gear_ratio: torch.Tensor = None
"""Gear ratio for relating motor torques to applied Joint torques. Shape is (num_instances, num_joints)."""
| 4,271 | Python | 34.305785 | 115 | 0.694919 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/articulation/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for rigid articulated assets."""
from .articulation import Articulation
from .articulation_cfg import ArticulationCfg
from .articulation_data import ArticulationData
| 304 | Python | 26.72727 | 56 | 0.792763 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/articulation/articulation.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# Flag for pyright to ignore type errors in this file.
# pyright: reportPrivateUsage=false
from __future__ import annotations
import torch
import warnings
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
import carb
import omni.physics.tensors.impl.api as physx
from omni.isaac.core.utils.types import ArticulationActions
from pxr import UsdPhysics
import omni.isaac.orbit.sim as sim_utils
import omni.isaac.orbit.utils.math as math_utils
import omni.isaac.orbit.utils.string as string_utils
from omni.isaac.orbit.actuators import ActuatorBase, ActuatorBaseCfg, ImplicitActuator
from ..rigid_object import RigidObject
from .articulation_data import ArticulationData
if TYPE_CHECKING:
from .articulation_cfg import ArticulationCfg
class Articulation(RigidObject):
"""An articulation asset class.
An articulation is a collection of rigid bodies connected by joints. The joints can be either
fixed or actuated. The joints can be of different types, such as revolute, prismatic, D-6, etc.
However, the articulation class has currently been tested with revolute and prismatic joints.
The class supports both floating-base and fixed-base articulations. The type of articulation
is determined based on the root joint of the articulation. If the root joint is fixed, then
the articulation is considered a fixed-base system. Otherwise, it is considered a floating-base
system. This can be checked using the :attr:`Articulation.is_fixed_base` attribute.
For an asset to be considered an articulation, the root prim of the asset must have the
`USD ArticulationRootAPI`_. This API is used to define the sub-tree of the articulation using
the reduced coordinate formulation. On playing the simulation, the physics engine parses the
articulation root prim and creates the corresponding articulation in the physics engine. The
articulation root prim can be specified using the :attr:`AssetBaseCfg.prim_path` attribute.
The articulation class is a subclass of the :class:`RigidObject` class. Therefore, it inherits
all the functionality of the rigid object class. In case of an articulation, the :attr:`root_physx_view`
attribute corresponds to the articulation root view and can be used to access the articulation
related data.
The articulation class also provides the functionality to augment the simulation of an articulated
system with custom actuator models. These models can either be explicit or implicit, as detailed in
the :mod:`omni.isaac.orbit.actuators` module. The actuator models are specified using the
:attr:`ArticulationCfg.actuators` attribute. These are then parsed and used to initialize the
corresponding actuator models, when the simulation is played.
During the simulation step, the articulation class first applies the actuator models to compute
the joint commands based on the user-specified targets. These joint commands are then applied
into the simulation. The joint commands can be either position, velocity, or effort commands.
As an example, the following snippet shows how this can be used for position commands:
.. code-block:: python
# an example instance of the articulation class
my_articulation = Articulation(cfg)
# set joint position targets
my_articulation.set_joint_position_target(position)
# propagate the actuator models and apply the computed commands into the simulation
my_articulation.write_data_to_sim()
# step the simulation using the simulation context
sim_context.step()
# update the articulation state, where dt is the simulation time step
my_articulation.update(dt)
.. _`USD ArticulationRootAPI`: https://openusd.org/dev/api/class_usd_physics_articulation_root_a_p_i.html
"""
cfg: ArticulationCfg
"""Configuration instance for the articulations."""
def __init__(self, cfg: ArticulationCfg):
"""Initialize the articulation.
Args:
cfg: A configuration instance.
"""
super().__init__(cfg)
# container for data access
self._data = ArticulationData()
# data for storing actuator group
self.actuators: dict[str, ActuatorBase] = dict.fromkeys(self.cfg.actuators.keys())
"""
Properties
"""
@property
def data(self) -> ArticulationData:
return self._data
@property
def is_fixed_base(self) -> bool:
"""Whether the articulation is a fixed-base or floating-base system."""
return self.root_physx_view.shared_metatype.fixed_base
@property
def num_joints(self) -> int:
"""Number of joints in articulation."""
return self.root_physx_view.shared_metatype.dof_count
@property
def num_fixed_tendons(self) -> int:
"""Number of fixed tendons in articulation."""
return self.root_physx_view.max_fixed_tendons
@property
def num_bodies(self) -> int:
"""Number of bodies in articulation."""
return self.root_physx_view.shared_metatype.link_count
@property
def joint_names(self) -> list[str]:
"""Ordered names of joints in articulation."""
return self.root_physx_view.shared_metatype.dof_names
@property
def body_names(self) -> list[str]:
"""Ordered names of bodies in articulation."""
return self.root_physx_view.shared_metatype.link_names
@property
def root_physx_view(self) -> physx.ArticulationView:
"""Articulation view for the asset (PhysX).
Note:
Use this view with caution. It requires handling of tensors in a specific way.
"""
return self._root_physx_view
@property
def body_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
.. deprecated:: v0.3.0
In previous versions, this attribute returned the rigid body view over all the links of the articulation.
However, this led to confusion with the link ordering as they were not ordered in the same way as the
articulation view.
Therefore, this attribute will be removed in v0.4.0. Please use the :attr:`root_physx_view` attribute
instead.
"""
dep_msg = "The attribute 'body_physx_view' will be removed in v0.4.0. Please use 'root_physx_view' instead."
warnings.warn(dep_msg, DeprecationWarning)
carb.log_error(dep_msg)
return self._body_physx_view
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None):
super().reset(env_ids)
# use ellipses object to skip initial indices.
if env_ids is None:
env_ids = slice(None)
# reset actuators
for actuator in self.actuators.values():
actuator.reset(env_ids)
def write_data_to_sim(self):
"""Write external wrenches and joint commands to the simulation.
If any explicit actuators are present, then the actuator models are used to compute the
joint commands. Otherwise, the joint commands are directly set into the simulation.
"""
# write external wrench
if self.has_external_wrench:
# apply external forces and torques
self._body_physx_view.apply_forces_and_torques_at_position(
force_data=self._external_force_body_view_b.view(-1, 3),
torque_data=self._external_torque_body_view_b.view(-1, 3),
position_data=None,
indices=self._ALL_BODY_INDICES,
is_global=False,
)
# apply actuator models
self._apply_actuator_model()
# write actions into simulation
self.root_physx_view.set_dof_actuation_forces(self._joint_effort_target_sim, self._ALL_INDICES)
# position and velocity targets only for implicit actuators
if self._has_implicit_actuators:
self.root_physx_view.set_dof_position_targets(self._joint_pos_target_sim, self._ALL_INDICES)
self.root_physx_view.set_dof_velocity_targets(self._joint_vel_target_sim, self._ALL_INDICES)
def update(self, dt: float):
# -- root state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.root_state_w[:, :7] = self.root_physx_view.get_root_transforms()
self._data.root_state_w[:, 3:7] = math_utils.convert_quat(self._data.root_state_w[:, 3:7], to="wxyz")
self._data.root_state_w[:, 7:] = self.root_physx_view.get_root_velocities()
# -- body-state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.body_state_w[..., :7] = self.root_physx_view.get_link_transforms()
self._data.body_state_w[..., 3:7] = math_utils.convert_quat(self._data.body_state_w[..., 3:7], to="wxyz")
self._data.body_state_w[..., 7:] = self.root_physx_view.get_link_velocities()
# -- joint states
self._data.joint_pos[:] = self.root_physx_view.get_dof_positions()
self._data.joint_vel[:] = self.root_physx_view.get_dof_velocities()
self._data.joint_acc[:] = (self._data.joint_vel - self._previous_joint_vel) / dt
# -- update common data
# note: these are computed in the base class
self._update_common_data(dt)
# -- update history buffers
self._previous_joint_vel[:] = self._data.joint_vel[:]
def find_joints(
self, name_keys: str | Sequence[str], joint_subset: list[str] | None = None, preserve_order: bool = False
) -> tuple[list[int], list[str]]:
"""Find joints in the articulation based on the name keys.
Please see the :func:`omni.isaac.orbit.utils.string.resolve_matching_names` function for more information
on the name matching.
Args:
name_keys: A regular expression or a list of regular expressions to match the joint names.
joint_subset: A subset of joints to search for. Defaults to None, which means all joints
in the articulation are searched.
preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False.
Returns:
A tuple of lists containing the joint indices and names.
"""
if joint_subset is None:
joint_subset = self.joint_names
# find joints
return string_utils.resolve_matching_names(name_keys, joint_subset, preserve_order)
"""
Operations - Setters.
"""
def set_external_force_and_torque(
self,
forces: torch.Tensor,
torques: torch.Tensor,
body_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
# call parent to set the external forces and torques into buffers
super().set_external_force_and_torque(forces, torques, body_ids, env_ids)
# reordering of the external forces and torques to match the body view ordering
if self.has_external_wrench:
self._external_force_body_view_b = self._external_force_b[:, self._body_view_ordering]
self._external_torque_body_view_b = self._external_torque_b[:, self._body_view_ordering]
"""
Operations - Writers.
"""
def write_root_pose_to_sim(self, root_pose: torch.Tensor, env_ids: Sequence[int] | None = None):
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, :7] = root_pose.clone()
# convert root quaternion from wxyz to xyzw
root_poses_xyzw = self._data.root_state_w[:, :7].clone()
root_poses_xyzw[:, 3:] = math_utils.convert_quat(root_poses_xyzw[:, 3:], to="xyzw")
# set into simulation
self.root_physx_view.set_root_transforms(root_poses_xyzw, indices=physx_env_ids)
def write_root_velocity_to_sim(self, root_velocity: torch.Tensor, env_ids: Sequence[int] | None = None):
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, 7:] = root_velocity.clone()
# set into simulation
self.root_physx_view.set_root_velocities(self._data.root_state_w[:, 7:], indices=physx_env_ids)
def write_joint_state_to_sim(
self,
position: torch.Tensor,
velocity: torch.Tensor,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | slice | None = None,
):
"""Write joint positions and velocities to the simulation.
Args:
position: Joint positions. Shape is (len(env_ids), len(joint_ids)).
velocity: Joint velocities. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_pos[env_ids, joint_ids] = position
self._data.joint_vel[env_ids, joint_ids] = velocity
self._previous_joint_vel[env_ids, joint_ids] = velocity
self._data.joint_acc[env_ids, joint_ids] = 0.0
# set into simulation
self.root_physx_view.set_dof_positions(self._data.joint_pos, indices=physx_env_ids)
self.root_physx_view.set_dof_velocities(self._data.joint_vel, indices=physx_env_ids)
def write_joint_stiffness_to_sim(
self,
stiffness: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint stiffness into the simulation.
Args:
stiffness: Joint stiffness. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the stiffness for. Defaults to None (all joints).
env_ids: The environment indices to set the stiffness for. Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_stiffness[env_ids, joint_ids] = stiffness
# set into simulation
self.root_physx_view.set_dof_stiffnesses(self._data.joint_stiffness.cpu(), indices=physx_env_ids.cpu())
def write_joint_damping_to_sim(
self,
damping: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint damping into the simulation.
Args:
damping: Joint damping. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the damping for.
Defaults to None (all joints).
env_ids: The environment indices to set the damping for.
Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_damping[env_ids, joint_ids] = damping
# set into simulation
self.root_physx_view.set_dof_dampings(self._data.joint_damping.cpu(), indices=physx_env_ids.cpu())
def write_joint_effort_limit_to_sim(
self,
limits: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint effort limits into the simulation.
Args:
limits: Joint torque limits. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# move tensor to cpu if needed
if isinstance(limits, torch.Tensor):
limits = limits.cpu()
# set into internal buffers
torque_limit_all = self.root_physx_view.get_dof_max_forces()
torque_limit_all[env_ids, joint_ids] = limits
# set into simulation
self.root_physx_view.set_dof_max_forces(torque_limit_all.cpu(), indices=physx_env_ids.cpu())
def write_joint_armature_to_sim(
self,
armature: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint armature into the simulation.
Args:
armature: Joint armature. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_armature[env_ids, joint_ids] = armature
# set into simulation
self.root_physx_view.set_dof_armatures(self._data.joint_armature.cpu(), indices=physx_env_ids.cpu())
def write_joint_friction_to_sim(
self,
joint_friction: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint friction into the simulation.
Args:
joint_friction: Joint friction. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
# set into internal buffers
self._data.joint_friction[env_ids, joint_ids] = joint_friction
# set into simulation
self.root_physx_view.set_dof_friction_coefficients(self._data.joint_friction.cpu(), indices=physx_env_ids.cpu())
"""
Operations - State.
"""
def set_joint_position_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint position targets into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint position targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
# set targets
self._data.joint_pos_target[env_ids, joint_ids] = target
def set_joint_velocity_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint velocity targets into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint velocity targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
# set targets
self._data.joint_vel_target[env_ids, joint_ids] = target
def set_joint_effort_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint efforts into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint effort targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
# set targets
self._data.joint_effort_target[env_ids, joint_ids] = target
"""
Internal helper.
"""
def _initialize_impl(self):
# create simulation view
self._physics_sim_view = physx.create_simulation_view(self._backend)
self._physics_sim_view.set_subspace_roots("/")
# obtain the first prim in the regex expression (all others are assumed to be a copy of this)
template_prim = sim_utils.find_first_matching_prim(self.cfg.prim_path)
if template_prim is None:
raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.")
template_prim_path = template_prim.GetPath().pathString
# find articulation root prims
root_prims = sim_utils.get_all_matching_child_prims(
template_prim_path, predicate=lambda prim: prim.HasAPI(UsdPhysics.ArticulationRootAPI)
)
if len(root_prims) != 1:
raise RuntimeError(
f"Failed to find a single articulation root when resolving '{self.cfg.prim_path}'."
f" Found roots '{root_prims}' under '{template_prim_path}'."
)
# resolve articulation root prim back into regex expression
root_prim_path = root_prims[0].GetPath().pathString
root_prim_path_expr = self.cfg.prim_path + root_prim_path[len(template_prim_path) :]
# -- articulation
self._root_physx_view = self._physics_sim_view.create_articulation_view(root_prim_path_expr.replace(".*", "*"))
# -- link views
# note: we use the root view to get the body names, but we use the body view to get the
# actual data. This is mainly needed to apply external forces to the bodies.
physx_body_names = self.root_physx_view.shared_metatype.link_names
body_names_regex = r"(" + "|".join(physx_body_names) + r")"
body_names_regex = f"{self.cfg.prim_path}/{body_names_regex}"
self._body_physx_view = self._physics_sim_view.create_rigid_body_view(body_names_regex.replace(".*", "*"))
# create ordering from articulation view to body view for body names
# note: we need to do this since the body view is not ordered in the same way as the articulation view
# -- root view
root_view_body_names = self.body_names
# -- body view
prim_paths = self._body_physx_view.prim_paths[: self.num_bodies]
body_view_body_names = [path.split("/")[-1] for path in prim_paths]
# -- mapping from articulation view to body view
self._body_view_ordering = [body_view_body_names.index(name) for name in root_view_body_names]
self._body_view_ordering = torch.tensor(self._body_view_ordering, dtype=torch.long, device=self.device)
# log information about the articulation
carb.log_info(f"Articulation initialized at: {self.cfg.prim_path} with root '{root_prim_path_expr}'.")
carb.log_info(f"Is fixed root: {self.is_fixed_base}")
carb.log_info(f"Number of bodies: {self.num_bodies}")
carb.log_info(f"Body names: {self.body_names}")
carb.log_info(f"Number of joints: {self.num_joints}")
carb.log_info(f"Joint names: {self.joint_names}")
carb.log_info(f"Number of fixed tendons: {self.num_fixed_tendons}")
# -- assert that parsing was successful
if set(physx_body_names) != set(self.body_names):
raise RuntimeError("Failed to parse all bodies properly in the articulation.")
# create buffers
self._create_buffers()
# process configuration
self._process_cfg()
self._process_actuators_cfg()
# validate configuration
self._validate_cfg()
# log joint information
self._log_articulation_joint_info()
def _create_buffers(self):
# allocate buffers
super()._create_buffers()
# history buffers
self._previous_joint_vel = torch.zeros(self.num_instances, self.num_joints, device=self.device)
# asset data
# -- properties
self._data.joint_names = self.joint_names
# -- joint states
self._data.joint_pos = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.joint_vel = torch.zeros_like(self._data.joint_pos)
self._data.joint_acc = torch.zeros_like(self._data.joint_pos)
self._data.default_joint_pos = torch.zeros_like(self._data.joint_pos)
self._data.default_joint_vel = torch.zeros_like(self._data.joint_pos)
# -- joint commands
self._data.joint_pos_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_vel_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_effort_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_stiffness = torch.zeros_like(self._data.joint_pos)
self._data.joint_damping = torch.zeros_like(self._data.joint_pos)
self._data.joint_armature = torch.zeros_like(self._data.joint_pos)
self._data.joint_friction = torch.zeros_like(self._data.joint_pos)
# -- joint commands (explicit)
self._data.computed_torque = torch.zeros_like(self._data.joint_pos)
self._data.applied_torque = torch.zeros_like(self._data.joint_pos)
# -- other data
self._data.soft_joint_pos_limits = torch.zeros(self.num_instances, self.num_joints, 2, device=self.device)
self._data.soft_joint_vel_limits = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.gear_ratio = torch.ones(self.num_instances, self.num_joints, device=self.device)
# soft joint position limits (recommended not to be too close to limits).
joint_pos_limits = self.root_physx_view.get_dof_limits()
joint_pos_mean = (joint_pos_limits[..., 0] + joint_pos_limits[..., 1]) / 2
joint_pos_range = joint_pos_limits[..., 1] - joint_pos_limits[..., 0]
soft_limit_factor = self.cfg.soft_joint_pos_limit_factor
# add to data
self._data.soft_joint_pos_limits[..., 0] = joint_pos_mean - 0.5 * joint_pos_range * soft_limit_factor
self._data.soft_joint_pos_limits[..., 1] = joint_pos_mean + 0.5 * joint_pos_range * soft_limit_factor
# create buffers to store processed actions from actuator models
self._joint_pos_target_sim = torch.zeros_like(self._data.joint_pos_target)
self._joint_vel_target_sim = torch.zeros_like(self._data.joint_pos_target)
self._joint_effort_target_sim = torch.zeros_like(self._data.joint_pos_target)
def _process_cfg(self):
"""Post processing of configuration parameters."""
# default state
super()._process_cfg()
# -- joint state
# joint pos
indices_list, _, values_list = string_utils.resolve_matching_names_values(
self.cfg.init_state.joint_pos, self.joint_names
)
self._data.default_joint_pos[:, indices_list] = torch.tensor(values_list, device=self.device)
# joint vel
indices_list, _, values_list = string_utils.resolve_matching_names_values(
self.cfg.init_state.joint_vel, self.joint_names
)
self._data.default_joint_vel[:, indices_list] = torch.tensor(values_list, device=self.device)
"""
Internal helpers -- Actuators.
"""
def _process_actuators_cfg(self):
"""Process and apply articulation joint properties."""
# flag for implicit actuators
# if this is false, we by-pass certain checks when doing actuator-related operations
self._has_implicit_actuators = False
# cache the values coming from the usd
usd_stiffness = self.root_physx_view.get_dof_stiffnesses().clone()
usd_damping = self.root_physx_view.get_dof_dampings().clone()
usd_armature = self.root_physx_view.get_dof_armatures().clone()
usd_friction = self.root_physx_view.get_dof_friction_coefficients().clone()
usd_effort_limit = self.root_physx_view.get_dof_max_forces().clone()
usd_velocity_limit = self.root_physx_view.get_dof_max_velocities().clone()
# iterate over all actuator configurations
for actuator_name, actuator_cfg in self.cfg.actuators.items():
# type annotation for type checkers
actuator_cfg: ActuatorBaseCfg
# create actuator group
joint_ids, joint_names = self.find_joints(actuator_cfg.joint_names_expr)
# check if any joints are found
if len(joint_names) == 0:
raise ValueError(
f"No joints found for actuator group: {actuator_name} with joint name expression:"
f" {actuator_cfg.joint_names_expr}."
)
# create actuator collection
# note: for efficiency avoid indexing when over all indices
actuator: ActuatorBase = actuator_cfg.class_type(
cfg=actuator_cfg,
joint_names=joint_names,
joint_ids=slice(None) if len(joint_names) == self.num_joints else joint_ids,
num_envs=self.num_instances,
device=self.device,
stiffness=usd_stiffness[:, joint_ids],
damping=usd_damping[:, joint_ids],
armature=usd_armature[:, joint_ids],
friction=usd_friction[:, joint_ids],
effort_limit=usd_effort_limit[:, joint_ids],
velocity_limit=usd_velocity_limit[:, joint_ids],
)
# log information on actuator groups
carb.log_info(
f"Actuator collection: {actuator_name} with model '{actuator_cfg.class_type.__name__}' and"
f" joint names: {joint_names} [{joint_ids}]."
)
# store actuator group
self.actuators[actuator_name] = actuator
# set the passed gains and limits into the simulation
if isinstance(actuator, ImplicitActuator):
self._has_implicit_actuators = True
# the gains and limits are set into the simulation since actuator model is implicit
self.write_joint_stiffness_to_sim(actuator.stiffness, joint_ids=actuator.joint_indices)
self.write_joint_damping_to_sim(actuator.damping, joint_ids=actuator.joint_indices)
self.write_joint_effort_limit_to_sim(actuator.effort_limit, joint_ids=actuator.joint_indices)
self.write_joint_armature_to_sim(actuator.armature, joint_ids=actuator.joint_indices)
self.write_joint_friction_to_sim(actuator.friction, joint_ids=actuator.joint_indices)
else:
# the gains and limits are processed by the actuator model
# we set gains to zero, and torque limit to a high value in simulation to avoid any interference
self.write_joint_stiffness_to_sim(0.0, joint_ids=actuator.joint_indices)
self.write_joint_damping_to_sim(0.0, joint_ids=actuator.joint_indices)
self.write_joint_effort_limit_to_sim(1.0e9, joint_ids=actuator.joint_indices)
self.write_joint_armature_to_sim(actuator.armature, joint_ids=actuator.joint_indices)
self.write_joint_friction_to_sim(actuator.friction, joint_ids=actuator.joint_indices)
# perform some sanity checks to ensure actuators are prepared correctly
total_act_joints = sum(actuator.num_joints for actuator in self.actuators.values())
if total_act_joints != (self.num_joints - self.num_fixed_tendons):
carb.log_warn(
"Not all actuators are configured! Total number of actuated joints not equal to number of"
f" joints available: {total_act_joints} != {self.num_joints}."
)
def _apply_actuator_model(self):
"""Processes joint commands for the articulation by forwarding them to the actuators.
The actions are first processed using actuator models. Depending on the robot configuration,
the actuator models compute the joint level simulation commands and sets them into the PhysX buffers.
"""
# process actions per group
for actuator in self.actuators.values():
# prepare input for actuator model based on cached data
# TODO : A tensor dict would be nice to do the indexing of all tensors together
control_action = ArticulationActions(
joint_positions=self._data.joint_pos_target[:, actuator.joint_indices],
joint_velocities=self._data.joint_vel_target[:, actuator.joint_indices],
joint_efforts=self._data.joint_effort_target[:, actuator.joint_indices],
joint_indices=actuator.joint_indices,
)
# compute joint command from the actuator model
control_action = actuator.compute(
control_action,
joint_pos=self._data.joint_pos[:, actuator.joint_indices],
joint_vel=self._data.joint_vel[:, actuator.joint_indices],
)
# update targets (these are set into the simulation)
if control_action.joint_positions is not None:
self._joint_pos_target_sim[:, actuator.joint_indices] = control_action.joint_positions
if control_action.joint_velocities is not None:
self._joint_vel_target_sim[:, actuator.joint_indices] = control_action.joint_velocities
if control_action.joint_efforts is not None:
self._joint_effort_target_sim[:, actuator.joint_indices] = control_action.joint_efforts
# update state of the actuator model
# -- torques
self._data.computed_torque[:, actuator.joint_indices] = actuator.computed_effort
self._data.applied_torque[:, actuator.joint_indices] = actuator.applied_effort
# -- actuator data
self._data.soft_joint_vel_limits[:, actuator.joint_indices] = actuator.velocity_limit
# TODO: find a cleaner way to handle gear ratio. Only needed for variable gear ratio actuators.
if hasattr(actuator, "gear_ratio"):
self._data.gear_ratio[:, actuator.joint_indices] = actuator.gear_ratio
"""
Internal helpers -- Debugging.
"""
def _validate_cfg(self):
"""Validate the configuration after processing.
Note:
This function should be called only after the configuration has been processed and the buffers have been
created. Otherwise, some settings that are altered during processing may not be validated.
For instance, the actuator models may change the joint max velocity limits.
"""
# check that the default values are within the limits
joint_pos_limits = self.root_physx_view.get_dof_limits()[0].to(self.device)
out_of_range = self._data.default_joint_pos[0] < joint_pos_limits[:, 0]
out_of_range |= self._data.default_joint_pos[0] > joint_pos_limits[:, 1]
violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1)
# throw error if any of the default joint positions are out of the limits
if len(violated_indices) > 0:
# prepare message for violated joints
msg = "The following joints have default positions out of the limits: \n"
for idx in violated_indices:
joint_name = self.data.joint_names[idx]
joint_limits = joint_pos_limits[idx]
joint_pos = self.data.default_joint_pos[0, idx]
# add to message
msg += f"\t- '{joint_name}': {joint_pos:.3f} not in [{joint_limits[0]:.3f}, {joint_limits[1]:.3f}]\n"
raise ValueError(msg)
# check that the default joint velocities are within the limits
joint_max_vel = self.root_physx_view.get_dof_max_velocities()[0].to(self.device)
out_of_range = torch.abs(self._data.default_joint_vel[0]) > joint_max_vel
violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1)
if len(violated_indices) > 0:
# prepare message for violated joints
msg = "The following joints have default velocities out of the limits: \n"
for idx in violated_indices:
joint_name = self.data.joint_names[idx]
joint_limits = [-joint_max_vel[idx], joint_max_vel[idx]]
joint_vel = self.data.default_joint_vel[0, idx]
# add to message
msg += f"\t- '{joint_name}': {joint_vel:.3f} not in [{joint_limits[0]:.3f}, {joint_limits[1]:.3f}]\n"
raise ValueError(msg)
def _log_articulation_joint_info(self):
"""Log information about the articulation's simulated joints."""
# read out all joint parameters from simulation
# -- gains
stiffnesses = self.root_physx_view.get_dof_stiffnesses()[0].tolist()
dampings = self.root_physx_view.get_dof_dampings()[0].tolist()
# -- properties
armatures = self.root_physx_view.get_dof_armatures()[0].tolist()
frictions = self.root_physx_view.get_dof_friction_coefficients()[0].tolist()
# -- limits
position_limits = self.root_physx_view.get_dof_limits()[0].tolist()
velocity_limits = self.root_physx_view.get_dof_max_velocities()[0].tolist()
effort_limits = self.root_physx_view.get_dof_max_forces()[0].tolist()
# create table for term information
table = PrettyTable(float_format=".3f")
table.title = f"Simulation Joint Information (Prim path: {self.cfg.prim_path})"
table.field_names = [
"Index",
"Name",
"Stiffness",
"Damping",
"Armature",
"Friction",
"Position Limits",
"Velocity Limits",
"Effort Limits",
]
# set alignment of table columns
table.align["Name"] = "l"
# add info on each term
for index, name in enumerate(self.joint_names):
table.add_row([
index,
name,
stiffnesses[index],
dampings[index],
armatures[index],
frictions[index],
position_limits[index],
velocity_limits[index],
effort_limits[index],
])
# convert table to string
carb.log_info(f"Simulation parameters for joints in {self.cfg.prim_path}:\n" + table.get_string())
# read out all tendon parameters from simulation
if self.num_fixed_tendons > 0:
# -- gains
ft_stiffnesses = self.root_physx_view.get_fixed_tendon_stiffnesses()[0].tolist()
ft_dampings = self.root_physx_view.get_fixed_tendon_dampings()[0].tolist()
# -- limits
ft_limit_stiffnesses = self.root_physx_view.get_fixed_tendon_limit_stiffnesses()[0].tolist()
ft_limits = self.root_physx_view.get_fixed_tendon_limits()[0].tolist()
ft_rest_lengths = self.root_physx_view.get_fixed_tendon_rest_lengths()[0].tolist()
ft_offsets = self.root_physx_view.get_fixed_tendon_offsets()[0].tolist()
# create table for term information
tendon_table = PrettyTable(float_format=".3f")
tendon_table.title = f"Simulation Tendon Information (Prim path: {self.cfg.prim_path})"
tendon_table.field_names = [
"Index",
"Stiffness",
"Damping",
"Limit Stiffness",
"Limit",
"Rest Length",
"Offset",
]
# add info on each term
for index in range(self.num_fixed_tendons):
tendon_table.add_row([
index,
ft_stiffnesses[index],
ft_dampings[index],
ft_limit_stiffnesses[index],
ft_limits[index],
ft_rest_lengths[index],
ft_offsets[index],
])
# convert table to string
carb.log_info(f"Simulation parameters for tendons in {self.cfg.prim_path}:\n" + tendon_table.get_string())
| 43,405 | Python | 47.015487 | 120 | 0.627808 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/assets/articulation/articulation_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from dataclasses import MISSING
from omni.isaac.orbit.actuators import ActuatorBaseCfg
from omni.isaac.orbit.utils import configclass
from ..rigid_object import RigidObjectCfg
from .articulation import Articulation
@configclass
class ArticulationCfg(RigidObjectCfg):
"""Configuration parameters for an articulation."""
class_type: type = Articulation
@configclass
class InitialStateCfg(RigidObjectCfg.InitialStateCfg):
"""Initial state of the articulation."""
# root position
joint_pos: dict[str, float] = {".*": 0.0}
"""Joint positions of the joints. Defaults to 0.0 for all joints."""
joint_vel: dict[str, float] = {".*": 0.0}
"""Joint velocities of the joints. Defaults to 0.0 for all joints."""
##
# Initialize configurations.
##
init_state: InitialStateCfg = InitialStateCfg()
"""Initial state of the articulated object. Defaults to identity pose with zero velocity and zero joint state."""
soft_joint_pos_limit_factor: float = 1.0
"""Fraction specifying the range of DOF position limits (parsed from the asset) to use.
Defaults to 1.0."""
actuators: dict[str, ActuatorBaseCfg] = MISSING
"""Actuators for the robot with corresponding joint names."""
| 1,427 | Python | 31.454545 | 117 | 0.703574 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/markers/visualization_markers.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""A class to coordinate groups of visual markers (such as spheres, frames or arrows)
using `UsdGeom.PointInstancer`_ class.
The class :class:`VisualizationMarkers` is used to create a group of visual markers and
visualize them in the viewport. The markers are represented as :class:`UsdGeom.PointInstancer` prims
in the USD stage. The markers are created as prototypes in the :class:`UsdGeom.PointInstancer` prim
and are instanced in the :class:`UsdGeom.PointInstancer` prim. The markers can be visualized by
passing the indices of the marker prototypes and their translations, orientations and scales.
The marker prototypes can be configured with the :class:`VisualizationMarkersCfg` class.
.. _UsdGeom.PointInstancer: https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html
"""
from __future__ import annotations
import numpy as np
import torch
from dataclasses import MISSING
import omni.isaac.core.utils.stage as stage_utils
import omni.kit.commands
import omni.physx.scripts.utils as physx_utils
from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics, Vt
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.sim.spawners import SpawnerCfg
from omni.isaac.orbit.utils.configclass import configclass
from omni.isaac.orbit.utils.math import convert_quat
@configclass
class VisualizationMarkersCfg:
"""A class to configure a :class:`VisualizationMarkers`."""
prim_path: str = MISSING
"""The prim path where the :class:`UsdGeom.PointInstancer` will be created."""
markers: dict[str, SpawnerCfg] = MISSING
"""The dictionary of marker configurations.
The key is the name of the marker, and the value is the configuration of the marker.
The key is used to identify the marker in the class.
"""
class VisualizationMarkers:
"""A class to coordinate groups of visual markers (loaded from USD).
This class allows visualization of different UI markers in the scene, such as points and frames.
The class wraps around the `UsdGeom.PointInstancer`_ for efficient handling of objects
in the stage via instancing the created marker prototype prims.
A marker prototype prim is a reusable template prim used for defining variations of objects
in the scene. For example, a sphere prim can be used as a marker prototype prim to create
multiple sphere prims in the scene at different locations. Thus, prototype prims are useful
for creating multiple instances of the same prim in the scene.
The class parses the configuration to create different the marker prototypes into the stage. Each marker
prototype prim is created as a child of the :class:`UsdGeom.PointInstancer` prim. The prim path for the
the marker prim is resolved using the key of the marker in the :attr:`VisualizationMarkersCfg.markers`
dictionary. The marker prototypes are created using the :meth:`omni.isaac.core.utils.create_prim`
function, and then then instanced using :class:`UsdGeom.PointInstancer` prim to allow creating multiple
instances of the marker prims.
Switching between different marker prototypes is possible by calling the :meth:`visualize` method with
the prototype indices corresponding to the marker prototype. The prototype indices are based on the order
in the :attr:`VisualizationMarkersCfg.markers` dictionary. For example, if the dictionary has two markers,
"marker1" and "marker2", then their prototype indices are 0 and 1 respectively. The prototype indices
can be passed as a list or array of integers.
Usage:
The following snippet shows how to create 24 sphere markers with a radius of 1.0 at random translations
within the range [-1.0, 1.0]. The first 12 markers will be colored red and the rest will be colored green.
.. code-block:: python
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.markers import VisualizationMarkersCfg, VisualizationMarkers
# Create the markers configuration
# This creates two marker prototypes, "marker1" and "marker2" which are spheres with a radius of 1.0.
# The color of "marker1" is red and the color of "marker2" is green.
cfg = VisualizationMarkersCfg(
prim_path="/World/Visuals/testMarkers",
markers={
"marker1": sim_utils.SphereCfg(
radius=1.0,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"marker2": VisualizationMarkersCfg.SphereCfg(
radius=1.0,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
),
}
)
# Create the markers instance
# This will create a UsdGeom.PointInstancer prim at the given path along with the marker prototypes.
marker = VisualizationMarkers(cfg)
# Set position of the marker
# -- randomly sample translations between -1.0 and 1.0
marker_translations = np.random.uniform(-1.0, 1.0, (24, 3))
# -- this will create 24 markers at the given translations
# note: the markers will all be `marker1` since the marker indices are not given
marker.visualize(translations=marker_translations)
# alter the markers based on their prototypes indices
# first 12 markers will be marker1 and the rest will be marker2
# 0 -> marker1, 1 -> marker2
marker_indices = [0] * 12 + [1] * 12
# this will change the marker prototypes at the given indices
# note: the translations of the markers will not be changed from the previous call
# since the translations are not given.
marker.visualize(marker_indices=marker_indices)
# alter the markers based on their prototypes indices and translations
marker.visualize(marker_indices=marker_indices, translations=marker_translations)
.. _UsdGeom.PointInstancer: https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html
"""
def __init__(self, cfg: VisualizationMarkersCfg):
"""Initialize the class.
When the class is initialized, the :class:`UsdGeom.PointInstancer` is created into the stage
and the marker prims are registered into it.
.. note::
If a prim already exists at the given path, the function will find the next free path
and create the :class:`UsdGeom.PointInstancer` prim there.
Args:
cfg: The configuration for the markers.
Raises:
ValueError: When no markers are provided in the :obj:`cfg`.
"""
# get next free path for the prim
prim_path = stage_utils.get_next_free_path(cfg.prim_path)
# create a new prim
stage = stage_utils.get_current_stage()
self._instancer_manager = UsdGeom.PointInstancer.Define(stage, prim_path)
# store inputs
self.prim_path = prim_path
self.cfg = cfg
# check if any markers is provided
if len(self.cfg.markers) == 0:
raise ValueError(f"The `cfg.markers` cannot be empty. Received: {self.cfg.markers}")
# create a child prim for the marker
self._add_markers_prototypes(self.cfg.markers)
# Note: We need to do this the first time to initialize the instancer.
# Otherwise, the instancer will not be "created" and the function `GetInstanceIndices()` will fail.
self._instancer_manager.GetProtoIndicesAttr().Set(list(range(self.num_prototypes)))
self._instancer_manager.GetPositionsAttr().Set([Gf.Vec3f(0.0)] * self.num_prototypes)
self._count = self.num_prototypes
def __str__(self) -> str:
"""Return: A string representation of the class."""
msg = f"VisualizationMarkers(prim_path={self.prim_path})"
msg += f"\n\tCount: {self.count}"
msg += f"\n\tNumber of prototypes: {self.num_prototypes}"
msg += "\n\tMarkers Prototypes:"
for index, (name, marker) in enumerate(self.cfg.markers.items()):
msg += f"\n\t\t[Index: {index}]: {name}: {marker.to_dict()}"
return msg
"""
Properties.
"""
@property
def num_prototypes(self) -> int:
"""The number of marker prototypes available."""
return len(self.cfg.markers)
@property
def count(self) -> int:
"""The total number of marker instances."""
# TODO: Update this when the USD API is available (Isaac Sim 2023.1)
# return self._instancer_manager.GetInstanceCount()
return self._count
"""
Operations.
"""
def set_visibility(self, visible: bool):
"""Sets the visibility of the markers.
The method does this through the USD API.
Args:
visible: flag to set the visibility.
"""
imageable = UsdGeom.Imageable(self._instancer_manager)
if visible:
imageable.MakeVisible()
else:
imageable.MakeInvisible()
def is_visible(self) -> bool:
"""Checks the visibility of the markers.
Returns:
True if the markers are visible, False otherwise.
"""
return self._instancer_manager.GetVisibilityAttr().Get() != UsdGeom.Tokens.invisible
def visualize(
self,
translations: np.ndarray | torch.Tensor | None = None,
orientations: np.ndarray | torch.Tensor | None = None,
scales: np.ndarray | torch.Tensor | None = None,
marker_indices: list[int] | np.ndarray | torch.Tensor | None = None,
):
"""Update markers in the viewport.
.. note::
If the prim `PointInstancer` is hidden in the stage, the function will simply return
without updating the markers. This helps in unnecessary computation when the markers
are not visible.
Whenever updating the markers, the input arrays must have the same number of elements
in the first dimension. If the number of elements is different, the `UsdGeom.PointInstancer`
will raise an error complaining about the mismatch.
Additionally, the function supports dynamic update of the markers. This means that the
number of markers can change between calls. For example, if you have 24 points that you
want to visualize, you can pass 24 translations, orientations, and scales. If you want to
visualize only 12 points, you can pass 12 translations, orientations, and scales. The
function will automatically update the number of markers in the scene.
The function will also update the marker prototypes based on their prototype indices. For instance,
if you have two marker prototypes, and you pass the following marker indices: [0, 1, 0, 1], the function
will update the first and third markers with the first prototype, and the second and fourth markers
with the second prototype. This is useful when you want to visualize different markers in the same
scene. The list of marker indices must have the same number of elements as the translations, orientations,
or scales. If the number of elements is different, the function will raise an error.
.. caution::
This function will update all the markers instanced from the prototypes. That means
if you have 24 markers, you will need to pass 24 translations, orientations, and scales.
If you want to update only a subset of the markers, you will need to handle the indices
yourself and pass the complete arrays to this function.
Args:
translations: Translations w.r.t. parent prim frame. Shape is (M, 3).
Defaults to None, which means left unchanged.
orientations: Quaternion orientations (w, x, y, z) w.r.t. parent prim frame. Shape is (M, 4).
Defaults to None, which means left unchanged.
scales: Scale applied before any rotation is applied. Shape is (M, 3).
Defaults to None, which means left unchanged.
marker_indices: Decides which marker prototype to visualize. Shape is (M).
Defaults to None, which means left unchanged provided that the total number of markers
is the same as the previous call. If the number of markers is different, the function
will update the number of markers in the scene.
Raises:
ValueError: When input arrays do not follow the expected shapes.
ValueError: When the function is called with all None arguments.
"""
# check if it is visible (if not then let's not waste time)
if not self.is_visible():
return
# check if we have any markers to visualize
num_markers = 0
# resolve inputs
# -- position
if translations is not None:
if isinstance(translations, torch.Tensor):
translations = translations.detach().cpu().numpy()
# check that shape is correct
if translations.shape[1] != 3 or len(translations.shape) != 2:
raise ValueError(f"Expected `translations` to have shape (M, 3). Received: {translations.shape}.")
# apply translations
self._instancer_manager.GetPositionsAttr().Set(Vt.Vec3fArray.FromNumpy(translations))
# update number of markers
num_markers = translations.shape[0]
# -- orientation
if orientations is not None:
if isinstance(orientations, torch.Tensor):
orientations = orientations.detach().cpu().numpy()
# check that shape is correct
if orientations.shape[1] != 4 or len(orientations.shape) != 2:
raise ValueError(f"Expected `orientations` to have shape (M, 4). Received: {orientations.shape}.")
# roll orientations from (w, x, y, z) to (x, y, z, w)
# internally USD expects (x, y, z, w)
orientations = convert_quat(orientations, to="xyzw")
# apply orientations
self._instancer_manager.GetOrientationsAttr().Set(Vt.QuathArray.FromNumpy(orientations))
# update number of markers
num_markers = orientations.shape[0]
# -- scales
if scales is not None:
if isinstance(scales, torch.Tensor):
scales = scales.detach().cpu().numpy()
# check that shape is correct
if scales.shape[1] != 3 or len(scales.shape) != 2:
raise ValueError(f"Expected `scales` to have shape (M, 3). Received: {scales.shape}.")
# apply scales
self._instancer_manager.GetScalesAttr().Set(Vt.Vec3fArray.FromNumpy(scales))
# update number of markers
num_markers = scales.shape[0]
# -- status
if marker_indices is not None or num_markers != self._count:
# apply marker indices
if marker_indices is not None:
if isinstance(marker_indices, torch.Tensor):
marker_indices = marker_indices.detach().cpu().numpy()
elif isinstance(marker_indices, list):
marker_indices = np.array(marker_indices)
# check that shape is correct
if len(marker_indices.shape) != 1:
raise ValueError(f"Expected `marker_indices` to have shape (M,). Received: {marker_indices.shape}.")
# apply proto indices
self._instancer_manager.GetProtoIndicesAttr().Set(Vt.IntArray.FromNumpy(marker_indices))
# update number of markers
num_markers = marker_indices.shape[0]
else:
# check that number of markers is not zero
if num_markers == 0:
raise ValueError("Number of markers cannot be zero! Hint: The function was called with no inputs?")
# set all markers to be the first prototype
self._instancer_manager.GetProtoIndicesAttr().Set([0] * num_markers)
# set number of markers
self._count = num_markers
"""
Helper functions.
"""
def _add_markers_prototypes(self, markers_cfg: dict[str, sim_utils.SpawnerCfg]):
"""Adds markers prototypes to the scene and sets the markers instancer to use them."""
# add markers based on config
for name, cfg in markers_cfg.items():
# resolve prim path
marker_prim_path = f"{self.prim_path}/{name}"
# create a child prim for the marker
prim = cfg.func(prim_path=marker_prim_path, cfg=cfg)
# make the asset uninstanceable (in case it is)
# point instancer defines its own prototypes so if an asset is already instanced, this doesn't work.
self._process_prototype_prim(prim)
# remove any physics on the markers because they are only for visualization!
physx_utils.removeRigidBodySubtree(prim)
# add child reference to point instancer
self._instancer_manager.GetPrototypesRel().AddTarget(marker_prim_path)
# check that we loaded all the prototypes
prototypes = self._instancer_manager.GetPrototypesRel().GetTargets()
if len(prototypes) != len(markers_cfg):
raise RuntimeError(
f"Failed to load all the prototypes. Expected: {len(markers_cfg)}. Received: {len(prototypes)}."
)
def _process_prototype_prim(self, prim: Usd.Prim):
"""Process a prim and its descendants to make them suitable for defining prototypes.
Point instancer defines its own prototypes so if an asset is already instanced, this doesn't work.
This function checks if the prim at the specified prim path and its descendants are instanced.
If so, it makes the respective prim uninstanceable by disabling instancing on the prim.
Additionally, it makes the prim invisible to secondary rays. This is useful when we do not want
to see the marker prims on camera images.
Args:
prim_path: The prim path to check.
stage: The stage where the prim exists.
Defaults to None, in which case the current stage is used.
"""
# check if prim is valid
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim.GetPrimAtPath()}' is not valid.")
# iterate over all prims under prim-path
all_prims = [prim]
while len(all_prims) > 0:
# get current prim
child_prim = all_prims.pop(0)
# check if it is physics body -> if so, remove it
if child_prim.HasAPI(UsdPhysics.ArticulationRootAPI):
child_prim.RemoveAPI(UsdPhysics.ArticulationRootAPI)
child_prim.RemoveAPI(PhysxSchema.PhysxArticulationAPI)
if child_prim.HasAPI(UsdPhysics.RigidBodyAPI):
child_prim.RemoveAPI(UsdPhysics.RigidBodyAPI)
child_prim.RemoveAPI(PhysxSchema.PhysxRigidBodyAPI)
if child_prim.IsA(UsdPhysics.Joint):
child_prim.GetAttribute("physics:jointEnabled").Set(False)
# check if prim is instanced -> if so, make it uninstanceable
if child_prim.IsInstance():
child_prim.SetInstanceable(False)
# check if prim is a mesh -> if so, make it invisible to secondary rays
if child_prim.IsA(UsdGeom.Gprim):
# invisible to secondary rays such as depth images
omni.kit.commands.execute(
"ChangePropertyCommand",
prop_path=Sdf.Path(f"{child_prim.GetPrimPath().pathString}.primvars:invisibleToSecondaryRays"),
value=True,
prev=None,
type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool,
)
# add children to list
all_prims += child_prim.GetChildren()
| 20,362 | Python | 48.787286 | 120 | 0.646646 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/markers/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package for marker utilities to simplify creation of UI elements in the GUI.
Currently, the sub-package provides the following classes:
* :class:`VisualizationMarkers` for creating a group of markers using `UsdGeom.PointInstancer
<https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html>`_.
.. note::
For some simple use-cases, it may be sufficient to use the debug drawing utilities from Isaac Sim.
The debug drawing API is available in the `omni.isaac.debug_drawing`_ module. It allows drawing of
points and splines efficiently on the UI.
.. _omni.isaac.debug_drawing: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_debug_drawing.html
"""
from __future__ import annotations
from .config import * # noqa: F401, F403
from .visualization_markers import VisualizationMarkers, VisualizationMarkersCfg
| 1,003 | Python | 34.857142 | 127 | 0.761715 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/omni/isaac/orbit/markers/config/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.markers.visualization_markers import VisualizationMarkersCfg
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
##
# Sensors.
##
RAY_CASTER_MARKER_CFG = VisualizationMarkersCfg(
markers={
"hit": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
},
)
"""Configuration for the ray-caster marker."""
CONTACT_SENSOR_MARKER_CFG = VisualizationMarkersCfg(
markers={
"contact": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"no_contact": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
visible=False,
),
},
)
"""Configuration for the contact sensor marker."""
##
# Frames.
##
FRAME_MARKER_CFG = VisualizationMarkersCfg(
markers={
"frame": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/frame_prim.usd",
scale=(0.5, 0.5, 0.5),
)
}
)
"""Configuration for the frame marker."""
RED_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
)
}
)
"""Configuration for the red arrow marker (along x-direction)."""
BLUE_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)),
)
}
)
"""Configuration for the blue arrow marker (along x-direction)."""
GREEN_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
)
}
)
"""Configuration for the green arrow marker (along x-direction)."""
##
# Goals.
##
CUBOID_MARKER_CFG = VisualizationMarkersCfg(
markers={
"cuboid": sim_utils.CuboidCfg(
size=(0.1, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
}
)
"""Configuration for the cuboid marker."""
POSITION_GOAL_MARKER_CFG = VisualizationMarkersCfg(
markers={
"target_far": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"target_near": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
),
"target_invisible": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)),
visible=False,
),
}
)
"""Configuration for the end-effector tracking marker."""
| 3,547 | Python | 27.384 | 87 | 0.610939 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/docs/CHANGELOG.rst | Changelog
---------
0.15.10 (2024-04-11)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed sharing of the same memory address between returned tensors from observation terms
in the :class:`omni.isaac.orbit.managers.ObservationManager` class. Earlier, the returned
tensors could map to the same memory address, causing issues when the tensors were modified
during scaling, clipping or other operations.
0.15.9 (2024-04-04)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed assignment of individual termination terms inside the :class:`omni.isaac.orbit.managers.TerminationManager`
class. Earlier, the terms were being assigned their values through an OR operation which resulted in incorrect
values. This regression was introduced in version 0.15.1.
0.15.8 (2024-04-02)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added option to define ordering of points for the mesh-grid generation in the
:func:`omni.isaac.orbit.sensors.ray_caster.patterns.grid_pattern`. This parameter defaults to 'xy'
for backward compatibility.
0.15.7 (2024-03-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds option to return indices/data in the specified query keys order in
:class:`omni.isaac.orbit.managers.SceneEntityCfg` class, and the respective
:func:`omni.isaac.orbit.utils.string.resolve_matching_names_values` and
:func:`omni.isaac.orbit.utils.string.resolve_matching_names` functions.
0.15.6 (2024-03-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Extended the :class:`omni.isaac.orbit.app.AppLauncher` class to support the loading of experience files
from the command line. This allows users to load a specific experience file when running the application
(such as for multi-camera rendering or headless mode).
Changed
^^^^^^^
* Changed default loading of experience files in the :class:`omni.isaac.orbit.app.AppLauncher` class from the ones
provided by Isaac Sim to the ones provided in Orbit's ``source/apps`` directory.
0.15.5 (2024-03-23)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the env origins in :meth:`_compute_env_origins_grid` of :class:`omni.isaac.orbit.terrain.TerrainImporter`
to match that obtained from the Isaac Sim :class:`omni.isaac.cloner.GridCloner` class.
Added
^^^^^
* Added unit test to ensure consistency between environment origins generated by IsaacSim's Grid Cloner and those
produced by the TerrainImporter.
0.15.4 (2024-03-22)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.envs.mdp.actions.NonHolonomicActionCfg` class to use
the correct variable when applying actions.
0.15.3 (2024-03-21)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added unit test to check that :class:`omni.isaac.orbit.scene.InteractiveScene` entity data is not shared between separate instances.
Fixed
^^^^^
* Moved class variables in :class:`omni.isaac.orbit.scene.InteractiveScene` to correctly be assigned as
instance variables.
* Removed custom ``__del__`` magic method from :class:`omni.isaac.orbit.scene.InteractiveScene`.
0.15.2 (2024-03-21)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added resolving of relative paths for the main asset USD file when using the
:class:`omni.isaac.orbit.sim.converters.UrdfConverter` class. This is to ensure that the material paths are
resolved correctly when the main asset file is moved to a different location.
0.15.1 (2024-03-19)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the imitation learning workflow example script, updating Orbit and Robomimic API calls.
* Removed the resetting of :attr:`_term_dones` in the :meth:`omni.isaac.orbit.managers.TerminationManager.reset`.
Previously, the environment cleared out all the terms. However, it impaired reading the specific term's values externally.
0.15.0 (2024-03-17)
~~~~~~~~~~~~~~~~~~~
Deprecated
^^^^^^^^^^
* Renamed :class:`omni.isaac.orbit.managers.RandomizationManager` to :class:`omni.isaac.orbit.managers.EventManager`
class for clarification as the manager takes care of events such as reset in addition to pure randomizations.
* Renamed :class:`omni.isaac.orbit.managers.RandomizationTermCfg` to :class:`omni.isaac.orbit.managers.EventTermCfg`
for consistency with the class name change.
0.14.1 (2024-03-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added simulation schemas for joint drive and fixed tendons. These can be configured for assets imported
from file formats.
* Added logging of tendon properties to the articulation class (if they are present in the USD prim).
0.14.0 (2024-03-15)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the ordering of body names used in the :class:`omni.isaac.orbit.assets.Articulation` class. Earlier,
the body names were not following the same ordering as the bodies in the articulation. This led
to issues when using the body names to access data related to the links from the articulation view
(such as Jacobians, mass matrices, etc.).
Removed
^^^^^^^
* Removed the attribute :attr:`body_physx_view` from the :class:`omni.isaac.orbit.assets.RigidObject`
and :class:`omni.isaac.orbit.assets.Articulation` classes. These were causing confusions when used
with articulation view since the body names were not following the same ordering.
0.13.1 (2024-03-14)
~~~~~~~~~~~~~~~~~~~
Removed
^^^^^^^
* Removed the :mod:`omni.isaac.orbit.compat` module. This module was used to provide compatibility
with older versions of Isaac Sim. It is no longer needed since we have most of the functionality
absorbed into the main classes.
0.13.0 (2024-03-12)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for the following data types inside the :class:`omni.isaac.orbit.sensors.Camera` class:
``instance_segmentation_fast`` and ``instance_id_segmentation_fast``. These are are GPU-supported annotations
and are faster than the regular annotations.
Fixed
^^^^^
* Fixed handling of semantic filtering inside the :class:`omni.isaac.orbit.sensors.Camera` class. Earlier,
the annotator was given ``semanticTypes`` as an argument. However, with Isaac Sim 2023.1, the annotator
does not accept this argument. Instead the mapping needs to be set to the synthetic data interface directly.
* Fixed the return shape of colored images for segmentation data types inside the
:class:`omni.isaac.orbit.sensors.Camera` class. Earlier, the images were always returned as ``int32``. Now,
they are casted to ``uint8`` 4-channel array before returning if colorization is enabled for the annotation type.
Removed
^^^^^^^
* Dropped support for ``instance_segmentation`` and ``instance_id_segmentation`` annotations in the
:class:`omni.isaac.orbit.sensors.Camera` class. Their "fast" counterparts should be used instead.
* Renamed the argument :attr:`omni.isaac.orbit.sensors.CameraCfg.semantic_types` to
:attr:`omni.isaac.orbit.sensors.CameraCfg.semantic_filter`. This is more aligned with Replicator's terminology
for semantic filter predicates.
* Replaced the argument :attr:`omni.isaac.orbit.sensors.CameraCfg.colorize` with separate colorized
arguments for each annotation type (:attr:`~omni.isaac.orbit.sensors.CameraCfg.colorize_instance_segmentation`,
:attr:`~omni.isaac.orbit.sensors.CameraCfg.colorize_instance_id_segmentation`, and
:attr:`~omni.isaac.orbit.sensors.CameraCfg.colorize_semantic_segmentation`).
0.12.4 (2024-03-11)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Adapted randomization terms to deal with ``slice`` for the body indices. Earlier, the terms were not
able to handle the slice object and were throwing an error.
* Added ``slice`` type-hinting to all body and joint related methods in the rigid body and articulation
classes. This is to make it clear that the methods can handle both list of indices and slices.
0.12.3 (2024-03-11)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added signal handler to the :class:`omni.isaac.orbit.app.AppLauncher` class to catch the ``SIGINT`` signal
and close the application gracefully. This is to prevent the application from crashing when the user
presses ``Ctrl+C`` to close the application.
0.12.2 (2024-03-10)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added observation terms for states of a rigid object in world frame.
* Added randomization terms to set root state with randomized orientation and joint state within user-specified limits.
* Added reward term for penalizing specific termination terms.
Fixed
^^^^^
* Improved sampling of states inside randomization terms. Earlier, the code did multiple torch calls
for sampling different components of the vector. Now, it uses a single call to sample the entire vector.
0.12.1 (2024-03-09)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added an option to the last actions observation term to get a specific term by name from the action manager.
If None, the behavior remains the same as before (the entire action is returned).
0.12.0 (2024-03-08)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added functionality to sample flat patches on a generated terrain. This can be configured using
:attr:`omni.isaac.orbit.terrains.SubTerrainBaseCfg.flat_patch_sampling` attribute.
* Added a randomization function for setting terrain-aware root state. Through this, an asset can be
reset to a randomly sampled flat patches.
Fixed
^^^^^
* Separated normal and terrain-base position commands. The terrain based commands rely on the
terrain to sample flat patches for setting the target position.
* Fixed command resample termination function.
Changed
^^^^^^^
* Added the attribute :attr:`omni.isaac.orbit.envs.mdp.commands.UniformVelocityCommandCfg.heading_control_stiffness`
to control the stiffness of the heading control term in the velocity command term. Earlier, this was
hard-coded to 0.5 inside the term.
Removed
^^^^^^^
* Removed the function :meth:`sample_new_targets` in the terrain importer. Instead the attribute
:attr:`omni.isaac.orbit.terrains.TerrainImporter.flat_patches` should be used to sample new targets.
0.11.3 (2024-03-04)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Corrects the functions :func:`omni.isaac.orbit.utils.math.axis_angle_from_quat` and :func:`omni.isaac.orbit.utils.math.quat_error_magnitude`
to accept tensors of the form (..., 4) instead of (N, 4). This brings us in line with our documentation and also upgrades one of our functions
to handle higher dimensions.
0.11.2 (2024-03-04)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added checks for default joint position and joint velocity in the articulation class. This is to prevent
users from configuring values for these quantities that might be outside the valid range from the simulation.
0.11.1 (2024-02-29)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Replaced the default values for ``joint_ids`` and ``body_ids`` from ``None`` to ``slice(None)``
in the :class:`omni.isaac.orbit.managers.SceneEntityCfg`.
* Adapted rewards and observations terms so that the users can query a subset of joints and bodies.
0.11.0 (2024-02-27)
~~~~~~~~~~~~~~~~~~~
Removed
^^^^^^^
* Dropped support for Isaac Sim<=2022.2. As part of this, removed the components of :class:`omni.isaac.orbit.app.AppLauncher`
which handled ROS extension loading. We no longer need them in Isaac Sim>=2023.1 to control the load order to avoid crashes.
* Upgraded Dockerfile to use ISAACSIM_VERSION=2023.1.1 by default.
0.10.28 (2024-02-29)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Implemented relative and moving average joint position action terms. These allow the user to specify
the target joint positions as relative to the current joint positions or as a moving average of the
joint positions over a window of time.
0.10.27 (2024-02-28)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added UI feature to start and stop animation recording in the stage when running an environment.
To enable this feature, please pass the argument ``--disable_fabric`` to the environment script to allow
USD read/write operations. Be aware that this will slow down the simulation.
0.10.26 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a viewport camera controller class to the :class:`omni.isaac.orbit.envs.BaseEnv`. This is useful
for applications where the user wants to render the viewport from different perspectives even when the
simulation is running in headless mode.
0.10.25 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Ensures that all path arguments in :mod:`omni.isaac.orbit.sim.utils` are cast to ``str``. Previously,
we had handled path types as strings without casting.
0.10.24 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added tracking of contact time in the :class:`omni.isaac.orbit.sensors.ContactSensor` class. Previously,
only the air time was being tracked.
* Added contact force threshold, :attr:`omni.isaac.orbit.sensors.ContactSensorCfg.force_threshold`, to detect
when the contact sensor is in contact. Previously, this was set to hard-coded 1.0 in the sensor class.
0.10.23 (2024-02-21)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixes the order of size arguments in :meth:`omni.isaac.orbit.terrains.height_field.random_uniform_terrain`. Previously, the function would crash if the size along x and y were not the same.
0.10.22 (2024-02-14)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed "divide by zero" bug in :class:`~omni.isaac.orbit.sim.SimulationContext` when setting gravity vector.
Now, it is correctly disabled when the gravity vector is set to zero.
0.10.21 (2024-02-12)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the printing of articulation joint information when the articulation has only one joint.
Earlier, the function was performing a squeeze operation on the tensor, which caused an error when
trying to index the tensor of shape (1,).
0.10.20 (2024-02-12)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds :attr:`omni.isaac.orbit.sim.PhysxCfg.enable_enhanced_determinism` to enable improved
determinism from PhysX. Please note this comes at the expense of performance.
0.10.19 (2024-02-08)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed environment closing so that articulations, objects, and sensors are cleared properly.
0.10.18 (2024-02-05)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Pinned :mod:`torch` version to 2.0.1 in the setup.py to keep parity version of :mod:`torch` supplied by
Isaac 2023.1.1, and prevent version incompatibility between :mod:`torch` ==2.2 and
:mod:`typing-extensions` ==3.7.4.3
0.10.17 (2024-02-02)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^^
* Fixed carb setting ``/app/livestream/enabled`` to be set as False unless live-streaming is specified
by :class:`omni.isaac.orbit.app.AppLauncher` settings. This fixes the logic of :meth:`SimulationContext.render`,
which depended on the config in previous versions of Isaac defaulting to false for this setting.
0.10.16 (2024-01-29)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^^
* Added an offset parameter to the height scan observation term. This allows the user to specify the
height offset of the scan from the tracked body. Previously it was hard-coded to be 0.5.
0.10.15 (2024-01-29)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed joint torque computation for implicit actuators. Earlier, the torque was always zero for implicit
actuators. Now, it is computed approximately by applying the PD law.
0.10.14 (2024-01-22)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the tensor shape of :attr:`omni.isaac.orbit.sensors.ContactSensorData.force_matrix_w`. Earlier, the reshaping
led to a mismatch with the data obtained from PhysX.
0.10.13 (2024-01-15)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed running of environments with a single instance even if the :attr:`replicate_physics`` flag is set to True.
0.10.12 (2024-01-10)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed indexing of source and target frames in the :class:`omni.isaac.orbit.sensors.FrameTransformer` class.
Earlier, it always assumed that the source frame body is at index 0. Now, it uses the body index of the
source frame to compute the transformation.
Deprecated
^^^^^^^^^^
* Renamed quantities in the :class:`omni.isaac.orbit.sensors.FrameTransformerData` class to be more
consistent with the terminology used in the asset classes. The following quantities are deprecated:
* ``target_rot_w`` -> ``target_quat_w``
* ``source_rot_w`` -> ``source_quat_w``
* ``target_rot_source`` -> ``target_quat_source``
0.10.11 (2024-01-08)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed attribute error raised when calling the :class:`omni.isaac.orbit.envs.mdp.TerrainBasedPositionCommand`
command term.
* Added a dummy function in :class:`omni.isaac.orbit.terrain.TerrainImporter` that returns environment
origins as terrain-aware sampled targets. This function should be implemented by child classes based on
the terrain type.
0.10.10 (2023-12-21)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed reliance on non-existent ``Viewport`` in :class:`omni.isaac.orbit.sim.SimulationContext` when loading livestreaming
by ensuring that the extension ``omni.kit.viewport.window`` is enabled in :class:`omni.isaac.orbit.app.AppLauncher` when
livestreaming is enabled
0.10.9 (2023-12-21)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed invalidation of physics views inside the asset and sensor classes. Earlier, they were left initialized
even when the simulation was stopped. This caused issues when closing the application.
0.10.8 (2023-12-20)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.envs.mdp.actions.DifferentialInverseKinematicsAction` class
to account for the offset pose of the end-effector.
0.10.7 (2023-12-19)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a check to ray-cast and camera sensor classes to ensure that the sensor prim path does not
have a regex expression at its leaf. For instance, ``/World/Robot/camera_.*`` is not supported
for these sensor types. This behavior needs to be fixed in the future.
0.10.6 (2023-12-19)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for using articulations as visualization markers. This disables all physics APIs from
the articulation and allows the user to use it as a visualization marker. It is useful for creating
visualization markers for the end-effectors or base of the robot.
Fixed
^^^^^
* Fixed hiding of debug markers from secondary images when using the
:class:`omni.isaac.orbit.markers.VisualizationMarkers` class. Earlier, the properties were applied on
the XForm prim instead of the Mesh prim.
0.10.5 (2023-12-18)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed test ``check_base_env_anymal_locomotion.py``, which
previously called :func:`torch.jit.load` with the path to a policy (which would work
for a local file), rather than calling
:func:`omni.isaac.orbit.utils.assets.read_file` on the path to get the file itself.
0.10.4 (2023-12-14)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed potentially breaking import of omni.kit.widget.toolbar by ensuring that
if live-stream is enabled, then the :mod:`omni.kit.widget.toolbar`
extension is loaded.
0.10.3 (2023-12-12)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the attribute :attr:`omni.isaac.orbit.actuators.ActuatorNetMLPCfg.input_order`
to specify the order of the input tensors to the MLP network.
Fixed
^^^^^
* Fixed computation of metrics for the velocity command term. Earlier, the norm was being computed
over the entire batch instead of the last dimension.
* Fixed the clipping inside the :class:`omni.isaac.orbit.actuators.DCMotor` class. Earlier, it was
not able to handle the case when configured saturation limit was set to None.
0.10.2 (2023-12-12)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a check in the simulation stop callback in the :class:`omni.isaac.orbit.sim.SimulationContext` class
to not render when an exception is raised. The while loop in the callback was preventing the application
from closing when an exception was raised.
0.10.1 (2023-12-06)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added command manager class with terms defined by :class:`omni.isaac.orbit.managers.CommandTerm`. This
allow for multiple types of command generators to be used in the same environment.
0.10.0 (2023-12-04)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Modified the sensor and asset base classes to use the underlying PhysX views instead of Isaac Sim views.
Using Isaac Sim classes led to a very high load time (of the order of minutes) when using a scene with
many assets. This is because Isaac Sim supports USD paths which are slow and not required.
Added
^^^^^
* Added faster implementation of USD stage traversal methods inside the :class:`omni.isaac.orbit.sim.utils` module.
* Added properties :attr:`omni.isaac.orbit.assets.AssetBase.num_instances` and
:attr:`omni.isaac.orbit.sensor.SensorBase.num_instances` to obtain the number of instances of the asset
or sensor in the simulation respectively.
Removed
^^^^^^^
* Removed dependencies on Isaac Sim view classes. It is no longer possible to use :attr:`root_view` and
:attr:`body_view`. Instead use :attr:`root_physx_view` and :attr:`body_physx_view` to access the underlying
PhysX views.
0.9.55 (2023-12-03)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the Nucleus directory path in the :attr:`omni.isaac.orbit.utils.assets.NVIDIA_NUCLEUS_DIR`.
Earlier, it was referring to the ``NVIDIA/Assets`` directory instead of ``NVIDIA``.
0.9.54 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed pose computation in the :class:`omni.isaac.orbit.sensors.Camera` class to obtain them from XFormPrimView
instead of using ``UsdGeomCamera.ComputeLocalToWorldTransform`` method. The latter is not updated correctly
during GPU simulation.
* Fixed initialization of the annotator info in the class :class:`omni.isaac.orbit.sensors.Camera`. Previously
all dicts had the same memory address which caused all annotators to have the same info.
* Fixed the conversion of ``uint32`` warp arrays inside the :meth:`omni.isaac.orbit.utils.array.convert_to_torch`
method. PyTorch does not support this type, so it is converted to ``int32`` before converting to PyTorch tensor.
* Added render call inside :meth:`omni.isaac.orbit.sim.SimulationContext.reset` to initialize Replicator
buffers when the simulation is reset.
0.9.53 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of passing :obj:`None` to the :class:`omni.isaac.orbit.actuators.ActuatorBaseCfg`
class. Earlier, they were resolved to fixed default values. Now, they imply that the values are loaded
from the USD joint drive configuration.
Added
^^^^^
* Added setting of joint armature and friction quantities to the articulation class.
0.9.52 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the warning print in :meth:`omni.isaac.orbit.sim.utils.apply_nested` method
to be more descriptive. Earlier, it was printing a warning for every instanced prim.
Now, it only prints a warning if it could not apply the attribute to any of the prims.
Added
^^^^^
* Added the method :meth:`omni.isaac.orbit.utils.assets.retrieve_file_path` to
obtain the absolute path of a file on the Nucleus server or locally.
Fixed
^^^^^
* Fixed hiding of STOP button in the :class:`AppLauncher` class when running the
simulation in headless mode.
* Fixed a bug with :meth:`omni.isaac.orbit.sim.utils.clone` failing when the input prim path
had no parent (example: "/Table").
0.9.51 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the :meth:`omni.isaac.orbit.sensor.SensorBase.update` method to always recompute the buffers if
the sensor is in visualization mode.
Added
^^^^^
* Added available entities to the error message when accessing a non-existent entity in the
:class:`InteractiveScene` class.
* Added a warning message when the user tries to reference an invalid prim in the :class:`FrameTransformer` sensor.
0.9.50 (2023-11-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Hid the ``STOP`` button in the UI when running standalone Python scripts. This is to prevent
users from accidentally clicking the button and stopping the simulation. They should only be able to
play and pause the simulation from the UI.
Removed
^^^^^^^
* Removed :attr:`omni.isaac.orbit.sim.SimulationCfg.shutdown_app_on_stop`. The simulation is always rendering
if it is stopped from the UI. The user needs to close the window or press ``Ctrl+C`` to close the simulation.
0.9.49 (2023-11-27)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added an interface class, :class:`omni.isaac.orbit.managers.ManagerTermBase`, to serve as the parent class
for term implementations that are functional classes.
* Adapted all managers to support terms that are classes and not just functions clearer. This allows the user to
create more complex terms that require additional state information.
0.9.48 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed initialization of drift in the :class:`omni.isaac.orbit.sensors.RayCasterCamera` class.
0.9.47 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Automated identification of the root prim in the :class:`omni.isaac.orbit.assets.RigidObject` and
:class:`omni.isaac.orbit.assets.Articulation` classes. Earlier, the root prim was hard-coded to
the spawn prim path. Now, the class searches for the root prim under the spawn prim path.
0.9.46 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed a critical issue in the asset classes with writing states into physics handles.
Earlier, the states were written over all the indices instead of the indices of the
asset that were being updated. This caused the physics handles to refresh the states
of all the assets in the scene, which is not desirable.
0.9.45 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :class:`omni.isaac.orbit.command_generators.UniformPoseCommandGenerator` to generate
poses in the asset's root frame by uniformly sampling from a given range.
0.9.44 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added methods :meth:`reset` and :meth:`step` to the :class:`omni.isaac.orbit.envs.BaseEnv`. This unifies
the environment interface for simple standalone applications with the class.
0.9.43 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Replaced subscription of physics play and stop events in the :class:`omni.isaac.orbit.assets.AssetBase` and
:class:`omni.isaac.orbit.sensors.SensorBase` classes with subscription to time-line play and stop events.
This is to prevent issues in cases where physics first needs to perform mesh cooking and handles are not
available immediately. For instance, with deformable meshes.
0.9.42 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed setting of damping values from the configuration for :class:`ActuatorBase` class. Earlier,
the stiffness values were being set into damping when a dictionary configuration was passed to the
actuator model.
* Added dealing with :class:`int` and :class:`float` values in the configurations of :class:`ActuatorBase`.
Earlier, a type-error was thrown when integer values were passed to the actuator model.
0.9.41 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the naming and shaping issues in the binary joint action term.
0.9.40 (2023-11-09)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Simplified the manual initialization of Isaac Sim :class:`ArticulationView` class. Earlier, we basically
copied the code from the Isaac Sim source code. Now, we just call their initialize method.
Changed
^^^^^^^
* Changed the name of attribute :attr:`default_root_state_w` to :attr:`default_root_state`. The latter is
more correct since the data is actually in the local environment frame and not the simulation world frame.
0.9.39 (2023-11-08)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed the reference of private ``_body_view`` variable inside the :class:`RigidObject` class
to the public ``body_view`` property. For a rigid object, the private variable is not defined.
0.9.38 (2023-11-07)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Upgraded the :class:`omni.isaac.orbit.envs.RLTaskEnv` class to support Gym 0.29.0 environment definition.
Added
^^^^^
* Added computation of ``time_outs`` and ``terminated`` signals inside the termination manager. These follow the
definition mentioned in `Gym 0.29.0 <https://gymnasium.farama.org/tutorials/gymnasium_basics/handling_time_limits/>`_.
* Added proper handling of observation and action spaces in the :class:`omni.isaac.orbit.envs.RLTaskEnv` class.
These now follow closely to how Gym VecEnv handles the spaces.
0.9.37 (2023-11-06)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed broken visualization in :mod:`omni.isaac.orbit.sensors.FrameTramsformer` class by overwriting the
correct ``_debug_vis_callback`` function.
* Moved the visualization marker configurations of sensors to their respective sensor configuration classes.
This allows users to set these configurations from the configuration object itself.
0.9.36 (2023-11-03)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added explicit deleting of different managers in the :class:`omni.isaac.orbit.envs.BaseEnv` and
:class:`omni.isaac.orbit.envs.RLTaskEnv` classes. This is required since deleting the managers
is order-sensitive (many managers need to be deleted before the scene is deleted).
0.9.35 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the error: ``'str' object has no attribute '__module__'`` introduced by adding the future import inside the
:mod:`omni.isaac.orbit.utils.warp.kernels` module. Warp language does not support the ``__future__`` imports.
0.9.34 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added missing import of ``from __future__ import annotations`` in the :mod:`omni.isaac.orbit.utils.warp`
module. This is needed to have a consistent behavior across Python versions.
0.9.33 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.command_generators.NullCommandGenerator` class. Earlier,
it was having a runtime error due to infinity in the resampling time range. Now, the class just
overrides the parent methods to perform no operations.
0.9.32 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Renamed the :class:`omni.isaac.orbit.envs.RLEnv` class to :class:`omni.isaac.orbit.envs.RLTaskEnv` to
avoid confusions in terminologies between environments and tasks.
0.9.31 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.orbit.sensors.RayCasterCamera` class, as a ray-casting based camera for
"distance_to_camera", "distance_to_image_plane" and "normals" annotations. It has the same interface and
functionalities as the USD Camera while it is on average 30% faster.
0.9.30 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added skipping of None values in the :class:`InteractiveScene` class when creating the scene from configuration
objects. Earlier, it was throwing an error when the user passed a None value for a scene element.
* Added ``kwargs`` to the :class:`RLEnv` class to allow passing additional arguments from gym registry function.
This is now needed since the registry function passes args beyond the ones specified in the constructor.
0.9.29 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the material path resolution inside the :class:`omni.isaac.orbit.sim.converters.UrdfConverter` class.
With Isaac Sim 2023.1, the material paths from the importer are always saved as absolute paths. This caused
issues when the generated USD file was moved to a different location. The fix now resolves the material paths
relative to the USD file location.
0.9.28 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the way the :func:`omni.isaac.orbit.sim.spawners.from_files.spawn_ground_plane` function sets the
height of the ground. Earlier, it was reading the height from the configuration object. Now, it expects the
desired transformation as inputs to the function. This makes it consistent with the other spawner functions.
0.9.27 (2023-10-31)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Removed the default value of the argument ``camel_case`` in setters of USD attributes. This is to avoid
confusion with the naming of the attributes in the USD file.
Fixed
^^^^^
* Fixed the selection of material prim in the :class:`omni.isaac.orbit.sim.spawners.materials.spawn_preview_surface`
method. Earlier, the created prim was being selected in the viewport which interfered with the selection of
prims by the user.
* Updated :class:`omni.isaac.orbit.sim.converters.MeshConverter` to use a different stage than the default stage
for the conversion. This is to avoid the issue of the stage being closed when the conversion is done.
0.9.26 (2023-10-31)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the sensor implementation for :class:`omni.isaac.orbit.sensors.FrameTransformer` class. Currently,
it handles obtaining the transformation between two frames in the same articulation.
0.9.25 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :mod:`omni.isaac.orbit.envs.ui` module to put all the UI-related classes in one place. This currently
implements the :class:`omni.isaac.orbit.envs.ui.BaseEnvWindow` and :class:`omni.isaac.orbit.envs.ui.RLEnvWindow`
classes. Users can inherit from these classes to create their own UI windows.
* Added the attribute :attr:`omni.isaac.orbit.envs.BaseEnvCfg.ui_window_class_type` to specify the UI window class
to be used for the environment. This allows the user to specify their own UI window class to be used for the
environment.
0.9.24 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of setting up debug visualization for assets, sensors and command generators.
Earlier it was raising an error if debug visualization was not enabled in the configuration object.
Now it checks whether debug visualization is implemented and only sets up the callback if it is
implemented.
0.9.23 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed a typo in the :class:`AssetBase` and :class:`SensorBase` that effected the class destructor.
Earlier, a tuple was being created in the constructor instead of the actual object.
0.9.22 (2023-10-26)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a :class:`omni.isaac.orbit.command_generators.NullCommandGenerator` class for no command environments.
This is easier to work with than having checks for :obj:`None` in the command generator.
Fixed
^^^^^
* Moved the randomization manager to the :class:`omni.isaac.orbit.envs.BaseEnv` class with the default
settings to reset the scene to the defaults specified in the configurations of assets.
* Moved command generator to the :class:`omni.isaac.orbit.envs.RlEnv` class to have all task-specification
related classes in the same place.
0.9.21 (2023-10-26)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Decreased the priority of callbacks in asset and sensor base classes. This may help in preventing
crashes when warm starting the simulation.
* Fixed no rendering mode when running the environment from the GUI. Earlier the function
:meth:`SimulationContext.set_render_mode` was erroring out.
0.9.20 (2023-10-25)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed naming in :class:`omni.isaac.orbit.sim.SimulationContext.RenderMode` to use ``NO_GUI_OR_RENDERING``
and ``NO_RENDERING`` instead of ``HEADLESS`` for clarity.
* Changed :class:`omni.isaac.orbit.sim.SimulationContext` to be capable of handling livestreaming and
offscreen rendering.
* Changed :class:`omni.isaac.orbit.app.AppLauncher` envvar ``VIEWPORT_RECORD`` to the more descriptive
``OFFSCREEN_RENDER``.
0.9.19 (2023-10-25)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added Gym observation and action spaces for the :class:`omni.isaac.orbit.envs.RLEnv` class.
0.9.18 (2023-10-23)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Created :class:`omni.issac.orbit.sim.converters.asset_converter.AssetConverter` to serve as a base
class for all asset converters.
* Added :class:`omni.issac.orbit.sim.converters.mesh_converter.MeshConverter` to handle loading and conversion
of mesh files (OBJ, STL and FBX) into USD format.
* Added script ``convert_mesh.py`` to ``source/tools`` to allow users to convert a mesh to USD via command line arguments.
Changed
^^^^^^^
* Renamed the submodule :mod:`omni.isaac.orbit.sim.loaders` to :mod:`omni.isaac.orbit.sim.converters` to be more
general with the functionality of the module.
* Updated ``check_instanceable.py`` script to convert relative paths to absolute paths.
0.9.17 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added setters and getters for term configurations in the :class:`RandomizationManager`, :class:`RewardManager`
and :class:`TerminationManager` classes. This allows the user to modify the term configurations after the
manager has been created.
* Added the method :meth:`compute_group` to the :class:`omni.isaac.orbit.managers.ObservationManager` class to
compute the observations for only a given group.
* Added the curriculum term for modifying reward weights after certain environment steps.
0.9.16 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for keyword arguments for terms in the :class:`omni.isaac.orbit.managers.ManagerBase`.
Fixed
^^^^^
* Fixed resetting of buffers in the :class:`TerminationManager` class. Earlier, the values were being set
to ``0.0`` instead of ``False``.
0.9.15 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added base yaw heading and body acceleration into :class:`omni.isaac.orbit.assets.RigidObjectData` class.
These quantities are computed inside the :class:`RigidObject` class.
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.orbit.assets.RigidObject.set_external_force_and_torque` method to correctly
deal with the body indices.
* Fixed a bug in the :meth:`omni.isaac.orbit.utils.math.wrap_to_pi` method to prevent self-assignment of
the input tensor.
0.9.14 (2023-10-21)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added 2-D drift (i.e. along x and y) to the :class:`omni.isaac.orbit.sensors.RayCaster` class.
* Added flags to the :class:`omni.isaac.orbit.sensors.ContactSensorCfg` to optionally obtain the
sensor origin and air time information. Since these are not required by default, they are
disabled by default.
Fixed
^^^^^
* Fixed the handling of contact sensor history buffer in the :class:`omni.isaac.orbit.sensors.ContactSensor` class.
Earlier, the buffer was not being updated correctly.
0.9.13 (2023-10-20)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the issue with double :obj:`Ellipsis` when indexing tensors with multiple dimensions.
The fix now uses :obj:`slice(None)` instead of :obj:`Ellipsis` to index the tensors.
0.9.12 (2023-10-18)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed bugs in actuator model implementation for actuator nets. Earlier the DC motor clipping was not working.
* Fixed bug in applying actuator model in the :class:`omni.isaac.orbit.asset.Articulation` class. The new
implementation caches the outputs from explicit actuator model into the ``joint_pos_*_sim`` buffer to
avoid feedback loops in the tensor operation.
0.9.11 (2023-10-17)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the support for semantic tags into the :class:`omni.isaac.orbit.sim.spawner.SpawnerCfg` class. This allows
the user to specify the semantic tags for a prim when spawning it into the scene. It follows the same format as
Omniverse Replicator.
0.9.10 (2023-10-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added ``--livestream`` and ``--ros`` CLI args to :class:`omni.isaac.orbit.app.AppLauncher` class.
* Added a static function :meth:`omni.isaac.orbit.app.AppLauncher.add_app_launcher_args`, which
appends the arguments needed for :class:`omni.isaac.orbit.app.AppLauncher` to the argument parser.
Changed
^^^^^^^
* Within :class:`omni.isaac.orbit.app.AppLauncher`, removed ``REMOTE_DEPLOYMENT`` env-var processing
in the favor of ``HEADLESS`` and ``LIVESTREAM`` env-vars. These have clearer uses and better parity
with the CLI args.
0.9.9 (2023-10-12)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the property :attr:`omni.isaac.orbit.assets.Articulation.is_fixed_base` to the articulation class to
check if the base of the articulation is fixed or floating.
* Added the task-space action term corresponding to the differential inverse-kinematics controller.
Fixed
^^^^^
* Simplified the :class:`omni.isaac.orbit.controllers.DifferentialIKController` to assume that user provides the
correct end-effector poses and Jacobians. Earlier it was doing internal frame transformations which made the
code more complicated and error-prone.
0.9.8 (2023-09-30)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the boundedness of class objects that register callbacks into the simulator.
These include devices, :class:`AssetBase`, :class:`SensorBase` and :class:`CommandGenerator`.
The fix ensures that object gets deleted when the user deletes the object.
0.9.7 (2023-09-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Modified the :class:`omni.isaac.orbit.markers.VisualizationMarkers` to use the
:class:`omni.isaac.orbit.sim.spawner.SpawnerCfg` class instead of their
own configuration objects. This makes it consistent with the other ways to spawn assets in the scene.
Added
^^^^^
* Added the method :meth:`copy` to configclass to allow copying of configuration objects.
0.9.6 (2023-09-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed class-level configuration classes to refer to class types using ``class_type`` attribute instead
of ``cls`` or ``cls_name``.
0.9.5 (2023-09-25)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Added future import of ``annotations`` to have a consistent behavior across Python versions.
* Removed the type-hinting from docstrings to simplify maintenance of the documentation. All type-hints are
now in the code itself.
0.9.4 (2023-08-29)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :class:`omni.isaac.orbit.scene.InteractiveScene`, as the central scene unit that contains all entities
that are part of the simulation. These include the terrain, sensors, articulations, rigid objects etc.
The scene groups the common operations of these entities and allows to access them via their unique names.
* Added :mod:`omni.isaac.orbit.envs` module that contains environment definitions that encapsulate the different
general (scene, action manager, observation manager) and RL-specific (reward and termination manager) managers.
* Added :class:`omni.isaac.orbit.managers.SceneEntityCfg` to handle which scene elements are required by the
manager's terms. This allows the manager to parse useful information from the scene elements, such as the
joint and body indices, and pass them to the term.
* Added :class:`omni.isaac.orbit.sim.SimulationContext.RenderMode` to handle different rendering modes based on
what the user wants to update (viewport, cameras, or UI elements).
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.command_generators.CommandGeneratorBase` to register a debug visualization
callback similar to how sensors and robots handle visualization.
0.9.3 (2023-08-23)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Enabled the `faulthander <https://docs.python.org/3/library/faulthandler.html>`_ to catch segfaults and print
the stack trace. This is enabled by default in the :class:`omni.isaac.orbit.app.AppLauncher` class.
Fixed
^^^^^
* Re-added the :mod:`omni.isaac.orbit.utils.kit` to the ``compat`` directory and fixed all the references to it.
* Fixed the deletion of Replicator nodes for the :class:`omni.isaac.orbit.sensors.Camera` class. Earlier, the
Replicator nodes were not being deleted when the camera was deleted. However, this does not prevent the random
crashes that happen when the camera is deleted.
* Fixed the :meth:`omni.isaac.orbit.utils.math.convert_quat` to support both numpy and torch tensors.
Changed
^^^^^^^
* Renamed all the scripts inside the ``test`` directory to follow the convention:
* ``test_<module_name>.py``: Tests for the module ``<module_name>`` using unittest.
* ``check_<module_name>``: Check for the module ``<module_name>`` using python main function.
0.9.2 (2023-08-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the ability to color meshes in the :class:`omni.isaac.orbit.terrain.TerrainGenerator` class. Currently,
it only supports coloring the mesh randomly (``"random"``), based on the terrain height (``"height"``), and
no coloring (``"none"``).
Fixed
^^^^^
* Modified the :class:`omni.isaac.orbit.terrain.TerrainImporter` class to configure visual and physics materials
based on the configuration object.
0.9.1 (2023-08-18)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Introduced three different rotation conventions in the :class:`omni.isaac.orbit.sensors.Camera` class. These
conventions are:
* ``opengl``: the camera is looking down the -Z axis with the +Y axis pointing up
* ``ros``: the camera is looking down the +Z axis with the +Y axis pointing down
* ``world``: the camera is looking along the +X axis with the -Z axis pointing down
These can be used to declare the camera offset in :class:`omni.isaac.orbit.sensors.CameraCfg.OffsetCfg` class
and in :meth:`omni.isaac.orbit.sensors.Camera.set_world_pose` method. Additionally, all conventions are
saved to :class:`omni.isaac.orbit.sensors.CameraData` class for easy access.
Changed
^^^^^^^
* Adapted all the sensor classes to follow a structure similar to the :class:`omni.issac.orbit.assets.AssetBase`.
Hence, the spawning and initialization of sensors manually by the users is avoided.
* Removed the :meth:`debug_vis` function since that this functionality is handled by a render callback automatically
(based on the passed configuration for the :class:`omni.isaac.orbit.sensors.SensorBaseCfg.debug_vis` flag).
0.9.0 (2023-08-18)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Introduces a new set of asset interfaces. These interfaces simplify the spawning of assets into the scene
and initializing the physics handle by putting that inside post-startup physics callbacks. With this, users
no longer need to worry about the :meth:`spawn` and :meth:`initialize` calls.
* Added utility methods to :mod:`omni.isaac.orbit.utils.string` module that resolve regex expressions based
on passed list of target keys.
Changed
^^^^^^^
* Renamed all references of joints in an articulation from "dof" to "joint". This makes it consistent with the
terminology used in robotics.
Deprecated
^^^^^^^^^^
* Removed the previous modules for objects and robots. Instead the :class:`Articulation` and :class:`RigidObject`
should be used.
0.8.12 (2023-08-18)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added other properties provided by ``PhysicsScene`` to the :class:`omni.isaac.orbit.sim.SimulationContext`
class to allow setting CCD, solver iterations, etc.
* Added commonly used functions to the :class:`SimulationContext` class itself to avoid having additional
imports from Isaac Sim when doing simple tasks such as setting camera view or retrieving the simulation settings.
Fixed
^^^^^
* Switched the notations of default buffer values in :class:`omni.isaac.orbit.sim.PhysxCfg` from multiplication
to scientific notation to avoid confusion with the values.
0.8.11 (2023-08-18)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds utility functions and configuration objects in the :mod:`omni.isaac.orbit.sim.spawners`
to create the following prims in the scene:
* :mod:`omni.isaac.orbit.sim.spawners.from_file`: Create a prim from a USD/URDF file.
* :mod:`omni.isaac.orbit.sim.spawners.shapes`: Create USDGeom prims for shapes (box, sphere, cylinder, capsule, etc.).
* :mod:`omni.isaac.orbit.sim.spawners.materials`: Create a visual or physics material prim.
* :mod:`omni.isaac.orbit.sim.spawners.lights`: Create a USDLux prim for different types of lights.
* :mod:`omni.isaac.orbit.sim.spawners.sensors`: Create a USD prim for supported sensors.
Changed
^^^^^^^
* Modified the :class:`SimulationContext` class to take the default physics material using the material spawn
configuration object.
0.8.10 (2023-08-17)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added methods for defining different physics-based schemas in the :mod:`omni.isaac.orbit.sim.schemas` module.
These methods allow creating the schema if it doesn't exist at the specified prim path and modify
its properties based on the configuration object.
0.8.9 (2023-08-09)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Moved the :class:`omni.isaac.orbit.asset_loader.UrdfLoader` class to the :mod:`omni.isaac.orbit.sim.loaders`
module to make it more accessible to the user.
0.8.8 (2023-08-09)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added configuration classes and functions for setting different physics-based schemas in the
:mod:`omni.isaac.orbit.sim.schemas` module. These allow modifying properties of the physics solver
on the asset using configuration objects.
0.8.7 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added support for `__post_init__ <https://docs.python.org/3/library/dataclasses.html#post-init-processing>`_ in
the :class:`omni.isaac.orbit.utils.configclass` decorator.
0.8.6 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for callable classes in the :class:`omni.isaac.orbit.managers.ManagerBase`.
0.8.5 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.orbit.markers.Visualizationmarkers` class so that the markers are not visible in camera rendering mode.
Changed
^^^^^^^
* Simplified the creation of the point instancer in the :class:`omni.isaac.orbit.markers.Visualizationmarkers` class. It now creates a new
prim at the next available prim path if a prim already exists at the given path.
0.8.4 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.orbit.sim.SimulationContext` class to the :mod:`omni.isaac.orbit.sim` module.
This class inherits from the :class:`omni.isaac.core.simulation_context.SimulationContext` class and adds
the ability to create a simulation context from a configuration object.
0.8.3 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Moved the :class:`ActuatorBase` class to the :mod:`omni.isaac.orbit.actuators.actuator_base` module.
* Renamed the :mod:`omni.isaac.orbit.actuators.actuator` module to :mod:`omni.isaac.orbit.actuators.actuator_pd`
to make it more explicit that it contains the PD actuator models.
0.8.2 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Cleaned up the :class:`omni.isaac.orbit.terrain.TerrainImporter` class to take all the parameters from the configuration
object. This makes it consistent with the other classes in the package.
* Moved the configuration classes for terrain generator and terrain importer into separate files to resolve circular
dependency issues.
0.8.1 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a hack into :class:`omni.isaac.orbit.app.AppLauncher` class to remove orbit packages from the path before launching
the simulation application. This prevents the warning messages that appears when the user launches the ``SimulationApp``.
Added
^^^^^
* Enabled necessary viewport extensions in the :class:`omni.isaac.orbit.app.AppLauncher` class itself if ``VIEWPORT_ENABLED``
flag is true.
0.8.0 (2023-07-26)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`ActionManager` class to the :mod:`omni.isaac.orbit.managers` module to handle actions in the
environment through action terms.
* Added contact force history to the :class:`omni.isaac.orbit.sensors.ContactSensor` class. The history is stored
in the ``net_forces_w_history`` attribute of the sensor data.
Changed
^^^^^^^
* Implemented lazy update of buffers in the :class:`omni.isaac.orbit.sensors.SensorBase` class. This allows the user
to update the sensor data only when required, i.e. when the data is requested by the user. This helps avoid double
computation of sensor data when a reset is called in the environment.
Deprecated
^^^^^^^^^^
* Removed the support for different backends in the sensor class. We only use Pytorch as the backend now.
* Removed the concept of actuator groups. They are now handled by the :class:`omni.isaac.orbit.managers.ActionManager`
class. The actuator models are now directly handled by the robot class itself.
0.7.4 (2023-07-26)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of the :class:`omni.isaac.orbit.terrains.TerrainImporter` class. It now expects the terrain
type to be specified in the configuration object. This allows the user to specify everything in the configuration
object and not have to do an explicit call to import a terrain.
Fixed
^^^^^
* Fixed setting of quaternion orientations inside the :class:`omni.isaac.orbit.markers.Visualizationmarkers` class.
Earlier, the orientation was being set into the point instancer in the wrong order (``wxyz`` instead of ``xyzw``).
0.7.3 (2023-07-25)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the issue with multiple inheritance in the :class:`omni.isaac.orbit.utils.configclass` decorator.
Earlier, if the inheritance tree was more than one level deep and the lowest level configuration class was
not updating its values from the middle level classes.
0.7.2 (2023-07-24)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the method :meth:`replace` to the :class:`omni.isaac.orbit.utils.configclass` decorator to allow
creating a new configuration object with values replaced from keyword arguments. This function internally
calls the `dataclasses.replace <https://docs.python.org/3/library/dataclasses.html#dataclasses.replace>`_.
Fixed
^^^^^
* Fixed the handling of class types as member values in the :meth:`omni.isaac.orbit.utils.configclass`. Earlier it was
throwing an error since class types were skipped in the if-else block.
0.7.1 (2023-07-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`TerminationManager`, :class:`CurriculumManager`, and :class:`RandomizationManager` classes
to the :mod:`omni.isaac.orbit.managers` module to handle termination, curriculum, and randomization respectively.
0.7.0 (2023-07-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Created a new :mod:`omni.isaac.orbit.managers` module for all the managers related to the environment / scene.
This includes the :class:`omni.isaac.orbit.managers.ObservationManager` and :class:`omni.isaac.orbit.managers.RewardManager`
classes that were previously in the :mod:`omni.isaac.orbit.utils.mdp` module.
* Added the :class:`omni.isaac.orbit.managers.ManagerBase` class to handle the creation of managers.
* Added configuration classes for :class:`ObservationTermCfg` and :class:`RewardTermCfg` to allow easy creation of
observation and reward terms.
Changed
^^^^^^^
* Changed the behavior of :class:`ObservationManager` and :class:`RewardManager` classes to accept the key ``func``
in each configuration term to be a callable. This removes the need to inherit from the base class
and allows more reusability of the functions across different environments.
* Moved the old managers to the :mod:`omni.isaac.orbit.compat.utils.mdp` module.
* Modified the necessary scripts to use the :mod:`omni.isaac.orbit.compat.utils.mdp` module.
0.6.2 (2023-07-21)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :mod:`omni.isaac.orbit.command_generators` to generate different commands based on the desired task.
It allows the user to generate commands for different tasks in the same environment without having to write
custom code for each task.
0.6.1 (2023-07-16)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.orbit.utils.math.quat_apply_yaw` to compute the yaw quaternion correctly.
Added
^^^^^
* Added functions to convert string and callable objects in :mod:`omni.isaac.orbit.utils.string`.
0.6.0 (2023-07-16)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the argument :attr:`sort_keys` to the :meth:`omni.isaac.orbit.utils.io.yaml.dump_yaml` method to allow
enabling/disabling of sorting of keys in the output yaml file.
Fixed
^^^^^
* Fixed the ordering of terms in :mod:`omni.isaac.orbit.utils.configclass` to be consistent in the order in which
they are defined. Previously, the ordering was done alphabetically which made it inconsistent with the order in which
the parameters were defined.
Changed
^^^^^^^
* Changed the default value of the argument :attr:`sort_keys` in the :meth:`omni.isaac.orbit.utils.io.yaml.dump_yaml`
method to ``False``.
* Moved the old config classes in :mod:`omni.isaac.orbit.utils.configclass` to
:mod:`omni.isaac.orbit.compat.utils.configclass` so that users can still run their old code where alphabetical
ordering was used.
0.5.0 (2023-07-04)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a generalized :class:`omni.isaac.orbit.sensors.SensorBase` class that leverages the ideas of views to
handle multiple sensors in a single class.
* Added the classes :class:`omni.isaac.orbit.sensors.RayCaster`, :class:`omni.isaac.orbit.sensors.ContactSensor`,
and :class:`omni.isaac.orbit.sensors.Camera` that output a batched tensor of sensor data.
Changed
^^^^^^^
* Renamed the parameter ``sensor_tick`` to ``update_freq`` to make it more intuitive.
* Moved the old sensors in :mod:`omni.isaac.orbit.sensors` to :mod:`omni.isaac.orbit.compat.sensors`.
* Modified the standalone scripts to use the :mod:`omni.isaac.orbit.compat.sensors` module.
0.4.4 (2023-07-05)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.orbit.terrains.trimesh.utils.make_plane` method to handle the case when the
plane origin does not need to be centered.
* Added the :attr:`omni.isaac.orbit.terrains.TerrainGeneratorCfg.seed` to make generation of terrains reproducible.
The default value is ``None`` which means that the seed is not set.
Changed
^^^^^^^
* Changed the saving of ``origins`` in :class:`omni.isaac.orbit.terrains.TerrainGenerator` class to be in CSV format
instead of NPY format.
0.4.3 (2023-06-28)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.orbit.markers.PointInstancerMarker` class that wraps around
`UsdGeom.PointInstancer <https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html>`_
to directly work with torch and numpy arrays.
Changed
^^^^^^^
* Moved the old markers in :mod:`omni.isaac.orbit.markers` to :mod:`omni.isaac.orbit.compat.markers`.
* Modified the standalone scripts to use the :mod:`omni.isaac.orbit.compat.markers` module.
0.4.2 (2023-06-28)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the sub-module :mod:`omni.isaac.orbit.terrains` to allow procedural generation of terrains and supporting
importing of terrains from different sources (meshes, usd files or default ground plane).
0.4.1 (2023-06-27)
~~~~~~~~~~~~~~~~~~
* Added the :class:`omni.isaac.orbit.app.AppLauncher` class to allow controlled instantiation of
the `SimulationApp <https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.kit/docs/index.html>`_
and extension loading for remote deployment and ROS bridges.
Changed
^^^^^^^
* Modified all standalone scripts to use the :class:`omni.isaac.orbit.app.AppLauncher` class.
0.4.0 (2023-05-27)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a helper class :class:`omni.isaac.orbit.asset_loader.UrdfLoader` that converts a URDF file to instanceable USD
file based on the input configuration object.
0.3.2 (2023-04-27)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added safe-printing of functions while using the :meth:`omni.isaac.orbit.utils.dict.print_dict` function.
0.3.1 (2023-04-23)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a modified version of ``lula_franka_gen.urdf`` which includes an end-effector frame.
* Added a standalone script ``play_rmpflow.py`` to show RMPFlow controller.
Fixed
^^^^^
* Fixed the splitting of commands in the :meth:`ActuatorGroup.compute` method. Earlier it was reshaping the
commands to the shape ``(num_actuators, num_commands)`` which was causing the commands to be split incorrectly.
* Fixed the processing of actuator command in the :meth:`RobotBase._process_actuators_cfg` to deal with multiple
command types when using "implicit" actuator group.
0.3.0 (2023-04-20)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added the destructor to the keyboard devices to unsubscribe from carb.
Added
^^^^^
* Added the :class:`Se2Gamepad` and :class:`Se3Gamepad` for gamepad teleoperation support.
0.2.8 (2023-04-10)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed bugs in :meth:`axis_angle_from_quat` in the ``omni.isaac.orbit.utils.math`` to handle quaternion with negative w component.
* Fixed bugs in :meth:`subtract_frame_transforms` in the ``omni.isaac.orbit.utils.math`` by adding the missing final rotation.
0.2.7 (2023-04-07)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed repetition in applying mimic multiplier for "p_abs" in the :class:`GripperActuatorGroup` class.
* Fixed bugs in :meth:`reset_buffers` in the :class:`RobotBase` and :class:`LeggedRobot` classes.
0.2.6 (2023-03-16)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`CollisionPropertiesCfg` to rigid/articulated object and robot base classes.
* Added the :class:`PhysicsMaterialCfg` to the :class:`SingleArm` class for tool sites.
Changed
^^^^^^^
* Changed the default control mode of the :obj:`PANDA_HAND_MIMIC_GROUP_CFG` to be from ``"v_abs"`` to ``"p_abs"``.
Using velocity control for the mimic group can cause the hand to move in a jerky manner.
0.2.5 (2023-03-08)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the indices used for the Jacobian and dynamics quantities in the :class:`MobileManipulator` class.
0.2.4 (2023-03-04)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :meth:`apply_nested_physics_material` to the ``omni.isaac.orbit.utils.kit``.
* Added the :meth:`sample_cylinder` to sample points from a cylinder's surface.
* Added documentation about the issue in using instanceable asset as markers.
Fixed
^^^^^
* Simplified the physics material application in the rigid object and legged robot classes.
Removed
^^^^^^^
* Removed the ``geom_prim_rel_path`` argument in the :class:`RigidObjectCfg.MetaInfoCfg` class.
0.2.3 (2023-02-24)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the end-effector body index used for getting the Jacobian in the :class:`SingleArm` and :class:`MobileManipulator` classes.
0.2.2 (2023-01-27)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`set_world_pose_ros` and :meth:`set_world_pose_from_view` in the :class:`Camera` class.
Deprecated
^^^^^^^^^^
* Removed the :meth:`set_world_pose_from_ypr` method from the :class:`Camera` class.
0.2.1 (2023-01-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`Camera` class to support different fisheye projection types.
0.2.0 (2023-01-25)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for warp backend in camera utilities.
* Extended the ``play_camera.py`` with ``--gpu`` flag to use GPU replicator backend.
0.1.1 (2023-01-24)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed setting of physics material on the ground plane when using :meth:`omni.isaac.orbit.utils.kit.create_ground_plane` function.
0.1.0 (2023-01-17)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Initial release of the extension with experimental API.
* Available robot configurations:
* **Quadrupeds:** Unitree A1, ANYmal B, ANYmal C
* **Single-arm manipulators:** Franka Emika arm, UR5
* **Mobile manipulators:** Clearpath Ridgeback with Franka Emika arm or UR5
| 63,088 | reStructuredText | 29.820225 | 191 | 0.713337 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit/docs/README.md | # Orbit: Framework
Orbit includes its own set of interfaces and wrappers around Isaac Sim classes. One of the main goals behind this
decision is to have a unified description for different systems. While isaac Sim tries to be general for a wider
variety of simulation requires, our goal has been to specialize these for learning requirements. These include
features such as augmenting simulators with non-ideal actuator models, managing different observation and reward
settings, integrate different sensors, as well as provide interfaces to features that are currently not available in
Isaac Sim but are available from the physics side (such as deformable bodies).
We recommend the users to try out the demo scripts present in `standalone/demos` that display how different parts
of the framework can be integrated together.
| 827 | Markdown | 67.999994 | 116 | 0.822249 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/setup.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Installation script for the 'omni.isaac.orbit_assets' python package."""
import os
import toml
from setuptools import setup
# Obtain the extension data from the extension.toml file
EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__))
# Read the extension.toml file
EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml"))
# Installation operation
setup(
name="omni-isaac-orbit_assets",
author="ORBIT Project Developers",
maintainer="Mayank Mittal",
maintainer_email="[email protected]",
url=EXTENSION_TOML_DATA["package"]["repository"],
version=EXTENSION_TOML_DATA["package"]["version"],
description=EXTENSION_TOML_DATA["package"]["description"],
keywords=EXTENSION_TOML_DATA["package"]["keywords"],
include_package_data=True,
python_requires=">=3.10",
packages=["omni.isaac.orbit_assets"],
classifiers=[
"Natural Language :: English",
"Programming Language :: Python :: 3.10",
"Isaac Sim :: 2023.1.0-hotfix.1",
"Isaac Sim :: 2023.1.1",
],
zip_safe=False,
)
| 1,216 | Python | 30.205127 | 89 | 0.688322 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "0.1.2"
# Description
title = "ORBIT Assets"
description="Extension containing configuration instances of different assets and sensors"
readme = "docs/README.md"
repository = "https://github.com/NVIDIA-Omniverse/Orbit"
category = "robotics"
keywords = ["kit", "robotics", "assets", "orbit"]
[dependencies]
"omni.isaac.orbit" = {}
# Main python module this extension provides.
[[python.module]]
name = "omni.isaac.orbit_assets"
| 503 | TOML | 25.526314 | 90 | 0.73161 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/unitree.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for Unitree robots.
The following configurations are available:
* :obj:`UNITREE_A1_CFG`: Unitree A1 robot with DC motor model for the legs
* :obj:`UNITREE_GO1_CFG`: Unitree Go1 robot with actuator net model for the legs
* :obj:`UNITREE_GO2_CFG`: Unitree Go2 robot with DC motor model for the legs
Reference: https://github.com/unitreerobotics/unitree_ros
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ActuatorNetMLPCfg, DCMotorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
##
# Configuration - Actuators.
##
GO1_ACTUATOR_CFG = ActuatorNetMLPCfg(
joint_names_expr=[".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"],
network_file=f"{ISAAC_ORBIT_NUCLEUS_DIR}/ActuatorNets/Unitree/unitree_go1.pt",
pos_scale=-1.0,
vel_scale=1.0,
torque_scale=1.0,
input_order="pos_vel",
input_idx=[0, 1, 2],
effort_limit=23.7, # taken from spec sheet
velocity_limit=30.0, # taken from spec sheet
saturation_effort=23.7, # same as effort limit
)
"""Configuration of Go1 actuators using MLP model.
Actuator specifications: https://shop.unitree.com/products/go1-motor
This model is taken from: https://github.com/Improbable-AI/walk-these-ways
"""
##
# Configuration
##
UNITREE_A1_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Unitree/A1/a1.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.42),
joint_pos={
".*L_hip_joint": 0.1,
".*R_hip_joint": -0.1,
"F[L,R]_thigh_joint": 0.8,
"R[L,R]_thigh_joint": 1.0,
".*_calf_joint": -1.5,
},
joint_vel={".*": 0.0},
),
soft_joint_pos_limit_factor=0.9,
actuators={
"base_legs": DCMotorCfg(
joint_names_expr=[".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"],
effort_limit=33.5,
saturation_effort=33.5,
velocity_limit=21.0,
stiffness=25.0,
damping=0.5,
friction=0.0,
),
},
)
"""Configuration of Unitree A1 using DC motor.
Note: Specifications taken from: https://www.trossenrobotics.com/a1-quadruped#specifications
"""
UNITREE_GO1_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Unitree/Go1/go1.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.4),
joint_pos={
".*L_hip_joint": 0.1,
".*R_hip_joint": -0.1,
"F[L,R]_thigh_joint": 0.8,
"R[L,R]_thigh_joint": 1.0,
".*_calf_joint": -1.5,
},
joint_vel={".*": 0.0},
),
soft_joint_pos_limit_factor=0.9,
actuators={
"base_legs": GO1_ACTUATOR_CFG,
},
)
"""Configuration of Unitree Go1 using MLP-based actuator model."""
UNITREE_GO2_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Unitree/Go2/go2.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.4),
joint_pos={
".*L_hip_joint": 0.1,
".*R_hip_joint": -0.1,
"F[L,R]_thigh_joint": 0.8,
"R[L,R]_thigh_joint": 1.0,
".*_calf_joint": -1.5,
},
joint_vel={".*": 0.0},
),
soft_joint_pos_limit_factor=0.9,
actuators={
"base_legs": DCMotorCfg(
joint_names_expr=[".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"],
effort_limit=23.5,
saturation_effort=23.5,
velocity_limit=30.0,
stiffness=25.0,
damping=0.5,
friction=0.0,
),
},
)
"""Configuration of Unitree Go2 using DC-Motor actuator model."""
| 5,691 | Python | 31.340909 | 111 | 0.601652 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/shadow_hand.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the dexterous hand from Shadow Robot.
The following configurations are available:
* :obj:`SHADOW_HAND_CFG`: Shadow Hand with implicit actuator model.
Reference:
* https://www.shadowrobot.com/dexterous-hand-series/
"""
from __future__ import annotations
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators.actuator_cfg import ImplicitActuatorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
##
# Configuration
##
SHADOW_HAND_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/ShadowHand/shadow_hand_instanceable.usd",
activate_contact_sensors=False,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=True,
retain_accelerations=True,
max_depenetration_velocity=1000.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True,
solver_position_iteration_count=8,
solver_velocity_iteration_count=0,
sleep_threshold=0.005,
stabilization_threshold=0.0005,
),
# collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.005, rest_offset=0.0),
joint_drive_props=sim_utils.JointDrivePropertiesCfg(drive_type="force"),
fixed_tendons_props=sim_utils.FixedTendonPropertiesCfg(limit_stiffness=30.0, damping=0.1),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.5),
rot=(0.0, 0.0, -0.7071, 0.7071),
joint_pos={".*": 0.0},
),
actuators={
"fingers": ImplicitActuatorCfg(
joint_names_expr=["robot0_WR.*", "robot0_(FF|MF|RF|LF|TH)J(3|2|1)", "robot0_(LF|TH)J4", "robot0_THJ0"],
effort_limit={
"robot0_WRJ1": 4.785,
"robot0_WRJ0": 2.175,
"robot0_(FF|MF|RF|LF)J1": 0.7245,
"robot0_FFJ(3|2)": 0.9,
"robot0_MFJ(3|2)": 0.9,
"robot0_RFJ(3|2)": 0.9,
"robot0_LFJ(4|3|2)": 0.9,
"robot0_THJ4": 2.3722,
"robot0_THJ3": 1.45,
"robot0_THJ(2|1)": 0.99,
"robot0_THJ0": 0.81,
},
stiffness={
"robot0_WRJ.*": 5.0,
"robot0_(FF|MF|RF|LF|TH)J(3|2|1)": 1.0,
"robot0_(LF|TH)J4": 1.0,
"robot0_THJ0": 1.0,
},
damping={
"robot0_WRJ.*": 0.5,
"robot0_(FF|MF|RF|LF|TH)J(3|2|1)": 0.1,
"robot0_(LF|TH)J4": 0.1,
"robot0_THJ0": 0.1,
},
),
},
soft_joint_pos_limit_factor=1.0,
)
"""Configuration of Shadow Hand robot."""
| 2,953 | Python | 32.954023 | 115 | 0.573315 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/sawyer.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the Rethink Robotics arms.
The following configuration parameters are available:
* :obj:`SAWYER_CFG`: The Sawyer arm without any tool attached.
Reference: https://github.com/RethinkRobotics/sawyer_robot
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
##
# Configuration
##
SAWYER_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/RethinkRobotics/sawyer_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=5.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=8, solver_velocity_iteration_count=0
),
activate_contact_sensors=False,
),
init_state=ArticulationCfg.InitialStateCfg(
joint_pos={
"head_pan": 0.0,
"right_j0": 0.0,
"right_j1": -0.785,
"right_j2": 0.0,
"right_j3": 1.05,
"right_j4": 0.0,
"right_j5": 1.3,
"right_j6": 0.0,
},
),
actuators={
"head": ImplicitActuatorCfg(
joint_names_expr=["head_pan"],
velocity_limit=100.0,
effort_limit=8.0,
stiffness=800.0,
damping=40.0,
),
"arm": ImplicitActuatorCfg(
joint_names_expr=["right_j[0-6]"],
velocity_limit=100.0,
effort_limit={
"right_j[0-1]": 80.0,
"right_j[2-3]": 40.0,
"right_j[4-6]": 9.0,
},
stiffness=100.0,
damping=4.0,
),
},
)
"""Configuration of Rethink Robotics Sawyer arm."""
| 2,083 | Python | 27.944444 | 110 | 0.590494 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES, ETH Zurich, and University of Toronto
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Package containing asset and sensor configurations."""
import os
import toml
# Conveniences to other module directories via relative paths
ORBIT_ASSETS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
"""Path to the extension source directory."""
ORBIT_ASSETS_DATA_DIR = os.path.join(ORBIT_ASSETS_EXT_DIR, "data")
"""Path to the extension data directory."""
ORBIT_ASSETS_METADATA = toml.load(os.path.join(ORBIT_ASSETS_EXT_DIR, "config", "extension.toml"))
"""Extension metadata dictionary parsed from the extension.toml file."""
# Configure the module-level variables
__version__ = ORBIT_ASSETS_METADATA["package"]["version"]
##
# Configuration for different assets.
##
from .allegro import *
from .anymal import *
from .cartpole import *
from .franka import *
from .kinova import *
from .ridgeback_franka import *
from .sawyer import *
from .shadow_hand import *
from .unitree import *
from .universal_robots import *
| 1,243 | Python | 27.272727 | 97 | 0.736122 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/ridgeback_franka.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the Ridgeback-Manipulation robots.
The following configurations are available:
* :obj:`RIDGEBACK_FRANKA_PANDA_CFG`: Clearpath Ridgeback base with Franka Emika arm
Reference: https://github.com/ridgeback/ridgeback_manipulation
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
RIDGEBACK_FRANKA_PANDA_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Clearpath/RidgebackFranka/ridgeback_franka.usd",
activate_contact_sensors=False,
),
init_state=ArticulationCfg.InitialStateCfg(
joint_pos={
# base
"dummy_base_prismatic_y_joint": 0.0,
"dummy_base_prismatic_x_joint": 0.0,
"dummy_base_revolute_z_joint": 0.0,
# franka arm
"panda_joint1": 0.0,
"panda_joint2": -0.569,
"panda_joint3": 0.0,
"panda_joint4": -2.810,
"panda_joint5": 0.0,
"panda_joint6": 3.037,
"panda_joint7": 0.741,
# tool
"panda_finger_joint.*": 0.035,
},
joint_vel={".*": 0.0},
),
actuators={
"base": ImplicitActuatorCfg(
joint_names_expr=["dummy_base_.*"],
velocity_limit=100.0,
effort_limit=1000.0,
stiffness=0.0,
damping=1e5,
),
"panda_shoulder": ImplicitActuatorCfg(
joint_names_expr=["panda_joint[1-4]"],
effort_limit=87.0,
velocity_limit=100.0,
stiffness=800.0,
damping=40.0,
),
"panda_forearm": ImplicitActuatorCfg(
joint_names_expr=["panda_joint[5-7]"],
effort_limit=12.0,
velocity_limit=100.0,
stiffness=800.0,
damping=40.0,
),
"panda_hand": ImplicitActuatorCfg(
joint_names_expr=["panda_finger_joint.*"],
effort_limit=200.0,
velocity_limit=0.2,
stiffness=1e5,
damping=1e3,
),
},
)
"""Configuration of Franka arm with Franka Hand on a Clearpath Ridgeback base using implicit actuator models.
The following control configuration is used:
* Base: velocity control with damping
* Arm: position control with damping (contains default position offsets)
* Hand: mimic control
"""
| 2,651 | Python | 30.571428 | 109 | 0.599774 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/cassie.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for Agility robots.
The following configurations are available:
* :obj:`CASSIE_CFG`: Agility Cassie robot with simple PD controller for the legs
Reference: https://github.com/UMich-BipedLab/Cassie_Model/blob/master/urdf/cassie.urdf
"""
from __future__ import annotations
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
##
# Configuration
##
CASSIE_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Agility/Cassie/cassie.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.9),
joint_pos={
"hip_abduction_left": 0.1,
"hip_rotation_left": 0.0,
"hip_flexion_left": 1.0,
"thigh_joint_left": -1.8,
"ankle_joint_left": 1.57,
"toe_joint_left": -1.57,
"hip_abduction_right": -0.1,
"hip_rotation_right": 0.0,
"hip_flexion_right": 1.0,
"thigh_joint_right": -1.8,
"ankle_joint_right": 1.57,
"toe_joint_right": -1.57,
},
joint_vel={".*": 0.0},
),
soft_joint_pos_limit_factor=0.9,
actuators={
"legs": ImplicitActuatorCfg(
joint_names_expr=["hip_.*", "thigh_.*", "ankle_.*"],
effort_limit=200.0,
velocity_limit=10.0,
stiffness={
"hip_abduction.*": 100.0,
"hip_rotation.*": 100.0,
"hip_flexion.*": 200.0,
"thigh_joint.*": 200.0,
"ankle_joint.*": 200.0,
},
damping={
"hip_abduction.*": 3.0,
"hip_rotation.*": 3.0,
"hip_flexion.*": 6.0,
"thigh_joint.*": 6.0,
"ankle_joint.*": 6.0,
},
),
"toes": ImplicitActuatorCfg(
joint_names_expr=["toe_.*"],
effort_limit=20.0,
velocity_limit=10.0,
stiffness={
"toe_joint.*": 20.0,
},
damping={
"toe_joint.*": 1.0,
},
),
},
)
| 3,001 | Python | 30.270833 | 110 | 0.54082 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/universal_robots.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the Universal Robots.
The following configuration parameters are available:
* :obj:`UR10_CFG`: The UR10 arm without a gripper.
Reference: https://github.com/ros-industrial/universal_robot
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
##
# Configuration
##
UR10_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/UniversalRobots/UR10/ur10_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=5.0,
),
activate_contact_sensors=False,
),
init_state=ArticulationCfg.InitialStateCfg(
joint_pos={
"shoulder_pan_joint": 0.0,
"shoulder_lift_joint": -1.712,
"elbow_joint": 1.712,
"wrist_1_joint": 0.0,
"wrist_2_joint": 0.0,
"wrist_3_joint": 0.0,
},
),
actuators={
"arm": ImplicitActuatorCfg(
joint_names_expr=[".*"],
velocity_limit=100.0,
effort_limit=87.0,
stiffness=800.0,
damping=40.0,
),
},
)
"""Configuration of UR-10 arm using implicit actuator models."""
| 1,542 | Python | 27.054545 | 96 | 0.637484 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/franka.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the Franka Emika robots.
The following configurations are available:
* :obj:`FRANKA_PANDA_CFG`: Franka Emika Panda robot with Panda hand
* :obj:`FRANKA_PANDA_HIGH_PD_CFG`: Franka Emika Panda robot with Panda hand with stiffer PD control
Reference: https://github.com/frankaemika/franka_ros
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
##
# Configuration
##
FRANKA_PANDA_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/FrankaEmika/panda_instanceable.usd",
activate_contact_sensors=False,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=5.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=8, solver_velocity_iteration_count=0
),
# collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.005, rest_offset=0.0),
),
init_state=ArticulationCfg.InitialStateCfg(
joint_pos={
"panda_joint1": 0.0,
"panda_joint2": -0.569,
"panda_joint3": 0.0,
"panda_joint4": -2.810,
"panda_joint5": 0.0,
"panda_joint6": 3.037,
"panda_joint7": 0.741,
"panda_finger_joint.*": 0.04,
},
),
actuators={
"panda_shoulder": ImplicitActuatorCfg(
joint_names_expr=["panda_joint[1-4]"],
effort_limit=87.0,
velocity_limit=2.175,
stiffness=80.0,
damping=4.0,
),
"panda_forearm": ImplicitActuatorCfg(
joint_names_expr=["panda_joint[5-7]"],
effort_limit=12.0,
velocity_limit=2.61,
stiffness=80.0,
damping=4.0,
),
"panda_hand": ImplicitActuatorCfg(
joint_names_expr=["panda_finger_joint.*"],
effort_limit=200.0,
velocity_limit=0.2,
stiffness=2e3,
damping=1e2,
),
},
soft_joint_pos_limit_factor=1.0,
)
"""Configuration of Franka Emika Panda robot."""
FRANKA_PANDA_HIGH_PD_CFG = FRANKA_PANDA_CFG.copy()
FRANKA_PANDA_HIGH_PD_CFG.spawn.rigid_props.disable_gravity = True
FRANKA_PANDA_HIGH_PD_CFG.actuators["panda_shoulder"].stiffness = 400.0
FRANKA_PANDA_HIGH_PD_CFG.actuators["panda_shoulder"].damping = 80.0
FRANKA_PANDA_HIGH_PD_CFG.actuators["panda_forearm"].stiffness = 400.0
FRANKA_PANDA_HIGH_PD_CFG.actuators["panda_forearm"].damping = 80.0
"""Configuration of Franka Emika Panda robot with stiffer PD control.
This configuration is useful for task-space control using differential IK.
"""
| 3,036 | Python | 33.511363 | 110 | 0.64888 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/cartpole.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for a simple Cartpole robot."""
from __future__ import annotations
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
CARTPOLE_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Classic/Cartpole/cartpole.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
rigid_body_enabled=True,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=100.0,
enable_gyroscopic_forces=True,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False,
solver_position_iteration_count=4,
solver_velocity_iteration_count=0,
sleep_threshold=0.005,
stabilization_threshold=0.001,
),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 2.0), joint_pos={"slider_to_cart": 0.0, "cart_to_pole": 0.0}
),
actuators={
"cart_actuator": ImplicitActuatorCfg(
joint_names_expr=["slider_to_cart"],
effort_limit=400.0,
velocity_limit=100.0,
stiffness=0.0,
damping=10.0,
),
"pole_actuator": ImplicitActuatorCfg(
joint_names_expr=["cart_to_pole"], effort_limit=400.0, velocity_limit=100.0, stiffness=0.0, damping=0.0
),
},
)
| 1,711 | Python | 33.938775 | 115 | 0.641146 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/allegro.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the Allegro Hand robots from Wonik Robotics.
The following configurations are available:
* :obj:`ALLEGRO_HAND_CFG`: Allegro Hand with implicit actuator model.
Reference:
* https://www.wonikrobotics.com/robot-hand
"""
from __future__ import annotations
import math
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators.actuator_cfg import ImplicitActuatorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
##
# Configuration
##
ALLEGRO_HAND_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/AllegroHand/allegro_hand_instanceable.usd",
activate_contact_sensors=False,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=True,
retain_accelerations=False,
enable_gyroscopic_forces=False,
angular_damping=0.01,
max_linear_velocity=1000.0,
max_angular_velocity=64 / math.pi * 180.0,
max_depenetration_velocity=1000.0,
max_contact_impulse=1e32,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True,
solver_position_iteration_count=8,
solver_velocity_iteration_count=0,
sleep_threshold=0.005,
stabilization_threshold=0.0005,
),
# collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.005, rest_offset=0.0),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.5),
rot=(0.257551, 0.283045, 0.683330, -0.621782),
joint_pos={"^(?!thumb_joint_0).*": 0.0, "thumb_joint_0": 0.28},
),
actuators={
"fingers": ImplicitActuatorCfg(
joint_names_expr=[".*"],
effort_limit=0.5,
velocity_limit=100.0,
stiffness=3.0,
damping=0.1,
friction=0.01,
),
},
soft_joint_pos_limit_factor=1.0,
)
"""Configuration of Allegro Hand robot."""
| 2,220 | Python | 29.847222 | 98 | 0.647748 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/kinova.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the Kinova Robotics arms.
The following configuration parameters are available:
* :obj:`KINOVA_JACO2_N7S300_CFG`: The Kinova JACO2 (7-Dof) arm with a 3-finger gripper.
* :obj:`KINOVA_JACO2_N6S300_CFG`: The Kinova JACO2 (6-Dof) arm with a 3-finger gripper.
* :obj:`KINOVA_GEN3_N7_CFG`: The Kinova Gen3 (7-Dof) arm with no gripper.
Reference: https://github.com/Kinovarobotics/kinova-ros
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
##
# Configuration
##
KINOVA_JACO2_N7S300_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Kinova/Jaco2/J2N7S300/j2n7s300_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=5.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=8, solver_velocity_iteration_count=0
),
activate_contact_sensors=False,
),
init_state=ArticulationCfg.InitialStateCfg(
joint_pos={
"j2n7s300_joint_1": 0.0,
"j2n7s300_joint_2": 2.76,
"j2n7s300_joint_3": 0.0,
"j2n7s300_joint_4": 2.0,
"j2n7s300_joint_5": 2.0,
"j2n7s300_joint_6": 0.0,
"j2n7s300_joint_7": 0.0,
"j2n7s300_joint_finger_[1-3]": 0.2, # close: 1.2, open: 0.2
"j2n7s300_joint_finger_tip_[1-3]": 0.2, # close: 1.2, open: 0.2
},
),
actuators={
"arm": ImplicitActuatorCfg(
joint_names_expr=[".*_joint_[1-7]"],
velocity_limit=100.0,
effort_limit={
".*_joint_[1-2]": 80.0,
".*_joint_[3-4]": 40.0,
".*_joint_[5-7]": 20.0,
},
stiffness={
".*_joint_[1-4]": 40.0,
".*_joint_[5-7]": 15.0,
},
damping={
".*_joint_[1-4]": 1.0,
".*_joint_[5-7]": 0.5,
},
),
"gripper": ImplicitActuatorCfg(
joint_names_expr=[".*_finger_[1-3]", ".*_finger_tip_[1-3]"],
velocity_limit=100.0,
effort_limit=2.0,
stiffness=1.2,
damping=0.01,
),
},
)
"""Configuration of Kinova JACO2 (7-Dof) arm with 3-finger gripper."""
KINOVA_JACO2_N6S300_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Kinova/Jaco2/J2N6S300/j2n6s300_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=5.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=8, solver_velocity_iteration_count=0
),
activate_contact_sensors=False,
),
init_state=ArticulationCfg.InitialStateCfg(
joint_pos={
"j2n6s300_joint_1": 0.0,
"j2n6s300_joint_2": 2.76,
"j2n6s300_joint_3": 2.76,
"j2n6s300_joint_4": 2.5,
"j2n6s300_joint_5": 2.0,
"j2n6s300_joint_6": 0.0,
"j2n6s300_joint_finger_[1-3]": 0.2, # close: 1.2, open: 0.2
"j2n6s300_joint_finger_tip_[1-3]": 0.2, # close: 1.2, open: 0.2
},
),
actuators={
"arm": ImplicitActuatorCfg(
joint_names_expr=[".*_joint_[1-6]"],
velocity_limit=100.0,
effort_limit={
".*_joint_[1-2]": 80.0,
".*_joint_3": 40.0,
".*_joint_[4-6]": 20.0,
},
stiffness={
".*_joint_[1-3]": 40.0,
".*_joint_[4-6]": 15.0,
},
damping={
".*_joint_[1-3]": 1.0,
".*_joint_[4-6]": 0.5,
},
),
"gripper": ImplicitActuatorCfg(
joint_names_expr=[".*_finger_[1-3]", ".*_finger_tip_[1-3]"],
velocity_limit=100.0,
effort_limit=2.0,
stiffness=1.2,
damping=0.01,
),
},
)
"""Configuration of Kinova JACO2 (6-Dof) arm with 3-finger gripper."""
KINOVA_GEN3_N7_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Kinova/Gen3/gen3n7_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=5.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=8, solver_velocity_iteration_count=0
),
activate_contact_sensors=False,
),
init_state=ArticulationCfg.InitialStateCfg(
joint_pos={
"joint_1": 0.0,
"joint_2": 0.65,
"joint_3": 0.0,
"joint_4": 1.89,
"joint_5": 0.0,
"joint_6": 0.6,
"joint_7": -1.57,
},
),
actuators={
"arm": ImplicitActuatorCfg(
joint_names_expr=["joint_[1-7]"],
velocity_limit=100.0,
effort_limit={
"joint_[1-4]": 39.0,
"joint_[5-7]": 9.0,
},
stiffness={
"joint_[1-4]": 40.0,
"joint_[5-7]": 15.0,
},
damping={
"joint_[1-4]": 1.0,
"joint_[5-7]": 0.5,
},
),
},
)
"""Configuration of Kinova Gen3 (7-Dof) arm with no gripper."""
| 5,949 | Python | 32.055555 | 110 | 0.525971 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/anymal.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the ANYbotics robots.
The following configuration parameters are available:
* :obj:`ANYMAL_B_CFG`: The ANYmal-B robot with ANYdrives 3.0
* :obj:`ANYMAL_C_CFG`: The ANYmal-C robot with ANYdrives 3.0
* :obj:`ANYMAL_D_CFG`: The ANYmal-D robot with ANYdrives 3.0
Reference:
* https://github.com/ANYbotics/anymal_b_simple_description
* https://github.com/ANYbotics/anymal_c_simple_description
* https://github.com/ANYbotics/anymal_d_simple_description
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ActuatorNetLSTMCfg, DCMotorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
##
# Configuration - Actuators.
##
ANYDRIVE_3_SIMPLE_ACTUATOR_CFG = DCMotorCfg(
joint_names_expr=[".*HAA", ".*HFE", ".*KFE"],
saturation_effort=120.0,
effort_limit=80.0,
velocity_limit=7.5,
stiffness={".*": 40.0},
damping={".*": 5.0},
)
"""Configuration for ANYdrive 3.x with DC actuator model."""
ANYDRIVE_3_LSTM_ACTUATOR_CFG = ActuatorNetLSTMCfg(
joint_names_expr=[".*HAA", ".*HFE", ".*KFE"],
network_file=f"{ISAAC_ORBIT_NUCLEUS_DIR}/ActuatorNets/ANYbotics/anydrive_3_lstm_jit.pt",
saturation_effort=120.0,
effort_limit=80.0,
velocity_limit=7.5,
)
"""Configuration for ANYdrive 3.0 (used on ANYmal-C) with LSTM actuator model."""
##
# Configuration - Articulation.
##
ANYMAL_B_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-B/anymal_b.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
# collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.02, rest_offset=0.0),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.6),
joint_pos={
".*HAA": 0.0, # all HAA
".*F_HFE": 0.4, # both front HFE
".*H_HFE": -0.4, # both hind HFE
".*F_KFE": -0.8, # both front KFE
".*H_KFE": 0.8, # both hind KFE
},
),
actuators={"legs": ANYDRIVE_3_LSTM_ACTUATOR_CFG},
soft_joint_pos_limit_factor=0.95,
)
"""Configuration of ANYmal-B robot using actuator-net."""
ANYMAL_C_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-C/anymal_c.usd",
# usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/ANYbotics/anymal_instanceable.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
# collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.02, rest_offset=0.0),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.6),
joint_pos={
".*HAA": 0.0, # all HAA
".*F_HFE": 0.4, # both front HFE
".*H_HFE": -0.4, # both hind HFE
".*F_KFE": -0.8, # both front KFE
".*H_KFE": 0.8, # both hind KFE
},
),
actuators={"legs": ANYDRIVE_3_LSTM_ACTUATOR_CFG},
soft_joint_pos_limit_factor=0.95,
)
"""Configuration of ANYmal-C robot using actuator-net."""
ANYMAL_D_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-D/anymal_d.usd",
# usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/ANYbotics/ANYmal-D/anymal_d_minimal.usd",
activate_contact_sensors=True,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=1000.0,
max_angular_velocity=1000.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
# collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.02, rest_offset=0.0),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.6),
joint_pos={
".*HAA": 0.0, # all HAA
".*F_HFE": 0.4, # both front HFE
".*H_HFE": -0.4, # both hind HFE
".*F_KFE": -0.8, # both front KFE
".*H_KFE": 0.8, # both hind KFE
},
),
actuators={"legs": ANYDRIVE_3_LSTM_ACTUATOR_CFG},
soft_joint_pos_limit_factor=0.95,
)
"""Configuration of ANYmal-D robot using actuator-net.
Note:
Since we don't have a publicly available actuator network for ANYmal-D, we use the same network as ANYmal-C.
This may impact the sim-to-real transfer performance.
"""
| 5,833 | Python | 34.791411 | 112 | 0.633636 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/docs/CHANGELOG.rst | Changelog
---------
0.1.2 (2024-04-03)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added configurations for different arms from Kinova Robotics and Rethink Robotics.
0.1.1 (2024-03-11)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added configurations for allegro and shadow hand assets.
0.1.0 (2023-12-20)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Moved all assets' configuration from ``omni.isaac.orbit`` to ``omni.isaac.orbit_assets`` extension.
| 427 | reStructuredText | 13.75862 | 101 | 0.590164 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_assets/docs/README.md | # Orbit: Assets for Robots and Objects
This extension contains configurations for various assets and sensors. The configuration instances are
used to spawn and configure the instances in the simulation. They are passed to their corresponding
classes during construction.
## Organizing custom assets
For Orbit, we primarily store assets on the Omniverse Nucleus server. However, at times, it may be
needed to store the assets locally (for debugging purposes). In such cases, the extension's `data`
directory can be used for temporary hosting of assets.
Inside the `data` directory, we recommend following the same structure as our Nucleus directory
`Isaac/Samples/Orbit`. This helps us later to move these assets to the Nucleus server seamlessly.
The recommended directory structure inside `data` is as follows:
* **`Robots/<Company-Name>/<Robot-Name>`**: The USD files should be inside `<Robot-Name>` directory with
the name of the robot.
* **`Props/<Prop-Type>/<Prop-Name>`**: The USD files should be inside `<Prop-Name>` directory with the name
of the prop. This includes mounts, objects and markers.
* **`ActuatorNets/<Company-Name>`**: The actuator networks should inside `<Company-Name` directory with the
name of the actuator that it models.
* **`Policies/<Task-Name>`**: The policy should be JIT/ONNX compiled with the name `policy.pt`. It should also
contain the parameters used for training the checkpoint. This is to ensure reproducibility.
* **`Test/<Test-Name>`**: The asset used for unit testing purposes.
## Referring to the assets in your code
You can use the following snippet to refer to the assets:
```python
from omni.isaac.orbit_assets import ORBIT_ASSETS_DATA_DIR
# ANYmal-C
ANYMAL_C_USD_PATH = f"{ORBIT_ASSETS_DATA_DIR}/Robots/ANYbotics/ANYmal-C/anymal_c.usd"
# ANYmal-D
ANYMAL_D_USD_PATH = f"{ORBIT_ASSETS_DATA_DIR}/Robots/ANYbotics/ANYmal-D/anymal_d.usd"
```
| 1,903 | Markdown | 44.333332 | 110 | 0.763531 |
NVIDIA-Omniverse/orbit/source/standalone/tools/convert_mesh.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Utility to convert a OBJ/STL/FBX into USD format.
The OBJ file format is a simple data-format that represents 3D geometry alone — namely, the position
of each vertex, the UV position of each texture coordinate vertex, vertex normals, and the faces that
make each polygon defined as a list of vertices, and texture vertices.
An STL file describes a raw, unstructured triangulated surface by the unit normal and vertices (ordered
by the right-hand rule) of the triangles using a three-dimensional Cartesian coordinate system.
FBX files are a type of 3D model file created using the Autodesk FBX software. They can be designed and
modified in various modeling applications, such as Maya, 3ds Max, and Blender. Moreover, FBX files typically
contain mesh, material, texture, and skeletal animation data.
Link: https://www.autodesk.com/products/fbx/overview
This script uses the asset converter extension from Isaac Sim (``omni.kit.asset_converter``) to convert a
OBJ/STL/FBX asset into USD format. It is designed as a convenience script for command-line use.
positional arguments:
input The path to the input mesh (.OBJ/.STL/.FBX) file.
output The path to store the USD file.
optional arguments:
-h, --help Show this help message and exit
--make-instanceable, Make the asset instanceable for efficient cloning. (default: False)
--collision-approximation The method used for approximating collision mesh. Defaults to convexDecomposition.
Set to \"none\" to not add a collision mesh to the converted mesh. (default: convexDecomposition)
--mass The mass (in kg) to assign to the converted asset. (default: None)
"""
"""Launch Isaac Sim Simulator first."""
import argparse
from omni.isaac.orbit.app import AppLauncher
# add argparse arguments
parser = argparse.ArgumentParser(description="Utility to convert a mesh file into USD format.")
parser.add_argument("input", type=str, help="The path to the input mesh file.")
parser.add_argument("output", type=str, help="The path to store the USD file.")
parser.add_argument(
"--make-instanceable",
action="store_true",
default=False,
help="Make the asset instanceable for efficient cloning.",
)
parser.add_argument(
"--collision-approximation",
type=str,
default="convexDecomposition",
choices=["convexDecomposition", "convexHull", "none"],
help=(
'The method used for approximating collision mesh. Set to "none" '
"to not add a collision mesh to the converted mesh."
),
)
parser.add_argument(
"--mass",
type=float,
default=None,
help="The mass (in kg) to assign to the converted asset. If not provided, then no mass is added.",
)
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
# parse the arguments
args_cli = parser.parse_args()
# launch omniverse app
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
"""Rest everything follows."""
import contextlib
import os
import carb
import omni.isaac.core.utils.stage as stage_utils
import omni.kit.app
from omni.isaac.orbit.sim.converters import MeshConverter, MeshConverterCfg
from omni.isaac.orbit.sim.schemas import schemas_cfg
from omni.isaac.orbit.utils.assets import check_file_path
from omni.isaac.orbit.utils.dict import print_dict
def main():
# check valid file path
mesh_path = args_cli.input
if not os.path.isabs(mesh_path):
mesh_path = os.path.abspath(mesh_path)
if not check_file_path(mesh_path):
raise ValueError(f"Invalid mesh file path: {mesh_path}")
# create destination path
dest_path = args_cli.output
if not os.path.isabs(dest_path):
dest_path = os.path.abspath(dest_path)
print(dest_path)
print(os.path.dirname(dest_path))
print(os.path.basename(dest_path))
# Mass properties
if args_cli.mass is not None:
mass_props = schemas_cfg.MassPropertiesCfg(mass=args_cli.mass)
rigid_props = schemas_cfg.RigidBodyPropertiesCfg()
else:
mass_props = None
rigid_props = None
# Collision properties
collision_props = schemas_cfg.CollisionPropertiesCfg(collision_enabled=args_cli.collision_approximation != "none")
# Create Mesh converter config
mesh_converter_cfg = MeshConverterCfg(
mass_props=mass_props,
rigid_props=rigid_props,
collision_props=collision_props,
asset_path=mesh_path,
force_usd_conversion=True,
usd_dir=os.path.dirname(dest_path),
usd_file_name=os.path.basename(dest_path),
make_instanceable=args_cli.make_instanceable,
collision_approximation=args_cli.collision_approximation,
)
# Print info
print("-" * 80)
print("-" * 80)
print(f"Input Mesh file: {mesh_path}")
print("Mesh importer config:")
print_dict(mesh_converter_cfg.to_dict(), nesting=0)
print("-" * 80)
print("-" * 80)
# Create Mesh converter and import the file
mesh_converter = MeshConverter(mesh_converter_cfg)
# print output
print("Mesh importer output:")
print(f"Generated USD file: {mesh_converter.usd_path}")
print("-" * 80)
print("-" * 80)
# Determine if there is a GUI to update:
# acquire settings interface
carb_settings_iface = carb.settings.get_settings()
# read flag for whether a local GUI is enabled
local_gui = carb_settings_iface.get("/app/window/enabled")
# read flag for whether livestreaming GUI is enabled
livestream_gui = carb_settings_iface.get("/app/livestream/enabled")
# Simulate scene (if not headless)
if local_gui or livestream_gui:
# Open the stage with USD
stage_utils.open_stage(mesh_converter.usd_path)
# Reinitialize the simulation
app = omni.kit.app.get_app_interface()
# Run simulation
with contextlib.suppress(KeyboardInterrupt):
while app.is_running():
# perform step
app.update()
if __name__ == "__main__":
# run the main function
main()
# close sim app
simulation_app.close()
| 6,290 | Python | 33.95 | 129 | 0.692846 |
NVIDIA-Omniverse/orbit/source/standalone/tools/check_instanceable.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
This script uses the cloner API to check if asset has been instanced properly.
Usage with different inputs (replace `<Asset-Path>` and `<Asset-Path-Instanced>` with the path to the
original asset and the instanced asset respectively):
```bash
./orbit.sh -p source/tools/check_instanceable.py <Asset-Path> -n 4096 --headless --physics
./orbit.sh -p source/tools/check_instanceable.py <Asset-Path-Instanced> -n 4096 --headless --physics
./orbit.sh -p source/tools/check_instanceable.py <Asset-Path> -n 4096 --headless
./orbit.sh -p source/tools/check_instanceable.py <Asset-Path-Instanced> -n 4096 --headless
```
Output from the above commands:
```bash
>>> Cloning time (cloner.clone): 0.648198 seconds
>>> Setup time (sim.reset): : 5.843589 seconds
[#clones: 4096, physics: True] Asset: <Asset-Path-Instanced> : 6.491870 seconds
>>> Cloning time (cloner.clone): 0.693133 seconds
>>> Setup time (sim.reset): 50.860526 seconds
[#clones: 4096, physics: True] Asset: <Asset-Path> : 51.553743 seconds
>>> Cloning time (cloner.clone) : 0.687201 seconds
>>> Setup time (sim.reset) : 6.302215 seconds
[#clones: 4096, physics: False] Asset: <Asset-Path-Instanced> : 6.989500 seconds
>>> Cloning time (cloner.clone) : 0.678150 seconds
>>> Setup time (sim.reset) : 52.854054 seconds
[#clones: 4096, physics: False] Asset: <Asset-Path> : 53.532287 seconds
```
"""
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import argparse
import contextlib
import os
# omni-isaac-orbit
from omni.isaac.orbit.app import AppLauncher
# add argparse arguments
parser = argparse.ArgumentParser("Utility to empirically check if asset in instanced properly.")
parser.add_argument("input", type=str, help="The path to the USD file.")
parser.add_argument("-n", "--num_clones", type=int, default=128, help="Number of clones to spawn.")
parser.add_argument("-s", "--spacing", type=float, default=1.5, help="Spacing between instances in a grid.")
parser.add_argument("-p", "--physics", action="store_true", default=False, help="Clone assets using physics cloner.")
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
# parse the arguments
args_cli = parser.parse_args()
# launch omniverse app
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
"""Rest everything follows."""
import omni.isaac.core.utils.prims as prim_utils
from omni.isaac.cloner import GridCloner
from omni.isaac.core.simulation_context import SimulationContext
from omni.isaac.core.utils.carb import set_carb_setting
from omni.isaac.orbit.utils import Timer
from omni.isaac.orbit.utils.assets import check_file_path
def main():
"""Spawns the USD asset robot and clones it using Isaac Gym Cloner API."""
# check valid file path
if not check_file_path(args_cli.input):
raise ValueError(f"Invalid file path: {args_cli.input}")
# Load kit helper
sim = SimulationContext(
stage_units_in_meters=1.0, physics_dt=0.01, rendering_dt=0.01, backend="torch", device="cuda:0"
)
# enable flatcache which avoids passing data over to USD structure
# this speeds up the read-write operation of GPU buffers
if sim.get_physics_context().use_gpu_pipeline:
sim.get_physics_context().enable_flatcache(True)
# enable hydra scene-graph instancing
# this is needed to visualize the scene when flatcache is enabled
set_carb_setting(sim._settings, "/persistent/omnihydra/useSceneGraphInstancing", True)
# Create interface to clone the scene
cloner = GridCloner(spacing=args_cli.spacing)
cloner.define_base_env("/World/envs")
prim_utils.define_prim("/World/envs/env_0")
# Spawn things into stage
prim_utils.create_prim("/World/Light", "DistantLight")
# Everything under the namespace "/World/envs/env_0" will be cloned
prim_utils.create_prim("/World/envs/env_0/Asset", "Xform", usd_path=os.path.abspath(args_cli.input))
# Clone the scene
num_clones = args_cli.num_clones
# Create a timer to measure the cloning time
with Timer(f"[#clones: {num_clones}, physics: {args_cli.physics}] Asset: {args_cli.input}"):
# Clone the scene
with Timer(">>> Cloning time (cloner.clone)"):
cloner.define_base_env("/World/envs")
envs_prim_paths = cloner.generate_paths("/World/envs/env", num_paths=num_clones)
_ = cloner.clone(
source_prim_path="/World/envs/env_0", prim_paths=envs_prim_paths, replicate_physics=args_cli.physics
)
# Play the simulator
with Timer(">>> Setup time (sim.reset)"):
sim.reset()
# Simulate scene (if not headless)
if not args_cli.headless:
with contextlib.suppress(KeyboardInterrupt):
while sim.is_playing():
# perform step
sim.step()
if __name__ == "__main__":
# run the main function
main()
# close sim app
simulation_app.close()
| 5,076 | Python | 36.607407 | 117 | 0.6974 |
NVIDIA-Omniverse/orbit/source/standalone/tools/blender_obj.py | #!/usr/bin/env python
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Convert a mesh file to `.obj` using blender.
This file processes a given dae mesh file and saves the resulting mesh file in obj format.
It needs to be called using the python packaged with blender, i.e.:
blender --background --python blender_obj.py -- -in_file FILE -out_file FILE
For more information: https://docs.blender.org/api/current/index.html
The script was tested on Blender 3.2 on Ubuntu 20.04LTS.
"""
from __future__ import annotations
import bpy
import os
import sys
def parse_cli_args():
"""Parse the input command line arguments.
Reference: https://developer.blender.org/diffusion/B/browse/master/release/scripts/templates_py/background_job.py
"""
import argparse
# get the args passed to blender after "--", all of which are ignored by
# blender so scripts may receive their own arguments
argv = sys.argv
if "--" not in argv:
argv = [] # as if no args are passed
else:
argv = argv[argv.index("--") + 1 :] # get all args after "--"
# When --help or no args are given, print this help
usage_text = (
f"Run blender in background mode with this script:\n\tblender --background --python {__file__} -- [options]"
)
parser = argparse.ArgumentParser(description=usage_text)
# Add arguments
parser.add_argument("-i", "--in_file", metavar="FILE", type=str, required=True, help="Path to input OBJ file.")
parser.add_argument("-o", "--out_file", metavar="FILE", type=str, required=True, help="Path to output OBJ file.")
args = parser.parse_args(argv)
# Check if any arguments provided
if not argv or not args.in_file or not args.out_file:
parser.print_help()
return None
# return arguments
return args
def convert_to_obj(in_file: str, out_file: str, save_usd: bool = False):
"""Convert a mesh file to `.obj` using blender.
Args:
in_file: Input mesh file to process.
out_file: Path to store output obj file.
"""
# check valid input file
if not os.path.exists(in_file):
raise FileNotFoundError(in_file)
# add ending of file format
if not out_file.endswith(".obj"):
out_file += ".obj"
# create directory if it doesn't exist for destination file
if not os.path.exists(os.path.dirname(out_file)):
os.makedirs(os.path.dirname(out_file), exist_ok=True)
# reset scene to empty
bpy.ops.wm.read_factory_settings(use_empty=True)
# load object into scene
if in_file.endswith(".dae"):
bpy.ops.wm.collada_import(filepath=in_file)
elif in_file.endswith(".stl") or in_file.endswith(".STL"):
bpy.ops.import_mesh.stl(filepath=in_file)
else:
raise ValueError(f"Input file not in dae/stl format: {in_file}")
# convert to obj format and store with z up
# TODO: Read the convention from dae file instead of manually fixing it.
# Reference: https://docs.blender.org/api/2.79/bpy.ops.export_scene.html
bpy.ops.export_scene.obj(
filepath=out_file, check_existing=False, axis_forward="Y", axis_up="Z", global_scale=1, path_mode="RELATIVE"
)
# save it as usd as well
if save_usd:
out_file = out_file.replace("obj", "usd")
bpy.ops.wm.usd_export(filepath=out_file, check_existing=False)
if __name__ == "__main__":
# read arguments
cli_args = parse_cli_args()
# check CLI args
if cli_args is None:
sys.exit()
# process via blender
convert_to_obj(cli_args.in_file, cli_args.out_file)
| 3,662 | Python | 33.233645 | 117 | 0.659203 |
NVIDIA-Omniverse/orbit/source/standalone/tools/process_meshes_to_obj.py | #!/usr/bin/env python
# Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Convert all mesh files to `.obj` in given folders."""
from __future__ import annotations
import argparse
import os
import shutil
import subprocess
# Constants
# Path to blender
BLENDER_EXE_PATH = shutil.which("blender")
def parse_cli_args():
"""Parse the input command line arguments.
Reference: https://developer.blender.org/diffusion/B/browse/master/release/scripts/templates_py/background_job.py
"""
# add argparse arguments
parser = argparse.ArgumentParser("Utility to convert all mesh files to `.obj` in given folders.")
parser.add_argument("input_dir", type=str, help="The input directory from which to load meshes.")
parser.add_argument(
"-o",
"--output_dir",
type=str,
default=None,
help="The output directory to save converted meshes into. Default is same as input directory.",
)
args_cli = parser.parse_args()
# resolve output directory
if args_cli.output_dir is None:
args_cli.output_dir = args_cli.input_dir
# return arguments
return args_cli
def run_blender_convert2obj(in_file: str, out_file: str):
"""Calls the python script using `subprocess` to perform processing of mesh file.
Args:
in_file: Input mesh file.
out_file: Output obj file.
"""
# resolve for python file
tools_dirname = os.path.dirname(os.path.abspath(__file__))
script_file = os.path.join(tools_dirname, "blender_obj.py")
# complete command
command_exe = f"{BLENDER_EXE_PATH} --background --python {script_file} -- -i {in_file} -o {out_file}"
# break command into list
command_exe_list = command_exe.split(" ")
# run command
subprocess.run(command_exe_list)
def convert_meshes(source_folders: list[str], destination_folders: list[str]):
"""Processes all mesh files of supported format into OBJ file using blender.
Args:
source_folders: List of directories to search for meshes.
destination_folders: List of directories to dump converted files.
"""
# create folder for corresponding destination
for folder in destination_folders:
os.makedirs(folder, exist_ok=True)
# iterate over each folder
for in_folder, out_folder in zip(source_folders, destination_folders):
# extract all dae files in the directory
mesh_filenames = [f for f in os.listdir(in_folder) if f.endswith("dae")]
mesh_filenames += [f for f in os.listdir(in_folder) if f.endswith("stl")]
mesh_filenames += [f for f in os.listdir(in_folder) if f.endswith("STL")]
# print status
print(f"Found {len(mesh_filenames)} files to process in directory: {in_folder}")
# iterate over each OBJ file
for mesh_file in mesh_filenames:
# extract meshname
mesh_name = os.path.splitext(mesh_file)[0]
# complete path of input and output files
in_file_path = os.path.join(in_folder, mesh_file)
out_file_path = os.path.join(out_folder, mesh_name + ".obj")
# perform blender processing
print("Processing: ", in_file_path)
run_blender_convert2obj(in_file_path, out_file_path)
if __name__ == "__main__":
# Parse command line arguments
args = parse_cli_args()
# Run conversion
convert_meshes([args.input_dir], [args.output_dir])
| 3,502 | Python | 34.744898 | 117 | 0.659909 |
NVIDIA-Omniverse/orbit/source/standalone/tools/convert_urdf.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Utility to convert a URDF into USD format.
Unified Robot Description Format (URDF) is an XML file format used in ROS to describe all elements of
a robot. For more information, see: http://wiki.ros.org/urdf
This script uses the URDF importer extension from Isaac Sim (``omni.isaac.urdf_importer``) to convert a
URDF asset into USD format. It is designed as a convenience script for command-line use. For more
information on the URDF importer, see the documentation for the extension:
https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html
positional arguments:
input The path to the input URDF file.
output The path to store the USD file.
optional arguments:
-h, --help Show this help message and exit
--merge-joints Consolidate links that are connected by fixed joints. (default: False)
--fix-base Fix the base to where it is imported. (default: False)
--make-instanceable Make the asset instanceable for efficient cloning. (default: False)
"""
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import argparse
from omni.isaac.orbit.app import AppLauncher
# add argparse arguments
parser = argparse.ArgumentParser(description="Utility to convert a URDF into USD format.")
parser.add_argument("input", type=str, help="The path to the input URDF file.")
parser.add_argument("output", type=str, help="The path to store the USD file.")
parser.add_argument(
"--merge-joints",
action="store_true",
default=False,
help="Consolidate links that are connected by fixed joints.",
)
parser.add_argument("--fix-base", action="store_true", default=False, help="Fix the base to where it is imported.")
parser.add_argument(
"--make-instanceable",
action="store_true",
default=False,
help="Make the asset instanceable for efficient cloning.",
)
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
# parse the arguments
args_cli = parser.parse_args()
# launch omniverse app
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
"""Rest everything follows."""
import contextlib
import os
import carb
import omni.isaac.core.utils.stage as stage_utils
import omni.kit.app
from omni.isaac.orbit.sim.converters import UrdfConverter, UrdfConverterCfg
from omni.isaac.orbit.utils.assets import check_file_path
from omni.isaac.orbit.utils.dict import print_dict
def main():
# check valid file path
urdf_path = args_cli.input
if not os.path.isabs(urdf_path):
urdf_path = os.path.abspath(urdf_path)
if not check_file_path(urdf_path):
raise ValueError(f"Invalid file path: {urdf_path}")
# create destination path
dest_path = args_cli.output
if not os.path.isabs(dest_path):
dest_path = os.path.abspath(dest_path)
# Create Urdf converter config
urdf_converter_cfg = UrdfConverterCfg(
asset_path=urdf_path,
usd_dir=os.path.dirname(dest_path),
usd_file_name=os.path.basename(dest_path),
fix_base=args_cli.fix_base,
merge_fixed_joints=args_cli.merge_joints,
force_usd_conversion=True,
make_instanceable=args_cli.make_instanceable,
)
# Print info
print("-" * 80)
print("-" * 80)
print(f"Input URDF file: {urdf_path}")
print("URDF importer config:")
print_dict(urdf_converter_cfg.to_dict(), nesting=0)
print("-" * 80)
print("-" * 80)
# Create Urdf converter and import the file
urdf_converter = UrdfConverter(urdf_converter_cfg)
# print output
print("URDF importer output:")
print(f"Generated USD file: {urdf_converter.usd_path}")
print("-" * 80)
print("-" * 80)
# Determine if there is a GUI to update:
# acquire settings interface
carb_settings_iface = carb.settings.get_settings()
# read flag for whether a local GUI is enabled
local_gui = carb_settings_iface.get("/app/window/enabled")
# read flag for whether livestreaming GUI is enabled
livestream_gui = carb_settings_iface.get("/app/livestream/enabled")
# Simulate scene (if not headless)
if local_gui or livestream_gui:
# Open the stage with USD
stage_utils.open_stage(urdf_converter.usd_path)
# Reinitialize the simulation
app = omni.kit.app.get_app_interface()
# Run simulation
with contextlib.suppress(KeyboardInterrupt):
while app.is_running():
# perform step
app.update()
if __name__ == "__main__":
# run the main function
main()
# close sim app
simulation_app.close()
| 4,784 | Python | 32 | 115 | 0.687709 |
NVIDIA-Omniverse/orbit/source/standalone/tutorials/01_assets/run_articulation.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""This script demonstrates how to spawn a cart-pole and interact with it.
.. code-block:: bash
# Usage
./orbit.sh -p source/standalone/tutorials/01_assets/run_articulation.py
"""
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import argparse
from omni.isaac.orbit.app import AppLauncher
# add argparse arguments
parser = argparse.ArgumentParser(description="Tutorial on spawning and interacting with an articulation.")
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
# parse the arguments
args_cli = parser.parse_args()
# launch omniverse app
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
"""Rest everything follows."""
import torch
import omni.isaac.core.utils.prims as prim_utils
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.sim import SimulationContext
##
# Pre-defined configs
##
from omni.isaac.orbit_assets import CARTPOLE_CFG # isort:skip
def design_scene() -> tuple[dict, list[list[float]]]:
"""Designs the scene."""
# Ground-plane
cfg = sim_utils.GroundPlaneCfg()
cfg.func("/World/defaultGroundPlane", cfg)
# Lights
cfg = sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75))
cfg.func("/World/Light", cfg)
# Create separate groups called "Origin1", "Origin2", "Origin3"
# Each group will have a robot in it
origins = [[0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]]
# Origin 1
prim_utils.create_prim("/World/Origin1", "Xform", translation=origins[0])
# Origin 2
prim_utils.create_prim("/World/Origin2", "Xform", translation=origins[1])
# Articulation
cartpole_cfg = CARTPOLE_CFG.copy()
cartpole_cfg.prim_path = "/World/Origin.*/Robot"
cartpole = Articulation(cfg=cartpole_cfg)
# return the scene information
scene_entities = {"cartpole": cartpole}
return scene_entities, origins
def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, Articulation], origins: torch.Tensor):
"""Runs the simulation loop."""
# Extract scene entities
# note: we only do this here for readability. In general, it is better to access the entities directly from
# the dictionary. This dictionary is replaced by the InteractiveScene class in the next tutorial.
robot = entities["cartpole"]
# Define simulation stepping
sim_dt = sim.get_physics_dt()
count = 0
# Simulation loop
while simulation_app.is_running():
# Reset
if count % 500 == 0:
# reset counter
count = 0
# reset the scene entities
# root state
# we offset the root state by the origin since the states are written in simulation world frame
# if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world
root_state = robot.data.default_root_state.clone()
root_state[:, :3] += origins
robot.write_root_state_to_sim(root_state)
# set joint positions with some noise
joint_pos, joint_vel = robot.data.default_joint_pos.clone(), robot.data.default_joint_vel.clone()
joint_pos += torch.rand_like(joint_pos) * 0.1
robot.write_joint_state_to_sim(joint_pos, joint_vel)
# clear internal buffers
robot.reset()
print("[INFO]: Resetting robot state...")
# Apply random action
# -- generate random joint efforts
efforts = torch.randn_like(robot.data.joint_pos) * 5.0
# -- apply action to the robot
robot.set_joint_effort_target(efforts)
# -- write data to sim
robot.write_data_to_sim()
# Perform step
sim.step()
# Increment counter
count += 1
# Update buffers
robot.update(sim_dt)
def main():
"""Main function."""
# Load kit helper
sim_cfg = sim_utils.SimulationCfg(device="cpu", use_gpu_pipeline=False)
sim = SimulationContext(sim_cfg)
# Set main camera
sim.set_camera_view([2.5, 0.0, 4.0], [0.0, 0.0, 2.0])
# Design scene
scene_entities, scene_origins = design_scene()
scene_origins = torch.tensor(scene_origins, device=sim.device)
# Play the simulator
sim.reset()
# Now we are ready!
print("[INFO]: Setup complete...")
# Run the simulator
run_simulator(sim, scene_entities, scene_origins)
if __name__ == "__main__":
# run the main function
main()
# close sim app
simulation_app.close()
| 4,689 | Python | 31.344827 | 111 | 0.655577 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.