file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/kit-extension-sample-asset-search/exts/omni.example.asset_provider/omni/assetprovider/template/constants.py | SETTING_ROOT = "/exts/omni.assetprovider.template/"
SETTING_STORE_ENABLE = SETTING_ROOT + "enable" | 98 | Python | 48.499976 | 51 | 0.765306 |
NVIDIA-Omniverse/kit-extension-sample-asset-search/exts/omni.example.asset_provider/omni/assetprovider/template/extension.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import importlib
import carb
import carb.settings
import carb.tokens
import omni.ext
from omni.services.browser.asset import get_instance as get_asset_services
from .model import TemplateAssetProvider
from .constants import SETTING_STORE_ENABLE
class TemplateAssetProviderExtension(omni.ext.IExt):
""" Template Asset Provider extension.
"""
def on_startup(self, ext_id):
self._asset_provider = TemplateAssetProvider()
self._asset_service = get_asset_services()
self._asset_service.register_store(self._asset_provider)
carb.settings.get_settings().set(SETTING_STORE_ENABLE, True)
def on_shutdown(self):
self._asset_service.unregister_store(self._asset_provider)
carb.settings.get_settings().set(SETTING_STORE_ENABLE, False)
self._asset_provider = None
self._asset_service = None
| 1,291 | Python | 34.888888 | 76 | 0.751356 |
NVIDIA-Omniverse/kit-extension-sample-asset-search/exts/omni.example.asset_provider/omni/assetprovider/template/model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import Dict, List, Optional, Union, Tuple
import aiohttp
from omni.services.browser.asset import BaseAssetStore, AssetModel, SearchCriteria, ProviderModel
from .constants import SETTING_STORE_ENABLE
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data")
# The name of your company
PROVIDER_ID = "PROVIDER_NAME"
# The URL location of your API
STORE_URL = "https://www.your_store_url.com"
class TemplateAssetProvider(BaseAssetStore):
"""
Asset provider implementation.
"""
def __init__(self, ov_app="Kit", ov_version="na") -> None:
super().__init__(PROVIDER_ID)
self._ov_app = ov_app
self._ov_version = ov_version
async def _search(self, search_criteria: SearchCriteria) -> Tuple[List[AssetModel], bool]:
""" Searches the asset store.
This function needs to be implemented as part of an implementation of the BaseAssetStore.
This function is called by the public `search` function that will wrap this function in a timeout.
"""
params = {}
# Setting for filter search criteria
if search_criteria.filter.categories:
# No category search, also use keywords instead
categories = search_criteria.filter.categories
for category in categories:
if category.startswith("/"):
category = category[1:]
category_keywords = category.split("/")
params["filter[categories]"] = ",".join(category_keywords).lower()
# Setting for keywords search criteria
if search_criteria.keywords:
params["keywords"] = ",".join(search_criteria.keywords)
# Setting for page number search criteria
if search_criteria.page.number:
params["page"] = search_criteria.page.number
# Setting for max number of items per page
if search_criteria.page.size:
params["page_size"] = search_criteria.page.size
items = []
# TODO: Uncomment once valid Store URL has been provided
# async with aiohttp.ClientSession() as session:
# async with session.get(f"{STORE_URL}", params=params) as resp:
# result = await resp.read()
# result = await resp.json()
# items = result
assets: List[AssetModel] = []
# Create AssetModel based off of JSON data
for item in items:
assets.append(
AssetModel(
identifier="",
name="",
published_at="",
categories=[],
tags=[],
vendor=PROVIDER_ID,
product_url="",
download_url="",
price=0.0,
thumbnail="",
)
)
# Are there more assets that we can load?
more = True
if search_criteria.page.size and len(assets) < search_criteria.page.size:
more = False
return (assets, more)
def provider(self) -> ProviderModel:
"""Return provider info"""
return ProviderModel(
name=PROVIDER_ID, icon=f"{DATA_PATH}/logo_placeholder.png", enable_setting=SETTING_STORE_ENABLE
)
| 3,820 | Python | 34.055046 | 110 | 0.605497 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/commands.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import omni.client
import omni.kit.commands
# import omni.kit.utils
from omni.client._omniclient import Result
from omni.importer.urdf import _urdf
from pxr import Usd
class URDFCreateImportConfig(omni.kit.commands.Command):
"""
Returns an ImportConfig object that can be used while parsing and importing.
Should be used with `URDFParseFile` and `URDFParseAndImportFile` commands
Returns:
:obj:`omni.importer.urdf._urdf.ImportConfig`: Parsed URDF stored in an internal structure.
"""
def __init__(self) -> None:
pass
def do(self) -> _urdf.ImportConfig:
return _urdf.ImportConfig()
def undo(self) -> None:
pass
class URDFParseFile(omni.kit.commands.Command):
"""
This command parses a given urdf and returns a UrdfRobot object
Args:
arg0 (:obj:`str`): The absolute path to where the urdf file is
arg1 (:obj:`omni.importer.urdf._urdf.ImportConfig`): Import Configuration
Returns:
:obj:`omni.importer.urdf._urdf.UrdfRobot`: Parsed URDF stored in an internal structure.
"""
def __init__(self, urdf_path: str = "", import_config: _urdf.ImportConfig = _urdf.ImportConfig()) -> None:
self._root_path, self._filename = os.path.split(os.path.abspath(urdf_path))
self._import_config = import_config
self._urdf_interface = _urdf.acquire_urdf_interface()
pass
def do(self) -> _urdf.UrdfRobot:
return self._urdf_interface.parse_urdf(self._root_path, self._filename, self._import_config)
def undo(self) -> None:
pass
class URDFParseAndImportFile(omni.kit.commands.Command):
"""
This command parses and imports a given urdf and returns a UrdfRobot object
Args:
arg0 (:obj:`str`): The absolute path to where the urdf file is
arg1 (:obj:`omni.importer.urdf._urdf.ImportConfig`): Import Configuration
arg2 (:obj:`str`): destination path for robot usd. Default is "" which will load the robot in-memory on the open stage.
Returns:
:obj:`str`: Path to the robot on the USD stage.
"""
def __init__(self, urdf_path: str = "", import_config=_urdf.ImportConfig(), dest_path: str = "") -> None:
self.dest_path = dest_path
self._urdf_path = urdf_path
self._root_path, self._filename = os.path.split(os.path.abspath(urdf_path))
self._import_config = import_config
self._urdf_interface = _urdf.acquire_urdf_interface()
pass
def do(self) -> str:
status, imported_robot = omni.kit.commands.execute(
"URDFParseFile", urdf_path=self._urdf_path, import_config=self._import_config
)
if self.dest_path:
self.dest_path = self.dest_path.replace(
"\\", "/"
) # Omni client works with both slashes cross platform, making it standard to make it easier later on
result = omni.client.read_file(self.dest_path)
if result[0] != Result.OK:
stage = Usd.Stage.CreateNew(self.dest_path)
stage.Save()
return self._urdf_interface.import_robot(
self._root_path, self._filename, imported_robot, self._import_config, self.dest_path
)
def undo(self) -> None:
pass
omni.kit.commands.register_all_commands_in_module(__name__)
| 4,037 | Python | 33.51282 | 127 | 0.662868 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/extension.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import gc
import os
import weakref
import carb
import omni.client
import omni.ext
import omni.ui as ui
from omni.importer.urdf import _urdf
from omni.importer.urdf.scripts.ui import (
btn_builder,
cb_builder,
dropdown_builder,
float_builder,
get_style,
make_menu_item_description,
setup_ui_headers,
str_builder,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from pxr import Sdf, Usd, UsdGeom, UsdPhysics
# from .menu import make_menu_item_description
# from .ui_utils import (
# btn_builder,
# cb_builder,
# dropdown_builder,
# float_builder,
# get_style,
# setup_ui_headers,
# str_builder,
# )
EXTENSION_NAME = "URDF Importer"
def is_urdf_file(path: str):
_, ext = os.path.splitext(path.lower())
return ext in [".urdf", ".URDF"]
def on_filter_item(item) -> bool:
if not item or item.is_folder:
return not (item.name == "Omniverse" or item.path.startswith("omniverse:"))
return is_urdf_file(item.path)
def on_filter_folder(item) -> bool:
if item and item.is_folder:
return True
else:
return False
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._ext_id = ext_id
self._urdf_interface = _urdf.acquire_urdf_interface()
self._usd_context = omni.usd.get_context()
self._window = omni.ui.Window(
EXTENSION_NAME, width=400, height=500, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
menu_items = [
make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback())
]
self._menu_items = [MenuItemDescription(name="Workflows", sub_menu=menu_items)]
add_menu_items(self._menu_items, "Isaac Utils")
self._file_picker = None
self._models = {}
result, self._config = omni.kit.commands.execute("URDFCreateImportConfig")
self._filepicker = None
self._last_folder = None
self._content_browser = None
self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
self._imported_robot = None
# Set defaults
self._config.set_merge_fixed_joints(False)
self._config.set_replace_cylinders_with_capsules(False)
self._config.set_convex_decomp(False)
self._config.set_fix_base(True)
self._config.set_import_inertia_tensor(False)
self._config.set_distance_scale(1.0)
self._config.set_density(0.0)
self._config.set_default_drive_type(1)
self._config.set_default_drive_strength(1e7)
self._config.set_default_position_drive_damping(1e5)
self._config.set_self_collision(False)
self._config.set_up_vector(0, 0, 1)
self._config.set_make_default_prim(True)
self._config.set_create_physics_scene(True)
self._config.set_collision_from_visuals(False)
def build_ui(self):
with self._window.frame:
with ui.VStack(spacing=5, height=0):
self._build_info_ui()
self._build_options_ui()
self._build_import_ui()
stage = self._usd_context.get_stage()
if stage:
if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y:
self._config.set_up_vector(0, 1, 0)
if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z:
self._config.set_up_vector(0, 0, 1)
units_per_meter = 1.0 / UsdGeom.GetStageMetersPerUnit(stage)
self._models["scale"].set_value(units_per_meter)
async def dock_window():
await omni.kit.app.get_app().next_update_async()
def dock(space, name, location, pos=0.5):
window = omni.ui.Workspace.get_window(name)
if window and space:
window.dock_in(space, location, pos)
return window
tgt = ui.Workspace.get_window("Viewport")
dock(tgt, EXTENSION_NAME, omni.ui.DockPosition.LEFT, 0.33)
await omni.kit.app.get_app().next_update_async()
self._task = asyncio.ensure_future(dock_window())
def _build_info_ui(self):
title = EXTENSION_NAME
doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html"
overview = "This utility is used to import URDF representations of robots into Isaac Sim. "
overview += "URDF is an XML format for representing a robot model in ROS."
overview += "\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
def _build_options_ui(self):
frame = ui.CollapsableFrame(
title="Import Options",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
cb_builder(
label="Merge Fixed Joints",
tooltip="Consolidate links that are connected by fixed joints.",
on_clicked_fn=lambda m, config=self._config: config.set_merge_fixed_joints(m),
)
cb_builder(
label="Replace Cylinders with Capsules",
tooltip="Replace Cylinder collision bodies by capsules.",
on_clicked_fn=lambda m, config=self._config: config.set_replace_cylinders_with_capsules(m),
)
cb_builder(
"Fix Base Link",
tooltip="Fix the robot base robot to where it's imported in world coordinates.",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_fix_base(m),
)
cb_builder(
"Import Inertia Tensor",
tooltip="Load inertia tensor directly from the URDF.",
on_clicked_fn=lambda m, config=self._config: config.set_import_inertia_tensor(m),
)
self._models["scale"] = float_builder(
"Stage Units Per Meter",
default_val=1.0,
tooltip="Sets the scaling factor to match the units used in the URDF. Default Stage units are (cm).",
)
self._models["scale"].add_value_changed_fn(
lambda m, config=self._config: config.set_distance_scale(m.get_value_as_float())
)
self._models["density"] = float_builder(
"Link Density",
default_val=0.0,
tooltip="Density value to compute mass based on link volume. Use 0.0 to automatically compute density.",
)
self._models["density"].add_value_changed_fn(
lambda m, config=self._config: config.set_density(m.get_value_as_float())
)
dropdown_builder(
"Joint Drive Type",
items=["None", "Position", "Velocity"],
default_val=1,
on_clicked_fn=lambda i, config=self._config: config.set_default_drive_type(
0 if i == "None" else (1 if i == "Position" else 2)
),
tooltip="Default Joint drive type.",
)
self._models["drive_strength"] = float_builder(
"Joint Drive Strength",
default_val=1e4,
tooltip="Joint stiffness for position drive, or damping for velocity driven joints. Set to -1 to prevent this parameter from getting used.",
)
self._models["drive_strength"].add_value_changed_fn(
lambda m, config=self._config: config.set_default_drive_strength(m.get_value_as_float())
)
self._models["position_drive_damping"] = float_builder(
"Joint Position Damping",
default_val=1e3,
tooltip="Default damping value when drive type is set to Position. Set to -1 to prevent this parameter from getting used.",
)
self._models["position_drive_damping"].add_value_changed_fn(
lambda m, config=self._config: config.set_default_position_drive_damping(m.get_value_as_float())
)
self._models["clean_stage"] = cb_builder(
label="Clear Stage", tooltip="Clear the Stage prior to loading the URDF."
)
dropdown_builder(
"Normals Subdivision",
items=["catmullClark", "loop", "bilinear", "none"],
default_val=2,
on_clicked_fn=lambda i, dict={
"catmullClark": 0,
"loop": 1,
"bilinear": 2,
"none": 3,
}, config=self._config: config.set_subdivision_scheme(dict[i]),
tooltip="Mesh surface normal subdivision scheme. Use `none` to avoid overriding authored values.",
)
cb_builder(
"Convex Decomposition",
tooltip="Decompose non-convex meshes into convex collision shapes. If false, convex hull will be used.",
on_clicked_fn=lambda m, config=self._config: config.set_convex_decomp(m),
)
cb_builder(
"Self Collision",
tooltip="Enables self collision between adjacent links.",
on_clicked_fn=lambda m, config=self._config: config.set_self_collision(m),
)
cb_builder(
"Collision From Visuals",
tooltip="Creates collision geometry from visual geometry.",
on_clicked_fn=lambda m, config=self._config: config.set_collision_from_visuals(m),
)
cb_builder(
"Create Physics Scene",
tooltip="Creates a default physics scene on the stage on import.",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_create_physics_scene(m),
)
cb_builder(
"Create Instanceable Asset",
tooltip="If true, creates an instanceable version of the asset. Meshes will be saved in a separate USD file",
default_val=False,
on_clicked_fn=lambda m, config=self._config: config.set_make_instanceable(m),
)
self._models["instanceable_usd_path"] = str_builder(
"Instanceable USD Path",
tooltip="USD file to store instanceable meshes in",
default_val="./instanceable_meshes.usd",
use_folder_picker=True,
folder_dialog_title="Select Output File",
folder_button_title="Select File",
)
self._models["instanceable_usd_path"].add_value_changed_fn(
lambda m, config=self._config: config.set_instanceable_usd_path(m.get_value_as_string())
)
def _build_import_ui(self):
frame = ui.CollapsableFrame(
title="Import",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def check_file_type(model=None):
path = model.get_value_as_string()
if is_urdf_file(path) and "omniverse:" not in path.lower():
self._models["import_btn"].enabled = True
else:
carb.log_warn(f"Invalid path to URDF: {path}")
kwargs = {
"label": "Input File",
"default_val": "",
"tooltip": "Click the Folder Icon to Set Filepath",
"use_folder_picker": True,
"item_filter_fn": on_filter_item,
"bookmark_label": "Built In URDF Files",
"bookmark_path": f"{self._extension_path}/data/urdf",
"folder_dialog_title": "Select URDF File",
"folder_button_title": "Select URDF",
}
self._models["input_file"] = str_builder(**kwargs)
self._models["input_file"].add_value_changed_fn(check_file_type)
kwargs = {
"label": "Output Directory",
"type": "stringfield",
"default_val": self.get_dest_folder(),
"tooltip": "Click the Folder Icon to Set Filepath",
"use_folder_picker": True,
}
self.dest_model = str_builder(**kwargs)
# btn_builder("Import URDF", text="Select and Import", on_clicked_fn=self._parse_urdf)
self._models["import_btn"] = btn_builder("Import", text="Import", on_clicked_fn=self._load_robot)
self._models["import_btn"].enabled = False
def get_dest_folder(self):
stage = omni.usd.get_context().get_stage()
if stage:
path = stage.GetRootLayer().identifier
if not path.startswith("anon"):
basepath = path[: path.rfind("/")]
if path.rfind("/") < 0:
basepath = path[: path.rfind("\\")]
return basepath
return "(same as source)"
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_window(self, visible):
if self._window.visible:
self.build_ui()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="urdf importer stage event"
)
else:
self._events = None
self._stage_event_sub = None
def _on_stage_event(self, event):
stage = self._usd_context.get_stage()
if event.type == int(omni.usd.StageEventType.OPENED) and stage:
if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y:
self._config.set_up_vector(0, 1, 0)
if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z:
self._config.set_up_vector(0, 0, 1)
units_per_meter = 1.0 / UsdGeom.GetStageMetersPerUnit(stage)
self._models["scale"].set_value(units_per_meter)
self.dest_model.set_value(self.get_dest_folder())
def _load_robot(self, path=None):
path = self._models["input_file"].get_value_as_string()
if path:
dest_path = self.dest_model.get_value_as_string()
base_path = path[: path.rfind("/")]
basename = path[path.rfind("/") + 1 :]
basename = basename[: basename.rfind(".")]
if path.rfind("/") < 0:
base_path = path[: path.rfind("\\")]
basename = path[path.rfind("\\") + 1]
if dest_path != "(same as source)":
base_path = dest_path # + "/" + basename
dest_path = "{}/{}/{}.usd".format(base_path, basename, basename)
# counter = 1
# while result[0] == Result.OK:
# dest_path = "{}/{}_{:02}.usd".format(base_path, basename, counter)
# result = omni.client.read_file(dest_path)
# counter +=1
# result = omni.client.read_file(dest_path)
# if
# stage = Usd.Stage.Open(dest_path)
# else:
# stage = Usd.Stage.CreateNew(dest_path)
# UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=path, import_config=self._config, dest_path=dest_path
)
# print("Created file, instancing it now")
stage = Usd.Stage.Open(dest_path)
prim_name = str(stage.GetDefaultPrim().GetName())
# print(prim_name)
# stage.Save()
def add_reference_to_stage():
current_stage = omni.usd.get_context().get_stage()
if current_stage:
prim_path = omni.usd.get_stage_next_free_path(
current_stage, str(current_stage.GetDefaultPrim().GetPath()) + "/" + prim_name, False
)
robot_prim = current_stage.OverridePrim(prim_path)
if "anon:" in current_stage.GetRootLayer().identifier:
robot_prim.GetReferences().AddReference(dest_path)
else:
robot_prim.GetReferences().AddReference(
omni.client.make_relative_url(current_stage.GetRootLayer().identifier, dest_path)
)
if self._config.create_physics_scene:
UsdPhysics.Scene.Define(current_stage, Sdf.Path("/physicsScene"))
async def import_with_clean_stage():
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
add_reference_to_stage()
await omni.kit.app.get_app().next_update_async()
if self._models["clean_stage"].get_value_as_bool():
asyncio.ensure_future(import_with_clean_stage())
else:
add_reference_to_stage()
def on_shutdown(self):
_urdf.release_urdf_interface(self._urdf_interface)
remove_menu_items(self._menu_items, "Isaac Utils")
if self._window:
self._window = None
gc.collect()
| 19,344 | Python | 43.267734 | 160 | 0.549783 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/ui/menu.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ext
from omni.kit.menu.utils import MenuItemDescription
def make_menu_item_description(ext_id: str, name: str, onclick_fun, action_name: str = "") -> None:
"""Easily replace the onclick_fn with onclick_action when creating a menu description
Args:
ext_id (str): The extension you are adding the menu item to.
name (str): Name of the menu item displayed in UI.
onclick_fun (Function): The function to run when clicking the menu item.
action_name (str): name for the action, in case ext_id+name don't make a unique string
Note:
ext_id + name + action_name must concatenate to a unique identifier.
"""
# TODO, fix errors when reloading extensions
# action_unique = f'{ext_id.replace(" ", "_")}{name.replace(" ", "_")}{action_name.replace(" ", "_")}'
# action_registry = omni.kit.actions.core.get_action_registry()
# action_registry.register_action(ext_id, action_unique, onclick_fun)
return MenuItemDescription(name=name, onclick_fn=onclick_fun)
| 1,716 | Python | 44.184209 | 106 | 0.716783 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/ui/ui_utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import os
import subprocess
import sys
from cmath import inf
import carb.settings
import omni.appwindow
import omni.ext
import omni.ui as ui
from omni.kit.window.extensions import SimpleCheckBox
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.window.property.templates import LABEL_HEIGHT, LABEL_WIDTH
# from .callbacks import on_copy_to_clipboard, on_docs_link_clicked, on_open_folder_clicked, on_open_IDE_clicked
from .style import BUTTON_WIDTH, COLOR_W, COLOR_X, COLOR_Y, COLOR_Z, get_style
def btn_builder(label="", type="button", text="button", tooltip="", on_clicked_fn=None):
"""Creates a stylized button.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "button".
text (str, optional): Text rendered on the button. Defaults to "button".
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
ui.Button: Button
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
btn = ui.Button(
text.upper(),
name="Button",
width=BUTTON_WIDTH,
clicked_fn=on_clicked_fn,
style=get_style(),
alignment=ui.Alignment.LEFT_CENTER,
)
ui.Spacer(width=5)
add_line_rect_flourish(True)
# ui.Spacer(width=ui.Fraction(1))
# ui.Spacer(width=10)
# with ui.Frame(width=0):
# with ui.VStack():
# with ui.Placer(offset_x=0, offset_y=7):
# ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER)
# ui.Spacer(width=5)
return btn
def state_btn_builder(
label="", type="state_button", a_text="STATE A", b_text="STATE B", tooltip="", on_clicked_fn=None
):
"""Creates a State Change Button that changes text when pressed.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "button".
a_text (str, optional): Text rendered on the button for State A. Defaults to "STATE A".
b_text (str, optional): Text rendered on the button for State B. Defaults to "STATE B".
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
"""
def toggle():
if btn.text == a_text.upper():
btn.text = b_text.upper()
on_clicked_fn(True)
else:
btn.text = a_text.upper()
on_clicked_fn(False)
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
btn = ui.Button(
a_text.upper(),
name="Button",
width=BUTTON_WIDTH,
clicked_fn=toggle,
style=get_style(),
alignment=ui.Alignment.LEFT_CENTER,
)
ui.Spacer(width=5)
# add_line_rect_flourish(False)
ui.Spacer(width=ui.Fraction(1))
ui.Spacer(width=10)
with ui.Frame(width=0):
with ui.VStack():
with ui.Placer(offset_x=0, offset_y=7):
ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER)
ui.Spacer(width=5)
return btn
def cb_builder(label="", type="checkbox", default_val=False, tooltip="", on_clicked_fn=None):
"""Creates a Stylized Checkbox
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "checkbox".
default_val (bool, optional): Checked is True, Unchecked is False. Defaults to False.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
ui.SimpleBoolModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
model = ui.SimpleBoolModel()
callable = on_clicked_fn
if callable is None:
callable = lambda x: None
SimpleCheckBox(default_val, callable, model=model)
add_line_rect_flourish()
return model
def multi_btn_builder(
label="", type="multi_button", count=2, text=["button", "button"], tooltip=["", "", ""], on_clicked_fn=[None, None]
):
"""Creates a Row of Stylized Buttons
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "multi_button".
count (int, optional): Number of UI elements to create. Defaults to 2.
text (list, optional): List of text rendered on the UI elements. Defaults to ["button", "button"].
tooltip (list, optional): List of tooltips to display over the UI elements. Defaults to ["", "", ""].
on_clicked_fn (list, optional): List of call-backs function when clicked. Defaults to [None, None].
Returns:
list(ui.Button): List of Buttons
"""
btns = []
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0]))
for i in range(count):
btn = ui.Button(
text[i].upper(),
name="Button",
width=BUTTON_WIDTH,
clicked_fn=on_clicked_fn[i],
tooltip=format_tt(tooltip[i + 1]),
style=get_style(),
alignment=ui.Alignment.LEFT_CENTER,
)
btns.append(btn)
if i < count:
ui.Spacer(width=5)
add_line_rect_flourish()
return btns
def multi_cb_builder(
label="",
type="multi_checkbox",
count=2,
text=[" ", " "],
default_val=[False, False],
tooltip=["", "", ""],
on_clicked_fn=[None, None],
):
"""Creates a Row of Stylized Checkboxes.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "multi_checkbox".
count (int, optional): Number of UI elements to create. Defaults to 2.
text (list, optional): List of text rendered on the UI elements. Defaults to [" ", " "].
default_val (list, optional): List of default values. Checked is True, Unchecked is False. Defaults to [False, False].
tooltip (list, optional): List of tooltips to display over the UI elements. Defaults to ["", "", ""].
on_clicked_fn (list, optional): List of call-backs function when clicked. Defaults to [None, None].
Returns:
list(ui.SimpleBoolModel): List of models
"""
cbs = []
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0]))
for i in range(count):
cb = ui.SimpleBoolModel(default_value=default_val[i])
callable = on_clicked_fn[i]
if callable is None:
callable = lambda x: None
SimpleCheckBox(default_val[i], callable, model=cb)
ui.Label(
text[i], width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[i + 1])
)
if i < count - 1:
ui.Spacer(width=5)
cbs.append(cb)
add_line_rect_flourish()
return cbs
def str_builder(
label="",
type="stringfield",
default_val=" ",
tooltip="",
on_clicked_fn=None,
use_folder_picker=False,
read_only=False,
item_filter_fn=None,
bookmark_label=None,
bookmark_path=None,
folder_dialog_title="Select Output Folder",
folder_button_title="Select Folder",
):
"""Creates a Stylized Stringfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "stringfield".
default_val (str, optional): Text to initialize in Stringfield. Defaults to " ".
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
use_folder_picker (bool, optional): Add a folder picker button to the right. Defaults to False.
read_only (bool, optional): Prevents editing. Defaults to False.
item_filter_fn (Callable, optional): filter function to pass to the FilePicker
bookmark_label (str, optional): bookmark label to pass to the FilePicker
bookmark_path (str, optional): bookmark path to pass to the FilePicker
Returns:
AbstractValueModel: model of Stringfield
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
str_field = ui.StringField(
name="StringField", width=ui.Fraction(1), height=0, alignment=ui.Alignment.LEFT_CENTER, read_only=read_only
).model
str_field.set_value(default_val)
if use_folder_picker:
def update_field(filename, path):
if filename == "":
val = path
elif filename[0] != "/" and path[-1] != "/":
val = path + "/" + filename
elif filename[0] == "/" and path[-1] == "/":
val = path + filename[1:]
else:
val = path + filename
str_field.set_value(val)
add_folder_picker_icon(
update_field,
item_filter_fn,
bookmark_label,
bookmark_path,
dialog_title=folder_dialog_title,
button_title=folder_button_title,
)
else:
add_line_rect_flourish(False)
return str_field
def int_builder(label="", type="intfield", default_val=0, tooltip="", min=sys.maxsize * -1, max=sys.maxsize):
"""Creates a Stylized Intfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "intfield".
default_val (int, optional): Default Value of UI element. Defaults to 0.
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
min (int, optional): Minimum limit for int field. Defaults to sys.maxsize * -1
max (int, optional): Maximum limit for int field. Defaults to sys.maxsize * 1
Returns:
AbstractValueModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
int_field = ui.IntDrag(
name="Field", height=LABEL_HEIGHT, min=min, max=max, alignment=ui.Alignment.LEFT_CENTER
).model
int_field.set_value(default_val)
add_line_rect_flourish(False)
return int_field
def float_builder(label="", type="floatfield", default_val=0, tooltip="", min=-inf, max=inf, step=0.1, format="%.2f"):
"""Creates a Stylized Floatfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "floatfield".
default_val (int, optional): Default Value of UI element. Defaults to 0.
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
Returns:
AbstractValueModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
float_field = ui.FloatDrag(
name="FloatField",
width=ui.Fraction(1),
height=0,
alignment=ui.Alignment.LEFT_CENTER,
min=min,
max=max,
step=step,
format=format,
).model
float_field.set_value(default_val)
add_line_rect_flourish(False)
return float_field
def combo_cb_str_builder(
label="",
type="checkbox_stringfield",
default_val=[False, " "],
tooltip="",
on_clicked_fn=lambda x: None,
use_folder_picker=False,
read_only=False,
folder_dialog_title="Select Output Folder",
folder_button_title="Select Folder",
):
"""Creates a Stylized Checkbox + Stringfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "checkbox_stringfield".
default_val (str, optional): Text to initialize in Stringfield. Defaults to [False, " "].
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
use_folder_picker (bool, optional): Add a folder picker button to the right. Defaults to False.
read_only (bool, optional): Prevents editing. Defaults to False.
Returns:
Tuple(ui.SimpleBoolModel, AbstractValueModel): (cb_model, str_field_model)
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
cb = ui.SimpleBoolModel(default_value=default_val[0])
SimpleCheckBox(default_val[0], on_clicked_fn, model=cb)
str_field = ui.StringField(
name="StringField", width=ui.Fraction(1), height=0, alignment=ui.Alignment.LEFT_CENTER, read_only=read_only
).model
str_field.set_value(default_val[1])
if use_folder_picker:
def update_field(val):
str_field.set_value(val)
add_folder_picker_icon(update_field, dialog_title=folder_dialog_title, button_title=folder_button_title)
else:
add_line_rect_flourish(False)
return cb, str_field
def dropdown_builder(
label="", type="dropdown", default_val=0, items=["Option 1", "Option 2", "Option 3"], tooltip="", on_clicked_fn=None
):
"""Creates a Stylized Dropdown Combobox
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "dropdown".
default_val (int, optional): Default index of dropdown items. Defaults to 0.
items (list, optional): List of items for dropdown box. Defaults to ["Option 1", "Option 2", "Option 3"].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
AbstractItemModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
combo_box = ui.ComboBox(
default_val, *items, name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER
).model
add_line_rect_flourish(False)
def on_clicked_wrapper(model, val):
on_clicked_fn(items[model.get_item_value_model().as_int])
if on_clicked_fn is not None:
combo_box.add_item_changed_fn(on_clicked_wrapper)
return combo_box
def combo_intfield_slider_builder(
label="", type="intfield_stringfield", default_val=0.5, min=0, max=1, step=0.01, tooltip=["", ""]
):
"""Creates a Stylized IntField + Stringfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "intfield_stringfield".
default_val (float, optional): Default Value. Defaults to 0.5.
min (int, optional): Minimum Value. Defaults to 0.
max (int, optional): Maximum Value. Defaults to 1.
step (float, optional): Step. Defaults to 0.01.
tooltip (list, optional): List of tooltips. Defaults to ["", ""].
Returns:
Tuple(AbstractValueModel, IntSlider): (flt_field_model, flt_slider_model)
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0]))
ff = ui.IntDrag(
name="Field", width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[1])
).model
ff.set_value(default_val)
ui.Spacer(width=5)
fs = ui.IntSlider(
width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER, min=min, max=max, step=step, model=ff
)
add_line_rect_flourish(False)
return ff, fs
def combo_floatfield_slider_builder(
label="", type="floatfield_stringfield", default_val=0.5, min=0, max=1, step=0.01, tooltip=["", ""]
):
"""Creates a Stylized FloatField + FloatSlider Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "floatfield_stringfield".
default_val (float, optional): Default Value. Defaults to 0.5.
min (int, optional): Minimum Value. Defaults to 0.
max (int, optional): Maximum Value. Defaults to 1.
step (float, optional): Step. Defaults to 0.01.
tooltip (list, optional): List of tooltips. Defaults to ["", ""].
Returns:
Tuple(AbstractValueModel, IntSlider): (flt_field_model, flt_slider_model)
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0]))
ff = ui.FloatField(
name="Field", width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[1])
).model
ff.set_value(default_val)
ui.Spacer(width=5)
fs = ui.FloatSlider(
width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER, min=min, max=max, step=step, model=ff
)
add_line_rect_flourish(False)
return ff, fs
def multi_dropdown_builder(
label="",
type="multi_dropdown",
count=2,
default_val=[0, 0],
items=[["Option 1", "Option 2", "Option 3"], ["Option A", "Option B", "Option C"]],
tooltip="",
on_clicked_fn=[None, None],
):
"""Creates a Stylized Multi-Dropdown Combobox
Returns:
AbstractItemModel: model
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "multi_dropdown".
count (int, optional): Number of UI elements. Defaults to 2.
default_val (list(int), optional): List of default indices of dropdown items. Defaults to 0.. Defaults to [0, 0].
items (list(list), optional): List of list of items for dropdown boxes. Defaults to [["Option 1", "Option 2", "Option 3"], ["Option A", "Option B", "Option C"]].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (list(Callable), optional): List of call-back function when clicked. Defaults to [None, None].
Returns:
list(AbstractItemModel): list(models)
"""
elems = []
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
for i in range(count):
elem = ui.ComboBox(
default_val[i], *items[i], name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER
)
def on_clicked_wrapper(model, val, index):
on_clicked_fn[index](items[index][model.get_item_value_model().as_int])
elem.model.add_item_changed_fn(lambda m, v, index=i: on_clicked_wrapper(m, v, index))
elems.append(elem)
if i < count - 1:
ui.Spacer(width=5)
add_line_rect_flourish(False)
return elems
def combo_cb_dropdown_builder(
label="",
type="checkbox_dropdown",
default_val=[False, 0],
items=["Option 1", "Option 2", "Option 3"],
tooltip="",
on_clicked_fn=[lambda x: None, None],
):
"""Creates a Stylized Dropdown Combobox with an Enable Checkbox
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "checkbox_dropdown".
default_val (list, optional): list(cb_default, dropdown_default). Defaults to [False, 0].
items (list, optional): List of items for dropdown box. Defaults to ["Option 1", "Option 2", "Option 3"].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (list, optional): List of callback functions. Defaults to [lambda x: None, None].
Returns:
Tuple(ui.SimpleBoolModel, ui.ComboBox): (cb_model, combobox)
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
cb = ui.SimpleBoolModel(default_value=default_val[0])
SimpleCheckBox(default_val[0], on_clicked_fn[0], model=cb)
combo_box = ui.ComboBox(
default_val[1], *items, name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER
)
def on_clicked_wrapper(model, val):
on_clicked_fn[1](items[model.get_item_value_model().as_int])
combo_box.model.add_item_changed_fn(on_clicked_wrapper)
add_line_rect_flourish(False)
return cb, combo_box
def scrolling_frame_builder(label="", type="scrolling_frame", default_val="No Data", tooltip=""):
"""Creates a Labeled Scrolling Frame with CopyToClipboard button
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "scrolling_frame".
default_val (str, optional): Default Text. Defaults to "No Data".
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
ui.Label: label
"""
with ui.VStack(style=get_style(), spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
with ui.ScrollingFrame(
height=LABEL_HEIGHT * 5,
style_type_name_override="ScrollingFrame",
alignment=ui.Alignment.LEFT_TOP,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
text = ui.Label(
default_val,
style_type_name_override="Label::label",
word_wrap=True,
alignment=ui.Alignment.LEFT_TOP,
)
with ui.Frame(width=0, tooltip="Copy To Clipboard"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text),
style=get_style()["IconButton.Image::CopyToClipboard"],
alignment=ui.Alignment.RIGHT_TOP,
)
return text
def combo_cb_scrolling_frame_builder(
label="", type="cb_scrolling_frame", default_val=[False, "No Data"], tooltip="", on_clicked_fn=lambda x: None
):
"""Creates a Labeled, Checkbox-enabled Scrolling Frame with CopyToClipboard button
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "cb_scrolling_frame".
default_val (list, optional): List of Checkbox and Frame Defaults. Defaults to [False, "No Data"].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Callback function when clicked. Defaults to lambda x : None.
Returns:
list(SimpleBoolModel, ui.Label): (model, label)
"""
with ui.VStack(style=get_style(), spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
with ui.VStack(width=0):
cb = ui.SimpleBoolModel(default_value=default_val[0])
SimpleCheckBox(default_val[0], on_clicked_fn, model=cb)
ui.Spacer(height=18 * 4)
with ui.ScrollingFrame(
height=18 * 5,
style_type_name_override="ScrollingFrame",
alignment=ui.Alignment.LEFT_TOP,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
text = ui.Label(
default_val[1],
style_type_name_override="Label::label",
word_wrap=True,
alignment=ui.Alignment.LEFT_TOP,
)
with ui.Frame(width=0, tooltip="Copy to Clipboard"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text),
style=get_style()["IconButton.Image::CopyToClipboard"],
alignment=ui.Alignment.RIGHT_TOP,
)
return cb, text
def xyz_builder(
label="",
tooltip="",
axis_count=3,
default_val=[0.0, 0.0, 0.0, 0.0],
min=float("-inf"),
max=float("inf"),
step=0.001,
on_value_changed_fn=[None, None, None, None],
):
"""[summary]
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "".
axis_count (int, optional): Number of Axes to Display. Max 4. Defaults to 3.
default_val (list, optional): List of default values. Defaults to [0.0, 0.0, 0.0, 0.0].
min (float, optional): Minimum Float Value. Defaults to float("-inf").
max (float, optional): Maximum Float Value. Defaults to float("inf").
step (float, optional): Step. Defaults to 0.001.
on_value_changed_fn (list, optional): List of callback functions for each axes. Defaults to [None, None, None, None].
Returns:
list(AbstractValueModel): list(model)
"""
# These styles & colors are taken from omni.kit.property.transform_builder.py _create_multi_float_drag_matrix_with_labels
if axis_count <= 0 or axis_count > 4:
import builtins
carb.log_warn("Invalid axis_count: must be in range 1 to 4. Clamping to default range.")
axis_count = builtins.max(builtins.min(axis_count, 4), 1)
field_labels = [("X", COLOR_X), ("Y", COLOR_Y), ("Z", COLOR_Z), ("W", COLOR_W)]
field_tooltips = ["X Value", "Y Value", "Z Value", "W Value"]
RECT_WIDTH = 13
# SPACING = 4
val_models = [None] * axis_count
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=RECT_WIDTH)
for i in range(axis_count):
val_models[i] = ui.FloatDrag(
name="Field",
height=LABEL_HEIGHT,
min=min,
max=max,
step=step,
alignment=ui.Alignment.LEFT_CENTER,
tooltip=field_tooltips[i],
).model
val_models[i].set_value(default_val[i])
if on_value_changed_fn[i] is not None:
val_models[i].add_value_changed_fn(on_value_changed_fn[i])
if i != axis_count - 1:
ui.Spacer(width=19)
with ui.HStack():
for i in range(axis_count):
if i != 0:
ui.Spacer() # width=BUTTON_WIDTH - 1)
field_label = field_labels[i]
with ui.ZStack(width=RECT_WIDTH + 2 * i):
ui.Rectangle(name="vector_label", style={"background_color": field_label[1]})
ui.Label(field_label[0], name="vector_label", alignment=ui.Alignment.CENTER)
ui.Spacer()
add_line_rect_flourish(False)
return val_models
def color_picker_builder(label="", type="color_picker", default_val=[1.0, 1.0, 1.0, 1.0], tooltip="Color Picker"):
"""Creates a Color Picker Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "color_picker".
default_val (list, optional): List of (R,G,B,A) default values. Defaults to [1.0, 1.0, 1.0, 1.0].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "Color Picker".
Returns:
AbstractItemModel: ui.ColorWidget.model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
model = ui.ColorWidget(*default_val, width=BUTTON_WIDTH).model
ui.Spacer(width=5)
add_line_rect_flourish()
return model
def progress_bar_builder(label="", type="progress_bar", default_val=0, tooltip="Progress"):
"""Creates a Progress Bar Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "progress_bar".
default_val (int, optional): Starting Value. Defaults to 0.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "Progress".
Returns:
AbstractValueModel: ui.ProgressBar().model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER)
model = ui.ProgressBar().model
model.set_value(default_val)
add_line_rect_flourish(False)
return model
def plot_builder(label="", data=None, min=-1, max=1, type=ui.Type.LINE, value_stride=1, color=None, tooltip=""):
"""Creates a stylized static plot
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
data (list(float), optional): Data to plot. Defaults to None.
min (int, optional): Minimum Y Value. Defaults to -1.
max (int, optional): Maximum Y Value. Defaults to 1.
type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE.
value_stride (int, optional): Width of plot stride. Defaults to 1.
color (int, optional): Plot color. Defaults to None.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
ui.Plot: plot
"""
with ui.VStack(spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
plot_height = LABEL_HEIGHT * 2 + 13
plot_width = ui.Fraction(1)
with ui.ZStack():
ui.Rectangle(width=plot_width, height=plot_height)
if not color:
color = 0xFFDDDDDD
plot = ui.Plot(
type,
min,
max,
*data,
value_stride=value_stride,
width=plot_width,
height=plot_height,
style={"color": color, "background_color": 0x0},
)
def update_min(model):
plot.scale_min = model.as_float
def update_max(model):
plot.scale_max = model.as_float
ui.Spacer(width=5)
with ui.Frame(width=0):
with ui.VStack(spacing=5):
max_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max"
).model
max_model.set_value(max)
min_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min"
).model
min_model.set_value(min)
min_model.add_value_changed_fn(update_min)
max_model.add_value_changed_fn(update_max)
ui.Spacer(width=20)
add_separator()
return plot
def xyz_plot_builder(label="", data=[], min=-1, max=1, tooltip=""):
"""Creates a stylized static XYZ plot
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
data (list(float), optional): Data to plot. Defaults to [].
min (int, optional): Minimum Y Value. Defaults to -1.
max (int, optional): Maximum Y Value. Defaults to "".
tooltip (str, optional): Tooltip to display over the Label.. Defaults to "".
Returns:
list(ui.Plot): list(x_plot, y_plot, z_plot)
"""
with ui.VStack(spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
plot_height = LABEL_HEIGHT * 2 + 13
plot_width = ui.Fraction(1)
with ui.ZStack():
ui.Rectangle(width=plot_width, height=plot_height)
plot_0 = ui.Plot(
ui.Type.LINE,
min,
max,
*data[0],
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::X"],
)
plot_1 = ui.Plot(
ui.Type.LINE,
min,
max,
*data[1],
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::Y"],
)
plot_2 = ui.Plot(
ui.Type.LINE,
min,
max,
*data[2],
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::Z"],
)
def update_min(model):
plot_0.scale_min = model.as_float
plot_1.scale_min = model.as_float
plot_2.scale_min = model.as_float
def update_max(model):
plot_0.scale_max = model.as_float
plot_1.scale_max = model.as_float
plot_2.scale_max = model.as_float
ui.Spacer(width=5)
with ui.Frame(width=0):
with ui.VStack(spacing=5):
max_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max"
).model
max_model.set_value(max)
min_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min"
).model
min_model.set_value(min)
min_model.add_value_changed_fn(update_min)
max_model.add_value_changed_fn(update_max)
ui.Spacer(width=20)
add_separator()
return [plot_0, plot_1, plot_2]
def combo_cb_plot_builder(
label="",
default_val=False,
on_clicked_fn=lambda x: None,
data=None,
min=-1,
max=1,
type=ui.Type.LINE,
value_stride=1,
color=None,
tooltip="",
):
"""Creates a Checkbox-Enabled dyanamic plot
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
default_val (bool, optional): Checkbox default. Defaults to False.
on_clicked_fn (Callable, optional): Checkbox Callback function. Defaults to lambda x: None.
data (list(), optional): Data to plat. Defaults to None.
min (int, optional): Min Y Value. Defaults to -1.
max (int, optional): Max Y Value. Defaults to 1.
type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE.
value_stride (int, optional): Width of plot stride. Defaults to 1.
color (int, optional): Plot color. Defaults to None.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
list(SimpleBoolModel, ui.Plot): (cb_model, plot)
"""
with ui.VStack(spacing=5):
with ui.HStack():
# Label
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
# Checkbox
with ui.Frame(width=0):
with ui.Placer(offset_x=-10, offset_y=0):
with ui.VStack():
SimpleCheckBox(default_val, on_clicked_fn)
ui.Spacer(height=ui.Fraction(1))
ui.Spacer()
# Plot
plot_height = LABEL_HEIGHT * 2 + 13
plot_width = ui.Fraction(1)
with ui.ZStack():
ui.Rectangle(width=plot_width, height=plot_height)
if not color:
color = 0xFFDDDDDD
plot = ui.Plot(
type,
min,
max,
*data,
value_stride=value_stride,
width=plot_width,
height=plot_height,
style={"color": color, "background_color": 0x0},
)
# Min/Max Helpers
def update_min(model):
plot.scale_min = model.as_float
def update_max(model):
plot.scale_max = model.as_float
ui.Spacer(width=5)
with ui.Frame(width=0):
with ui.VStack(spacing=5):
# Min/Max Fields
max_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max"
).model
max_model.set_value(max)
min_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min"
).model
min_model.set_value(min)
min_model.add_value_changed_fn(update_min)
max_model.add_value_changed_fn(update_max)
ui.Spacer(width=20)
with ui.HStack():
ui.Spacer(width=LABEL_WIDTH + 29)
# Current Value Field (disabled by default)
val_model = ui.FloatDrag(
name="Field",
width=BUTTON_WIDTH,
height=LABEL_HEIGHT,
enabled=False,
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Value",
).model
add_separator()
return plot, val_model
def combo_cb_xyz_plot_builder(
label="",
default_val=False,
on_clicked_fn=lambda x: None,
data=[],
min=-1,
max=1,
type=ui.Type.LINE,
value_stride=1,
tooltip="",
):
"""[summary]
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
default_val (bool, optional): Checkbox default. Defaults to False.
on_clicked_fn (Callable, optional): Checkbox Callback function. Defaults to lambda x: None.
data list(), optional): Data to plat. Defaults to None.
min (int, optional): Min Y Value. Defaults to -1.
max (int, optional): Max Y Value. Defaults to 1.
type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE.
value_stride (int, optional): Width of plot stride. Defaults to 1.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
Tuple(list(ui.Plot), list(AbstractValueModel)): ([plot_0, plot_1, plot_2], [val_model_x, val_model_y, val_model_z])
"""
with ui.VStack(spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
# Checkbox
with ui.Frame(width=0):
with ui.Placer(offset_x=-10, offset_y=0):
with ui.VStack():
SimpleCheckBox(default_val, on_clicked_fn)
ui.Spacer(height=ui.Fraction(1))
ui.Spacer()
# Plots
plot_height = LABEL_HEIGHT * 2 + 13
plot_width = ui.Fraction(1)
with ui.ZStack():
ui.Rectangle(width=plot_width, height=plot_height)
plot_0 = ui.Plot(
type,
min,
max,
*data[0],
value_stride=value_stride,
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::X"],
)
plot_1 = ui.Plot(
type,
min,
max,
*data[1],
value_stride=value_stride,
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::Y"],
)
plot_2 = ui.Plot(
type,
min,
max,
*data[2],
value_stride=value_stride,
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::Z"],
)
def update_min(model):
plot_0.scale_min = model.as_float
plot_1.scale_min = model.as_float
plot_2.scale_min = model.as_float
def update_max(model):
plot_0.scale_max = model.as_float
plot_1.scale_max = model.as_float
plot_2.scale_max = model.as_float
ui.Spacer(width=5)
with ui.Frame(width=0):
with ui.VStack(spacing=5):
max_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max"
).model
max_model.set_value(max)
min_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min"
).model
min_model.set_value(min)
min_model.add_value_changed_fn(update_min)
max_model.add_value_changed_fn(update_max)
ui.Spacer(width=20)
# with ui.HStack():
# ui.Spacer(width=40)
# val_models = xyz_builder()#**{"args":args})
field_labels = [("X", COLOR_X), ("Y", COLOR_Y), ("Z", COLOR_Z), ("W", COLOR_W)]
RECT_WIDTH = 13
# SPACING = 4
with ui.HStack():
ui.Spacer(width=LABEL_WIDTH + 29)
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=RECT_WIDTH)
# value_widget = ui.MultiFloatDragField(
# *args, name="multivalue", min=min, max=max, step=step, h_spacing=RECT_WIDTH + SPACING, v_spacing=2
# ).model
val_model_x = ui.FloatDrag(
name="Field",
width=BUTTON_WIDTH - 5,
height=LABEL_HEIGHT,
enabled=False,
alignment=ui.Alignment.LEFT_CENTER,
tooltip="X Value",
).model
ui.Spacer(width=19)
val_model_y = ui.FloatDrag(
name="Field",
width=BUTTON_WIDTH - 5,
height=LABEL_HEIGHT,
enabled=False,
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Y Value",
).model
ui.Spacer(width=19)
val_model_z = ui.FloatDrag(
name="Field",
width=BUTTON_WIDTH - 5,
height=LABEL_HEIGHT,
enabled=False,
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Z Value",
).model
with ui.HStack():
for i in range(3):
if i != 0:
ui.Spacer(width=BUTTON_WIDTH - 1)
field_label = field_labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": field_label[1]})
ui.Label(field_label[0], name="vector_label", alignment=ui.Alignment.CENTER)
add_separator()
return [plot_0, plot_1, plot_2], [val_model_x, val_model_y, val_model_z]
def add_line_rect_flourish(draw_line=True):
"""Aesthetic element that adds a Line + Rectangle after all UI elements in the row.
Args:
draw_line (bool, optional): Set false to only draw rectangle. Defaults to True.
"""
if draw_line:
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1), alignment=ui.Alignment.CENTER)
ui.Spacer(width=10)
with ui.Frame(width=0):
with ui.VStack():
with ui.Placer(offset_x=0, offset_y=7):
ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER)
ui.Spacer(width=5)
def add_separator():
"""Aesthetic element to adds a Line Separator."""
with ui.VStack(spacing=5):
ui.Spacer()
with ui.HStack():
ui.Spacer(width=LABEL_WIDTH)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
ui.Spacer(width=20)
ui.Spacer()
def add_folder_picker_icon(
on_click_fn,
item_filter_fn=None,
bookmark_label=None,
bookmark_path=None,
dialog_title="Select Output Folder",
button_title="Select Folder",
):
def open_file_picker():
def on_selected(filename, path):
on_click_fn(filename, path)
file_picker.hide()
def on_canceled(a, b):
file_picker.hide()
file_picker = FilePickerDialog(
dialog_title,
allow_multi_selection=False,
apply_button_label=button_title,
click_apply_handler=lambda a, b: on_selected(a, b),
click_cancel_handler=lambda a, b: on_canceled(a, b),
item_filter_fn=item_filter_fn,
enable_versioning_pane=True,
)
if bookmark_label and bookmark_path:
file_picker.toggle_bookmark_from_path(bookmark_label, bookmark_path, True)
with ui.Frame(width=0, tooltip=button_title):
ui.Button(
name="IconButton",
width=24,
height=24,
clicked_fn=open_file_picker,
style=get_style()["IconButton.Image::FolderPicker"],
alignment=ui.Alignment.RIGHT_TOP,
)
def add_folder_picker_btn(on_click_fn):
def open_folder_picker():
def on_selected(a, b):
on_click_fn(a, b)
folder_picker.hide()
def on_canceled(a, b):
folder_picker.hide()
folder_picker = FilePickerDialog(
"Select Output Folder",
allow_multi_selection=False,
apply_button_label="Select Folder",
click_apply_handler=lambda a, b: on_selected(a, b),
click_cancel_handler=lambda a, b: on_canceled(a, b),
)
with ui.Frame(width=0):
ui.Button("SELECT", width=BUTTON_WIDTH, clicked_fn=open_folder_picker, tooltip="Select Folder")
def format_tt(tt):
import string
formated = ""
i = 0
for w in tt.split():
if w.isupper():
formated += w + " "
elif len(w) > 3 or i == 0:
formated += string.capwords(w) + " "
else:
formated += w.lower() + " "
i += 1
return formated
def setup_ui_headers(
ext_id,
file_path,
title="My Custom Extension",
doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html",
overview="",
):
"""Creates the Standard UI Elements at the top of each Isaac Extension.
Args:
ext_id (str): Extension ID.
file_path (str): File path to source code.
title (str, optional): Name of Extension. Defaults to "My Custom Extension".
doc_link (str, optional): Hyperlink to Documentation. Defaults to "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html".
overview (str, optional): Overview Text explaining the Extension. Defaults to "".
"""
ext_manager = omni.kit.app.get_app().get_extension_manager()
extension_path = ext_manager.get_extension_path(ext_id)
ext_path = os.path.dirname(extension_path) if os.path.isfile(extension_path) else extension_path
build_header(ext_path, file_path, title, doc_link)
build_info_frame(overview)
def build_header(
ext_path,
file_path,
title="My Custom Extension",
doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html",
):
"""Title Header with Quick Access Utility Buttons."""
def build_icon_bar():
"""Adds the Utility Buttons to the Title Header"""
with ui.Frame(style=get_style(), width=0):
with ui.VStack():
with ui.HStack():
icon_size = 24
with ui.Frame(tooltip="Open Source Code"):
ui.Button(
name="IconButton",
width=icon_size,
height=icon_size,
clicked_fn=lambda: on_open_IDE_clicked(ext_path, file_path),
style=get_style()["IconButton.Image::OpenConfig"],
# style_type_name_override="IconButton.Image::OpenConfig",
alignment=ui.Alignment.LEFT_CENTER,
# tooltip="Open in IDE",
)
with ui.Frame(tooltip="Open Containing Folder"):
ui.Button(
name="IconButton",
width=icon_size,
height=icon_size,
clicked_fn=lambda: on_open_folder_clicked(file_path),
style=get_style()["IconButton.Image::OpenFolder"],
alignment=ui.Alignment.LEFT_CENTER,
)
with ui.Placer(offset_x=0, offset_y=3):
with ui.Frame(tooltip="Link to Docs"):
ui.Button(
name="IconButton",
width=icon_size - icon_size * 0.25,
height=icon_size - icon_size * 0.25,
clicked_fn=lambda: on_docs_link_clicked(doc_link),
style=get_style()["IconButton.Image::OpenLink"],
alignment=ui.Alignment.LEFT_TOP,
)
with ui.ZStack():
ui.Rectangle(style={"border_radius": 5})
with ui.HStack():
ui.Spacer(width=5)
ui.Label(title, width=0, name="title", style={"font_size": 16})
ui.Spacer(width=ui.Fraction(1))
build_icon_bar()
ui.Spacer(width=5)
def build_info_frame(overview=""):
"""Info Frame with Overview, Instructions, and Metadata for an Extension"""
frame = ui.CollapsableFrame(
title="Information",
height=0,
collapsed=True,
horizontal_clipping=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
label = "Overview"
default_val = overview
tooltip = "Overview"
with ui.VStack(style=get_style(), spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH / 2, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
with ui.ScrollingFrame(
height=LABEL_HEIGHT * 5,
style_type_name_override="ScrollingFrame",
alignment=ui.Alignment.LEFT_TOP,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
text = ui.Label(
default_val,
style_type_name_override="Label::label",
word_wrap=True,
alignment=ui.Alignment.LEFT_TOP,
)
with ui.Frame(width=0, tooltip="Copy To Clipboard"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text),
style=get_style()["IconButton.Image::CopyToClipboard"],
alignment=ui.Alignment.RIGHT_TOP,
)
return
# def build_settings_frame(log_filename="extension.log", log_to_file=False, save_settings=False):
# """Settings Frame for Common Utilities Functions"""
# frame = ui.CollapsableFrame(
# title="Settings",
# height=0,
# collapsed=True,
# horizontal_clipping=False,
# style=get_style(),
# style_type_name_override="CollapsableFrame",
# )
# def on_log_to_file_enabled(val):
# # TO DO
# carb.log_info(f"Logging to {model.get_value_as_string()}:", val)
# def on_save_out_settings(val):
# # TO DO
# carb.log_info("Save Out Settings?", val)
# with frame:
# with ui.VStack(style=get_style(), spacing=5):
# # # Log to File Settings
# # default_output_path = os.path.realpath(os.getcwd())
# # kwargs = {
# # "label": "Log to File",
# # "type": "checkbox_stringfield",
# # "default_val": [log_to_file, default_output_path + "/" + log_filename],
# # "on_clicked_fn": on_log_to_file_enabled,
# # "tooltip": "Log Out to File",
# # "use_folder_picker": True,
# # }
# # model = combo_cb_str_builder(**kwargs)[1]
# # Save Settings on Exit
# # kwargs = {
# # "label": "Save Settings",
# # "type": "checkbox",
# # "default_val": save_settings,
# # "on_clicked_fn": on_save_out_settings,
# # "tooltip": "Save out GUI Settings on Exit.",
# # }
# # cb_builder(**kwargs)
class SearchListItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return f'"{self.name_model.as_string}"'
def name(self):
return self.name_model.as_string
class SearchListItemModel(ui.AbstractItemModel):
"""
Represents the model for lists. It's very easy to initialize it
with any string list:
string_list = ["Hello", "World"]
model = ListModel(*string_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
self._children = [SearchListItem(t) for t in args]
self._filtered = [SearchListItem(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._filtered
def filter_text(self, text):
import fnmatch
self._filtered = []
if len(text) == 0:
for c in self._children:
self._filtered.append(c)
else:
parts = text.split()
# for i in range(len(parts) - 1, -1, -1):
# w = parts[i]
leftover = " ".join(parts)
if len(leftover) > 0:
filter_str = f"*{leftover.lower()}*"
for c in self._children:
if fnmatch.fnmatch(c.name().lower(), filter_str):
self._filtered.append(c)
# This tells the Delegate to update the TreeView
self._item_changed(None)
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
class SearchListItemDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def __init__(self, on_double_click_fn=None):
super().__init__()
self._on_double_click_fn = on_double_click_fn
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
stack = ui.ZStack(height=20, style=get_style())
with stack:
with ui.HStack():
ui.Spacer(width=5)
value_model = model.get_item_value_model(item, column_id)
label = ui.Label(value_model.as_string, name="TreeView.Item")
if not self._on_double_click_fn:
self._on_double_click_fn = self.on_double_click
# Set a double click function
stack.set_mouse_double_clicked_fn(lambda x, y, b, m, l=label: self._on_double_click_fn(b, m, l))
def on_double_click(self, button, model, label):
"""Called when the user double-clicked the item in TreeView"""
if button != 0:
return
def build_simple_search(label="", type="search", model=None, delegate=None, tooltip=""):
"""A Simple Search Bar + TreeView Widget.\n
Pass a list of items through the model, and a custom on_click_fn through the delegate.\n
Returns the SearchWidget so user can destroy it on_shutdown.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "search".
model (ui.AbstractItemModel, optional): Item Model for Search. Defaults to None.
delegate (ui.AbstractItemDelegate, optional): Item Delegate for Search. Defaults to None.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
Tuple(Search Widget, Treeview):
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
with ui.VStack(spacing=5):
def filter_text(item):
model.filter_text(item)
from omni.kit.window.extensions.ext_components import SearchWidget
search_bar = SearchWidget(filter_text)
with ui.ScrollingFrame(
height=LABEL_HEIGHT * 5,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style=get_style(),
style_type_name_override="TreeView.ScrollingFrame",
):
treeview = ui.TreeView(
model,
delegate=delegate,
root_visible=False,
header_visible=False,
style={
"TreeView.ScrollingFrame": {"background_color": 0xFFE0E0E0},
"TreeView.Item": {"color": 0xFF535354, "font_size": 16},
"TreeView.Item:selected": {"color": 0xFF23211F},
"TreeView:selected": {"background_color": 0x409D905C},
}
# name="TreeView",
# style_type_name_override="TreeView",
)
add_line_rect_flourish(False)
return search_bar, treeview
| 62,248 | Python | 38.373182 | 169 | 0.558958 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/common.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import carb.tokens
import omni
from pxr import PhysxSchema, UsdGeom, UsdPhysics
def set_drive_parameters(drive, target_type, target_value, stiffness=None, damping=None, max_force=None):
"""Enable velocity drive for a given joint"""
if target_type == "position":
if not drive.GetTargetPositionAttr():
drive.CreateTargetPositionAttr(target_value)
else:
drive.GetTargetPositionAttr().Set(target_value)
elif target_type == "velocity":
if not drive.GetTargetVelocityAttr():
drive.CreateTargetVelocityAttr(target_value)
else:
drive.GetTargetVelocityAttr().Set(target_value)
if stiffness is not None:
if not drive.GetStiffnessAttr():
drive.CreateStiffnessAttr(stiffness)
else:
drive.GetStiffnessAttr().Set(stiffness)
if damping is not None:
if not drive.GetDampingAttr():
drive.CreateDampingAttr(damping)
else:
drive.GetDampingAttr().Set(damping)
if max_force is not None:
if not drive.GetMaxForceAttr():
drive.CreateMaxForceAttr(max_force)
else:
drive.GetMaxForceAttr().Set(max_force)
| 1,900 | Python | 34.203703 | 105 | 0.693158 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/import_franka.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import math
import weakref
import omni
import omni.ui as ui
from omni.importer.urdf.scripts.ui import (
btn_builder,
get_style,
make_menu_item_description,
setup_ui_headers,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf, PhysicsSchemaTools, PhysxSchema, Sdf, UsdLux, UsdPhysics
from .common import set_drive_parameters
EXTENSION_NAME = "Import Franka"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
ext_manager = omni.kit.app.get_app().get_extension_manager()
self._ext_id = ext_id
self._extension_path = ext_manager.get_extension_path(ext_id)
self._menu_items = [
MenuItemDescription(
name="Import Robots",
sub_menu=[
make_menu_item_description(ext_id, "Franka URDF", lambda a=weakref.proxy(self): a._menu_callback())
],
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
def _build_ui(self):
self._window = omni.ui.Window(
EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Import a Franka Panda via URDF"
doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html"
overview = (
"This Example shows you import a URDF.\n\nPress the 'Open in IDE' button to view the source code."
)
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
dict = {
"label": "Load Robot",
"type": "button",
"text": "Load",
"tooltip": "Load a UR10 Robot into the Scene",
"on_clicked_fn": self._on_load_robot,
}
btn_builder(**dict)
dict = {
"label": "Configure Drives",
"type": "button",
"text": "Configure",
"tooltip": "Configure Joint Drives",
"on_clicked_fn": self._on_config_robot,
}
btn_builder(**dict)
dict = {
"label": "Move to Pose",
"type": "button",
"text": "move",
"tooltip": "Drive the Robot to a specific pose",
"on_clicked_fn": self._on_config_drives,
}
btn_builder(**dict)
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_load_robot(self):
load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._load_franka(load_stage))
async def _load_franka(self, task):
done, pending = await asyncio.wait({task})
if task in done:
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = False
import_config.fix_base = True
import_config.make_default_prim = True
import_config.create_physics_scene = True
omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=self._extension_path + "/data/urdf/robots/franka_description/robots/panda_arm_hand.urdf",
import_config=import_config,
)
camera_state = ViewportCameraState("/OmniverseKit_Persp")
camera_state.set_position_world(Gf.Vec3d(1.22, -1.24, 1.13), True)
camera_state.set_target_world(Gf.Vec3d(-0.96, 1.08, 0.0), True)
stage = omni.usd.get_context().get_stage()
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
plane_path = "/groundPlane"
PhysicsSchemaTools.addGroundPlane(
stage,
plane_path,
"Z",
1500.0,
Gf.Vec3f(0, 0, 0),
Gf.Vec3f([0.5, 0.5, 0.5]),
)
# make sure the ground plane is under root prim and not robot
omni.kit.commands.execute(
"MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True
)
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
def _on_config_robot(self):
stage = omni.usd.get_context().get_stage()
# Set the solver parameters on the articulation
PhysxSchema.PhysxArticulationAPI.Get(stage, "/panda").CreateSolverPositionIterationCountAttr(64)
PhysxSchema.PhysxArticulationAPI.Get(stage, "/panda").CreateSolverVelocityIterationCountAttr(64)
self.joint_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link0/panda_joint1"), "angular")
self.joint_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link1/panda_joint2"), "angular")
self.joint_3 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link2/panda_joint3"), "angular")
self.joint_4 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link3/panda_joint4"), "angular")
self.joint_5 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link4/panda_joint5"), "angular")
self.joint_6 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link5/panda_joint6"), "angular")
self.joint_7 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link6/panda_joint7"), "angular")
self.finger_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_hand/panda_finger_joint1"), "linear")
self.finger_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_hand/panda_finger_joint2"), "linear")
# Set the drive mode, target, stiffness, damping and max force for each joint
set_drive_parameters(self.joint_1, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_2, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_3, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_4, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_5, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_6, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_7, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.finger_1, "position", 0, 1e7, 1e6)
set_drive_parameters(self.finger_2, "position", 0, 1e7, 1e6)
def _on_config_drives(self):
self._on_config_robot() # make sure drives are configured first
# Set the drive mode, target, stiffness, damping and max force for each joint
set_drive_parameters(self.joint_1, "position", math.degrees(0.012))
set_drive_parameters(self.joint_2, "position", math.degrees(-0.57))
set_drive_parameters(self.joint_3, "position", math.degrees(0))
set_drive_parameters(self.joint_4, "position", math.degrees(-2.81))
set_drive_parameters(self.joint_5, "position", math.degrees(0))
set_drive_parameters(self.joint_6, "position", math.degrees(3.037))
set_drive_parameters(self.joint_7, "position", math.degrees(0.741))
set_drive_parameters(self.finger_1, "position", 4)
set_drive_parameters(self.finger_2, "position", 4)
| 9,623 | Python | 47.361809 | 119 | 0.601268 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/import_kaya.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import math
import weakref
import omni
import omni.kit.commands
import omni.ui as ui
from omni.importer.urdf.scripts.ui import (
btn_builder,
get_style,
make_menu_item_description,
setup_ui_headers,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf, PhysicsSchemaTools, Sdf, UsdLux, UsdPhysics
from .common import set_drive_parameters
EXTENSION_NAME = "Import Kaya"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
ext_manager = omni.kit.app.get_app().get_extension_manager()
self._ext_id = ext_id
self._extension_path = ext_manager.get_extension_path(ext_id)
self._menu_items = [
MenuItemDescription(
name="Import Robots",
sub_menu=[
make_menu_item_description(ext_id, "Kaya URDF", lambda a=weakref.proxy(self): a._menu_callback())
],
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
def _build_ui(self):
self._window = omni.ui.Window(
EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Import a Kaya Robot via URDF"
doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html"
overview = "This Example shows you import an NVIDIA Kaya robot via URDF.\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
dict = {
"label": "Load Robot",
"type": "button",
"text": "Load",
"tooltip": "Load a UR10 Robot into the Scene",
"on_clicked_fn": self._on_load_robot,
}
btn_builder(**dict)
dict = {
"label": "Configure Drives",
"type": "button",
"text": "Configure",
"tooltip": "Configure Joint Drives",
"on_clicked_fn": self._on_config_robot,
}
btn_builder(**dict)
dict = {
"label": "Spin Robot",
"type": "button",
"text": "move",
"tooltip": "Spin the Robot in Place",
"on_clicked_fn": self._on_config_drives,
}
btn_builder(**dict)
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_load_robot(self):
load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._load_kaya(load_stage))
async def _load_kaya(self, task):
done, pending = await asyncio.wait({task})
if task in done:
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
import_config.import_inertia_tensor = False
# import_config.distance_scale = 1.0
import_config.fix_base = False
import_config.make_default_prim = True
import_config.create_physics_scene = True
omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=self._extension_path + "/data/urdf/robots/kaya/urdf/kaya.urdf",
import_config=import_config,
)
camera_state = ViewportCameraState("/OmniverseKit_Persp")
camera_state.set_position_world(Gf.Vec3d(-1.0, 1.5, 0.5), True)
camera_state.set_target_world(Gf.Vec3d(0.0, 0.0, 0.0), True)
stage = omni.usd.get_context().get_stage()
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
plane_path = "/groundPlane"
PhysicsSchemaTools.addGroundPlane(
stage, plane_path, "Z", 1500.0, Gf.Vec3f(0, 0, -0.25), Gf.Vec3f([0.5, 0.5, 0.5])
)
# make sure the ground plane is under root prim and not robot
omni.kit.commands.execute(
"MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True
)
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
def _on_config_robot(self):
stage = omni.usd.get_context().get_stage()
# Make all rollers spin freely by removing extra drive API
for axle in range(0, 2 + 1):
for ring in range(0, 1 + 1):
for roller in range(0, 4 + 1):
prim_path = (
"/kaya/axle_"
+ str(axle)
+ "/roller_"
+ str(axle)
+ "_"
+ str(ring)
+ "_"
+ str(roller)
+ "_joint"
)
prim = stage.GetPrimAtPath(prim_path)
# omni.kit.commands.execute(
# "UnapplyAPISchemaCommand",
# api=UsdPhysics.DriveAPI,
# prim=prim,
# api_prefix="drive",
# multiple_api_token="angular",
# )
prim.RemoveAPI(UsdPhysics.DriveAPI, "angular")
def _on_config_drives(self):
self._on_config_robot() # make sure drives are configured first
stage = omni.usd.get_context().get_stage()
# set each axis to spin at a rate of 1 rad/s
axle_0 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_0_joint"), "angular")
axle_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_1_joint"), "angular")
axle_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_2_joint"), "angular")
set_drive_parameters(axle_0, "velocity", math.degrees(1), 0, math.radians(1e7))
set_drive_parameters(axle_1, "velocity", math.degrees(1), 0, math.radians(1e7))
set_drive_parameters(axle_2, "velocity", math.degrees(1), 0, math.radians(1e7))
| 8,253 | Python | 41.328205 | 148 | 0.545499 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/tests/test_urdf.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import os
import numpy as np
import omni.kit.commands
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
import pxr
from pxr import Gf, PhysicsSchemaTools, Sdf, UsdGeom, UsdPhysics, UsdShade
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class TestUrdf(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self._timeline = omni.timeline.get_timeline_interface()
ext_manager = omni.kit.app.get_app().get_extension_manager()
ext_id = ext_manager.get_enabled_extension_id("omni.importer.urdf")
self._extension_path = ext_manager.get_extension_path(ext_id)
self.dest_path = os.path.abspath(self._extension_path + "/tests_out")
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
pass
# After running each test
async def tearDown(self):
# _urdf.release_urdf_interface(self._urdf_interface)
await omni.kit.app.get_app().next_update_async()
pass
# Tests to make sure visual mesh names are incremented
async def test_urdf_mesh_naming(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_names.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
prim = stage.GetPrimAtPath("/test_names/cube/visuals")
prim_range = prim.GetChildren()
# There should be a total of 6 visual meshes after import
self.assertEqual(len(prim_range), 6)
# basic urdf test: joints and links are imported correctly
async def test_urdf_basic(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/test_basic")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints exist
root_joint = stage.GetPrimAtPath("/test_basic/root_joint")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint")
self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint")
fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint")
self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08)
fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2")
self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0)
self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
pass
async def test_urdf_save_to_file(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
dest_path = os.path.abspath(self.dest_path + "/test_basic.usd")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
stage = pxr.Usd.Stage.Open(dest_path)
prim = stage.GetPrimAtPath("/test_basic")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints exist
root_joint = stage.GetPrimAtPath("/test_basic/root_joint")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint")
self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint")
fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint")
self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08)
fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2")
self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0)
self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3)
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
stage = None
pass
async def test_urdf_textured_obj(self):
base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf"
basename = "cube_obj"
dest_path = "{}/{}/{}.usd".format(self.dest_path, basename, basename)
mats_path = "{}/{}/materials".format(self.dest_path, basename)
omni.client.create_folder("{}/{}".format(self.dest_path, basename))
omni.client.create_folder(mats_path)
urdf_path = "{}/{}.urdf".format(base_path, basename)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
result = omni.client.list(mats_path)
self.assertEqual(result[0], omni.client._omniclient.Result.OK)
self.assertEqual(len(result[1]), 4) # Metallic texture is unsuported by assimp on OBJ
pass
async def test_urdf_textured_in_memory(self):
base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf"
basename = "cube_obj"
urdf_path = "{}/{}.urdf".format(base_path, basename)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
pass
async def test_urdf_textured_dae(self):
base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf"
basename = "cube_dae"
dest_path = "{}/{}/{}.usd".format(self.dest_path, basename, basename)
mats_path = "{}/{}/materials".format(self.dest_path, basename)
omni.client.create_folder("{}/{}".format(self.dest_path, basename))
omni.client.create_folder(mats_path)
urdf_path = "{}/{}.urdf".format(base_path, basename)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
result = omni.client.list(mats_path)
self.assertEqual(result[0], omni.client._omniclient.Result.OK)
self.assertEqual(len(result[1]), 1) # only albedo is supported for Collada
pass
async def test_urdf_overwrite_file(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
dest_path = os.path.abspath(self._extension_path + "/data/urdf/tests/tests_out/test_basic.usd")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
stage = pxr.Usd.Stage.Open(dest_path)
prim = stage.GetPrimAtPath("/test_basic")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints exist
root_joint = stage.GetPrimAtPath("/test_basic/root_joint")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint")
self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint")
fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint")
self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08)
fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2")
self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0)
self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
stage = None
pass
# advanced urdf test: test for all the categories of inputs that an urdf can hold
async def test_urdf_advanced(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_advanced.urdf")
stage = omni.usd.get_context().get_stage()
# enable merging fixed joints
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
import_config.default_position_drive_damping = -1 # ignore this setting by making it -1
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
# check if object is there
prim = stage.GetPrimAtPath("/test_advanced")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# check color are imported
mesh = stage.GetPrimAtPath("/test_advanced/link_1/visuals")
self.assertNotEqual(mesh.GetPath(), Sdf.Path.emptyPath)
mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial()
shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader"))
self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0, 0.8, 0), 1e-5))
# check joint properties
elbowPrim = stage.GetPrimAtPath("/test_advanced/link_1/elbow_joint")
self.assertNotEqual(elbowPrim.GetPath(), Sdf.Path.emptyPath)
self.assertAlmostEqual(elbowPrim.GetAttribute("physxJoint:jointFriction").Get(), 0.1)
self.assertAlmostEqual(elbowPrim.GetAttribute("drive:angular:physics:damping").Get(), 0.1)
# check position of a link
joint_pos = elbowPrim.GetAttribute("physics:localPos0").Get()
self.assertTrue(Gf.IsClose(joint_pos, Gf.Vec3f(0, 0, 0.40), 1e-5))
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
# test for importing urdf where fixed joints are merged
async def test_urdf_merge_joints(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_merge_joints.urdf")
stage = omni.usd.get_context().get_stage()
# enable merging fixed joints
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# the merged link shouldn't be there
prim = stage.GetPrimAtPath("/test_merge_joints/link_2")
self.assertEqual(prim.GetPath(), Sdf.Path.emptyPath)
pass
async def test_urdf_mtl(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_mtl.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
mesh = stage.GetPrimAtPath("/test_mtl/cube/visuals")
self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None)
mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial()
shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader"))
print(shader)
self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0.8, 0.0, 0), 1e-5))
async def test_urdf_material(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_material.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
mesh = stage.GetPrimAtPath("/test_material/base/visuals")
self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None)
mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial()
shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader"))
print(shader)
self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(1.0, 0.0, 0.0), 1e-5))
async def test_urdf_mtl_stl(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_mtl_stl.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
mesh = stage.GetPrimAtPath("/test_mtl_stl/cube/visuals")
self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None)
mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial()
shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader"))
print(shader)
self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0.8, 0.0, 0), 1e-5))
async def test_urdf_carter(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/carter/urdf/carter.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = False
status, path = omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config
)
self.assertTrue(path, "/carter")
# TODO add checks here
async def test_urdf_franka(self):
urdf_path = os.path.abspath(
self._extension_path + "/data/urdf/robots/franka_description/robots/panda_arm_hand.urdf"
)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# TODO add checks here'
async def test_urdf_ur10(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/ur10/urdf/ur10.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# TODO add checks here'
async def test_urdf_kaya(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/kaya/urdf/kaya.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = False
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# TODO add checks here
async def test_missing(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_missing.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# This sample corresponds to the example in the docs, keep this and the version in the docs in sync
async def test_doc_sample(self):
import omni.kit.commands
from pxr import Gf, Sdf, UsdLux, UsdPhysics
# setting up import configuration:
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = False
import_config.convex_decomp = False
import_config.import_inertia_tensor = True
import_config.fix_base = False
# Get path to extension data:
ext_manager = omni.kit.app.get_app().get_extension_manager()
ext_id = ext_manager.get_enabled_extension_id("omni.importer.urdf")
extension_path = ext_manager.get_extension_path(ext_id)
# import URDF
omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=extension_path + "/data/urdf/robots/carter/urdf/carter.urdf",
import_config=import_config,
)
# get stage handle
stage = omni.usd.get_context().get_stage()
# enable physics
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
# set gravity
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
# add ground plane
PhysicsSchemaTools.addGroundPlane(stage, "/World/groundPlane", "Z", 1500, Gf.Vec3f(0, 0, -50), Gf.Vec3f(0.5))
# add lighting
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
####
#### Next Docs section
####
# get handle to the Drive API for both wheels
left_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/left_wheel"), "angular")
right_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/right_wheel"), "angular")
# Set the velocity drive target in degrees/second
left_wheel_drive.GetTargetVelocityAttr().Set(150)
right_wheel_drive.GetTargetVelocityAttr().Set(150)
# Set the drive damping, which controls the strength of the velocity drive
left_wheel_drive.GetDampingAttr().Set(15000)
right_wheel_drive.GetDampingAttr().Set(15000)
# Set the drive stiffness, which controls the strength of the position drive
# In this case because we want to do velocity control this should be set to zero
left_wheel_drive.GetStiffnessAttr().Set(0)
right_wheel_drive.GetStiffnessAttr().Set(0)
# Make sure that a urdf with more than 63 links imports
async def test_64(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_large.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/test_large")
self.assertTrue(prim)
# basic urdf test: joints and links are imported correctly
async def test_urdf_floating(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_floating.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/test_floating")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints exist
root_joint = stage.GetPrimAtPath("/test_floating/root_joint")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
link_1 = stage.GetPrimAtPath("/test_floating/link_1")
self.assertNotEqual(link_1.GetPath(), Sdf.Path.emptyPath)
link_1_trans = np.array(omni.usd.get_world_transform_matrix(link_1).ExtractTranslation())
self.assertAlmostEqual(np.linalg.norm(link_1_trans - np.array([0, 0, 0.45])), 0, delta=0.03)
floating_link = stage.GetPrimAtPath("/test_floating/floating_link")
self.assertNotEqual(floating_link.GetPath(), Sdf.Path.emptyPath)
floating_link_trans = np.array(omni.usd.get_world_transform_matrix(floating_link).ExtractTranslation())
self.assertAlmostEqual(np.linalg.norm(floating_link_trans - np.array([0, 0, 1.450])), 0, delta=0.03)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
async def test_urdf_scale(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.distance_scale = 1.0
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
pass
async def test_urdf_drive_none(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
from omni.importer.urdf._urdf import UrdfJointTargetType
import_config.default_drive_type = UrdfJointTargetType.JOINT_DRIVE_NONE
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
self.assertFalse(stage.GetPrimAtPath("/test_basic/root_joint").HasAPI(UsdPhysics.DriveAPI))
self.assertTrue(stage.GetPrimAtPath("/test_basic/link_1/elbow_joint").HasAPI(UsdPhysics.DriveAPI))
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
async def test_urdf_usd(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_usd.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
from omni.importer.urdf._urdf import UrdfJointTargetType
import_config.default_drive_type = UrdfJointTargetType.JOINT_DRIVE_NONE
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
self.assertNotEqual(stage.GetPrimAtPath("/test_usd/cube/visuals/mesh_0/Cylinder"), Sdf.Path.emptyPath)
self.assertNotEqual(stage.GetPrimAtPath("/test_usd/cube/visuals/mesh_1/Torus"), Sdf.Path.emptyPath)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
# test negative joint limits
async def test_urdf_limits(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_limits.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
# ensure the import completed.
prim = stage.GetPrimAtPath("/test_limits")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# ensure the joint limits are set on the elbow
elbowJoint = stage.GetPrimAtPath("/test_limits/link_1/elbow_joint")
self.assertNotEqual(elbowJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(elbowJoint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertTrue(elbowJoint.HasAPI(UsdPhysics.DriveAPI))
# ensure the joint limits are set on the wrist
wristJoint = stage.GetPrimAtPath("/test_limits/link_2/wrist_joint")
self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertTrue(wristJoint.HasAPI(UsdPhysics.DriveAPI))
# ensure the joint limits are set on the finger1
finger1Joint = stage.GetPrimAtPath("/test_limits/palm_link/finger_1_joint")
self.assertNotEqual(finger1Joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(finger1Joint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertTrue(finger1Joint.HasAPI(UsdPhysics.DriveAPI))
# ensure the joint limits are set on the finger2
finger2Joint = stage.GetPrimAtPath("/test_limits/palm_link/finger_2_joint")
self.assertNotEqual(finger2Joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(finger2Joint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertTrue(finger2Joint.HasAPI(UsdPhysics.DriveAPI))
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
# test collision from visuals
async def test_collision_from_visuals(self):
# import a urdf file without collision
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_collision_from_visuals.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.set_collision_from_visuals(True)
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
# ensure the import completed.
prim = stage.GetPrimAtPath("/test_collision_from_visuals")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# ensure the base_link collision prim exists and has the collision API applied.
base_link = stage.GetPrimAtPath("/test_collision_from_visuals/base_link/collisions")
self.assertNotEqual(base_link.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(base_link.GetAttribute("physics:collisionEnabled").Get())
# ensure the link_1 collision prim exists and has the collision API applied.
link_1 = stage.GetPrimAtPath("/test_collision_from_visuals/link_1/collisions")
self.assertNotEqual(link_1.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(link_1.GetAttribute("physics:collisionEnabled").Get())
# ensure the link_2 collision prim exists and has the collision API applied.
link_2 = stage.GetPrimAtPath("/test_collision_from_visuals/link_2/collisions")
self.assertNotEqual(link_2.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(link_2.GetAttribute("physics:collisionEnabled").Get())
# ensure the palm_link collision prim exists and has the collision API applied.
palm_link = stage.GetPrimAtPath("/test_collision_from_visuals/palm_link/collisions")
self.assertNotEqual(palm_link.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(palm_link.GetAttribute("physics:collisionEnabled").Get())
# ensure the finger_link_1 collision prim exists and has the collision API applied.
finger_link_1 = stage.GetPrimAtPath("/test_collision_from_visuals/finger_link_1/collisions")
self.assertNotEqual(finger_link_1.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(finger_link_1.GetAttribute("physics:collisionEnabled").Get())
# ensure the finger_link_2 collision prim exists and has the collision API applied.
finger_link_2 = stage.GetPrimAtPath("/test_collision_from_visuals/finger_link_2/collisions")
self.assertNotEqual(finger_link_2.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(finger_link_2.GetAttribute("physics:collisionEnabled").Get())
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(2.0)
# nothing crashes
self._timeline.stop()
pass
| 31,541 | Python | 46.646526 | 142 | 0.682287 |
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/rep_widgets.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from .widgets import MinMaxWidget, CustomDirectory, PathWidget
from .utils import *
from pxr import Sdf
from pathlib import Path
import omni.kit.notification_manager as nm
TEXTURE_DIR = Path(__file__).parent / "data"
SCRATCHES_DIR = TEXTURE_DIR / "scratches"
# Parameter Objects
class DefectParameters:
def __init__(self) -> None:
self.semantic_label = ui.SimpleStringModel("defect")
self.count = ui.SimpleIntModel(1)
self._build_semantic_label()
self.defect_text = CustomDirectory("Defect Texture Folder",
default_dir=str(SCRATCHES_DIR.as_posix()),
tooltip="A folder location containing a single or set of textures (.png)",
file_types=[("*.png", "PNG"), ("*", "All Files")])
self.dim_w = MinMaxWidget("Defect Dimensions Width",
min_value=0.1,
tooltip="Defining the Minimum and Maximum Width of the Defect")
self.dim_h = MinMaxWidget("Defect Dimensions Length",
min_value=0.1,
tooltip="Defining the Minimum and Maximum Length of the Defect")
self.rot = MinMaxWidget("Defect Rotation",
tooltip="Defining the Minimum and Maximum Rotation of the Defect")
def _build_semantic_label(self):
with ui.HStack(height=0, tooltip="The label that will be associated with the defect"):
ui.Label("Defect Semantic")
ui.StringField(model=self.semantic_label)
def destroy(self):
self.semantic_label = None
self.defect_text.destroy()
self.defect_text = None
self.dim_w.destroy()
self.dim_w = None
self.dim_h.destroy()
self.dim_h = None
self.rot.destroy()
self.rot = None
class ObjectParameters():
def __init__(self) -> None:
self.target_prim = PathWidget("Target Prim")
def apply_primvars(prim):
# Apply prim vars
prim.CreateAttribute('primvars:d1_forward_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0))
prim.CreateAttribute('primvars:d1_right_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0))
prim.CreateAttribute('primvars:d1_up_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0))
prim.CreateAttribute('primvars:d1_position', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0))
prim.CreateAttribute('primvars:v3_scale', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0))
nm.post_notification(f"Applied Primvars to: {prim.GetPath()}", hide_after_timeout=True, duration=5, status=nm.NotificationStatus.INFO)
def apply():
# Check Paths
if not check_path(self.target_prim.path_value):
return
# Check if prim is valid
prim = is_valid_prim(self.target_prim.path_value)
if prim is None:
return
apply_primvars(prim)
ui.Button("Apply",
style={"padding": 5},
clicked_fn=lambda: apply(),
tooltip="Apply Primvars and Material to selected Prim."
)
def destroy(self):
self.target_prim.destroy()
self.target_prim = None
class MaterialParameters():
def __init__(self) -> None:
pass | 4,224 | Python | 40.831683 | 146 | 0.608191 |
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/widgets.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from omni.kit.window.file_importer import get_file_importer
from typing import List
import carb
import omni.usd
class CustomDirectory:
def __init__(self, label: str, tooltip: str = "", default_dir: str = "", file_types: List[str] = None) -> None:
self._label_text = label
self._tooltip = tooltip
self._file_types = file_types
self._dir = ui.SimpleStringModel(default_dir)
self._build_directory()
@property
def directory(self) -> str:
"""
Selected Directory name from file importer
:type: str
"""
return self._dir.get_value_as_string()
def _build_directory(self):
with ui.HStack(height=0, tooltip=self._tooltip):
ui.Label(self._label_text)
ui.StringField(model=self._dir)
ui.Button("Open", width=0, style={"padding": 5}, clicked_fn=self._pick_directory)
def _pick_directory(self):
file_importer = get_file_importer()
if not file_importer:
carb.log_warning("Unable to get file importer")
file_importer.show_window(title="Select Folder",
import_button_label="Import Directory",
import_handler=self.import_handler,
file_extension_types=self._file_types
)
def import_handler(self, filename: str, dirname: str, selections: List[str] = []):
self._dir.set_value(dirname)
def destroy(self):
self._dir = None
class MinMaxWidget:
def __init__(self, label: str, min_value: float = 0, max_value: float = 1, tooltip: str = "") -> None:
self._min_model = ui.SimpleFloatModel(min_value)
self._max_model = ui.SimpleFloatModel(max_value)
self._label_text = label
self._tooltip = tooltip
self._build_min_max()
@property
def min_value(self) -> float:
"""
Min Value of the UI
:type: int
"""
return self._min_model.get_value_as_float()
@property
def max_value(self) -> float:
"""
Max Value of the UI
:type: int
"""
return self._max_model.get_value_as_float()
def _build_min_max(self):
with ui.HStack(height=0, tooltip=self._tooltip):
ui.Label(self._label_text)
with ui.HStack():
ui.Label("Min", width=0)
ui.FloatDrag(model=self._min_model)
ui.Label("Max", width=0)
ui.FloatDrag(model=self._max_model)
def destroy(self):
self._max_model = None
self._min_model = None
class PathWidget:
def __init__(self, label: str, button_label: str = "Copy", read_only: bool = False, tooltip: str = "") -> None:
self._label_text = label
self._tooltip = tooltip
self._button_label = button_label
self._read_only = read_only
self._path_model = ui.SimpleStringModel()
self._top_stack = ui.HStack(height=0, tooltip=self._tooltip)
self._button = None
self._build()
@property
def path_value(self) -> str:
"""
Path of the Prim in the scene
:type: str
"""
return self._path_model.get_value_as_string()
@path_value.setter
def path_value(self, value) -> None:
"""
Sets the path value
:type: str
"""
self._path_model.set_value(value)
def _build(self):
def copy():
ctx = omni.usd.get_context()
selection = ctx.get_selection().get_selected_prim_paths()
if len(selection) > 0:
self._path_model.set_value(str(selection[0]))
with self._top_stack:
ui.Label(self._label_text)
ui.StringField(model=self._path_model, read_only=self._read_only)
self._button = ui.Button(self._button_label, width=0, style={"padding": 5}, clicked_fn=lambda: copy(), tooltip="Copies the Current Selected Path in the Stage")
def destroy(self):
self._path_model = None
| 4,815 | Python | 31.986301 | 171 | 0.58837 |
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/extension.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ext
from .window import DefectsWindow
class DefectsGenerator(omni.ext.IExt):
WINDOW_NAME = "Defects Sample Extension"
MENU_PATH = f"Window/{WINDOW_NAME}"
def __init__(self) -> None:
super().__init__()
self._window = None
def on_startup(self, ext_id):
self._menu = omni.kit.ui.get_editor_menu().add_item(
DefectsGenerator.MENU_PATH, self.show_window, toggle=True, value=True
)
self.show_window(None, True)
def on_shutdown(self):
if self._menu:
omni.kit.ui.get_editor_menu().remove_item(DefectsGenerator.MENU_PATH)
self._menu
if self._window:
self._window.destroy()
self._window = None
def _set_menu(self, value):
omni.kit.ui.get_editor_menu().set_value(DefectsGenerator.MENU_PATH, value)
def _visibility_changed_fn(self, visible):
self._set_menu(visible)
if not visible:
self._window = None
def show_window(self, menu, value):
self._set_menu(value)
if value:
self._set_menu(True)
self._window = DefectsWindow(DefectsGenerator.WINDOW_NAME, width=450, height=700)
self._window.set_visibility_changed_fn(self._visibility_changed_fn)
elif self._window:
self._window.visible = False
| 2,037 | Python | 34.13793 | 98 | 0.65783 |
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.usd
import carb
import omni.kit.commands
import os
def get_current_stage():
context = omni.usd.get_context()
stage = context.get_stage()
return stage
def check_path(path: str) -> bool:
if not path:
carb.log_error("No path was given")
return False
return True
def is_valid_prim(path: str):
prim = get_prim(path)
if not prim.IsValid():
carb.log_warn(f"No valid prim at path given: {path}")
return None
return prim
def delete_prim(path: str):
omni.kit.commands.execute('DeletePrims',
paths=[path],
destructive=False)
def get_prim_attr(prim_path: str, attr_name: str):
prim = get_prim(prim_path)
return prim.GetAttribute(attr_name).Get()
def get_textures(dir_path, png_type=".png"):
textures = []
dir_path += "/"
for file in os.listdir(dir_path):
if file.endswith(png_type):
textures.append(dir_path + file)
return textures
def get_prim(prim_path: str):
stage = get_current_stage()
prim = stage.GetPrimAtPath(prim_path)
return prim
| 1,768 | Python | 28 | 98 | 0.687783 |
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import carb
import omni.ui as ui
from omni.ui import DockPreference
from .style import *
from .widgets import CustomDirectory
from .replicator_defect import create_defect_layer, rep_preview, does_defect_layer_exist, rep_run, get_defect_layer
from .rep_widgets import DefectParameters, ObjectParameters
from .utils import *
from pathlib import Path
class DefectsWindow(ui.Window):
def __init__(self, title: str, dockPreference: DockPreference = DockPreference.DISABLED, **kwargs) -> None:
super().__init__(title, dockPreference, **kwargs)
# Models
self.frames = ui.SimpleIntModel(1, min=1)
self.rt_subframes = ui.SimpleIntModel(1, min=1)
# Widgets
self.defect_params = None
self.object_params = None
self.output_dir = None
self.frame_change = None
self.frame.set_build_fn(self._build_frame)
def _build_collapse_base(self, label: str, collapsed: bool = False):
v_stack = None
with ui.CollapsableFrame(label, height=0, collapsed=collapsed):
with ui.ZStack():
ui.Rectangle()
v_stack = ui.VStack()
return v_stack
def _build_frame(self):
with self.frame:
with ui.ScrollingFrame(style=default_defect_main):
with ui.VStack(style={"margin": 3}):
self._build_object_param()
self._build_defect_param()
self._build_replicator_param()
def _build_object_param(self):
with self._build_collapse_base("Object Parameters"):
self.object_params = ObjectParameters()
def _build_defect_param(self):
with self._build_collapse_base("Defect Parameters"):
self.defect_params = DefectParameters()
def _build_replicator_param(self):
def preview_data():
if does_defect_layer_exist():
rep_preview()
else:
create_defect_layer(self.defect_params, self.object_params)
self.rep_layer_button.text = "Recreate Replicator Graph"
def remove_replicator_graph():
if get_defect_layer() is not None:
layer, pos = get_defect_layer()
omni.kit.commands.execute('RemoveSublayer',
layer_identifier=layer.identifier,
sublayer_position=pos)
if is_valid_prim('/World/Looks/ProjectPBRMaterial'):
delete_prim('/World/Looks/ProjectPBRMaterial')
if is_valid_prim(self.object_params.target_prim.path_value + "/Projection"):
delete_prim(self.object_params.target_prim.path_value + "/Projection")
if is_valid_prim('/Replicator'):
delete_prim('/Replicator')
def run_replicator():
remove_replicator_graph()
total_frames = self.frames.get_value_as_int()
subframes = self.rt_subframes.get_value_as_int()
if subframes <= 0:
subframes = 0
if total_frames > 0:
create_defect_layer(self.defect_params, self.object_params, total_frames, self.output_dir.directory, subframes, self._use_seg.as_bool, self._use_bb.as_bool)
self.rep_layer_button.text = "Recreate Replicator Graph"
rep_run()
else:
carb.log_error(f"Number of frames is {total_frames}. Input value needs to be greater than 0.")
def create_replicator_graph():
remove_replicator_graph()
create_defect_layer(self.defect_params, self.object_params)
self.rep_layer_button.text = "Recreate Replicator Graph"
def set_text(label, model):
label.text = model.as_string
with self._build_collapse_base("Replicator Parameters"):
home_dir = Path.home()
valid_out_dir = home_dir / "omni.replicator_out"
self.output_dir = CustomDirectory("Output Directory", default_dir=str(valid_out_dir.as_posix()), tooltip="Directory to specify where the output files will be stored. Default is [DRIVE/Users/USER/omni.replicator_out]")
with ui.HStack(height=0, tooltip="Check off which annotator you want to use; You can also use both"):
ui.Label("Annotations: ", width=0)
ui.Spacer()
ui.Label("Segmentation", width=0)
self._use_seg = ui.CheckBox().model
ui.Label("Bounding Box", width=0)
self._use_bb = ui.CheckBox().model
ui.Spacer()
with ui.HStack(height=0):
ui.Label("Render Subframe Count: ", width=0,
tooltip="Defines how many subframes of rendering occur before going to the next frame")
ui.Spacer(width=ui.Fraction(0.25))
ui.IntField(model=self.rt_subframes)
self.rep_layer_button = ui.Button("Create Replicator Layer",
clicked_fn=lambda: create_replicator_graph(),
tooltip="Creates/Recreates the Replicator Graph, based on the current Defect Parameters")
with ui.HStack(height=0):
ui.Button("Preview", width=0, clicked_fn=lambda: preview_data(),
tooltip="Preview a Replicator Scene")
ui.Label("or", width=0)
ui.Button("Run for", width=0, clicked_fn=lambda: run_replicator(),
tooltip="Run replicator for so many frames")
with ui.ZStack(width=0):
l = ui.Label("", style={"color": ui.color.transparent, "margin_width": 10})
self.frame_change = ui.StringField(model=self.frames)
self.frame_change_cb = self.frame_change.model.add_value_changed_fn(lambda m, l=l: set_text(l, m))
ui.Label("frame(s)")
def destroy(self) -> None:
self.frames = None
self.defect_semantic = None
if self.frame_change is not None:
self.frame_change.model.remove_value_changed_fn(self.frame_change_cb)
if self.defect_params is not None:
self.defect_params.destroy()
self.defect_params = None
if self.object_params is not None:
self.object_params.destroy()
self.object_params = None
return super().destroy()
| 7,174 | Python | 46.833333 | 229 | 0.597017 |
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/replicator_defect.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.replicator.core as rep
import carb
from .rep_widgets import DefectParameters, ObjectParameters
from .utils import *
camera_path = "/World/Camera"
def rep_preview():
rep.orchestrator.preview()
def rep_run():
rep.orchestrator.run()
def does_defect_layer_exist() -> bool:
stage = get_current_stage()
for layer in stage.GetLayerStack():
if layer.GetDisplayName() == "Defect":
return True
return False
def get_defect_layer():
stage = get_current_stage()
pos = 0
for layer in stage.GetLayerStack():
if layer.GetDisplayName() == "Defect":
return layer, pos
pos = pos + 1
return None
def create_randomizers(defect_params: DefectParameters, object_params: ObjectParameters):
diffuse_textures = get_textures(defect_params.defect_text.directory, "_D.png")
normal_textures = get_textures(defect_params.defect_text.directory, "_N.png")
roughness_textures = get_textures(defect_params.defect_text.directory, "_R.png")
def move_defect():
defects = rep.get.prims(semantics=[('class', defect_params.semantic_label.as_string + '_mesh')])
plane = rep.get.prim_at_path(object_params.target_prim.path_value)
with defects:
rep.randomizer.scatter_2d(plane)
rep.modify.pose(
rotation=rep.distribution.uniform(
(defect_params.rot.min_value, 0, 90),
(defect_params.rot.max_value, 0, 90)
),
scale=rep.distribution.uniform(
(1, defect_params.dim_h.min_value,defect_params.dim_w.min_value),
(1, defect_params.dim_h.max_value, defect_params.dim_w.max_value)
)
)
return defects.node
def change_defect_image():
projections = rep.get.prims(semantics=[('class', defect_params.semantic_label.as_string + '_projectmat')])
with projections:
rep.modify.projection_material(
diffuse=rep.distribution.sequence(diffuse_textures),
normal=rep.distribution.sequence(normal_textures),
roughness=rep.distribution.sequence(roughness_textures))
return projections.node
rep.randomizer.register(move_defect)
rep.randomizer.register(change_defect_image)
def create_camera(target_path):
if is_valid_prim(camera_path) is None:
camera = rep.create.camera(position=1000, look_at=rep.get.prim_at_path(target_path))
carb.log_info(f"Creating Camera: {camera}")
else:
camera = rep.get.prim_at_path(camera_path)
return camera
def create_defects(defect_params: DefectParameters, object_params: ObjectParameters):
target_prim = rep.get.prims(path_pattern=object_params.target_prim.path_value)
count = 1
if defect_params.count.as_int > 1:
count = defect_params.count.as_int
for i in range(count):
cube = rep.create.cube(visible=False, semantics=[('class', defect_params.semantic_label.as_string + '_mesh')], position=0, scale=1, rotation=(0, 0, 90))
with target_prim:
rep.create.projection_material(cube, [('class', defect_params.semantic_label.as_string + '_projectmat')])
def create_defect_layer(defect_params: DefectParameters, object_params: ObjectParameters, frames: int = 1, output_dir: str = "_defects", rt_subframes: int = 0, use_seg: bool = False, use_bb: bool = True):
if len(defect_params.defect_text.directory) <= 0:
carb.log_error("No directory selected")
return
with rep.new_layer("Defect"):
create_defects(defect_params, object_params)
create_randomizers(defect_params=defect_params, object_params=object_params)
# Create / Get camera
camera = create_camera(object_params.target_prim.path_value)
# Add Default Light
distance_light = rep.create.light(rotation=(315,0,0), intensity=3000, light_type="distant")
render_product = rep.create.render_product(camera, (1024, 1024))
# Initialize and attach writer
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(output_dir=output_dir, rgb=True, semantic_segmentation=use_seg, bounding_box_2d_tight=use_bb)
# Attach render_product to the writer
writer.attach([render_product])
# Setup randomization
with rep.trigger.on_frame(num_frames=frames, rt_subframes=rt_subframes):
rep.randomizer.move_defect()
rep.randomizer.change_defect_image()
| 5,247 | Python | 40.984 | 204 | 0.66438 |
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/extension.py | # SPDX-License-Identifier: Apache-2.0
import asyncio
import aiohttp
import carb
import omni.ext
import omni.ui as ui
class APIWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
"""
Initialize the widget.
Args:
title : Title of the widget. This is used to display the window title on the GUI.
"""
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
# async function to get the color palette from huemint.com and print it
async def get_colors_from_api(self, color_widgets):
"""
Get colors from HueMint API and store them in color_widgets.
Args:
color_widgets : List of widgets to
"""
# Create the task for progress indication and change button text
self.button.text = "Loading"
task = asyncio.create_task(self.run_forever())
# Create a aiohttp session to make the request, building the url and the data to send
# By default it will timeout after 5 minutes.
# See more here: https://docs.aiohttp.org/en/latest/client_quickstart.html
async with aiohttp.ClientSession() as session:
url = "https://api.huemint.com/color"
data = {
"mode": "transformer", # transformer, diffusion or random
"num_colors": "5", # max 12, min 2
"temperature": "1.2", # max 2.4, min 0
"num_results": "1", # max 50 for transformer, 5 for diffusion
"adjacency": ["0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0",
], # nxn adjacency matrix as a flat array of strings
"palette": ["-", "-", "-", "-", "-"], # locked colors as hex codes, or '-' if blank
}
# make the request
try:
async with session.post(url, json=data) as resp:
# get the response as json
result = await resp.json(content_type=None)
# get the palette from the json
palette = result["results"][0]["palette"]
# apply the colors to the color widgets
await self.apply_colors(palette, color_widgets)
# Cancel the progress indication and return the button to the original text
task.cancel()
self.button.text = "Refresh"
except Exception as e:
carb.log_info(f"Caught Exception {e}")
# Cancel the progress indication and return the button to the original text
task.cancel()
self.button.text = "Connection Timed Out \nClick to Retry"
# apply the colors fetched from the api to the color widgets
async def apply_colors(self, palette, color_widgets):
"""
Apply the colors to the ColorWidget. This is a helper method to allow us to get the color values
from the API and set them in the color widgets
Args:
palette : The palette that we want to apply
color_widgets : The list of color widgets
"""
colors = [palette[i] for i in range(5)]
index = 0
# This will fetch the RGB colors from the color widgets and set them to the color of the color widget.
for color_widget in color_widgets:
await omni.kit.app.get_app().next_update_async()
# we get the individual RGB colors from ColorWidget model
color_model = color_widget.model
children = color_model.get_item_children()
hex_to_float = self.hextofloats(colors[index])
# we set the color of the color widget to the color fetched from the api
color_model.get_item_value_model(children[0]).set_value(hex_to_float[0])
color_model.get_item_value_model(children[1]).set_value(hex_to_float[1])
color_model.get_item_value_model(children[2]).set_value(hex_to_float[2])
index = index + 1
async def run_forever(self):
"""
Run the loop until we get a response from omni.
"""
count = 0
dot_count = 0
# Update the button text.
while True:
# Reset the button text to Loading
if count % 10 == 0:
# Reset the text for the button
# Add a dot after Loading.
if dot_count == 3:
self.button.text = "Loading"
dot_count = 0
# Add a dot after Loading
else:
self.button.text += "."
dot_count += 1
count += 1
await omni.kit.app.get_app().next_update_async()
# hex to float conversion for transforming hex color codes to float values
def hextofloats(self, h):
"""
Convert hex values to floating point numbers. This is useful for color conversion to a 3 or 5 digit hex value
Args:
h : RGB string in the format 0xRRGGBB
Returns:
float tuple of ( r g b ) where r g b are floats between 0 and 1 and b
"""
# Convert hex rgb string in an RGB tuple (float, float, float)
return tuple(int(h[i : i + 2], 16) / 255.0 for i in (1, 3, 5)) # skip '#'
def _build_fn(self):
"""
Build the function to call the api when the app starts.
"""
with self.frame:
with ui.VStack(alignment=ui.Alignment.CENTER):
# Get the run loop
run_loop = asyncio.get_event_loop()
ui.Label("Click the button to get a new color palette", height=30, alignment=ui.Alignment.CENTER)
with ui.HStack(height=100):
color_widgets = [ui.ColorWidget(1, 1, 1) for i in range(5)]
def on_click():
"""
Get colors from API and run task in run_loop. This is called when user clicks the button
"""
run_loop.create_task(self.get_colors_from_api(color_widgets))
# create a button to trigger the api call
self.button = ui.Button("Refresh", clicked_fn=on_click)
# we execute the api call once on startup
run_loop.create_task(self.get_colors_from_api(color_widgets))
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
"""
Called when the extension is started.
Args:
ext_id - id of the extension
"""
print("[omni.example.apiconnect] MyExtension startup")
# create a new window
self._window = APIWindowExample("API Connect Demo - HueMint", width=260, height=270)
def on_shutdown(self):
"""
Called when the extension is shut down. Destroys the window if it exists and sets it to None
"""
print("[omni.example.apiconnect] MyExtension shutdown")
# Destroys the window and releases the reference to the window.
if self._window:
self._window.destroy()
self._window = None
| 7,649 | Python | 40.351351 | 130 | 0.569355 |
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/__init__.py | # SPDX-License-Identifier: Apache-2.0
from .extension import *
| 64 | Python | 15.249996 | 37 | 0.75 |
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/__init__.py | from .extension import ExampleViewportReticleExtension
| 55 | Python | 26.999987 | 54 | 0.909091 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/style.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["main_window_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
fl_attr_hspacing = 10
fl_attr_spacing = 1
fl_group_spacing = 5
cl_attribute_dark = cl("#202324")
cl_attribute_red = cl("#ac6060")
cl_attribute_green = cl("#60ab7c")
cl_attribute_blue = cl("#35889e")
cl_line = cl("#404040")
cl_text_blue = cl("#5eb3ff")
cl_text_gray = cl("#707070")
cl_text = cl("#a1a1a1")
cl_text_hovered = cl("#ffffff")
cl_field_text = cl("#5f5f5f")
cl_widget_background = cl("#1f2123")
cl_attribute_default = cl("#505050")
cl_attribute_changed = cl("#55a5e2")
cl_slider = cl("#383b3e")
cl_combobox_background = cl("#252525")
cl_main_background = cl("#2a2b2c")
cls_temperature_gradient = [cl("#fe0a00"), cl("#f4f467"), cl("#a8b9ea"), cl("#2c4fac"), cl("#274483"), cl("#1f334e")]
cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")]
cls_tint_gradient = [cl("#1D1D92"), cl("#7E7EC9"), cl("#FFFFFF")]
cls_grey_gradient = [cl("#020202"), cl("#525252"), cl("#FFFFFF")]
cls_button_gradient = [cl("#232323"), cl("#656565")]
# The main style dict
main_window_style = {
"Button::add": {"background_color": cl_widget_background},
"Field::add": { "font_size": 14, "color": cl_text},
"Field::search": { "font_size": 16, "color": cl_field_text},
"Field::path": { "font_size": 14, "color": cl_field_text},
"ScrollingFrame::main_frame": {"background_color": cl_main_background},
# for CollapsableFrame
"CollapsableFrame::group": {
"margin_height": fl_group_spacing,
"background_color": 0x0,
"secondary_color": 0x0,
},
"CollapsableFrame::group:hovered": {
"margin_height": fl_group_spacing,
"background_color": 0x0,
"secondary_color": 0x0,
},
# for Secondary CollapsableFrame
"Circle::group_circle": {
"background_color": cl_line,
},
"Line::group_line": {"color": cl_line},
# all the labels
"Label::collapsable_name": {
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl_text
},
"Label::attribute_bool": {
"alignment": ui.Alignment.LEFT_BOTTOM,
"margin_height": fl_attr_spacing,
"margin_width": fl_attr_hspacing,
"color": cl_text
},
"Label::attribute_name": {
"alignment": ui.Alignment.RIGHT_CENTER,
"margin_height": fl_attr_spacing,
"margin_width": fl_attr_hspacing,
"color": cl_text
},
"Label::attribute_name:hovered": {"color": cl_text_hovered},
"Label::header_attribute_name": {
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl_text
},
"Label::details": {
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl_text_blue,
"font_size": 19,
},
"Label::layers": {
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl_text_gray,
"font_size": 19,
},
"Label::attribute_r": {
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl_attribute_red
},
"Label::attribute_g": {
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl_attribute_green
},
"Label::attribute_b": {
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl_attribute_blue
},
# for Gradient Float Slider
"Slider::float_slider":{
"background_color": cl_widget_background,
"secondary_color": cl_slider,
"border_radius": 3,
"corner_flag": ui.CornerFlag.ALL,
"draw_mode": ui.SliderDrawMode.FILLED,
},
# for color slider
"Circle::slider_handle":{"background_color": 0x0, "border_width": 2, "border_color": cl_combobox_background},
# for Value Changed Widget
"Rectangle::attribute_changed": {"background_color":cl_attribute_changed, "border_radius": 2},
"Rectangle::attribute_default": {"background_color":cl_attribute_default, "border_radius": 1},
# all the images
"Image::pin": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/Pin.svg"},
"Image::expansion": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/Details_options.svg"},
"Image::transform": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/offset_dark.svg"},
"Image::link": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/link_active_dark.svg"},
"Image::on_off": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/on_off.svg"},
"Image::header_frame": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/head.png"},
"Image::checked": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/checked.svg"},
"Image::unchecked": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/unchecked.svg"},
"Image::separator":{"image_url": f"{EXTENSION_FOLDER_PATH}/icons/separator.svg"},
"Image::collapsable_opened": {"color": cl_text, "image_url": f"{EXTENSION_FOLDER_PATH}/icons/closed.svg"},
"Image::collapsable_closed": {"color": cl_text, "image_url": f"{EXTENSION_FOLDER_PATH}/icons/open.svg"},
"Image::combobox": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/combobox_bg.svg"},
# for Gradient Image
"ImageWithProvider::gradient_slider":{"border_radius": 4, "corner_flag": ui.CornerFlag.ALL},
"ImageWithProvider::button_background_gradient": {"border_radius": 3, "corner_flag": ui.CornerFlag.ALL},
# for Customized ComboBox
"ComboBox::dropdown_menu":{
"color": cl_text, # label color
"background_color": cl_combobox_background,
"secondary_color": 0x0, # button background color
},
}
def hex_to_color(hex: int) -> tuple:
# convert Value from int
red = hex & 255
green = (hex >> 8) & 255
blue = (hex >> 16) & 255
alpha = (hex >> 24) & 255
rgba_values = [red, green, blue, alpha]
return rgba_values
def _interpolate_color(hex_min: int, hex_max: int, intep):
max_color = hex_to_color(hex_max)
min_color = hex_to_color(hex_min)
color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)]
return (color[3] << 8 * 3) + (color[2] << 8 * 2) + (color[1] << 8 * 1) + color[0]
def get_gradient_color(value, max, colors):
step_size = len(colors) - 1
step = 1.0/float(step_size)
percentage = value / float(max)
idx = (int) (percentage / step)
if idx == step_size:
color = colors[-1]
else:
color = _interpolate_color(colors[idx], colors[idx+1], percentage)
return color
def generate_byte_data(colors):
data = []
for color in colors:
data += hex_to_color(color)
_byte_provider = ui.ByteImageProvider()
_byte_provider.set_bytes_data(data, [len(colors), 1])
return _byte_provider
def build_gradient_image(colors, height, style_name):
byte_provider = generate_byte_data(colors)
ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name)
return byte_provider | 7,557 | Python | 34.819905 | 117 | 0.633849 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ExampleWindowExtension"]
from .window import PropertyWindowExample
from functools import partial
import asyncio
import omni.ext
import omni.kit.ui
import omni.ui as ui
class ExampleWindowExtension(omni.ext.IExt):
"""The entry point for Gradient Style Window Example"""
WINDOW_NAME = "Gradient Style Window Example"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self):
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None))
# Put the new menu
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
# Show the window. It will call `self.show_window`
ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME)
def on_shutdown(self):
self._menu = None
if self._window:
self._window.destroy()
self._window = None
# Deregister the function that shows the window from omni.ui
ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, None)
def _set_menu(self, value):
"""Set the menu to create this window on and off"""
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(ExampleWindowExtension.MENU_PATH, value)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visiblity_changed_fn(self, visible):
# Called when the user pressed "X"
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, menu, value):
if value:
self._window = PropertyWindowExample(ExampleWindowExtension.WINDOW_NAME, width=450, height=900)
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
| 2,895 | Python | 36.610389 | 108 | 0.666321 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/collapsable_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CustomCollsableFrame"]
import omni.ui as ui
def build_collapsable_header(collapsed, title):
"""Build a custom title of CollapsableFrame"""
with ui.HStack():
ui.Spacer(width=10)
ui.Label(title, name="collapsable_name")
if collapsed:
image_name = "collapsable_opened"
else:
image_name = "collapsable_closed"
ui.Image(name=image_name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=16, height=16)
class CustomCollsableFrame:
"""The compound widget for color input"""
def __init__(self, frame_name, collapsed=False):
with ui.ZStack():
self.collapsable_frame = ui.CollapsableFrame(
frame_name, name="group", build_header_fn=build_collapsable_header, collapsed=collapsed)
with ui.VStack():
ui.Spacer(height=29)
with ui.HStack():
ui.Spacer(width=20)
ui.Image(name="separator", fill_policy=ui.FillPolicy.STRETCH, height=15)
ui.Spacer(width=20)
| 1,519 | Python | 35.190475 | 104 | 0.655036 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/color_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ColorWidget"]
from ctypes import Union
from typing import List, Optional
import omni.ui as ui
from .style import build_gradient_image, cl_attribute_red, cl_attribute_green, cl_attribute_blue, cl_attribute_dark
SPACING = 16
class ColorWidget:
"""The compound widget for color input"""
def __init__(self, *args, model=None, **kwargs):
self.__defaults: List[Union[float, int]] = args
self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None)
self.__multifield: Optional[ui.MultiFloatDragField] = None
self.__colorpicker: Optional[ui.ColorWidget] = None
self.__draw_colorpicker = kwargs.pop("draw_colorpicker", True)
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__model = None
self.__multifield = None
self.__colorpicker = None
self.__frame = None
def __getattr__(self, attr):
"""
Pretend it's self.__frame, so we have access to width/height and
callbacks.
"""
return getattr(self.__root_frame, attr)
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__multifield:
return self.__multifield.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__multifield.model = value
self.__colorpicker.model = value
def _build_fn(self):
def _on_value_changed(model, rect_changed, rect_default):
if model.get_item_value_model().get_value_as_float() != 0:
rect_changed.visible = False
rect_default.visible = True
else:
rect_changed.visible = True
rect_default.visible = False
def _restore_default(model, rect_changed, rect_default):
items = model.get_item_children()
for id, item in enumerate(items):
model.get_item_value_model(item).set_value(self.__defaults[id])
rect_changed.visible = False
rect_default.visible = True
with ui.HStack(spacing=SPACING):
# The construction of multi field depends on what the user provided,
# defaults or a model
if self.__model:
# the user provided a model
self.__multifield = ui.MultiFloatDragField(
min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color"
)
model = self.__model
else:
# the user provided a list of default values
with ui.ZStack():
with ui.HStack():
self.color_button_gradient_R = build_gradient_image([cl_attribute_dark, cl_attribute_red], 22, "button_background_gradient")
ui.Spacer(width=9)
with ui.VStack(width=6):
ui.Spacer(height=8)
ui.Circle(name="group_circle", width=4, height=4)
self.color_button_gradient_G = build_gradient_image([cl_attribute_dark, cl_attribute_green], 22, "button_background_gradient")
ui.Spacer(width=9)
with ui.VStack(width=6):
ui.Spacer(height=8)
ui.Circle(name="group_circle", width=4, height=4)
self.color_button_gradient_B = build_gradient_image([cl_attribute_dark, cl_attribute_blue], 22, "button_background_gradient")
ui.Spacer(width=2)
with ui.HStack():
with ui.VStack():
ui.Spacer(height=1)
self.__multifield = ui.MultiFloatDragField(
*self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color")
ui.Spacer(width=3)
with ui.HStack(spacing=22):
labels = ["R", "G", "B"] if self.__draw_colorpicker else ["X", "Y", "Z"]
ui.Label(labels[0], name="attribute_r")
ui.Label(labels[1], name="attribute_g")
ui.Label(labels[2], name="attribute_b")
model = self.__multifield.model
if self.__draw_colorpicker:
self.__colorpicker = ui.ColorWidget(model, width=0)
rect_changed, rect_default = self.__build_value_changed_widget()
model.add_item_changed_fn(lambda model, i: _on_value_changed(model, rect_changed, rect_default))
rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(model, rect_changed, rect_default))
def __build_value_changed_widget(self):
with ui.VStack(width=0):
ui.Spacer(height=3)
rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False)
ui.Spacer(height=4)
with ui.HStack():
ui.Spacer(width=3)
rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True)
return rect_changed, rect_default
| 5,735 | Python | 43.465116 | 150 | 0.565998 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved./icons/
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["PropertyWindowExample"]
from ast import With
from ctypes import alignment
import omni.kit
import omni.ui as ui
from .style import main_window_style, get_gradient_color, build_gradient_image
from .style import cl_combobox_background, cls_temperature_gradient, cls_color_gradient, cls_tint_gradient, cls_grey_gradient, cls_button_gradient
from .color_widget import ColorWidget
from .collapsable_widget import CustomCollsableFrame, build_collapsable_header
LABEL_WIDTH = 120
SPACING = 10
def _get_plus_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg")
def _get_search_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_search.svg")
class PropertyWindowExample(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = main_window_style
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _build_transform(self):
"""Build the widgets of the "Calculations" group"""
with ui.ZStack():
with ui.VStack():
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer()
ui.Image(name="transform", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=24, height=24)
ui.Spacer(width=30)
ui.Spacer()
with CustomCollsableFrame("TRANSFORMS").collapsable_frame:
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=2)
self._build_vector_widget("Position", 70)
self._build_vector_widget("Rotation", 70)
with ui.ZStack():
self._build_vector_widget("Scale", 85)
with ui.HStack():
ui.Spacer(width=42)
ui.Image(name="link", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20)
def _build_path(self):
CustomCollsableFrame("PATH", collapsed=True)
def _build_light_properties(self):
"""Build the widgets of the "Parameters" group"""
with CustomCollsableFrame("LIGHT PROPERTIES").collapsable_frame:
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=2)
self._build_combobox("Type", ["Sphere Light", "Disk Light", "Rect Light"])
self.color_gradient_data, self.tint_gradient_data, self.grey_gradient_data = self._build_color_widget("Color")
self._build_color_temperature()
self.diffuse_button_data = self._build_gradient_float_slider("Diffuse Multiplier")
self.exposture_button_data = self._build_gradient_float_slider("Exposture")
self.intensity_button_data = self._build_gradient_float_slider("Intensity", default_value=3000, min=0, max=6000)
self._build_checkbox("Normalize Power", False)
self._build_combobox("Purpose", ["Default", "Customized"])
self.radius_button_data = self._build_gradient_float_slider("Radius")
self._build_shaping()
self.specular_button_data = self._build_gradient_float_slider("Specular Multiplier")
self._build_checkbox("Treat As Point")
def _build_line_dot(self, line_width, height):
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack(width=line_width):
ui.Spacer(height=height)
ui.Line(name="group_line", alignment=ui.Alignment.TOP)
with ui.VStack(width=6):
ui.Spacer(height=height-2)
ui.Circle(name="group_circle", width=6, height=6, alignment=ui.Alignment.BOTTOM)
def _build_shaping(self):
"""Build the widgets of the "SHAPING" group"""
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=3)
self._build_line_dot(10, 17)
with ui.HStack():
ui.Spacer(width=13)
with ui.VStack():
ui.Spacer(height=17)
ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0)
ui.Spacer(height=80)
with ui.CollapsableFrame(" SHAPING", name="group", build_header_fn=build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
self.angle_button_data = self._build_gradient_float_slider("Cone Angle")
self.softness_button_data = self._build_gradient_float_slider("Cone Softness")
self.focus_button_data = self._build_gradient_float_slider("Focus")
self.focus_color_data, self.focus_tint_data, self.focus_grey_data = self._build_color_widget("Focus Tint")
def _build_vector_widget(self, widget_name, space):
with ui.HStack():
ui.Label(widget_name, name="attribute_name", width=0)
ui.Spacer(width=space)
# The custom compound widget
ColorWidget(1.0, 1.0, 1.0, draw_colorpicker=False)
ui.Spacer(width=10)
def _build_color_temperature(self):
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack():
ui.Spacer(height=8)
ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0)
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
self._build_line_dot(10, 8)
ui.Label("Enable Color Temperature", name="attribute_name", width=0)
ui.Spacer()
ui.Image(name="on_off", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20)
rect_changed, rect_default = self.__build_value_changed_widget()
self.temperature_button_data = self._build_gradient_float_slider(" Color Temperature", default_value=6500.0)
self.temperature_slider_data = self._build_slider_handle(cls_temperature_gradient)
with ui.HStack():
ui.Spacer(width=10)
ui.Line(name="group_line", alignment=ui.Alignment.TOP)
def _build_color_widget(self, widget_name):
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack():
ui.Spacer(height=8)
ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0)
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
self._build_line_dot(40, 9)
ui.Label(widget_name, name="attribute_name", width=0)
# The custom compound widget
ColorWidget(0.25, 0.5, 0.75)
ui.Spacer(width=10)
color_data = self._build_slider_handle(cls_color_gradient)
tint_data = self._build_slider_handle(cls_tint_gradient)
grey_data = self._build_slider_handle(cls_grey_gradient)
with ui.HStack():
ui.Spacer(width=10)
ui.Line(name="group_line", alignment=ui.Alignment.TOP)
return color_data, tint_data, grey_data
def _build_slider_handle(self, colors):
handle_Style = {"background_color": colors[0], "border_width": 2, "border_color": cl_combobox_background}
def set_color(placer, handle, offset):
# first clamp the value
max = placer.computed_width - handle.computed_width
if offset < 0:
placer.offset_x = 0
elif offset > max:
placer.offset_x = max
color = get_gradient_color(placer.offset_x.value, max, colors)
handle_Style.update({"background_color": color})
handle.style = handle_Style
with ui.HStack():
ui.Spacer(width=18)
with ui.ZStack():
with ui.VStack():
ui.Spacer(height=3)
byte_provider = build_gradient_image(colors, 8, "gradient_slider")
with ui.HStack():
handle_placer = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=0)
with handle_placer:
handle = ui.Circle(width=15, height=15, style=handle_Style)
handle_placer.set_offset_x_changed_fn(lambda offset: set_color(handle_placer, handle, offset.value))
ui.Spacer(width=22)
return byte_provider
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame(name="main_frame"):
with ui.VStack(height=0, spacing=SPACING):
self._build_head()
self._build_transform()
self._build_path()
self._build_light_properties()
ui.Spacer(height=30)
def _build_head(self):
with ui.ZStack():
ui.Image(name="header_frame", height=150, fill_policy=ui.FillPolicy.STRETCH)
with ui.HStack():
ui.Spacer(width=12)
with ui.VStack(spacing=8):
self._build_tabs()
ui.Spacer(height=1)
self._build_selection_widget()
self._build_stage_path_widget()
self._build_search_field()
ui.Spacer(width=12)
def _build_tabs(self):
with ui.HStack(height=35):
ui.Label("DETAILS", width=ui.Percent(17), name="details")
with ui.ZStack():
ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35)
with ui.HStack():
ui.Spacer(width=15)
ui.Label("LAYERS | ", name="layers", width=0)
ui.Label(f"{_get_plus_glyph()}", width=0)
ui.Spacer()
ui.Image(name="pin", width=20)
def _build_selection_widget(self):
with ui.HStack(height=20):
add_button = ui.Button(f"{_get_plus_glyph()} Add", width=60, name="add")
ui.Spacer(width=14)
ui.StringField(name="add").model.set_value("(2 models selected)")
ui.Spacer(width=8)
ui.Image(name="expansion", width=20)
def _build_stage_path_widget(self):
with ui.HStack(height=20):
ui.Spacer(width=3)
ui.Label("Stage Path", name="header_attribute_name", width=70)
ui.StringField(name="path").model.set_value("/World/environment/tree")
def _build_search_field(self):
with ui.HStack():
ui.Spacer(width=2)
# would add name="search" style, but there is a bug to use glyph together with style
# make sure the test passes for now
ui.StringField(height=23).model.set_value(f"{_get_search_glyph()} Search")
def _build_checkbox(self, label_name, default_value=True):
def _restore_default(rect_changed, rect_default):
image.name = "checked" if default_value else "unchecked"
rect_changed.visible = False
rect_default.visible = True
def _on_value_changed(image, rect_changed, rect_default):
image.name = "unchecked" if image.name == "checked" else "checked"
if (default_value and image.name == "unchecked") or (not default_value and image.name == "checked"):
rect_changed.visible = True
rect_default.visible = False
else:
rect_changed.visible = False
rect_default.visible = True
with ui.HStack():
ui.Label(label_name, name=f"attribute_bool", width=self.label_width, height=20)
name = "checked" if default_value else "unchecked"
image =ui.Image(name=name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=18, width=18)
ui.Spacer()
rect_changed, rect_default = self.__build_value_changed_widget()
image.set_mouse_pressed_fn(lambda x, y, b, m: _on_value_changed(image, rect_changed, rect_default))
# add call back to click the rect_changed to restore the default value
rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(rect_changed, rect_default))
def __build_value_changed_widget(self):
with ui.VStack(width=20):
ui.Spacer(height=3)
rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False)
ui.Spacer(height=4)
with ui.HStack():
ui.Spacer(width=3)
rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True)
return rect_changed, rect_default
def _build_gradient_float_slider(self, label_name, default_value=0, min=0, max=1):
def _on_value_changed(model, rect_changed, rect_defaul):
if model.as_float == default_value:
rect_changed.visible = False
rect_defaul.visible = True
else:
rect_changed.visible = True
rect_defaul.visible = False
def _restore_default(slider):
slider.model.set_value(default_value)
with ui.HStack():
ui.Label(label_name, name=f"attribute_name", width=self.label_width)
with ui.ZStack():
button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient")
with ui.VStack():
ui.Spacer(height=1.5)
with ui.HStack():
slider = ui.FloatSlider(name="float_slider", height=0, min=min, max=max)
slider.model.set_value(default_value)
ui.Spacer(width=1.5)
ui.Spacer(width=4)
rect_changed, rect_default = self.__build_value_changed_widget()
# switch the visibility of the rect_changed and rect_default to indicate value changes
slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default))
# add call back to click the rect_changed to restore the default value
rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider))
return button_background_gradient
def _build_combobox(self, label_name, options):
def _on_value_changed(model, rect_changed, rect_defaul):
index = model.get_item_value_model().get_value_as_int()
if index == 0:
rect_changed.visible = False
rect_defaul.visible = True
else:
rect_changed.visible = True
rect_defaul.visible = False
def _restore_default(combo_box):
combo_box.model.get_item_value_model().set_value(0)
with ui.HStack():
ui.Label(label_name, name=f"attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35)
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack():
ui.Spacer(height=10)
option_list = list(options)
combo_box = ui.ComboBox(0, *option_list, name="dropdown_menu")
with ui.VStack(width=0):
ui.Spacer(height=10)
rect_changed, rect_default = self.__build_value_changed_widget()
# switch the visibility of the rect_changed and rect_default to indicate value changes
combo_box.model.add_item_changed_fn(lambda m, i: _on_value_changed(m, rect_changed, rect_default))
# add call back to click the rect_changed to restore the default value
rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(combo_box))
| 17,220 | Python | 45.923706 | 146 | 0.573403 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/tests/test_window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TestWindow"]
from omni.example.ui_gradient_window import PropertyWindowExample
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
import omni.kit.test
EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class TestWindow(OmniUiTest):
async def test_general(self):
"""Testing general look of section"""
window = PropertyWindowExample("Test")
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=450,
height=600,
)
# Wait for images
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
| 1,363 | Python | 34.894736 | 115 | 0.710198 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_radio_collection.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CustomRadioCollection"]
from typing import List, Optional
import omni.ui as ui
from .style import ATTR_LABEL_WIDTH
SPACING = 5
class CustomRadioCollection:
"""A custom collection of radio buttons. The group_name is on the first
line, and each label and radio button are on subsequent lines. This one
does not inherit from CustomBaseWidget because it doesn't have the same
Head label, and doesn't have a Revert button at the end.
"""
def __init__(self,
group_name: str,
labels: List[str],
model: ui.AbstractItemModel = None,
default_value: bool = True,
**kwargs):
self.__group_name = group_name
self.__labels = labels
self.__default_val = default_value
self.__images = []
self.__selection_model = ui.SimpleIntModel(default_value)
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__images = []
self.__selection_model = None
self.__frame = None
@property
def model(self) -> Optional[ui.AbstractValueModel]:
"""The widget's model"""
if self.__selection_model:
return self.__selection_model
@model.setter
def model(self, value: int):
"""The widget's model"""
self.__selection_model.set(value)
def __getattr__(self, attr):
"""
Pretend it's self.__frame, so we have access to width/height and
callbacks.
"""
return getattr(self.__frame, attr)
def _on_value_changed(self, index: int = 0):
"""Set states of all radio buttons so only one is On."""
self.__selection_model.set_value(index)
for i, img in enumerate(self.__images):
img.checked = i == index
img.name = "radio_on" if img.checked else "radio_off"
def _build_fn(self):
"""Main meat of the widget. Draw the group_name label, label and
radio button for each row, and set up callbacks to keep them updated.
"""
with ui.VStack(spacing=SPACING):
ui.Spacer(height=2)
ui.Label(self.__group_name.upper(), name="radio_group_name",
width=ATTR_LABEL_WIDTH)
for i, label in enumerate(self.__labels):
with ui.HStack():
ui.Label(label, name="attribute_name",
width=ATTR_LABEL_WIDTH)
with ui.HStack():
with ui.VStack():
ui.Spacer(height=2)
self.__images.append(
ui.Image(
name=("radio_on" if self.__default_val == i else "radio_off"),
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
height=16, width=16, checked=self.__default_val
)
)
ui.Spacer()
ui.Spacer(height=2)
# Set up a mouse click callback for each radio button image
for i in range(len(self.__labels)):
self.__images[i].set_mouse_pressed_fn(
lambda x, y, b, m, i=i: self._on_value_changed(i))
| 3,781 | Python | 35.718446 | 98 | 0.556467 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_bool_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CustomBoolWidget"]
import omni.ui as ui
from .custom_base_widget import CustomBaseWidget
class CustomBoolWidget(CustomBaseWidget):
"""A custom checkbox or switch widget"""
def __init__(self,
model: ui.AbstractItemModel = None,
default_value: bool = True,
**kwargs):
self.__default_val = default_value
self.__bool_image = None
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__bool_image = None
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
self.__bool_image.checked = self.__default_val
self.__bool_image.name = (
"checked" if self.__bool_image.checked else "unchecked"
)
self.revert_img.enabled = False
def _on_value_changed(self):
"""Swap checkbox images and set revert_img to correct state."""
self.__bool_image.checked = not self.__bool_image.checked
self.__bool_image.name = (
"checked" if self.__bool_image.checked else "unchecked"
)
self.revert_img.enabled = self.__default_val != self.__bool_image.checked
def _build_body(self):
"""Main meat of the widget. Draw the appropriate checkbox image, and
set up callback.
"""
with ui.HStack():
with ui.VStack():
# Just shift the image down slightly (2 px) so it's aligned the way
# all the other rows are.
ui.Spacer(height=2)
self.__bool_image = ui.Image(
name="checked" if self.__default_val else "unchecked",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
height=16, width=16, checked=self.__default_val
)
# Let this spacer take up the rest of the Body space.
ui.Spacer()
self.__bool_image.set_mouse_pressed_fn(
lambda x, y, b, m: self._on_value_changed())
| 2,626 | Python | 37.072463 | 87 | 0.604722 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_multifield_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CustomMultifieldWidget"]
from typing import List, Optional
import omni.ui as ui
from .custom_base_widget import CustomBaseWidget
class CustomMultifieldWidget(CustomBaseWidget):
"""A custom multifield widget with a variable number of fields, and
customizable sublabels.
"""
def __init__(self,
model: ui.AbstractItemModel = None,
sublabels: Optional[List[str]] = None,
default_vals: Optional[List[float]] = None,
**kwargs):
self.__field_labels = sublabels or ["X", "Y", "Z"]
self.__default_vals = default_vals or [0.0] * len(self.__field_labels)
self.__multifields = []
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__multifields = []
@property
def model(self, index: int = 0) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__multifields:
return self.__multifields[index].model
@model.setter
def model(self, value: ui.AbstractItemModel, index: int = 0):
"""The widget's model"""
self.__multifields[index].model = value
def _restore_default(self):
"""Restore the default values."""
if self.revert_img.enabled:
for i in range(len(self.__multifields)):
model = self.__multifields[i].model
model.as_float = self.__default_vals[i]
self.revert_img.enabled = False
def _on_value_changed(self, val_model: ui.SimpleFloatModel, index: int):
"""Set revert_img to correct state."""
val = val_model.as_float
self.revert_img.enabled = self.__default_vals[index] != val
def _build_body(self):
"""Main meat of the widget. Draw the multiple Fields with their
respective labels, and set up callbacks to keep them updated.
"""
with ui.HStack():
for i, (label, val) in enumerate(zip(self.__field_labels, self.__default_vals)):
with ui.HStack(spacing=3):
ui.Label(label, name="multi_attr_label", width=0)
model = ui.SimpleFloatModel(val)
# TODO: Hopefully fix height after Field padding bug is merged!
self.__multifields.append(
ui.FloatField(model=model, name="multi_attr_field"))
if i < len(self.__default_vals) - 1:
# Only put space between fields and not after the last one
ui.Spacer(width=15)
for i, f in enumerate(self.__multifields):
f.model.add_value_changed_fn(lambda v: self._on_value_changed(v, i))
| 3,255 | Python | 39.19753 | 92 | 0.614132 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_color_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CustomColorWidget"]
from ctypes import Union
import re
from typing import List, Optional
import omni.ui as ui
from .custom_base_widget import CustomBaseWidget
from .style import BLOCK_HEIGHT
COLOR_PICKER_WIDTH = ui.Percent(35)
FIELD_WIDTH = ui.Percent(65)
COLOR_WIDGET_NAME = "color_block"
SPACING = 4
class CustomColorWidget(CustomBaseWidget):
"""The compound widget for color input. The color picker widget model converts
its 3 RGB values into a comma-separated string, to display in the StringField.
And vice-versa.
"""
def __init__(self, *args, model=None, **kwargs):
self.__defaults: List[Union[float, int]] = [a for a in args if a is not None]
self.__strfield: Optional[ui.StringField] = None
self.__colorpicker: Optional[ui.ColorWidget] = None
self.__color_sub = None
self.__strfield_sub = None
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__strfield = None
self.__colorpicker = None
self.__color_sub = None
self.__strfield_sub = None
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__colorpicker:
return self.__colorpicker.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__colorpicker.model = value
@staticmethod
def simplify_str(val):
s = str(round(val, 3))
s_clean = re.sub(r'0*$', '', s) # clean trailing 0's
s_clean = re.sub(r'[.]$', '', s_clean) # clean trailing .
s_clean = re.sub(r'^0', '', s_clean) # clean leading 0
return s_clean
def set_color_stringfield(self, item_model: ui.AbstractItemModel,
children: List[ui.AbstractItem]):
"""Take the colorpicker model that has 3 child RGB values,
convert them to a comma-separated string, and set the StringField value
to that string.
Args:
item_model: Colorpicker model
children: child Items of the colorpicker
"""
field_str = ", ".join([self.simplify_str(item_model.get_item_value_model(c).as_float)
for c in children])
self.__strfield.model.set_value(field_str)
if self.revert_img:
self._on_value_changed()
def set_color_widget(self, str_model: ui.SimpleStringModel,
children: List[ui.AbstractItem]):
"""Parse the new StringField value and set the ui.ColorWidget
component items to the new values.
Args:
str_model: SimpleStringModel for the StringField
children: Child Items of the ui.ColorWidget's model
"""
joined_str = str_model.get_value_as_string()
for model, comp_str in zip(children, joined_str.split(",")):
comp_str_clean = comp_str.strip()
try:
self.__colorpicker.model.get_item_value_model(model).as_float = float(comp_str_clean)
except ValueError:
# Usually happens in the middle of typing
pass
def _on_value_changed(self, *args):
"""Set revert_img to correct state."""
default_str = ", ".join([self.simplify_str(val) for val in self.__defaults])
cur_str = self.__strfield.model.as_string
self.revert_img.enabled = default_str != cur_str
def _restore_default(self):
"""Restore the default values."""
if self.revert_img.enabled:
field_str = ", ".join([self.simplify_str(val) for val in self.__defaults])
self.__strfield.model.set_value(field_str)
self.revert_img.enabled = False
def _build_body(self):
"""Main meat of the widget. Draw the colorpicker, stringfield, and
set up callbacks to keep them updated.
"""
with ui.HStack(spacing=SPACING):
# The construction of the widget depends on what the user provided,
# defaults or a model
if self.existing_model:
# the user provided a model
self.__colorpicker = ui.ColorWidget(
self.existing_model,
width=COLOR_PICKER_WIDTH,
height=BLOCK_HEIGHT,
name=COLOR_WIDGET_NAME
)
color_model = self.existing_model
else:
# the user provided a list of default values
self.__colorpicker = ui.ColorWidget(
*self.__defaults,
width=COLOR_PICKER_WIDTH,
height=BLOCK_HEIGHT,
name=COLOR_WIDGET_NAME
)
color_model = self.__colorpicker.model
self.__strfield = ui.StringField(width=FIELD_WIDTH, name="attribute_color")
self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn(
lambda m, _, children=color_model.get_item_children():
self.set_color_stringfield(m, children))
self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn(
lambda m, children=color_model.get_item_children():
self.set_color_widget(m, children))
# show data at the start
self.set_color_stringfield(self.__colorpicker.model,
children=color_model.get_item_children())
| 6,076 | Python | 39.245033 | 101 | 0.59842 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_path_button.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CustomPathButtonWidget"]
from typing import Callable, Optional
import omni.ui as ui
from .style import ATTR_LABEL_WIDTH, BLOCK_HEIGHT
class CustomPathButtonWidget:
"""A compound widget for holding a path in a StringField, and a button
that can perform an action.
TODO: Get text ellision working in the path field, to start with "..."
"""
def __init__(self,
label: str,
path: str,
btn_label: str,
btn_callback: Callable):
self.__attr_label = label
self.__pathfield: ui.StringField = None
self.__path = path
self.__btn_label = btn_label
self.__btn = None
self.__callback = btn_callback
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__pathfield = None
self.__btn = None
self.__callback = None
self.__frame = None
@property
def model(self) -> Optional[ui.AbstractItem]:
"""The widget's model"""
if self.__pathfield:
return self.__pathfield.model
@model.setter
def model(self, value: ui.AbstractItem):
"""The widget's model"""
self.__pathfield.model = value
def get_path(self):
return self.model.as_string
def _build_fn(self):
"""Draw all of the widget parts and set up callbacks."""
with ui.HStack():
ui.Label(
self.__attr_label,
name="attribute_name",
width=ATTR_LABEL_WIDTH
)
self.__pathfield = ui.StringField(
name="path_field",
height=BLOCK_HEIGHT,
width=ui.Fraction(2),
)
# TODO: Add clippingType=ELLIPSIS_LEFT for long paths
self.__pathfield.model.set_value(self.__path)
self.__btn = ui.Button(
self.__btn_label,
name="tool_button",
height=BLOCK_HEIGHT,
width=ui.Fraction(1),
clicked_fn=lambda path=self.get_path(): self.__callback(path),
)
| 2,599 | Python | 30.707317 | 78 | 0.576376 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_slider_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CustomSliderWidget"]
from typing import Optional
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
from .custom_base_widget import CustomBaseWidget
NUM_FIELD_WIDTH = 50
SLIDER_WIDTH = ui.Percent(100)
FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18
SPACING = 4
TEXTURE_NAME = "slider_bg_texture"
class CustomSliderWidget(CustomBaseWidget):
"""A compound widget for scalar slider input, which contains a
Slider and a Field with text input next to it.
"""
def __init__(self,
model: ui.AbstractItemModel = None,
num_type: str = "float",
min=0.0,
max=1.0,
default_val=0.0,
display_range: bool = False,
**kwargs):
self.__slider: Optional[ui.AbstractSlider] = None
self.__numberfield: Optional[ui.AbstractField] = None
self.__min = min
self.__max = max
self.__default_val = default_val
self.__num_type = num_type
self.__display_range = display_range
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__slider = None
self.__numberfield = None
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__slider:
return self.__slider.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__slider.model = value
self.__numberfield.model = value
def _on_value_changed(self, *args):
"""Set revert_img to correct state."""
if self.__num_type == "float":
index = self.model.as_float
else:
index = self.model.as_int
self.revert_img.enabled = self.__default_val != index
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
self.model.set_value(self.__default_val)
self.revert_img.enabled = False
def _build_display_range(self):
"""Builds just the tiny text range under the slider."""
with ui.HStack():
ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text")
if self.__min < 0 and self.__max > 0:
# Add middle value (always 0), but it may or may not be centered,
# depending on the min/max values.
total_range = self.__max - self.__min
# subtract 25% to account for end number widths
left = 100 * abs(0 - self.__min) / total_range - 25
right = 100 * abs(self.__max - 0) / total_range - 25
ui.Spacer(width=ui.Percent(left))
ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text")
ui.Spacer(width=ui.Percent(right))
else:
ui.Spacer()
ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text")
ui.Spacer(height=.75)
def _build_body(self):
"""Main meat of the widget. Draw the Slider, display range text, Field,
and set up callbacks to keep them updated.
"""
with ui.HStack(spacing=0):
# the user provided a list of default values
with ui.VStack(spacing=3, width=ui.Fraction(3)):
with ui.ZStack():
# Put texture image here, with rounded corners, then make slider
# bg be fully transparent, and fg be gray and partially transparent
with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT,
horizontal_clipping=True):
# Spacing is negative because "tileable" texture wasn't
# perfectly tileable, so that adds some overlap to line up better.
with ui.HStack(spacing=-12):
for i in range(50): # tiling the texture
ui.Image(name=TEXTURE_NAME,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
width=50,)
slider_cls = (
ui.FloatSlider if self.__num_type == "float" else ui.IntSlider
)
self.__slider = slider_cls(
height=FIELD_HEIGHT,
min=self.__min, max=self.__max, name="attr_slider"
)
if self.__display_range:
self._build_display_range()
with ui.VStack(width=ui.Fraction(1)):
model = self.__slider.model
model.set_value(self.__default_val)
field_cls = (
ui.FloatField if self.__num_type == "float" else ui.IntField
)
# Note: This is a hack to allow for text to fill the Field space more, as there was a bug
# with Field padding. It is fixed, and will be available in the next release of Kit.
with ui.ZStack():
# height=FIELD_HEIGHT-1 to account for the border, so the field isn't
# slightly taller than the slider
ui.Rectangle(
style_type_name_override="Field",
name="attr_field",
height=FIELD_HEIGHT - 1
)
with ui.HStack(height=0):
ui.Spacer(width=2)
self.__numberfield = field_cls(
model,
height=0,
style={
"background_color": cl.transparent,
"border_color": cl.transparent,
"padding": 4,
"font_size": fl.field_text_font_size,
},
)
if self.__display_range:
ui.Spacer()
model.add_value_changed_fn(self._on_value_changed)
| 6,797 | Python | 40.451219 | 105 | 0.529351 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["JuliaModelerWindow"]
import omni.ui as ui
from omni.kit.window.popup_dialog import MessageDialog
from .custom_bool_widget import CustomBoolWidget
from .custom_color_widget import CustomColorWidget
from .custom_combobox_widget import CustomComboboxWidget
from .custom_multifield_widget import CustomMultifieldWidget
from .custom_path_button import CustomPathButtonWidget
from .custom_radio_collection import CustomRadioCollection
from .custom_slider_widget import CustomSliderWidget
from .style import julia_modeler_style, ATTR_LABEL_WIDTH
SPACING = 5
class JuliaModelerWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = ATTR_LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = julia_modeler_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# Destroys all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def on_export_btn_click(self, path):
"""Sample callback that is used when the Export button is pressed."""
dialog = MessageDialog(
title="Button Pressed Dialog",
message=f"Export Button was clicked with path inside: {path}",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
def _build_title(self):
with ui.VStack():
ui.Spacer(height=10)
ui.Label("JULIA QUATERNION MODELER - 1.0", name="window_title")
ui.Spacer(height=10)
def _build_collapsable_header(self, collapsed, title):
"""Build a custom title of CollapsableFrame"""
with ui.VStack():
ui.Spacer(height=8)
with ui.HStack():
ui.Label(title, name="collapsable_name")
if collapsed:
image_name = "collapsable_opened"
else:
image_name = "collapsable_closed"
ui.Image(name=image_name, width=10, height=10)
ui.Spacer(height=8)
ui.Line(style_type_name_override="HeaderLine")
def _build_calculations(self):
"""Build the widgets of the "Calculations" group"""
with ui.CollapsableFrame("Calculations".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomSliderWidget(min=0, max=20, num_type="int",
label="Precision", default_val=6)
CustomSliderWidget(min=0, max=20, num_type="int",
label="Iterations", default_val=10)
def _build_parameters(self):
"""Build the widgets of the "Parameters" group"""
with ui.CollapsableFrame("Parameters".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomSliderWidget(min=-2, max=2, display_range=True,
label="Iterations", default_val=0.75)
CustomSliderWidget(min=0, max=2, display_range=True,
label="i", default_val=0.65)
CustomSliderWidget(min=0, max=2, display_range=True,
label="j", default_val=0.25)
CustomSliderWidget(min=0, max=2, display_range=True,
label="k", default_val=0.55)
CustomSliderWidget(min=0, max=3.14, display_range=True,
label="Theta", default_val=1.25)
def _build_light_1(self):
"""Build the widgets of the "Light 1" group"""
with ui.CollapsableFrame("Light 1".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomMultifieldWidget(
label="Orientation",
default_vals=[0.0, 0.0, 0.0]
)
CustomSliderWidget(min=0, max=1.75, label="Intensity", default_val=1.75)
CustomColorWidget(1.0, 0.875, 0.5, label="Color")
CustomBoolWidget(label="Shadow", default_value=True)
CustomSliderWidget(min=0, max=2, label="Shadow Softness", default_val=.1)
def _build_scene(self):
"""Build the widgets of the "Scene" group"""
with ui.CollapsableFrame("Scene".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomSliderWidget(min=0, max=160, display_range=True,
num_type="int", label="Field of View", default_val=60)
CustomMultifieldWidget(
label="Orientation",
default_vals=[0.0, 0.0, 0.0]
)
CustomSliderWidget(min=0, max=2, label="Camera Distance", default_val=.1)
CustomBoolWidget(label="Antialias", default_value=False)
CustomBoolWidget(label="Ambient Occlusion", default_value=True)
CustomMultifieldWidget(
label="Ambient Distance",
sublabels=["Min", "Max"],
default_vals=[0.0, 200.0]
)
CustomComboboxWidget(label="Ambient Falloff",
options=["Linear", "Quadratic", "Cubic"])
CustomColorWidget(.6, 0.62, 0.9, label="Background Color")
CustomRadioCollection("Render Method", labels=["Path Traced", "Volumetric"],
default_value=1)
CustomPathButtonWidget(
label="Export Path",
path=".../export/mesh1.usd",
btn_label="Export",
btn_callback=self.on_export_btn_click,
)
ui.Spacer(height=10)
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame(name="window_bg",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.VStack(height=0):
self._build_title()
self._build_calculations()
self._build_parameters()
self._build_light_1()
self._build_scene()
| 7,703 | Python | 37.909091 | 100 | 0.564975 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/style.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["example_window_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
cl.example_window_attribute_bg = cl("#1f2124")
cl.example_window_attribute_fg = cl("#0f1115")
cl.example_window_hovered = cl("#FFFFFF")
cl.example_window_text = cl("#CCCCCC")
fl.example_window_attr_hspacing = 10
fl.example_window_attr_spacing = 1
fl.example_window_group_spacing = 2
url.example_window_icon_closed = f"{EXTENSION_FOLDER_PATH}/data/closed.svg"
url.example_window_icon_opened = f"{EXTENSION_FOLDER_PATH}/data/opened.svg"
# The main style dict
example_window_style = {
"Label::attribute_name": {
"alignment": ui.Alignment.RIGHT_CENTER,
"margin_height": fl.example_window_attr_spacing,
"margin_width": fl.example_window_attr_hspacing,
},
"Label::attribute_name:hovered": {"color": cl.example_window_hovered},
"Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER},
"Slider::attribute_int:hovered": {"color": cl.example_window_hovered},
"Slider": {
"background_color": cl.example_window_attribute_bg,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::attribute_float": {
"draw_mode": ui.SliderDrawMode.FILLED,
"secondary_color": cl.example_window_attribute_fg,
},
"Slider::attribute_float:hovered": {"color": cl.example_window_hovered},
"Slider::attribute_vector:hovered": {"color": cl.example_window_hovered},
"Slider::attribute_color:hovered": {"color": cl.example_window_hovered},
"CollapsableFrame::group": {"margin_height": fl.example_window_group_spacing},
"Image::collapsable_opened": {"color": cl.example_window_text, "image_url": url.example_window_icon_opened},
"Image::collapsable_closed": {"color": cl.example_window_text, "image_url": url.example_window_icon_closed},
}
| 2,530 | Python | 42.63793 | 112 | 0.717787 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/color_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ColorWidget"]
from ctypes import Union
from typing import List, Optional
import omni.ui as ui
COLOR_PICKER_WIDTH = 20
SPACING = 4
class ColorWidget:
"""The compound widget for color input"""
def __init__(self, *args, model=None, **kwargs):
self.__defaults: List[Union[float, int]] = args
self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None)
self.__multifield: Optional[ui.MultiFloatDragField] = None
self.__colorpicker: Optional[ui.ColorWidget] = None
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__model = None
self.__multifield = None
self.__colorpicker = None
self.__frame = None
def __getattr__(self, attr):
"""
Pretend it's self.__frame, so we have access to width/height and
callbacks.
"""
return getattr(self.__root_frame, attr)
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__multifield:
return self.__multifield.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__multifield.model = value
self.__colorpicker.model = value
def _build_fn(self):
with ui.HStack(spacing=SPACING):
# The construction of multi field depends on what the user provided,
# defaults or a model
if self.__model:
# the user provided a model
self.__multifield = ui.MultiFloatDragField(
min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color"
)
model = self.__model
else:
# the user provided a list of default values
self.__multifield = ui.MultiFloatDragField(
*self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color"
)
model = self.__multifield.model
self.__colorpicker = ui.ColorWidget(model, width=COLOR_PICKER_WIDTH)
| 2,600 | Python | 33.223684 | 95 | 0.611538 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ExampleWindow"]
import omni.ui as ui
from .style import example_window_style
from .color_widget import ColorWidget
LABEL_WIDTH = 120
SPACING = 4
class ExampleWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = example_window_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _build_collapsable_header(self, collapsed, title):
"""Build a custom title of CollapsableFrame"""
with ui.HStack():
ui.Label(title, name="collapsable_name")
if collapsed:
image_name = "collapsable_opened"
else:
image_name = "collapsable_closed"
ui.Image(name=image_name, width=20, height=20)
def _build_calculations(self):
"""Build the widgets of the "Calculations" group"""
with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Precision", name="attribute_name", width=self.label_width)
ui.IntSlider(name="attribute_int")
with ui.HStack():
ui.Label("Iterations", name="attribute_name", width=self.label_width)
ui.IntSlider(name="attribute_int", min=0, max=5)
def _build_parameters(self):
"""Build the widgets of the "Parameters" group"""
with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Value", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
with ui.HStack():
ui.Label("i", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("j", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("k", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("Theta", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
def _build_light_1(self):
"""Build the widgets of the "Light 1" group"""
with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Orientation", name="attribute_name", width=self.label_width)
ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector")
with ui.HStack():
ui.Label("Intensity", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
with ui.HStack():
ui.Label("Color", name="attribute_name", width=self.label_width)
# The custom compound widget
ColorWidget(0.25, 0.5, 0.75)
with ui.HStack():
ui.Label("Shadow", name="attribute_name", width=self.label_width)
ui.CheckBox(name="attribute_bool")
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame():
with ui.VStack(height=0):
self._build_calculations()
self._build_parameters()
self._build_light_1()
| 5,056 | Python | 39.13492 | 111 | 0.584256 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from pathlib import Path
icons_path = Path(__file__).parent.parent.parent.parent / "icons"
gen_ai_style = {
"HStack": {
"margin": 3
},
"Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976}
}
| 946 | Python | 32.821427 | 98 | 0.726216 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/extension.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ext
from .window import DeepSearchPickerWindow
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self._window = DeepSearchPickerWindow("DeepSearch Swap", width=300, height=300)
def on_shutdown(self):
self._window.destroy()
self._window = None
| 1,423 | Python | 44.935482 | 119 | 0.747013 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/deep_search.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from omni.kit.ngsearch.client import NGSearchClient
import carb
import asyncio
class deep_search():
async def query_items(queries, url: str, paths):
result = list(tuple())
for query in queries:
query_result = await deep_search._query_first(query, url, paths)
if query_result is not None:
result.append(query_result)
return result
async def _query_first(query: str, url: str, paths):
filtered_query = "ext:usd,usdz,usda path:"
for path in paths:
filtered_query = filtered_query + "\"" + str(path) + "\","
filtered_query = filtered_query[:-1]
filtered_query = filtered_query + " "
filtered_query = filtered_query + query
SearchResult = await NGSearchClient.get_instance().find2(
query=filtered_query, url=url)
if len(SearchResult.paths) > 0:
return (query, SearchResult.paths[0].uri)
else:
return None
async def query_all(query: str, url: str, paths):
filtered_query = "ext:usd,usdz,usda path:"
for path in paths:
filtered_query = filtered_query + "\"" + str(path) + "\","
filtered_query = filtered_query[:-1]
filtered_query = filtered_query + " "
filtered_query = filtered_query + query
return await NGSearchClient.get_instance().find2(query=filtered_query, url=url)
| 2,185 | Python | 32.121212 | 98 | 0.632494 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
import omni.usd
import carb
from .style import gen_ai_style
from .deep_search import deep_search
import asyncio
from pxr import UsdGeom, Usd, Sdf, Gf
class DeepSearchPickerWindow(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Models
self.frame.set_build_fn(self._build_fn)
self._index = 0
self._query_results = None
self._selected_prim = None
self._prim_path_model = ui.SimpleStringModel()
def _build_fn(self):
async def replace_prim():
self._index = 0
ctx = omni.usd.get_context()
prim_paths = ctx.get_selection().get_selected_prim_paths()
if len(prim_paths) != 1:
carb.log_warn("You must select one and only one prim")
return
prim_path = prim_paths[0]
stage = ctx.get_stage()
self._selected_prim = stage.GetPrimAtPath(prim_path)
query = self._selected_prim.GetAttribute("DeepSearch:Query").Get()
prop_paths = ["/Projects/simready_content/common_assets/props/",
"/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Robots/",
"/NVIDIA/Assets/Isaac/2022.1/NVIDIA/Assets/ArchVis/Residential/Furniture/"]
self._query_results = await deep_search.query_all(query, "omniverse://ov-simready/", paths=prop_paths)
self._prim_path_model.set_value(prim_path)
def increment_prim_index():
if self._query_results is None:
return
self._index = self._index + 1
if self._index >= len(self._query_results.paths):
self._index = 0
self.replace_reference()
def decrement_prim_index():
if self._query_results is None:
return
self._index = self._index - 1
if self._index <= 0:
self._index = len(self._query_results.paths) - 1
self.replace_reference()
with self.frame:
with ui.VStack(style=gen_ai_style):
with ui.HStack(height=0):
ui.Spacer()
ui.StringField(model=self._prim_path_model, width=365, height=30)
ui.Button(name="create", width=30, height=30, clicked_fn=lambda: asyncio.ensure_future(replace_prim()))
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Button("<", width=200, clicked_fn=lambda: decrement_prim_index())
ui.Button(">", width=200, clicked_fn=lambda: increment_prim_index())
ui.Spacer()
def replace_reference(self):
references: Usd.references = self._selected_prim.GetReferences()
references.ClearReferences()
references.AddReference(
assetPath="omniverse://ov-simready" + self._query_results.paths[self._index].uri)
carb.log_info("Got it?")
def destroy(self):
super().destroy() | 3,815 | Python | 36.048543 | 123 | 0.589253 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/priminfo.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pxr import Usd, Gf
class PrimInfo:
# Class that stores the prim info
def __init__(self, prim: Usd.Prim, name: str = "") -> None:
self.prim = prim
self.child = prim.GetAllChildren()[0]
self.length = self.GetLengthOfPrim()
self.width = self.GetWidthOfPrim()
self.origin = self.GetPrimOrigin()
self.area_name = name
def GetLengthOfPrim(self) -> str:
# Returns the X value
attr = self.child.GetAttribute('xformOp:scale')
x_scale = attr.Get()[0]
return str(x_scale)
def GetWidthOfPrim(self) -> str:
# Returns the Z value
attr = self.child.GetAttribute('xformOp:scale')
z_scale = attr.Get()[2]
return str(z_scale)
def GetPrimOrigin(self) -> str:
attr = self.prim.GetAttribute('xformOp:translate')
origin = Gf.Vec3d(0,0,0)
if attr:
origin = attr.Get()
phrase = str(origin[0]) + ", " + str(origin[1]) + ", " + str(origin[2])
return phrase | 1,706 | Python | 36.108695 | 98 | 0.651817 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/widgets.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from omni.ui import color as cl
import asyncio
import omni
import carb
class ProgressBar:
def __init__(self):
self.progress_bar_window = None
self.left = None
self.right = None
self._build_fn()
async def play_anim_forever(self):
fraction = 0.0
while True:
fraction = (fraction + 0.01) % 1.0
self.left.width = ui.Fraction(fraction)
self.right.width = ui.Fraction(1.0-fraction)
await omni.kit.app.get_app().next_update_async()
def _build_fn(self):
with ui.VStack():
self.progress_bar_window = ui.HStack(height=0, visible=False)
with self.progress_bar_window:
ui.Label("Processing", width=0, style={"margin_width": 3})
self.left = ui.Spacer(width=ui.Fraction(0.0))
ui.Rectangle(width=50, style={"background_color": cl("#76b900")})
self.right = ui.Spacer(width=ui.Fraction(1.0))
def show_bar(self, to_show):
self.progress_bar_window.visible = to_show
| 1,770 | Python | 34.419999 | 98 | 0.655367 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/chatgpt_apiconnect.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import carb
import aiohttp
import asyncio
from .prompts import system_input, user_input, assistant_input
from .deep_search import query_items
from .item_generator import place_greyboxes, place_deepsearch_results
async def chatGPT_call(prompt: str):
# Load your API key from an environment variable or secret management service
settings = carb.settings.get_settings()
apikey = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
my_prompt = prompt.replace("\n", " ")
# Send a request API
try:
parameters = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": system_input},
{"role": "user", "content": user_input},
{"role": "assistant", "content": assistant_input},
{"role": "user", "content": my_prompt}
]
}
chatgpt_url = "https://api.openai.com/v1/chat/completions"
headers = {"Authorization": "Bearer %s" % apikey}
# Create a completion using the chatGPT model
async with aiohttp.ClientSession() as session:
async with session.post(chatgpt_url, headers=headers, json=parameters) as r:
response = await r.json()
text = response["choices"][0]["message"]['content']
except Exception as e:
carb.log_error("An error as occurred")
return None, str(e)
# Parse data that was given from API
try:
#convert string to object
data = json.loads(text)
except ValueError as e:
carb.log_error(f"Exception occurred: {e}")
return None, text
else:
# Get area_objects_list
object_list = data['area_objects_list']
return object_list, text
async def call_Generate(prim_info, prompt, use_chatgpt, use_deepsearch, response_label, progress_widget):
run_loop = asyncio.get_event_loop()
progress_widget.show_bar(True)
task = run_loop.create_task(progress_widget.play_anim_forever())
response = ""
#chain the prompt
area_name = prim_info.area_name.split("/World/Layout/")
concat_prompt = area_name[-1].replace("_", " ") + ", " + prim_info.length + "x" + prim_info.width + ", origin at (0.0, 0.0, 0.0), generate a list of appropriate items in the correct places. " + prompt
root_prim_path = "/World/Layout/GPT/"
if prim_info.area_name != "":
root_prim_path= prim_info.area_name + "/items/"
if use_chatgpt: #when calling the API
objects, response = await chatGPT_call(concat_prompt)
else: #when testing and you want to skip the API call
data = json.loads(assistant_input)
objects = data['area_objects_list']
if objects is None:
response_label.text = response
return
if use_deepsearch:
settings = carb.settings.get_settings()
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
filter_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/filter_path")
filter_paths = filter_path.split(',')
queries = list()
for item in objects:
queries.append(item['object_name'])
query_result = await query_items(queries=queries, url=nucleus_path, paths=filter_paths)
if query_result is not None:
place_deepsearch_results(
gpt_results=objects,
query_result=query_result,
root_prim_path=root_prim_path)
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
task.cancel()
await asyncio.sleep(1)
response_label.text = response
progress_widget.show_bar(False)
| 4,729 | Python | 39.775862 | 204 | 0.623176 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from pathlib import Path
icons_path = Path(__file__).parent.parent.parent.parent / "icons"
gen_ai_style = {
"HStack": {
"margin": 3
},
"Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976},
"Button.Image::properties": {"image_url": f"{icons_path}/cog.svg", "color": 0xFF989898},
"Line": {
"margin": 3
},
"Label": {
"margin_width": 5
}
}
guide = """
Step 1: Create a Floor
- You can draw a floor outline using the pencil tool. Right click in the viewport then `Create>BasicCurves>From Pencil`
- OR Create a prim and scale it to the size you want. i.e. Right click in the viewport then `Create>Mesh>Cube`.
- Next, with the floor selected type in a name into "Area Name". Make sure the area name is relative to the room you want to generate.
For example, if you inputted the name as "bedroom" ChatGPT will be prompted that the room is a bedroom.
- Then click the '+' button. This will generate the floor and add the option to our combo box.
Step 2: Prompt
- Type in a prompt that you want to send along to ChatGPT. This can be information about what is inside of the room.
For example, "generate a comfortable reception area that contains a front desk and an area for guest to sit down".
Step 3: Generate
- Select 'use ChatGPT' if you want to recieve a response from ChatGPT otherwise it will use a premade response.
- Select 'use Deepsearch' if you want to use the deepsearch functionality. (ENTERPRISE USERS ONLY)
When deepsearch is false it will spawn in cubes that greybox the scene.
- Hit Generate, after hitting generate it will start making the appropriate calls. Loading bar will be shown as api-calls are being made.
Step 4: More Rooms
- To add another room you can repeat Steps 1-3. To regenerate a previous room just select it from the 'Current Room' in the dropdown menu.
- The dropdown menu will remember the last prompt you used to generate the items.
- If you do not like the items it generated, you can hit the generate button until you are satisfied with the items.
""" | 2,792 | Python | 45.549999 | 138 | 0.731734 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/prompts.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
system_input='''You are an area generator expert. Given an area of a certain size, you can generate a list of items that are appropriate to that area, in the right place, and with a representative material.
You operate in a 3D Space. You work in a X,Y,Z coordinate system. X denotes width, Y denotes height, Z denotes depth. 0.0,0.0,0.0 is the default space origin.
You receive from the user the name of the area, the size of the area on X and Z axis in centimetres, the origin point of the area (which is at the center of the area).
You answer by only generating JSON files that contain the following information:
- area_name: name of the area
- X: coordinate of the area on X axis
- Y: coordinate of the area on Y axis
- Z: coordinate of the area on Z axis
- area_size_X: dimension in cm of the area on X axis
- area_size_Z: dimension in cm of the area on Z axis
- area_objects_list: list of all the objects in the area
For each object you need to store:
- object_name: name of the object
- X: coordinate of the object on X axis
- Y: coordinate of the object on Y axis
- Z: coordinate of the object on Z axis
- Length: dimension in cm of the object on X axis
- Width: dimension in cm of the object on Y axis
- Height: dimension in cm of the object on Z axis
- Material: a reasonable material of the object using an exact name from the following list: Plywood, Leather_Brown, Leather_Pumpkin, Leather_Black, Aluminum_Cast, Birch, Beadboard, Cardboard, Cloth_Black, Cloth_Gray, Concrete_Polished, Glazed_Glass, CorrugatedMetal, Cork, Linen_Beige, Linen_Blue, Linen_White, Mahogany, MDF, Oak, Plastic_ABS, Steel_Carbon, Steel_Stainless, Veneer_OU_Walnut, Veneer_UX_Walnut_Cherry, Veneer_Z5_Maple.
Each object name should include an appropriate adjective.
Keep in mind, objects should be disposed in the area to create the most meaningful layout possible, and they shouldn't overlap.
All objects must be within the bounds of the area size; Never place objects further than 1/2 the length or 1/2 the depth of the area from the origin.
Also keep in mind that the objects should be disposed all over the area in respect to the origin point of the area, and you can use negative values as well to display items correctly, since origin of the area is always at the center of the area.
Remember, you only generate JSON code, nothing else. It's very important.
'''
user_input="Warehouse, 1000x1000, origin at (0.0,0.0,0.0), generate a list of appropriate items in the correct places. Generate warehouse objects"
assistant_input='''{
"area_name": "Warehouse_Area",
"X": 0.0,
"Y": 0.0,
"Z": 0.0,
"area_size_X": 1000,
"area_size_Z": 1000,
"area_objects_list": [
{
"object_name": "Parts_Pallet_1",
"X": -150,
"Y": 0.0,
"Z": 250,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Boxes_Pallet_2",
"X": -150,
"Y": 0.0,
"Z": 150,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Industrial_Storage_Rack_1",
"X": -150,
"Y": 0.0,
"Z": 50,
"Length": 200,
"Width": 50,
"Height": 300,
"Material": "Steel_Carbon"
},
{
"object_name": "Empty_Pallet_3",
"X": -150,
"Y": 0.0,
"Z": -50,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Yellow_Forklift_1",
"X": 50,
"Y": 0.0,
"Z": -50,
"Length": 200,
"Width": 100,
"Height": 250,
"Material": "Plastic_ABS"
},
{
"object_name": "Heavy_Duty_Forklift_2",
"X": 150,
"Y": 0.0,
"Z": -50,
"Length": 200,
"Width": 100,
"Height": 250,
"Material": "Steel_Stainless"
}
]
}'''
| 4,898 | Python | 37.880952 | 435 | 0.612903 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/materials.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
MaterialPresets = {
"Leather_Brown":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl',
"Leather_Pumpkin_01":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Pumpkin.mdl',
"Leather_Brown_02":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl',
"Leather_Black_01":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Black.mdl',
"Aluminum_cast":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Aluminum_Cast.mdl',
"Birch":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Birch.mdl',
"Beadboard":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Beadboard.mdl',
"Cardboard":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl',
"Cloth_Black":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Black.mdl',
"Cloth_Gray":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Gray.mdl',
"Concrete_Polished":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Polished.mdl',
"Glazed_Glass":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Glass/Glazed_Glass.mdl',
"CorrugatedMetal":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/CorrugatedMetal.mdl',
"Cork":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Cork.mdl',
"Linen_Beige":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Beige.mdl',
"Linen_Blue":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Blue.mdl',
"Linen_White":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_White.mdl',
"Mahogany":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Mahogany.mdl',
"MDF":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/MDF.mdl',
"Oak":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Oak.mdl',
"Plastic_ABS":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Plastic_ABS.mdl',
"Steel_Carbon":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Carbon.mdl',
"Steel_Stainless":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Stainless.mdl',
"Veneer_OU_Walnut":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_OU_Walnut.mdl',
"Veneer_UX_Walnut_Cherry":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_UX_Walnut_Cherry.mdl',
"Veneer_Z5_Maple":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_Z5_Maple.mdl',
"Plywood":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Plywood.mdl',
"Concrete_Rough_Dirty":
'http://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/vMaterials_2/Concrete/Concrete_Rough.mdl'
} | 4,323 | Python | 58.232876 | 121 | 0.743234 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.kit.commands
from pxr import Gf, Sdf, UsdGeom
from .materials import *
import carb
def CreateCubeFromCurve(curve_path: str, area_name: str = ""):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
min_coords, max_coords = get_coords_from_bbox(curve_path)
x,y,z = get_bounding_box_dimensions(curve_path)
xForm_scale = Gf.Vec3d(x, 1, z)
cube_scale = Gf.Vec3d(0.01, 0.01, 0.01)
prim = stage.GetPrimAtPath(curve_path)
origin = prim.GetAttribute('xformOp:translate').Get()
if prim.GetTypeName() == "BasisCurves":
origin = Gf.Vec3d(min_coords[0]+x/2, 0, min_coords[2]+z/2)
area_path = '/World/Layout/Area'
if len(area_name) != 0:
area_path = '/World/Layout/' + area_name.replace(" ", "_")
new_area_path = omni.usd.get_stage_next_free_path(stage, area_path, False)
new_cube_xForm_path = new_area_path + "/" + "Floor"
new_cube_path = new_cube_xForm_path + "/" + "Cube"
# Create xForm to hold all items
item_container = create_prim(new_area_path)
set_transformTRS_attrs(item_container, translate=origin)
# Create Scale Xform for floor
xform = create_prim(new_cube_xForm_path)
set_transformTRS_attrs(xform, scale=xForm_scale)
# Create Floor Cube
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
prim_path=new_cube_path,
select_new_prim=True
)
cube = stage.GetPrimAtPath(new_cube_path)
set_transformTRS_attrs(cube, scale=cube_scale)
cube.CreateAttribute("primvar:area_name", Sdf.ValueTypeNames.String, custom=True).Set(area_name)
omni.kit.commands.execute('DeletePrims',
paths=[curve_path],
destructive=False)
apply_material_to_prim('Concrete_Rough_Dirty', new_area_path)
return new_area_path
def apply_material_to_prim(material_name: str, prim_path: str):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
looks_path = '/World/Looks/'
mat_path = looks_path + material_name
mat_prim = stage.GetPrimAtPath(mat_path)
if MaterialPresets.get(material_name, None) is not None:
if not mat_prim.IsValid():
omni.kit.commands.execute('CreateMdlMaterialPrimCommand',
mtl_url=MaterialPresets[material_name],
mtl_name=material_name,
mtl_path=mat_path)
omni.kit.commands.execute('BindMaterialCommand',
prim_path=prim_path,
material_path=mat_path)
def create_prim(prim_path, prim_type='Xform'):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.DefinePrim(prim_path)
if prim_type == 'Xform':
xform = UsdGeom.Xform.Define(stage, prim_path)
else:
xform = UsdGeom.Cube.Define(stage, prim_path)
create_transformOps_for_xform(xform)
return prim
def create_transformOps_for_xform(xform):
xform.AddTranslateOp()
xform.AddRotateXYZOp()
xform.AddScaleOp()
def set_transformTRS_attrs(prim, translate: Gf.Vec3d = Gf.Vec3d(0,0,0), rotate: Gf.Vec3d=Gf.Vec3d(0,0,0), scale: Gf.Vec3d=Gf.Vec3d(1,1,1)):
prim.GetAttribute('xformOp:translate').Set(translate)
prim.GetAttribute('xformOp:rotateXYZ').Set(rotate)
prim.GetAttribute('xformOp:scale').Set(scale)
def get_bounding_box_dimensions(prim_path: str):
min_coords, max_coords = get_coords_from_bbox(prim_path)
length = max_coords[0] - min_coords[0]
width = max_coords[1] - min_coords[1]
height = max_coords[2] - min_coords[2]
return length, width, height
def get_coords_from_bbox(prim_path: str):
ctx = omni.usd.get_context()
bbox = ctx.compute_path_world_bounding_box(prim_path)
min_coords, max_coords = bbox
return min_coords, max_coords
def scale_object_if_needed(prim_path):
stage = omni.usd.get_context().get_stage()
length, width, height = get_bounding_box_dimensions(prim_path)
largest_dimension = max(length, width, height)
if largest_dimension < 10:
prim = stage.GetPrimAtPath(prim_path)
# HACK: All Get Attribute Calls need to check if the attribute exists and add it if it doesn't
if prim.IsValid():
scale_attr = prim.GetAttribute('xformOp:scale')
if scale_attr.IsValid():
current_scale = scale_attr.Get()
new_scale = (current_scale[0] * 100, current_scale[1] * 100, current_scale[2] * 100)
scale_attr.Set(new_scale)
carb.log_info(f"Scaled object by 100 times: {prim_path}")
else:
carb.log_info(f"Scale attribute not found for prim at path: {prim_path}")
else:
carb.log_info(f"Invalid prim at path: {prim_path}")
else:
carb.log_info(f"No scaling needed for object: {prim_path}") | 5,463 | Python | 38.594203 | 139 | 0.663738 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/item_generator.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#hotkey
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pxr import Usd, Sdf, Gf
from .utils import scale_object_if_needed, apply_material_to_prim, create_prim, set_transformTRS_attrs
def place_deepsearch_results(gpt_results, query_result, root_prim_path):
index = 0
for item in query_result:
item_name = item[0]
item_path = item[1]
# Define Prim
prim_parent_path = root_prim_path + item_name.replace(" ", "_")
prim_path = prim_parent_path + "/" + item_name.replace(" ", "_")
parent_prim = create_prim(prim_parent_path)
next_prim = create_prim(prim_path)
# Add reference to USD Asset
references: Usd.references = next_prim.GetReferences()
# TODO: The query results should returnt he full path of the prim
references.AddReference(
assetPath="omniverse://ov-simready" + item_path)
# Add reference for future search refinement
config = next_prim.CreateAttribute("DeepSearch:Query", Sdf.ValueTypeNames.String)
config.Set(item_name)
# HACK: All "GetAttribute" calls should need to check if the attribute exists
# translate prim
next_object = gpt_results[index]
index = index + 1
x = next_object['X']
y = next_object['Y']
z = next_object['Z']
set_transformTRS_attrs(parent_prim, Gf.Vec3d(x,y,z), Gf.Vec3d(0,-90,-90), Gf.Vec3d(1.0,1.0,1.0))
scale_object_if_needed(prim_parent_path)
def place_greyboxes(gpt_results, root_prim_path):
index = 0
for item in gpt_results:
# Define Prim
prim_parent_path = root_prim_path + item['object_name'].replace(" ", "_")
prim_path = prim_parent_path + "/" + item['object_name'].replace(" ", "_")
# Define Dimensions and material
length = item['Length']/100
width = item['Width']/100
height = item['Height']/100
x = item['X']
y = item['Y']+height*100*.5 #shift bottom of object to y=0
z = item['Z']
material = item['Material']
# Create Prim
parent_prim = create_prim(prim_parent_path)
set_transformTRS_attrs(parent_prim)
prim = create_prim(prim_path, 'Cube')
set_transformTRS_attrs(prim, translate=Gf.Vec3d(x,y,z), scale=Gf.Vec3d(length, height, width))
prim.GetAttribute('extent').Set([(-50.0, -50.0, -50.0), (50.0, 50.0, 50.0)])
prim.GetAttribute('size').Set(100)
index = index + 1
# Add Attribute and Material
attr = prim.CreateAttribute("object_name", Sdf.ValueTypeNames.String)
attr.Set(item['object_name'])
apply_material_to_prim(material, prim_path)
| 3,365 | Python | 38.139534 | 104 | 0.63477 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
import omni.usd
import carb
import asyncio
import omni.kit.commands
from omni.kit.window.popup_dialog.form_dialog import FormDialog
from .utils import CreateCubeFromCurve
from .style import gen_ai_style, guide
from .chatgpt_apiconnect import call_Generate
from .priminfo import PrimInfo
from pxr import Sdf
from .widgets import ProgressBar
class GenAIWindow(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Models
self._path_model = ui.SimpleStringModel()
self._prompt_model = ui.SimpleStringModel("generate warehouse objects")
self._area_name_model = ui.SimpleStringModel()
self._use_deepsearch = ui.SimpleBoolModel()
self._use_chatgpt = ui.SimpleBoolModel()
self._areas = []
self.response_log = None
self.current_index = -1
self.current_area = None
self._combo_changed_sub = None
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.ScrollingFrame():
with ui.VStack(style=gen_ai_style):
with ui.HStack(height=0):
ui.Label("Content Generatation with ChatGPT", style={"font_size": 18})
ui.Button(name="properties", tooltip="Configure API Key and Nucleus Path", width=30, height=30, clicked_fn=lambda: self._open_settings())
with ui.CollapsableFrame("Getting Started Instructions", height=0, collapsed=True):
ui.Label(guide, word_wrap=True)
ui.Line()
with ui.HStack(height=0):
ui.Label("Area Name", width=ui.Percent(30))
ui.StringField(model=self._area_name_model)
ui.Button(name="create", width=30, height=30, clicked_fn=lambda: self._create_new_area(self.get_area_name()))
with ui.HStack(height=0):
ui.Label("Current Room", width=ui.Percent(30))
self._build_combo_box()
ui.Line()
with ui.HStack(height=ui.Percent(50)):
ui.Label("Prompt", width=0)
ui.StringField(model=self._prompt_model, multiline=True)
ui.Line()
self._build_ai_section()
def _save_settings(self, dialog):
values = dialog.get_values()
carb.log_info(values)
settings = carb.settings.get_settings()
settings.set_string("/persistent/exts/omni.example.airoomgenerator/APIKey", values["APIKey"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path", values["deepsearch_nucleus_path"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/path_filter", values["path_filter"])
dialog.hide()
def _open_settings(self):
settings = carb.settings.get_settings()
apikey_value = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
path_filter = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/path_filter")
if apikey_value == "":
apikey_value = "Enter API Key Here"
if nucleus_path == "":
nucleus_path = "(ENTERPRISE ONLY) Enter Nucleus Path Here"
if path_filter == "":
path_filter = ""
field_defs = [
FormDialog.FieldDef("APIKey", "API Key: ", ui.StringField, apikey_value),
FormDialog.FieldDef("deepsearch_nucleus_path", "Nucleus Path: ", ui.StringField, nucleus_path),
FormDialog.FieldDef("path_filter", "Path Filter: ", ui.StringField, path_filter)
]
dialog = FormDialog(
title="Settings",
message="Your Settings: ",
field_defs = field_defs,
ok_handler=lambda dialog: self._save_settings(dialog))
dialog.show()
def _build_ai_section(self):
with ui.HStack(height=0):
ui.Spacer()
ui.Label("Use ChatGPT: ")
ui.CheckBox(model=self._use_chatgpt)
ui.Label("Use Deepsearch: ", tooltip="ENTERPRISE USERS ONLY")
ui.CheckBox(model=self._use_deepsearch)
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer(width=ui.Percent(10))
ui.Button("Generate", height=40,
clicked_fn=lambda: self._generate())
ui.Spacer(width=ui.Percent(10))
self.progress = ProgressBar()
with ui.CollapsableFrame("ChatGPT Response / Log", height=0, collapsed=True):
self.response_log = ui.Label("", word_wrap=True)
def _build_combo_box(self):
self.combo_model = ui.ComboBox(self.current_index, *[str(x) for x in self._areas] ).model
def combo_changed(item_model, item):
index_value_model = item_model.get_item_value_model(item)
self.current_area = self._areas[index_value_model.as_int]
self.current_index = index_value_model.as_int
self.rebuild_frame()
self._combo_changed_sub = self.combo_model.subscribe_item_changed_fn(combo_changed)
def _create_new_area(self, area_name: str):
if area_name == "":
carb.log_warn("No area name provided")
return
new_area_name = CreateCubeFromCurve(self.get_prim_path(), area_name)
self._areas.append(new_area_name)
self.current_index = len(self._areas) - 1
index_value_model = self.combo_model.get_item_value_model()
index_value_model.set_value(self.current_index)
def rebuild_frame(self):
# we do want to update the area name and possibly last prompt?
area_name = self.current_area.split("/World/Layout/")
self._area_name_model.set_value(area_name[-1].replace("_", " "))
attr_prompt = self.get_prim().GetAttribute('genai:prompt')
if attr_prompt.IsValid():
self._prompt_model.set_value(attr_prompt.Get())
else:
self._prompt_model.set_value("")
self.frame.rebuild()
def _generate(self):
prim = self.get_prim()
attr = prim.GetAttribute('genai:prompt')
if not attr.IsValid():
attr = prim.CreateAttribute('genai:prompt', Sdf.ValueTypeNames.String)
attr.Set(self.get_prompt())
items_path = self.current_area + "/items"
ctx = omni.usd.get_context()
stage = ctx.get_stage()
if stage.GetPrimAtPath(items_path).IsValid():
omni.kit.commands.execute('DeletePrims',
paths=[items_path],
destructive=False)
# asyncio.ensure_future(self.progress.fill_bar(0,100))
run_loop = asyncio.get_event_loop()
run_loop.create_task(call_Generate(self.get_prim_info(),
self.get_prompt(),
self._use_chatgpt.as_bool,
self._use_deepsearch.as_bool,
self.response_log,
self.progress
))
# Returns a PrimInfo object containing the Length, Width, Origin and Area Name
def get_prim_info(self) -> PrimInfo:
prim = self.get_prim()
prim_info = None
if prim.IsValid():
prim_info = PrimInfo(prim, self.current_area)
return prim_info
# # Get the prim path specified
def get_prim_path(self):
ctx = omni.usd.get_context()
selection = ctx.get_selection().get_selected_prim_paths()
if len(selection) > 0:
return str(selection[0])
carb.log_warn("No Prim Selected")
return ""
# Get the area name specified
def get_area_name(self):
if self._area_name_model == "":
carb.log_warn("No Area Name Provided")
return self._area_name_model.as_string
# Get the prompt specified
def get_prompt(self):
if self._prompt_model == "":
carb.log_warn("No Prompt Provided")
return self._prompt_model.as_string
# Get the prim based on the Prim Path
def get_prim(self):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.GetPrimAtPath(self.current_area)
if prim.IsValid() is None:
carb.log_warn("No valid prim in the scene")
return prim
def destroy(self):
super().destroy()
self._combo_changed_sub = None
self._path_model = None
self._prompt_model = None
self._area_name_model = None
self._use_deepsearch = None
self._use_chatgpt = None | 9,607 | Python | 41.892857 | 161 | 0.595503 |
NVIDIA-Omniverse/orbit/tools/tests_to_skip.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# The following tests are skipped by run_tests.py
TESTS_TO_SKIP = [
# orbit
"test_argparser_launch.py", # app.close issue
"test_env_var_launch.py", # app.close issue
"test_kwarg_launch.py", # app.close issue
"test_differential_ik.py", # Failing
# orbit_tasks
"test_data_collector.py", # Failing
"test_record_video.py", # Failing
"test_rsl_rl_wrapper.py", # Timing out (10 minutes)
"test_sb3_wrapper.py", # Timing out (10 minutes)
]
| 603 | Python | 30.789472 | 56 | 0.660033 |
NVIDIA-Omniverse/orbit/tools/run_all_tests.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""A runner script for all the tests within source directory.
.. code-block:: bash
./orbit.sh -p tools/run_all_tests.py
# for dry run
./orbit.sh -p tools/run_all_tests.py --discover_only
# for quiet run
./orbit.sh -p tools/run_all_tests.py --quiet
# for increasing timeout (default is 600 seconds)
./orbit.sh -p tools/run_all_tests.py --timeout 1000
"""
from __future__ import annotations
import argparse
import logging
import os
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path
from prettytable import PrettyTable
# Tests to skip
from tests_to_skip import TESTS_TO_SKIP
ORBIT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
"""Path to the root directory of Orbit repository."""
def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Run all tests under current directory.")
# add arguments
parser.add_argument(
"--skip_tests",
default="",
help="Space separated list of tests to skip in addition to those in tests_to_skip.py.",
type=str,
nargs="*",
)
# configure default test directory (source directory)
default_test_dir = os.path.join(ORBIT_PATH, "source")
parser.add_argument(
"--test_dir", type=str, default=default_test_dir, help="Path to the directory containing the tests."
)
# configure default logging path based on time stamp
log_file_name = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".log"
default_log_path = os.path.join(ORBIT_PATH, "logs", "test_results", log_file_name)
parser.add_argument(
"--log_path", type=str, default=default_log_path, help="Path to the log file to store the results in."
)
parser.add_argument("--discover_only", action="store_true", help="Only discover and print tests, don't run them.")
parser.add_argument("--quiet", action="store_true", help="Don't print to console, only log to file.")
parser.add_argument("--timeout", type=int, default=600, help="Timeout for each test in seconds.")
# parse arguments
args = parser.parse_args()
return args
def test_all(
test_dir: str,
tests_to_skip: list[str],
log_path: str,
timeout: float = 600.0,
discover_only: bool = False,
quiet: bool = False,
) -> bool:
"""Run all tests under the given directory.
Args:
test_dir: Path to the directory containing the tests.
tests_to_skip: List of tests to skip.
log_path: Path to the log file to store the results in.
timeout: Timeout for each test in seconds. Defaults to 600 seconds (10 minutes).
discover_only: If True, only discover and print the tests without running them. Defaults to False.
quiet: If False, print the output of the tests to the terminal console (in addition to the log file).
Defaults to False.
Returns:
True if all un-skipped tests pass or `discover_only` is True. Otherwise, False.
Raises:
ValueError: If any test to skip is not found under the given `test_dir`.
"""
# Create the log directory if it doesn't exist
os.makedirs(os.path.dirname(log_path), exist_ok=True)
# Add file handler to log to file
logging_handlers = [logging.FileHandler(log_path)]
# We also want to print to console
if not quiet:
logging_handlers.append(logging.StreamHandler())
# Set up logger
logging.basicConfig(level=logging.INFO, format="%(message)s", handlers=logging_handlers)
# Discover all tests under current directory
all_test_paths = [str(path) for path in Path(test_dir).resolve().rglob("*test_*.py")]
skipped_test_paths = []
test_paths = []
# Check that all tests to skip are actually in the tests
for test_to_skip in tests_to_skip:
for test_path in all_test_paths:
if test_to_skip in test_path:
break
else:
raise ValueError(f"Test to skip '{test_to_skip}' not found in tests.")
# Remove tests to skip from the list of tests to run
if len(tests_to_skip) != 0:
for test_path in all_test_paths:
if any([test_to_skip in test_path for test_to_skip in tests_to_skip]):
skipped_test_paths.append(test_path)
else:
test_paths.append(test_path)
else:
test_paths = all_test_paths
# Sort test paths so they're always in the same order
all_test_paths.sort()
test_paths.sort()
skipped_test_paths.sort()
# Print tests to be run
logging.info("\n" + "=" * 60 + "\n")
logging.info(f"The following {len(all_test_paths)} tests were found:")
for i, test_path in enumerate(all_test_paths):
logging.info(f"{i + 1:02d}: {test_path}")
logging.info("\n" + "=" * 60 + "\n")
logging.info(f"The following {len(skipped_test_paths)} tests are marked to be skipped:")
for i, test_path in enumerate(skipped_test_paths):
logging.info(f"{i + 1:02d}: {test_path}")
logging.info("\n" + "=" * 60 + "\n")
# Exit if only discovering tests
if discover_only:
return True
results = {}
# Run each script and store results
for test_path in test_paths:
results[test_path] = {}
before = time.time()
logging.info("\n" + "-" * 60 + "\n")
logging.info(f"[INFO] Running '{test_path}'\n")
try:
completed_process = subprocess.run(
[sys.executable, test_path], check=True, capture_output=True, timeout=timeout
)
except subprocess.TimeoutExpired as e:
logging.error(f"Timeout occurred: {e}")
result = "TIMEDOUT"
stdout = e.stdout
stderr = e.stderr
except subprocess.CalledProcessError as e:
# When check=True is passed to subprocess.run() above, CalledProcessError is raised if the process returns a
# non-zero exit code. The caveat is returncode is not correctly updated in this case, so we simply
# catch the exception and set this test as FAILED
result = "FAILED"
stdout = e.stdout
stderr = e.stderr
except Exception as e:
logging.error(f"Unexpected exception {e}. Please report this issue on the repository.")
result = "FAILED"
stdout = e.stdout
stderr = e.stderr
else:
# Should only get here if the process ran successfully, e.g. no exceptions were raised
# but we still check the returncode just in case
result = "PASSED" if completed_process.returncode == 0 else "FAILED"
stdout = completed_process.stdout
stderr = completed_process.stderr
after = time.time()
time_elapsed = after - before
# Decode stdout and stderr and write to file and print to console if desired
stdout_str = stdout.decode("utf-8") if stdout is not None else ""
stderr_str = stderr.decode("utf-8") if stderr is not None else ""
# Write to log file
logging.info(stdout_str)
logging.info(stderr_str)
logging.info(f"[INFO] Time elapsed: {time_elapsed:.2f} s")
logging.info(f"[INFO] Result '{test_path}': {result}")
# Collect results
results[test_path]["time_elapsed"] = time_elapsed
results[test_path]["result"] = result
# Calculate the number and percentage of passing tests
num_tests = len(all_test_paths)
num_passing = len([test_path for test_path in test_paths if results[test_path]["result"] == "PASSED"])
num_failing = len([test_path for test_path in test_paths if results[test_path]["result"] == "FAILED"])
num_timing_out = len([test_path for test_path in test_paths if results[test_path]["result"] == "TIMEDOUT"])
num_skipped = len(skipped_test_paths)
if num_tests == 0:
passing_percentage = 100
else:
passing_percentage = (num_passing + num_skipped) / num_tests * 100
# Print summaries of test results
summary_str = "\n\n"
summary_str += "===================\n"
summary_str += "Test Result Summary\n"
summary_str += "===================\n"
summary_str += f"Total: {num_tests}\n"
summary_str += f"Passing: {num_passing}\n"
summary_str += f"Failing: {num_failing}\n"
summary_str += f"Skipped: {num_skipped}\n"
summary_str += f"Timing Out: {num_timing_out}\n"
summary_str += f"Passing Percentage: {passing_percentage:.2f}%\n"
# Print time elapsed in hours, minutes, seconds
total_time = sum([results[test_path]["time_elapsed"] for test_path in test_paths])
summary_str += f"Total Time Elapsed: {total_time // 3600}h"
summary_str += f"{total_time // 60 % 60}m"
summary_str += f"{total_time % 60:.2f}s"
summary_str += "\n\n=======================\n"
summary_str += "Per Test Result Summary\n"
summary_str += "=======================\n"
# Construct table of results per test
per_test_result_table = PrettyTable(field_names=["Test Path", "Result", "Time (s)"])
per_test_result_table.align["Test Path"] = "l"
per_test_result_table.align["Time (s)"] = "r"
for test_path in test_paths:
per_test_result_table.add_row(
[test_path, results[test_path]["result"], f"{results[test_path]['time_elapsed']:0.2f}"]
)
for test_path in skipped_test_paths:
per_test_result_table.add_row([test_path, "SKIPPED", "N/A"])
summary_str += per_test_result_table.get_string()
# Print summary to console and log file
logging.info(summary_str)
# Only count failing and timing out tests towards failure
return num_failing + num_timing_out == 0
if __name__ == "__main__":
# parse command line arguments
args = parse_args()
# add tests to skip to the list of tests to skip
tests_to_skip = TESTS_TO_SKIP
tests_to_skip += args.skip_tests
# run all tests
test_success = test_all(
test_dir=args.test_dir,
tests_to_skip=tests_to_skip,
log_path=args.log_path,
timeout=args.timeout,
discover_only=args.discover_only,
quiet=args.quiet,
)
# update exit status based on all tests passing or not
if not test_success:
exit(1)
| 10,468 | Python | 36.256228 | 120 | 0.62629 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/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_tasks' python package."""
import itertools
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"))
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
# generic
"numpy",
"torch==2.0.1",
"torchvision>=0.14.1", # ensure compatibility with torch 1.13.1
"protobuf>=3.20.2",
# data collection
"h5py",
# basic logger
"tensorboard",
# video recording
"moviepy",
]
# Extra dependencies for RL agents
EXTRAS_REQUIRE = {
"sb3": ["stable-baselines3>=2.0"],
"skrl": ["skrl>=1.1.0"],
"rl_games": ["rl-games==1.6.1", "gym"], # rl-games still needs gym :(
"rsl_rl": ["rsl_rl@git+https://github.com/leggedrobotics/rsl_rl.git"],
"robomimic": ["robomimic@git+https://github.com/ARISE-Initiative/robomimic.git"],
}
# cumulation of all extra-requires
EXTRAS_REQUIRE["all"] = list(itertools.chain.from_iterable(EXTRAS_REQUIRE.values()))
# Installation operation
setup(
name="omni-isaac-orbit_tasks",
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",
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRE,
packages=["omni.isaac.orbit_tasks"],
classifiers=[
"Natural Language :: English",
"Programming Language :: Python :: 3.10",
"Isaac Sim :: 2023.1.0-hotfix.1",
"Isaac Sim :: 2023.1.1",
],
zip_safe=False,
)
| 2,113 | Python | 29.637681 | 89 | 0.67345 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/test/test_environments.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
from omni.isaac.orbit.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.orbit.envs import RLTaskEnv, RLTaskEnvCfg
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils.parse_cfg import parse_env_cfg
class TestEnvironments(unittest.TestCase):
"""Test cases for all registered environments."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
"""
Test fixtures.
"""
def test_multiple_instances_gpu(self):
"""Run all environments with multiple instances and check environments return valid signals."""
# common parameters
num_envs = 32
use_gpu = True
# iterate over all registered environments
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# check environment
self._check_random_actions(task_name, use_gpu, num_envs, num_steps=100)
# close the environment
print(f">>> Closing environment: {task_name}")
print("-" * 80)
def test_single_instance_gpu(self):
"""Run all environments with single instance and check environments return valid signals."""
# common parameters
num_envs = 1
use_gpu = True
# iterate over all registered environments
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# check environment
self._check_random_actions(task_name, use_gpu, num_envs, num_steps=100)
# close the environment
print(f">>> Closing environment: {task_name}")
print("-" * 80)
"""
Helper functions.
"""
def _check_random_actions(self, task_name: str, use_gpu: bool, num_envs: int, num_steps: int = 1000):
"""Run random actions and check environments return valid signals."""
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=use_gpu, num_envs=num_envs)
# create environment
env: RLTaskEnv = gym.make(task_name, cfg=env_cfg)
# reset environment
obs, _ = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
# simulate environment for num_steps steps
with torch.inference_mode():
for _ in range(num_steps):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
env.close()
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestEnvironments._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
run_tests()
| 4,563 | Python | 32.807407 | 105 | 0.608372 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/test/test_data_collector.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
from omni.isaac.orbit.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import os
import torch
import unittest
from omni.isaac.orbit_tasks.utils.data_collector import RobomimicDataCollector
class TestRobomimicDataCollector(unittest.TestCase):
"""Test dataset flushing behavior of robomimic data collector."""
def test_basic_flushing(self):
"""Adds random data into the collector and checks saving of the data."""
# name of the environment (needed by robomimic)
task_name = "My-Task-v0"
# specify directory for logging experiments
test_dir = os.path.dirname(os.path.abspath(__file__))
log_dir = os.path.join(test_dir, "output", "demos")
# name of the file to save data
filename = "hdf_dataset.hdf5"
# number of episodes to collect
num_demos = 10
# number of environments to simulate
num_envs = 4
# create data-collector
collector_interface = RobomimicDataCollector(task_name, log_dir, filename, num_demos)
# reset the collector
collector_interface.reset()
while not collector_interface.is_stopped():
# generate random data to store
# -- obs
obs = {"joint_pos": torch.randn(num_envs, 7), "joint_vel": torch.randn(num_envs, 7)}
# -- actions
actions = torch.randn(num_envs, 7)
# -- next obs
next_obs = {"joint_pos": torch.randn(num_envs, 7), "joint_vel": torch.randn(num_envs, 7)}
# -- rewards
rewards = torch.randn(num_envs)
# -- dones
dones = torch.rand(num_envs) > 0.5
# store signals
# -- obs
for key, value in obs.items():
collector_interface.add(f"obs/{key}", value)
# -- actions
collector_interface.add("actions", actions)
# -- next_obs
for key, value in next_obs.items():
collector_interface.add(f"next_obs/{key}", value.cpu().numpy())
# -- rewards
collector_interface.add("rewards", rewards)
# -- dones
collector_interface.add("dones", dones)
# flush data from collector for successful environments
# note: in this case we flush all the time
reset_env_ids = dones.nonzero(as_tuple=False).squeeze(-1)
collector_interface.flush(reset_env_ids)
# close collector
collector_interface.close()
# TODO: Add inspection of the saved dataset as part of the test.
if __name__ == "__main__":
run_tests()
| 2,942 | Python | 32.443181 | 101 | 0.604351 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/test/test_record_video.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
from omni.isaac.orbit.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True, offscreen_render=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import os
import torch
import unittest
import omni.usd
from omni.isaac.orbit.envs import RLTaskEnv, RLTaskEnvCfg
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils import parse_env_cfg
class TestRecordVideoWrapper(unittest.TestCase):
"""Test recording videos using the RecordVideo wrapper."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
# directory to save videos
cls.videos_dir = os.path.join(os.path.dirname(__file__), "output", "videos")
def setUp(self) -> None:
# common parameters
self.num_envs = 16
self.use_gpu = True
# video parameters
self.step_trigger = lambda step: step % 225 == 0
self.video_length = 200
def test_record_video(self):
"""Run random actions agent with recording of videos."""
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env: RLTaskEnv = gym.make(task_name, cfg=env_cfg, render_mode="rgb_array")
# directory to save videos
videos_dir = os.path.join(self.videos_dir, task_name)
# wrap environment to record videos
env = gym.wrappers.RecordVideo(
env, videos_dir, step_trigger=self.step_trigger, video_length=self.video_length, disable_logger=True
)
# reset environment
env.reset()
# simulate environment
with torch.inference_mode():
for _ in range(500):
# compute zero actions
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
_ = env.step(actions)
# close the simulator
env.close()
if __name__ == "__main__":
run_tests()
| 2,956 | Python | 31.141304 | 116 | 0.618065 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/test/wrappers/test_rsl_rl_wrapper.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
from omni.isaac.orbit.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.orbit.envs import RLTaskEnvCfg
import omni.isaac.orbit_tasks # noqa: F401
from omni.isaac.orbit_tasks.utils.parse_cfg import parse_env_cfg
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlVecEnvWrapper
class TestRslRlVecEnvWrapper(unittest.TestCase):
"""Test that RSL-RL VecEnv wrapper works as expected."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# only pick the first three environments to test
cls.registered_tasks = cls.registered_tasks[:3]
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
def setUp(self) -> None:
# common parameters
self.num_envs = 64
self.use_gpu = True
def test_random_actions(self):
"""Run random actions and check environments return valid signals."""
for task_name in self.registered_tasks:
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = RslRlVecEnvWrapper(env)
# reset environment
obs, extras = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
self.assertTrue(self._check_valid_tensor(extras))
# simulate environment for 1000 steps
with torch.inference_mode():
for _ in range(1000):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
def test_no_time_outs(self):
"""Check that environments with finite horizon do not send time-out signals."""
for task_name in self.registered_tasks[0:5]:
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# change to finite horizon
env_cfg.is_finite_horizon = True
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = RslRlVecEnvWrapper(env)
# reset environment
_, extras = env.reset()
# check signal
self.assertNotIn("time_outs", extras, msg="Time-out signal found in finite horizon environment.")
# simulate environment for 10 steps
with torch.inference_mode():
for _ in range(10):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
extras = env.step(actions)[-1]
# check signals
self.assertNotIn("time_outs", extras, msg="Time-out signal found in finite horizon environment.")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
"""
Helper functions.
"""
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestRslRlVecEnvWrapper._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
run_tests()
| 5,464 | Python | 34.487013 | 117 | 0.587299 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Classic environments for control.
These environments are based on the MuJoCo environments provided by OpenAI.
Reference:
https://github.com/openai/gym/tree/master/gym/envs/mujoco
"""
| 315 | Python | 23.307691 | 75 | 0.75873 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/ant_env_cfg.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.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import EventTermCfg as EventTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.terrains import TerrainImporterCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
import omni.isaac.orbit_tasks.classic.humanoid.mdp as mdp
##
# Scene definition
##
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Configuration for the terrain scene with an ant robot."""
# terrain
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="average",
restitution_combine_mode="average",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
debug_vis=False,
)
# robot
robot = ArticulationCfg(
prim_path="{ENV_REGEX_NS}/Robot",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Ant/ant_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=10.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,
),
copy_from_source=False,
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.5),
joint_pos={".*": 0.0},
),
actuators={
"body": ImplicitActuatorCfg(
joint_names_expr=[".*"],
stiffness=0.0,
damping=0.0,
),
},
)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=[".*"], scale=7.5)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for the policy."""
base_height = ObsTerm(func=mdp.base_pos_z)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel)
base_ang_vel = ObsTerm(func=mdp.base_ang_vel)
base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll)
base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)})
base_up_proj = ObsTerm(func=mdp.base_up_proj)
base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)})
joint_pos_norm = ObsTerm(func=mdp.joint_pos_norm)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.2)
feet_body_forces = ObsTerm(
func=mdp.body_incoming_wrench,
scale=0.1,
params={
"asset_cfg": SceneEntityCfg(
"robot", body_names=["front_left_foot", "front_right_foot", "left_back_foot", "right_back_foot"]
)
},
)
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
reset_base = EventTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={"pose_range": {}, "velocity_range": {}},
)
reset_robot_joints = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"position_range": (-0.2, 0.2),
"velocity_range": (-0.1, 0.1),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Reward for moving forward
progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)})
# (2) Stay alive bonus
alive = RewTerm(func=mdp.is_alive, weight=0.5)
# (3) Reward for non-upright posture
upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93})
# (4) Reward for moving in the right direction
move_to_target = RewTerm(
func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)}
)
# (5) Penalty for large action commands
action_l2 = RewTerm(func=mdp.action_l2, weight=-0.005)
# (6) Penalty for energy consumption
energy = RewTerm(func=mdp.power_consumption, weight=-0.05, params={"gear_ratio": {".*": 15.0}})
# (7) Penalty for reaching close to joint limits
joint_limits = RewTerm(
func=mdp.joint_limits_penalty_ratio, weight=-0.1, params={"threshold": 0.99, "gear_ratio": {".*": 15.0}}
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Terminate if the episode length is exceeded
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Terminate if the robot falls
torso_height = DoneTerm(func=mdp.base_height, params={"minimum_height": 0.31})
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
pass
@configclass
class AntEnvCfg(RLTaskEnvCfg):
"""Configuration for the MuJoCo-style Ant walking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
events: EventCfg = EventCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 16.0
# simulation settings
self.sim.dt = 1 / 120.0
self.sim.physx.bounce_threshold_velocity = 0.2
# default friction material
self.sim.physics_material.static_friction = 1.0
self.sim.physics_material.dynamic_friction = 1.0
self.sim.physics_material.restitution = 0.0
| 7,500 | Python | 31.055555 | 116 | 0.634667 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Ant locomotion environment (similar to OpenAI Gym Ant-v2).
"""
import gymnasium as gym
from . import agents, ant_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Ant-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": ant_env_cfg.AntEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.AntPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 776 | Python | 24.899999 | 79 | 0.653351 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/ant/agents/rsl_rl_ppo_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class AntPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 32
max_iterations = 1000
save_interval = 50
experiment_name = "ant"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[400, 200, 100],
critic_hidden_dims=[400, 200, 100],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,068 | Python | 24.45238 | 58 | 0.641386 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Cartpole balancing environment.
"""
import gymnasium as gym
from . import agents
from .cartpole_env_cfg import CartpoleEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Cartpole-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": CartpoleEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.CartpolePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 784 | Python | 24.32258 | 79 | 0.667092 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/cartpole_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import math
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import EventTermCfg as EventTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.utils import configclass
import omni.isaac.orbit_tasks.classic.cartpole.mdp as mdp
##
# Pre-defined configs
##
from omni.isaac.orbit_assets.cartpole import CARTPOLE_CFG # isort:skip
##
# Scene definition
##
@configclass
class CartpoleSceneCfg(InteractiveSceneCfg):
"""Configuration for a cart-pole scene."""
# ground plane
ground = AssetBaseCfg(
prim_path="/World/ground",
spawn=sim_utils.GroundPlaneCfg(size=(100.0, 100.0)),
)
# cartpole
robot: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# lights
dome_light = AssetBaseCfg(
prim_path="/World/DomeLight",
spawn=sim_utils.DomeLightCfg(color=(0.9, 0.9, 0.9), intensity=500.0),
)
distant_light = AssetBaseCfg(
prim_path="/World/DistantLight",
spawn=sim_utils.DistantLightCfg(color=(0.9, 0.9, 0.9), intensity=2500.0),
init_state=AssetBaseCfg.InitialStateCfg(rot=(0.738, 0.477, 0.477, 0.0)),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["slider_to_cart"], scale=100.0)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
# observation terms (order preserved)
joint_pos_rel = ObsTerm(func=mdp.joint_pos_rel)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel)
def __post_init__(self) -> None:
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
# reset
reset_cart_position = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]),
"position_range": (-1.0, 1.0),
"velocity_range": (-0.5, 0.5),
},
)
reset_pole_position = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]),
"position_range": (-0.25 * math.pi, 0.25 * math.pi),
"velocity_range": (-0.25 * math.pi, 0.25 * math.pi),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Constant running reward
alive = RewTerm(func=mdp.is_alive, weight=1.0)
# (2) Failure penalty
terminating = RewTerm(func=mdp.is_terminated, weight=-2.0)
# (3) Primary task: keep pole upright
pole_pos = RewTerm(
func=mdp.joint_pos_target_l2,
weight=-1.0,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), "target": 0.0},
)
# (4) Shaping tasks: lower cart velocity
cart_vel = RewTerm(
func=mdp.joint_vel_l1,
weight=-0.01,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"])},
)
# (5) Shaping tasks: lower pole angular velocity
pole_vel = RewTerm(
func=mdp.joint_vel_l1,
weight=-0.005,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"])},
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Time out
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Cart out of bounds
cart_out_of_bounds = DoneTerm(
func=mdp.joint_pos_manual_limit,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), "bounds": (-3.0, 3.0)},
)
@configclass
class CurriculumCfg:
"""Configuration for the curriculum."""
pass
##
# Environment configuration
##
@configclass
class CartpoleEnvCfg(RLTaskEnvCfg):
"""Configuration for the locomotion velocity-tracking environment."""
# Scene settings
scene: CartpoleSceneCfg = CartpoleSceneCfg(num_envs=4096, env_spacing=4.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
events: EventCfg = EventCfg()
# MDP settings
curriculum: CurriculumCfg = CurriculumCfg()
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
# No command generator
commands: CommandsCfg = CommandsCfg()
# Post initialization
def __post_init__(self) -> None:
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 5
# viewer settings
self.viewer.eye = (8.0, 0.0, 5.0)
# simulation settings
self.sim.dt = 1 / 120
| 5,671 | Python | 26.803921 | 109 | 0.6535 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/cartpole/mdp/rewards.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.utils.math import wrap_to_pi
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def joint_pos_target_l2(env: RLTaskEnv, target: float, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Penalize joint position deviation from a target value."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# wrap the joint positions to (-pi, pi)
joint_pos = wrap_to_pi(asset.data.joint_pos[:, asset_cfg.joint_ids])
# compute the reward
return torch.sum(torch.square(joint_pos - target), dim=1)
| 907 | Python | 32.629628 | 98 | 0.742007 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Humanoid locomotion environment (similar to OpenAI Gym Humanoid-v2).
"""
import gymnasium as gym
from . import agents, humanoid_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Humanoid-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": humanoid_env_cfg.HumanoidEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.HumanoidPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 811 | Python | 26.066666 | 79 | 0.668311 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/humanoid_env_cfg.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.actuators import ImplicitActuatorCfg
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import EventTermCfg as EventTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.terrains import TerrainImporterCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
import omni.isaac.orbit_tasks.classic.humanoid.mdp as mdp
##
# Scene definition
##
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Configuration for the terrain scene with a humanoid robot."""
# terrain
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=1.0, dynamic_friction=1.0, restitution=0.0),
debug_vis=False,
)
# robot
robot = ArticulationCfg(
prim_path="{ENV_REGEX_NS}/Robot",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Humanoid/humanoid_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=None,
max_depenetration_velocity=10.0,
enable_gyroscopic_forces=True,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True,
solver_position_iteration_count=4,
solver_velocity_iteration_count=0,
sleep_threshold=0.005,
stabilization_threshold=0.001,
),
copy_from_source=False,
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 1.34),
joint_pos={".*": 0.0},
),
actuators={
"body": ImplicitActuatorCfg(
joint_names_expr=[".*"],
stiffness={
".*_waist.*": 20.0,
".*_upper_arm.*": 10.0,
"pelvis": 10.0,
".*_lower_arm": 2.0,
".*_thigh:0": 10.0,
".*_thigh:1": 20.0,
".*_thigh:2": 10.0,
".*_shin": 5.0,
".*_foot.*": 2.0,
},
damping={
".*_waist.*": 5.0,
".*_upper_arm.*": 5.0,
"pelvis": 5.0,
".*_lower_arm": 1.0,
".*_thigh:0": 5.0,
".*_thigh:1": 5.0,
".*_thigh:2": 5.0,
".*_shin": 0.1,
".*_foot.*": 1.0,
},
),
},
)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(
asset_name="robot",
joint_names=[".*"],
scale={
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
},
)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for the policy."""
base_height = ObsTerm(func=mdp.base_pos_z)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel)
base_ang_vel = ObsTerm(func=mdp.base_ang_vel, scale=0.25)
base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll)
base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)})
base_up_proj = ObsTerm(func=mdp.base_up_proj)
base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)})
joint_pos_norm = ObsTerm(func=mdp.joint_pos_norm)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.1)
feet_body_forces = ObsTerm(
func=mdp.body_incoming_wrench,
scale=0.01,
params={"asset_cfg": SceneEntityCfg("robot", body_names=["left_foot", "right_foot"])},
)
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
reset_base = EventTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={"pose_range": {}, "velocity_range": {}},
)
reset_robot_joints = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"position_range": (-0.2, 0.2),
"velocity_range": (-0.1, 0.1),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Reward for moving forward
progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)})
# (2) Stay alive bonus
alive = RewTerm(func=mdp.is_alive, weight=2.0)
# (3) Reward for non-upright posture
upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93})
# (4) Reward for moving in the right direction
move_to_target = RewTerm(
func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)}
)
# (5) Penalty for large action commands
action_l2 = RewTerm(func=mdp.action_l2, weight=-0.01)
# (6) Penalty for energy consumption
energy = RewTerm(
func=mdp.power_consumption,
weight=-0.005,
params={
"gear_ratio": {
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
}
},
)
# (7) Penalty for reaching close to joint limits
joint_limits = RewTerm(
func=mdp.joint_limits_penalty_ratio,
weight=-0.25,
params={
"threshold": 0.98,
"gear_ratio": {
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
},
},
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Terminate if the episode length is exceeded
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Terminate if the robot falls
torso_height = DoneTerm(func=mdp.base_height, params={"minimum_height": 0.8})
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
pass
@configclass
class HumanoidEnvCfg(RLTaskEnvCfg):
"""Configuration for the MuJoCo-style Humanoid walking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
events: EventCfg = EventCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 16.0
# simulation settings
self.sim.dt = 1 / 120.0
self.sim.physx.bounce_threshold_velocity = 0.2
# default friction material
self.sim.physics_material.static_friction = 1.0
self.sim.physics_material.dynamic_friction = 1.0
self.sim.physics_material.restitution = 0.0
| 9,098 | Python | 30.484429 | 116 | 0.558474 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/mdp/rewards.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
import omni.isaac.orbit.utils.math as math_utils
import omni.isaac.orbit.utils.string as string_utils
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import ManagerTermBase, RewardTermCfg, SceneEntityCfg
from . import observations as obs
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def upright_posture_bonus(
env: RLTaskEnv, threshold: float, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Reward for maintaining an upright posture."""
up_proj = obs.base_up_proj(env, asset_cfg).squeeze(-1)
return (up_proj > threshold).float()
def move_to_target_bonus(
env: RLTaskEnv,
threshold: float,
target_pos: tuple[float, float, float],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
) -> torch.Tensor:
"""Reward for moving to the target heading."""
heading_proj = obs.base_heading_proj(env, target_pos, asset_cfg).squeeze(-1)
return torch.where(heading_proj > threshold, 1.0, heading_proj / threshold)
class progress_reward(ManagerTermBase):
"""Reward for making progress towards the target."""
def __init__(self, env: RLTaskEnv, cfg: RewardTermCfg):
# initialize the base class
super().__init__(cfg, env)
# create history buffer
self.potentials = torch.zeros(env.num_envs, device=env.device)
self.prev_potentials = torch.zeros_like(self.potentials)
def reset(self, env_ids: torch.Tensor):
# extract the used quantities (to enable type-hinting)
asset: Articulation = self._env.scene["robot"]
# compute projection of current heading to desired heading vector
target_pos = torch.tensor(self.cfg.params["target_pos"], device=self.device)
to_target_pos = target_pos - asset.data.root_pos_w[env_ids, :3]
# reward terms
self.potentials[env_ids] = -torch.norm(to_target_pos, p=2, dim=-1) / self._env.step_dt
self.prev_potentials[env_ids] = self.potentials[env_ids]
def __call__(
self,
env: RLTaskEnv,
target_pos: tuple[float, float, float],
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
) -> torch.Tensor:
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute vector to target
target_pos = torch.tensor(target_pos, device=env.device)
to_target_pos = target_pos - asset.data.root_pos_w[:, :3]
to_target_pos[:, 2] = 0.0
# update history buffer and compute new potential
self.prev_potentials[:] = self.potentials[:]
self.potentials[:] = -torch.norm(to_target_pos, p=2, dim=-1) / env.step_dt
return self.potentials - self.prev_potentials
class joint_limits_penalty_ratio(ManagerTermBase):
"""Penalty for violating joint limits weighted by the gear ratio."""
def __init__(self, env: RLTaskEnv, cfg: RewardTermCfg):
# add default argument
if "asset_cfg" not in cfg.params:
cfg.params["asset_cfg"] = SceneEntityCfg("robot")
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[cfg.params["asset_cfg"].name]
# resolve the gear ratio for each joint
self.gear_ratio = torch.ones(env.num_envs, asset.num_joints, device=env.device)
index_list, _, value_list = string_utils.resolve_matching_names_values(
cfg.params["gear_ratio"], asset.joint_names
)
self.gear_ratio[:, index_list] = torch.tensor(value_list, device=env.device)
self.gear_ratio_scaled = self.gear_ratio / torch.max(self.gear_ratio)
def __call__(
self, env: RLTaskEnv, threshold: float, gear_ratio: dict[str, float], asset_cfg: SceneEntityCfg
) -> torch.Tensor:
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute the penalty over normalized joints
joint_pos_scaled = math_utils.scale_transform(
asset.data.joint_pos, asset.data.soft_joint_pos_limits[..., 0], asset.data.soft_joint_pos_limits[..., 1]
)
# scale the violation amount by the gear ratio
violation_amount = (torch.abs(joint_pos_scaled) - threshold) / (1 - threshold)
violation_amount = violation_amount * self.gear_ratio_scaled
return torch.sum((torch.abs(joint_pos_scaled) > threshold) * violation_amount, dim=-1)
class power_consumption(ManagerTermBase):
"""Penalty for the power consumed by the actions to the environment.
This is computed as commanded torque times the joint velocity.
"""
def __init__(self, env: RLTaskEnv, cfg: RewardTermCfg):
# add default argument
if "asset_cfg" not in cfg.params:
cfg.params["asset_cfg"] = SceneEntityCfg("robot")
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[cfg.params["asset_cfg"].name]
# resolve the gear ratio for each joint
self.gear_ratio = torch.ones(env.num_envs, asset.num_joints, device=env.device)
index_list, _, value_list = string_utils.resolve_matching_names_values(
cfg.params["gear_ratio"], asset.joint_names
)
self.gear_ratio[:, index_list] = torch.tensor(value_list, device=env.device)
self.gear_ratio_scaled = self.gear_ratio / torch.max(self.gear_ratio)
def __call__(self, env: RLTaskEnv, gear_ratio: dict[str, float], asset_cfg: SceneEntityCfg) -> torch.Tensor:
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# return power = torque * velocity (here actions: joint torques)
return torch.sum(torch.abs(env.action_manager.action * asset.data.joint_vel * self.gear_ratio_scaled), dim=-1)
| 6,069 | Python | 42.985507 | 118 | 0.66782 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/classic/humanoid/mdp/observations.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
import omni.isaac.orbit.utils.math as math_utils
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import SceneEntityCfg
if TYPE_CHECKING:
from omni.isaac.orbit.envs import BaseEnv
def base_yaw_roll(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Yaw and roll of the base in the simulation world frame."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# extract euler angles (in world frame)
roll, _, yaw = math_utils.euler_xyz_from_quat(asset.data.root_quat_w)
# normalize angle to [-pi, pi]
roll = torch.atan2(torch.sin(roll), torch.cos(roll))
yaw = torch.atan2(torch.sin(yaw), torch.cos(yaw))
return torch.cat((yaw.unsqueeze(-1), roll.unsqueeze(-1)), dim=-1)
def base_up_proj(env: BaseEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Projection of the base up vector onto the world up vector."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute base up vector
base_up_vec = math_utils.quat_rotate(asset.data.root_quat_w, -asset.GRAVITY_VEC_W)
return base_up_vec[:, 2].unsqueeze(-1)
def base_heading_proj(
env: BaseEnv, target_pos: tuple[float, float, float], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Projection of the base forward vector onto the world forward vector."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute desired heading direction
to_target_pos = torch.tensor(target_pos, device=env.device) - asset.data.root_pos_w[:, :3]
to_target_pos[:, 2] = 0.0
to_target_dir = math_utils.normalize(to_target_pos)
# compute base forward vector
heading_vec = math_utils.quat_rotate(asset.data.root_quat_w, asset.FORWARD_VEC_B)
# compute dot product between heading and target direction
heading_proj = torch.bmm(heading_vec.view(env.num_envs, 1, 3), to_target_dir.view(env.num_envs, 3, 1))
return heading_proj.view(env.num_envs, 1)
def base_angle_to_target(
env: BaseEnv, target_pos: tuple[float, float, float], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Angle between the base forward vector and the vector to the target."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# compute desired heading direction
to_target_pos = torch.tensor(target_pos, device=env.device) - asset.data.root_pos_w[:, :3]
walk_target_angle = torch.atan2(to_target_pos[:, 1], to_target_pos[:, 0])
# compute base forward vector
_, _, yaw = math_utils.euler_xyz_from_quat(asset.data.root_quat_w)
# normalize angle to target to [-pi, pi]
angle_to_target = walk_target_angle - yaw
angle_to_target = torch.atan2(torch.sin(angle_to_target), torch.cos(angle_to_target))
return angle_to_target.unsqueeze(-1)
| 3,270 | Python | 42.039473 | 109 | 0.705505 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Manipulation environments for fixed-arm robots."""
from .reach import * # noqa
| 207 | Python | 22.111109 | 56 | 0.729469 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/reach_env_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
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import ActionTermCfg as ActionTerm
from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm
from omni.isaac.orbit.managers import EventTermCfg as EventTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise
import omni.isaac.orbit_tasks.manipulation.reach.mdp as mdp
##
# Scene definition
##
@configclass
class ReachSceneCfg(InteractiveSceneCfg):
"""Configuration for the scene with a robotic arm."""
# world
ground = AssetBaseCfg(
prim_path="/World/ground",
spawn=sim_utils.GroundPlaneCfg(),
init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, -1.05)),
)
table = AssetBaseCfg(
prim_path="{ENV_REGEX_NS}/Table",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/SeattleLabTable/table_instanceable.usd",
),
init_state=AssetBaseCfg.InitialStateCfg(pos=(0.55, 0.0, 0.0), rot=(0.70711, 0.0, 0.0, 0.70711)),
)
# robots
robot: ArticulationCfg = MISSING
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DomeLightCfg(color=(0.75, 0.75, 0.75), intensity=2500.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
ee_pose = mdp.UniformPoseCommandCfg(
asset_name="robot",
body_name=MISSING,
resampling_time_range=(4.0, 4.0),
debug_vis=True,
ranges=mdp.UniformPoseCommandCfg.Ranges(
pos_x=(0.35, 0.65),
pos_y=(-0.2, 0.2),
pos_z=(0.15, 0.5),
roll=(0.0, 0.0),
pitch=MISSING, # depends on end-effector axis
yaw=(-3.14, 3.14),
),
)
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
arm_action: ActionTerm = MISSING
gripper_action: ActionTerm | None = None
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
# observation terms (order preserved)
joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01))
joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-0.01, n_max=0.01))
pose_command = ObsTerm(func=mdp.generated_commands, params={"command_name": "ee_pose"})
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = True
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
reset_robot_joints = EventTerm(
func=mdp.reset_joints_by_scale,
mode="reset",
params={
"position_range": (0.5, 1.5),
"velocity_range": (0.0, 0.0),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# task terms
end_effector_position_tracking = RewTerm(
func=mdp.position_command_error,
weight=-0.2,
params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "command_name": "ee_pose"},
)
end_effector_orientation_tracking = RewTerm(
func=mdp.orientation_command_error,
weight=-0.05,
params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "command_name": "ee_pose"},
)
# action penalty
action_rate = RewTerm(func=mdp.action_rate_l2, weight=-0.0001)
joint_vel = RewTerm(
func=mdp.joint_vel_l2,
weight=-0.0001,
params={"asset_cfg": SceneEntityCfg("robot")},
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
time_out = DoneTerm(func=mdp.time_out, time_out=True)
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
action_rate = CurrTerm(
func=mdp.modify_reward_weight, params={"term_name": "action_rate", "weight": -0.005, "num_steps": 4500}
)
##
# Environment configuration
##
@configclass
class ReachEnvCfg(RLTaskEnvCfg):
"""Configuration for the reach end-effector pose tracking environment."""
# Scene settings
scene: ReachSceneCfg = ReachSceneCfg(num_envs=4096, env_spacing=2.5)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
events: EventCfg = EventCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 12.0
self.viewer.eye = (3.5, 3.5, 3.5)
# simulation settings
self.sim.dt = 1.0 / 60.0
| 5,740 | Python | 27.562189 | 111 | 0.661324 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Fixed-arm environments with end-effector pose tracking commands."""
| 194 | Python | 26.857139 | 70 | 0.752577 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/mdp/rewards.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import RigidObject
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.utils.math import combine_frame_transforms, quat_error_magnitude, quat_mul
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def position_command_error(env: RLTaskEnv, command_name: str, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Penalize tracking of the position error using L2-norm.
The function computes the position error between the desired position (from the command) and the
current position of the asset's body (in world frame). The position error is computed as the L2-norm
of the difference between the desired and current positions.
"""
# extract the asset (to enable type hinting)
asset: RigidObject = env.scene[asset_cfg.name]
command = env.command_manager.get_command(command_name)
# obtain the desired and current positions
des_pos_b = command[:, :3]
des_pos_w, _ = combine_frame_transforms(asset.data.root_state_w[:, :3], asset.data.root_state_w[:, 3:7], des_pos_b)
curr_pos_w = asset.data.body_state_w[:, asset_cfg.body_ids[0], :3] # type: ignore
return torch.norm(curr_pos_w - des_pos_w, dim=1)
def orientation_command_error(env: RLTaskEnv, command_name: str, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Penalize tracking orientation error using shortest path.
The function computes the orientation error between the desired orientation (from the command) and the
current orientation of the asset's body (in world frame). The orientation error is computed as the shortest
path between the desired and current orientations.
"""
# extract the asset (to enable type hinting)
asset: RigidObject = env.scene[asset_cfg.name]
command = env.command_manager.get_command(command_name)
# obtain the desired and current orientations
des_quat_b = command[:, 3:7]
des_quat_w = quat_mul(asset.data.root_state_w[:, 3:7], des_quat_b)
curr_quat_w = asset.data.body_state_w[:, asset_cfg.body_ids[0], 3:7] # type: ignore
return quat_error_magnitude(curr_quat_w, des_quat_w)
| 2,337 | Python | 44.843136 | 119 | 0.728712 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/franka/ik_rel_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.controllers.differential_ik_cfg import DifferentialIKControllerCfg
from omni.isaac.orbit.envs.mdp.actions.actions_cfg import DifferentialInverseKinematicsActionCfg
from omni.isaac.orbit.utils import configclass
from . import joint_pos_env_cfg
##
# Pre-defined configs
##
from omni.isaac.orbit_assets.franka import FRANKA_PANDA_HIGH_PD_CFG # isort: skip
@configclass
class FrankaReachEnvCfg(joint_pos_env_cfg.FrankaReachEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# Set Franka as robot
# We switch here to a stiffer PD controller for IK tracking to be better.
self.scene.robot = FRANKA_PANDA_HIGH_PD_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# Set actions for the specific robot type (franka)
self.actions.body_joint_pos = DifferentialInverseKinematicsActionCfg(
asset_name="robot",
joint_names=["panda_joint.*"],
body_name="panda_hand",
controller=DifferentialIKControllerCfg(command_type="pose", use_relative_mode=True, ik_method="dls"),
scale=0.5,
body_offset=DifferentialInverseKinematicsActionCfg.OffsetCfg(pos=[0.0, 0.0, 0.107]),
)
@configclass
class FrankaReachEnvCfg_PLAY(FrankaReachEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# disable randomization for play
self.observations.policy.enable_corruption = False
| 1,734 | Python | 34.408163 | 113 | 0.683968 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/franka/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, ik_abs_env_cfg, ik_rel_env_cfg, joint_pos_env_cfg
##
# Register Gym environments.
##
##
# Joint Position Control
##
gym.register(
id="Isaac-Reach-Franka-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": joint_pos_env_cfg.FrankaReachEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_cfg:FrankaReachPPORunnerCfg",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
)
gym.register(
id="Isaac-Reach-Franka-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": joint_pos_env_cfg.FrankaReachEnvCfg_PLAY,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_cfg:FrankaReachPPORunnerCfg",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
)
##
# Inverse Kinematics - Absolute Pose Control
##
gym.register(
id="Isaac-Reach-Franka-IK-Abs-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_abs_env_cfg.FrankaReachEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_cfg:FrankaReachPPORunnerCfg",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
gym.register(
id="Isaac-Reach-Franka-IK-Abs-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_abs_env_cfg.FrankaReachEnvCfg_PLAY,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_cfg:FrankaReachPPORunnerCfg",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
##
# Inverse Kinematics - Relative Pose Control
##
gym.register(
id="Isaac-Reach-Franka-IK-Rel-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_rel_env_cfg.FrankaReachEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_cfg:FrankaReachPPORunnerCfg",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
gym.register(
id="Isaac-Reach-Franka-IK-Rel-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_rel_env_cfg.FrankaReachEnvCfg_PLAY,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_cfg:FrankaReachPPORunnerCfg",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
| 3,205 | Python | 31.714285 | 90 | 0.64337 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/franka/joint_pos_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import math
from omni.isaac.orbit.utils import configclass
import omni.isaac.orbit_tasks.manipulation.reach.mdp as mdp
from omni.isaac.orbit_tasks.manipulation.reach.reach_env_cfg import ReachEnvCfg
##
# Pre-defined configs
##
from omni.isaac.orbit_assets import FRANKA_PANDA_CFG # isort: skip
##
# Environment configuration
##
@configclass
class FrankaReachEnvCfg(ReachEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# switch robot to franka
self.scene.robot = FRANKA_PANDA_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# override rewards
self.rewards.end_effector_position_tracking.params["asset_cfg"].body_names = ["panda_hand"]
self.rewards.end_effector_orientation_tracking.params["asset_cfg"].body_names = ["panda_hand"]
# override actions
self.actions.arm_action = mdp.JointPositionActionCfg(
asset_name="robot", joint_names=["panda_joint.*"], scale=0.5, use_default_offset=True
)
# override command generator body
# end-effector is along z-direction
self.commands.ee_pose.body_name = "panda_hand"
self.commands.ee_pose.ranges.pitch = (math.pi, math.pi)
@configclass
class FrankaReachEnvCfg_PLAY(FrankaReachEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# disable randomization for play
self.observations.policy.enable_corruption = False
| 1,754 | Python | 29.789473 | 102 | 0.676739 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/ur_10/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, joint_pos_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Reach-UR10-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": joint_pos_env_cfg.UR10ReachEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UR10ReachPPORunnerCfg",
},
)
gym.register(
id="Isaac-Reach-UR10-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": joint_pos_env_cfg.UR10ReachEnvCfg_PLAY,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UR10ReachPPORunnerCfg",
},
)
| 1,008 | Python | 27.828571 | 92 | 0.660714 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/reach/config/ur_10/joint_pos_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import math
from omni.isaac.orbit.utils import configclass
import omni.isaac.orbit_tasks.manipulation.reach.mdp as mdp
from omni.isaac.orbit_tasks.manipulation.reach.reach_env_cfg import ReachEnvCfg
##
# Pre-defined configs
##
from omni.isaac.orbit_assets import UR10_CFG # isort: skip
##
# Environment configuration
##
@configclass
class UR10ReachEnvCfg(ReachEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# switch robot to ur10
self.scene.robot = UR10_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# override events
self.events.reset_robot_joints.params["position_range"] = (0.75, 1.25)
# override rewards
self.rewards.end_effector_position_tracking.params["asset_cfg"].body_names = ["ee_link"]
self.rewards.end_effector_orientation_tracking.params["asset_cfg"].body_names = ["ee_link"]
# override actions
self.actions.arm_action = mdp.JointPositionActionCfg(
asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True
)
# override command generator body
# end-effector is along x-direction
self.commands.ee_pose.body_name = "ee_link"
self.commands.ee_pose.ranges.pitch = (math.pi / 2, math.pi / 2)
@configclass
class UR10ReachEnvCfg_PLAY(UR10ReachEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# disable randomization for play
self.observations.policy.enable_corruption = False
| 1,823 | Python | 29.915254 | 99 | 0.665387 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/cabinet/cabinet_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2022-2023, The ORBIT Project Developers.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from dataclasses import MISSING
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators.actuator_cfg import ImplicitActuatorCfg
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import EventTermCfg as EventTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.sensors import FrameTransformerCfg
from omni.isaac.orbit.sensors.frame_transformer import OffsetCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
from . import mdp
##
# Pre-defined configs
##
from omni.isaac.orbit.markers.config import FRAME_MARKER_CFG # isort: skip
FRAME_MARKER_SMALL_CFG = FRAME_MARKER_CFG.copy()
FRAME_MARKER_SMALL_CFG.markers["frame"].scale = (0.10, 0.10, 0.10)
##
# Scene definition
##
@configclass
class CabinetSceneCfg(InteractiveSceneCfg):
"""Configuration for the cabinet scene with a robot and a cabinet.
This is the abstract base implementation, the exact scene is defined in the derived classes
which need to set the robot and end-effector frames
"""
# robots, Will be populated by agent env cfg
robot: ArticulationCfg = MISSING
# End-effector, Will be populated by agent env cfg
ee_frame: FrameTransformerCfg = MISSING
cabinet = ArticulationCfg(
prim_path="{ENV_REGEX_NS}/Cabinet",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Sektion_Cabinet/sektion_cabinet_instanceable.usd",
activate_contact_sensors=False,
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.8, 0, 0.4),
rot=(0.0, 0.0, 0.0, 1.0),
joint_pos={
"door_left_joint": 0.0,
"door_right_joint": 0.0,
"drawer_bottom_joint": 0.0,
"drawer_top_joint": 0.0,
},
),
actuators={
"drawers": ImplicitActuatorCfg(
joint_names_expr=["drawer_top_joint", "drawer_bottom_joint"],
effort_limit=87.0,
velocity_limit=100.0,
stiffness=10.0,
damping=1.0,
),
"doors": ImplicitActuatorCfg(
joint_names_expr=["door_left_joint", "door_right_joint"],
effort_limit=87.0,
velocity_limit=100.0,
stiffness=10.0,
damping=2.5,
),
},
)
# Frame definitions for the cabinet.
cabinet_frame = FrameTransformerCfg(
prim_path="{ENV_REGEX_NS}/Cabinet/sektion",
debug_vis=True,
visualizer_cfg=FRAME_MARKER_SMALL_CFG.replace(prim_path="/Visuals/CabinetFrameTransformer"),
target_frames=[
FrameTransformerCfg.FrameCfg(
prim_path="{ENV_REGEX_NS}/Cabinet/drawer_handle_top",
name="drawer_handle_top",
offset=OffsetCfg(
pos=(0.305, 0.0, 0.01),
rot=(0.5, 0.5, -0.5, -0.5), # align with end-effector frame
),
),
],
)
# plane
plane = AssetBaseCfg(
prim_path="/World/GroundPlane",
init_state=AssetBaseCfg.InitialStateCfg(),
spawn=sim_utils.GroundPlaneCfg(),
collision_group=-1,
)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DomeLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
null_command = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
body_joint_pos: mdp.JointPositionActionCfg = MISSING
finger_joint_pos: mdp.BinaryJointPositionActionCfg = MISSING
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
joint_pos = ObsTerm(func=mdp.joint_pos_rel)
joint_vel = ObsTerm(func=mdp.joint_vel_rel)
cabinet_joint_pos = ObsTerm(
func=mdp.joint_pos_rel,
params={"asset_cfg": SceneEntityCfg("cabinet", joint_names=["drawer_top_joint"])},
)
cabinet_joint_vel = ObsTerm(
func=mdp.joint_vel_rel,
params={"asset_cfg": SceneEntityCfg("cabinet", joint_names=["drawer_top_joint"])},
)
rel_ee_drawer_distance = ObsTerm(func=mdp.rel_ee_drawer_distance)
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = True
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
robot_physics_material = EventTerm(
func=mdp.randomize_rigid_body_material,
mode="startup",
params={
"asset_cfg": SceneEntityCfg("robot", body_names=".*"),
"static_friction_range": (0.8, 1.25),
"dynamic_friction_range": (0.8, 1.25),
"restitution_range": (0.0, 0.0),
"num_buckets": 16,
},
)
cabinet_physics_material = EventTerm(
func=mdp.randomize_rigid_body_material,
mode="startup",
params={
"asset_cfg": SceneEntityCfg("cabinet", body_names="drawer_handle_top"),
"static_friction_range": (1.0, 1.25),
"dynamic_friction_range": (1.25, 1.5),
"restitution_range": (0.0, 0.0),
"num_buckets": 16,
},
)
reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset")
reset_robot_joints = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"position_range": (-0.1, 0.1),
"velocity_range": (0.0, 0.0),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# 1. Approach the handle
approach_ee_handle = RewTerm(func=mdp.approach_ee_handle, weight=2.0, params={"threshold": 0.2})
align_ee_handle = RewTerm(func=mdp.align_ee_handle, weight=0.5)
# 2. Grasp the handle
approach_gripper_handle = RewTerm(func=mdp.approach_gripper_handle, weight=5.0, params={"offset": MISSING})
align_grasp_around_handle = RewTerm(func=mdp.align_grasp_around_handle, weight=0.125)
grasp_handle = RewTerm(
func=mdp.grasp_handle,
weight=0.5,
params={
"threshold": 0.03,
"open_joint_pos": MISSING,
"asset_cfg": SceneEntityCfg("robot", joint_names=MISSING),
},
)
# 3. Open the drawer
open_drawer_bonus = RewTerm(
func=mdp.open_drawer_bonus,
weight=7.5,
params={"asset_cfg": SceneEntityCfg("cabinet", joint_names=["drawer_top_joint"])},
)
multi_stage_open_drawer = RewTerm(
func=mdp.multi_stage_open_drawer,
weight=1.0,
params={"asset_cfg": SceneEntityCfg("cabinet", joint_names=["drawer_top_joint"])},
)
# 4. Penalize actions for cosmetic reasons
action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-1e-2)
joint_vel = RewTerm(func=mdp.joint_vel_l2, weight=-0.0001)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
time_out = DoneTerm(func=mdp.time_out, time_out=True)
##
# Environment configuration
##
@configclass
class CabinetEnvCfg(RLTaskEnvCfg):
"""Configuration for the cabinet environment."""
# Scene settings
scene: CabinetSceneCfg = CabinetSceneCfg(num_envs=4096, env_spacing=2.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
events: EventCfg = EventCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 1
self.episode_length_s = 8.0
self.viewer.eye = (-2.0, 2.0, 2.0)
self.viewer.lookat = (0.8, 0.0, 0.5)
# simulation settings
self.sim.dt = 1 / 60 # 60Hz
self.sim.physx.bounce_threshold_velocity = 0.2
self.sim.physx.bounce_threshold_velocity = 0.01
self.sim.physx.friction_correlation_distance = 0.00625
| 9,095 | Python | 30.044368 | 111 | 0.625069 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/cabinet/mdp/rewards.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.utils.math import matrix_from_quat
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def approach_ee_handle(env: RLTaskEnv, threshold: float) -> torch.Tensor:
r"""Reward the robot for reaching the drawer handle using inverse-square law.
It uses a piecewise function to reward the robot for reaching the handle.
.. math::
reward = \begin{cases}
2 * (1 / (1 + distance^2))^2 & \text{if } distance \leq threshold \\
(1 / (1 + distance^2))^2 & \text{otherwise}
\end{cases}
"""
ee_tcp_pos = env.scene["ee_frame"].data.target_pos_w[..., 0, :]
handle_pos = env.scene["cabinet_frame"].data.target_pos_w[..., 0, :]
# Compute the distance of the end-effector to the handle
distance = torch.norm(handle_pos - ee_tcp_pos, dim=-1, p=2)
# Reward the robot for reaching the handle
reward = 1.0 / (1.0 + distance**2)
reward = torch.pow(reward, 2)
return torch.where(distance <= threshold, 2 * reward, reward)
def align_ee_handle(env: RLTaskEnv) -> torch.Tensor:
"""Reward for aligning the end-effector with the handle.
The reward is based on the alignment of the gripper with the handle. It is computed as follows:
.. math::
reward = 0.5 * (align_z^2 + align_x^2)
where :math:`align_z` is the dot product of the z direction of the gripper and the -x direction of the handle
and :math:`align_x` is the dot product of the x direction of the gripper and the -y direction of the handle.
"""
ee_tcp_quat = env.scene["ee_frame"].data.target_quat_w[..., 0, :]
handle_quat = env.scene["cabinet_frame"].data.target_quat_w[..., 0, :]
ee_tcp_rot_mat = matrix_from_quat(ee_tcp_quat)
handle_mat = matrix_from_quat(handle_quat)
# get current x and y direction of the handle
handle_x, handle_y = handle_mat[..., 0], handle_mat[..., 1]
# get current x and z direction of the gripper
ee_tcp_x, ee_tcp_z = ee_tcp_rot_mat[..., 0], ee_tcp_rot_mat[..., 2]
# make sure gripper aligns with the handle
# in this case, the z direction of the gripper should be close to the -x direction of the handle
# and the x direction of the gripper should be close to the -y direction of the handle
# dot product of z and x should be large
align_z = torch.bmm(ee_tcp_z.unsqueeze(1), -handle_x.unsqueeze(-1)).squeeze(-1).squeeze(-1)
align_x = torch.bmm(ee_tcp_x.unsqueeze(1), -handle_y.unsqueeze(-1)).squeeze(-1).squeeze(-1)
return 0.5 * (torch.sign(align_z) * align_z**2 + torch.sign(align_x) * align_x**2)
def align_grasp_around_handle(env: RLTaskEnv) -> torch.Tensor:
"""Bonus for correct hand orientation around the handle.
The correct hand orientation is when the left finger is above the handle and the right finger is below the handle.
"""
# Target object position: (num_envs, 3)
handle_pos = env.scene["cabinet_frame"].data.target_pos_w[..., 0, :]
# Fingertips position: (num_envs, n_fingertips, 3)
ee_fingertips_w = env.scene["ee_frame"].data.target_pos_w[..., 1:, :]
lfinger_pos = ee_fingertips_w[..., 0, :]
rfinger_pos = ee_fingertips_w[..., 1, :]
# Check if hand is in a graspable pose
is_graspable = (rfinger_pos[:, 2] < handle_pos[:, 2]) & (lfinger_pos[:, 2] > handle_pos[:, 2])
# bonus if left finger is above the drawer handle and right below
return is_graspable
def approach_gripper_handle(env: RLTaskEnv, offset: float = 0.04) -> torch.Tensor:
"""Reward the robot's gripper reaching the drawer handle with the right pose.
This function returns the distance of fingertips to the handle when the fingers are in a grasping orientation
(i.e., the left finger is above the handle and the right finger is below the handle). Otherwise, it returns zero.
"""
# Target object position: (num_envs, 3)
handle_pos = env.scene["cabinet_frame"].data.target_pos_w[..., 0, :]
# Fingertips position: (num_envs, n_fingertips, 3)
ee_fingertips_w = env.scene["ee_frame"].data.target_pos_w[..., 1:, :]
lfinger_pos = ee_fingertips_w[..., 0, :]
rfinger_pos = ee_fingertips_w[..., 1, :]
# Compute the distance of each finger from the handle
lfinger_dist = torch.abs(lfinger_pos[:, 2] - handle_pos[:, 2])
rfinger_dist = torch.abs(rfinger_pos[:, 2] - handle_pos[:, 2])
# Check if hand is in a graspable pose
is_graspable = (rfinger_pos[:, 2] < handle_pos[:, 2]) & (lfinger_pos[:, 2] > handle_pos[:, 2])
return is_graspable * ((offset - lfinger_dist) + (offset - rfinger_dist))
def grasp_handle(env: RLTaskEnv, threshold: float, open_joint_pos: float, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Reward for closing the fingers when being close to the handle.
The :attr:`threshold` is the distance from the handle at which the fingers should be closed.
The :attr:`open_joint_pos` is the joint position when the fingers are open.
Note:
It is assumed that zero joint position corresponds to the fingers being closed.
"""
ee_tcp_pos = env.scene["ee_frame"].data.target_pos_w[..., 0, :]
handle_pos = env.scene["cabinet_frame"].data.target_pos_w[..., 0, :]
gripper_joint_pos = env.scene[asset_cfg.name].data.joint_pos[:, asset_cfg.joint_ids]
distance = torch.norm(handle_pos - ee_tcp_pos, dim=-1, p=2)
is_close = distance <= threshold
return is_close * torch.sum(open_joint_pos - gripper_joint_pos, dim=-1)
def open_drawer_bonus(env: RLTaskEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Bonus for opening the drawer given by the joint position of the drawer.
The bonus is given when the drawer is open. If the grasp is around the handle, the bonus is doubled.
"""
drawer_pos = env.scene[asset_cfg.name].data.joint_pos[:, asset_cfg.joint_ids[0]]
is_graspable = align_grasp_around_handle(env).float()
return (is_graspable + 1.0) * drawer_pos
def multi_stage_open_drawer(env: RLTaskEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Multi-stage bonus for opening the drawer.
Depending on the drawer's position, the reward is given in three stages: easy, medium, and hard.
This helps the agent to learn to open the drawer in a controlled manner.
"""
drawer_pos = env.scene[asset_cfg.name].data.joint_pos[:, asset_cfg.joint_ids[0]]
is_graspable = align_grasp_around_handle(env).float()
open_easy = (drawer_pos > 0.01) * 0.5
open_medium = (drawer_pos > 0.2) * is_graspable
open_hard = (drawer_pos > 0.3) * is_graspable
return open_easy + open_medium + open_hard
| 6,848 | Python | 41.540372 | 118 | 0.665596 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/cabinet/mdp/observations.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import ArticulationData
from omni.isaac.orbit.sensors import FrameTransformerData
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def rel_ee_object_distance(env: RLTaskEnv) -> torch.Tensor:
"""The distance between the end-effector and the object."""
ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data
object_data: ArticulationData = env.scene["object"].data
return object_data.root_pos_w - ee_tf_data.target_pos_w[..., 0, :]
def rel_ee_drawer_distance(env: RLTaskEnv) -> torch.Tensor:
"""The distance between the end-effector and the object."""
ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data
cabinet_tf_data: FrameTransformerData = env.scene["cabinet_frame"].data
return cabinet_tf_data.target_pos_w[..., 0, :] - ee_tf_data.target_pos_w[..., 0, :]
def fingertips_pos(env: RLTaskEnv) -> torch.Tensor:
"""The position of the fingertips relative to the environment origins."""
ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data
fingertips_pos = ee_tf_data.target_pos_w[..., 1:, :] - env.scene.env_origins.unsqueeze(1)
return fingertips_pos.view(env.num_envs, -1)
def ee_pos(env: RLTaskEnv) -> torch.Tensor:
"""The position of the end-effector relative to the environment origins."""
ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data
ee_pos = ee_tf_data.target_pos_w[..., 0, :] - env.scene.env_origins
return ee_pos
def ee_quat(env: RLTaskEnv) -> torch.Tensor:
"""The orientation of the end-effector in the environment frame."""
ee_tf_data: FrameTransformerData = env.scene["ee_frame"].data
ee_quat = ee_tf_data.target_quat_w[..., 0, :]
# make first element of quaternion positive
ee_quat[ee_quat[:, 0] < 0] *= -1
return ee_quat
| 2,031 | Python | 34.034482 | 93 | 0.696701 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/cabinet/config/franka/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, ik_abs_env_cfg, ik_rel_env_cfg, joint_pos_env_cfg
##
# Register Gym environments.
##
##
# Joint Position Control
##
gym.register(
id="Isaac-Open-Drawer-Franka-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": joint_pos_env_cfg.FrankaCabinetEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CabinetPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
},
disable_env_checker=True,
)
gym.register(
id="Isaac-Open-Drawer-Franka-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": joint_pos_env_cfg.FrankaCabinetEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CabinetPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
},
disable_env_checker=True,
)
##
# Inverse Kinematics - Absolute Pose Control
##
gym.register(
id="Isaac-Open-Drawer-Franka-IK-Abs-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_abs_env_cfg.FrankaCabinetEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CabinetPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
},
disable_env_checker=True,
)
gym.register(
id="Isaac-Open-Drawer-Franka-IK-Abs-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_abs_env_cfg.FrankaCabinetEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CabinetPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
},
disable_env_checker=True,
)
##
# Inverse Kinematics - Relative Pose Control
##
gym.register(
id="Isaac-Open-Drawer-Franka-IK-Rel-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_rel_env_cfg.FrankaCabinetEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CabinetPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
},
disable_env_checker=True,
)
gym.register(
id="Isaac-Open-Drawer-Franka-IK-Rel-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_rel_env_cfg.FrankaCabinetEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CabinetPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
},
disable_env_checker=True,
)
| 2,714 | Python | 28.193548 | 79 | 0.662491 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/cabinet/config/franka/joint_pos_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.sensors import FrameTransformerCfg
from omni.isaac.orbit.sensors.frame_transformer.frame_transformer_cfg import OffsetCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_tasks.manipulation.cabinet import mdp
from omni.isaac.orbit_tasks.manipulation.cabinet.cabinet_env_cfg import CabinetEnvCfg
##
# Pre-defined configs
##
from omni.isaac.orbit_assets.franka import FRANKA_PANDA_CFG # isort: skip
from omni.isaac.orbit_tasks.manipulation.cabinet.cabinet_env_cfg import FRAME_MARKER_SMALL_CFG # isort: skip
@configclass
class FrankaCabinetEnvCfg(CabinetEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# Set franka as robot
self.scene.robot = FRANKA_PANDA_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# Set Actions for the specific robot type (franka)
self.actions.body_joint_pos = mdp.JointPositionActionCfg(
asset_name="robot",
joint_names=["panda_joint.*"],
scale=1.0,
use_default_offset=True,
)
self.actions.finger_joint_pos = mdp.BinaryJointPositionActionCfg(
asset_name="robot",
joint_names=["panda_finger.*"],
open_command_expr={"panda_finger_.*": 0.04},
close_command_expr={"panda_finger_.*": 0.0},
)
# Listens to the required transforms
# IMPORTANT: The order of the frames in the list is important. The first frame is the tool center point (TCP)
# the other frames are the fingers
self.scene.ee_frame = FrameTransformerCfg(
prim_path="{ENV_REGEX_NS}/Robot/panda_link0",
debug_vis=False,
visualizer_cfg=FRAME_MARKER_SMALL_CFG.replace(prim_path="/Visuals/EndEffectorFrameTransformer"),
target_frames=[
FrameTransformerCfg.FrameCfg(
prim_path="{ENV_REGEX_NS}/Robot/panda_hand",
name="ee_tcp",
offset=OffsetCfg(
pos=(0.0, 0.0, 0.1034),
),
),
FrameTransformerCfg.FrameCfg(
prim_path="{ENV_REGEX_NS}/Robot/panda_leftfinger",
name="tool_leftfinger",
offset=OffsetCfg(
pos=(0.0, 0.0, 0.046),
),
),
FrameTransformerCfg.FrameCfg(
prim_path="{ENV_REGEX_NS}/Robot/panda_rightfinger",
name="tool_rightfinger",
offset=OffsetCfg(
pos=(0.0, 0.0, 0.046),
),
),
],
)
# override rewards
self.rewards.approach_gripper_handle.params["offset"] = 0.04
self.rewards.grasp_handle.params["open_joint_pos"] = 0.04
self.rewards.grasp_handle.params["asset_cfg"].joint_names = ["panda_finger_.*"]
@configclass
class FrankaCabinetEnvCfg_PLAY(FrankaCabinetEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# disable randomization for play
self.observations.policy.enable_corruption = False
| 3,464 | Python | 37.076923 | 117 | 0.58776 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/lift_env_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
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm
from omni.isaac.orbit.managers import EventTermCfg as EventTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.sensors.frame_transformer.frame_transformer_cfg import FrameTransformerCfg
from omni.isaac.orbit.sim.spawners.from_files.from_files_cfg import GroundPlaneCfg, UsdFileCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
from . import mdp
##
# Scene definition
##
@configclass
class ObjectTableSceneCfg(InteractiveSceneCfg):
"""Configuration for the lift scene with a robot and a object.
This is the abstract base implementation, the exact scene is defined in the derived classes
which need to set the target object, robot and end-effector frames
"""
# robots: will be populated by agent env cfg
robot: ArticulationCfg = MISSING
# end-effector sensor: will be populated by agent env cfg
ee_frame: FrameTransformerCfg = MISSING
# target object: will be populated by agent env cfg
object: RigidObjectCfg = MISSING
# Table
table = AssetBaseCfg(
prim_path="{ENV_REGEX_NS}/Table",
init_state=AssetBaseCfg.InitialStateCfg(pos=[0.5, 0, 0], rot=[0.707, 0, 0, 0.707]),
spawn=UsdFileCfg(usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Mounts/SeattleLabTable/table_instanceable.usd"),
)
# plane
plane = AssetBaseCfg(
prim_path="/World/GroundPlane",
init_state=AssetBaseCfg.InitialStateCfg(pos=[0, 0, -1.05]),
spawn=GroundPlaneCfg(),
)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DomeLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
object_pose = mdp.UniformPoseCommandCfg(
asset_name="robot",
body_name=MISSING, # will be set by agent env cfg
resampling_time_range=(5.0, 5.0),
debug_vis=True,
ranges=mdp.UniformPoseCommandCfg.Ranges(
pos_x=(0.4, 0.6), pos_y=(-0.25, 0.25), pos_z=(0.25, 0.5), roll=(0.0, 0.0), pitch=(0.0, 0.0), yaw=(0.0, 0.0)
),
)
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
# will be set by agent env cfg
body_joint_pos: mdp.JointPositionActionCfg = MISSING
finger_joint_pos: mdp.BinaryJointPositionActionCfg = MISSING
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
joint_pos = ObsTerm(func=mdp.joint_pos_rel)
joint_vel = ObsTerm(func=mdp.joint_vel_rel)
object_position = ObsTerm(func=mdp.object_position_in_robot_root_frame)
target_object_position = ObsTerm(func=mdp.generated_commands, params={"command_name": "object_pose"})
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = True
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
reset_all = EventTerm(func=mdp.reset_scene_to_default, mode="reset")
reset_object_position = EventTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={
"pose_range": {"x": (-0.1, 0.1), "y": (-0.25, 0.25), "z": (0.0, 0.0)},
"velocity_range": {},
"asset_cfg": SceneEntityCfg("object", body_names="Object"),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
reaching_object = RewTerm(func=mdp.object_ee_distance, params={"std": 0.1}, weight=1.0)
lifting_object = RewTerm(func=mdp.object_is_lifted, params={"minimal_height": 0.06}, weight=15.0)
object_goal_tracking = RewTerm(
func=mdp.object_goal_distance,
params={"std": 0.3, "minimal_height": 0.06, "command_name": "object_pose"},
weight=16.0,
)
object_goal_tracking_fine_grained = RewTerm(
func=mdp.object_goal_distance,
params={"std": 0.05, "minimal_height": 0.06, "command_name": "object_pose"},
weight=5.0,
)
# action penalty
action_rate = RewTerm(func=mdp.action_rate_l2, weight=-1e-3)
joint_vel = RewTerm(
func=mdp.joint_vel_l2,
weight=-1e-4,
params={"asset_cfg": SceneEntityCfg("robot")},
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
time_out = DoneTerm(func=mdp.time_out, time_out=True)
object_dropping = DoneTerm(
func=mdp.base_height, params={"minimum_height": -0.05, "asset_cfg": SceneEntityCfg("object")}
)
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
action_rate = CurrTerm(
func=mdp.modify_reward_weight, params={"term_name": "action_rate", "weight": -1e-1, "num_steps": 10000}
)
joint_vel = CurrTerm(
func=mdp.modify_reward_weight, params={"term_name": "joint_vel", "weight": -1e-1, "num_steps": 10000}
)
##
# Environment configuration
##
@configclass
class LiftEnvCfg(RLTaskEnvCfg):
"""Configuration for the lifting environment."""
# Scene settings
scene: ObjectTableSceneCfg = ObjectTableSceneCfg(num_envs=4096, env_spacing=2.5)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
events: EventCfg = EventCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 5.0
# simulation settings
self.sim.dt = 0.01 # 100Hz
self.sim.physx.bounce_threshold_velocity = 0.2
self.sim.physx.bounce_threshold_velocity = 0.01
self.sim.physx.gpu_found_lost_aggregate_pairs_capacity = 1024 * 1024 * 4
self.sim.physx.gpu_total_aggregate_pairs_capacity = 16 * 1024
self.sim.physx.friction_correlation_distance = 0.00625
| 6,999 | Python | 30.111111 | 119 | 0.673096 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/mdp/rewards.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import RigidObject
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.sensors import FrameTransformer
from omni.isaac.orbit.utils.math import combine_frame_transforms
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def object_is_lifted(
env: RLTaskEnv, minimal_height: float, object_cfg: SceneEntityCfg = SceneEntityCfg("object")
) -> torch.Tensor:
"""Reward the agent for lifting the object above the minimal height."""
object: RigidObject = env.scene[object_cfg.name]
return torch.where(object.data.root_pos_w[:, 2] > minimal_height, 1.0, 0.0)
def object_ee_distance(
env: RLTaskEnv,
std: float,
object_cfg: SceneEntityCfg = SceneEntityCfg("object"),
ee_frame_cfg: SceneEntityCfg = SceneEntityCfg("ee_frame"),
) -> torch.Tensor:
"""Reward the agent for reaching the object using tanh-kernel."""
# extract the used quantities (to enable type-hinting)
object: RigidObject = env.scene[object_cfg.name]
ee_frame: FrameTransformer = env.scene[ee_frame_cfg.name]
# Target object position: (num_envs, 3)
cube_pos_w = object.data.root_pos_w
# End-effector position: (num_envs, 3)
ee_w = ee_frame.data.target_pos_w[..., 0, :]
# Distance of the end-effector to the object: (num_envs,)
object_ee_distance = torch.norm(cube_pos_w - ee_w, dim=1)
return 1 - torch.tanh(object_ee_distance / std)
def object_goal_distance(
env: RLTaskEnv,
std: float,
minimal_height: float,
command_name: str,
robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
object_cfg: SceneEntityCfg = SceneEntityCfg("object"),
) -> torch.Tensor:
"""Reward the agent for tracking the goal pose using tanh-kernel."""
# extract the used quantities (to enable type-hinting)
robot: RigidObject = env.scene[robot_cfg.name]
object: RigidObject = env.scene[object_cfg.name]
command = env.command_manager.get_command(command_name)
# compute the desired position in the world frame
des_pos_b = command[:, :3]
des_pos_w, _ = combine_frame_transforms(robot.data.root_state_w[:, :3], robot.data.root_state_w[:, 3:7], des_pos_b)
# distance of the end-effector to the object: (num_envs,)
distance = torch.norm(des_pos_w - object.data.root_pos_w[:, :3], dim=1)
# rewarded if the object is lifted above the threshold
return (object.data.root_pos_w[:, 2] > minimal_height) * (1 - torch.tanh(distance / std))
| 2,683 | Python | 38.470588 | 119 | 0.701826 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/mdp/terminations.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Common functions that can be used to activate certain terminations for the lift task.
The functions can be passed to the :class:`omni.isaac.orbit.managers.TerminationTermCfg` object to enable
the termination introduced by the function.
"""
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import RigidObject
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.utils.math import combine_frame_transforms
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def object_reached_goal(
env: RLTaskEnv,
command_name: str = "object_pose",
threshold: float = 0.02,
robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
object_cfg: SceneEntityCfg = SceneEntityCfg("object"),
) -> torch.Tensor:
"""Termination condition for the object reaching the goal position.
Args:
env: The environment.
command_name: The name of the command that is used to control the object.
threshold: The threshold for the object to reach the goal position. Defaults to 0.02.
robot_cfg: The robot configuration. Defaults to SceneEntityCfg("robot").
object_cfg: The object configuration. Defaults to SceneEntityCfg("object").
"""
# extract the used quantities (to enable type-hinting)
robot: RigidObject = env.scene[robot_cfg.name]
object: RigidObject = env.scene[object_cfg.name]
command = env.command_manager.get_command(command_name)
# compute the desired position in the world frame
des_pos_b = command[:, :3]
des_pos_w, _ = combine_frame_transforms(robot.data.root_state_w[:, :3], robot.data.root_state_w[:, 3:7], des_pos_b)
# distance of the end-effector to the object: (num_envs,)
distance = torch.norm(des_pos_w - object.data.root_pos_w[:, :3], dim=1)
# rewarded if the object is lifted above the threshold
return distance < threshold
| 2,055 | Python | 37.074073 | 119 | 0.722141 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/mdp/observations.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.orbit.assets import RigidObject
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.utils.math import subtract_frame_transforms
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def object_position_in_robot_root_frame(
env: RLTaskEnv,
robot_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
object_cfg: SceneEntityCfg = SceneEntityCfg("object"),
) -> torch.Tensor:
"""The position of the object in the robot's root frame."""
robot: RigidObject = env.scene[robot_cfg.name]
object: RigidObject = env.scene[object_cfg.name]
object_pos_w = object.data.root_pos_w[:, :3]
object_pos_b, _ = subtract_frame_transforms(
robot.data.root_state_w[:, :3], robot.data.root_state_w[:, 3:7], object_pos_w
)
return object_pos_b
| 1,020 | Python | 30.906249 | 85 | 0.721569 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
import os
from . import agents, ik_abs_env_cfg, ik_rel_env_cfg, joint_pos_env_cfg
##
# Register Gym environments.
##
##
# Joint Position Control
##
gym.register(
id="Isaac-Lift-Cube-Franka-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": joint_pos_env_cfg.FrankaCubeLiftEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.LiftCubePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
gym.register(
id="Isaac-Lift-Cube-Franka-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": joint_pos_env_cfg.FrankaCubeLiftEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.LiftCubePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
##
# Inverse Kinematics - Absolute Pose Control
##
gym.register(
id="Isaac-Lift-Cube-Franka-IK-Abs-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_abs_env_cfg.FrankaCubeLiftEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.LiftCubePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
gym.register(
id="Isaac-Lift-Cube-Franka-IK-Abs-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_abs_env_cfg.FrankaCubeLiftEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.LiftCubePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
##
# Inverse Kinematics - Relative Pose Control
##
gym.register(
id="Isaac-Lift-Cube-Franka-IK-Rel-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_rel_env_cfg.FrankaCubeLiftEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.LiftCubePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"robomimic_bc_cfg_entry_point": os.path.join(agents.__path__[0], "robomimic/bc.json"),
},
disable_env_checker=True,
)
gym.register(
id="Isaac-Lift-Cube-Franka-IK-Rel-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
kwargs={
"env_cfg_entry_point": ik_rel_env_cfg.FrankaCubeLiftEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.LiftCubePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
disable_env_checker=True,
)
| 2,769 | Python | 28.784946 | 94 | 0.660888 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/manipulation/lift/config/franka/joint_pos_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.assets import RigidObjectCfg
from omni.isaac.orbit.sensors import FrameTransformerCfg
from omni.isaac.orbit.sensors.frame_transformer.frame_transformer_cfg import OffsetCfg
from omni.isaac.orbit.sim.schemas.schemas_cfg import RigidBodyPropertiesCfg
from omni.isaac.orbit.sim.spawners.from_files.from_files_cfg import UsdFileCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_NUCLEUS_DIR
from omni.isaac.orbit_tasks.manipulation.lift import mdp
from omni.isaac.orbit_tasks.manipulation.lift.lift_env_cfg import LiftEnvCfg
##
# Pre-defined configs
##
from omni.isaac.orbit.markers.config import FRAME_MARKER_CFG # isort: skip
from omni.isaac.orbit_assets.franka import FRANKA_PANDA_CFG # isort: skip
@configclass
class FrankaCubeLiftEnvCfg(LiftEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# Set Franka as robot
self.scene.robot = FRANKA_PANDA_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# Set actions for the specific robot type (franka)
self.actions.body_joint_pos = mdp.JointPositionActionCfg(
asset_name="robot", joint_names=["panda_joint.*"], scale=0.5, use_default_offset=True
)
self.actions.finger_joint_pos = mdp.BinaryJointPositionActionCfg(
asset_name="robot",
joint_names=["panda_finger.*"],
open_command_expr={"panda_finger_.*": 0.04},
close_command_expr={"panda_finger_.*": 0.0},
)
# Set the body name for the end effector
self.commands.object_pose.body_name = "panda_hand"
# Set Cube as object
self.scene.object = RigidObjectCfg(
prim_path="{ENV_REGEX_NS}/Object",
init_state=RigidObjectCfg.InitialStateCfg(pos=[0.5, 0, 0.055], rot=[1, 0, 0, 0]),
spawn=UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd",
scale=(0.8, 0.8, 0.8),
rigid_props=RigidBodyPropertiesCfg(
solver_position_iteration_count=16,
solver_velocity_iteration_count=1,
max_angular_velocity=1000.0,
max_linear_velocity=1000.0,
max_depenetration_velocity=5.0,
disable_gravity=False,
),
),
)
# Listens to the required transforms
marker_cfg = FRAME_MARKER_CFG.copy()
marker_cfg.markers["frame"].scale = (0.1, 0.1, 0.1)
marker_cfg.prim_path = "/Visuals/FrameTransformer"
self.scene.ee_frame = FrameTransformerCfg(
prim_path="{ENV_REGEX_NS}/Robot/panda_link0",
debug_vis=False,
visualizer_cfg=marker_cfg,
target_frames=[
FrameTransformerCfg.FrameCfg(
prim_path="{ENV_REGEX_NS}/Robot/panda_hand",
name="end_effector",
offset=OffsetCfg(
pos=[0.0, 0.0, 0.1034],
),
),
],
)
@configclass
class FrankaCubeLiftEnvCfg_PLAY(FrankaCubeLiftEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# disable randomization for play
self.observations.policy.enable_corruption = False
| 3,644 | Python | 37.776595 | 97 | 0.613886 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go1/rough_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_tasks.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg
##
# Pre-defined configs
##
from omni.isaac.orbit_assets.unitree import UNITREE_GO1_CFG # isort: skip
@configclass
class UnitreeGo1RoughEnvCfg(LocomotionVelocityRoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
self.scene.robot = UNITREE_GO1_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/trunk"
# scale down the terrains because the robot is small
self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1)
self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06)
self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01
# reduce action scale
self.actions.joint_pos.scale = 0.25
# event
self.events.push_robot = None
self.events.add_base_mass.params["mass_range"] = (-1.0, 3.0)
self.events.add_base_mass.params["asset_cfg"].body_names = "trunk"
self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk"
self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0)
self.events.reset_base.params = {
"pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)},
"velocity_range": {
"x": (0.0, 0.0),
"y": (0.0, 0.0),
"z": (0.0, 0.0),
"roll": (0.0, 0.0),
"pitch": (0.0, 0.0),
"yaw": (0.0, 0.0),
},
}
# rewards
self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot"
self.rewards.feet_air_time.weight = 0.01
self.rewards.undesired_contacts = None
self.rewards.dof_torques_l2.weight = -0.0002
self.rewards.track_lin_vel_xy_exp.weight = 1.5
self.rewards.track_ang_vel_z_exp.weight = 0.75
self.rewards.dof_acc_l2.weight = -2.5e-7
# terminations
self.terminations.base_contact.params["sensor_cfg"].body_names = "trunk"
@configclass
class UnitreeGo1RoughEnvCfg_PLAY(UnitreeGo1RoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# spawn the robot randomly in the grid (instead of their terrain levels)
self.scene.terrain.max_init_terrain_level = None
# reduce the number of terrains to save memory
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.num_rows = 5
self.scene.terrain.terrain_generator.num_cols = 5
self.scene.terrain.terrain_generator.curriculum = False
# disable randomization for play
self.observations.policy.enable_corruption = False
# remove random pushing event
self.events.base_external_force_torque = None
self.events.push_robot = None
| 3,351 | Python | 38.435294 | 101 | 0.621904 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go1/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, flat_env_cfg, rough_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Velocity-Flat-Unitree-Go1-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.UnitreeGo1FlatEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeGo1FlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Flat-Unitree-Go1-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.UnitreeGo1FlatEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeGo1FlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Unitree-Go1-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.UnitreeGo1RoughEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeGo1RoughPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Unitree-Go1-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.UnitreeGo1RoughEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeGo1RoughPPORunnerCfg,
},
)
| 1,498 | Python | 27.283018 | 80 | 0.690921 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/cassie/rough_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.utils import configclass
import omni.isaac.orbit_tasks.locomotion.velocity.mdp as mdp
from omni.isaac.orbit_tasks.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg, RewardsCfg
##
# Pre-defined configs
##
from omni.isaac.orbit_assets.cassie import CASSIE_CFG # isort: skip
@configclass
class CassieRewardsCfg(RewardsCfg):
termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0)
feet_air_time = RewTerm(
func=mdp.feet_air_time_positive_biped,
weight=2.5,
params={
"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*toe"),
"command_name": "base_velocity",
"threshold": 0.3,
},
)
joint_deviation_hip = RewTerm(
func=mdp.joint_deviation_l1,
weight=-0.2,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["hip_abduction_.*", "hip_rotation_.*"])},
)
joint_deviation_toes = RewTerm(
func=mdp.joint_deviation_l1,
weight=-0.2,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["toe_joint_.*"])},
)
# penalize toe joint limits
dof_pos_limits = RewTerm(
func=mdp.joint_pos_limits,
weight=-1.0,
params={"asset_cfg": SceneEntityCfg("robot", joint_names="toe_joint_.*")},
)
@configclass
class CassieRoughEnvCfg(LocomotionVelocityRoughEnvCfg):
"""Cassie rough environment configuration."""
rewards: CassieRewardsCfg = CassieRewardsCfg()
def __post_init__(self):
super().__post_init__()
# scene
self.scene.robot = CASSIE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/pelvis"
# actions
self.actions.joint_pos.scale = 0.5
# events
self.events.push_robot = None
self.events.add_base_mass = None
self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0)
self.events.base_external_force_torque.params["asset_cfg"].body_names = [".*pelvis"]
self.events.reset_base.params = {
"pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)},
"velocity_range": {
"x": (0.0, 0.0),
"y": (0.0, 0.0),
"z": (0.0, 0.0),
"roll": (0.0, 0.0),
"pitch": (0.0, 0.0),
"yaw": (0.0, 0.0),
},
}
# terminations
self.terminations.base_contact.params["sensor_cfg"].body_names = [".*pelvis"]
# rewards
self.rewards.undesired_contacts = None
self.rewards.dof_torques_l2.weight = -5.0e-6
self.rewards.track_lin_vel_xy_exp.weight = 2.0
self.rewards.track_ang_vel_z_exp.weight = 1.0
self.rewards.action_rate_l2.weight *= 1.5
self.rewards.dof_acc_l2.weight *= 1.5
@configclass
class CassieRoughEnvCfg_PLAY(CassieRoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# spawn the robot randomly in the grid (instead of their terrain levels)
self.scene.terrain.max_init_terrain_level = None
# reduce the number of terrains to save memory
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.num_rows = 5
self.scene.terrain.terrain_generator.num_cols = 5
self.scene.terrain.terrain_generator.curriculum = False
self.commands.base_velocity.ranges.lin_vel_x = (0.7, 1.0)
self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0)
self.commands.base_velocity.ranges.heading = (0.0, 0.0)
# disable randomization for play
self.observations.policy.enable_corruption = False
| 4,139 | Python | 35 | 113 | 0.614641 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/cassie/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, flat_env_cfg, rough_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Velocity-Flat-Cassie-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.CassieFlatEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CassieFlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Flat-Cassie-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.CassieFlatEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CassieFlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Cassie-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.CassieRoughEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CassieRoughPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Cassie-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.CassieRoughEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.CassieRoughPPORunnerCfg,
},
)
| 1,446 | Python | 26.301886 | 76 | 0.682573 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_b/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, flat_env_cfg, rough_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Velocity-Flat-Anymal-B-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.AnymalBFlatEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalBFlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Flat-Anymal-B-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.AnymalBFlatEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalBFlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Anymal-B-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.AnymalBRoughEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalBRoughPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Anymal-B-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.AnymalBRoughEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalBRoughPPORunnerCfg,
},
)
| 1,462 | Python | 26.603773 | 77 | 0.683311 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/anymal_c/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, flat_env_cfg, rough_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Velocity-Flat-Anymal-C-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.AnymalCFlatEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalCFlatPPORunnerCfg,
"skrl_cfg_entry_point": "omni.isaac.orbit_tasks.locomotion.velocity.anymal_c.agents:skrl_cfg.yaml",
},
)
gym.register(
id="Isaac-Velocity-Flat-Anymal-C-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.AnymalCFlatEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalCFlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Anymal-C-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.AnymalCRoughEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalCRoughPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Anymal-C-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.AnymalCRoughEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalCRoughPPORunnerCfg,
},
)
| 1,570 | Python | 28.092592 | 107 | 0.685987 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_go2/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, flat_env_cfg, rough_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Velocity-Flat-Unitree-Go2-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.UnitreeGo2FlatEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeGo2FlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Flat-Unitree-Go2-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.UnitreeGo2FlatEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeGo2FlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Unitree-Go2-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.UnitreeGo2RoughEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeGo2RoughPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Unitree-Go2-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.UnitreeGo2RoughEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeGo2RoughPPORunnerCfg,
},
)
| 1,498 | Python | 27.283018 | 80 | 0.690921 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/locomotion/velocity/config/unitree_a1/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, flat_env_cfg, rough_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Velocity-Flat-Unitree-A1-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.UnitreeA1FlatEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeA1FlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Flat-Unitree-A1-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.UnitreeA1FlatEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeA1FlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Unitree-A1-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.UnitreeA1RoughEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeA1RoughPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Unitree-A1-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.UnitreeA1RoughEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.UnitreeA1RoughPPORunnerCfg,
},
)
| 1,486 | Python | 27.056603 | 79 | 0.688425 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/utils/importer.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module with utility for importing all modules in a package recursively."""
from __future__ import annotations
import importlib
import pkgutil
import sys
def import_packages(package_name: str, blacklist_pkgs: list[str] = None):
"""Import all sub-packages in a package recursively.
It is easier to use this function to import all sub-packages in a package recursively
than to manually import each sub-package.
It replaces the need of the following code snippet on the top of each package's ``__init__.py`` file:
.. code-block:: python
import .locomotion.velocity
import .manipulation.reach
import .manipulation.lift
Args:
package_name: The package name.
blacklist_pkgs: The list of blacklisted packages to skip. Defaults to None,
which means no packages are blacklisted.
"""
# Default blacklist
if blacklist_pkgs is None:
blacklist_pkgs = []
# Import the package itself
package = importlib.import_module(package_name)
# Import all Python files
for _ in _walk_packages(package.__path__, package.__name__ + ".", blacklist_pkgs=blacklist_pkgs):
pass
def _walk_packages(
path: str | None = None,
prefix: str = "",
onerror: callable | None = None,
blacklist_pkgs: list[str] | None = None,
):
"""Yields ModuleInfo for all modules recursively on path, or, if path is None, all accessible modules.
Note:
This function is a modified version of the original ``pkgutil.walk_packages`` function. It adds
the `blacklist_pkgs` argument to skip blacklisted packages. Please refer to the original
``pkgutil.walk_packages`` function for more details.
"""
if blacklist_pkgs is None:
blacklist_pkgs = []
def seen(p, m={}):
if p in m:
return True
m[p] = True # noqa: R503
for info in pkgutil.iter_modules(path, prefix):
# check blacklisted
if any([black_pkg_name in info.name for black_pkg_name in blacklist_pkgs]):
continue
# yield the module info
yield info
if info.ispkg:
try:
__import__(info.name)
except Exception:
if onerror is not None:
onerror(info.name)
else:
raise
else:
path = getattr(sys.modules[info.name], "__path__", None) or []
# don't traverse path items we've seen before
path = [p for p in path if not seen(p)]
yield from _walk_packages(path, info.name + ".", onerror, blacklist_pkgs)
| 2,791 | Python | 30.727272 | 106 | 0.617341 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/utils/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package with utilities, data collectors and environment wrappers."""
from .importer import import_packages
from .parse_cfg import get_checkpoint_path, load_cfg_from_registry, parse_env_cfg
| 320 | Python | 31.099997 | 81 | 0.771875 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/utils/parse_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module with utilities for parsing and loading configurations."""
from __future__ import annotations
import gymnasium as gym
import importlib
import inspect
import os
import re
import yaml
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.utils import update_class_from_dict, update_dict
def load_cfg_from_registry(task_name: str, entry_point_key: str) -> dict | RLTaskEnvCfg:
"""Load default configuration given its entry point from the gym registry.
This function loads the configuration object from the gym registry for the given task name.
It supports both YAML and Python configuration files.
It expects the configuration to be registered in the gym registry as:
.. code-block:: python
gym.register(
id="My-Awesome-Task-v0",
...
kwargs={"env_entry_point_cfg": "path.to.config:ConfigClass"},
)
The parsed configuration object for above example can be obtained as:
.. code-block:: python
from omni.isaac.orbit_tasks.utils.parse_cfg import load_cfg_from_registry
cfg = load_cfg_from_registry("My-Awesome-Task-v0", "env_entry_point_cfg")
Args:
task_name: The name of the environment.
entry_point_key: The entry point key to resolve the configuration file.
Returns:
The parsed configuration object. This is either a dictionary or a class object.
Raises:
ValueError: If the entry point key is not available in the gym registry for the task.
"""
# obtain the configuration entry point
cfg_entry_point = gym.spec(task_name).kwargs.get(entry_point_key)
# check if entry point exists
if cfg_entry_point is None:
raise ValueError(
f"Could not find configuration for the environment: '{task_name}'."
f" Please check that the gym registry has the entry point: '{entry_point_key}'."
)
# parse the default config file
if isinstance(cfg_entry_point, str) and cfg_entry_point.endswith(".yaml"):
if os.path.exists(cfg_entry_point):
# absolute path for the config file
config_file = cfg_entry_point
else:
# resolve path to the module location
mod_name, file_name = cfg_entry_point.split(":")
mod_path = os.path.dirname(importlib.import_module(mod_name).__file__)
# obtain the configuration file path
config_file = os.path.join(mod_path, file_name)
# load the configuration
print(f"[INFO]: Parsing configuration from: {config_file}")
with open(config_file, encoding="utf-8") as f:
cfg = yaml.full_load(f)
else:
if callable(cfg_entry_point):
# resolve path to the module location
mod_path = inspect.getfile(cfg_entry_point)
# load the configuration
cfg_cls = cfg_entry_point()
elif isinstance(cfg_entry_point, str):
# resolve path to the module location
mod_name, attr_name = cfg_entry_point.split(":")
mod = importlib.import_module(mod_name)
cfg_cls = getattr(mod, attr_name)
else:
cfg_cls = cfg_entry_point
# load the configuration
print(f"[INFO]: Parsing configuration from: {cfg_entry_point}")
if callable(cfg_cls):
cfg = cfg_cls()
else:
cfg = cfg_cls
return cfg
def parse_env_cfg(
task_name: str, use_gpu: bool | None = None, num_envs: int | None = None, use_fabric: bool | None = None
) -> dict | RLTaskEnvCfg:
"""Parse configuration for an environment and override based on inputs.
Args:
task_name: The name of the environment.
use_gpu: Whether to use GPU/CPU pipeline. Defaults to None, in which case it is left unchanged.
num_envs: Number of environments to create. Defaults to None, in which case it is left unchanged.
use_fabric: Whether to enable/disable fabric interface. If false, all read/write operations go through USD.
This slows down the simulation but allows seeing the changes in the USD through the USD stage.
Defaults to None, in which case it is left unchanged.
Returns:
The parsed configuration object. This is either a dictionary or a class object.
Raises:
ValueError: If the task name is not provided, i.e. None.
"""
# check if a task name is provided
if task_name is None:
raise ValueError("Please provide a valid task name. Hint: Use --task <task_name>.")
# create a dictionary to update from
args_cfg = {"sim": {"physx": dict()}, "scene": dict()}
# resolve pipeline to use (based on input)
if use_gpu is not None:
if not use_gpu:
args_cfg["sim"]["use_gpu_pipeline"] = False
args_cfg["sim"]["physx"]["use_gpu"] = False
args_cfg["sim"]["device"] = "cpu"
else:
args_cfg["sim"]["use_gpu_pipeline"] = True
args_cfg["sim"]["physx"]["use_gpu"] = True
args_cfg["sim"]["device"] = "cuda:0"
# disable fabric to read/write through USD
if use_fabric is not None:
args_cfg["sim"]["use_fabric"] = use_fabric
# number of environments
if num_envs is not None:
args_cfg["scene"]["num_envs"] = num_envs
# load the default configuration
cfg = load_cfg_from_registry(task_name, "env_cfg_entry_point")
# update the main configuration
if isinstance(cfg, dict):
cfg = update_dict(cfg, args_cfg)
else:
update_class_from_dict(cfg, args_cfg)
return cfg
def get_checkpoint_path(
log_path: str, run_dir: str = ".*", checkpoint: str = ".*", other_dirs: list[str] = None, sort_alpha: bool = True
) -> str:
"""Get path to the model checkpoint in input directory.
The checkpoint file is resolved as: ``<log_path>/<run_dir>/<*other_dirs>/<checkpoint>``, where the
:attr:`other_dirs` are intermediate folder names to concatenate. These cannot be regex expressions.
If :attr:`run_dir` and :attr:`checkpoint` are regex expressions then the most recent (highest alphabetical order)
run and checkpoint are selected. To disable this behavior, set the flag :attr:`sort_alpha` to False.
Args:
log_path: The log directory path to find models in.
run_dir: The regex expression for the name of the directory containing the run. Defaults to the most
recent directory created inside :attr:`log_path`.
other_dirs: The intermediate directories between the run directory and the checkpoint file. Defaults to
None, which implies that checkpoint file is directly under the run directory.
checkpoint: The regex expression for the model checkpoint file. Defaults to the most recent
torch-model saved in the :attr:`run_dir` directory.
sort_alpha: Whether to sort the runs by alphabetical order. Defaults to True.
If False, the folders in :attr:`run_dir` are sorted by the last modified time.
Raises:
ValueError: When no runs are found in the input directory.
ValueError: When no checkpoints are found in the input directory.
Returns:
The path to the model checkpoint.
Reference:
https://github.com/leggedrobotics/legged_gym/blob/master/legged_gym/utils/helpers.py#L103
"""
# check if runs present in directory
try:
# find all runs in the directory that math the regex expression
runs = [
os.path.join(log_path, run) for run in os.scandir(log_path) if run.is_dir() and re.match(run_dir, run.name)
]
# sort matched runs by alphabetical order (latest run should be last)
if sort_alpha:
runs.sort()
else:
runs = sorted(runs, key=os.path.getmtime)
# create last run file path
if other_dirs is not None:
run_path = os.path.join(runs[-1], *other_dirs)
else:
run_path = runs[-1]
except IndexError:
raise ValueError(f"No runs present in the directory: '{log_path}' match: '{run_dir}'.")
# list all model checkpoints in the directory
model_checkpoints = [f for f in os.listdir(run_path) if re.match(checkpoint, f)]
# check if any checkpoints are present
if len(model_checkpoints) == 0:
raise ValueError(f"No checkpoints in the directory: '{run_path}' match '{checkpoint}'.")
# sort alphabetically while ensuring that *_10 comes after *_9
model_checkpoints.sort(key=lambda m: f"{m:0>15}")
# get latest matched checkpoint file
checkpoint_file = model_checkpoints[-1]
return os.path.join(run_path, checkpoint_file)
| 8,833 | Python | 39.898148 | 119 | 0.646892 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/utils/wrappers/skrl.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Wrapper to configure an :class:`RLTaskEnv` instance to skrl environment.
The following example shows how to wrap an environment for skrl:
.. code-block:: python
from omni.isaac.orbit_tasks.utils.wrappers.skrl import SkrlVecEnvWrapper
env = SkrlVecEnvWrapper(env)
Or, equivalently, by directly calling the skrl library API as follows:
.. code-block:: python
from skrl.envs.torch.wrappers import wrap_env
env = wrap_env(env, wrapper="isaac-orbit")
"""
from __future__ import annotations
import copy
import torch
import tqdm
from skrl.agents.torch import Agent
from skrl.envs.wrappers.torch import Wrapper, wrap_env
from skrl.resources.preprocessors.torch import RunningStandardScaler # noqa: F401
from skrl.resources.schedulers.torch import KLAdaptiveLR # noqa: F401
from skrl.trainers.torch import Trainer
from skrl.trainers.torch.sequential import SEQUENTIAL_TRAINER_DEFAULT_CONFIG
from skrl.utils.model_instantiators.torch import Shape # noqa: F401
from omni.isaac.orbit.envs import RLTaskEnv
"""
Configuration Parser.
"""
def process_skrl_cfg(cfg: dict) -> dict:
"""Convert simple YAML types to skrl classes/components.
Args:
cfg: A configuration dictionary.
Returns:
A dictionary containing the converted configuration.
"""
_direct_eval = [
"learning_rate_scheduler",
"state_preprocessor",
"value_preprocessor",
"input_shape",
"output_shape",
]
def reward_shaper_function(scale):
def reward_shaper(rewards, timestep, timesteps):
return rewards * scale
return reward_shaper
def update_dict(d):
for key, value in d.items():
if isinstance(value, dict):
update_dict(value)
else:
if key in _direct_eval:
d[key] = eval(value)
elif key.endswith("_kwargs"):
d[key] = value if value is not None else {}
elif key in ["rewards_shaper_scale"]:
d["rewards_shaper"] = reward_shaper_function(value)
return d
# parse agent configuration and convert to classes
return update_dict(cfg)
"""
Vectorized environment wrapper.
"""
def SkrlVecEnvWrapper(env: RLTaskEnv):
"""Wraps around Orbit environment for skrl.
This function wraps around the Orbit environment. Since the :class:`RLTaskEnv` environment
wrapping functionality is defined within the skrl library itself, this implementation
is maintained for compatibility with the structure of the extension that contains it.
Internally it calls the :func:`wrap_env` from the skrl library API.
Args:
env: The environment to wrap around.
Raises:
ValueError: When the environment is not an instance of :class:`RLTaskEnv`.
Reference:
https://skrl.readthedocs.io/en/latest/modules/skrl.envs.wrapping.html
"""
# check that input is valid
if not isinstance(env.unwrapped, RLTaskEnv):
raise ValueError(f"The environment must be inherited from RLTaskEnv. Environment type: {type(env)}")
# wrap and return the environment
return wrap_env(env, wrapper="isaac-orbit")
"""
Custom trainer for skrl.
"""
class SkrlSequentialLogTrainer(Trainer):
"""Sequential trainer with logging of episode information.
This trainer inherits from the :class:`skrl.trainers.base_class.Trainer` class. It is used to
train agents in a sequential manner (i.e., one after the other in each interaction with the
environment). It is most suitable for on-policy RL agents such as PPO, A2C, etc.
It modifies the :class:`skrl.trainers.torch.sequential.SequentialTrainer` class with the following
differences:
* It also log episode information to the agent's logger.
* It does not close the environment at the end of the training.
Reference:
https://skrl.readthedocs.io/en/latest/modules/skrl.trainers.base_class.html
"""
def __init__(
self,
env: Wrapper,
agents: Agent | list[Agent],
agents_scope: list[int] | None = None,
cfg: dict | None = None,
):
"""Initializes the trainer.
Args:
env: Environment to train on.
agents: Agents to train.
agents_scope: Number of environments for each agent to
train on. Defaults to None.
cfg: Configuration dictionary. Defaults to None.
"""
# update the config
_cfg = copy.deepcopy(SEQUENTIAL_TRAINER_DEFAULT_CONFIG)
_cfg.update(cfg if cfg is not None else {})
# store agents scope
agents_scope = agents_scope if agents_scope is not None else []
# initialize the base class
super().__init__(env=env, agents=agents, agents_scope=agents_scope, cfg=_cfg)
# init agents
if self.env.num_agents > 1:
for agent in self.agents:
agent.init(trainer_cfg=self.cfg)
else:
self.agents.init(trainer_cfg=self.cfg)
def train(self):
"""Train the agents sequentially.
This method executes the training loop for the agents. It performs the following steps:
* Pre-interaction: Perform any pre-interaction operations.
* Compute actions: Compute the actions for the agents.
* Step the environments: Step the environments with the computed actions.
* Record the environments' transitions: Record the transitions from the environments.
* Log custom environment data: Log custom environment data.
* Post-interaction: Perform any post-interaction operations.
* Reset the environments: Reset the environments if they are terminated or truncated.
"""
# init agent
self.agents.init(trainer_cfg=self.cfg)
self.agents.set_running_mode("train")
# reset env
states, infos = self.env.reset()
# training loop
for timestep in tqdm.tqdm(range(self.timesteps), disable=self.disable_progressbar):
# pre-interaction
self.agents.pre_interaction(timestep=timestep, timesteps=self.timesteps)
# compute actions
with torch.no_grad():
actions = self.agents.act(states, timestep=timestep, timesteps=self.timesteps)[0]
# step the environments
next_states, rewards, terminated, truncated, infos = self.env.step(actions)
# note: here we do not call render scene since it is done in the env.step() method
# record the environments' transitions
with torch.no_grad():
self.agents.record_transition(
states=states,
actions=actions,
rewards=rewards,
next_states=next_states,
terminated=terminated,
truncated=truncated,
infos=infos,
timestep=timestep,
timesteps=self.timesteps,
)
# log custom environment data
if "episode" in infos:
for k, v in infos["episode"].items():
if isinstance(v, torch.Tensor) and v.numel() == 1:
self.agents.track_data(f"EpisodeInfo / {k}", v.item())
# post-interaction
self.agents.post_interaction(timestep=timestep, timesteps=self.timesteps)
# reset the environments
# note: here we do not call reset scene since it is done in the env.step() method
# update states
states.copy_(next_states)
def eval(self) -> None:
"""Evaluate the agents sequentially.
This method executes the following steps in loop:
* Compute actions: Compute the actions for the agents.
* Step the environments: Step the environments with the computed actions.
* Record the environments' transitions: Record the transitions from the environments.
* Log custom environment data: Log custom environment data.
"""
# set running mode
if self.num_agents > 1:
for agent in self.agents:
agent.set_running_mode("eval")
else:
self.agents.set_running_mode("eval")
# single agent
if self.num_agents == 1:
self.single_agent_eval()
return
# reset env
states, infos = self.env.reset()
# evaluation loop
for timestep in tqdm.tqdm(range(self.initial_timestep, self.timesteps), disable=self.disable_progressbar):
# compute actions
with torch.no_grad():
actions = torch.vstack([
agent.act(states[scope[0] : scope[1]], timestep=timestep, timesteps=self.timesteps)[0]
for agent, scope in zip(self.agents, self.agents_scope)
])
# step the environments
next_states, rewards, terminated, truncated, infos = self.env.step(actions)
with torch.no_grad():
# write data to TensorBoard
for agent, scope in zip(self.agents, self.agents_scope):
# track data
agent.record_transition(
states=states[scope[0] : scope[1]],
actions=actions[scope[0] : scope[1]],
rewards=rewards[scope[0] : scope[1]],
next_states=next_states[scope[0] : scope[1]],
terminated=terminated[scope[0] : scope[1]],
truncated=truncated[scope[0] : scope[1]],
infos=infos,
timestep=timestep,
timesteps=self.timesteps,
)
# log custom environment data
if "log" in infos:
for k, v in infos["log"].items():
if isinstance(v, torch.Tensor) and v.numel() == 1:
agent.track_data(k, v.item())
# perform post-interaction
super(type(agent), agent).post_interaction(timestep=timestep, timesteps=self.timesteps)
# reset environments
# note: here we do not call reset scene since it is done in the env.step() method
states.copy_(next_states)
| 10,584 | Python | 36.271127 | 114 | 0.607899 |
NVIDIA-Omniverse/orbit/source/extensions/omni.isaac.orbit_tasks/omni/isaac/orbit_tasks/utils/wrappers/rl_games.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Wrapper to configure an :class:`RLTaskEnv` instance to RL-Games vectorized environment.
The following example shows how to wrap an environment for RL-Games and register the environment construction
for RL-Games :class:`Runner` class:
.. code-block:: python
from rl_games.common import env_configurations, vecenv
from omni.isaac.orbit_tasks.utils.wrappers.rl_games import RlGamesGpuEnv, RlGamesVecEnvWrapper
# configuration parameters
rl_device = "cuda:0"
clip_obs = 10.0
clip_actions = 1.0
# wrap around environment for rl-games
env = RlGamesVecEnvWrapper(env, rl_device, clip_obs, clip_actions)
# register the environment to rl-games registry
# note: in agents configuration: environment name must be "rlgpu"
vecenv.register(
"IsaacRlgWrapper", lambda config_name, num_actors, **kwargs: RlGamesGpuEnv(config_name, num_actors, **kwargs)
)
env_configurations.register("rlgpu", {"vecenv_type": "IsaacRlgWrapper", "env_creator": lambda **kwargs: env})
"""
from __future__ import annotations
import gym.spaces # needed for rl-games incompatibility: https://github.com/Denys88/rl_games/issues/261
import gymnasium
import torch
from rl_games.common import env_configurations
from rl_games.common.vecenv import IVecEnv
from omni.isaac.orbit.envs import RLTaskEnv, VecEnvObs
"""
Vectorized environment wrapper.
"""
class RlGamesVecEnvWrapper(IVecEnv):
"""Wraps around Orbit environment for RL-Games.
This class wraps around the Orbit environment. Since RL-Games works directly on
GPU buffers, the wrapper handles moving of buffers from the simulation environment
to the same device as the learning agent. Additionally, it performs clipping of
observations and actions.
For algorithms like asymmetric actor-critic, RL-Games expects a dictionary for
observations. This dictionary contains "obs" and "states" which typically correspond
to the actor and critic observations respectively.
To use asymmetric actor-critic, the environment observations from :class:`RLTaskEnv`
must have the key or group name "critic". The observation group is used to set the
:attr:`num_states` (int) and :attr:`state_space` (:obj:`gym.spaces.Box`). These are
used by the learning agent in RL-Games to allocate buffers in the trajectory memory.
Since this is optional for some environments, the wrapper checks if these attributes exist.
If they don't then the wrapper defaults to zero as number of privileged observations.
.. caution::
This class must be the last wrapper in the wrapper chain. This is because the wrapper does not follow
the :class:`gym.Wrapper` interface. Any subsequent wrappers will need to be modified to work with this
wrapper.
Reference:
https://github.com/Denys88/rl_games/blob/master/rl_games/common/ivecenv.py
https://github.com/NVIDIA-Omniverse/IsaacGymEnvs
"""
def __init__(self, env: RLTaskEnv, rl_device: str, clip_obs: float, clip_actions: float):
"""Initializes the wrapper instance.
Args:
env: The environment to wrap around.
rl_device: The device on which agent computations are performed.
clip_obs: The clipping value for observations.
clip_actions: The clipping value for actions.
Raises:
ValueError: The environment is not inherited from :class:`RLTaskEnv`.
ValueError: If specified, the privileged observations (critic) are not of type :obj:`gym.spaces.Box`.
"""
# check that input is valid
if not isinstance(env.unwrapped, RLTaskEnv):
raise ValueError(f"The environment must be inherited from RLTaskEnv. Environment type: {type(env)}")
# initialize the wrapper
self.env = env
# store provided arguments
self._rl_device = rl_device
self._clip_obs = clip_obs
self._clip_actions = clip_actions
self._sim_device = env.unwrapped.device
# information for privileged observations
if self.state_space is None:
self.rlg_num_states = 0
else:
self.rlg_num_states = self.state_space.shape[0]
def __str__(self):
"""Returns the wrapper name and the :attr:`env` representation string."""
return (
f"<{type(self).__name__}{self.env}>"
f"\n\tObservations clipping: {self._clip_obs}"
f"\n\tActions clipping : {self._clip_actions}"
f"\n\tAgent device : {self._rl_device}"
f"\n\tAsymmetric-learning : {self.rlg_num_states != 0}"
)
def __repr__(self):
"""Returns the string representation of the wrapper."""
return str(self)
"""
Properties -- Gym.Wrapper
"""
@property
def render_mode(self) -> str | None:
"""Returns the :attr:`Env` :attr:`render_mode`."""
return self.env.render_mode
@property
def observation_space(self) -> gym.spaces.Box:
"""Returns the :attr:`Env` :attr:`observation_space`."""
# note: rl-games only wants single observation space
policy_obs_space = self.unwrapped.single_observation_space["policy"]
if not isinstance(policy_obs_space, gymnasium.spaces.Box):
raise NotImplementedError(
f"The RL-Games wrapper does not currently support observation space: '{type(policy_obs_space)}'."
f" If you need to support this, please modify the wrapper: {self.__class__.__name__},"
" and if you are nice, please send a merge-request."
)
# note: maybe should check if we are a sub-set of the actual space. don't do it right now since
# in RLTaskEnv we are setting action space as (-inf, inf).
return gym.spaces.Box(-self._clip_obs, self._clip_obs, policy_obs_space.shape)
@property
def action_space(self) -> gym.Space:
"""Returns the :attr:`Env` :attr:`action_space`."""
# note: rl-games only wants single action space
action_space = self.unwrapped.single_action_space
if not isinstance(action_space, gymnasium.spaces.Box):
raise NotImplementedError(
f"The RL-Games wrapper does not currently support action space: '{type(action_space)}'."
f" If you need to support this, please modify the wrapper: {self.__class__.__name__},"
" and if you are nice, please send a merge-request."
)
# return casted space in gym.spaces.Box (OpenAI Gym)
# note: maybe should check if we are a sub-set of the actual space. don't do it right now since
# in RLTaskEnv we are setting action space as (-inf, inf).
return gym.spaces.Box(-self._clip_actions, self._clip_actions, action_space.shape)
@classmethod
def class_name(cls) -> str:
"""Returns the class name of the wrapper."""
return cls.__name__
@property
def unwrapped(self) -> RLTaskEnv:
"""Returns the base environment of the wrapper.
This will be the bare :class:`gymnasium.Env` environment, underneath all layers of wrappers.
"""
return self.env.unwrapped
"""
Properties
"""
@property
def num_envs(self) -> int:
"""Returns the number of sub-environment instances."""
return self.unwrapped.num_envs
@property
def device(self) -> str:
"""Returns the base environment simulation device."""
return self.unwrapped.device
@property
def state_space(self) -> gym.spaces.Box | None:
"""Returns the :attr:`Env` :attr:`observation_space`."""
# note: rl-games only wants single observation space
critic_obs_space = self.unwrapped.single_observation_space.get("critic")
# check if we even have a critic obs
if critic_obs_space is None:
return None
elif not isinstance(critic_obs_space, gymnasium.spaces.Box):
raise NotImplementedError(
f"The RL-Games wrapper does not currently support state space: '{type(critic_obs_space)}'."
f" If you need to support this, please modify the wrapper: {self.__class__.__name__},"
" and if you are nice, please send a merge-request."
)
# return casted space in gym.spaces.Box (OpenAI Gym)
# note: maybe should check if we are a sub-set of the actual space. don't do it right now since
# in RLTaskEnv we are setting action space as (-inf, inf).
return gym.spaces.Box(-self._clip_obs, self._clip_obs, critic_obs_space.shape)
def get_number_of_agents(self) -> int:
"""Returns number of actors in the environment."""
return getattr(self, "num_agents", 1)
def get_env_info(self) -> dict:
"""Returns the Gym spaces for the environment."""
return {
"observation_space": self.observation_space,
"action_space": self.action_space,
"state_space": self.state_space,
}
"""
Operations - MDP
"""
def seed(self, seed: int = -1) -> int: # noqa: D102
return self.unwrapped.seed(seed)
def reset(self): # noqa: D102
obs_dict, _ = self.env.reset()
# process observations and states
return self._process_obs(obs_dict)
def step(self, actions): # noqa: D102
# move actions to sim-device
actions = actions.detach().clone().to(device=self._sim_device)
# clip the actions
actions = torch.clamp(actions, -self._clip_actions, self._clip_actions)
# perform environment step
obs_dict, rew, terminated, truncated, extras = self.env.step(actions)
# move time out information to the extras dict
# this is only needed for infinite horizon tasks
# note: only useful when `value_bootstrap` is True in the agent configuration
if not self.unwrapped.cfg.is_finite_horizon:
extras["time_outs"] = truncated.to(device=self._rl_device)
# process observations and states
obs_and_states = self._process_obs(obs_dict)
# move buffers to rl-device
# note: we perform clone to prevent issues when rl-device and sim-device are the same.
rew = rew.to(device=self._rl_device)
dones = (terminated | truncated).to(device=self._rl_device)
extras = {
k: v.to(device=self._rl_device, non_blocking=True) if hasattr(v, "to") else v for k, v in extras.items()
}
# remap extras from "log" to "episode"
if "log" in extras:
extras["episode"] = extras.pop("log")
return obs_and_states, rew, dones, extras
def close(self): # noqa: D102
return self.env.close()
"""
Helper functions
"""
def _process_obs(self, obs_dict: VecEnvObs) -> torch.Tensor | dict[str, torch.Tensor]:
"""Processing of the observations and states from the environment.
Note:
States typically refers to privileged observations for the critic function. It is typically used in
asymmetric actor-critic algorithms.
Args:
obs_dict: The current observations from environment.
Returns:
If environment provides states, then a dictionary containing the observations and states is returned.
Otherwise just the observations tensor is returned.
"""
# process policy obs
obs = obs_dict["policy"]
# clip the observations
obs = torch.clamp(obs, -self._clip_obs, self._clip_obs)
# move the buffer to rl-device
obs = obs.to(device=self._rl_device).clone()
# check if asymmetric actor-critic or not
if self.rlg_num_states > 0:
# acquire states from the environment if it exists
try:
states = obs_dict["critic"]
except AttributeError:
raise NotImplementedError("Environment does not define key 'critic' for privileged observations.")
# clip the states
states = torch.clamp(states, -self._clip_obs, self._clip_obs)
# move buffers to rl-device
states = states.to(self._rl_device).clone()
# convert to dictionary
return {"obs": obs, "states": states}
else:
return obs
"""
Environment Handler.
"""
class RlGamesGpuEnv(IVecEnv):
"""Thin wrapper to create instance of the environment to fit RL-Games runner."""
# TODO: Adding this for now but do we really need this?
def __init__(self, config_name: str, num_actors: int, **kwargs):
"""Initialize the environment.
Args:
config_name: The name of the environment configuration.
num_actors: The number of actors in the environment. This is not used in this wrapper.
"""
self.env: RlGamesVecEnvWrapper = env_configurations.configurations[config_name]["env_creator"](**kwargs)
def step(self, action): # noqa: D102
return self.env.step(action)
def reset(self): # noqa: D102
return self.env.reset()
def get_number_of_agents(self) -> int:
"""Get number of agents in the environment.
Returns:
The number of agents in the environment.
"""
return self.env.get_number_of_agents()
def get_env_info(self) -> dict:
"""Get the Gym spaces for the environment.
Returns:
The Gym spaces for the environment.
"""
return self.env.get_env_info()
| 13,736 | Python | 38.587896 | 117 | 0.637813 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.